阿里云官方提供的 DEMO
<https://help.aliyun.com/document_detail/42693.html?spm=a2c4g.11186623.6.640.MsPJNh>
里面没有Python接入 阿里云物联网平台(原物联网套件)
<https://www.aliyun.com/product/iot?spm=5176.8142029.388261.689.a7236d3e8FvZVj&accounttraceid=f54da94c-2d9e-4fec-a61c-c827724f722a>
 的例子,不便于我们在电脑端做虚拟终端的相关测试,本文介绍一种基于使用Python3、MQTT-TCP连接通信
<https://help.aliyun.com/document_detail/73742.html?spm=a2c4g.11174283.6.621.zg8Emw>
 接入阿里云物联网平台(原物联网套件)。

开发语言:Python3.5

开发环境:Ubutnu16.04

IDE:PyCharm Community Edition <http://www.jetbrains.com/pycharm/index.html>

通信协议:MQTT、TCP
<https://help.aliyun.com/document_detail/73742.html?spm=a2c4g.11174283.6.621.zg8Emw>

参考资料:开源MQTT客户端参考 <https://github.com/mqtt/mqtt.github.io/wiki/libraries>、 
MQTT协议 <http://mqtt.org>

相关筹备:阿里云物联网平台(原物联网套件)、创建产品、创建Topic(data)
<https://iot.console.aliyun.com/product/region/cn-shanghai>

1. 新建文件夹AliYun_Iot,在此文件夹下新建Get_para.py、Sub_Client.py、Pub_Client.py。

2. 编辑Get_para.py,如下
#!/usr/bin/env python3.5 # -*- coding:utf-8 -*- """ file: Get_para.py date:
20171111 author: S_L_zheng function: return client_id, username, password. """
import time import hmac import hashlib import math class Get_para(object): def
__init__(self, PK, DN, DS): self.ProductKey = PK self.DeviceName = DN
self.DeviceSecret = DS def get_para(self): ProductKey = self.ProductKey
ClientId = self.DeviceName DeviceName = self.DeviceName DeviceSecret =
self.DeviceSecret signmethod = "hmacsha1" us = math.modf(time.time())[0] ms =
int(round(us * 1000)) timestamp = str(ms) data = "".join(("clientId", ClientId,
"deviceName", DeviceName, "productKey", ProductKey, "timestamp", timestamp))
ret = hmac.new(bytes(DeviceSecret, encoding='utf-8'), bytes(data,
encoding='utf-8'), hashlib.sha1).hexdigest() sign = ret client_id =
"".join((ClientId, "|securemode=3", ",signmethod=", signmethod, ",timestamp=",
timestamp, "|")) username = "".join((DeviceName, "&", ProductKey)) password =
sign return client_id, username, password if __name__ == '__main__': instance =
Get_para(PK='YurProductKey', DN='YourDeviceName', DS='YourDeviceSecret')
client_id, username, password = instance.get_para()
print('client_id:',client_id) print('username:', username) print('password:',
password)
3. 编辑Sub_Client.py,如下
#!/usr/bin/env python3.5 # -*- coding:utf-8 -*- """ file: Sub_Client.py date:
20171111 author: S_L_zheng function: Subscribe Topic. """ import
paho.mqtt.client as mqtt import Get_para DeviceName = "YourDeviceName"
DeviceSecret = "YourDeviceSecret " ProductKey = "YourProductKey " res =
Get_para.Get_para(PK=ProductKey, DN=DeviceName, DS=DeviceSecret) paras =
res.get_para() client_id = paras[0] username = paras[1] password = paras[2]
strBroker = ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" port = 1883
topic = ProductKey+'/'+DeviceName+'/'+'data' def on_connect(mqttc, userdata,
flags, rc): print("Connected with result code " + str(rc))
mqttc.subscribe(topic) def on_message(mqttc, userdata, msg): msgpayload =
str(msg.payload, encoding='utf-8') print(msgpayload) def on_subscribe(mqttc,
userdata, mid, granted_qos): print('on_subscribe') def on_publish(mqttc,
userdata, mid): print('on_publish') if __name__ == '__main__': mqttc =
mqtt.Client(client_id) mqttc.username_pw_set(username, password)
mqttc.on_connect = on_connect mqttc.on_message = on_message mqttc.on_subscribe
= on_subscribe mqttc.on_publish = on_publish mqttc.connect(strBroker, port,
120) mqttc.loop_forever()
4. 编辑Pub_Client.py,如下
#!/usr/bin/env python3.5 # -*- coding:utf-8 -*- """ file: Pub_Client.py date:
20171111 author: S_L_zheng function: Publishi message to topic. """ import
paho.mqtt.client as mqtt import Get_para DeviceName = "YourDeviceName"
DeviceSecret = "YourDeviceSecret" ProductKey = "YourProductKey" res =
Get_para.Get_para(PK=ProductKey, DN=DeviceName, DS=DeviceSecret) paras =
res.get_para() client_id = paras[0] username = paras[1] password = paras[2]
strBroker = ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" port = 1883
topic = ProductKey+'/'+DeviceName+'/'+'data' def on_connect(mqttc, userdata,
flags, rc): print("Connected with result code " + str(rc)) message =
'{"weather":"28"}' # must json mqttc.publish(topic, message, 1) def
on_message(mqttc, userdata, msg): msgpayload = str(msg.payload,
encoding='utf-8') print(msgpayload) def on_publish(mqttc, userdata, mid):
print('on_publish') if __name__ == '__main__': mqttc = mqtt.Client(client_id)
mqttc.username_pw_set(username, password) mqttc.on_connect = on_connect
mqttc.on_message = on_message mqttc.on_publish = on_publish
mqttc.connect(strBroker, port, 120) mqttc.loop_forever()
 

5. 代码运行顺序

Get_para.py—Sub_Client.py—Pub_Client.py

 

 

 

 

 

 

 

 

 

 

 

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信