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

Listen for configuration messages

Stay organized with collections Save and categorize content based on your preferences.

Listen for configuration messages.

Code sample

Node.js

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

// const deviceId = `myDevice`;
// const gatewayId = `mygateway`;
// const registryId = `myRegistry`;
// const region = `us-central1`;
// const algorithm = `RS256`;
// const privateKeyFile = `./rsa_private.pem`;
// const serverCertFile = `./roots.pem`;
// const mqttBridgeHostname = `mqtt.googleapis.com`;
// const mqttBridgePort = 8883;
// const clientDuration = 60000;

const mqttClientId = `projects/${projectId}/locations/${region}/registries/${registryId}/devices/${gatewayId}`;
console.log(mqttClientId);
const connectionArgs = {
  host: mqttBridgeHostname,
  port: mqttBridgePort,
  clientId: mqttClientId,
  username: 'unused',
  password: createJwt(projectId, privateKeyFile, algorithm),
  protocol: 'mqtts',
  qos: 1,
  secureProtocol: 'TLSv1_2_method',
  ca: [readFileSync(serverCertFile)],
};

// Create a client, and connect to the Google MQTT bridge.
const client = mqtt.connect(connectionArgs);

client.on('connect', success => {
  if (!success) {
    console.log('Client not connected...');
  } else {
    console.log('Client connected: Gateway is listening, attaching device');
    attachDevice(deviceId, client);

    setTimeout(() => {
      // Subscribe to any configuration topics.
      client.subscribe(`/devices/${gatewayId}/config`, {qos: 1});
      client.subscribe(`/devices/${deviceId}/config`, {qos: 1});

      setTimeout(() => {
        detachDevice(deviceId, client);
        console.log('Closing connection to MQTT. Goodbye!');
        client.end(true);
      }, clientDuration); // Safely detach device and close connection.
    }, 5000);
  }
});

client.on('close', () => {
  console.log('Connection closed');
  shouldBackoff = true;
});

client.on('error', err => {
  console.log('error', err);
});

client.on('message', (topic, message) => {
  const decodedMessage = Buffer.from(message, 'base64').toString('ascii');

  if (topic === `/devices/${gatewayId}/errors`) {
    console.log(`message received on error topic: ${decodedMessage}`);
  } else {
    console.log(`message received on topic ${topic}: ${decodedMessage}`);
  }
});

client.on('packetsend', () => {
  // Note: logging packet send is very verbose
});

What's next

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