Your device can connect to and communicate with Alibaba Cloud IoT Platform by using the bridging service that is supported by the IoT as Bridge SDK. This article describes how to configure the IoT as Bridge SDK to use the basic features. These features include device connection and disconnection, and upstream and downstream message transmission.

For more information, see IoT as Bridge SDK.

Process

The following figure shows the process of connecting a device to IoT Platform by using the IoT as Bridge SDK.

Bridge

Deploy a development environment

Deploy a development environment to use the SDK for Java and add the following Maven dependency to your project to import the IoT as Bridge SDK.

<dependency>
  <groupId>com.aliyun.openservices</groupId>
  <artifactId>iot-as-bridge-sdk-core</artifactId>
  <version>2.3.5</version>
</dependency>

Initialize the SDK

  • Initialize the SDK.

    Create a BridgeBootstrap object and call the bootstrap() method. When you call this method, the IoT as Bridge SDK registers the DownlinkChannelHandler callback to receive downstream messages from IoT Platform.

    After the IoT as Bridge SDK is initialized, the SDK reads the bridge information and sends a connection request to IoT Platform for the bridge.

    Sample code:

    BridgeBootstrap bridgeBootstrap = new BridgeBootstrap();
    bridgeBootstrap.bootstrap(new DownlinkChannelHandler() {
        @Override
        public boolean pushToDevice(Session session, String topic, byte[] payload) {
            // Receive messages from IoT Platform.
            String content = new String(bytes);
            log.info("Get DownLink message, session:{}, {}, {}", session, topic, content);
            return true;
        }
    
        @Override
        public boolean broadcast(String topic, byte[] payload) {
            return false;
        }
    });
  • Specify the bridge information.

    By default, a bridge is configured by using a configuration file. The application.conf configuration file is in the src/main/resources/ directory of the Java project. The file format is HOCON (a JSON superset).

    The IoT as Bridge SDK uses the typesafe.config file to parse the configuration file.

    You must dynamically register a bridge device and specify the parameters of the bridge device.

    For more information about how to dynamically register bridge devices, see Dynamically register bridge devices.

    The following table describes the parameters of the bridge device.

    Parameter Required Description
    productKey Yes The ProductKey of the product to which the bridge device belongs.
    deviceName Yes The DeviceName of the bridge device.
    deviceSecret Yes The DeviceSecret of the bridge device.
    subDeviceConnectMode No The mode that devices use to connect with the bridge.
    • If this parameter is set to 3, a large-size bridge is created. A maximum of 500,000 devices can connect with the bridge.
    • If this parameter is not specified, a small-size bridge is created. A maximum of 15,00 devices can connect with the bridge.
    Large-size bridges and small-size bridges use different policies to disconnect devices. For more information, see Disconnect a device from IoT Platform.
    http2Endpoint Yes The endpoint of the HTTP/2 gateway. The bridge and IoT Platform establish a persistent connection over the HTTP/2 protocol.

    Endpoint format:

    • Public instance: https://${productKey}.iot-as-http2. ${RegionId}.aliyuncs.com:443.

      Replace ${productKey} with the ProductKey of the product to which your bridge device belongs.

      Replace ${RegionId} with the ID of the region where you purchased the IoT Platform service. For information about region IDs, see Regions and zones.

      For example, if the ProductKey of a bridge device is a1abcab**** and the IoT Platform service is purchased in the China (Shanghai) region, the endpoint is https://a1abcab****.iot-as-http2.cn-shanghai.aliyuncs.com:443.

    • Enterprise Edition instance: https://${IotInstanceId}.http2.iothub.aliyuncs.com:443.

      Replace ${IotInstanceId} with the ID of the purchased instance.

      For example, if the instance ID is iot-cn-g06kwb****, the endpoint is https://iot-cn-g06kwb****.http2.iothub.aliyuncs.com:443.

    authEndpoint Yes The endpoint of the device authentication server.

    Endpoint format:

    • Public instance: https://iot-auth. .${RegionId}.aliyuncs.com/auth/bridge.

      Replace ${RegionId} with the ID of the region where you purchased the IoT Platform service. For information about region IDs, see Regions and zones.

      For example, if the IoT Platform service is purchased in the China (Shanghai) region, the endpoint is https://iot-auth.cn-shanghai.aliyuncs.com/auth/bridge.

    • Enterprise Edition instance: https://${IotInstanceId}.auth.iothub.aliyuncs.com/auth/bridge.

      Replace ${IotInstanceId} with the ID of the purchased instance.

      For example, if the instance ID is iot-cn-g06kwb****, the endpoint is https://iot-cn-g06kwb****.auth.iothub.aliyuncs.com/auth/bridge.

    The following example shows how to configure a small-size bridge device. The public instance is used in the example.

    # The endpoint of the server.
    http2Endpoint = "https://a1tN7***.iot-as-http2.cn-shanghai.aliyuncs.com:443"
    authEndpoint = "https://iot-auth.cn-shanghai.aliyuncs.com/auth/bridge"
    
    # The information of the bridge device.
    productKey = ${bridge-ProductKey-in-Iot-Plaform}
    deviceName = ${bridge-DeviceName-in-Iot-Plaform}
    deviceSecret = ${bridge-DeviceSecret-in-Iot-Plaform}

Authenticate a device and connect the device to IoT Platform

  • Connect a device to the bridge.

    The following example shows how to connect a device to the bridge by using the IoT as Bridge SDK:

    /**
     * Authenticate the device.
     * @param newSession: the device session information that is returned in a downstream callback.
     * @param originalIdentity: the original identifier of the device.
     * @return
     */
    public boolean doOnline(Session newSession, String originalIdentity);

    When the device is connected to the bridge, the device must pass the Session parameter. The Session parameter is returned to the bridge by using a callback function of a downstream message. The bridge determines the device that sends the message by using the originalIdentity field in the Session parameter.

    The Session parameter includes the optional channel field that carries the information about the device connection. For example, your bridge server is built based on Netty. You can use the channel field to carry the channel object that corresponds to the persistent connection of the device. When a downstream message is sent, the bridge can obtain the channel object from the Session parameter.

    The IoT as Bridge SDK does not process the data of the channel field. You can also use the channel field to carry the device-related information.

    Sample code:

    UplinkChannelHandler uplinkHandler = new UplinkChannelHandler();
    // Create a session.
    Object channel = new Object();
    Session session = Session.newInstance(originalIdentity, channel);
    // Connect a device to the bridge.
    boolean success = uplinkHandler.doOnline(session, originalIdentity);
    if (success) {
        // If the device is connected, the bridge accepts subsequent communication requests from the device.
    } else {
        // If the device connection fails, the bridge rejects subsequent communication requests, such as disconnection requests.
    }
  • You must configure the mappings between device certificates and original device identifiers.

    By default, you can configure the settings by using a configuration file. The application.conf configuration file is in the src/main/resources/ directory of the Java project. The file format is HOCON (a JSON superset).

    The IoT as Bridge SDK uses the typesafe.config file to parse the configuration file.

    You must specify the following parameters in the file:

    ${device-originalIdentity} {
      productKey : ${device-ProductKey-in-Iot-Plaform}
      deviceName : ${device-DeviceName-in-Iot-Platform}
      deviceSecret : ${device-DeviceSceret-in-Iot-Platform}
    }
    Parameter Required Description
    productKey Yes The ProductKey of the product to which the device belongs.
    deviceName Yes The name of the device.
    deviceSecret Yes The DeviceSecret of the device.

Send data from a device to IoT Platform

The following example shows how to send data from a device to IoT Platform by using the IoT as Bridge SDK:

/**
 * Send a message from the device by using a synchronous call.
 * @param originalIdentity: the original identifier of the device.
 * @param protocolMsg: the message to be sent, including the topic, payload, and quality of service (QoS) information.
 * @param timeout: the timeout period. Unit: seconds.
 * @return: indicates whether the message is sent within the timeout period.
 */
boolean doPublish(String originalIdentity, ProtocolMessage protocolMsg, int timeout);
/**
 * Send a message from the device by using an asynchronous call.
 * @param originalIdentity: the original identifier of the device.
 * @param protocolMsg: the message to be sent, including the topic, payload, and QoS information.
 * @return: After this method is called, the CompletableFuture parameter is immediately returned and available for subsequent use.
 */
CompletableFuture<ProtocolMessage> doPublishAsync(String originalIdentity, 
                                                  ProtocolMessage protocolMsg);

Sample code:

DeviceIdentity deviceIdentity = 
    ConfigFactory.getDeviceConfigManager().getDeviceIdentity(originalIdentity);
ProtocolMessage protocolMessage = new ProtocolMessage();
protocolMessage.setPayload("Hello world".getBytes());
protocolMessage.setQos(0);
protocolMessage.setTopic(String.format("/%s/%s/update", 
        deviceIdentity.getProductKey(), deviceIdentity.getDeviceName()));
// Synchronous sending.
int timeoutSeconds = 3;
boolean success = upLinkHandler.doPublish(originalIdentity, protocolMessage, timeoutSeconds);
// Asynchronous sending.
upLinkHandler.doPublishAsync(originalIdentity, protocolMessage);

Push data from IoT Platform to a device

When the bridge calls the bootstrap() method, the IoT as Bridge SDK registers the DownlinkChannelHandler callback. When the IoT as Bridge SDK receives a message from IoT Platform, it calls the pushToDevice() method in DownlinkChannelHandler.

You can modify the pushToDevice() method to enable the bridge to process the downstream message.

Note
  • After a device is connected to IoT Platform by using the IoT as Bridge SDK, the device can receive downstream messages without subscribing to topics.
  • Do not implement a time-consuming logic in the pushToDevice() method. Otherwise, the thread that receives downstream messages are blocked. If a time-consuming logic or I/O logic is required, implement the logic in an asynchronous manner. For example, if a bridge uses a persistent connection to forward downstream messages to a device, you can implement the logic in an asynchronous manner.

Sample code:

private static ExecutorService executorService  = new ThreadPoolExecutor(
    Runtime.getRuntime().availableProcessors(),
    Runtime.getRuntime().availableProcessors() * 2,
    60, TimeUnit.SECONDS,
    new LinkedBlockingQueue<>(1000),
    new ThreadFactoryBuilder().setDaemon(true).setNameFormat("bridge-downlink-handle-%d").build(),
    new ThreadPoolExecutor.AbortPolicy());
public static void main(String args[]) {
    // By default, application.conf and devices.conf are used.
    bridgeBootstrap = new BridgeBootstrap();
    bridgeBootstrap.bootstrap(new DownlinkChannelHandler() {
        @Override
        public boolean pushToDevice(Session session, String topic, byte[] payload) {
            // Receive messages from IoT Platform.
            executorService.submit(() -> handleDownLinkMessage(session, topic, payload));
            return true;
        }
        @Override
        public boolean broadcast(String s, byte[] bytes) {
            return false;
        }
    });
}
private static void handleDownLinkMessage(Session session, String topic, byte[] payload) {
    String content = new String(payload);
    log.info("Get DownLink message, session:{}, topic:{}, content:{}", session, topic, content);
    Object channel = session.getChannel();
    String originalIdentity = session.getOriginalIdentity();
}
Parameter Description
session When you call the doOnline operation, pass the session parameter. This parameter is used to determine the device to which the downstream message is sent.
topic The topic of the downstream message.
payload The message body of the downstream message. The message body is in the binary format.

Disconnect a device from IoT Platform

The following points describe the scenarios of device disconnection:

  • If a small-size bridge is disconnected from IoT Platform, all devices that are connected to the bridge are automatically disconnected from IoT Platform.
  • If a large-size bridge is disconnected from IoT Platform, the devices that are connected to the bridge are not disconnected from IoT Platform. After the bridge is reconnected to IoT Platform, you can update the status of a sub-device by calling the doOffline operation.

    The status of a sub-device indicates whether the sub-device is connected to a gateway. The gateway reports the status of sub-devices to IoT Platform. If the gateway cannot report the status of the sub-device to IoT Platform, the status that is displayed in the IoT Platform console remains unchanged.

    Assume that a sub-device is connected to IoT Platform by using a gateway and the status of the sub-device is online. If the gateway is disconnected from IoT Platform, the gateway cannot report the status of the sub-device to IoT Platform. Therefore, the status of the sub-device remains online.

  • If small-size and large-size bridges are connected to IoT Platform, they can send a request to disconnect a device from IoT Platform.

    The following example shows how to send a disconnection request:

    /**
     * Send a request to disconnect a device from IoT Platform.
     * @param originalIdentity: the original identifier of the device.
     * @return: indicates whether the disconnection request is sent.
     */
    boolean doOffline(String originalIdentity);

    Sample code:

    upLinkHandler.doOffline(originalIdentity);

A bridge ends and re-establishes a connection with IoT Platform

A bridge can use the BridgeBootstrap object and call the disconnectBridge and reconnectBridge operations to end and re-establish a connection with IoT Platform.

Note The reconnectBridge operation is used for reconnection and cannot be used for first connection.

Sample code:

// End the connection with IoT Platform.
bridgeBootstrap.disconnectBridge();
Thread.sleep(1000);
// Check whether the bridge is connected to IoT Platform.
boolean isConnected = bridgeBootstrap.isBridgeConnected();

// Re-establish a connection with IoT Platform.
bridgeBootstrap.reconnectBridge();
Thread.sleep(1000);
isConnected = bridgeBootstrap.isBridgeConnected();