Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local config = dofile "config.lua"
- local function spudnet()
- if not http or not http.websocket then return "Websockets do not actually exist on this platform" end
- local ws
- local function send_packet(msg)
- ws.send(textutils.serialiseJSON(msg))
- end
- local function send(data)
- send_packet { type = "send", channel = "comm:arr", data = data }
- end
- local function connect()
- if ws then ws.close() end
- ws, err = http.websocket "wss://spudnet.osmarks.net/v4?enc=json"
- if not ws then print("websocket failure %s", err) return false end
- ws.url = "wss://spudnet.osmarks.net/v4?enc=json"
- send_packet { type = "identify", implementation = "ARR control unit", key = settings.get "spudnet_key" }
- send_packet { type = "set_channels", channels = { "comm:arr" } }
- print("websocket connected")
- return true
- end
- local function try_connect_loop()
- while not connect() do
- sleep(0.5)
- end
- end
- try_connect_loop()
- local function recv()
- while true do
- local e, u, x = os.pullEvent "websocket_message"
- if u == ws.url then return textutils.unserialiseJSON(x) end
- end
- end
- local ping_timeout_timer = nil
- local function ping_timer()
- while true do
- local _, t = os.pullEvent "timer"
- if t == ping_timeout_timer and ping_timeout_timer then
- -- 15 seconds since last ping, we probably got disconnected
- print "SPUDNET timed out, attempting reconnect"
- try_connect_loop()
- end
- end
- end
- local function main()
- while true do
- local packet = recv()
- if packet.type == "ping" then
- send_packet { type = "pong", seq = packet.seq }
- if ping_timeout_timer then os.cancelTimer(ping_timeout_timer) end
- ping_timeout_timer = os.startTimer(15)
- elseif packet.type == "error" then
- print("SPUDNET error", packet["for"], packet.error, packet.detail, textutils.serialise(packet))
- elseif packet.type == "message" then
- os.queueEvent("spudnet_message", packet.data)
- end
- end
- end
- return send, function() parallel.waitForAll(ping_timer, main) end
- end
- local spudnet_send, spudnet_handler = spudnet()
- local switches = {}
- local sweep_timer = os.startTimer(1)
- local function main()
- while true do
- local ev = {os.pullEvent()}
- if ev[1] == "spudnet_message" then
- local data = ev[2]
- if data.type == "sw_ping" then
- data.timer = timer
- data.last_ping = os.epoch "utc"
- switches[data.id] = data
- print(data.id)
- spudnet_send { type = "sw_cmd", cmd = "set", lamp = (os.clock() % 16) * 2048 }
- end
- elseif ev[1] == "timer" then
- if ev[2] == sweep_timer then
- local now = os.epoch "utc"
- for id, switch in pairs(switches) do
- if now - switch.last_ping >= 2000 then
- print(switch, "antimemeticized")
- switches[id] = nil
- end
- end
- sweep_timer = os.startTimer(1)
- end
- end
- end
- end
- parallel.waitForAll(spudnet_handler, main)
Add Comment
Please, Sign In to add comment