Search code examples
mqttpublish-subscribeesp8266

Multiple ESP8266 subscribe to one RPI 3


i have problem to subscribe 2 (and more) ESP8266 to one RPi3 broker. I used:

import paho.mqtt.client as mqtt
import datetime

mqtt_topics = ["esp8266-1", "esp8266-2"]

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    for topic in mqtt_topics:
     client.subscribe(topic)

def on_message(client, userdata, msg):
    print(datetime.datetime.now())
        print(str(msg.topic)+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.connect('localhost', 1883, 60)

try:
    for topic in mqtt_topics:
        client.on_message = on_message
    client.loop_forever()
except KeyboardInterrupt:
        print("CTRL-C: Terminating program.")

It works but ony to 1 esp. If i connect esp8266-1 it checks it values, then i connect esp8266-2 to have its values and esp8266-1 is no longer available (even if i turn of esp8266-2).

How to subscribe both esp8266? I only can have one of them at time.


Solution

  • The code needs few changes:

    import paho.mqtt.client as mqtt
    import datetime
    
    mqtt_topics = [("esp8266-1",0), ("esp8266-2",0)]
    
    def on_connect(client, userdata, flags, rc):
      print("Connected with result code "+str(rc))
      client.subscribe(mqtt_topics)
    
    def on_message(client, userdata, msg):
      print(datetime.datetime.now())
      print(str(msg.topic)+" "+str(msg.payload))
    
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect('localhost', 1883, 60)
    
    try:
      client.loop_forever()
    except KeyboardInterrupt:
      print("CTRL-C: Terminating program.")
    

    But if one client works and a second forces the first to disconnect then it sounds like you have the same clientID for both clients. clientIDs need to be unique for all client.