Google Cloud IoT - How to connect and publish to specific topic with MQTT?

1,260 views
Skip to first unread message

Dalton Cezane

unread,
Apr 18, 2018, 1:06:09 PM4/18/18
to Google Cloud Pub/Sub Discussions
Hello.

I am trying to connect a Python client to a pub/sub topic. I am using paho-mqtt. My code is below, based on examples of the Google IoT documentation, which is not so clear:

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...")

When I run, this is the output:

Connecting to Google IoT Broker...
False
Waiting for connection...
False
Waiting for connection...

Any help? I already read the following documentation and code:

This problem is also described at StackOverflow: https://stackoverflow.com/questions/49904705/google-cloud-iot-how-to-connect-and-publish-to-specific-topic-with-mqtt
Thank you in advance.

Dalton Cézane

unread,
Apr 18, 2018, 3:47:47 PM4/18/18
to Google Cloud Pub/Sub Discussions
I got success on the connect operation, just changing the "client.loop()" to "client.start_loop()". But now I am not able to publish to my specific topic, as described here:
https://stackoverflow.com/questions/49907529/google-cloud-iot-invalid-mqtt-publish-topic

The Google IoT Console presents the following message: "Invalid MQTT publish topic: projects/my_project/topics/sm1".

Any help?
Thank you.

--
You received this message because you are subscribed to the Google Groups "Google Cloud Pub/Sub Discussions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cloud-pubsub-discuss+unsub...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cloud-pubsub-discuss/e6f7dbc8-6a58-4a5a-a588-6a8a86c92e4d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
=======================================================
Dalton Cézane
Doutorando/Mestre/Especialista/Bacharel em Ciência da Computação (UFCG)
MBA em Gerenciamento de Projetos (Anglo Americano)
Técnico em Informática (ETER)

Katayoon (Cloud Platform Support)

unread,
Apr 18, 2018, 6:43:39 PM4/18/18
to Google Cloud Pub/Sub Discussions
I should note that Google Groups are reserved for general product discussions and are not for technical questions. For further technical support I recommend to work with the duplicate thread you have created in Stack Overflow.
Reply all
Reply to author
Forward
0 new messages