NodeMCU accesses Alibaba Cloud IoT platform demo

0. Environment and preparatory work

Arduino IDE + NodeMCU + PIR module + Firefox

The NodeMCU development environment has been configured on the Arduino IDE.

Connect the signal pin of the PIR module to D7 of NodeMCU.

1. Log in to the landing platform of the Internet of Things platform

The account can be TaoBao.

2. Create a product

3. Define functions for the product

The defining function here is mainly product parameters. Used to pass parameters on the device and network platform. There are a variety of parameters by default, and there are preset parameter types

4. Create a device

In the Alibaba Cloud IoT platform, the same product can have multiple devices. Create a new device here, the name is Light_1.

5. Write NodeMCU code

NodeMCU_Aliyun_PirLight.ino

#include <ESP8266WiFi.h>
/* 依赖 PubSubClient 2.4.0 */
#include <PubSubClient.h>
/* 依赖 ArduinoJson 5.13.4 */
#include <ArduinoJson.h>

#define SENSOR_PIN    13

/* 修改1 ------------------------------------------ */
/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID         "Nokia7"
#define WIFI_PASSWD       "testroom8"
/* 修改1 end--------------------------------------- */

/* 修改2 ------------------------------------------ */
/* 设备证书信息*/
#define PRODUCT_KEY       "a1LlrbbOE7d"
#define DEVICE_NAME       "Light_1"
#define DEVICE_SECRET     "123456"
#define REGION_ID         "cn-shanghai"
/* 修改2 end--------------------------------------- */

/* 线上环境域名和端口号,不需要改 */
#define MQTT_SERVER       PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
#define MQTT_PORT         1883
#define MQTT_USRNAME      DEVICE_NAME "&" PRODUCT_KEY

/* 修改3 ------------------------------------------ */
#define CLIENT_ID    "esp8266|securemode=3,signmethod=hmacsha1,timestamp=1234567890|"
// 请使用以上说明中的加密工具或参见MQTT-TCP连接通信文档加密生成password。
// 加密明文是参数和对应的值(clientIdesp8266deviceName${deviceName}productKey${productKey}timestamp1234567890)按字典顺序拼接
// 密钥是设备的DeviceSecret
#define MQTT_PASSWD       "888DB29EED6A21E077AFDE6B25887D5FF592CE08"
/* 修改3 end--------------------------------------- */

#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];

/* 修改4 ------------------------------------------ */
    sprintf(param, "{\"AlarmState\":%d}", digitalRead(13));
/* 修改4 end--------------------------------------- */

    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);
}


void setup() 
{

    pinMode(SENSOR_PIN,  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();
    if (digitalRead(SENSOR_PIN) == HIGH){
    Serial.println("Motion detected!");
    delay(2000);
      }
    else {
    Serial.println("Motion absent!");
    delay(2000);
  }

}

5.1 Modification 1

The first modification is the SSID and password of the WIFI.

5.2 Modification 2

The second modification is the device certificate information.

5.3 Amendment 3

The third modification is the ID and password of MQTT.

The password of MQTT_PASSWD needs to be generated by yourself, this link can download this password generator gadget.

https://files.alicdn.com/tpsservice/471c155376d6a88a29c9ad66784e94f0.zip?spm=a2c4g.11186623.2.17.61f6619bQ80OV1&file=471c155376d6a88a29c9ad66784e94f0.zip

After the software is decompressed, open sign.html with a browser. Enter relevant information to generate MQTT_PASSWD.

 

 

6. Modify the PubSubClient.h file (cannot connect to Mqtt server without modification)

The path in my computer is: D:\arduino-1.8.9\portable\sketchbook\libraries\PubSubClient\src\PubSubClient.h

Amend lines 22 -26 to:

// MQTT_MAX_PACKET_SIZE : Maximum packet size
#define MQTT_MAX_PACKET_SIZE 1024

// MQTT_KEEPALIVE : keepAlive interval in Seconds
#define MQTT_KEEPALIVE 60

 

7. Test

7.1 Compile and download, the serial port monitor of Arduino IDE, you can see the debugging information of NodeMCU.

7.2 Alibaba Cloud IOT platform

You can view real-time data through Device -> Running Status.

You can also go to monitor operation and maintenance -> online debugging. Observe the upload information of NodeMCU.

During online debugging, you can also send information to NodeMCU through the interface on the left.

 

Summary: This article introduces the general steps of using NodeMCU to access the Alibaba Cloud IoT platform. You can see that the interface of the platform is relatively friendly, but Alibaba Cloud's IoT platform requires the device to provide an ID and password when accessing the platform. The further work of this project is to use the development services of Alibaba Cloud IoT platform to generate APP. The difference between this article and reference [1] is that I have added pictures and descriptions to the areas of my personal attention.

 

Reference: 1. NodeMCU (ESP8266) is connected to the IoT platform

Guess you like

Origin blog.csdn.net/qq_27158179/article/details/90549494