首页 > 解决方案 > 羽绒服 MQTT

问题描述

我正在尝试将我的 Feather Huzzah 连接到本地 MQTT 服务器,但程序不断崩溃并抛出堆栈跟踪。当我尝试解码堆栈跟踪时,它只是空的,更频繁地我只得到堆栈跟踪的一部分。这是我正在运行的代码,其中大部分与 Arduino 的 pub/sub 客户端示例代码非常相似。我已经尝试擦除设备上的闪存,但这似乎没有帮助。

更奇怪的是它曾经工作过一次,但是当我再次尝试添加回调时,代码停止工作并崩溃了。如果我尝试删除回调,则没有任何变化。我已经尝试删除很多代码只是为了看看我是否可以获得与 MQTT 的一致连接,但这似乎也不起作用。MQTT 服务器是来自 Ubuntu 18.04 的最新 Mosquitto。

#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>

const char* ssid = "xxxxxxxx";
const char* password = "xxxxxxxxx";
const int hallPin = 14;
const int ledPin = 0;
const char* mqtt_server = "mosquitto.localdomain";
long lastMsg = 0;
char msg[100];
int value = 0;
int hallState = 0;

WiFiClient espClient;
PubSubClient client(espClient);
WiFiUDP ntpUDP;

// By default 'time.nist.gov' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP);

// Setup and connect to the wifi
void setup_wifi() {
  delay(100);
  Serial.print("Connecting to: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Wifi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Gateway: ");
  Serial.println(WiFi.gatewayIP());
}

//Reconnect to the MQTT broker
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("/homeassistant/devices/doorbell", "hello world");
      // ... and resubscribe
      client.subscribe("/homeassistant/doorbell/receiver");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//Process messages incoming from the broker
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
}

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
  Serial.begin(115200);
  setup_wifi();
  timeClient.begin();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) {
    setup_wifi();
  }
  if (!client.connected()) {
    reconnect();
  }
  hallState = digitalRead(hallPin);
  if (hallState == LOW) {
    digitalWrite(ledPin, HIGH);
    generateAndSendMessage(); 
    delay(1000); //Add in a delay so it doesn't send messages extremely rapidly
  } else {
    digitalWrite(ledPin, LOW);
  }
}

void generateAndSendMessage() {
  timeClient.update();
  StaticJsonBuffer<100> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["sensor"] = "doorbell";
  root["time"] = timeClient.getEpochTime();
  root["value"] = 1;
  root.printTo(msg);
  Serial.println(msg);
  client.publish("/homeassistant/devices/doorbell", msg);
}

标签: arduinomqttesp8266

解决方案


查看 generateAndSendMessage 函数,我相信由于 MQTT 缓冲区的大小,您遇到了问题。

MQTT 缓冲区默认设置为 128 字节。这包括通道名称的长度以及消息。

您的频道长度为 32 字节,用于制作消息的 json 缓冲区为 100 字节长。所以你可能只是超过了 128 字节标记。

只需在包含 PubSubClient.h 之前声明这一点

#define MQTT_MAX_PACKET_SIZE  200

此宏将 PubSubClient 的缓冲区大小定义为 200。您可以将其更改为您认为需要的任何内容。

我希望这有帮助。


推荐阅读