Advertisement
ale_ben

MQTT-reactor

Apr 18th, 2024 (edited)
1,427
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local mqtt = require("mqtt")
  2.  
  3. local reactor = peripheral.wrap("bottom")
  4.  
  5. if reactor == nil or reactor.isFormed() == false then
  6.     print("Unable to find reactor. Restarting in 5")
  7.     os.sleep(5)
  8.     os.reboot()
  9. end
  10.  
  11. local keep_alive = 60
  12. local baseTopic = "/ftbUniversity19/ITLandfill/fission/reactor/"
  13. local refresh = 10
  14.  
  15. local connected = false
  16.  
  17. -- create mqtt client
  18. local client = mqtt.client {
  19.     -- NOTE: this broker is not working sometimes; comment username = "..." below if you still want to use it
  20.     uri = "ws://test.mosquitto.org:8080",
  21.     clean = true,
  22.     keep_alive = keep_alive
  23. }
  24.  
  25. print("created MQTT client", client)
  26.  
  27. client:on {
  28.     connect = function(connack)
  29.         if connack.rc ~= 0 then
  30.             print("connection to broker failed:", connack:reason_string(), connack)
  31.             return
  32.         end
  33.         print("connected:", connack) -- successful connection
  34.         connected = true      
  35.         -- subscribe to test topic and publish message after it
  36.         assert(client:subscribe { topic = baseTopic .. "command/#", qos = 1, callback = function(suback)
  37.             print("subscribed:", suback)
  38.  
  39.         end })
  40.     end,
  41.  
  42.     message = function(msg)
  43.         assert(client:acknowledge(msg))
  44.  
  45.         print("received:", msg)
  46.  
  47.         if msg.payload == "disconnect" then
  48.             print("disconnecting...")
  49.             assert(client:disconnect())
  50.         end
  51.        
  52.         local command = string.sub(msg.topic, string.len(baseTopic .. "command/"))
  53.         print("Command topic: " .. command)
  54.         print("Command: " .. msg.payload)
  55.     end,
  56.  
  57.     error = function(err)
  58.         print("MQTT client error:", err)
  59.     end,
  60.  
  61.     close = function()
  62.         print("MQTT conn closed")
  63.     end
  64. }
  65.  
  66. function sendMessage(topic, message, retain)
  67.     if connected then    
  68.         assert(client:publish {
  69.             topic = baseTopic..topic,
  70.             payload = message,
  71.             retain = retain
  72.         })
  73.     else
  74.         print("Not connected")
  75.     end    
  76. end
  77.  
  78. function sendUpdate()
  79.     sendMessage("sensor/status", tostring(reactor.getStatus()), false)
  80.     sendMessage("sensor/temperature", tostring(reactor.getTemperature()), false)              
  81.     sendMessage("sensor/damage", tostring(reactor.getDamagePercent()), false)
  82.     sendMessage("sensor/coolant", tostring(reactor.getCoolantFilledPercentage()), false)
  83.     sendMessage("sensor/heatedCoolant", tostring(reactor.getHeatedCoolantFilledPercentage()), false)
  84.     sendMessage("sensor/fuel", tostring(reactor.getFuelFilledPercentage()), false)
  85.     sendMessage("sensor/waste", tostring(reactor.getWasteFilledPercentage()), false)
  86.    
  87.     --local burnRate = "{\"max\":"..tostring(reactor.getMaxBurnRate()) ..", \"set\":" .. tostring(reactor.getBurnRate()) .. ",\"val\":" .. tostring(reactor.getActualBurnRate()) .. "}"
  88.     sendMessage("sensor/burnRate/set", tostring(reactor.getBurnRate()), false)
  89.     sendMessage("sensor/burnRate/actual", tostring(reactor.getActualBurnRate()), false)
  90.     sendMessage("sensor/burnRate/max", tostring(reactor.getMaxBurnRate()), false)
  91.     sendMessage("sensor/burnRate/percent", tostring(reactor.getActualBurnRate()/reactor.getMaxBurnRate()), false)
  92.     --sendMessage("sensor/burnRate", burnRate, false)
  93. end
  94.  
  95. parallel.waitForAny(
  96.     function()
  97.         -- run io loop for client until connection close
  98.         -- please note that in sync mode background PINGREQ's are not available, and automatic reconnects too
  99.         print("running client in synchronous input/output loop")
  100.         mqtt.run_sync(client)
  101.         print("done, synchronous input/output loop is stopped")
  102.     end,
  103.     function()
  104.         while true do
  105.             os.sleep(keep_alive)
  106.             client:send_pingreq()
  107.         end
  108.     end,
  109.     function()
  110.         while true do
  111.             os.sleep(refresh)
  112.             if (pcall(sendUpdate) == false) then
  113.                 print("Error updating. Restarting in 5")
  114.                 os.sleep(5)
  115.                 os.reboot()
  116.             end
  117.         end
  118.     end
  119. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement