ESP8266 connects to Alibaba Cloud--MQTT protocol

ESP8266 connects to Alibaba Cloud – MQTT protocol

  MQTT (Message Queuing Telemetry Transport, Message Queuing Telemetry Transport Protocol) is a lightweight communication protocol based on the publish/subscribe (Publish/Subscribe) model, which is built on the TCP/IP protocol and released by IBM in 1999 . The biggest advantage of MQTT is that it can provide real-time and reliable message services for remote devices with very little code and limited bandwidth. As a low-overhead, low-bandwidth instant messaging protocol, MQTT has a wide range of applications in the Internet of Things, small devices, and mobile applications. MQTT is an application layer protocol. The latest version is the MQTT v5.0 standard. The connection to the Alibaba Cloud IoT platform is mainly based on the MQTT standard protocol version 3.1.

1. Register an Alibaba Cloud account and log in to the cloud platform

insert image description here
  1. Search for the IoT platform and log in to the IoT platform.
insert image description here
  2. Enter the IoT console
insert image description here
  3. Select a public instance4
insert image description here
  . Create a product
insert image description here
insert image description here
  5. Add a product
insert image description here
insert image description here
insert image description here  Add a device successfully:
insert image description here
  each device has its own triple, click the device name to view the device three groups: The
  device triple is very Important, you will need to log in to the Alibaba Cloud platform later.insert image description here

  1. Add product features
    insert image description hereinsert image description here

2. Create a project and connect to Alibaba Cloud

  2.1 Write the ESP8266 driver and connect to Alibaba Cloud.

//TCP+STA模式,连接服务器
#define WIFI_NAME     "WBYQ"  //wifi名
#define WIFI_PASSWORD "asdfghjkl23"//WiFi密码
#define SERVER_IP      "a1knXG89uwh.iot-as-mqtt.cn-shanghai.aliyuncs.com"//服务器ip
#define SERVER_PORT   1883//端口号
while(1)
{
    
    
    stat=Esp8266_STA_TCPclinet_Init((u8 *)WIFI_NAME,(u8 *)WIFI_PASSWORD,(u8 *)SERVER_IP,SERVER_PORT);
	if(stat==0)break;
	Delay_Ms(500);
	printf("stat=%d\r\n",stat);
}
printf("服务器连接成功\r\n");

  For server ip and port number settings, please refer to Alibaba Cloud Online Documentation
insert image description here
insert image description here
  Server IP Format:

${
    
    YourProductKey}.iot-as-mqtt.${
    
    YourRegionId}.aliyuncs.com:1883
${
    
    YourProductKey}为设备的ProductKey,上面讲到设备三元组已提到过。
${
    
    YourRegionId} 是区域代码,我这是属于华东2,区域代码:cn-shanghai
综上,服务器ip为 ”a1knXG89uwh.iot-as-mqtt.cn-shanghai.aliyuncs.com”

  2.2 MQTT continuous server
MQTT connection to Alibaba Cloud requires three parameters: client id, user name, and password.
For filling in these three parameters, please refer to Alibaba Cloud Documentation Tool.

#define ClientID "STM32|securemode=3,signmethod=hmacsha1|"
#define Username "STM32&a17b5WKUY0S"
#define Password "ebff9579ed3e610228da8c035afc9636954c43bd"//密文
	while(1)
	{
    
    
		MQTT_Init();
		stat=MQTT_Connect(ClientID,Username,Password);
		if(stat==0)break;
		Delay_Ms(500);
		printf("正在连接....\r\n");
	}
	printf("阿里云连接成功\r\n");

insert image description here
  2.3 Client ID
  According to Alibaba Cloud documentation, clientId can be customized. Generally, we directly use DeviceName in the triplet instead; timestamp can be left blank. In summary, mqttClientId: DS18B20|securemode=3,signmethod=hmacsha1|

  2.4 Username
  The deviceName in the username is replaced by the DeviceName in the triplet; productKey is replaced by the productKey in the triplet. In summary, mqttUsername: DS18B20&a1knXG89uwh

   2.5 Password
  Password Generation We can directly use the password tool password tool provided by Alibaba Cloud
insert image description here

3. Subscribe and publish messages

  3.1 Subscription message
  Uploading the data collected by the hardware to the cloud is called publishing a message; the cloud sending the data to the development board is called subscription.
  Open the product, view the product details, and you can see that there are subscription and publishing interfaces.
insert image description here

#define SET_TOPIC  "/sys/a1knXG89uwh/DS18B20/thing/service/property/set"//订阅
#define POST_TOPIC "/sys/a1knXG89uwh/DS18B20/thing/event/property/post"//发布
stat=MQTT_SubscribeTopic(SET_TOPIC,0,1);
if(stat)printf("订阅失败\r\n");
else printf("订阅成功\r\n");

  3.2
  The reporting format of the release message can be debugged online through the Alibaba Cloud platform, and data is uploaded according to the data format released by the cloud platform.
insert image description here
  Implement data reporting in this way

if(cnt>=1000)
{
    
    
    cnt=0;
    temp=DS18B20_GetTemp()*0.0625;
    sprintf(mqtt_message,"{\"method\":\"thing.event.property.post\",\"id\":\"0000000001\",\"params\":{\"RoomTemp\":%.2f},\"version\":\"1.0.0\"}",temp);//温度
    MQTT_PublishData(POST_TOPIC,mqtt_message,0);
}

4. Send heartbeat packets

  MQTT is a long-term connection. In order to keep the device online, it needs to send a heartbeat packet to the server at a fixed time. If it is not sent after the time expires, it will be forced to go offline.

if(time>=5000)
{
    
    
    time=0;
    MQTT_SentHeart();//发送心跳包
}

5. Main function

while(1)
	{
    
    
        stat=Esp8266_STA_TCPclinet_Init((u8 *)WIFI_NAME,(u8 *)WIFI_PASSWORD,(u8 *)SERVER_IP,SERVER_PORT);
		if(stat==0)break;
		Delay_Ms(500);
		printf("stat=%d\r\n",stat);
	}
	printf("服务器连接成功\r\n");
	while(1)
	{
    
    
		MQTT_Init();
		stat=MQTT_Connect(ClientID,Username,Password);
		if(stat==0)break;
		Delay_Ms(500);
		printf("正在连接....\r\n");
	}
	printf("阿里云连接成功\r\n");
	stat=MQTT_SubscribeTopic(SET_TOPIC,0,1);
	if(stat)printf("订阅失败\r\n");
	else printf("订阅成功\r\n");
	while(1)
	{
    
    
		if(usart3_flag)
		{
    
    
			usart3_cnt=0;
			usart3_flag=0;
		}
		Delay_Ms(1);
		time++;
		cnt++;
		if(time>=5000)
		{
    
    
			time=0;
			MQTT_SentHeart();//发送心跳包
		}
		if(cnt>=1000)
		{
    
    
			cnt=0;
			temp=DS18B20_GetTemp()*0.0625;
            sprintf(mqtt_message,"{\"method\":\"thing.event.property.post\",\"id\":\"0000000001\",\" params\":{\"RoomTemp\":%.2f},\"version\":\"1.0.0\"}",temp);//温度
			MQTT_PublishData(POST_TOPIC,mqtt_message,0);
		}
	}

6. Alibaba Cloud Web Design

  Alibaba Cloud Server provides web and mobile interface development. We introduce the basic usage of web interface design.
insert image description here
  6.1 Create a new web application insert image description here
insert image description here
  6.2 Associated products
insert image description here
  6.3 Create a new application
insert image description here
  6.4 Design the interface
insert image description here
  6.5. Configure the data source
insert image description here
  6.6. Save and publish
insert image description here
  6.7. Download the program, connect to Alibaba Cloud, and preview the web interface.
insert image description here

Summarize

  MQTT is a publish/subscribe mode messaging protocol for client-server architecture. Its design idea is light, open, simple, and standardized, so it is easy to implement. It consumes less resources, and there are only 14 packets in the MQTT3.1 standard protocol. Each message is divided into three parts: fixed header, variable header and payload.
insert image description here
  The 14 messages are as follows:
insert image description here
  For a detailed explanation of each MQTT message, see the MQTT3.1 protocol.
  Example project: https://download.csdn.net/download/weixin_44453694/16632625

Guess you like

Origin blog.csdn.net/weixin_44453694/article/details/115618940