我百度了一下,是客户端唯一标识符重复导致的出错,但是出错到底去哪里改也没有任何讲解,很纳闷...弄了很久,请问有人解决过这个问题吗?下面放上源码[mw_shl_code=arduino,true]#include <ESP8266WiFi.h>
/* 依赖 PubSubClient 2.4.0 */
#include <PubSubClient.h>
/* 依赖 ArduinoJson 5.13.4 */
#include <ArduinoJson.h>
const int trigPin = 5; //D1
const int echoPin = 4; //D2
int duration;
int distance;
/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID "ABC123"
#define WIFI_PASSWD "JFJS86328948."
/* 设备的三元组信息*/
#define PRODUCT_KEY "a1zdD6Vo6IT"
#define DEVICE_NAME "MY09s59vXPhFF76Z9nus"
#define DEVICE_SECRET "mMrQ7qbp3KVCDVRDGXUfLvBL38dEDmRI"
#define REGION_ID "cn-shanghai"
/* 线上环境域名和端口号,不需要改 */
#define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
#define MQTT_PORT 1883
#define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY
#define CLIENT_ID "sn123456|securemode=3,timestamp=1234567890,signmethod=hmacsha1|"
#define MQTT_PASSWD "3C5B003A994F4F9C4720DBC50ECB4AF4B4C948FD"
#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient client(espClient);
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);
}
void wifiInit()
{
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("WiFi not Connect");
}
Serial.println("Connected to AP");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("espClient [");
client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */
client.setCallback(callback);
}
void mqttCheckConnect()
{
while (!client.connected())
{
Serial.println("Connecting to MQTT Server ...");
if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
{
Serial.println("MQTT Connected!");
}
else
{
Serial.print("MQTT Connect err:");
Serial.println(client.state());
delay(5000);
}
}
}
void mqttIntervalPost()
{
char param[32];
char jsonBuf[128];
sprintf(param, "{\"idle\":%d}", UltrasonicFirst());
sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
Serial.println(jsonBuf);
boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
Serial.print("publish:0 失败;1成功");
Serial.println(d);
}
int UltrasonicFirst()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;
return distance;
}
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
/* initialize serial for debugging */
Serial.begin(115200);
Serial.println("Demo Start");
wifiInit();
}
// the loop function runs over and over again forever
void loop()
{
if (millis() - lastMs >= 5000)
{
lastMs = millis();
mqttCheckConnect();
/* 上报 */
mqttIntervalPost();
}
client.loop();
}[/mw_shl_code]
|