local MODEM_SIDE = "bottom"
local PROTOCOL = "rtm_switch"
local CONFIG_FILE = "slave.cfg"
local config = {
outputs = {
straight = {},
cross = {},
},
defaultState = "straight",
}
local state = "straight"
local function saveConfig()
local h = fs.open(CONFIG_FILE, "w")
h.write(textutils.serialize(config))
h.close()
end
local function loadConfig()
if not fs.exists(CONFIG_FILE) then
saveConfig()
return
end
local h = fs.open(CONFIG_FILE, "r")
local raw = h.readAll()
h.close()
local t = textutils.unserialize(raw)
if type(t) == "table" then
config = t
end
end
local function clearAll()
for _, side in ipairs({"top","bottom","left","right","front","back"}) do
if side ~= MODEM_SIDE then
redstone.setOutput(side, false)
end
end
end
local function applyOutputs(list)
clearAll()
for _, side in ipairs(list or {}) do
if side ~= MODEM_SIDE then
redstone.setOutput(side, true)
end
end
end
local function applyState()
if state == "straight" then
applyOutputs(config.outputs.straight)
else
applyOutputs(config.outputs.cross)
end
end
local function reply(targetId, extra)
local payload = {
ok = true,
id = os.getComputerID(),
state = state,
}
if type(extra) == "table" then
for k, v in pairs(extra) do payload[k] = v end
end
rednet.send(targetId, payload, PROTOCOL)
end
loadConfig()
state = config.defaultState or "straight"
applyState()
rednet.open(MODEM_SIDE)
while true do
local senderId, msg, protocol = rednet.receive(PROTOCOL)
if type(msg) == "table" then
if msg.cmd == "set" and (msg.state == "straight" or msg.state == "cross") then
state = msg.state
applyState()
reply(senderId)
elseif msg.cmd == "ping" then
reply(senderId, {alive = true})
elseif msg.cmd == "get_config" then
reply(senderId, {config = config})
end
end
end