Google Cloud IoT Core is being retired on August 16, 2023. Contact your Google Cloud account team for more information.

Attach a device

Attach a device to a gateway.

Code sample

Go

For more information, see the Cloud IoT Core Go API reference documentation.

To authenticate to Cloud IoT Core, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


// attachDevice attaches a device to a gateway.
func attachDevice(deviceID string, client mqtt.Client, jwt string) error {
	attachTopic := fmt.Sprintf("/devices/%s/attach", deviceID)
	fmt.Printf("Attaching device: %s\n", attachTopic)

	attachPayload := "{}"
	if jwt != "" {
		attachPayload = fmt.Sprintf("{ 'authorization' : %s }", jwt)
	}

	if token := client.Publish(attachTopic, 1, false, attachPayload); token.Wait() && token.Error() != nil {
		return token.Error()
	}
	return nil
}

Java

For more information, see the Cloud IoT Core Java API reference documentation.

To authenticate to Cloud IoT Core, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

final String attachTopic = String.format("/devices/%s/attach", deviceId);
System.out.println(String.format("Attaching: %s", attachTopic));
String attachPayload = "{}";
MqttMessage message = new MqttMessage(attachPayload.getBytes(StandardCharsets.UTF_8.name()));
message.setQos(1);
client.publish(attachTopic, message);

Python

For more information, see the Cloud IoT Core Python API reference documentation.

To authenticate to Cloud IoT Core, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

attach_topic = "/devices/{}/attach".format(device_id)
attach_payload = '{{"authorization" : "{}"}}'.format(auth)
client.publish(attach_topic, attach_payload, qos=1)

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.