Python3 Raspberry Pi connects to Alibaba Cloud IoT devices to send and receive data

Alibaba Cloud IoT

First, prepare the
creation process of Alibaba Cloud product equipment (three codes), you can refer to this document: Quectel BC35-G configuration network connection Alibaba Cloud MQTT sending data
insert image description here

code section

The IDE I use here is Pycham 2021.2 ( it can be ported to spyder, Thonny and other Raspberry Pi IDEs )

Library file

Here we need an Alibaba Cloud IOT library file

from linkkit import linkkit

and two base library files time , Json

import time        
import json        

Installation environment under Windows

Open a command prompt and enter

pip install aliyun-iot-linkkit

insert image description here

Raspberry Pi installation environment

open terminal

pip install aliyun-iot-linkkit

possible errors

insert image description here
Network delay problem, repeat pip install aliyun-iot- linkkit

code

Configure " Three Codes "

ProductKey="ProductKey"        #阿里云物联网ProductKey
DeviceName="DeviceName"        #阿里云物联网DeviceName
DeviceSecret="DeviceSecret"     #阿里云物联网DeviceSecret

Connecting and canceling Alibaba Cloud devices

#连接阿里云设备
def on_connect(session_flag, rc, userdata):
    print("on_connect:%d,rc:%d,userdata:" % (session_flag, rc))
    pass
#取消连接阿里云
def on_disconnect(rc, userdata):
    print("on_disconnect:rc:%d,userdata:" % rc)

Subscribe to topics

# 订阅topic
def on_subscribe_topic(mid, granted_qos, userdata):
    print("on_subscribe_topic mid:%d, granted_qos:%s" %
          (mid, str(','.join('%s' % it for it in granted_qos))))
    pass

Receive and stop data from Alibaba Cloud

#接收阿里云的数据
def on_topic_message(topic, payload, qos, userdata):
    print("阿里云发布数据:", str(payload))
    #拿到接收来的数据
    data=str(payload)[2:-1]
    print("阿里云发布数据:",data)
    dataDict=json.loads(data)
    # 切片左闭右开 取头不取尾
    print("阿里云发布数据:",type(dataDict))
    #多层解析
    {
    
    "temp":{
    
    "value":32}}
    print(dataDict["temp"]["value"]) #temp是温度标识符,value模拟温度数据
    pass

#停止订阅云端数据
def on_unsubscribe_topic(mid, userdata):
    print("取消订阅topic mid:%d" % mid)
    pass

The result of publishing the message to determine whether the publish function was successfully called

#发布消息的结果,判断是否成功调用发布函数
def on_publish_topic(mid, userdata):
    print("发布公共topic mid:%d" % mid)

Post topic

#发布主题
while True:
    data={
    
    
        "RoomTemp":28
    }
    #产品属性上报: /sys/a1TbSHGVD5F/${deviceName}/thing/event/property/post 发布 设备属性上报
    rc, mid = lk.publish_topic(lk.to_full_topic("/sys/ProductKey/deviceName/thing/event/property/post"),str(data))
    time.sleep(2)
    pass

p_forever()

full code

from linkkit import linkkit         #阿里云aliyun-iot-linkkit库
import time         #python延时库
import json         #发送json数据

ProductKey="ProductKey"        #阿里云物联网ProductKey
DeviceName="DeviceName"        #阿里云物联网DeviceName
DeviceSecret="DeviceSecret"     #阿里云物联网DeviceSecret

#连接阿里云设备
def on_connect(session_flag, rc, userdata):
    print("on_connect:%d,rc:%d,userdata:" % (session_flag, rc))
    pass

#取消连接阿里云
def on_disconnect(rc, userdata):
    print("on_disconnect:rc:%d,userdata:" % rc)
# 订阅topic
def on_subscribe_topic(mid, granted_qos, userdata):
    print("on_subscribe_topic mid:%d, granted_qos:%s" %
          (mid, str(','.join('%s' % it for it in granted_qos))))
    pass

#接收阿里云的数据
def on_topic_message(topic, payload, qos, userdata):
    print("阿里云发布数据:", str(payload))
    #拿到接收来的数据
    data=str(payload)[2:-1]
    print("阿里云发布数据:",data)
    dataDict=json.loads(data)
    # 切片左闭右开 取头不取尾
    print("阿里云发布数据:",type(dataDict))
    #多层解析
    {
    
    "temp":{
    
    "value":29.8}}
    print(dataDict["temp"]["value"]) #temp是温度标识符,value模拟温度数据
    pass

#停止订阅云端数据
def on_unsubscribe_topic(mid, userdata):
    print("取消订阅topic mid:%d" % mid)
    pass

#发布消息的结果,判断是否成功调用发布函数
def on_publish_topic(mid, userdata):
    print("发布公共topic mid:%d" % mid)

#初始化连接参数,阿里云三码设置
lk = linkkit.LinkKit(
    host_name="cn-shanghai",#当前设备服务器(上海-华东二)
    product_key=ProductKey,#当前设备product_key
    device_name=DeviceName,#当前设备device_name
    device_secret=DeviceSecret)#当前设备device_secret

#注册接收到云端数据的方法
lk.on_connect = on_connect

#注册取消接收到云端数据的方法
lk.on_disconnect = on_disconnect

#注册云端订阅的方法
lk.on_subscribe_topic = on_subscribe_topic

#注册当接受到云端发送的数据的时候的方法
lk.on_topic_message = on_topic_message

#注册向云端发布数据的时候顺便所调用的方法
lk.on_publish_topic = on_publish_topic

#注册取消云端订阅的方法
lk.on_unsubscribe_topic = on_unsubscribe_topic

#连接阿里云的函数(异步调用)
lk.connect_async()
time.sleep(2)       #延时设置

#订阅主题
rc, mid = lk.subscribe_topic(lk.to_full_topic("user/get"))

#发布主题
while True:
    data={
    
    
        "RoomTemp":28
    }
    #产品属性上报: /sys/ProductKey/${deviceName}/thing/event/property/post 发布 设备属性上报
    rc, mid = lk.publish_topic(lk.to_full_topic("/sys/ProductKey/deviceName/thing/event/property/post"),str(data))
    time.sleep(2)
    pass
p_forever()

Product property report: /sys/ProductKey/${deviceName}/thing/event/property/post publish device property report
insert image description here

Show results

insert image description here
Simulate data transmission The
insert image description here
platform sends data
insert image description here
insert image description here
insert image description here
to Raspberry Pi
. I wish you the best of luck! ! !

Guess you like

Origin blog.csdn.net/weixin_50679163/article/details/119840105