最近工作需要,接触了一下ESP32,这次记录下自己的学习过程
内容和esp8266接入阿里云差不多。可以参考->ESP8266接入阿里云
还是复制三元组(三元组别复制我的哈),复制我的代码就行了。
说明:任何ESP32系列都可以。
就更改这3样就好了。
下面附带详细代码
main.h
#include <WiFi.h>
#include <Wire.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "aliyun_mqtt.h"
#define SENSOR_PIN 10
//以下信息需要自己修改
#define WIFI_SSID "AA"//替换自己的WIFI
#define WIFI_PASSWD "22223333"//替换自己的WIFI
#define PRODUCT_KEY "a1rpMDX42C5" //替换自己的PRODUCT_KEY
#define DEVICE_NAME "wendu" //替换自己的DEVICE_NAME
#define DEVICE_SECRET "4b2e2205a07f4184f35ee5f959c184fe"//替换自己的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] = '\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, "{\"MotionAlarmState\":%d}", digitalRead(13));
sprintf(param, "{\"id\": 123,\"params\": {\"version\": \"%s\"}}", DEV_VERSION);
// sprintf(jsonBuf, ALINK_BODY_FORMAT, ALINK_METHOD_PROP_POST, param);
Serial.println(param);
mqttClient.publish(ALINK_TOPIC_DEV_INFO, param);
}
void mqtt_check_connect()
{
while (!mqttClient.connected())//
{
while (connect_aliyun_mqtt(mqttClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET))
{
Serial.println("MQTT connect succeed!");
//client.subscribe(ALINK_TOPIC_PROP_POSTRSP);
mqttClient.subscribe(ALINK_TOPIC_PROP_SET);
Serial.println("subscribe done");
mqtt_version_post();
}
}
}
void mqtt_interval_post()
{
static int i=0;
char param[512];
char jsonBuf[1024];
//sprintf(param, "{\"MotionAlarmState\":%d}", digitalRead(13));
sprintf(param, "{\"CurrentHumidity\":%d}", i);
i++;
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);
/* initialize serial for debugging */
Serial.begin(115200);
Serial.println("Demo Start");
init_wifi(WIFI_SSID, WIFI_PASSWD);
mqttClient.setCallback(mqtt_callback);
}
// the loop function runs over and over again forever
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);
}
aliyunmqtt.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());
}
aliyunmqtt.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
将这些加进去就行了
文章来源:https://www.toymoban.com/news/detail-512107.html
可以看到是ok的,100成功!文章来源地址https://www.toymoban.com/news/detail-512107.html
到了这里,关于ESP32-S2使用Arduino连接阿里云(图文教程,100%成功)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!