You can use the bridging service provided by IoT as Bridge SDK to connect a device to IoT Platform and enable communication between the device and IoT Platform. This topic describes how to configure IoT as Bridge SDK to use the basic features, such as device connection and disconnection, and upstream and downstream message transmission.
Obtain IoT as Bridge SDK
IoT Platform provides a demo of IoT as Bridge SDK. For more information, visit alibabacloud-iot-bridge-core-demo.
Flowchart
The following figure shows the flowchart of connecting a device to IoT Platform by using IoT as Bridge SDK.
Deploy a development environment
Deploy a Java development environment and add the following dependency to your Maven project to import IoT as Bridge SDK:
<dependency>
<groupId>com.aliyun.openservices</groupId>
<artifactId>iot-as-bridge-sdk-core</artifactId>
<version>2.4.1</version>
</dependency>
Initialization
Initialize the SDK
Create a BridgeBootstrap object and call the bootstrap() method. This method registers the DownlinkChannelHandler callback with IoT as Bridge SDK to receive downstream messages from IoT Platform.
After 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 downstream 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;
}
});
Configure a bridge
By default, a bridge is configured by using the application.conf configuration file in the src/main/resources/ directory of the Java project. The file format is HOCON, which is a JSON superset.
IoT as Bridge SDK parse the configuration file based on configurations in the typesafe.config file.
You can dynamically register a bridge or directly configure the parameters of a bridge.
For more information about how to dynamically register a device, see the Dynamically register bridges section of the "Use the advanced features" topic. The following table describes the parameters of a bridge.
Parameter
Required
Description
productKey
Yes
The ProductKey of the product to which the bridge belongs.
deviceName
Yes
The DeviceName of the bridge.
deviceSecret
Yes
The DeviceSecret of the bridge.
subDeviceConnectMode
No
The type of the bridge.
If this parameter is set to 3, a large-sized bridge is created. A maximum of 500,000 devices can be connected to the bridge.
If this parameter is not specified, a small-sized bridge is created. A maximum of 1,500 devices can be connected to the bridge.
Large-sized and small-sized 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 endpoint is used to establish a persistent connection between the bridge and IoT Platform over the HTTP/2 protocol.
Endpoint format:
Enterprise Edition instances:
https://${IotInstanceId}.http2.iothub.aliyuncs.com:443
.Replace ${IotInstanceId} with the ID of the instance that you purchased.
For example, if the instance ID is iot-cn-g06kwb****, the endpoint is
https://iot-cn-g06kwb****.http2.iothub.aliyuncs.com:443
.Public instances: The endpoint format for public instances of the new version is different from the endpoint format for public instances of the previous version.
Public instances of the new version use the same endpoint format as Enterprise Edition instances.
Public instances of the previous version:
https://${productKey}.iot-as-http2.${RegionId}.aliyuncs.com:443
.Replace ${productKey} with the ProductKey of the product to which your bridge belongs.
Replace ${RegionId} with the ID of the region in which your IoT Platform service resides. For more information about region IDs, see Regions and Zones.
For example, if the ProductKey of a bridge is a1abcab**** and the public instance resides in the China (Shanghai) region, the endpoint is
https://a1abcab****.iot-as-http2.cn-shanghai.aliyuncs.com:443
.
For more information about IoT Platform instances, see Overview.
authEndpoint
Yes
The endpoint of the device verification service.
Endpoint format:
Enterprise Edition instances:
https://${IotInstanceId}.auth.iothub.aliyuncs.com/auth/bridge
.Replace ${IotInstanceId} with the ID of the instance that you purchased.
For example, if the instance ID is iot-cn-g06kwb****, the endpoint is
https://iot-cn-g06kwb****.auth.iothub.aliyuncs.com/auth/bridge
.Public instances: The endpoint format for public instances of the new version is different from the endpoint format for public instances of the previous version.
Public instances of the new version use the same endpoint format as Enterprise Edition instances.
Public instances of the previous version:
https://iot-auth.${RegionId}.aliyuncs.com/auth/bridge
.Replace ${RegionId} with the ID of the region in which your IoT Platform service resides. For more information about region IDs, see Regions and Zones.
For example, if an instance resides in the China (Shanghai) region, the endpoint is
https://iot-auth.cn-shanghai.aliyuncs.com/auth/bridge
.
The following sample code shows how to configure a small-sized bridge. In this example, an Enterprise Edition instance is used.
// The endpoints of services. http2Endpoint = "https://iot-2w****.http2.iothub.aliyuncs.com:443" authEndpoint = "https://iot-2w****.auth.iothub.aliyuncs.com/auth/bridge" // The parameters of the bridge. productKey = ${bridge-ProductKey-in-Iot-Plaform} deviceName = ${bridge-DeviceName-in-Iot-Plaform} deviceSecret = ${bridge-DeviceSecret-in-Iot-Plaform}
Verify a device and connect the device to IoT Platform
Connect a device to IoT Platform
The following sample code shows how to connect a device to IoT Platform by using IoT as Bridge SDK:
/**
* Verify a 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 a device connects to IoT Platform, the device sends a Session
to the IoT Platform. When IoT Platform sends a downstream message, the Session
is sent to a bridge by using a callback function. The bridge determines the device to which the message is sent by using the originalIdentity field in the Session
.
The Session
includes the optional channel field that contains the information about the device connection. For example, your bridge server is built based on Netty. You can use the channel field to store the channel object that corresponds to the persistent connection of the device. If a downstream message is sent, the bridge can obtain the channel object from the Session
.
IoT as Bridge SDK does not process the data of the channel field. You can use the channel field to store any 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 IoT Platform.
boolean success = uplinkHandler.doOnline(session, originalIdentity);
if (success) {
// If the device is connected to IoT Platform, the bridge accepts subsequent communication requests from the device.
} else {
// If the device fails to connect to IoT Platform, the bridge rejects subsequent communication requests, such as disconnection requests.
}
Configure mappings between device certificates and original device identifiers
By default, the mappings are configured by using the devices.conf configuration file in the src/main/resources/ directory of the Java project. The file format is HOCON, which is a JSON superset.
IoT as Bridge SDK parse the configuration file based on configurations in the typesafe.config file.
You must configure the following parameters in the file:
${device-originalIdentity} {
productKey : ${device-ProductKey-in-Iot-Plaform}
deviceName : ${device-DeviceName-in-Iot-Platform}
deviceSecret : ${device-DeviceSecret-in-Iot-Platform}
}
Parameter | Required | Description |
productKey | Yes | The ProductKey of the product to which the device belongs. |
deviceName | Yes | The DeviceName of the device. |
deviceSecret | Yes | The DeviceSecret of the device. |
Send data from a device to IoT Platform
The following sample code shows how to send data from a device to IoT Platform by using IoT as Bridge SDK:
/**
* Send a message from a device in synchronous mode.
* @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 a device in asynchronous mode.
* @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, a CompletableFuture object 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()));
// Send a message in synchronous mode.
int timeoutSeconds = 3;
boolean success = upLinkHandler.doPublish(originalIdentity, protocolMessage, timeoutSeconds);
// Send a message in asynchronous mode.
upLinkHandler.doPublishAsync(originalIdentity, protocolMessage);
Push data from IoT Platform to a device
When you call the bootstrap() method for a bridge, the DownlinkChannelHandler callback is registered with IoT as Bridge SDK. When IoT as Bridge SDK receives a message from IoT Platform, IoT as Bridge SDK calls the pushToDevice() method in DownlinkChannelHandler.
You can modify the pushToDevice() method to allow the bridge to process the downstream message.
After a device is connected to IoT Platform by using IoT as Bridge SDK, the device can receive downstream messages without the need to subscribe to topics.
Do not implement a time-consuming logic in the pushToDevice() method. Otherwise, the thread that receives downstream messages is 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, the application.conf and devices.conf files are used.
BridgeBootstrap bridgeBootstrap = new BridgeBootstrap();
bridgeBootstrap.bootstrap(new DownlinkChannelHandler() {
@Override
public boolean pushToDevice(Session session, String topic, byte[] payload) {
// Receive downstream 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 | The Session that you specified when you call the doOnline method. 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 items describe the scenarios in which device disconnection occurs:
If a small-sized bridge is disconnected from IoT Platform, all devices that are connected to the bridge are automatically disconnected from IoT Platform.
If a large-sized 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 device by calling the doOffline method.
The status of a device indicates whether the device is connected to the bridge. The bridge submits the status information of devices to IoT Platform. If the bridge cannot submit the status information of a device to IoT Platform, the status that is displayed in the IoT Platform console remains unchanged.
For example, a device is connected to IoT Platform by using a bridge and the status of the device is online. If the bridge is disconnected from IoT Platform, the bridge cannot submit the status information of the device to IoT Platform. As a result, the status of the device remains online.
If small-sized and large-sized bridges are connected to IoT Platform, the bridges can send a request to disconnect a device from IoT Platform.
The following sample code 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 closes and re-establishes a connection to IoT Platform
A bridge can use the BridgeBootstrap object and call the disconnectBridge and reconnectBridge methods to close and re-establish a connection to IoT Platform.
The reconnectBridge method is used for reconnection and cannot be used for first connection.
Sample code:
// Disconnect a bridge from IoT Platform.
bridgeBootstrap.disconnectBridge();
Thread.sleep(1000);
// Check whether the bridge is connected to IoT Platform.
boolean isConnected = bridgeBootstrap.isBridgeConnected();
// Re-establish a connection to IoT Platform.
bridgeBootstrap.reconnectBridge();
Thread.sleep(1000);
isConnected = bridgeBootstrap.isBridgeConnected();