Attach a device

Attach a device to a gateway.

Code sample


public static object AttachDevice(MqttClient client, string deviceId, string auth)
    var attachTopic = $"/devices/{deviceId}/attach";
    Console.WriteLine("Attaching: {0}", attachTopic);
    var BinaryData = Encoding.UTF8.GetBytes(auth);
    client.Publish(attachTopic, BinaryData, MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, true);

    Console.WriteLine("Waiting for device to attach.");
    return 0;


// 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


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(;
client.publish(attachTopic, message);


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