ESP8266 for arduino 如何连接到阿里云物联网平台(AliYun)

前言

最近物联网越来越火,阿里也出了自己的物联网平台,对于物联网工程师来说,简直是天大的福音。阿里云物联网平台支持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 
#include 
#include 

#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] = '';
    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())//mqtt���
    {
        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()
{
    char param[512];
    char jsonBuf[1024];

    //sprintf(param, "{"MotionAlarmState":%d}", digitalRead(13));
    sprintf(param, "{"CurrentHumidity":%d,"CurrentTemperature":12,"GeoLocation":{"CoordinateSystem":2,"Latitude":2,"Longitude":123,"Altitude":1}}", 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);
    /* 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);
}

 

2.修改PubSubClient.h

3.arduino安装加密库

4.编译下载,重新上电

查看结果


下载地址

https://gitee.com/schuck/ESP8266_AliYun

百度云下载链接:
链接: https://pan.baidu.com/s/1VlyXOXHwzblU1vIphhuYoA 提取码:

隐藏内容,您需要满足以下条件方可查看
End

转载自网络·文章原作者:sunny.Bit

人已赞赏
动态

MQTT实时数据在线更新

2020-3-15 0:56:27

Arduino动态

使用ESP32创建Web服务器

2020-5-27 11:11:08

2 条回复 A文章作者 M管理员
  1. 我是季付会员也看不了?

    • 现在可以查看了,之前权限没勾上。

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索