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

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

发布时间:2018-08-16 10:32,

浏览次数:733

, 标签:

Python

阿里云官方提供的 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值