Last active
November 30, 2017 17:19
-
-
Save ax003d/1538dad770844e313d81531772b86a6d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
""" | |
requirements: | |
paho-mqtt==1.2 | |
""" | |
import hashlib | |
import hmac | |
import json | |
import time | |
from uuid import uuid4 | |
import paho.mqtt.client as mqtt | |
def sign(params, secret): | |
msg = [] | |
for k in sorted(params.keys()): | |
msg.append(k) | |
msg.append(str(params[k])) | |
msg = ''.join(msg) | |
return hmac.new(secret.encode(), msg.encode(), hashlib.sha1).digest().hex().upper() | |
def main(device_name, product_key, secret): | |
device_sn = uuid4().hex | |
t = int(time.time() * 1000) | |
params = { | |
'productKey': product_key, | |
'deviceName': device_name, | |
'clientId': device_sn, | |
'timestamp': t | |
} | |
host = "{}.iot-as-mqtt.cn-shanghai.aliyuncs.com".format(product_key) | |
port = 1883 | |
client_id = "{}|securemode=2,signmethod=hmacsha1,timestamp={}|".format(device_sn, t) | |
username = "{}&{}".format(device_name, product_key) | |
password = sign(params, secret) | |
def on_connect(client, userdata, flags, rc): | |
print("on_connect") | |
client.subscribe("/{}/{}/get".format(product_key, device_name)) | |
client.publish( | |
"/{}/{}/update".format(product_key, device_name), | |
payload=json.dumps({"content": "msg from :{}, {}".format(device_sn, t)}), | |
qos=0, | |
retain=False) | |
def on_message(client, userdata, msg): | |
print("on_message") | |
print("topic: {}".format(msg.topic)) | |
print("payload: {}".format(msg.payload.encode('hex'))) | |
def on_publish(client, userdata, mid): | |
print("on_publish") | |
client = mqtt.Client(client_id, protocol=mqtt.MQTTv311) | |
client.username_pw_set(username, password) | |
client.tls_set('root.crt') | |
client.on_connect = on_connect | |
client.on_message = on_message | |
client.on_publish = on_publish | |
client.connect(host, port) | |
client.loop_forever() | |
if __name__ == '__main__': | |
device_name = "" | |
product_key = "" | |
secret = "" | |
main(device_name, product_key, secret) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment