Maschini

startup

Jan 8th, 2023 (edited)
994
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.01 KB | None | 0 0
  1. local addr = ""
  2.  
  3. function log(prefix, message)
  4.     local div = " : "
  5.     local time = os.date("%Z%X")
  6.     write(time .. div .. prefix .. div .. message .. "\n")
  7. end
  8.  
  9. function printLine()
  10.     local w, h = term.getSize()
  11.     for i = 1, w-1 do
  12.         write("-")
  13.     end
  14.     print("-")
  15. end
  16.  
  17. function setup()
  18.     local config = {}
  19.     if fs.exists(".config") then
  20.         config = setupFromFile()
  21.     else
  22.         config = setupFromUser()
  23.         local file = fs.open(".config", "w")
  24.         file.write(textutils.serialiseJSON(config))
  25.         file.close()
  26.     end
  27.  
  28.     addr = "ws://" .. config["host"] .. "/api/ws"
  29.  
  30.     print("INITIALIZATION COMPLETE:")
  31.     print(textutils.serialise(config))
  32.     printLine()
  33. end
  34.  
  35. function setupFromFile()
  36.     local file = fs.open(".config", "r")
  37.     local config = textutils.unserialiseJSON(file.readAll())
  38.     file.close()
  39.     return config
  40. end
  41.  
  42. function setupFromUser()
  43.     local config = {}
  44.  
  45.     print("HOST? ")
  46.     write("> ")
  47.     config["host"] = read()
  48.  
  49.     return config
  50. end
  51.  
  52. function connect()
  53.     ws, err = http.websocket(addr)
  54.     if not ws then
  55.         log("!!", err)
  56.     end
  57.  
  58.     printLine()
  59.     print("INCOMING MESSAGES: ->")
  60.     print("OUTGOING MESSAGES: <-")
  61.     printLine()
  62.  
  63.     while true do
  64.         local message, isBinary = ws.receive()
  65.         if not isBinary then
  66.             log("->", message:gsub("\n", ""))
  67.             t = textutils.unserialiseJSON(message)
  68.  
  69.             local f, err = loadstring(t.func)
  70.             if not err then
  71.                 local result = f()
  72.                 local resultJson = textutils.serialiseJSON(result)
  73.  
  74.                 log("<-", resultJson)
  75.                 ws.send(resultJson)
  76.             else
  77.                 print(err)
  78.                 ws.send(textutils.serialiseJSON({
  79.                     err = err
  80.                 }))
  81.             end
  82.         end
  83.     end
  84. end
  85.  
  86. setup()
  87.  
  88. local backoff = 1
  89. while not pcall(connect) do
  90.     log("! ", "trying to reconnect")
  91.     sleep(backoff)
  92. end
Advertisement
Add Comment
Please, Sign In to add comment