Thing Specification Language Model SDK
The Thing Specification Language (TSL) Model SDK provides TSL models for apps that include properties, events, and services. You can use these models to develop device interfaces to view and control devices from a mobile phone.
| Dependent SDKs | Overview |
| API Channel SDK | The API Channel SDK provides HTTPS request capabilities with encapsulated IoT service protocols. It also integrates security components to enhance channel security. |
| Persistent Connection Channel SDK | The Persistent Connection Channel SDK provides cloud-to-device data delivery capabilities with encapsulated IoT service protocols. It lets apps subscribe to and publish messages, and supports a request-response model. |
Initialization
For more information, see SDK initialization.
Usage
The local communication feature is a basic capability of the TSL Model SDK. It provides device control within a local area network (LAN) when the external network is disconnected.
When the external network is disconnected, the local communication module searches for devices in the current LAN. If a discovered device was previously controlled by the app user, you can control the device through the local communication link.
If the external network is disconnected, you cannot pull the list of devices under the user's account from the cloud. In this case, you can use the following interface to retrieve the list of devices that can be controlled through local communication. This API was added in SDK v2.1.4.
DeviceManager.getInstance().getLocalAuthedDeviceDataList();The return value is a JSON array object. For more information about the data format within the object, see AccountDevDTO structure of the protocol for obtaining binding relationships based on devices.
Device creation
PanelDevice panelDevice = new PanelDevice(iotid);iotid can be retrieved using a cloud API. For more information, see TSL model service.
panelDevice.init(context, new IPanelCallback() {
@Override
public void onComplete(boolean bSuc, Object o) {
}
});
// context is the application's context. IPanelCallback is the initialization callback interface.
// bSuc indicates the initialization result. true indicates success, and false indicates failure.
// o represents the specific data. If the operation fails, it is an AError structure. If the operation succeeds, this parameter is ignored.Device control
Device control involves managing the properties, events, and services that are defined for a device based on its TSL model. For more information about properties, events, and services, see Generate a Thing Specification Language (TSL) model.
- Retrieve device status
panelDevice.getStatus(new IPanelCallback() { @Override public void onComplete(boolean bSuc, Object o) { ALog.d(TAG,"getStatus(), request complete," + bSuc); JSONObject data = new JSONObject((String)o); } }); // bSuc indicates whether the retrieval was successful. true indicates success, and false indicates failure. // o represents the specific data. If the operation fails, it is an AError structure. If the operation succeeds, it is a JSON string in the following format: /* { "code":200, "data":{ "status":1 "time":1232341455 } } Note: status indicates the device lifecycle. The following statuses are available: 0: inactive; 1: online; 3: offline; 8: disabled; time indicates the start time of the current status. */ - Retrieve device properties
panelDevice.getProperties(new IPanelCallback() { @Override public void onComplete(boolean bSuc, Object o) { ALog.d(TAG,"getProps(), request complete," + bSuc); JSONObject data = new JSONObject((String)o); } }); // bSuc indicates whether the retrieval was successful. true indicates success, and false indicates failure. // o represents the specific data. If the operation fails, it is an AError structure. If the operation succeeds, it is a JSON string in the following format: /* { "code":200, "data":{ "WorkMode": { "time": 1516347450295, "value": 0 } } } */You can use the
getPropertiesinterface of panelDevice to retrieve all the current property values of the device. - Set device properties
panelDevice.setProperties(paramsStr, new IPanelCallback() { @Override public void onComplete(boolean bSuc, Object o) { ALog.d(TAG,"setProps(), request complete,"+bSuc); JSONObject data = new JSONObject((String)o); } }); // For the format of paramsStr, see the following example: /* { "items":{ "LightSwitch":0 }, "iotId":"s66CDxxxxXH000102" } */ // bSuc indicates whether the operation was successful. true indicates success, and false indicates failure. // o represents the specific data. If the operation fails, it is an AError structure. If the operation succeeds, this parameter is ignored.paramsStr is the string for the params parameter in the set-property protocol. For more information, see Generate a Thing Specification Language (TSL) model.
- Invoke service
panelDevice.invokeService(paramsStr, new IPanelCallback() { @Override public void onComplete(boolean bSuc, Object o) { ALog.d(TAG,"callService(), request complete,"+bSuc); JSONObject data = new JSONObject((String)o); } }); // For the format of paramsStr, see the following example: /* { "args":{ "Saturation":80, "LightDuration":50, "Hue":325, "Value":50 }, "identifier":"Rhythm", "iotId":"s66CDxxxxItXH000102" } */ // bSuc indicates whether the operation was successful. true indicates success, and false indicates failure. // o represents the specific data. If the operation fails, it is an AError structure. If the operation succeeds, this parameter is ignored. - Subscribe to all events
If a user unbinds a device in the app or resets the device, the cloud proactively sends a notification to the app. After the app receives the push notification, the SDK automatically clears the relevant cached data and issues an unbinding notification. For more information about the format of the unbinding notification, see the calling example.
panelDevice.subAllEvent( new IPanelCallback() { @Override public void onComplete(boolean bSuc, Object data) { ALog.d(TAG,"doTslTest data:" + data) ; } } ,new IPanelEventCallback() { @Override public void onNotify(String iotid,String topic, Object data) { ALog.d(TAG,"onNofity(),topic = "+topic); JSONObject jData = new JSONObject((String)data); } } ,null); // IPanelCallback is the callback that is invoked when the subscription succeeds or fails. // The following describes the parameters in the onComplete interface of IPanelCallback: // bSuc indicates whether the operation was successful. true indicates success, and false indicates failure. // o represents the specific data. If the operation fails, it is an AError structure and no event callback occurs. If the operation succeeds, this parameter is ignored. // IPanelEventCallback is the callback that is invoked when an event is triggered. // The iotid parameter is the device iotid. // The topic parameter is the string of the event topic for the callback. // The Object data parameter is the content of the triggering event. It is a JSON string. For the format, see the following example: /* { "params": { "iotId":"0300MSKL03xxxx4Sv4Za4", "productKey":"X5xxxxH7", "deviceName":"5gJtxDxxxxpisjX", "items":{ "temperature":{ "time":1510292697471, "value":30 } } }, "method":"thing.properties" } */ // If the value of operation is Unbind, the device is unbound. For the format of the unbinding notification, see the following example: // topic: /sys/${pk}/${dn}/app/down/_thing/event/notify /* { "identifier":"awss.BindNotify", "value":{ "iotId":"apVtLzgkxxxxV000102", "identityId":"5063op37bxxxxxe0bfa9d98037", "owned":1, "productKey":"a2xxxxxyi", "deviceName":"IoT_Dev_33", "operation":"Unbind" } } */
Clear cache
You must clear the cached account data when a user logs out.
DeviceManager.getInstance().clearAccessTokenCache();Obtain the thing model
panelDevice.getTslByCache(new IPanelCallback() {
@Override
public void onComplete(boolean bSuc, Object data) {
ALog.d(TAG,"doTslTest data:" + data) ;
}
});
// bSuc indicates whether the retrieval was successful. true indicates success, and false indicates failure.
// data is the returned data in a JSON string format. If the operation fails, it is an AError structure.
Developers can also use a cloud API to retrieve the original TSL model. For more information, see TSL model service.
Obfuscation configuration
In the proguard-rules.pro file, add the following code to prevent specific classes and methods from being obfuscated.
-keep class com.aliyun.alink.linksdk.tmp.**{*;}
-keep class com.aliyun.alink.linksdk.cmp.**{*;}
-keep class com.aliyun.alink.linksdk.alcs.**{*;}
-keep class com.aliyun.iot.ble.**{*;}
-keep class com.aliyun.iot.breeze.**{*;}Bluetooth device support
Due to connection constraints, Bluetooth devices often cannot connect directly to the Alibaba Cloud IoT Platform. A gateway device is required to establish a connection channel between the Bluetooth device and the platform. A mobile phone can act as a gateway in this process.
These APIs provide the following capabilities.
- Discover and connect to Bluetooth devices.
- Provide a cloud connection channel for Bluetooth devices to upload and download data.
- Control Bluetooth devices and retrieve data.
| Dependent SDKs | Overview |
| Bluetooth Breeze SDK | This is a mobile Bluetooth SDK implemented according to specifications. It helps partners quickly integrate Bluetooth features on mobile phones. The main features of the Breeze SDK include device discovery and connection, device communication, encrypted transmission, and large data transmission. |
| Mobile Device Gateway SDK | The Mobile Device Gateway SDK is a sub-device gateway that runs on an app. For sub-devices that cannot directly connect to the network, such as Bluetooth devices, it provides sub-device management features. These features include adding and deleting topologies, bringing devices online and offline, and handling data uploads and downloads. |
- Import Bluetooth API dependencies
To support Bluetooth devices in the TSL Model SDK, import the following dependencies. You can obtain the relevant versions from the SDK download page in the IoT Platform console. For more information, see Download and integrate an SDK.
compile 'com.aliyun.alink.linksdk:lpbs-plugin-breeze:${version}' compile 'com.aliyun.alink.linksdk:breeze-biz:${version}' compile 'com.aliyun.alink.linksdk:breeze:${version}' compile 'com.aliyun.alink.linksdk:ble-library:${version}' - Initialize the Mobile Device Gateway SDK
This feature module depends on the Mobile Device Gateway SDK. You must initialize this SDK before you use it.
- Notes on using Bluetooth access
Before you can use a Bluetooth device, the app must have the following permissions:
- Bluetooth permission
- Bluetooth management permission
In addition, on Android systems with API level 21 or higher, the following permissions are also required:
- Coarse location permission
- Fine location permission
NoteIn addition to the preceding permissions, you must enable location services on Android systems with API level 21 or higher. Otherwise, scanning will not work. For more information about how to enable location services, see the Android developer reference documentation. For more information about why location permissions and services are required, see the official documentation.
For more information, see the official documentation.
- Discover Bluetooth devices
// The discoverDevices interface is used to discover local devices. // The first parameter is userdata, which is generally set to null. // The second parameter specifies whether to clear previously discovered devices. true indicates to clear them. false indicates not to clear them. This is generally set to false. // The third parameter specifies the device discovery timeout period in milliseconds. // The fourth parameter is the filter interface. If it returns true, the device is required by the service layer. If it returns false, the device is excluded. // The fifth parameter is the discovery callback interface. Locally discovered devices are returned through this callback interface. DeviceManager.getInstance().discoverDevices(null, false, 5000, new IDiscoveryFilter() { @Override public boolean doFilter(DeviceBasicData basicData) { return true; } },listener); - Add and bind a Bluetooth device
The binding process for a Bluetooth device consists of two steps.
- The Bluetooth device connects to the cloud through the app. You can use the API that is provided by the SDK to complete this step.
DevService.subDeviceAuthenLogin(params, new DevService.ServiceListener() { @Override public void onComplete(boolean isSuccess,Object bundle) { ALog.e(TAG,"subDeviceAuthenLogin onComplete isSuccess:" + isSuccess + " bundle:" + bundle); String productKey = null; String deviceName = null; if(bundle != null && bundle instanceof Bundle){ Bundle resultBundle = (Bundle)bundle; productKey = resultBundle.getString(DevService.BUNDLE_KEY_PRODUCTKEY); deviceName = resultBundle.getString(DevService.BUNDLE_KEY_DEVICENAME); } if(boneCallback != null){ boneCallback.success(getRspObject(isSuccess,productKey,deviceName)); } } }); // The params parameter is the sub-device information. For the format, see the following example: /* { "iotId":"your iotid", "productKey":"your productkey", "deviceName":"your deviceName " } */ // ServiceListener is the callback interface. // isSuccess indicates whether the operation was successful. true indicates success, and false indicates failure. // bundle is an extended parameter for the callback that contains device information. - After the device is connected, you can call a cloud API to bind it to an account. After the device is successfully bound, you must notify the SDK.
IoTCallback callback = new IotCallback(){ @Override void onFailure(IoTRequest var1, Exception var2){ } @Override void onResponse(IoTRequest var1, IoTResponse var2){ SubDevInfo subDevInfo = new SubDevInfo(deviceInfo.productKey,deviceInfo.deviceName); DevService.notifySubDeviceBinded(); } } Map<String, Object> params = new HashMap(); params.put("deviceName", deviceInfo.deviceName); params.put("productKey", deviceInfo.productKey); IoTRequest request = (new IoTRequestBuilder()).setApiVersion("1.0.3").setAuthType("iotAuth").setPath("/awss/time/window/user/bind").setParams(params).build(); IoTAPIClient ioTAPIClient = (new IoTAPIClientFactory()).getClient(); ioTAPIClient.send(request, callback); // This is an API Gateway request. The interface requires the device's productKey and deviceName. // For more information, see API Channel SDK.
- The Bluetooth device connects to the cloud through the app. You can use the API that is provided by the SDK to complete this step.
- Connect to or disconnect from a local Bluetooth device
After this SDK is initialized, the local link is established. The upper layer does not need to call the connect and disconnect interfaces. If the device disconnects, you can use the local connection interface to re-establish the connection.
- Establish a local connection
panelDevice.startLocalConnect(new IPanelCallback() { @Override public void onComplete(boolean bSuc, Object o) { ALog.d(TAG,"startLocalConnect, onComplete,"+bSuc); } }); // bSuc indicates the initialization result. true indicates success, and false indicates failure. // o is an extended parameter. If the operation succeeds, this parameter is ignored. If the operation fails, it is an AError structure. - Disconnect the local connection
panelDevice.stopLocalConnect(new IPanelCallback() { @Override public void onComplete(boolean bSuc, Object o) { ALog.d(TAG,"stopLocalConnect, onComplete,"+bSuc); } }); // bSuc indicates the initialization result. true indicates success, and false indicates failure. // o is an extended parameter. If the operation succeeds, this parameter is ignored. If the operation fails, it is an AError structure.
- Establish a local connection
- Control a Bluetooth device
The APIs for controlling Bluetooth devices and retrieving information are the same as those for Wi-Fi devices. For more information, see the preceding sections of this document.