Here is a goodway to wrap a modem (it can be easily adapted to make use for other peripherals too. You can also add an isWireless() check if you want)
Code:
function wrapOnePeripheral(pType) -- pType is the name of the peripheral.*
local wrap = nil
for i, v in pairs(peripheral.getNames()) do -- Searches through every peripheral
if peripheral.getType(v) == pType then -- Checks if that peripheral is a pType
wrap = peripheral.wrap(v) -- Wraps the peripheral
end
end
return wrap -- Returns the peripheral handle that you can store
end
--[[* Finding the right name for a peripheral can be a bit tricky sometimes but in vanilla computercraft the names are straightforward. Wired and wireless modems are both called "modem"]]
local modem = wrapOnePeripheral("modem")
Using that function means you don't need to worry about which side a peripheral is on (it also works for peripherals connected via wired modem)
Sending a message with the modem api is easy. You need three pieces of information, the sending channel, the reply channel and the message
Code:
local sendChannel = 100
local replyChannel = 101
local message = "Hello"
modem.transmit(sendChannel, replyChannel, message)
Any computer listening to sendChannel will be able to receive that message as a "modem_message" event
You can open and close modem channels to enable or disable listening on that channel. Capture a message by waiting for the "modem_message" event
Code:
modem.open(sendChannel)
local event = {os.pullEvent("modem_message")} -- All the variables returned by the modem message will be captured inside a new table called event
--[[ event table structure
event = {
[1] = string eventDescription, - "modem_message"
[2] = string modemSide,
[3] = number sendChannel,
[4] = number replyChannel,
[5] = string message,
[6] = number distance,
}
]]
--Event gets fired as message is received!
local messageReceived = event[5]
Arrange for the computer that controls the junction to receive a message like this. Then you can run a condition based on the message to make the computer do what you want for example:
Code:
if messageReceived == "hello" then
modem.transmit(replyChannel, sendChannel, "Hello to you too")
redstone.setOutput("right", true)
else
print("The message I got was not what I expected")
redstone.setOutput("right", false)
end
Put the event code inside a while loop to make it work forever.
You can send serialised tables to send more complicated information. This can allow you to set up a complicated filter so if you are controlling multiple junctions with the same main computer you have a way of making sure the right message is only interpreted by the right computers.