热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用Python3接入阿里云物联网平台(原物联网套件)

阿里云官方提供的 DEMO里面没有Python接入 阿里云物联网平台(原物联网套件) 的例子,不便于我们在电脑端做虚拟终端的相关测试,本文介绍一种基于使用Python3、MQTT-TCP连接通信

阿里云官方提供的 DEMO里面没有Python接入 阿里云物联网平台(原物联网套件) 的例子,不便于我们在电脑端做虚拟终端的相关测试,本文介绍一种基于使用Python3、MQTT-TCP连接通信 接入阿里云物联网平台(原物联网套件)。

开发语言:Python3.5

开发环境:Ubutnu16.04

IDE:PyCharm Community Edition

通信协议:MQTT、TCP

参考资料:开源MQTT客户端参考、 MQTT协议

相关筹备:阿里云物联网平台(原物联网套件)、创建产品、创建Topic(data)

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

 

 

 

 

 

 

 

 

 

 

 


推荐阅读
author-avatar
存在米小寒_151
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有