buxtronix / am43

Control AM43 blinds with an ESP32
MIT License
76 stars 25 forks source link

multiple devices on a single network #7

Closed adotagarwal closed 4 years ago

adotagarwal commented 4 years ago

In the example - It looks like the code uses a hardcoded prefix when it calls subscribe, ignoring the prefix set in config.h

if (pubSubClient.connect("am43-gateway", MQTT_USERNAME, MQTT_PASSWORD, "am43/LWT", 0, false, "Offline")) {
  Serial.println("connected");
  // Once connected, publish an announcement...
  pubSubClient.publish("am43/LWT", "Online", true);
  pubSubClient.subscribe("am43/restart");
  pubSubClient.subscribe("am43/all/set");
  pubSubClient.subscribe("am43/all/set_position");
  pubSubClient.loop();

Perhaps something along these lines would be better, otherwise the example will cause constant disconnects when deployed more than once with different prefixes

void reconnect_mqtt() {
  if (WiFi.status() == WL_CONNECTED && millis() > nextMqttAttempt) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (pubSubClient.connect((String(MQTT_TOPIC_PREFIX) + "-gateway").c_str(), MQTT_USERNAME, MQTT_PASSWORD, (String(MQTT_TOPIC_PREFIX) + "/LWT").c_str(), 0, false, "Offline")) {
      Serial.println("connected");
      // Once connected, publish an announcement...

      pubSubClient.publish((String(MQTT_TOPIC_PREFIX) + "/LWT").c_str(), "Online", true);
      pubSubClient.subscribe((String(MQTT_TOPIC_PREFIX) + "/restart").c_str());
      pubSubClient.subscribe((String(MQTT_TOPIC_PREFIX) + "/all/set").c_str());
      pubSubClient.subscribe((String(MQTT_TOPIC_PREFIX) + "/all/set_position").c_str());
      pubSubClient.loop();
    } else {
      Serial.print("failed, rc=");
      Serial.print(pubSubClient.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      nextMqttAttempt = millis() + 5000;
    }
  }
}
buxtronix commented 4 years ago

Fixed in the current repo version.