Search code examples
python-2.7mqttpahogoogle-cloud-iot

What's the difference between the two ways of creating client in Google Cloud IoT Core?


For making a client in Google Cloud IoT Core, I initially just use:

client = mqtt.Client(client_id=('projects/{}/locations/{}/registries/{}/devices/{}'
                    .format(args.project_id, args.cloud_region,
                            args.registry_id, args.device_id)))

Though, in many documentation code samples, I saw that this and another way given below were used:

client = get_client(service_account_json)

To be able to use the above, I had to generate another JSON key. Not able to understand what's the essential difference between the two clients. Also, I had used the second way to obtain state of a device.


Solution

  • These are from two different APIs. One is the client side (there is no API per se, it's just the method devices [clients] use to connect to IoT Core) and the other is for the IoT Core administration side of things.

    The MQTT bridge is used to connect a device to IoT Core in order to send the telemetry data. That's the mqtt client code in your first snippet. There's no API for devices to connect to send telemetry, IoT Core is just an MQTT (or HTTP) endpoint. In the above case, you've probably also got code in there to do the client.publish to mqtt.googleapis.com:8883. That connects the device to IoT Core via MQTT.

    The second one is what you need to use in order to call the IoT Core Admin SDK. For example if you had a script that wanted to update the config on a device controlled by IoT Core.

    The JSON key you had to generate is to authenticate with the API service. There's details about the authentication piece here. In the device using MQTT case, there's no API auth, it's using the JWT to authenticate in that instance, but for the admin SDK, you need to authenticate with the Cloud Project in order to issue those sorts of admin commands.

    So TL;DR, in your first snippet, that's an MQTT client you're creating. In the second snippet, it's a Google Cloud Project (GCP) client. First is for devices sending data to IoT Core, second is for issuing administration type calls to GCP.