Guest User

Untitled

a guest
Apr 18th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. import paho.mqtt.client as mqtt
  2. import ssl, random, jwt_maker
  3. from time import sleep
  4.  
  5. root_ca = './../roots.pem'
  6. public_crt = './../my_cert.pem'
  7. private_key = './../my_pr.pem'
  8.  
  9. mqtt_url = "mqtt.googleapis.com"
  10. mqtt_port = 8883
  11. mqtt_topic = "/devices/sm1/events"
  12. project_id = "myprojectname"
  13. cloud_region = "us-central1"
  14. registry_id = "sm1"
  15. device_id = "sm1"
  16.  
  17. connflag = False
  18.  
  19. def on_connect(client, userdata, flags, response_code):
  20. global connflag
  21. connflag = True
  22. print("Connected with status: {0}".format(response_code))
  23.  
  24. def on_publish(client, userdata, mid):
  25. print("User data: {0} -- mid: {1}".format(userdata, mid))
  26. #client.disconnect()
  27.  
  28. if __name__ == "__main__":
  29.  
  30. client = mqtt.Client("projects/{}/locations/{}/registries/{}/devices/{}".format(
  31. project_id,
  32. cloud_region,
  33. registry_id,
  34. device_id))
  35.  
  36. client.username_pw_set(username='unused',
  37. password=jwt_maker.create_jwt(project_id,
  38. private_key,
  39. algorithm="RS256"))
  40.  
  41. client.tls_set(root_ca,
  42. certfile = public_crt,
  43. keyfile = private_key,
  44. cert_reqs = ssl.CERT_REQUIRED,
  45. tls_version = ssl.PROTOCOL_TLSv1_2,
  46. ciphers = None)
  47.  
  48. client.on_connect = on_connect
  49. client.on_publish = on_publish
  50.  
  51. print("Connecting to Google IoT Broker...")
  52. client.connect(mqtt_url, mqtt_port, keepalive=60)
  53. client.loop()
  54.  
  55. while True:
  56. sleep(0.5)
  57. print connflag
  58. if connflag == True:
  59. print("Publishing...")
  60. ap_measurement = random.uniform(25.0, 150.0)
  61. #payload = "sm1/sm1-payload-{}".format(ap_measurement)
  62. client.publish(mqtt_topic, ap_measurement, qos=1)
  63. print("Payload published: %.2f" % ap_measurement)
  64. else:
  65. print("Waiting for connection...")
  66.  
  67. mqtt_topic = "/devices/your_device/events"
  68.  
  69. mqtt_topic = "projects/your_project_here/topics/your_topic_here"
Add Comment
Please, Sign In to add comment