Compare commits

...

4 Commits

Author SHA1 Message Date
Luca 26c6b24c78 style: convert snake_case to camelCase 2024-09-05 17:00:57 +02:00
Luca f9b8ecf600 feat: return error from internet.open 2024-09-05 17:00:36 +02:00
Luca 970c2fa1f3 feat: set timeout to one second 2024-09-05 16:59:50 +02:00
Luca 49b7fdb832 feat: flush after write 2024-09-05 16:59:16 +02:00
1 changed files with 17 additions and 5 deletions

View File

@ -1,6 +1,6 @@
local mqtt = {}
local read_varint = function (conn, first_byte)
local readVarint = function (conn, first_byte)
local b
if first_byte == nil then
b = conn:read(1)
@ -29,9 +29,9 @@ end
local MqttClient = {}
function mqtt.open (address, port)
local conn = require("internet").open(address, port)
local conn, err = require("internet").open(address, port)
if conn == nil then
return nil, "connection failed"
return nil, err
end
return MqttClient:new(conn), nil
@ -42,7 +42,9 @@ function MqttClient:new (conn)
setmetatable(c, self)
self.__index = self
conn.read_varint = read_varint
conn.readVarint = readVarint
conn:setTimeout(1)
c.conn = conn
c.is_connecting = false
c.is_connected = false
@ -58,7 +60,7 @@ function MqttClient:handle ()
local ptype, length, _ = string.unpack("B B", s)
local length, err = self.conn:read_varint(length)
local length, err = self.conn:readVarint(length)
if err ~= nil then
return err
end
@ -142,6 +144,11 @@ function MqttClient:connect (username, password)
return err
end
local _, err = self.conn:flush()
if err ~= nil then
return err
end
self.is_connecting = true
return nil
@ -163,6 +170,11 @@ function MqttClient:disconnect (reason)
return err
end
local _, err = self.conn:flush()
if err ~= nil then
return err
end
self.is_connecting = false
self.is_connected = false