ESP32-C3 uploads temperature and humidity to Ali Cloud Internet of Things platform through MQTT protocol

Recently, I wanted to realize that the WeChat applet controls the light switch through OneNet platform, but I didn't expect that the code of the WeChat applet has written the interface well. I found that the application management that onenet wants to issue commands is very expensive. I uphold the spirit of never giving up and resolutely converted to Aliyun platform.

1. Ali Yun Platform

1.1 Open Public Instances

Money-free, generally enough for us students.

1.2 Create a product

Click on the public instance to go in, find the product in Device Management, and click Create Product to create it. Enter the name of the product (you decide the name), then select a custom category, the other defaults will be fine.

1.3 Create Devices

Click on the device on the left to add it. The product chooses which one we just created. The name of the device is up to you!

1.4 Get related device data

After adding the device successfully, click View on the right to get the device details here, there are two pieces of data we need to note down, which are the DeviceSecret triple data and the MQTT connection parameters.


1.5 Creation Model Data

Here's the data we uploaded, and on the right side of the same page where we worked in the last step, there's a physical model data, and by then our data will be displayed here. But creating this object model data is actually done over the functional definition of the product.

Choosing the custom function, I have to say that the Ali cloud here is much more useful than Onenet, where the identifiers are consistent with the data transferred later. The data type is up to you, and I'm here to show it decimal, so float now. Then choose Publish Online as we see in the Device Page's physical model data!


2. Equipment Development

Device I use esp32-c3, sensor dht11, code development environment is Arduino IDE, specific working environment configuration can refer to the development environment in this article https://blog.csdn.net/weixin_44107116/article/details/122263799?spm=1001.2014.3001.5502.

2.1 Header File

#include <WiFi.h>
#include "DHT.h"
#include "PubSubClient.h"

2.2 dht11 sensor

#define DHTPIN 7 //Data Interface 
#define DHTTYPE DHT11   // DHT 11
DHT dht(DHTPIN, DHTTYPE);

2.3 Ali Cloud Data Deployment

Swap in the triple data and MQTT connection parameters we got in Ali Cloud

/* Triple information for devices*/
#define PRODUCT_KEY       "gtbww9C9Wsj"     
#Define DEVICE_ NAME "dht11" //device name
#define DEVICE_SECRET     "54aa54bd68a34c684f15931c643a664e"
#Define REGION_ ID "cn-shanghai" //See where you choose

/* Online environment domain name and port number, no change required */
#define MQTT_SERVER    PRODUCT_KEY".iot-as-mqtt."REGION_ID".aliyuncs.com"
#define MQTT_PORT         1883
#define MQTT_USRNAME      DEVICE_NAME"&"PRODUCT_KEY

#define CLIENT_ID         "gtbww9C9Wsj.dht11|securemode=2,signmethod=hmacsha256,timestamp=2524608000000|"
#define MQTT_PASSWD       "2e31a42e357c59e6ca19f6f2b31705c0baddbad8ee4d46118dfecbbe517e70b8"

2.4 MQTT Connection Server

//mqtt connection
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);

          }
        
    }
}

2.5 Send data to Aliyun

Macro Definition Subscription Theme

#Define ALINK_ BODY_ FORMAT'{\"id":"dht11", \"version":\"1.0", \"method":"thing.event.property.post", \"params":%s}"//dht11 is the device name, so you can change it to yours
#define ALINK_TOPIC_PROP_POST     "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
//send data
void mqttIntervalPost()
{
    char param[32];
    char jsonBuf[128];
    
    soil_data = dht.readHumidity();   
    sprintf(param, "{\"shidu\":%2f}", soil_data);  //Replace with the corresponding identifier
    sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
    
    Serial.println(jsonBuf);
    boolean b = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
    if(b){
      Serial.println("publish Humidity success"); 
    }else{
      Serial.println("publish Humidity fail"); 
    }

    tep =dht.readTemperature();
    sprintf(param, "{\"wendu\":%2f}",tep); //Replace with the corresponding identifier
    sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
    Serial.println(jsonBuf);
    boolean c = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);

    if(c){
      Serial.println("publish Temperature success"); 
    }else{
      Serial.println("publish Temperature fail"); 
    }
    
}
void setup() 
{
  
    Serial.begin(115200);
    dht.begin();
    wifiInit();
    client.setServer(MQTT_SERVER, MQTT_PORT);   /* Connect to MQTT Server */
}

void loop()
{
    if (millis() - lastMs >= 5000)
    {
        lastMs = millis();
        mqttCheckConnect(); 
        /* Report */
        mqttIntervalPost();
    }
    client.loop();
    delay(2000);
}

2.6 Complete Code

#include <WiFi.h>
#include "DHT.h"
#include "PubSubClient.h"


#define DHTPIN 7     
#define DHTTYPE DHT11   // DHT 11
DHT dht(DHTPIN, DHTTYPE);

/* Connect WIFI SSID and Password */
#define WIFI_SSID         "3671"
#define WIFI_PASSWD       "05210835"

/* Triple information for devices*/
#define PRODUCT_KEY       "gtbww9C9Wsj"
#define DEVICE_NAME       "dht11"
#define DEVICE_SECRET     "54aa54bd68a34c684f15931c643a664e"
#define REGION_ID         "cn-shanghai"

/* Online environment domain name and port number, no change required */
#define MQTT_SERVER       PRODUCT_KEY".iot-as-mqtt."REGION_ID".aliyuncs.com"
#define MQTT_PORT         1883
#define MQTT_USRNAME      DEVICE_NAME"&"PRODUCT_KEY

#define CLIENT_ID         "gtbww9C9Wsj.dht11|securemode=2,signmethod=hmacsha256,timestamp=2524608000000|"
#define MQTT_PASSWD       "2e31a42e357c59e6ca19f6f2b31705c0baddbad8ee4d46118dfecbbe517e70b8"


#define ALINK_BODY_FORMAT         "{\"id\":\"dht11\",\"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);

float soil_data ;  
float tep;  

//Connect wifi
void wifiInit()
{
    WiFi.begin(WIFI_SSID, WIFI_PASSWD);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.println("WiFi not Connect");
    }
    
}

//mqtt connection
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];
    
    soil_data = dht.readHumidity();   
    sprintf(param, "{\"shidu\":%2f}", soil_data);
    sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
    
    Serial.println(jsonBuf);
    boolean b = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
    if(b){
      Serial.println("publish Humidity success"); 
    }else{
      Serial.println("publish Humidity fail"); 
    }

    tep =dht.readTemperature();
    sprintf(param, "{\"wendu\":%2f}",tep);
    sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
    Serial.println(jsonBuf);
    boolean c = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);

    if(c){
      Serial.println("publish Temperature success"); 
    }else{
      Serial.println("publish Temperature fail"); 
    }
   
}

void setup() 
{
    Serial.begin(115200);
    dht.begin();
    wifiInit();
    client.setServer(MQTT_SERVER, MQTT_PORT);   /* Connect to MQTT Server */
}

void loop()
{
    if (millis() - lastMs >= 5000)
    {
        lastMs = millis();
        mqttCheckConnect(); 
        /* Report */
        mqttIntervalPost();
    }
    client.loop();
    delay(2000);
}

3. Problems Meet

The code did not make an error and successfully connected to wifi, but even if the connection to the mqtt server could not be made, the return error code was 2, which was later found on the web: the CONNECT instruction needs to contain KeepAlive. The heart rate preservation time ranges from 30 seconds to 1200 seconds. If the heartbeat time is not within this range, the Internet of Things platform will refuse to connect. A value of more than 300 seconds is recommended. If the network is unstable, set the heartbeat time higher.

Just modify the PubSubClient later. MQTT_defined in H file MAX_ PACKET_ SIZE value, preferably greater than 1024, MQTT_KEEPALIVE is greater than 60; I Modify MQTT_KEEPALIVE (the value set before the code is 5)

IV. Effect Charts


Happy New Year!!!!

Keywords: IoT Alibaba Cloud

Added by keyurshah on Mon, 31 Jan 2022 04:08:25 +0200