0
votes

My problem:

I have a Raspberry Pi, and I have installed the Mosquitto MQTT broker on it. My objective is to make 2 MQTT clients communicate over the Mosquitto broker, so I have installed the code below on two ESP8266 (WeMos D1 mini) and I have created this MQTT command: mosquitto_pub -h 192.168.1.20 -t /wassim/led -m "on".

So, when I connect only one ESP client, I see the message "on" in the serial monitor. But when I connect the second ESP client, I can't see any message on the serial monitor... (But if on the terminal of the Raspberry, then I can see everything. On the clients I can't see anything). The code:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <MQTTClient.h>

float temp;
float lm;
String aw="";
const char* host = "192.168.1.20";
const char* ssid = "THOMSON1121";
const char* password = "Wassim";
WiFiClient net;
MQTTClient mqtt;

void connect();

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("Booting...");
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);
  mqtt.begin(host, net);
  connect();
  if(mqtt.subscribe("/wassim/led")) {
    Serial.println("Subscription Valid !");
  }
  Serial.println("Setup completed...");
}

void loop() {
  if (!mqtt.connected()) {
    connect();
  }
  mqtt.loop();
  delay(3000);
}

void connect() {
  while(WiFi.waitForConnectResult() != WL_CONNECTED) {
    WiFi.begin(ssid, password);
    Serial.println("WiFi connection failed. Retry.");
  }
  Serial.print("Wifi connection successful - IP-Address: ");
  Serial.println(WiFi.localIP());
  while (!mqtt.connect(host)) {
    Serial.print(".");
  }
  Serial.println("MQTT connected!");
}

void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
  Serial.print("incoming: ");
  Serial.print(topic);
  Serial.print(" - ");
  Serial.print(payload);
  Serial.println();
}

The change from one client to another is if(mqtt.subscribe("/wassim/tmp")).

1
It's not clear you are asking here. Do you mean that one client is subscribed to /wassim/led & one to /wassim/tmp? If so you are only publishing to /wassim/led so only one device will receive the message. - hardillb

1 Answers

0
votes

MQTT is a 'message bus' application....in order to have multiple 'subscribers' receive the same message that is being put on the bus by a 'publisher', they both have to subscribe to the same topic...or at least enough of the topic + wildcard...in order to get sent that published message. You only have one of your two clients listening to the topic that your 'mosquitto_pub' command is sending out. For it to receive, you either specify the full topic (mqtt.subscribe("/wassim/led")), or a wildcard to pick up all the 'wassim' messages sent out (mqtt.subscribe("/wassim/#")).