连接阿里云的Python源码,参考网上的代码,然后QT代码也是参照这个写的。
代码中加了很多注释,可以轻易看懂。
# coding=utf-8
# !/usr/bin/python3
import datetime
import time
import hmac
import hashlib
import math
TEST = 0
ProductKey = "a1EdB95bzby"
ClientId = "test123" # 自定义clientId
DeviceName = "test01"
DeviceSecret = "qU47CjbOh5F26D8isBX6BC5jZ9Uo2Nto"
# signmethod
signmethod = "hmacsha1"
# signmethod = "hmacmd5"
# 当前时间毫秒值
us = math.modf(time.time())[0]#获取当前时间微秒
ms = int(round(us * 1000))#round是默认取整,后面可以加保留的小数位数,不过不是严格四舍五入,结果是毫秒。
#timestamp = str(ms)#转换为字符串
timestamp = "12345"
data = "".join(("clientId", ClientId, "deviceName", DeviceName, #生成进行哈希算法的原始数据
"productKey", ProductKey, "timestamp", timestamp
))
# print(round((time.time() * 1000)))
print("data:", data)
if "hmacsha1" == signmethod:
ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"), #hmacsha1是哈希算法的一种
bytes(data, encoding="utf-8"),
hashlib.sha1).hexdigest() #这里的hexdigest直接输出16进制str
elif "hmacmd5" == signmethod:
ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"), #md5也是一种信息摘要算法,用以取代md4。2004年,证实MD5算法无法防止碰撞(collision),因此不适用于安全性认证,如SSL公开密钥认证或是数字签名等用途。
bytes(data, encoding="utf-8"),
hashlib.md5).hexdigest() #这里的hexdigest直接输出16进制str
else:
raise ValueError #当程序出错时,python会自动触发异常,也可以通过raise显示引发异常,一旦执行了raise语句,raise之后的语句不在执行
sign = ret #ret是哈希算法生成的摘要,这里作为用户密码
print("sign:", sign)
# ======================================================
strBroker = ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" #生成域名,阿里的服务器域名对应好几个IP地址,有一部分原因是为了做负载均衡。
port = 1883 #端口号是1883
client_id = "".join((ClientId, #生成client_id
"|securemode=3",
",signmethod=", signmethod,
",timestamp=", timestamp,
"|"))
username = "".join((DeviceName, "&", ProductKey)) #生成用户名
password = sign #用户密码也就是ret(哈希生成的摘要)
print("="*30)
print("client_id:", client_id)
print("username:", username)
print("password:", password)
print("="*30)
def secret_test():
DeviceSecret = "secret"
data = "clientId12345deviceNamedeviceproductKeypktimestamp789"
ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"), #bytes主要是给在计算机看的,string主要是给人看的,转换桥梁就是编码
bytes(data, encoding="utf-8"),
hashlib.sha1).hexdigest()
print("test:", ret)
# ======================================================
# MQTT Initialize.--------------------------------------
try:
import paho.mqtt.client as mqtt #导入paho.mqtt,这是一个MQTT协议的JavaScript库,还有一个js库MQTT.js,MQTT.js是需要Node.js的相关环境的
except ImportError:
print("MQTT client not find. Please install as follow:")
print("git clone http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.python.git")
print("cd org.eclipse.paho.mqtt.python")
print("sudo python setup.py install")
# ======================================================
#这里重写了mqtt库中的部分函数
def on_connect(mqttc, obj, rc):
print("OnConnetc, rc: " + str(rc))
mqttc.subscribe("test", 0)
#将消息发送到云端
def on_publish(mqttc, obj, mid):
print("OnPublish, mid: " + str(mid))
def on_subscribe(mqttc, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(mqttc, obj, level, string):
print("Log:" + string)
#接收与处理来自云端的消息
def on_message(mqttc, obj, msg):
curtime = datetime.datetime.now()
strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
print(strcurtime + ": " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
on_exec(str(msg.payload))
def on_exec(strcmd):
print("Exec:", strcmd)
strExec = strcmd
# =====================================================
if __name__ == '__main__':
if TEST:
secret_test()
exit(0)
mqttc = mqtt.Client(client_id)
mqttc.username_pw_set(username, password)
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
mqttc.on_log = on_log
mqttc.connect(strBroker, port, 120)
mqttc.loop_forever()