|
用EPS8266 NODEMCU 搞了一个用MQTT将数据上传阿里云的小玩意,数据只能上传一次就崩溃然后重新开始初始化
代码如下:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <aliyun_mqtt.h>
#define WIFI_SSID "XXX"
#define WIFI_PASSWD "XXX"
#define PRODUCT_KEY "XXX"
#define DEVICE_NAME "GL_SOHO_NO37_3F_1"
#define DEVICE_SECRET "XXXX"
#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"%s\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
#define ALINK_TOPIC_PROP_POSTRSP "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post_reply"
#define ALINK_TOPIC_PROP_SET "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/service/property/set"
#define ALINK_METHOD_PROP_POST "thing.event.property.post"
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient mqttClient(espClient);
void initWifi(const char *ssid, const char *password)
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("WiFi does not connect, try again ...");
delay(3000);
}
Serial.println("Wifi is connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
payload[length] = '\0';
Serial.println((char *)payload);
if (strstr(topic, ALINK_TOPIC_PROP_SET))
{
StaticJsonBuffer<100> jsonBuffer;
JsonObject &root = jsonBuffer.parseObject(payload);
if (!root.success())
{
Serial.println("parseObject() failed");
return;
}
}
}
void mqttCheckConnect()
{
while (!connectAliyunMQTT(mqttClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET))
{
}
Serial.println("MQTT connect succeed!");
mqttClient.subscribe(ALINK_TOPIC_PROP_SET);
Serial.println("subscribe done");
}
void mqttIntervalPost()
{
char param[32], jsonBuf[128], str_temp[18], str_temp2[20];
sprintf(param, "{\"mtemp\":%s}", "13.32");
sprintf(jsonBuf, ALINK_BODY_FORMAT, ALINK_METHOD_PROP_POST, param);
Serial.print("jsonBuf=");
Serial.println(jsonBuf);
mqttClient.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
}
void setup()
{
Serial.begin(115200);
Serial.println("");
Serial.println("");
Serial.println("Start......");
initWifi(WIFI_SSID, WIFI_PASSWD);
mqttClient.setCallback(callback);
}
void loop()
{
if (millis() - lastMs >= 5000)
{
lastMs = millis();
mqttCheckConnect();
mqttIntervalPost();
}
}
MQTT_MAX_PACKET_SIZE=2048了还崩溃,不知道为什
|
-
崩溃图片
|