Smart trash can designed based on STM32+Huawei Cloud IOT

1. Project introduction

In crowded places such as commercial streets, snack streets, and scenic spots, timely cleaning of trash cans is crucial to providing a good visitor experience. However, the traditional method of cleaning trash cans is usually carried out on a scheduled or periodic basis and cannot respond in time according to the actual situation, resulting in overflowing trash cans, affecting environmental sanitation, and causing inconvenience and dissatisfaction to tourists.

In order to solve this problem, this project designed a smart trash can management system based on the STM32F103ZET6 main control chip and Huawei Cloud IoT platform. The system is connected to the Huawei Cloud IoT platform through the NBIOT-BC26 module, enabling real-time collection and uploading of trash can data.

Locally, trash cans collect data through a variety of sensors. Use the DHT11 module to monitor the ambient temperature and humidity in real time to understand the status of the environment where the trash can is located. The GPS module produced by Zhongke Microelectronics is used to output GPS data through the serial port to realize the positioning function of the trash can. The trash can mouth is also equipped with an infrared sensor to detect whether the trash can is full.

Through the NBIOT-BC26 module, the collected data is uploaded to the Huawei Cloud IoT platform in real time. In the cleaning staff management center, a large data screen was developed using Qt and running under Windows system. The large data screen displays detailed information about the trash cans in the area, including ambient temperature, humidity, GPS positioning and the overflow status of the trash cans.

When the trash can is full, the host will send a text message in real time to notify the cleaning staff to clean it, and provide the location information of the trash can so that the cleaning staff can respond quickly and perform cleaning operations.

Through this intelligent trash can management system, the cleaning of trash cans can be scheduled in time according to the actual situation, which improves the efficiency of trash can use, improves environmental sanitation, and enhances tourists' experience. At the same time, cleaning staff can manage trash cans more efficiently, improve work efficiency and reduce resource waste. The entire system is designed to provide an intelligent and efficient trash can management solution, bringing convenience and improvement to environmental sanitation management in public places.

image-20230728140353572

image-20230728140410093

image-20230728141958810

2. Summary of design ideas

2.1 Hardware selection

【1】Main control chip: STM32F103ZET6

  • The STM32F103 series is a low-power, high-performance 32-bit ARM Cortex-M3 microcontroller series launched by STMicroelectronics. STM32F103ZET6 was chosen as the main control chip because it has high computing power and rich peripheral interfaces, which can meet the needs of the project.

【2】Communication module: NBIOT-BC26

  • NBIOT-BC26 is a narrowband Internet of Things (NB-IoT) communication module that supports low-power consumption, wide coverage, and long-distance IoT communication. It can upload the data collected from the trash can to the cloud platform through the NB-IoT network to achieve real-time monitoring and remote management.

【3】Sensor module:

  • DHT11 module: used to collect ambient temperature and humidity data. DHT11 is a low-cost, digital temperature and humidity sensor with a simple interface and good performance, which is suitable for the temperature and humidity monitoring needs of this project.
  • GPS module: used to realize the positioning function of the trash can. Select the GPS module produced by Zhongke Microelectronics and output the GPS data through the serial port to accurately obtain the location information of the trash can.
  • Infrared sensor: used to detect whether the trash can is full. The infrared sensor can determine whether there is garbage in the trash can through the reflection of infrared rays, thereby determining the overflow status of the trash can.

【5】Data large screen: developed using Qt and running under Windows system. The large data screen displays the detailed information of the trash bin through a graphical interface, including ambient temperature, humidity, GPS positioning and the overflow status of the trash bin.

The hardware selection of the project includes main control chip, communication module, sensor module, infrared sensor and large data screen. These hardware components cooperate with each other to realize the functions of the intelligent trash can management system, including data collection, communication transmission, positioning functions and information display.

2.2 Hardware design

[1] Main control chip selection:
As the core of the entire system, STM32F103ZET6 was selected as the main control chip. The chip has high computing power and rich peripheral interfaces, which can meet the needs of the project. The main control chip is responsible for communication and data processing with each hardware module, and at the same time controls the data transmission of the communication module.

[2] Communication module selection:
In order to realize real-time collection and upload of trash can data, the NBIOT-BC26 communication module was selected. NBIOT-BC26 supports narrowband IoT communication and features low power consumption, wide coverage, and long-distance transmission. It can upload collected data to the Huawei Cloud IoT platform through the NB-IoT network.

【3】Sensor module selection:

  • The DHT11 module is used to collect ambient temperature and humidity data. DHT11 is a low-cost, digital temperature and humidity sensor that outputs temperature and humidity values ​​through digital signals. It has a simple interface and good performance, and is suitable for the temperature and humidity monitoring needs of this project.
  • The GPS module is used to realize the positioning function of the trash can. Select the GPS module produced by Zhongke Microelectronics and output the GPS data through the serial port to accurately obtain the location information of the trash can.
  • Infrared sensor design:
    In order to detect whether the trash can is full, an infrared sensor is used. The infrared sensor can determine whether there is garbage in the trash can through the reflection of infrared rays, thereby determining the overflow status of the trash can. The infrared sensor is connected to the main control chip, receives the sensor signal through the digital input port, and performs processing and judgment.

【4】Data large screen design:
Data large screen is developed using Qt and runs under Windows system. The detailed information of the trash can is displayed through the graphical interface, including ambient temperature, humidity, GPS positioning and the overflow status of the trash can. The main control chip transmits data in real time through the communication interface with the data screen, and the data screen displays the data according to the received data.

The entire hardware design idea is to connect each hardware module with the main control chip, and realize data collection, communication transmission, positioning function and information display through the control and data processing of the main control chip. Through reasonable selection of hardware components and appropriate connection and interface design, the functions of the intelligent trash can management system are realized.

2.3 Software design

【1】System architecture design:
The first step in software design is to determine the overall architecture of the system. Based on project requirements, a layered architecture design can be adopted to divide the system into application layer, business logic layer and driver layer. The application layer is responsible for interacting with users, the business logic layer handles specific business logic, and the driver layer communicates and controls the hardware modules.

【2】Hardware driver design:
For each hardware module, a corresponding driver needs to be written. The main control chip communicates with the communication module, sensor module and infrared sensor, and interacts with them through serial port, I2C, SPI and other interfaces. The driver of each hardware module should include functions such as initialization, data acquisition and control.

【3】Data processing and logic control:
The main control chip is responsible for receiving data from each hardware module and performing processing and logic control. For example, after reading the temperature and humidity data from the DHT11 sensor, the data can be verified and converted, and then based on the set threshold, it can be determined whether drying operation is required. At the same time, the main control chip is also responsible for controlling the infrared sensor to detect the overflow status of the trash can.

[4] Communication and data upload:
Through the NBIOT-BC26 communication module, the collected data is uploaded to the Huawei Cloud IoT platform through the NB-IoT network. The main control chip communicates with the communication module, packages the data that needs to be uploaded into the corresponding format, and sends it to the communication module through the serial port and other interfaces to implement data upload.

【5】User interface design:
The software also needs to design a user interface so that users can intuitively view the status and data information of the trash can. You can use tools such as Qt for interface design to display information such as ambient temperature, humidity, GPS positioning, and the overflow status of the trash can. The user interface communicates with the main control chip, receives data and displays it.

The entire software design idea is based on system architecture design, and the functions of the intelligent trash can management system are realized through the development of modules such as hardware drivers, data processing and logic control, communication and data upload, and user interface design. Software design needs to be combined with hardware design to ensure coordinated operation of data collection, processing, transmission and display.

2.4 System interaction process

【1】The user opens the application of the smart trash can management system.

【2】System initialization:

  • The system performs hardware initialization, including initialization of the main control chip, communication module, sensor module and infrared sensor.
  • Ensure that the communication module is connected to the NB-IoT network and establishes a communication connection with the Huawei Cloud IoT platform.

【3】Environmental monitoring:

  • The system begins to monitor the ambient temperature and humidity and obtains the location information of the trash can. The main control chip obtains temperature and humidity data through the DHT11 sensor and obtains the location information of the trash can through the GPS module.

【4】Data processing and logic control:

  • The main control chip processes and logically controls the collected data. It can determine whether the trash can needs to be cleaned based on temperature and humidity data, and detect overflowing status of the trash can through infrared sensors.

【5】Data upload:

  • The main control chip uploads the processed data to the Huawei Cloud IoT platform through the communication module. Data can include information such as ambient temperature, humidity, GPS location and overflow status of trash cans.
  • The uploaded data can be packaged in JSON and other formats and transmitted to the Huawei Cloud IoT platform through the NB-IoT network.

【6】Data display:

  • The user interface receives the data transmitted from the main control chip and displays it. Users can view information such as ambient temperature, humidity, GPS positioning, and the overflow status of the trash can on the interface.
  • Data display can be presented in the form of charts, text, images, etc., so that users can intuitively understand the system status and data information.

The interaction process of the entire system involves data collection of the hardware module, data processing and logic control of the main control chip, data upload of the communication module, and data display and user interaction of the user interface. Through these steps, users can easily monitor and manage the status and data information of the smart trash can.

3. Deploy Huawei Cloud IoT Platform

Huawei Cloud official website: https://www.huaweicloud.com/

Open the official website and search for Internet of Things to find it quickly 设备接入IoTDA.

image-20221204193824815

3.1 Introduction to IoT platform

Huawei Cloud Internet of Things Platform (IoT device access cloud service) provides access and management capabilities for massive devices, connects physical devices to the cloud, supports device data collection on the cloud and the cloud issues commands to devices for remote control, and cooperates with Huawei Cloud Other products help us quickly build IoT solutions.

Using the IoT platform to build a complete IoT solution mainly includes 3 parts: IoT platform, business applications and equipment.

As the middle layer that connects business applications and devices, the IoT platform shields various complex device interfaces and enables quick access to devices. It also provides powerful open capabilities to support industry users in building various IoT solutions.

Devices can access the IoT platform through fixed network, 2G/3G/4G/5G, NB-IoT, Wifi and other networks, and use LWM2M/CoAP, MQTT, HTTPS protocols to report business data to the platform. The platform can also Send control commands to the device.

Business applications implement business scenarios such as device data collection, command issuance, and device management by calling the API provided by the IoT platform.

img

3.2 Activate IoT services

Address: https://www.huaweicloud.com/product/iothub.html

image-20221204194233414

By default, you will be prompted to activate the standard version when you enter. There will be no basic version after January 1, 2023.

image-20230313171311582

image-20230313171325183

After activation, click 总览to view access information. Our current equipment is going to use the MQTT protocol to connect to the Huawei Cloud platform. Here you can see the address and port number of the MQTT protocol and other information.

image-20230321154943337

Summarize:

端口号:   MQTT (1883)| MQTTS (8883)   
接入地址: 7445c6bcd3.st1.iotda-app.cn-north-4.myhuaweicloud.com

Get IP address information based on domain name address:

Microsoft Windows [版本 10.0.19044.2728]
(c) Microsoft Corporation。保留所有权利。

C:\Users\11266>ping 7445c6bcd3.st1.iotda-device.cn-north-4.myhuaweicloud.com

正在 Ping 7445c6bcd3.st1.iotda-device.cn-north-4.myhuaweicloud.com [117.78.5.125] 具有 32 字节的数据:
来自 117.78.5.125 的回复: 字节=32 时间=42ms TTL=30
来自 117.78.5.125 的回复: 字节=32 时间=35ms TTL=30
来自 117.78.5.125 的回复: 字节=32 时间=36ms TTL=30
来自 117.78.5.125 的回复: 字节=32 时间=36ms TTL=30

117.78.5.125 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 35ms,最长 = 42ms,平均 = 37ms

C:\Users\11266>

image-20230321161044723

There are two MQTT protocol access port numbers. 1883 is a non-encrypted port and 8883 is a certificate encryption port. The microcontroller cannot load the certificate, so it is more appropriate to use port 1883. The next ESP8266 uses port 1883 to connect to the Huawei Cloud IoT platform.

3.3 Create products

(1) Create products

Click on the product page, then click Create Product in the upper left corner.

image-20230313171503547

(2) Fill in product information

Fill in the form based on your product name.

image-20230728135430775

(3) Product creation is successful

image-20230728135444283

(4) Add custom model

After the product is created, click to enter the product details page and scroll to the bottom to see the model definition.

Click on Custom Model first.

image-20230313171815860

Create another service ID.

image-20230321155733514

Then click Add attribute.

image-20230321155756735

3.4 Add device

The product is an abstract model belonging to the upper layer, and then the actual equipment is added under the product model. The added device eventually needs to be associated with the real device to complete data interaction.

(1) Register device

image-20230313173158883

(2) Fill in according to your own equipment

image-20230728135539727

(3) Save device information

After creation, click Save and Close to get the created device key information. This information is needed when generating MQTT triples later.

image-20230728135557050

(4) Device creation completed

image-20230728135620427

3.5 MQTT protocol topic subscription and publishing

(1) Introduction to MQTT protocol

The current equipment uses the MQTT protocol to communicate with the Huawei Cloud Platform.

MQTT is an IoT transport protocol that is designed for lightweight publish/subscribe message transmission to provide reliable network services for IoT devices in low-bandwidth and unstable network environments. MQTT is a lightweight transmission protocol developed specifically for the Internet of Things. The MQTT protocol has been specially optimized for low-bandwidth networks and devices with low computing power, making it adaptable to various IoT application scenarios. At present, MQTT has clients on various platforms and devices, and has formed a preliminary ecosystem.

MQTT is a message queue protocol that uses the publish/subscribe message model to provide one-to-many message publishing and decouple applications. Compared with other protocols, development is simpler; the MQTT protocol works on the TCP/IP protocol; by TCP The /IP protocol provides a stable network connection; therefore, any network device with a TCP protocol stack can use the MQTT protocol. The ESP8266 used in this device has a TCP protocol stack and can establish a TCP connection. Therefore, with the MQTT protocol encapsulated in the STM32 code, communication with the Huawei cloud platform can be completed.

Huawei Cloud's MQTT protocol access help document is here: https://support.huaweicloud.com/devg-iothub/iot_02_2200.html

img

Business Process:

img

(2) Huawei Cloud Platform MQTT protocol usage restrictions

describe limit
Supported MQTT protocol versions 3.1.1
Differences from the standard MQTT protocol Supports Qos 0 and Qos 1. Supports Topic customization. Does not support QoS2. Does not support will and retain msg.
Security levels supported by MQTTS Adopt TCP channel base + TLS protocol (up to TLSv1.3 version)
Maximum number of MQTT connection requests per second for a single account Unlimited
Maximum number of MQTT connections supported by a single device per minute 1
The throughput per second of a single MQTT connection, that is, the bandwidth, including directly connected devices and gateways 3KB/s
The maximum length of a single MQTT publishing message. Publishing requests exceeding this size will be directly rejected. 1MB
MQTT connection heartbeat time recommended value The heartbeat time is limited to 30 to 1200 seconds, and the recommended setting is 120 seconds
Does the product support custom topics? support
Message publishing and subscription The device can only publish and subscribe messages to its own Topic.
Maximum number of subscriptions per subscription request Unlimited

(3) Topic subscription format

Help document address: https://support.huaweicloud.com/devg-iothub/iot_02_2200.html

image-20221207153310037

For devices, they generally subscribe to the topic of messages sent by the platform to the device.

If a device wants to receive messages sent by the platform, it needs to subscribe to the topic of messages sent by the platform to the device. After subscribing, the platform sends messages to the device, and the device will receive the message.

If the device wants to know the messages sent by the platform, it needs to subscribe to the topic marked in the picture above.

以当前设备为例,最终订阅主题的格式如下:
$oc/devices/{device_id}/sys/messages/down

最终的格式:
$oc/devices/6419627e40773741f9fbdac7_dev1/sys/messages/down

(4) Topic publishing format

For devices, topic publishing means uploading data to the cloud platform, and uploading the latest sensor data and device status to the cloud platform.

This operation is called: attribute reporting.

Help document address: https://support.huaweicloud.com/usermanual-iothub/iot_06_v5_3010.html

image-20221207153637391

According to the introduction of the help document, the current device publishing theme and the format of reported attributes are summarized as follows:

发布的主题格式:
$oc/devices/{device_id}/sys/properties/report
 
最终的格式:
$oc/devices/6419627e40773741f9fbdac7_dev1/sys/properties/report
发布主题时,需要上传数据,这个数据格式是JSON格式。

上传的JSON数据格式如下:

{
  "services": [
    {
      "service_id": <填服务ID>,
      "properties": {
        "<填属性名称1>": <填属性值>,
        "<填属性名称2>": <填属性值>,
        ..........
      }
    }
  ]
}
根据JSON格式,一次可以上传多个属性字段。 这个JSON格式里的,服务ID,属性字段名称,属性值类型,在前面创建产品的时候就已经介绍了,不记得可以翻到前面去查看。

根据这个格式,组合一次上传的属性数据:
{"services": [{"service_id": "stm32","properties":{"DS18B20":18,"motor_water":1,"motor_oxygen":1,"temp_max":10,"water_hp":130,"motor_food":0,"time_food":0,"oxygen_food":3}}]}

3.6 MQTT triples

MQTT protocol login requires filling in user ID, device ID, device password and other information. Just like when we usually log in to QQ and WeChat, we need to enter the account password to log in. These three parameters logged in the MQTT protocol are generally called MQTT triples.

Next, we will introduce how to obtain the MQTT triplet parameters of Huawei Cloud Platform.

(1) MQTT server address

To log in to the MQTT server, first remember to know the address and port of the server.

Help document address: https://console.huaweicloud.com/iotdm/?region=cn-north-4#/dm-portal/home

image-20230302135718882

The port of the MQTT protocol supports 1883 and 8883. The difference between them is: 8883 is an encrypted port and is more secure. However, it is difficult to use on a microcontroller, so the current equipment uses the 1883 port for connection.

Based on the above domain name and port number, get the following IP address and port number information: If the device supports filling in the domain name, you can directly fill in the domain name, if not, directly fill in the IP address. (The IP address is obtained by domain name resolution)

华为云的MQTT服务器地址:114.116.232.138
域名:7445c6bcd3.st1.iotda-device.cn-north-4.myhuaweicloud.com
华为云的MQTT端口号:1883

(2) Generate MQTT triples

Huawei Cloud provides an online tool to generate MQTT authentication triples: https://iot-tool.obs-website.cn-north-4.myhuaweicloud.com/

Open this tool, fill in the device information (that is, the information saved after creating the device just now), click Generate, and you can get the MQTT login information.

Here is the page that opens:

image-20221207154917230

Fill in the device information: (The above two lines are saved after the device is created)

Get the triplet information directly.

image-20230321160708924

image-20230321160718302

After obtaining the triplet, when the device logs in for authentication through the MQTT protocol, just fill in the parameters.

ClientId 6419627e40773741f9fbdac7_dev1_0_0_2023032108
Username 6419627e40773741f9fbdac7_dev1
Password 861ac9e6a579d36888b2aaf97714be7af6c77017b017162884592bd68b086a6e

3.7 Simulate device login test

After the above steps, the product, device, and data model have been created, and the MQTT login information has been obtained. Next, use MQTT client software to simulate a real device to log in to the platform. Test whether communication with the server is normal.

(1) Fill in the login information

Open the MQTT client software and fill in the relevant information (the text introduction above). Then, click to log in, subscribe to the topic, and publish the topic.

image-20230321161132971

(2) Open the web page to view

After completing the above operations, open the Huawei Cloud web backend and you can see that the device is online.

Click on the details page to see the uploaded data.

At this point, the deployment of the cloud platform has been completed and the device can upload data normally.

4. PC development

In order to conveniently view the data uploaded by the device and remotely control the device, Qt is used to develop a host computer for Android and Windows systems.

Use the API interface provided by Huawei Cloud Platform to obtain the data uploaded by the device, and also issue instructions to the device to control the device.

In order to conveniently view the data uploaded by the device and remotely control the device, Qt is used to develop a host computer for Android and Windows systems.

Use the API interface provided by Huawei Cloud Platform to obtain the data uploaded by the device, and also issue instructions to the device to control the device.

4.1 Qt development environment installation

Qt’s Chinese official website: https://www.qt.io/zh-cn/image-20221207160550486

image-20221207160606892

Download address of QT5.12.6: https://download.qt.io/archive/qt/5.12/5.12.6

After opening the download link, select the version below to download:

qt-opensource-windows-x86-5.12.6.exe 13-Nov-2019 07:28 3.7G Details

Disconnect the network when installing the software, otherwise you will be prompted to enter your account.

When installing, mingw 32just check a compiler in the first check box, leave the others as default, just click Next to continue the installation.

image-20221203151742653

Note: I am only introducing the PC-side environment setup (this is relatively simple). The development environment of Android is quite troublesome. You can go to my blog for detailed articles.

Select MinGW 32-bit compiler:

image-20221203151750344

4.2 Create an IAM account

Create an IAM account, because in the future development of the host computer, you need to use the API interface of the cloud platform, and these interfaces require token for authentication. To put it simply, it is identity authentication. When calling the interface to obtain the Token, you need to fill in the IAM account information. So, let’s demonstrate the process next.

Address: https://console.huaweicloud.com/iam/?region=cn-north-4#/iam/users

When obtaining a Token, in addition to the AIM account, you also need project credentials:

faa0973835ab409ab48182e2590f4ad3

image-20230321161348409

image-20230321161414487

Click your nickname with the mouse and click Unified Identity Authentication.

image-20230321161433209

Click on the upper left corner 创建用户.

image-20230321161450557

image-20221207161209880

image-20221207161308917

image-20221207161327200

Created successfully:

image-20221212174359962

image-20221212174412097

image-20230321161557848

4.3 Obtain shadow data

Help document: https://support.huaweicloud.com/api-iothub/iot_06_v5_0079.html

Device shadow introduction:

设备影子是一个用于存储和检索设备当前状态信息的JSON文档。
每个设备有且只有一个设备影子,由设备ID唯一标识
设备影子仅保存最近一次设备的上报数据和预期数据
无论该设备是否在线,都可以通过该影子获取和设置设备的属性

To put it simply: the device shadow is the latest data uploaded by the device.

In the software we designed, if we want to obtain the latest status information of the device, we use the device shadow interface.

If you are not familiar with the interface, you can perform online debugging first: https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=IoTDA&api=ShowDeviceShadow

Online debugging interface, you can request the shadow interface to understand the request and returned data format.

image-20230321161636567

image-20230321161701419

The data returned by the device shadow interface is as follows:

{
    
    
 "device_id": "6419627e40773741f9fbdac7_dev1",
 "shadow": [
  {
    
    
   "service_id": "stm32",
   "desired": {
    
    
    "properties": null,
    "event_time": null
   },
   "reported": {
    
    
    "properties": {
    
    
     "DS18B20": 18,
     "motor_water": 1,
     "motor_oxygen": 1,
     "temp_max": 10,
     "water_hp": 130,
     "motor_food": 0,
     "time_food": 0,
     "oxygen_food": 3
    },
    "event_time": "20230321T081126Z"
   },
   "version": 0
  }
 ]
}

4.4 Modify device properties

Address: https://support.huaweicloud.com/api-iothub/iot_06_v5_0034.html

Interface Description

设备的产品模型中定义了物联网平台可向设备下发的属性,应用服务器可调用此接口向指定设备下发属性。平台负责将属性以同步方式发送给设备,并将设备执行属性结果同步返回。

The interface for modifying device attributes allows the server to issue instructions to the device and control the device if needed.

Online debugging address:

https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=IoTDA&api=UpdateProperties

Modifying device properties is a synchronous command and requires the device to be online before debugging. First use the MQTT client to log in to the server and simulate the device going online.

Then debug and send the test data to the device remotely.

【1】Use MQTT client to log in to the device first (this is a synchronous command and must be online to debug)

image-20230321161923007

【2】Click to debug

image-20230321161905033

{
    
    "services":{
    
    "temp_max":100}}

【4】As you can see, the MQTT client software has received the message sent by the server.

image-20230313175819901

Since it is a synchronous command, the server must receive a response from the device to successfully complete a process. Only when the device responds can the server determine that the data is successfully delivered.

image-20230321161941584

How does the MQTT device respond?

Device response format description: https://support.huaweicloud.com/api-iothub/iot_06_v5_3008.html

image-20221203163532648

Let’s do the actual operation:

After the server sends the command through online debugging, the client copies the request ID, adds it to the format of the published topic, and then replies back. The server receives the response, and one attribute modification is completed perfectly.

image-20230321162053263

This is the successful state:

image-20230321162026282

**The following is a summary of the request: ** (In response to the server's request to modify device attributes)

上报主题的格式:$oc/devices/{
    
    device_id}/sys/properties/set/response/request_id=

$oc/devices/6419627e40773741f9fbdac7_dev1/sys/properties/set/response/request_id=

响应的数据:
{
    
    "result_code": 0,"result_desc": "success"}

4.5 Design the host computer

The previous 2 explained the API interfaces that need to be used. Next, we use Qt to design the host computer, design the interface, and complete the logical design of the overall host computer.

【1】New Qt project

image-20230302144331541

Select the project path and place it under the English path.

image-20230321162532573

image-20230313180428670

image-20230313180451177

image-20230313180504518

image-20230321162620141

Created.

Create a new Android template:

image-20230321162657975

image-20230321162731010

image-20230321162741791

image-20230321162812486

【2】Interface design

image-20230728140933190

【4】Code design: reading and saving configuration parameters

/*
功能: 保存数据到文件
*/
void Widget::SaveDataToFile(QString text)
{
    
    
    /*保存数据到文件,方便下次加载*/
    QString file;
    file=QCoreApplication::applicationDirPath()+"/"+ConfigFile;
    QFile filesrc(file);
    filesrc.open(QIODevice::WriteOnly);
    QDataStream out(&filesrc);
    out << text;  //序列化写字符串
    filesrc.flush();
    filesrc.close();
}


/*
功能: 从文件读取数据
*/
QString Widget::ReadDataFile(void)
{
    
    
    //读取配置文件
    QString text,data;
    text=QCoreApplication::applicationDirPath()+"/"+ConfigFile;

    //判断文件是否存在
    if(QFile::exists(text))
    {
    
    
        QFile filenew(text);
        filenew.open(QIODevice::ReadOnly);
        QDataStream in(&filenew); // 从文件读取序列化数据
        in >> data; //提取写入的数据
        filenew.close();
    }
    return data; //返回值读取的值
}

【3】Code Design: Cloud Data Analysis

//解析反馈结果
void Widget::replyFinished(QNetworkReply *reply)
{
    
    
    QString displayInfo;

    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    //读取所有数据
    QByteArray replyData = reply->readAll();

    qDebug()<<"状态码:"<<statusCode;
    qDebug()<<"反馈的数据:"<<QString(replyData);

    //更新token
    if(function_select==3)
    {
    
    
        displayInfo="token 更新失败.";
        //读取HTTP响应头的数据
        QList<QNetworkReply::RawHeaderPair> RawHeader=reply->rawHeaderPairs();
        qDebug()<<"HTTP响应头数量:"<<RawHeader.size();
        for(int i=0;i<RawHeader.size();i++)
        {
    
    
            QString first=RawHeader.at(i).first;
            QString second=RawHeader.at(i).second;
            if(first=="X-Subject-Token")
            {
    
    
                Token=second.toUtf8();
                displayInfo="token 更新成功.";

                //保存到文件
                SaveDataToFile(Token);
                break;
            }
        }
        QMessageBox::information(this,"提示",displayInfo,QMessageBox::Ok,QMessageBox::Ok);
        return;
    }

    //判断状态码
    if(200 != statusCode)
    {
    
    
        //解析数据
        QJsonParseError json_error;
        QJsonDocument document = QJsonDocument::fromJson(replyData, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
    
    
            //判断是否是对象,然后开始解析数据
            if(document.isObject())
            {
    
    
                QString error_str="";
                QJsonObject obj = document.object();
                QString error_code;
                //解析错误代码
                if(obj.contains("error_code"))
                {
    
    
                    error_code=obj.take("error_code").toString();
                    error_str+="错误代码:";
                    error_str+=error_code;
                    error_str+="\n";
                }
                if(obj.contains("error_msg"))
                {
    
    
                    error_str+="错误消息:";
                    error_str+=obj.take("error_msg").toString();
                    error_str+="\n";
                }

                //显示错误代码
                QMessageBox::information(this,"提示",error_str,QMessageBox::Ok,QMessageBox::Ok);
            }
         }
        return;
    }

    //设置属性
    if(function_select==12 || function_select==13)
    {
    
    
        //解析数据
        QJsonParseError json_error;
        QJsonDocument document = QJsonDocument::fromJson(replyData, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
    
    
            //判断是否是对象,然后开始解析数据
            if(document.isObject())
            {
    
    
                QJsonObject obj = document.object();
                if(obj.contains("response"))
                {
    
    
                    QJsonObject obj1=obj.take("response").toObject();
                    int val=0;
                    QString success;
                    if(obj1.contains("result_code"))
                    {
    
    
                         val=obj1.take("result_code").toInt();
                    }
                    if(obj1.contains("result_desc"))
                    {
    
    
                         success=obj1.take("result_desc").toString();
                    }

                    if(val==0 && success =="success")
                    {
    
    
                        //显示状态
                        QMessageBox::information(this,"提示","远程命令操作完成.",QMessageBox::Ok,QMessageBox::Ok);
                        return;
                    }
                    else
                    {
    
    
                        //显示状态
                        QMessageBox::information(this,"提示","设备未正确回应.请检查设备网络.",QMessageBox::Ok,QMessageBox::Ok);
                        return;
                    }
                }
            }
         }
    }

    //查询设备属性
    if(function_select==0)
    {
    
    
        //解析数据
        QJsonParseError json_error;
        QJsonDocument document = QJsonDocument::fromJson(replyData, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
    
    
            //判断是否是对象,然后开始解析数据
            if(document.isObject())
            {
    
    
                QJsonObject obj = document.object();
                if(obj.contains("shadow"))
                {
    
    
                    QJsonArray array=obj.take("shadow").toArray();
                    for(int i=0;i<array.size();i++)
                    {
    
    
                        QJsonObject obj2=array.at(i).toObject();
                        if(obj2.contains("reported"))
                        {
    
    
                            QJsonObject obj3=obj2.take("reported").toObject();


                            if(obj3.contains("properties"))
                            {
    
    
                                QJsonObject properties=obj3.take("properties").toObject();

                                qDebug()<<"开始解析数据....";
                            }
                        }
                    }
                }
            }
         }
        return;
    }
}

5. Code implementation

5.1 BC26 connection cloud platform implementation code

The following is the implementation code for using STM32F103ZET6 and BC26 to connect to Huawei Cloud IoT platform to implement MQTT device login, topic subscription and topic publishing:

#include "stdio.h"
#include "string.h"
#include "stdlib.h"

// 定义华为云物联网平台的服务器地址、端口号、设备ID和设备密码
#define MQTT_SERVER "mqtt://xxxxxx.iotplatform.com"  // 请替换为实际的服务器地址
#define MQTT_PORT 1883  // 请根据实际情况修改端口号
#define DEVICE_ID "your_device_id"  // 请替换为实际的设备ID
#define DEVICE_PASSWORD "your_device_password"  // 请替换为实际的设备密码

// 定义MQTT相关的参数
#define MQTT_CLIENT_ID "your_client_id"  // 请替换为实际的客户端ID
#define MQTT_TOPIC "your_topic"  // 请替换为实际的主题

// 定义MQTT消息接收回调函数
void mqtt_message_received(char *topic, char *payload) {
    
    
    printf("Received message on topic: %s\n", topic);
    printf("Payload: %s\n", payload);
}

// 建立MQTT连接
void mqtt_connect() {
    
    
    // 连接到华为云物联网平台的MQTT服务器
    // 这里使用的是MQTT的QoS 1级别
    // 请根据实际情况修改QoS级别和其他参数
    char command[256];
    sprintf(command, "AT+QMTCFG=\"aliauth\",0,%d,\"%s\",\"%s\"", MQTT_PORT, DEVICE_ID, DEVICE_PASSWORD);
    printf("Sending command: %s\n", command);
    // 发送AT指令连接到MQTT服务器
    // ...

    // 订阅主题
    sprintf(command, "AT+QMTSUB=0,1,\"%s\",1", MQTT_TOPIC);
    printf("Sending command: %s\n", command);
    // 发送AT指令订阅主题
    // ...
}

// 发布MQTT消息
void mqtt_publish(char *payload) {
    
    
    // 发布消息到指定的主题
    char command[256];
    sprintf(command, "AT+QMTPUB=0,0,0,0,\"%s\"", MQTT_TOPIC);
    printf("Sending command: %s\n", command);
    // 发送AT指令设置发布的主题
    // ...

    sprintf(command, "AT+QMTPUB=0,1,0,0,%d", strlen(payload));
    printf("Sending command: %s\n", command);
    // 发送AT指令设置消息的长度
    // ...

    printf("Sending payload: %s\n", payload);
    // 发送消息的内容
    // ...

    // 等待MQTT服务器返回发布结果
    // ...
}

int main() {
    
    
    // 初始化串口和其他硬件模块
    // ...

    // 连接到华为云物联网平台的MQTT服务器
    mqtt_connect();

    // 进入主循环
    while (1) {
    
    
        // 处理其他任务
        // ...

        // 检查是否有需要发布的消息
        // 如果有,调用mqtt_publish函数发布消息
        // ...

        // 检查是否有接收到的MQTT消息
        // 如果有,调用mqtt_message_received函数处理消息
        // ...
    }

    return 0;
}

5.2 MQTT protocol instructions of BC26 module

The BC26 module is an IoT module that supports NB-IoT communication technology and can communicate and control external devices through AT commands.

The following are some common AT commands and their functions related to the BC26 module and the MQTT protocol:

【1】AT+QMTOPEN: Open MQTT client connection.

  • Function: Connect to the MQTT server through this command.
  • Parameters: server address, port number, user name and password, etc.
  • Example: AT+QMTOPEN=0,"mqtt://xxxxxx.iotplatform.com",1883

【2】AT+QMTCLOSE: Close the MQTT client connection.

  • Function: Use this command to close the connection with the MQTT server.
  • Parameters: None.
  • Example: AT+QMTCLOSE=0

【3】AT+QMTCONN: Establish MQTT connection.

  • Function: Use this command to establish a connection with the MQTT server.
  • Parameters: client ID, username, password, etc.
  • 示例:AT+QMTCONN=0,“your_client_id”,“your_username”,“your_password”

【4】AT+QMTDISC: Disconnect MQTT connection.

  • Function: Use this command to disconnect from the MQTT server.
  • Parameters: None.
  • Example: AT+QMTDISC=0

【5】AT+QMTSUB: Subscribe to MQTT topic.

  • Function: Use this command to subscribe to the specified MQTT topic.
  • Parameters: topic, QoS level, etc.
  • Example: AT+QMTSUB=0,1,"your_topic",1

【6】AT+QMTUNS: Unsubscribe from MQTT topic.

  • Function: Use this command to unsubscribe from the specified MQTT topic.
  • Parameters: topic.
  • Example: AT+QMTUNS=0,1,"your_topic"

【7】AT+QMTPUB: Publish MQTT messages.

  • Function: Use this command to publish messages to the specified MQTT topic.
  • Parameters: topic, message content, QoS level, etc.
  • Example: AT+QMTPUB=0,0,0,0,"your_topic"

【8】AT+QMTRECV: Receive MQTT messages.

  • Function: Use this command to receive messages received from the MQTT server.
  • Parameters: None.
  • Example: AT+QMTRECV=0

These are some common AT commands related to MQTT protocol in BC26 module.

5.3 Read the temperature and humidity data of the DHT11 sensor

The following is the implementation code for using STM32F103ZET6 to read the temperature and humidity data of the DHT11 sensor:

#include "stm32f10x.h"
#include "dht11.h"

int main(void)
{
    
    
    // 初始化DHT11传感器
    DHT11_Init();

    while (1)
    {
    
    
        // 读取DHT11传感器的温湿度数据
        DHT11_Result result = DHT11_Read();

        if (result.status == DHT11_OK)
        {
    
    
            // 温度数据
            uint8_t temperature = result.temperature;
            // 湿度数据
            uint8_t humidity = result.humidity;

            // 在这里进行温湿度数据的处理和使用
            // ...

            // 延时一段时间后再次读取
            DelayMs(2000);
        }
        else
        {
    
    
            // 读取失败,可以进行相应的错误处理
            // ...
        }
    }
}

In the main function, the temperature and humidity data of the DHT11 sensor are continuously read through a loop. If the reading is successful, resultthe temperature and humidity data can be obtained from the structure and processed accordingly. If the read fails, error handling can be done as needed.

5.4 DHT11.c and DHT11.h code

dht11.h:

#ifndef DHT11_H
#define DHT11_H

#include "stm32f10x.h"

typedef struct
{
    
    
    uint8_t status;      // 读取状态,0表示成功,其他表示失败
    uint8_t humidity;    // 湿度值
    uint8_t temperature; // 温度值
} DHT11_Result;

void DHT11_Init(void);
DHT11_Result DHT11_Read(void);

#endif

dht11.c:

#include "dht11.h"

#define DHT11_PORT GPIOA
#define DHT11_PIN GPIO_Pin_0

static void DHT11_Delay(uint32_t us)
{
    
    
    uint32_t count = us * 8;
    while (count--)
    {
    
    
        __NOP();
    }
}

static void DHT11_SetOutput(void)
{
    
    
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(DHT11_PORT, &GPIO_InitStructure);
}

static void DHT11_SetInput(void)
{
    
    
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_Init(DHT11_PORT, &GPIO_InitStructure);
}

static uint8_t DHT11_ReadByte(void)
{
    
    
    uint8_t byte = 0;
    for (uint8_t i = 0; i < 8; i++)
    {
    
    
        while (!GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN))
        {
    
    
            // 等待低电平结束
        }
        DHT11_Delay(30);
        if (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN))
        {
    
    
            byte |= (1 << (7 - i));
        }
        while (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN))
        {
    
    
            // 等待高电平结束
        }
    }
    return byte;
}

void DHT11_Init(void)
{
    
    
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(DHT11_PORT, &GPIO_InitStructure);

    GPIO_SetBits(DHT11_PORT, DHT11_PIN);
}

DHT11_Result DHT11_Read(void)
{
    
    
    DHT11_Result result;
    result.status = 1;

    DHT11_SetOutput();
    GPIO_ResetBits(DHT11_PORT, DHT11_PIN);
    DHT11_Delay(18000);
    GPIO_SetBits(DHT11_PORT, DHT11_PIN);
    DHT11_Delay(20);
    DHT11_SetInput();

    if (!GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN))
    {
    
    
        while (!GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN))
        {
    
    
            // 等待低电平结束
        }
        while (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN))
        {
    
    
            // 等待高电平结束
        }

        uint8_t data[5];
        for (uint8_t i = 0; i < 5; i++)
        {
    
    
            data[i] = DHT11_ReadByte();
        }

        uint8_t sum = data[0] + data[1] + data[2] + data[3];
        if (sum == data[4])
        {
    
    
            result.status = 0;
            result.humidity = data[0];
            result.temperature = data[2];
        }
    }

    return result;
}

The dht11.h file defines the initialization function DHT11_Init()and reading function of the DHT11 sensor DHT11_Read(), and the DHT11_Result structure is used to store the reading results.

The dht11.c file implements the initialization and reading functions of the DHT11 sensor. In the initialization function, the GPIO mode and speed of the DHT11 pin are configured. In the reading function, the temperature and humidity data of the DHT11 sensor is read and verified by sending a start signal and receiving data.

5.5 GPS data analysis

Read the positioning data returned by the GPS module through serial port 2 on STM32F103ZET6 and parse the longitude, latitude and positioning status.

#include "stm32f10x.h"
#include <stdio.h>
#include <string.h>

// 定义串口2接收缓冲区大小
#define RX_BUFFER_SIZE 256

// 定义GPS数据解析状态
typedef enum {
    
    
    GPS_STATE_IDLE,        // 空闲状态
    GPS_STATE_RECEIVING,   // 接收中状态
    GPS_STATE_COMPLETE     // 接收完成状态
} GPS_State;

// 定义接收缓冲区和接收状态变量
char rxBuffer[RX_BUFFER_SIZE];
volatile uint16_t rxIndex = 0;
volatile GPS_State gpsState = GPS_STATE_IDLE;

// 处理接收到的GPS数据
void processGPSData() {
    
    
    // 在这里进行GPS数据解析和处理
    // 解析经纬度和定位状态等信息
    // 根据需要进行相应的操作或显示
    // 例如,打印经纬度和定位状态
    printf("Latitude: %s\n", latitude);
    printf("Longitude: %s\n", longitude);
    printf("Position Fix Status: %s\n", positionStatus);
}

// 串口2接收中断处理函数
void USART2_IRQHandler(void) {
    
    
    if (USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) {
    
    
        char data = USART_ReceiveData(USART2);
        
        // 接收到回车换行符表示一条完整的GPS数据
        if (data == '\n') {
    
    
            rxBuffer[rxIndex] = '\0';
            rxIndex = 0;
            gpsState = GPS_STATE_COMPLETE;
        } else {
    
    
            // 将接收到的数据存储到缓冲区中
            rxBuffer[rxIndex] = data;
            rxIndex++;
            
            // 接收缓冲区溢出时进行处理
            if (rxIndex >= RX_BUFFER_SIZE) {
    
    
                rxIndex = 0;
                gpsState = GPS_STATE_IDLE;
            }
        }
    }
}

int main(void) {
    
    
    // 初始化串口2和GPIO引脚
    // 设置串口2的波特率、数据位、停止位等参数
    
    // 使能串口2接收中断
    USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
    NVIC_EnableIRQ(USART2_IRQn);
    
    while (1) {
    
    
        // 如果接收到完整的GPS数据
        if (gpsState == GPS_STATE_COMPLETE) {
    
    
            // 处理接收到的GPS数据
            processGPSData();
            
            // 处理完成后,重置接收状态为IDLE
            gpsState = GPS_STATE_IDLE;
        }
    }
}

The serial port initialization and interrupt handling parts in the code are based on the use of the standard library.

Guess you like

Origin blog.csdn.net/xiaolong1126626497/article/details/132991011