Advanced usage

更新时间:
复制 MD 格式

This topic describes how to use the advanced features of the cloud-to-cloud software development kit (SDK). These features include customizing configuration file paths, configuring the automatic creation of bridge devices, and calling encapsulated SDK interfaces to report Thing Specification Language (TSL) model data, batch report device properties and events, set properties, and invoke services.

Custom configuration management

By default, the bridge configuration file is read from application.conf, and the device certificate mapping file is read from devices.conf.

The cloud-to-cloud SDK provides a custom configuration feature. Before you call the bootstrap method, you can call the ConfigFactory.init method to customize the path of the configuration file and implement the corresponding interface for your custom instance.

Important

To use custom configuration management, you must implement the getDeviceIdentity and getOriginalIdentity methods.

Example code:

private static DeviceConfigManager selfDefineDeviceConfigManager = new DeviceConfigManager() {
    @Override
    public DeviceIdentity getDeviceIdentity(String originalIdentity) {
        // Return device information based on the originalIdentity.
        return devicesMap.get(originalIdentity);
    }

    @Override
    public String getOriginalIdentity(String productKey, String deviceName) {
        // Return the originalIdentity based on the device information.
        return null;
    }
};
BridgeBootstrap bridgeBootstrap = new BridgeBootstrap();
ConfigFactory.init(ConfigFactory.getBridgeConfigManager("application-self-define.conf"),selfDefineDeviceConfigManager);
bridgeBootstrap.bootstrap();

Dynamic creation of a bridge device

If you deploy a bridge application on multiple servers, specifying a different bridge device for each bridge server can be complicated. To solve this issue, you can configure the bridge configuration file application.conf to automatically create bridge devices.

In the configuration file, pass the productKey and popClientProfile parameters. The cloud-to-cloud SDK then calls an IoT Platform API to create a bridge device. The device name is set to the MAC address of the server.

Note
  • To automatically create a bridge device, you only need to modify the bridge configuration file. The code for the call is the same as in Basic usage.

  • All parameters for popClientProfile must be fully configured. If the current MAC address is already used as a device name, that device is used as the bridge device.

  • The deviceName and deviceSecret parameters must be empty. If bridge device information is already specified, a device is not automatically created.

  • Use a dedicated test device to debug the program. Do not debug on your local machine because this may affect the production environment.

    If you debug the program on multiple local PCs, the MAC address of each machine is registered as a bridge. All devices in the devices.conf file are then associated with that bridge.

Table 1. Configuration parameters

Parameter

Required

Description

productKey

Yes

The ProductKey of the product to which the bridge belongs.

subDeviceConnectMode

No

The mode for attaching devices to 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.

The unpublishing policies for large and small bridges are different. For more information, see Device unpublishing.

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.

popClientProfile

Yes

If you configure this parameter, the cloud-to-cloud SDK calls an Alibaba Cloud IoT Platform API to automatically create a bridge device.

For parameter details, see the popClientProfile table below.

Table 2. popClientProfile

Parameter

Required

Description

accessKey

Yes

The AccessKey ID of your Alibaba Cloud account.

In the IoT Platform console, move the mouse pointer over your profile picture and click AccessKey Management to create or view an AccessKey.

accessSecret

Yes

The AccessKey secret of your Alibaba Cloud account.

name

Yes

The ID of the region where the bridge device will be created.

For information about how to specify a region, see Regions and zones.

region

Yes

product

Yes

The product name. This is fixed as Iot.

endpoint

Yes

The endpoint for calling the API in the specified region. The structure is iot.${RegionId}.aliyuncs.com.

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, the endpoint for the China (Shanghai) region is iot.cn-shanghai.aliyuncs.com.

The following code provides an example of the configuration for automatically creating a bridge device for an Enterprise instance:

// Service endpoints
http2Endpoint = "https://${IotInstanceId}.http2.iothub.aliyuncs.com:443"
authEndpoint = "https://${IotInstanceId}.auth.iothub.aliyuncs.com/auth/bridge"

// Bridge device information
productKey = ${YourProductKey}

popClientProfile = {
    accessKey = ${YourAliyunAccessKey}
    accessSecret = ${YourAliyunAccessSecret}
    name = cn-shanghai
    region = cn-shanghai
    product = Iot
    endpoint = iot.cn-shanghai.aliyuncs.com
}

Call TSL model data reporting interfaces

The cloud-to-cloud SDK encapsulates several data reporting interfaces. These include the reportProperty interface for reporting properties, the fireEvent interface for reporting events, and the updateDeviceTag interface for updating device tags. You can use these interfaces to report device messages to IoT Platform.

Note
  • Before you call reportProperty and fireEvent to report property values and events, you must first define the properties and events. On the Product Details page for the device's product in the IoT Platform console, go to the Define Features tab. For more information, see Add a TSL model feature.

  • When you call the updateDeviceTag interface to report a device tag, if the tag already exists on the device's Device Details page in the IoT Platform console, the tag value is updated. Otherwise, a new tag is created.

Example call:

TslUplinkHandler tslUplinkHandler = new TslUplinkHandler();
// Report a property.
// The testProp property is defined.
String requestId = String.valueOf(random.nextInt(1000));
// Report the property without a timestamp.
tslUplinkHandler.reportProperty(requestId, originalIdentity, "testProp", random.nextInt(100));
// Report the property with a timestamp.
//tslUplinkHandler.reportProperty(requestId, originalIdentity, "testProp", random.nextInt(100), System.currentTimeMillis());

// Report an event.
// The testEvent event is defined.
requestId = String.valueOf(random.nextInt(1000));
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("testEventParam", 123);
// Report the event without a timestamp.
tslUplinkHandler.fireEvent(originalIdentity, "testEvent", ThingEventTypes.INFO, params);
// Report the event with a timestamp.
//tslUplinkHandler.fireEvent(originalIdentity, "testEvent", ThingEventTypes.INFO, params, System.currentTimeMillis());

// Report a device tag.
// The device tag key is defined as testDeviceTag.
requestId = String.valueOf(random.nextInt(1000));
tslUplinkHandler.updateDeviceTag(requestId, originalIdentity, "testDeviceTag", String.valueOf(random.nextInt(1000)));

The parameters in the preceding example are described as follows.

Parameter

Description

requestId

The ID of the request message.

originalIdentity

The original identity of the device.

testProp

The identifier of the property. In this example, the product's feature property identifier is defined as testProp. The value of this property is reported.

random.nextInt(100)

The reported property value. You can set the value range when you define the property. In this example, random.nextInt(100) gets a random integer value less than 100.

testEvent

The identifier of the event. In this example, the product's feature event identifier is defined as testEvent. This event is reported.

ThingEventTypes.INFO

The event type. ThingEventTypes indicates the event type, and INFO indicates that the event type is INFO.

In this example, when the testEvent event was defined for the product, the event type was set to INFO.

If the event type is defined as ERROR, this parameter is ThingEventTypes.ERROR.

params

The output parameters of the event. The identifier, data type, value range, and other details of the output parameters are defined when the event is defined. In this example, the identifier of the output parameter for the reported event is testEventParam, and the parameter value is 123.

testDeviceTag

The device tag key. This is a string. In this example, the key is testDeviceTag. When you use this, set the key based on the device tag key specifications and your requirements. For more information, see Device tags.

String.valueOf(random.nextInt(1000))

The device tag value. This is a string. In this example, String.valueOf(random.nextInt(1000)) gets a random value less than 1000. When you use this, set the value based on the device tag value specifications and your requirements. For more information, see Device tags.

System.currentTimeMillis()

Gets the current system time in milliseconds.

Call batch reporting interfaces for device properties and events

The cloud-to-cloud SDK encapsulates a batch data reporting interface. To use this interface, create a BatchPostEventPropertyMessage object instance. Then, chain calls to the addProperty and addEvent methods to add property and event data. Finally, use TslUplinkHandler to call the BatchPostEventPropertyMessage object instance to implement batch reporting of device data.

Note

Before you call reportProperty and fireEvent to report property values and events, you must first define the properties and events. On the Product Details page for the device's product in the IoT Platform console, go to the Define Features tab. For more information, see Add a TSL model feature.

Example call:

TslUplinkHandler tslUplinkHandler = new TslUplinkHandler();
// Batch report properties and events.
String requestId = String.valueOf(random.nextInt(1000));
long startTime = System.currentTimeMillis() - 3000;

// Construct the message for batch reporting.
BatchPostEventPropertyMessage batchPostEventPropertyMessage = new BatchPostEventPropertyMessage();
Map<String, Object> aiEventParams = new HashMap<>();
aiEventParams.put("EventContent", "hello world");
batchPostEventPropertyMessage
    .addProperty("PowerConsumption", 1000, startTime)
    .addProperty("PowerConsumption", 123, startTime + 1000)
    .addProperty("LightAdjustLevel", 23, startTime)
    .addProperty("LightAdjustLevel", 44, startTime + 1000)
    .addProperty("LightAdjustLevel", 47, startTime + 2000)
    .addEvent("AIEvent", aiEventParams, startTime);
batchPostEventPropertyMessage.setId(requestId);

// Initiate the report.
tslUplinkHandler.batchPostEventPropertyMessage(originalIdentity, batchPostEventPropertyMessage);

The parameters in the preceding example are described as follows.

Parameter

Description

requestId

The ID of the request message.

startTime

The timestamp for reporting properties and events. The type is UTC time in milliseconds. You can customize this as needed.

aiEventParams

The specific information for the reported event.

PowerConsumption

The identifier of the property. In this example, the product's feature property identifiers are defined as PowerConsumption and LightAdjustLevel. The values of these two properties are reported at different points in time.

LightAdjustLevel

AIEvent

The identifier of the event. In this example, the product's feature event identifier is defined as AIEvent. This event is reported.

originalIdentity

The original identity of the device.

Call property setting and service invocation interfaces

The cloud-to-cloud SDK encapsulates the PropertySetHandler interface for setting properties and the ServiceInvokeHandler interface for invoking services. You can use these interfaces to accept instructions sent from IoT Platform and update data.

Example call:

BridgeBootstrap bridgeBootstrap = new BridgeBootstrap();
// Set a property.
bridgeBootstrap.setPropertySetHandler(new PropertySetHandler() {
    @Override
    public void onPropertySet(PropertySetMessage msg) {
        log.info("on property set, {}", msg.getParams());
        // If replySuccess is called, the SDK sends a /property/set_reply message to IoT Platform with code 200.
        msg.replySuccess();
        // If replyFail is called, the SDK sends a /property/set_reply message to IoT Platform with the code specified by the caller.
        //msg.replyFail(400);
    }
});

// Invoke a service.
bridgeBootstrap.setServiceInvokeHandler(new ServiceInvokeHandler() {
    @Override
    public void onServiceInvoke(ServiceInvokeMessage message) {
        log.info("on service invoke, {}", message.getParams());
        // If replySuccess is called, the SDK sends a /service/{service.identifier}_reply message to IoT Platform with code 200.
        message.replySuccess();
        // If replyFail is called, the SDK sends a /service/{service.identifier}_reply message to IoT Platform with the code specified by the caller.
        //msg.replyFail(400);
    }
});