[ODYSSEY-STM32MP157C] Report data to Alibaba Cloud IoT platform

We have successfully read the data of the PMS5003ST sensor in the previous section "[ODYSSEY-STM32MP157C] Drive UART to read sensor data" . In this section, we will learn how to connect the device to the Alibaba Cloud IoT platform and report the data to the cloud.

Prepare materials

Create products and equipment

Log in to the Alibaba Cloud IoT platform , enter the "Console", select the "Device Management" -> "Product" page, and create a product.

Insert picture description here

Add a custom function, I added a total of 6 attributes here, namely PM1.0, PM2.5, PM10, formaldehyde concentration, temperature, humidity. The specific identifier, data type, and scope are as follows.

Insert picture description here

On the "Device Management" -> "Device" page, click "Add Device" to add a test device to the product.

Insert picture description here

After the device is successfully created, we will get the device triplet information (ProductKey, DeviceName, DeviceSecret), which is the credential for the device to connect to the Alibaba Cloud IoT platform. Save it and we will use it later.

Connection test

Similarly, we use Python to complete this task. First install the paho-mqtt library:

pip3 install paho-mqtt

Enter the Python3 interactive environment and import related software libraries

import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import random
import json

Fill in the previously created device triples information into the options object (remember to replace with your own triples):

options = {
    
    
    'productKey':'a16CxOWWTpI',
    'deviceName':'D001',
    'deviceSecret':'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'regionId':'cn-shanghai'
}

Create HOST and PORT variables:

HOST = options['productKey'] + '.iot-as-mqtt.'+options['regionId']+'.aliyuncs.com'
PORT = 1883

Because connecting to the Alibaba Cloud IoT platform requires building parameters such as Client ID, User name, and Password, add a hmacsha1 function:

def hmacsha1(key, msg):
    return hmac.new(key.encode(), msg.encode(), hashlib.sha1).hexdigest()

Add client build function:

def getAliyunIoTClient():
	timestamp = str(int(time.time()))
	CLIENT_ID = "paho.py|securemode=3,signmethod=hmacsha1,timestamp="+timestamp+"|"
	CONTENT_STR_FORMAT = "clientIdpaho.pydeviceName"+options['deviceName']+"productKey"+options['productKey']+"timestamp"+timestamp
	# set username/password.
	USER_NAME = options['deviceName']+"&"+options['productKey']
	PWD = hmacsha1(options['deviceSecret'],CONTENT_STR_FORMAT)
	client = mqtt.Client(client_id=CLIENT_ID, clean_session=False)
	client.username_pw_set(USER_NAME, PWD)
	return client

Alright, then you can create a client object and try to connect to the Alibaba Cloud IoT platform~

>>> client = getAliyunIoTClient()
>>> client.connect(HOST, PORT, 300)
0

Switch to the console of the Alibaba Cloud IoT platform, refresh it, and see if the D001 device changes from "offline" to "online".

Insert picture description here

Report data

A successful connection means that our ODYSSEY-STM32MP157C development board has become a device for this product. In order to complete sensor data collection and reporting tasks, we create a new upload_pms5003st.py file.

Integrating show_pms5003st.py from the previous section and the code to connect to the Alibaba Cloud IoT platform, the overall framework is as follows:

import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import random
import json
import sys
import glob
import serial

options = {
    
    
    'productKey':'',
    'deviceName':'',
    'deviceSecret':'',
    'regionId':'cn-shanghai'
}

HOST = options['productKey'] + '.iot-as-mqtt.'+options['regionId']+'.aliyuncs.com'
PORT = 1883
PUB_TOPIC = "/sys/" + options['productKey'] + "/" + options['deviceName'] + "/thing/event/property/post"

dev_name = '/dev/ttySTM2'
baudrate = 9600

CMD_READ = bytearray([0x42, 0x4d, 0xe2, 0x00, 0x00, 0x01, 0x71])
CMD_PASS = bytearray([0x42, 0x4d, 0xe1, 0x00, 0x00, 0x01, 0x70])
CMD_ACTI = bytearray([0x42, 0x4d, 0xe1, 0x00, 0x01, 0x01, 0x71])
CMD_STAN = bytearray([0x42, 0x4d, 0xe4, 0x00, 0x00, 0x01, 0x73])
CMD_NORM = bytearray([0x42, 0x4d, 0xe4, 0x00, 0x01, 0x01, 0x74])

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    # client.subscribe("the/topic")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

def hmacsha1(key, msg):
    return hmac.new(key.encode(), msg.encode(), hashlib.sha1).hexdigest()

def getAliyunIoTClient():
    # 忽略
    
def pms_value(hByte, lByte):
    return (hByte << 8 | lByte)

def loop(serial):
    while True:
        # 忽略
    time.sleep(5)

def main():
    print("Run ODYSSEY-uart demo")
    s = serial.Serial(dev_name, baudrate)

    try:
        s.write(CMD_PASS)
    except Exception as err:
        print(err)
    finally:
        time.sleep(1)

    loop(s)
    s.close()

if __name__ == '__main__':
    client = getAliyunIoTClient()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(HOST, 1883, 300)
    main()
    client.loop_forever()

The reported data is processed in the loop function. When the sensor data is obtained, the corresponding 6 attribute values ​​are encapsulated into JSON format data, and then the message can be published.

            payload_json = {
    
    
                'id': int(time.time()),
                'params': {
    
    
                    'PM1_0' : PM1_0_atm,
                    'PM2_5' : PM2_5_atm,
                    'PM10_0': PM10_0_atm,
                    'HCHO'  : hcho/1000,
                    'TEMP'  : temp,
                    'HUMI'  : humi
                },
                'method': "thing.event.property.post"
            }
            print('upload data to iot server: ' + str(payload_json))
            client.publish(PUB_TOPIC, payload=str(payload_json), qos=1)

For the complete code, please see https://github.com/luhuadong/ODYSSEY-STM32MP157C .

Run python3 upload_pms5003st.py, every time the data is reported, a JSON message will be printed out.

upload data to iot server: {
    
    'id': 1601621228, 'params': {
    
    'PM1_0': 24, 'PM2_5': 39, 'PM10_0': 45, 'HCHO': 0.0, 'TEMP': 27.6, 'HUMI': 52.1}, 'method': 'thing.event.property.post'}

On the Alibaba Cloud IoT platform page, open the device's object model data, and you can see the data reported periodically.

Insert picture description here

Well, at this point, we have completed the project of obtaining sensor data from the serial port, and then reporting the data to the cloud, and realized a prototype of the Internet of Things application. Awesome! Take a break~


Insert picture description here

Guess you like

Origin blog.csdn.net/luckydarcy/article/details/108902096