ESP32 uploads data to the OntNet platform (network layer) through the MQTT protocol

ESP32 uploads data to the OntNet platform (network layer) through the MQTT protocol



foreword

Because the variable definition of the previous code is messy, many places are not easy to understand, and it has not been used for a long time, so I re-debugged a relatively simple program, which can be regarded as a refresher, in which the uploaded data is changed from sensor data to custom If you need to upload other sensor data, you can directly modify the uploaded data.

You can learn together with the first two introductions! ! !
Thonny+MicroPython+ESP32 development environment construction

ESP32 drives vibration sensor, MAX4466 (sensing layer)


1. Understand the OneNet cloud platform

1. One Net registers new users

First, enter the official website of China Mobile OneNet platform https://open.iot.10086.cn , click "Register" in the upper right corner, and register an account. After the account registration is complete, click Login to enter the "Console" in the upper right corner, as shown in the figure below.
insert image description here

2. Add new products

Click Add Product and fill in the product parameters, as shown in the figure.
insert image description here
insert image description here
The above parameters can be set according to the needs. View the product parameters. The product ID inside is very important and needs to be used for identity authentication later.
insert image description here

3. Add new device

Enter the created product and click Add Device. Create a test device here, as shown in the figure below. There
insert image description here
are so many uses of the cloud platform, and there are many other functions that will not be introduced here. You can go to the official website to learn.

2. Data upload

1. Import library and connect to WIFI

from simple import MQTTClient  
from machine import Pin,Timer
import network,time

Among them, the network library is a library for connecting to WIFI, and the simple library is an MQTT protocol program. I put this link below and you can download and use it yourself, including simple.py and complete code.

Link: https://pan.baidu.com/s/1Q6lAEy7b7Hd_Kcue43spOg?pwd=8888
Extraction code: 8888

def WIFI_Connect():
 wlan = network.WLAN(network.STA_IF)
 wlan.active(True)
 start_time = time.time()
 if not wlan.isconnected():
    print("connecting to network...")
    wlan.connect('aaaaa', '11111111')
    while not wlan.isconnected():
      WIFI_LED.value(1)
      time.sleep_ms(300)
      WIFI_LED.value(0)
      time.sleep_ms(300)
      if time.time()-start_time > 15:
        print("WIFI Connected Timeout!")
        break
 if wlan.isconnected():
    WIFI_LED.value(1)
    return True 
 else:
    return False

The above is the function of connecting to WIFI. Only when the network is connected can the data be uploaded to the cloud platform. The WIFI_LED defined above is the LED to view the complete code.

2. Data upload function and callback upload function

Use the data upload function to upload the data to the cloud platform. Here, a timer is used to upload the data to the cloud platform in real time. The a variable is the custom data used to simulate the data of the sensor.

def MQTT_Send(tim):
  global a
  a+=1
  if(a>=999):
      a=0
  
  mymessage = ('{
    
    "id": 123,"dp": {
    
    "data": [{
    
     "v": %d}]}}')%a #上传的数据需要按照这个格式
  client.publish(topic=publish_TOPIC,msg=mymessage,retain=False,qos=0)
  client.check_msg()#检查有没有发信息

The callback function has not been carefully debugged. It is estimated that there is no problem. It is mainly used for data delivery. Since it will be used in the application layer, it is pasted here in advance.

#设置MQTT回调函数,有信息时候执行
def  MQTT_callback(topic,msg):
  print('topic:{}'.format(topic))
  print('msg:{}'.format(msg))
  s=str(topic,'utf-8').split('/')
  print(s[5])
  response_TOPIC='$sys/417488/test/cmd/response/'+s[5]
  res_msg='success'
  client.publish(topic=response_TOPIC,msg=res_msg,retain=False,qos=0)
  #print((topic,msg))
  if msg == b"1":
    WIFI_LED.value(1)
    print("1")
  elif msg == b"0":
    WIFI_LED.value(0)
    print("0")
    

3. Identity authentication

Device access to the OneNet platform requires an identity authentication, which is equivalent to an account password. The user name is the product ID, and the user password is calculated using the token tool. Token tool download website: https://open.iot.10086.cn/doc/mqtt/book/manual/auth/tool.html

Open the token generation tool token.exe, fill in the corresponding parameters, click generate, and generate the token, as shown in the figure. The
insert image description here
red box is the password we need, and
the res parameter format is as follows: products/{product ID}/devices/{device name} where Product ID is mentioned above.
The et parameter is a time parameter. Here you can choose a value that is much greater than the current time. For example: 1700000000
The key parameter is the key of the device. Here, open the device list and click the details to find it, as shown in the figure below: insert image description here
Other parameters can be set as the same as above. Finally click Generate to complete the generation. Every step here must not go wrong, otherwise the device and the cloud platform will not be able to connect.

4. Complete code

from simple import MQTTClient
from machine import Pin,Timer
import network,time


WIFI_LED = Pin(2,Pin.OUT)

#自定义用于模拟传感器数据
a=0

#连接WIFI的函数
def WIFI_Connect():
 wlan = network.WLAN(network.STA_IF)
 wlan.active(True)
 start_time = time.time()
 if not wlan.isconnected():
    print("connecting to network...")
    wlan.connect('aaaaa', '11111111')
    while not wlan.isconnected():
      WIFI_LED.value(1)
      time.sleep_ms(300)
      WIFI_LED.value(0)
      time.sleep_ms(300)
      if time.time()-start_time > 15:
        print("WIFI Connected Timeout!")
        break
 if wlan.isconnected():
    WIFI_LED.value(1)
    return True 
 else:
    return False


#数据上传函数
def MQTT_Send(tim):
  global a
  a+=1
  if(a>=999):
      a=0
  
  mymessage = ('{"id": 123,"dp": {"data": [{ "v": %d}]}}')%a
  client.publish(topic=publish_TOPIC,msg=mymessage,retain=False,qos=0)
  client.check_msg()#检查有没有发信息
  
  
#设置MQTT回调函数,有信息时候执行
def  MQTT_callback(topic,msg):
  print('topic:{}'.format(topic))
  print('msg:{}'.format(msg))
  s=str(topic,'utf-8').split('/')
  print(s[5])
  response_TOPIC='$sys/417488/test/cmd/response/'+s[5]
  res_msg='success'
  client.publish(topic=response_TOPIC,msg=res_msg,retain=False,qos=0)
  #print((topic,msg))
  if msg == b"1":
    WIFI_LED.value(1)
    print("1")
  elif msg == b"0":
    WIFI_LED.value(0)
    print("0")
    
  
if __name__ == "__main__":
    
    WIFI_Connect()
    
    if WIFI_Connect(): 
      #TOPIC名称  格式:$sys/{产品ID}/{设备名称}/dp/post/json
      publish_TOPIC = "$sys/417488/test/dp/post/json"
      #这个参数和上面那个差不多,只需要修改两个地方
      subscribe_TOPIC = "$sys/417488/test/cmd/request/+"
      #客户端ID:设备名称
      CLIENT_ID = "test"
      #用户名:产品ID
      user_name = "417488"
      #用户密码:用token工具计算
      user_password = "version=2018-10-31&res=products%2F417488%2Fdevices%2Ftest&et=1700000000&method=md5&sign=8II9kM5pBQJ%2FZ%2B8Wl8RItA%3D%3D"

      SERVER = "183.230.40.96"
      PORT = 1883
      client = MQTTClient(CLIENT_ID, SERVER, 0, user_name, user_password, 60)
      #设置回调函数
      client.set_callback(MQTT_callback)
      client.connect()
      #订阅主题
      client.subscribe(subscribe_TOPIC)
     
  
tim = Timer(-1)
tim.init(period=1000, mode=Timer.PERIODIC,callback=MQTT_Send)#周期为 1000ms


V. Summary

This is the basic data upload program. If you need to upload more data, you can modify it. Later, there will be an introduction to the app command issued by the application layer.

Guess you like

Origin blog.csdn.net/weixin_46155589/article/details/127019796