Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

This page explains how gateways can use the MQTT bridge to communicate with ClearBlade IoT Core and publish telemetry events on behalf of bound devices. Before you begin, read Using the MQTT bridge for general information on using the MQTT bridge with ClearBlade IoT Core.Try an end-to-end demo.

Using gateways with the MQTT bridge

1. After you've created and configured the gateway, connect it to ClearBlade IoT Core over the MQTT bridge.

2. Create devices if you haven't already.

3. Optional: Bind the devices to the gateway.

...

When using the MQTT bridge, you only need to bind the devices if they can't generate their JWTs.

4. Optional: Subscribe to the system error topic to get feedback on whether device operations are successful.

5. Attach the devices to the gateway.

6. Use the gateway to relay telemetry, device state, and configuration messages on its devices' behalf

...

.

Gateway messages

After the gateway connects to ClearBlade IoT Core over the MQTT bridge, it can send or receive three message types:

  • Control messages: Attaches a device to the gateway or detaches a device from the gateway. These messages are sent between the gateway and ClearBlade IoT Core. ClearBlade IoT Core accepts control messages only from gateways; if another device type of device attempts to send a control message, ClearBlade IoT Core closes the connection.

  • Messages from gateways and devices: Can be relayed by the gateway on a device’s behalf or sent directly from the gateway.

  • System error messages: When the gateway is subscribed to the MQTT system error topic on the device’s behalf, ClearBlade IoT Core sends error messages whenever the device encounters an error.

...

To enable the gateway to proxy device communications with ClearBlade IoT Core, have the gateway publish a QoS 1 /devices/{device_ID_to_attach}/attach control message over the MQTT bridge.

If you configured the gateway to authenticate devices using the devices' JWTs, the attached message’s payload must include the token in JSON format: { "authorization" : "{JWT_token}" }. Otherwise, ClearBlade IoT Core authenticates the device by checking its gateway’s association.

...

To be notified when a device encounters an error, subscribe the gateway to the MQTT /devices/{gateway_ID}/errors topic using QoS level 0.

These code samples illustrate how to subscribe the gateway to the MQTT/devices/{gateway_ID}/errors topic using QoS level 0:

...

Code Block
// const deviceId = `myDevice`;
// const gatewayId = `mygateway`;
// const registryId = `myRegistry`;
// const projectId = `my-project-123`;
// const region = `us-central1`;
// const algorithm = `RS256`;
// const privateKeyFile = `./rsa_private.pem`;
// const serverCertFile = `./roots.pem`;
/**
 * @see https://clearblade.atlassian.net/wiki/spaces/IC/pages/2210299905/Retargeting+Devices#Production-URL-%2F-URLs for a full URL list of URLs
 */
// const mqttBridgeHostname = `us-central1-mqtt.clearblade.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 ClearBlade MQTT bridge.
const client = mqtt.connect(connectionArgs);

client.on("connect", (success) => {
  if (!success) {
    console.log("Client not connected...");
  } else {
    setTimeout(() => {
      // Subscribe to gateway error topic.
      client.subscribe(`/devices/${gatewayId}/errors`, { qos: 0 });

      attachDevice(deviceId, client);

      setTimeout(() => {
        console.log("Closing connection to MQTT. Goodbye!");
        client.end(true);
      }, clientDuration); // Safely detach the device and close the 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");

  console.log(`message received on error topic ${topic}: ${decodedMessage}`);
});

client.on("packetsend", () => {
  // Logging packet send is very verbose
});

...

Error codes and error handling

Error code

Description

Recommended action

GATEWAY_ATTACHMENT_ERROR

A gateway attachment request failed.

Do not retry without fixing the problem.

GATEWAY_DEVICE_NOT_FOUND

The gateway could not find an attached device to handle an incoming message.

Do not retry without fixing the problem.

GATEWAY_INVALID_MQTT_TOPIC

The gateway could not parse the specified MQTT topic, which was ill-formatted or contained an invalid device ID or name.

Do not retry without fixing the problem.

GATEWAY_UNEXPECTED_PACKET_ID

The gateway could not process the message based on its packet ID. For example, a PUBACK may have contained a packet ID, but nothing awaited the response.

Do not retry without fixing the problem.

GATEWAY_UNEXPECTED_MESSAGE_TYPE

The gateway received unexpected messages, such as unsupported PUBREL, PUBREC, etc.

Do not retry without fixing the problem.

GATEWAY_DETACHMENT_DEVICE_ERROR

The gateway detached a device because of a device error.

Do not retry without fixing the problem.

UNKNOWN

The error is unknown.

Retry using exponential backoff.