From c7344711c2fab6090109f127965c5a4553f6e0cf Mon Sep 17 00:00:00 2001 From: Sebastiaan de Schaetzen Date: Sat, 20 Jul 2024 14:33:40 +0200 Subject: [PATCH] Working on better mqtt support --- controller-host/mqttthread.lua | 1 - controller-host/mymqtt.lua | 39 ++++++++++++++++++++++------------ get-ip.lua | 6 ++++-- 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/controller-host/mqttthread.lua b/controller-host/mqttthread.lua index 33b8162..bb4c1fc 100644 --- a/controller-host/mqttthread.lua +++ b/controller-host/mqttthread.lua @@ -38,7 +38,6 @@ local function onCommand(command) assert(client:subscribe { topic = topic }) - }) end end diff --git a/controller-host/mymqtt.lua b/controller-host/mymqtt.lua index b2a5ff8..627aa59 100644 --- a/controller-host/mymqtt.lua +++ b/controller-host/mymqtt.lua @@ -257,7 +257,7 @@ function clientMt:receiveBytes(count) result, err, partial = client:receive(1 - #partial, partial) if err == "timeout" then coroutine.yield() - else if result then + elseif result then return result else return nil, err @@ -266,7 +266,7 @@ function clientMt:receiveBytes(count) end function clientMt:receiveByte() - return string.byte(self:receiveBytes(1))) + return string.byte(self:receiveBytes(1)) end function clientMt:receiveVarInt() @@ -293,6 +293,7 @@ function clientMt:receivePacket() if err then return self:handleError(err) end local packetType = (firstByte >> 4) & 0xF + print("Got packet of type " .. packetType) if packetType == 2 then -- CONNACK assert(remainingLength == 2, "Invalid CONNACK length") @@ -313,16 +314,28 @@ function clientMt:receivePacket() end function clientMt:threadReceive() - while true do - if self.connection then - local err = self:receiveAndHandlePacket() - if err then - self:handleError(err) - end - else - coroutine.yield() - end - end + -- local status, err = pcall(function() + while true do + if self.connection then + local err = self:receiveAndHandlePacket() + if err then + self:handleError(err) + end + else + coroutine.yield() + end + end + -- end) + -- if err then + -- print(err) + -- error(err) + -- end +end + +function clientMt:runForever() + while true do + coroutine.resume(self.thread) + end end function clientMt:on(eventHandlers) @@ -339,7 +352,7 @@ function mqtt.client(args) buffer = "" } setmetatable(client, {__index = clientMt}) - client.create(function() client:threadReceive() end) + client.thread = coroutine.create(function() client:threadReceive() end) return client end diff --git a/get-ip.lua b/get-ip.lua index 12880a3..dbedfe4 100644 --- a/get-ip.lua +++ b/get-ip.lua @@ -1,5 +1,5 @@ package.path = package.path .. ';./controller-host/?/init.lua;./controller-host/?.lua' -local mqtt = require("mqtt") +local mqtt = require("mymqtt") local client local host = ... @@ -39,4 +39,6 @@ client:on { message = onMessage, } -mqtt.run_ioloop(client) +client:runForever() + +--mqtt.run_ioloop(client)