Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import paho.mqtt.client as mqtt
- import ssl, random, jwt_maker
- from time import sleep
- root_ca = './../roots.pem'
- public_crt = './../my_cert.pem'
- private_key = './../my_pr.pem'
- mqtt_url = "mqtt.googleapis.com"
- mqtt_port = 8883
- mqtt_topic = "/devices/sm1/events"
- project_id = "myprojectname"
- cloud_region = "us-central1"
- registry_id = "sm1"
- device_id = "sm1"
- connflag = False
- def on_connect(client, userdata, flags, response_code):
- global connflag
- connflag = True
- print("Connected with status: {0}".format(response_code))
- def on_publish(client, userdata, mid):
- print("User data: {0} -- mid: {1}".format(userdata, mid))
- #client.disconnect()
- if __name__ == "__main__":
- client = mqtt.Client("projects/{}/locations/{}/registries/{}/devices/{}".format(
- project_id,
- cloud_region,
- registry_id,
- device_id))
- client.username_pw_set(username='unused',
- password=jwt_maker.create_jwt(project_id,
- private_key,
- algorithm="RS256"))
- client.tls_set(root_ca,
- certfile = public_crt,
- keyfile = private_key,
- cert_reqs = ssl.CERT_REQUIRED,
- tls_version = ssl.PROTOCOL_TLSv1_2,
- ciphers = None)
- client.on_connect = on_connect
- client.on_publish = on_publish
- print("Connecting to Google IoT Broker...")
- client.connect(mqtt_url, mqtt_port, keepalive=60)
- client.loop()
- while True:
- sleep(0.5)
- print connflag
- if connflag == True:
- print("Publishing...")
- ap_measurement = random.uniform(25.0, 150.0)
- #payload = "sm1/sm1-payload-{}".format(ap_measurement)
- client.publish(mqtt_topic, ap_measurement, qos=1)
- print("Payload published: %.2f" % ap_measurement)
- else:
- print("Waiting for connection...")
- mqtt_topic = "/devices/your_device/events"
- mqtt_topic = "projects/your_project_here/topics/your_topic_here"
Add Comment
Please, Sign In to add comment