Guest User

Untitled

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