Invalid MQTT publish topic on Google Cloud IoT

0 votes

So, I am trying to publish in this specific topic of Google Cloud IoT: projects/my_project/topics/sm1. I'm using paho-mqtt with a Python client.

Code:

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 = "/projects/my_project/topics/sm1"
project_id   = "my_project"
cloud_region = "us-central1"
registry_id  = "sm1"
device_id    = "sm1"

connflag = False

def error_str(rc):
    """Convert a Paho error to a human readable string."""
    return "Some error occurred. {}: {}".format(rc, mqtt.error_string(rc))

def on_disconnect(unused_client, unused_userdata, rc):
    """Paho callback for when a device disconnects."""
    print("on_disconnect", error_str(rc))

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
    client.on_disconnect = on_disconnect

    print("Connecting to Google IoT Broker...")
    client.connect(mqtt_url, mqtt_port, keepalive=60)
    client.loop_start() 

    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)
            res = client.publish(mqtt_topic, ap_measurement, qos=1)
            if not res.is_published():
               print("Data not published!!")
            else:
               print("ActivePower published: %.2f" % ap_measurement)
        else:
            print("Waiting for connection...")

Error Message:

Invalid MQTT publish topic: projects/my_project/topics/sm1

Output:

Connecting to Google IoT Broker...
Connected with status: 0 -- msg: Connection Accepted.
True
Publishing...
Data not published!!
('on_disconnect', 'Some error occurred. 1: Out of memory.')

Any help is welcome and would be appreciated.

Feb 27, 2019 in IoT (Internet of Things) by Shubham
• 13,490 points
2,258 views

1 answer to this question.

0 votes

It's pretty simple. You have the incorrect topic name.

Your client ID must be:

"projects/{}/locations/{}/registries/{}/devices/{}".format(
  project_id,
  cloud_region,
  registry_id,
  device_id
)

And your topics must then be:

/devices/{}/config
/devices/{}/state
/devices/{}/events
/devices/{}/events/some/other/topic

Hope it works!!

To become a Google certified professional cloud architect, join GCP Training today.

Thanks!

answered Feb 27, 2019 by Upasana
• 8,620 points

Related Questions In IoT (Internet of Things)

0 votes
0 answers

MQTT-Google Cloud pub/sub connection status!

Please help! So, I have a couple of ...READ MORE

Jul 20, 2018 in IoT (Internet of Things) by Bharani
• 4,660 points
826 views
0 votes
1 answer

USB Mobile Broadband Modem on Windows 10 IoT

I was looking for a solution too, ...READ MORE

answered Jul 9, 2018 in IoT (Internet of Things) by anonymous2
• 4,240 points
2,735 views
0 votes
1 answer

Autostart published Application on Windows 10 IoT

It can be done by making changes ...READ MORE

answered Jul 13, 2018 in IoT (Internet of Things) by DataKing99
• 8,250 points
1,794 views
0 votes
1 answer

Send LoRa measures to Fiware IOT agent via MQTT

down vote I dont know if I understood ...READ MORE

answered Jul 13, 2018 in IoT (Internet of Things) by anonymous2
• 4,240 points
1,742 views
0 votes
1 answer

Need to enclose MQTTCLient Instance in try catch block

The instance doesn't need to be surrounded by try/catch, but ...READ MORE

answered Aug 21, 2018 in IoT (Internet of Things) by anonymous2
• 4,240 points
1,249 views
0 votes
1 answer

MQTT protocol connection error

Ok so you need two libraries to ...READ MORE

answered Jul 6, 2018 in IoT (Internet of Things) by anonymous2
• 4,240 points

reshown Jul 6, 2018 by Vardhan 3,067 views
0 votes
1 answer

Mosquitto 1.4.2 Websocket support

down vote In the dir mosquitto-1.4.X edit the ...READ MORE

answered Jul 9, 2018 in IoT (Internet of Things) by anonymous2
• 4,240 points
1,429 views
0 votes
1 answer

IoT request response protocol

Based on your requirement of a light ...READ MORE

answered Jul 13, 2018 in IoT (Internet of Things) by anonymous2
• 4,240 points
1,843 views
0 votes
1 answer
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP