Python通过MQTT连接阿里云实现

高飞依旧 自动化小天地 昨天

前面有介绍施耐德电气Modicon M262通过HTTP、MQTT将数据直传至阿里云IoT平台的实现。

但有很多PLC并不具备物联网的功能,这种情况下如果想要将数据上报至云平台,应该如何实现呢?


下面介绍一种基于Python 开源mqtt client库实现与阿里云的连接。


1. 安装mqtt client开源库

pip install paho-mqtt

2. 源代码如下

# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import random

options = {
'productKey': '请填写自己的设备信息',
'deviceName': '请填写自己的设备信息',
'deviceSecret':'请填写自己的设备信息',
'regionId': 'cn-shanghai',

}


Host = options['productKey']+'.iot-as-mqtt.cn-shanghai.aliyuncs.com'
Port = 1883
Topic_pub = "/sys/" + options['productKey'] + "/" + options['deviceName'] + "/thing/event/property/post"
ClientID = '456'

Client_Id = ClientID+"|securemode=2,signmethod=hmacsha1|"


payload_pub = {
'id': int(time.time()),
'params': {
'current': random.randint(0, 20),
'temperature': random.randint(20, 30),
'p_act': random.randint(1000, 2000),
'n_act': random.randint(500, 800)
},
'method': "thing.event.property.post"
}

def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.publish(Topic_pub, payload=str(payload_pub), qos=1)

def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))

def calculation_sign():
data = "".join(("clientId",ClientID, "deviceName",options['deviceName'],
"productKey", options['productKey']))
ret = hmac.new(bytes(options['deviceSecret'],encoding="utf-8"),bytes(data,encoding="utf-8"),hashlib.sha1).hexdigest()
return ret

def getAliyunIoTClient():
Username = options['deviceName']+'&'+options['productKey']
Password = calculation_sign()
client = mqtt.Client(Client_Id)
client.username_pw_set(Username, Password)
return client


if __name__ == '__main__':
client = getAliyunIoTClient()
client.on_connect = on_connect
client.on_message = on_message
client.connect(Host, Port, 300)
client.loop_forever()


3. 运行程序,打开阿里云Iot平台监控数据


注:

阿里云IoT平台配置和物模型创建请参考前面文章;

Python采集PLC数据部分请参考下面链接文章,本例仅发送模拟的随机数;


Python采集PLC数据:

如何通过手机监控PLC数据

如何通过手机监控PLC数据(二)


如果喜欢这篇文章,请点个“在看”吧