cc-rail-router/station.lua

69 lines
2.0 KiB
Lua
Raw Normal View History

2023-09-07 19:38:39 +00:00
--[[
Stations are kiosks where users can configure their portable computer for a
particular route to another station.
2023-09-08 14:49:17 +00:00
You should add a "station_config.tbl" file containing:
{
2023-09-12 18:11:57 +00:00
name = "stationname",
displayName = "Station Name",
2023-09-08 14:49:17 +00:00
range = 8,
routes = {
{name = "First", path = {"A", "B", "C"}},
{name = "Second", path = {"D", "A", "C"}}
}
}
2023-09-07 19:38:39 +00:00
]]--
local modem = peripheral.wrap("top") or error("Missing top modem")
2023-09-08 14:49:17 +00:00
local BROADCAST_CHANNEL = 45451
local RECEIVE_CHANNEL = 45452
modem.open(RECEIVE_CHANNEL)
2023-09-07 19:38:39 +00:00
2023-09-08 14:49:17 +00:00
local function readConfig()
local f = io.open("station_config.tbl", "r")
if not f then error("Missing station_config.tbl") end
local cfg = textutils.unserialize(f:read("*a"))
f:close()
return cfg
end
local function broadcastName(config)
2023-09-07 19:38:39 +00:00
while true do
2023-09-08 14:49:17 +00:00
modem.transmit(BROADCAST_CHANNEL, BROADCAST_CHANNEL, config.name)
2023-09-07 19:38:39 +00:00
os.sleep(1)
end
end
2023-09-08 14:49:17 +00:00
local function handleRequests(config)
while true do
local event, side, channel, replyChannel, msg, dist = os.pullEvent("modem_message")
if channel == RECEIVE_CHANNEL and dist <= config.range then
if msg == "GET_ROUTES" then
modem.transmit(replyChannel, RECEIVE_CHANNEL, config.routes)
print(textutils.formatTime(os.time()).." Sent routes to "..replyChannel)
end
end
end
end
local config = readConfig()
term.clear()
term.setCursorPos(1, 1)
print("Running station transponder for \""..config.name.."\".")
2023-09-12 18:11:57 +00:00
print(" Display Name: "..config.displayName)
2023-09-08 14:49:17 +00:00
print(" Range: "..config.range.." blocks")
print(" Routes:")
for i, route in pairs(config.routes) do
local pathStr = ""
for j, segment in pairs(route.path) do
pathStr = pathStr .. segment
if j < #route.path then pathStr = pathStr .. "," end
end
print(" "..i..". "..route.name..": "..pathStr)
end
2023-09-07 19:38:39 +00:00
parallel.waitForAll(
2023-09-08 14:49:17 +00:00
function() broadcastName(config) end,
function() handleRequests(config) end
2023-09-07 19:38:39 +00:00
)