problem with mqtt

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
bellad
Posts: 96
Joined: Tue May 14, 2019 1:47 pm

problem with mqtt

Post by bellad » Thu May 13, 2021 5:07 pm

hello
with sonoff and micropython , i have a error
it works for a while and after

Code: Select all

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "chauff_elec.py", line 71, in main
  File "umqttsimple.py", line 176, in wait_msg
OSError: -1
i understand !!
can you help ?
thank you

my code

Code: Select all







import machine
from umqttsimple import MQTTClient
import ujson


MQTTConfig = {
    "client_id": "sdb_electrique",
    "server": "192.168.1.51",
    "port": 1883,
    "keepalive": 60
}

LED = machine.Pin(13, machine.Pin.OUT)
REL = machine.Pin(12, machine.Pin.OUT)
LED.value(1)
REL.value(1)

mqtt = MQTTClient(MQTTConfig['client_id'], MQTTConfig['server'], port=int(MQTTConfig['port']), keepalive=int(MQTTConfig['keepalive']))



def sdb_statut_actions(msg):
    #print(msg)
    #global ancien_etat
    try:
        sdb = ujson.loads(msg)
        etat_relais = sdb['relais']['RELAIS']
        #print('relais =',etat_relais)
        
        if etat_relais == 1:
          REL.value(0)
          LED.value(0)
        else:
          REL.value(1)
          LED.value(1)  
           # pass

        #REL.value(etat_relais)
        #ancien_etat = etat_relais
        
        #mqtt.publish(b"sdb_statut", ujson.dumps({
        #    "nom": MQTTConfig['client_id'],
        #    "relais": REL.value()
        #}).decode())
    except (ValueError, KeyError):
        pass


def on_message(topic, msg):
    
    
    if topic == b'sdb_statut':
        #print(topic)
        sdb_statut_actions(msg)
        


def main():
    mqtt.set_callback(on_message)
    mqtt.connect()
    mqtt.subscribe("sdb_statut")

    try:
        while True:
            mqtt.wait_msg()
    finally:
        mqtt.disconnect()


if __name__ == "__main__":
    main()















User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: problem with mqtt

Post by pythoncoder » Fri May 14, 2021 10:33 am

I'm puzzled by the line number as this line should not be capable of an OSError. Have you got the current version?

As a general point the official MQTT code is not robust and doesn't cope well with brief WiFi outages. Further, in my experience some (but not all) Sonoff kit has poor WiFi connectivity. You might like to look at this repo which provides a more resilient MQTT implementation. This can automatically recover from outages amongst other advantages - but at the cost of larger code size.
Peter Hinch
Index to my micropython libraries.

Post Reply