HandieAndy

ir-oc-api_detector.lua

May 1st, 2020
345
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.09 KB | None | 0 0
  1. local component = require("component")
  2. local event = require("event")
  3. local thread = require("thread")
  4. local net = require("internet")
  5. local json = require("json")
  6.  
  7. -- The unique token for your world. If you don't have one yet, you can create one by posting to /worlds
  8. local WORLD_TOKEN = "imokvBK0D"
  9. local BASE_URL = "http://localhost:8567/worlds/%s/rolling_stocks/%s/status"
  10.  
  11. -- Sends a POST request to the given URL, with a JSON body.
  12. local function sendJsonPost(url, data)
  13.   local headers = {
  14.     ["Content-Type"]="application/json"
  15.   }
  16.   local handle = net.request(url, json.encode(data), headers, "POST")
  17.   if handle == nil then
  18.     print("Could not perform request to url: " .. url)
  19.     return
  20.   end
  21.   local result = ""
  22.   for chunk in handle do result = result .. chunk end
  23.   local mt = getmetatable(handle)
  24.   local code, message, headers = mt.__index.response()
  25.   return {
  26.     code=code,
  27.     message=message,
  28.     content=result
  29.   }
  30. end
  31.  
  32. -- Retrieves data from a detector, formats it, and sends it to the API.
  33. local function handleDetect(detector, stock_uuid)
  34.   print("Detected Stock with UUID: " .. stock_uuid)
  35.   local info = detector.info()
  36.   local x,y,z = detector.getPos()
  37.   local data = {
  38.     position={x=x, y=y, z=z},
  39.     jsonRollingStockId=info.id,
  40.     name=info.name,
  41.     cargoSize=info.cargo_size,
  42.     speed=info.speed,
  43.     weight=info.weight,
  44.     passengers=info.passengers,
  45.     direction=info.direction,
  46.     tag=info.tag
  47.   }
  48.  
  49.   local url = string.format(BASE_URL, WORLD_TOKEN, stock_uuid)
  50.   print("Sending status to " .. url)
  51.   local result = sendJsonPost(url, data)
  52.   print("Response code: " .. result.code .. ", Message: " .. result.message)
  53.   print("Response body: \n" .. result.content)
  54. end
  55.  
  56. -- Constantly wait for a detector to fire an event, then process it in another thread.
  57. while true do
  58.   print("Waiting for detection event.")
  59.   event_name, address, augment_type, stock_uuid = event.pull("ir_train_overhead")
  60.   if (augment_type == "DETECTOR" and stock_uuid ~= nil) then
  61.     thread.create(handleDetect, component.proxy(address), stock_uuid)
  62.   end
  63. end
Add Comment
Please, Sign In to add comment