Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local mqtt = require("mqtt")
- local induction = peripheral.wrap("bottom")
- if induction == nil or induction.isFormed() == false then
- print("Unable to find induction. Restarting in 5")
- os.sleep(5)
- os.reboot()
- end
- local keep_alive = 60
- local baseTopic = "/ftbUniversity19/ITLandfill/fission/induction/"
- local refresh = 10
- local connected = false
- -- create mqtt client
- local client = mqtt.client {
- -- NOTE: this broker is not working sometimes; comment username = "..." below if you still want to use it
- uri = "ws://test.mosquitto.org:8080",
- clean = true,
- keep_alive = keep_alive
- }
- print("created MQTT client", client)
- client:on {
- connect = function(connack)
- if connack.rc ~= 0 then
- print("connection to broker failed:", connack:reason_string(), connack)
- return
- end
- print("connected:", connack) -- successful connection
- connected = true
- -- subscribe to test topic and publish message after it
- assert(client:subscribe { topic = "/hfdghwl/#", qos = 1, callback = function(suback)
- print("subscribed:", suback)
- end })
- end,
- message = function(msg)
- assert(client:acknowledge(msg))
- print("received:", msg)
- if msg.payload == "disconnect" then
- print("disconnecting...")
- assert(client:disconnect())
- end
- end,
- error = function(err)
- print("MQTT client error:", err)
- end,
- close = function()
- print("MQTT conn closed")
- end
- }
- function sendMessage(topic, message, retain)
- if connected then
- assert(client:publish {
- topic = baseTopic..topic,
- payload = message,
- retain = retain
- })
- else
- print("Not connected")
- end
- end
- function sendUpdate()
- sendMessage("sensor/energy", tostring(induction.getEnergyFilledPercentage()), false)
- sendMessage("sensor/cells/induction", tostring(induction.getInstalledCells()), false)
- sendMessage("sensor/cells/provider", tostring(induction.getInstalledProviders()), false)
- sendMessage("sensor/lastInput", tostring(induction.getLastInput()), false)
- sendMessage("sensor/lastOutput", tostring(induction.getLastOutput()), false)
- end
- parallel.waitForAny(
- function()
- -- run io loop for client until connection close
- -- please note that in sync mode background PINGREQ's are not available, and automatic reconnects too
- print("running client in synchronous input/output loop")
- mqtt.run_sync(client)
- print("done, synchronous input/output loop is stopped")
- end,
- function()
- while true do
- os.sleep(keep_alive)
- client:send_pingreq()
- end
- end,
- function()
- while true do
- os.sleep(refresh)
- if (pcall(sendUpdate) == false) then
- print("Error updating. Restarting in 5")
- os.sleep(5)
- os.reboot()
- end
- end
- end
- )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement