Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hollymcr opened this issue Mar 25, 2024 · 0 comments

Comments

@hollymcr
Copy link

hollymcr commented Mar 25, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant