概述
一、前言
最近物联网越来越火,阿里也出了自己的物联网平台,对于物联网工程师来说,简直是天大的福音。阿里云物联网平台支持MQTT,手头上正好有ESP8266开发板,拿来练练手。对于开发ESP8266的小伙伴们来说,开发8266可以用SDK或者Arduino来开发,Arduino极大的简化了开发复杂度,所以本次开发就用Arduino。
二、工具准备
1.一个ESP8266开发板
三、阿里云平台注册设备(创建高级设备)
1.创建教程https://help.aliyun.com/document_detail/73705.html?spm=a2c4g.11174283.4.4.3a8b1668DyM7sV
2.主要地方用图说明
四、源代码修改
1.修改ESP8266.ino
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "aliyun_mqtt.h"
// GPIO 13, D7 on the Node MCU v3
#define SENSOR_PIN 13
#define WIFI_SSID "CMCC-123"//替换自己的WIFI
#define WIFI_PASSWD "12345678"//替换自己的WIFI
#define PRODUCT_KEY "abcvfg" //替换自己的PRODUCT_KEY
#define DEVICE_NAME "Temp_Sensor" //替换自己的DEVICE_NAME
#define DEVICE_SECRET "QhT3OdM9Yi4izSgiXdjKOPIoCzQbVcLy"//替换自己的DEVICE_SECRET
#define DEV_VERSION "S-TH-WIFI-v1.0-20190220" //固件版本信息
#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"
#define ALINK_TOPIC_DEV_INFO "/ota/device/inform/" PRODUCT_KEY "/" DEVICE_NAME ""
#define ALINK_VERSION_FROMA "{"id": 123,"params": {"version": "%s"}}"
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient mqttClient(espClient);
void init_wifi(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(500);
}
Serial.println("Wifi is connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void mqtt_callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
payload[length] = '