Working on better mqtt support

This commit is contained in:
Sebastiaan de Schaetzen 2024-07-20 14:33:40 +02:00
parent cec28500b3
commit c7344711c2
3 changed files with 30 additions and 16 deletions

View File

@ -38,7 +38,6 @@ local function onCommand(command)
assert(client:subscribe {
topic = topic
})
})
end
end

View File

@ -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,6 +314,7 @@ function clientMt:receivePacket()
end
function clientMt:threadReceive()
-- local status, err = pcall(function()
while true do
if self.connection then
local err = self:receiveAndHandlePacket()
@ -323,6 +325,17 @@ function clientMt:threadReceive()
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

View File

@ -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)