Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local rs = peripheral.find("rsBridge")
- if not rs then error("No RS Bridge attached!") end
- local function chunkString(value, chunkSize)
- if not chunkSize then chunkSize = 10000 end
- local length = value:len()
- local total = math.ceil(length / chunkSize)
- local chunks = {}
- local i = 1
- for i=1,total do
- local pos = 1 + ((i - 1) * chunkSize)
- chunks[i] = value:sub(pos, pos + chunkSize - 1)
- end
- return total, chunks
- end
- local function main()
- print("Connecting to the socket server...")
- local socket, reason = http.websocket("ws://ws.cnml.de:8080")
- if not socket then error("Socket server could not be reached: "..reason) end
- print("Connection successful!")
- socket.send("{\"role\":\"rs\"}")
- local function handleRequest(parsed)
- if parsed.method == "energyusage" then
- return true, tostring(rs.getEnergyUsage())
- elseif parsed.method == "energystorage" then
- return true, tostring(rs.getEnergyStorage())
- elseif parsed.method == "listitems" then
- return true, textutils.serializeJSON(rs.listItems())
- elseif parsed.method == "listfluids" then
- return true, textutils.serializeJSON(rs.listFluids())
- end
- return false, ("Invalid method: "..parsed.method.."!")
- end
- local function sendResponse(id, result)
- local total, chunks = chunkString(result)
- for i, chunk in pairs(chunks) do
- socket.send(textutils.serializeJSON({ id = id, result = chunk, chunk = i, total = total }))
- end
- end
- local function handleMessage(message)
- local parsed, reason = textutils.unserializeJSON(message)
- if not parsed then print("Deserialization failed: "..reason..", in messsage "..message) return end
- if parsed.type == "request" then
- local success, result = handleRequest(parsed)
- if success then
- sendResponse(parsed.id, result)
- else
- printError("Error when answering", parsed.method, "method:", result)
- end
- return
- end
- printError("No handler for messages of type", parsed.type)
- end
- while true do
- local message, binary = socket.receive(1)
- if not not message and not binary then
- handleMessage(message)
- end
- end
- end
- while true do
- local status, err = pcall(main)
- if not status then
- printError("Uncaught error:", err)
- print("Sleeping for 5 seconds and retrying!")
- sleep(5)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement