2
votes

I am using a Python client with paho-mqtt to publish in this specific topic of Google Cloud IoT: projects/my_project/topics/sm1. My code is below, based on examples of the Google IoT documentation:

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

When I run, the client connect but does not publish. At Google IoT Console, I can see the following error message:

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

And here is the 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.')

It is really strange, because the topic is there, created, and have a subscription associated to it!

Any help will be appreciated. I already read the following documentation and code:

2

2 Answers

5
votes

You have the incorrect topic name.

It's confusing (I just hit this too).

The client ID (as you have) must be:

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

The topics must then be of the form:

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

As stated in the comment of @ptone:

In cloud iot core, MQTT topics are many-to-one with Cloud PubSub topics. For security - devices may only publish to MQTT topics prefixed with their device namespace. You can then match sub-topics to other Cloud PubSub topics as noted here, but only up to 10. This is not designed to allow a 1:1 mapping device to PubSub Topic.

0
votes

My python code works when I change the mqtt_topic from events to state. In this example, I am trying to upload the current temperature and humidity from my device to Google IoT Core.

  ...
  data =  {'temp': temperature, 'humid': humidity}
  device_id = 'freedgePrototype'
  topic = 'state'

  mqtt_topic = '/devices/{}/{}'.format(device_id, topic)
  payload = json.dumps(data)
  print('Publishing message  {}'.format(payload))

  client.publish(mqtt_topic, payload, qos=1)

And the result would look like this.

enter image description here