当存在与MQTT代理的新连接时,Arduino回调停止工作

时间:2018-01-18 21:58:56

标签: websocket callback arduino mqtt

第一次在这里发帖,我希望有人能帮我解决一个烦人的问题。

我试图通过带有websockets的MQTT控制Arduino,这一切都正常,直到与代理建立新的连接,然后Arduino不响应回调。

    #include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 123);
const char* server = "192.168.0.30";
char message_buff[100];

// defines and variable for sensor/control mode
#define MODE_OFF    0  // not sensing light, LED off
#define MODE_ON     1  // not sensing light, LED on
#define MODE_SENSE  2  // sensing light, LED controlled by software
int senseMode = 0;
unsigned long time;

EthernetClient ethClient;
PubSubClient mqttClient(ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
  int i = 0;
  for (int i=0;i<length;i++) {
   message_buff[i] = payload[i];
  }


   String msgString = String(message_buff);
   Serial.println("Payload: " + msgString);
  if (msgString.equals("onn")){
      senseMode = MODE_ON;

    }else if(msgString.equals("off")){
     senseMode = MODE_OFF;

    }


}
void reconnect() {
  // Loop until we're reconnected
  while (!mqttClient.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (mqttClient.connect("arduinoClient")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      mqttClient.publish("test","AR1 Connected");
      // ... and resubscribe
      mqttClient.subscribe("test");
    } else {
      Serial.print("failed, rc=");

      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup()
{
  Serial.begin(9600);
  pinMode(7, OUTPUT);
  mqttClient.setServer(server, 1883);
  mqttClient.setCallback(callback);

  Ethernet.begin(mac, ip);
  // Allow the hardware to sort itself out
  delay(1500);

}

void loop()
{
  if (!mqttClient.connected()) {
    reconnect();
  }
    switch (senseMode) {
    case MODE_OFF:
      // light should be off
      digitalWrite(7, LOW);
      break;
    case MODE_ON:
      // light should be on
      digitalWrite(7, HIGH);
      break;
    }
  mqttClient.loop();
}

输出:

Attempting MQTT connection...failed, rc= try again in 5 seconds
Attempting MQTT connection...connected
Payload: onn
Payload: off
Payload: JTPA.CONNECTED
Payload: onnA.CONNECTED
Payload: offA.CONNECTED

非常感谢任何帮助。

感谢。

1 个答案:

答案 0 :(得分:0)

由于在评论中出现问题,这里的问题是您对所有实例使用相同的MQTT客户端ID。这不起作用,因为每个客户端都需要一个唯一的ID,并且代理将断开重复项。

您需要一种方法来生成唯一ID,Arduino网站上的这个question有一些关于如何执行此操作的提示。