flukso / lua-mosquitto

Lua bindings to the libmosquitto MQTT client library.
https://github.com/flukso/lua-mosquitto
Other
63 stars 42 forks source link

loop() throws "A network protocol error occurred when communicating with the broker" on disconnect #38

Open hollymcr opened 7 months ago

hollymcr commented 7 months ago

Until I have a valid connection, and then whilst I have a valid connection, loop(0) works fine. However if the connection drops, loop() calls the ON_DISCONNECT handler but then throws an exception.

I can catch the error with pcall but this doesn't seem like intended behaviour and I don't know if there is any cleaning up that needs doing after the exception prior to a reconnect?

Sample code:

MQTT_HOST  = '<HOST>'
MQTT_PORT  = <PORT>

MQTT_USER  = <USER>
MQTT_PASS  = <PASS>

MQTT_PEM = "/tmp/broker-cert.pem"

local mq = mqtt.new()
local mq_status = 'disconnected'

-- Setup MQTT connection
if MQTT_PEM then 
        mq:tls_set(MQTT_PEM) 
        mq:tls_insecure_set(true)
end
if MQTT_USER then mq:login_set(MQTT_USER,MQTT_PASS) end

mq.ON_CONNECT = function()
    mq_status = 'connected'
    print('Connected')
end

mq.ON_DISCONNECT = function(was_clean, rc, str)
    mq_status = 'disconnected'
    print("Disconnection detected")
end

mq.ON_MESSAGE = function(mid, k, v)
        print(k + '=' + v)
end

-- MAIN LOOP
while true do
        socket.sleep(0.1)
        -- Attempt MQTT connection if nec
        if mq_status == 'disconnected' then
                mq_status = 'connecting'
                ok, e, err = mq:connect(MQTT_HOST, MQTT_PORT)
                if ok then
                        print('Connecting')
                else
                        print('Unable to connect')
                        mq_status = 'disconnected'
                end
        end

    -- Handle MQTT comms
       ok, errno, errstr = mq:loop(0)
end

Platform: Teltonika TRB unit running OpenWRT, lib-mosquitto 0.4.1-1 package