Movatterモバイル変換


[0]ホーム

URL:


Skip to content
HOMEESP32ESP8266ESP32-CAMRASPBERRY PIMICROPYTHONRPi PICOARDUINOREVIEWS

MicroPython – Getting Started with MQTT on ESP32/ESP8266

In this tutorial, we’ll show you how to use MQTT to exchange data between two ESP32/ESP8266 boards using MicroPython firmware. As an example, we’ll exchange simple text messages between two ESP boards. The idea is to use the concepts learned here to exchange sensor readings, or commands.

MicroPython Getting Started with MQTT on ESP32/ESP8266

Note:this tutorialis compatible with both the ESP32 and ESP8266 development boards. 

Prerequisites

Before continuing with this tutorial, make sure you complete the following prerequisites:

MicroPython firmware

To program the ESP32 and ESP8266 with MicroPython, we use uPyCraft IDE as a programming environment. Follow the next tutorials to install uPyCraft IDE and flash MicroPython firmware on your board:

MQTT Broker

To use MQTT, you need a broker. We’ll be usingMosquitto broker installed on a Raspberry Pi. Read How to Install Mosquitto Broker on Raspberry Pi.

If you’re not familiar with MQTT make sure you read our introductory tutorial: What is MQTT and How It Works

Parts Required

For this tutorial you need two ESP32 or two ESP8266 boards:

You also need a Raspberry Pi and the following accessories:

You can use the preceding links or go directly toMakerAdvisor.com/tools to find all the parts for your projects at the best price!

Project Overview

Here’s a high-level overview of the project we’ll build:

  • ESP#1 publishes messages on thehellotopic. It publishes a “Hello” message followed by a counter (Hello 1, Hello 2, Hello 3, …). It publishes a new message every 5 seconds.
  • ESP#1 is subscribed to thenotificationtopic to receive notifications from the ESP#2 board.
  • ESP#2 is subscribed to thehello topic. ESP #1 is publishing in this topic. Therefore, ESP#2 receives ESP#1 messages.
  • When ESP#2 receives the messages, it sends a message saying ‘received’. This message is published on thenotification topic. ESP#1 is subscribed to that topic, so it receives the message.

Preparing ESP#1

Let’s start by preparing ESP#1:

  • It is subscribed to thenotificationtopic
  • It publishes on thehellotopic

Importing umqttsimple library

To use MQTT with the ESP32/ESP8266 and MicroPython, you need to install theumqttsimple library.

1. Create a new file by pressing theNew File button.

2. Copy theumqttsimple library code into it. You can access theumqttsimple library code in the following link:

3. Save the file by pressing theSave button.

4. Call this new file “umqttsimple.py” and pressok.

5. Click theDownload and Run button.

6. The file should be saved on thedevice folder with the name “umqttsimple.py” as highlighted in the figure below.

Now, you can use the library functionalities in your code by importing the library.

boot.py

Open theboot.py file and copy the following code to ESP#1.

# Complete project details at https://RandomNerdTutorials.com/micropython-programming-with-esp32-and-esp8266/import timefrom umqttsimple import MQTTClientimport ubinasciiimport machineimport micropythonimport networkimport espesp.osdebug(None)import gcgc.collect()ssid = 'REPLACE_WITH_YOUR_SSID'password = 'REPLACE_WITH_YOUR_PASSWORD'mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'mqtt_user = 'REPLACE_WITH_YOUR_MQTT_USERNAME'mqtt_pass = 'REPLACE_WITH_YOUR_MQTT_PASSWORD'#EXAMPLE IP ADDRESS#mqtt_server = '192.168.1.144'client_id = ubinascii.hexlify(machine.unique_id())topic_sub = b'notification'topic_pub = b'hello'last_message = 0message_interval = 5counter = 0station = network.WLAN(network.STA_IF)station.active(True)station.connect(ssid, password)while station.isconnected() == False:  passprint('Connection successful')print(station.ifconfig())

View raw code

How the Code Works

You need to import all the following libraries:

import timefrom umqttsimple import MQTTClientimport ubinasciiimport machineimport micropythonimport networkimport esp

Set the debug to None and activate the garbage collector.

esp.osdebug(None)import gcgc.collect()

In the following variables, you need to enter your network credentials, your broker IP address, the broker username and corresponding password.

ssid = 'REPLACE_WITH_YOUR_SSID'password = 'REPLACE_WITH_YOUR_PASSWORD'mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'mqtt_user = 'REPLACE_WITH_YOUR_MQTT_USERNAME'mqtt_pass = 'REPLACE_WITH_YOUR_MQTT_PASSWORD'

For example, our broker IP address is: 192.168.1.144.

Note: read this tutorial to see how to get your broker IP address.

To create an MQTT client, we need to get the ESP unique ID. That’s what we do in the following line (it is saved on theclient_id variable).

client_id = ubinascii.hexlify(machine.unique_id())

Next, write the topic the ESP#1 is subscribed to, and the topic it will be publishing messages:

topic_sub = b'notification'topic_pub = b'hello'

Then, create the following variables:

last_message = 0message_interval = 5counter = 0

Thelast_message variable will hold the last time a message was sent. Themessage_interval is the time between each message sent. Here, we’re setting it to 5 seconds (this means a new message will be sent every 5 seconds). Thecounter variable is simply a counter to be added to the message.

After that, we make the procedures to connect to the network.

station = network.WLAN(network.STA_IF)station.active(True)station.connect(ssid, password)while station.isconnected() == False:  passprint('Connection successful')print(station.ifconfig())

main.py

In themain.py file is where we’ll write the code to publish and receive the messages. Copy the following code to yourmain.py file.

# Complete project details at https://RandomNerdTutorials.com/micropython-programming-with-esp32-and-esp8266/def sub_cb(topic, msg):  print((topic, msg))  if topic == b'notification' and msg == b'received':    print('ESP received hello message')def connect_and_subscribe():  global client_id, mqtt_server, topic_sub  client = MQTTClient(client_id, mqtt_server, user=mqtt_user, password=mqtt_pass)  client.set_callback(sub_cb)  client.connect()  client.subscribe(topic_sub)  print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))  return clientdef restart_and_reconnect():  print('Failed to connect to MQTT broker. Reconnecting...')  time.sleep(10)  machine.reset()try:  client = connect_and_subscribe()except OSError as e:  restart_and_reconnect()while True:  try:    client.check_msg()    if (time.time() - last_message) > message_interval:      msg = b'Hello #%d' % counter      client.publish(topic_pub, msg)      last_message = time.time()      counter += 1  except OSError as e:    restart_and_reconnect()

View raw code

How the code works

The first thing you should do is creating a callback function that will run whenever a message is published on a topic the ESP is subscribed to.

Callback function

The callback function should accept as parameters the topic and the message.

defsub_cb(topic, msg):  print((topic, msg))  if topic == b'notification' and msg == b'received':    print('ESP received hello message')

In our callback function, we start by printing the topic and the message. Then, we check if the message was published on thenotificationtopic, and if the content of the message is ‘received’. If this if statement is True, it means that ESP#2 received the ‘hello’ message sent by ESP#1.

Basically, this callback function handles what happens when a certain message is received on a certain topic.

Connect and subscribe

Then, we have theconnect_and_subscribe() function. This function is responsible for connecting to the broker as well as to subscribe to a topic.

defconnect_and_subscribe():

Start by declaring theclient_id,mqtt_server andtopic_sub variables as global variables. This way, we can access these variables throughout the code.

global client_id, mqtt_server, topic_sub

Then, create aMQTTClient object calledclient. We need to pass as parameters thecliend_id, the IP address of the MQTT broker (mqtt_server), and the broker username and password. These variables were set on theboot.py file.

client = MQTTClient(client_id, mqtt_server, user=mqtt_user, password=mqtt_pass)

After that, set the callback function to the client (sub_cb).

client.set_callback(sub_cb)

Next, connect the client to the broker using theconnect() method on theMQTTClient object.

client.connect()

After connecting, we subscribe to thetopic_sub topic. Set thetopic_sub on theboot.py file (notification).

client.subscribe(topic_sub)

Finally, print a message and return the client:

print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))return client

Restart and reconnect

We create a function calledrestart_and_reconnect(). This function will be called in case the ESP32 or ESP8266 fails to connect to the broker.

This function prints a message to inform that the connection was not successful. We wait 10 seconds. Then, we reset the ESP using thereset() method.

defrestart_and_reconnect():  print('Failed to connect to MQTT broker. Reconnecting...')  time.sleep(10)  machine.reset()

Receive and publish messages

Until now, we’ve created functions to handle tasks related with the MQTT communication. From now on, the code will call those functions to make things happen.

The first thing we need to do is to connect to the MQTT broker and subscribe to a topic. So, we create a client by calling theconnect_and_subscribe() function.

try:  client = connect_and_subscribe()

In case we’re not able to connect to the MQTTT broker, we’ll restart the ESP by calling therestart_and_reconnect() function

except OSError as e:  restart_and_reconnect()

In the while loop is where we’ll be receiving and publishing the messages. We usetry andexcept statements to prevent the ESP from crashing in case something goes wrong.

Inside thetry block, we start by applying thecheck_msg() method on theclient.

try:  client.check_msg()

Thecheck_msg() method checks whether a pending message from the server is available. It waits for a single incoming MQTT message and process it. The subscribed messages are delivered to the callback function we’ve defined earlier (thesub_cb() function). If there isn’t a pending message, it returns withNone.

Then, we add anif statement to checker whether 5 seconds (message_interval) have passed since the last message was sent.

if (time.time() - last_message) > message_interval:

If it is time to send a new message, we create amsg variable with the “Hello” text followed by a counter.

msg = b'Hello #%d' % counter

To publish a message on a certain topic, you just need to apply thepublish() method on theclient and pass as arguments, the topic and the message. Thetopic_pub variable was set tohello in theboot.py file.

client.publish(topic_pub,msg)

After sending the message, we update the last time a message was received by setting thelast_message variable to the current time.

last_message = time.time()

Finally, we increase thecounter variable in every loop.

counter += 1

If something unexpected happens, we call therestart_and_reconnect() function.

except OSError as e:  restart_and_reconnect()

That’s it for ESP#1. Remember that you need to upload all the next files to make the project work (you should upload the files in order):

  1. umqttsimple.py;
  2. boot.py;
  3. main.py.

After uploading all files, you should get success messages on: establishing a network connection; connecting to the broker; and subscribing to the topic.

ESP #2

Let’s now prepare ESP#2:

  • It is subscribed to thehellotopic
  • It publishes on thenotificationtopic

Like the ESP#1, you also need to upload theumqttsimple.py,boot.py, andmain.py files.

Importing umqttsimple

To use MQTT with the ESP32/ESP8266 and MicroPython, you need to install theumqttsimple library. Follow the steps described earlier to install theumqttsimple library in ESP#2.

You can access the umqttsimple library code in the following link:

boot.py

Copy the following code to the ESP#2boot.py file.

# Complete project details at https://RandomNerdTutorials.com/micropython-programming-with-esp32-and-esp8266/import timefrom umqttsimple import MQTTClientimport ubinasciiimport machineimport micropythonimport networkimport espesp.osdebug(None)import gcgc.collect()ssid = 'REPLACE_WITH_YOUR_SSID'password = 'REPLACE_WITH_YOUR_PASSWORD'mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'mqtt_user = 'REPLACE_WITH_YOUR_MQTT_USERNAME'mqtt_pass = 'REPLACE_WITH_YOUR_MQTT_PASSWORD'#EXAMPLE IP ADDRESS#mqtt_server = '192.168.1.144'client_id = ubinascii.hexlify(machine.unique_id())topic_sub = b'hello'topic_pub = b'notification'station = network.WLAN(network.STA_IF)station.active(True)station.connect(ssid, password)while station.isconnected() == False:  passprint('Connection successful')print(station.ifconfig())

View raw code

This code is very similar to the previousboot.py file. You need to replace the following variables with your network credentials, the broker IP address, the broker username and password.

ssid = 'REPLACE_WITH_YOUR_SSID'password = 'REPLACE_WITH_YOUR_PASSWORD'mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'mqtt_user = 'REPLACE_WITH_YOUR_MQTT_USERNAME'mqtt_pass = 'REPLACE_WITH_YOUR_MQTT_PASSWORD'

The only difference here is that we subscribe to thehellotopic and publish on thenotificationtopic.

topic_sub = b'hello'topic_pub = b'notification'

main.py

Copy the following code to the ESP#2main.py file.

# Complete project details at https://RandomNerdTutorials.com/micropython-programming-with-esp32-and-esp8266/def sub_cb(topic, msg):  print((topic, msg))def connect_and_subscribe():  global client_id, mqtt_server, topic_sub  client = MQTTClient(client_id, mqtt_server, user=mqtt_user, password=mqtt_pass)  client.set_callback(sub_cb)  client.connect()  client.subscribe(topic_sub)  print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))  return clientdef restart_and_reconnect():  print('Failed to connect to MQTT broker. Reconnecting...')  time.sleep(10)  machine.reset()try:  client = connect_and_subscribe()except OSError as e:  restart_and_reconnect()while True:  try:    new_message = client.check_msg()    if new_message != 'None':      client.publish(topic_pub, b'received')    time.sleep(1)  except OSError as e:    restart_and_reconnect()

View raw code

This code is very similar to themain.py from ESP#1. We create thesub_cb(), theconnect_and_subscribe() and therestart_and_reconnect() functions. This time, thesub_cb() function just prints information about the topic and received message.

def sub_cb(topic, msg):  print((topic, msg))

In the while loop, we check if we got a new message and save it in thenew_message variable.

new_message = client.check_msg()

If we receive a new message, we publish a message saying ‘received’ on thetopic_sub topic (in this case we set it tonotification in theboot.py file).

if new_message != 'None':  client.publish(topic_pub, b'received')

That’s it for ESP#2. Remember that you need to upload all the next files to make the project work (you should upload the files in order):

  1. umqttsimple.py;
  2. boot.py;
  3. main.py.

The ESP32/ESP8266 should establish a network connection and connect to the broker successfully.

Demonstration

After uploading all the necessary scripts to both ESP boards and having both boards and the Raspberry Pi with the Mosquitto broker running, you are ready to test the setup.

The ESP#2 should be receiving the “Hello” messages from ESP#1, as shown in the figure below.

On the other side, ESP#1 board should receive the “received” message. The “received” message is published by ESP#2 on thenotificationtopic. ESP#1 is subscribed to that topic, so it receives the message.

Wrapping Up

In this simple example, you’ve learned how to exchange text between two ESP32/ESP8266 boards using MQTT communication protocol. The idea is to use the concepts learned here to exchange useful data like sensor readings or commands to control outputs.

If you like MicroPython with the ESP32/ESP8266, you may also like:



SMART HOME with Raspberry Pi ESP32 and ESP8266 Node-RED InfluxDB eBook
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects »Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

60 thoughts on “MicroPython – Getting Started with MQTT on ESP32/ESP8266”

  1. How is going mypython to ESP32 (BLE) ? (BLUETOOTH)

    Reply
  2. Prakticke, jednoduche perfekt!
    Priama komunikacia ESP32 s ESP32 bez Pi s micropython ?

    Reply
  3. Hi

    Does the mqtt library in this tutorial support mqtt over websocketS? If not do you know an ESP32 Arduino or Micropython library that does?

    Regards

    Ian

    Reply
  4. code reports a syntax error in line 82. Code copied directly from webpage with zero changes made to it. Has anyone actually gotten this code to run?

    https://raw.githubusercontent.com/RuiSantosdotme/ESP-MicroPython/master/code/MQTT/umqttsimple.py

    Reply
    • Hi Bill.
      That is the umqtt simple library code. I’ve tested uploading the library to my ESP32 and it is working fine.
      You probably have an indentation error.Please check that you have copied the code correctly and that all the indentation is ok.
      With some editors, sometimes it is very easy to accidentally mess up with indentation copying code.
      Regards,
      Sara

      Reply
    • I know this is old but I had this issue too. Here’s the fix: set keepalive to a nonzero number in the constructor in umqttsimple.py.

      definit(self, client_id, server, port=0, user=None, password=None, keepalive=1 <<– THIS

      github.com/micropython/micropython-lib/issues/466

      Reply
  5. one of the best mqtt instructions, thank you very much!

    Reply
  6. Great article! I’m trying to connect to a MQTT server with username/password though – do you have any hints on how I can achieve this?

    Reply
  7. Very nice article, I tried to figure out how to use keep alive and will so that I get a message when the device loses the connection to the broker. I now have a device that does not always detect that it is offline and does not restart. Thanks again for your effort!

    Reply
    • Hi.
      We added the restart_and_reconnect() that is responsible for restarting your board in case it disconnects from the broker.
      Isn’t that happening in your case?
      Regards,
      Sara

      Reply
      • Hi Sara and thanks for the fast answer. I’ve added stuff to the code (running leds based on mqtt messages) but after running for 4-5 hours the boards does not do anything anymore (I have 5 boards and today 2 of them stopped). The reconnect/restart happens if I shutdown the broker when it is still connected but it does not work if it has been on for hours and has lost connection. The only way to know if they are working is to check if they respond to the commands I send. That is why the keepalive is important because otherwise it will take hours before the will is broadcasted.

        Reply
  8. If you are using ESP8266 I recommend that instead of callingclient.check_msg() you useclient.wait_msg(). Executingclient.check_msg() in the while loop caused my device to constantly restart after a few minutes.

    Reply
  9. Late coming in…
    Great post!
    one comment: The umqttsimple lib in the top is spelled with 3 ‘t’s
    one question: instead of a second ESP32 how could I use the raspberry wthout the mosquito installed?

    Reply
  10. Also late finding this…
    I’m running my MQTT broker on a Win7 machine and trying to connect a NodeMCU running micro python on the same network. I’ve tried connecting to ‘localhost’, ‘127.0.0.1’, and ‘192.168.12.229’ (Win7 IP), but nothing works. It works fine when I connect to a cloud MQTT broker. The service is running and listening on port 1883. Any advice?
    Thanks.

    Reply
  11. Could I use mqtt.eclipseprojects.io as MQTT server?
    For example, modify mqtt_server = ‘REPLACE_WITH_YOUR_MQTT_BROKER_IP’
    become mqtt_server = ‘mqtt.eclipseprojects.io’

    Reply
  12. I try the demo code but it’s fail on client.connect() by connect_and_subscribe() functions.
    It seem that I didn’t connect to the broker successfully.
    Traceback (most recent call last):
    File “main.py”, line 21, in (this is point to try: client = connect_and_subscribe())
    File “main.py”, line 10, in connect_and_subscribe () (this is point to client.connect())
    File “umqttsimple.py”, line 103, in connect
    MQTTException: 2

    Reply
  13. I am trying to connect to test.mosquitto.org using umqttsimple and micropython but I keep getting an exception:

    $ ./micropython
    MicroPython v1.17-74-gd42cba0d2 on 2021-09-30; linux version
    Use Ctrl-D to exit, Ctrl-E for paste mode
    >>> from umqttsimple import MQTTClient
    >>> client = MQTTClient("test_client", "test.mosquitto.org")
    >>> client.connect()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "umqttsimple.py", line 102, in connect
    MQTTException: 2
    >>>

    This is running on the linux version of micropython, but I’ve also tried on an ESP8266 running micropython and get the same error.

    Reply
    • Hi.
      Do you get the same error when using the complete script?
      Regards,
      Sara

      Reply
      • So I’ve combined the boot.py and main.py together and commented out the parts that require an ESP:

        # Complete project details at https://RandomNerdTutorials.com

        import time
        from umqttsimple import MQTTClient
        import ubinascii
        import machine
        import micropython
        #import network
        #import esp
        #esp.osdebug(None)
        import gc
        gc.collect()

        ssid = 'REPLACE_WITH_YOUR_SSID'
        password = 'REPLACE_WITH_YOUR_PASSWORD'
        mqtt_server = 'mqtt.eclipseprojects.io'
        #EXAMPLE IP ADDRESS
        #mqtt_server = '192.168.1.144'
        client_id = "client_id"
        topic_sub = b'notification'
        topic_pub = b'hello'

        last_message = 0
        message_interval = 5
        counter = 0

        #station = network.WLAN(network.STA_IF)

        #station.active(True)
        #station.connect(ssid, password)

        #while station.isconnected() == False:
        # pass

        #print('Connection successful')
        #print(station.ifconfig())

        # Complete project details at https://RandomNerdTutorials.com

        def sub_cb(topic, msg):
        print((topic, msg))
        if topic == b'notification' and msg == b'received':
        print('ESP received hello message')

        def connect_and_subscribe():
        global client_id, mqtt_server, topic_sub
        client = MQTTClient(client_id, mqtt_server)
        client.set_callback(sub_cb)
        client.connect()
        client.subscribe(topic_sub)
        print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
        return client

        def restart_and_reconnect():
        print('Failed to connect to MQTT broker. Reconnecting...')
        time.sleep(10)
        machine.reset()

        try:
        client = connect_and_subscribe()
        except OSError as e:
        print(e)
        restart_and_reconnect()

        while True:
        try:
        client.check_msg()
        if (time.time() - last_message) > message_interval:
        msg = b'Hello #%d' % counter
        client.publish(topic_pub, msg)
        last_message = time.time()
        counter += 1
        except OSError as e:
        restart_and_reconnect()

        and I can confirm that I get the same error:

        $ ./micropython tmp.py
        Traceback (most recent call last):
        File "tmp.py", line 60, in <module>
        File "tmp.py", line 49, in connect_and_subscribe
        File "umqttsimple.py", line 102, in connect
        MQTTException: 2

        Reply
  14. Hi,
    Thanks for sharing.
    Why using umqttsimple library and not the built in umqtt.robust? What’s the difference? I’m using an ESP32.
    Thank you.

    Reply
  15. hi,
    Is there an easy way to store the subscribed message in a variable on the esp ?
    (i tried to store the message in a global var in the de “def sub_cb(topic, msg):” but that is not so stable)

    def sub_cb(topic, msg):
    print((topic, msg))
    test = (topic, msg)
    data = test[1].decode(“utf-8”)
    global command
    command = data

    Reply
  16. Thanks for providing this example code and special thanks to Macro for the keepalive fix.

    Reply
  17. This is a great tutorial thank you!! best one I found while researching AND got my esp32 up and working with mqtt….my only question is… and I’m new to micro python so forgive me if this is really basic… why do the pub/sub topics have a ‘b’ in front of them?

    Reply
  18. Hi,
    I am implement the code to MQTT and the conecction with the WIFI is successful however it trying conect with the broker is ‘Failed to connect to MQTT broker. Reconnecting…’ i am used the Node Red.
    someone can help me.
    Thank you.
    Lucas

    Reply
  19. Hola, muy buen tutorial. Quisiera saber como puedo enviar multiples datos con un solo publish. Por ejemplo, si tengo dos sensores, como deberia escribir la linea de código para enviar dos datos al tiempo?.

    Gracias

    Reply
  20. Hey! It can’t handle special characters like äåö, how can I solve this? UTF-8?

    Reply
  21. Hello. Thanks for the post

    “new_message = client.check_msg()” does not save the variable for me.

    I can see the text coming over just fine , but does not save to the variable:

    while True:
    try:
    a = client.check_msg()
    print(“a is”, a)
    time.sleep(5)
    except OSError as e:
    restart_and_reconnect()

    I just get:

    a is None

    Thanks!

    Reply
  22. Please provide guidance: ERROR: [Errno 104] ECONNRESET

    I can ping the ESP32 from the laptop

    The mosquitto broker is running (standard, no changes):
    ps ax | grep mosqu
    1043 ? Ss 0:00 /bin/sh /snap/mosquitto/776/launcher.sh
    1320 ? S 0:01 /snap/mosquitto/776/usr/sbin/mosquitto -c /snap/mosquitto/776/default_config.conf
    8230 pts/2 S+ 0:00 /snap/mosquitto/776/usr/bin/mosquitto_sub -h localhost -t to_sensors -v

    Subscriptions work on the laptop:
    mosquitto_sub -h localhost -t ‘to_sensors’ -v
    to_sensors Hello from mosquitto_pub
    to_sensors Hello from mosquitto_pub

    obviously the publisher must work because the subscriber is receiving:
    mosquitto_pub -h localhost -t ‘to_sensors’ -m ‘Hello from mosquitto_pub’

    I modified the example code in this post to read:
    try:
    client.connect()
    except Exception as e:
    print(f”MQTT: connect_and_subscribe: client.connect(): ERROR: {e}”)
    which is where we find the error:
    MQTT: connect_and_subscribe: client.connect(): ERROR: [Errno 104] ECONNRESET

    My phone can ping both the ESP32 and my laptop.

    I don’t think it is the firewall:
    sudo ufw status
    Status: inactive

    Help?

    Reply
  23. HI Sara: I have been looking for an asyncio mqtt client. Any pointers to the best one?

    Reply
  24. Hi, Sara:
    I’ve found a couple of bugs in umqttsimple.py. The first is that .check_msg() returns the return value of .wait_msg(), but .wait_msg never returns the payload message. The second is that, for whatever reason, when I call .publish() my broker never receives the payload.

    I’ve patched .wait_msg() by adding ‘return msg’ at line 202, but I can’t see why .publish() isn’t working.

    Reply
  25. If you take error with esp8266, you can add parameter “keepalive=60” while initilization of MQTTClient() class.

    Like this: client = MQTTClient( [..other parameters..] , keepalive=60)

    Reply
  26. Below code is not working:

    client_id = ubinascii.hexlify(machine.unique_id())

    mqttClient =MQTTClient(
    client_id=client_id,
    server=”host goes here”,
    port=12104,
    user=”default”,
    password= “password goes here”

    )

    topic_sub = b’notification’
    topic_pub = b’hello’

    def on_message_received(topic, msg):
    print((topic, msg))

    mqttClient.set_callback(on_message_received)
    print(“trying connect”)
    try:
    mqttClient.connect()
    client.subscribe(topic_sub)
    print(“Connected with robust client!”)
    except Exception as e:
    print(“Connection failed:”, e)

    Reply

Leave a CommentCancel reply

Learn MicroPython

MicroPython Introduction

Thonny IDE Install

VS Code Install

Flash Firmware esptool.py

MicroPython Programming

MicroPython GPIOs

ESP32 Pinout

MicroPython Inputs Outputs

MicroPython PWM

MicroPython Analog Inputs

MicroPython Interrupts

ESP32 Deep Sleep

ESP8266 Deep Sleep

Web Servers

MicroPython Output Web Server

MicroPython Relay Web Server

MicroPython DHT Web Server

MicroPython BME280 Web Server

MicroPython BME680 Web Server

MicroPython DS18B20 Web Server

Sensors and Modules

MicroPython Relay Module

MicroPython PIR

MicroPython DHT11/DHT22

MicroPython BME280

MicroPython BME680

MicroPython DS18B20

MicroPython Multiple DS18B20

Weather Station Datalogger

MicroPython OLED

MicroPython OLED Draw Shapes

MicroPython WS2812B LEDs

MicroPython HC-SR04

MQTT

MicroPython MQTT Introduction

MQTT DHT11/DHT22

MQTT BME280

MQTT BME680

MQTT DS18B20

Useful Guides

MicroPython Access Point

MicroPython WiFiManager

uPyCraft IDE Windows

uPyCraft IDE Mac OS X

uPyCraft IDE Linux

Flash MicroPython Firmware

Learn More

Learn ESP32

Learn ESP8266

Learn ESP32-CAM

Learn MicroPython

Learn Arduino

MicroPython eBook »

Affiliate Disclosure:Random Nerd Tutorials is a participant in affiliate advertising programs designed to provide a means for us to earn fees by linking to Amazon, eBay, AliExpress, and other sites. We might be compensated for referring traffic and business to these companies.



Learn ESP32 with Arduino IDE eBook » Complete guide to program the ESP32 with Arduino IDE!



SMART HOME with Raspberry Pi, ESP32, and ESP8266 » learn how to build a complete home automation system.



Learn Raspberry Pi Pico/Pico W with MicroPython​ » The complete getting started guide to get the most out of the the Raspberry Pi Pico/Pico W (RP2040) microcontroller board using MicroPython programming language.



🔥 Learn LVGL: Build GUIs for ESP32 Projects​ » Learn how to build Graphical User Interfaces (GUIs) for ESP32 Projects using LVGL (Light Versatile Graphics Library) with the Arduino IDE.

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.


[8]ページ先頭

©2009-2025 Movatter.jp