Advertisement
Guest User

Untitled

a guest
Feb 26th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. from paho.mqtt import client as mqtt
  2. import ssl
  3. import token_generator #a script that exports the token , it is working fine for device messages
  4.  
  5. path_to_root_cert = "cert.cer"
  6. device_id = "mydevice_id "
  7. endpoint ="myiot_hub_name.azure-devices.net/devices/mydevice_id "
  8. policyKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  9. sas_token = token_generator.generate_sas_token(endpoint ,policyKey ,None)
  10. iot_hub_name = "myiot_hub_name"
  11.  
  12. def on_connect(client, userdata, flags, rc):
  13. print ("Device connected with result code: " + str(rc))
  14. def on_disconnect(client, userdata, rc):
  15. print ("Device disconnected with result code: " + str(rc))
  16. def on_publish(client, userdata, mid):
  17. print ("Device sent message")
  18. def on_message(client, userdata, msg):
  19. print("Message received at: " + msg.topic+" with payload: "+str(msg.payload))
  20.  
  21. client = mqtt.Client(client_id=device_id, protocol=mqtt.MQTTv311)
  22.  
  23. client.on_connect = on_connect
  24. client.on_disconnect = on_disconnect
  25. client.on_publish = on_publish
  26. client.on_message = on_message
  27.  
  28. client.username_pw_set(username=iot_hub_name+".azure-devices.net/" + device_id, password=sas_token)
  29.  
  30. client.tls_set(ca_certs=path_to_root_cert, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1, ciphers=None)
  31. client.tls_insecure_set(False)
  32.  
  33. client.connect(iot_hub_name+".azure-devices.net", port=8883 )
  34.  
  35. client.subscribe("iothub/methods/POST/")
  36.  
  37. client.loop_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement