Google Cloud IoT Core wird am 16. August 2023 eingestellt. Weitere Informationen erhalten Sie von Ihrem Google Cloud-Account-Management-Team.

Auf Konfigurationsmeldungen achten

Auf Konfigurationsmeldungen achten.

Codebeispiel

Node.js

Weitere Informationen finden Sie in der Cloud IoT Core Node.js-Referenzdokumentation.

Für die Authentifizierung bei Cloud IoT Core richten Sie Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

// 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
});

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud-Produkte finden Sie unter Google Cloud-Beispielbrowser.