ESP32连接阿里云
主函数
#include <WiFi.h>
#include <Wire.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "aliyun_mqtt.h"
#define SENSOR_PIN 10
//以下信息需要自己修改
#define WIFI_SSID "******"//替换自己的WIFI
#define WIFI_PASSWD "************"//替换自己的WIFI
#define PRODUCT_KEY "*******" //替换自己的PRODUCT_KEY
#define DEVICE_NAME "*******" //替换自己的DEVICE_NAME
#define DEVICE_SECRET "*************"//替换自己的DEVICE_SECRET
//以下不需修改
#define DEV_VERSION "XYJ_TEST" //固件版本信息
#define TOPIC "/a1uPlcmbS7b/DHT11/user/wendu"
#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"%s\",\"params\":%s}" /*要发布的信息json*/
#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 "" /*设备上报固件信息(发布)*/
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient mqttClient(espClient);
//wifi初始化函数
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] = '\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 mqtt_version_post()
{
char param[512];
char jsonBuf[1024];
sprintf(param, "{\"id\": 123,\"params\": {\"version\": \"%s\"}}", DEV_VERSION);
Serial.println(param);
mqttClient.publish(ALINK_TOPIC_DEV_INFO, param);
}
//检查mqqt连接情况
void mqtt_check_connect()
{
while (!mqttClient.connected())//
{
while (connect_aliyun_mqtt(mqttClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET))
{
Serial.println("MQTT connect succeed!");
mqttClient.subscribe(ALINK_TOPIC_PROP_SET);
Serial.println("subscribe done");
mqtt_version_post();
}
}
}
//发布温湿度信息
void mqtt_interval_post()
{
char param[512];
char jsonBuf[1024];
sprintf(param, "{\"CurrentHumidity\":%d,\"CurrentTemperature\":18}", digitalRead(13));
sprintf(jsonBuf, ALINK_BODY_FORMAT, ALINK_METHOD_PROP_POST, param);
Serial.println(jsonBuf);
mqttClient.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
}
void setup()
{
pinMode(SENSOR_PIN, INPUT);
Serial.begin(115200);
Serial.println("Demo Start");
init_wifi(WIFI_SSID, WIFI_PASSWD);
mqttClient.setCallback(mqtt_callback);
}
void loop()
{
if (millis() - lastMs >= 20000)
{
lastMs = millis();
mqtt_check_connect();
/* Post */
mqtt_interval_post();
}
mqttClient.loop();
unsigned int WAIT_MS = 2000;
if (digitalRead(SENSOR_PIN) == HIGH)
{
Serial.println("Motion detected!");
}
else
{
Serial.println("Motion absent!");
}
delay(WAIT_MS); // ms
Serial.println(millis() / WAIT_MS);
}
cpp文件
/*
Aliyun_mqtt.h - Library for connect to Aliyun MQTT server.
*/
#include "aliyun_mqtt.h"
#include <SHA256.h>
#define MQTT_PORT 1883
#define SHA256HMAC_SIZE 32
// Verify tool: http://tool.oschina.net/encrypt?type=2
static String hmac256(const String &signcontent, const String &ds)
{
byte hashCode[SHA256HMAC_SIZE];
SHA256 sha256;
const char *key = ds.c_str();
size_t keySize = ds.length();
sha256.resetHMAC(key, keySize);
sha256.update((const byte *)signcontent.c_str(), signcontent.length());
sha256.finalizeHMAC(key, keySize, hashCode, sizeof(hashCode));
String sign = "";
for (byte i = 0; i < SHA256HMAC_SIZE; ++i)
{
sign += "0123456789ABCDEF"[hashCode[i] >> 4];
sign += "0123456789ABCDEF"[hashCode[i] & 0xf];
}
return sign;
}
static String mqttBroker;
static String mqttClientID;
static String mqttUserName;
static String mqttPassword;
// call this function once
void mqtt_prepare(const char *timestamp,const char *productKey, const char *deviceName,const char *deviceSecret,const char *region)
{
mqttBroker = productKey;
mqttBroker += ".iot-as-mqtt.";
mqttBroker += String(region);
mqttBroker += ".aliyuncs.com";
// Serial.println(mqttBroker);
mqttUserName = deviceName;
mqttUserName += '&';
mqttUserName += productKey;
//Serial.println(mqttUserName);
mqttClientID = deviceName; // device name used as client ID
mqttClientID += "|securemode=3,signmethod=hmacsha256,timestamp=";
mqttClientID += timestamp;
mqttClientID += '|';
//Serial.println(mqttClientID);
}
bool connect_aliyun_mqtt_With_password(PubSubClient &mqttClient, const char *password)
{
mqttClient.setServer(mqttBroker.c_str(), MQTT_PORT);
byte mqttConnectTryCnt = 5;
while (!mqttClient.connected() && mqttConnectTryCnt > 0)
{
//Serial.println("Connecting to MQTT Server ...");
if (mqttClient.connect(mqttClientID.c_str(), mqttUserName.c_str(), password))
{
// Serial.println("MQTT Connected!");
return true;
}
else
{
byte errCode = mqttClient.state();
//Serial.print("MQTT connect failed, error code:");
//Serial.println(errCode);
if (errCode == MQTT_CONNECT_BAD_PROTOCOL || errCode == MQTT_CONNECT_BAD_CLIENT_ID || errCode == MQTT_CONNECT_BAD_CREDENTIALS || errCode == MQTT_CONNECT_UNAUTHORIZED)
{
//Serial.println("No need to try again.");
break; // No need to try again for these situation
}
delay(3000);
}
mqttConnectTryCnt -= 1;
}
return false;
}
bool connect_aliyun_mqtt(
PubSubClient &mqttClient,
const char *productKey,
const char *deviceName,
const char *deviceSecret,
const char *region)
{
String timestamp = String(millis());
mqtt_prepare(timestamp.c_str(), productKey, deviceName, deviceSecret, region);
// Generate MQTT Password, use deviceName as clientID
String signcontent = "clientId";
signcontent += deviceName;
signcontent += "deviceName";
signcontent += deviceName;
signcontent += "productKey";
signcontent += productKey;
signcontent += "timestamp";
signcontent += timestamp;
String mqttPassword = hmac256(signcontent, deviceSecret);
//Serial.print("HMAC256 data: ");
//Serial.println(signcontent);
//Serial.print("HMAC256 key: ");
// Serial.println(deviceSecret);
// Serial.println(mqttPassword);
return connect_aliyun_mqtt_With_password(mqttClient, mqttPassword.c_str());
}
h文件
/*
Aliyun_mqtt.h - Library for connect to Aliyun MQTT server with authentication by
product key, device name and device secret.
https://www.alibabacloud.com/help/product/30520.htm
*/
#ifndef _ALIYUN_MATT_H
#define _ALIYUN_MATT_H
#include "Arduino.h"
#include <PubSubClient.h>
/**
* Connect to Alibaba Cloud MQTT server. In connection process, it will try several times for
* possible network failure. For authentication issue, it will return false at once.
*
* @param mqttClient: Caller provide a valid PubSubClient object (initialized with network client).
* @param productKey: Product Key, get from Alibaba Cloud Link Platform.
* @param deviceName: Device Name, get from Alibaba Cloud Link Platform.
* @param deviceSecret: Device Secret, get from Alibaba Cloud Link Platform.
*
* @param region: Optional region, use "cn-shanghai" as default. It can be "us-west-1",
* "ap-southeast-1" etc. Refer to Alibaba Cloud Link Platform.
*
*
* @return true if connect succeed, otherwise false.
*/
extern "C" bool connect_aliyun_mqtt(
PubSubClient &mqttClient,
const char *productKey,
const char *deviceName,
const char *deviceSecret,
const char *region = "cn-shanghai");
/**
* Two new added APIs are designed for devices with limited resource like Arduino UNO.
* Since it is hard to calculate HMAC256 on such devices, the calculation can be done externally.
*
* These two APIs should be used together with external HMAC256 calculation tools, e.g.
* http://tool.oschina.net/encrypt?type=2
* They can be used together to replace connectAliyunMQTT on resource-limited devices.
*/
/**
* This API should be called in setup() phase to init all MQTT parameters. Since HMAC256
* calculation is executed extenrally, a fixed timestamp string should be provided, such
* as "23668" etc. The same timestamp string is also used to calculate HMAC256 result.
*
* Other params are similar to them in connectAliyunMQTT.
*/
extern "C" void mqtt_prepare(
const char *timestamp,
const char *productKey,
const char *deviceName,
const char *deviceSecret,
const char *region = "cn-shanghai");
/**
* Use tools here to calculate HMAC256: http://tool.oschina.net/encrypt?type=2
* The calculated result should be defined as constants and passed when call this function.
*/
extern "C" bool connect_aliyun_mqtt_With_password(PubSubClient &mqttClient, const char *password);
#endif