Compare commits
No commits in common. "c0b86c765981ce40faa4cee2e83a30b0732394de" and "26c6b24c78cbdaa4c50b42cb689e70b2999eb664" have entirely different histories.
c0b86c7659
...
26c6b24c78
41
mqtt.lua
41
mqtt.lua
|
@ -1,36 +1,26 @@
|
|||
local mqtt = {}
|
||||
|
||||
local safeRead = function (conn, n)
|
||||
local success, result, err = pcall(conn.read, conn, n)
|
||||
if success then
|
||||
return result, err
|
||||
end
|
||||
|
||||
return nil, result
|
||||
end
|
||||
|
||||
local readVarint = function (conn, first_byte)
|
||||
local b, err
|
||||
local b
|
||||
if first_byte == nil then
|
||||
b, err = safeRead(conn, 1)
|
||||
b = conn:read(1)
|
||||
else
|
||||
b = first_byte
|
||||
end
|
||||
|
||||
local n, s = 0, 0
|
||||
while err == nil and b & 0x80 == 0x80 do
|
||||
while b ~= nil and b & 0x80 == 0x80 do
|
||||
if s > 21 then
|
||||
return 0, "number too large"
|
||||
end
|
||||
|
||||
n = n + ((b & 0x7F) << s)
|
||||
s = s + 7
|
||||
|
||||
b, err = safeRead(conn, 1)
|
||||
b = conn:read(1)
|
||||
end
|
||||
|
||||
if err ~= nil then
|
||||
return n, err
|
||||
if b == nil then
|
||||
return n, "eof"
|
||||
end
|
||||
|
||||
return n + (b << s), nil
|
||||
|
@ -53,7 +43,6 @@ function MqttClient:new (conn)
|
|||
self.__index = self
|
||||
|
||||
conn.readVarint = readVarint
|
||||
conn.safeRead = safeRead
|
||||
conn:setTimeout(1)
|
||||
|
||||
c.conn = conn
|
||||
|
@ -64,12 +53,12 @@ function MqttClient:new (conn)
|
|||
end
|
||||
|
||||
function MqttClient:handle ()
|
||||
local data, err = self.conn:safeRead(2)
|
||||
if err ~= nil then
|
||||
return err
|
||||
local data = self.conn:read(2)
|
||||
if data == nil then
|
||||
return "eof"
|
||||
end
|
||||
|
||||
local ptype, length, _ = string.unpack("B B", data)
|
||||
local ptype, length, _ = string.unpack("B B", s)
|
||||
|
||||
local length, err = self.conn:readVarint(length)
|
||||
if err ~= nil then
|
||||
|
@ -77,9 +66,9 @@ function MqttClient:handle ()
|
|||
end
|
||||
|
||||
if length > 0 then
|
||||
data, err = self.conn:safeRead(length)
|
||||
if err ~= nil then
|
||||
return err
|
||||
data = self.conn:read(length)
|
||||
if data == nil then
|
||||
return "eof"
|
||||
end
|
||||
else
|
||||
data = ""
|
||||
|
@ -127,8 +116,8 @@ function MqttClient:connect (username, password)
|
|||
return nil
|
||||
end
|
||||
|
||||
local length = 13
|
||||
local flags = 2
|
||||
local length = 15
|
||||
local flags = 1
|
||||
if username ~= nil then
|
||||
length = length + 2 + #username
|
||||
flags = flags | 0x80
|
||||
|
|
Loading…
Reference in New Issue