TSL Model SDK

更新时间:
复制 MD 格式

The TSL Model SDK provides models for your app based on the Thing Specification Language (TSL). These models define properties, events, and services. You can use these models to develop device interfaces that allow you to view and control devices from your phone.

Dependent SDKOverview
LogsA basic dependent SDK. It provides unified client-side logging, log level control, and module-based log isolation.
API Channel SDKThe API Channel SDK provides HTTPS request capabilities encapsulated by IoT business protocols. It integrates security components to enhance channel security.
Persistent Connection Channel SDKThe Persistent Connection Channel SDK provides cloud-to-device data transmission encapsulated by IoT business protocols. It lets apps subscribe to and publish messages, and supports a request-response model.

Initialization

To initialize the SDK, see SDK Initialization.

Usage instructions

  • Retrieve a list of locally discovered devices that support local control

    Local communication is a basic feature of the TSL Model SDK. This feature lets you control devices on a local area network (LAN) when the external network is disconnected. During an external network outage, the local communication module searches for devices on the current LAN. If a discovered device was previously controlled by the user, you can continue to control it through the local communication link.

    When the external network is disconnected, you cannot retrieve the device list for your account from the cloud. In this case, you can use the following interface to retrieve a list of devices that can be controlled through local communication. Because device discovery is a time-consuming process, the first call to this interface might return an empty list. You must provide an option for users to refresh the device list.

    #import <IMSThingCapability/IMSThingCapability.h>
    
    (NSArray<NSDictionary *> *)  devices = [kIMSThingManager getLocalAuthedDeviceDataList];
    // The NSDictionary stores the detailed information of the device.               
  • Create a device

    The `IMSThing` abstract class encapsulates all interfaces exposed by a device. This includes methods to retrieve the device's model, control the device, and retrieve basic device information.

    #import <IMSThingCapability/IMSThingCapability.h>
    /**
    You can use the API Channel SDK on the app to call the '/uc/listByAccount' interface. This retrieves a list of all devices attached to the current account. The returned device information contains the iotId of each device.
    
    */
    _thingShell = [kIMSThingManager buildThing:_iotId]; // _iotId is the unique identifier issued to the device by the cloud.
    // When the instance is no longer needed, remember to destroy it as follows:
    // [kIMSThingManager destroyThing:_thingShell];
    // To get the iotId of the device:
    // NSString * iotId = [_thingShell iotId];                  
  • Detach a device

    When a user detaches a device from the app or resets the device, the cloud sends a notification to the app. After the app receives the push notification, the SDK automatically purges the related cached data and sends an `onDeviceUnbind` notification.

    /**
    Notification that a device has been detached. For more information, see `IMSThingObserver`.
    @param iotId: The iotId of the thing.
    @param params: The raw data pushed from the cloud.
    */
    - (void)onDeviceUnbind:(NSString *)iotId params:(NSDictionary *)params;
                        
  • Control a device

    When the app needs to control a device, the SDK determines whether to send the control request to the device locally or through the cloud. The device control interface uses the IMSThingActions protocol.

    This protocol defines several interfaces for device control. The internal logic automatically handles channel selection. Device control is based on interacting with the properties, events, and services that are defined for the device in its TSL model. For more information about properties, events, and services, see Introduction to TSL models.

    For information about the input and response parameters for method calls, see TSL model services.

    • Retrieve device status
      [[_thingShell getThingActions] getStatus:^(IMSThingActionsResponse * _Nullable response) {
           NSDictionary * properties = [response.dataObject valueForKey:@"data"];
           // The format is as follows:  
           /* {
                  "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
      [[_thingShell getThingActions] getPropertiesFull:^(IMSThingActionsResponse * _Nullable response) {
           NSDictionary * properties = [response.dataObject valueForKey:@"data"];
           // The format is as follows:  
           /* {
                 "_sys_device_mid": {
                   "time": 1516356290173,
                   "value": "example.demo.module-id"
                  },
                 "WorkMode": {
                   "time": 1516347450295,
                   "value": 0
                  },
                 "_sys_device_pid": {
                   "time": 1516356290173,
                   "value": "example.demo.partner-id"
                 }
              }
           */
      }];
    • Set device properties
      NSDictionary * items = @{@"power":@"on", @"temperature":25};
      // items is a key-value pair. For specific values, see the properties and their data types in the TSL model.
      [[_thingShell getThingActions] setProperties:items
                                   responseHandler:^(IMSThingActionsResponse * _Nullable response) {
                                                 if (response.success) { 
                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                         [UiUtils showTip:[NSString stringWithFormat:@"Set property %@ successfully", [property name]]];
                                                     });
                                                 } else {
                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                         [UiUtils showTip:[NSString stringWithFormat:@"Failed to set property %@", [property name]]];
      
                                                     });
                                                 }
                                             }];
                                  
    • Invoke a service
      // For the identifier, see the Service description in the TSL model.
      // For the input parameters when invoking a service, see the inputData of the Service in the TSL model.
      // For the response parameters when invoking a service, see the outputData of the Service in the TSL model.
      [[ _thingShell getThingActions] invokeService:[service identifier] 
                                             params:valueDict 
                                    responseHandler:^(IMSThingActionsResponse * _Nullable response) {
                                                   if (response.success) {
                                                       dispatch_async(dispatch_get_main_queue(), ^{ 
                                                               [UiUtils showTip:[NSString stringWithFormat:@"Invoked service %@ successfully", [service name]]];
                                                                });
                                                   } else {
                                                      dispatch_async(dispatch_get_main_queue(), ^{
                                                                [UiUtils showTip:[NSString stringWithFormat:@"Failed to invoke service %@", [service name]]];
                                                                });
                                                           } }];
                                  
    • Subscribe to all events
      [_thingShell registerThingObserver:self];  // Register an observer for device status, property changes, and event triggers.
      // For more information, see `IMSThingObserver`. Note the lifecycle of the registered Observer.
      // The SDK only holds a weak reference to the instance. You must manage the Observer's lifecycle.
      // When you no longer need the listener, unregister it: [_thingShell unregisterThingObserver:self];
  • Clear the cache

    During operation, the SDK saves data to the phone's sandbox directory to accelerate local communication. You must clear this cache when the user logs out of their account.

    [kIMSThingManager clearLocalCache];

Obtaining the thing model

A Thing Specification Language (TSL) model defines a device and its capabilities. It includes the device's identity, connection status, and description, in addition to its properties, services, and events. These last three elements define the device's features. The Alibaba Cloud IoT Platform uses TSL to define these models.

When the IMSThingObserver didThingTslLoad method is called, you can retrieve the parsed TSL model.

IMSThingProfile * Profile = [thingShell getThingProfile];
// The three key elements of the thing are stored in IMSThingProfile.
_thingProperties = [[_thingShell getThingProfile] allPropertiesOfModel];
_thingEvents =  [[_thingShell getThingProfile] allEventsOfModel];
_thingServices =  [[_thingShell getThingProfile] allServicesOfModel];
// Note: The properties, events, and services obtained here are the three key elements of the thing in the TSL model.
// For more information, see the IoT TSL specification.

You can also use a cloud API to retrieve the raw TSL model. For more information, see Retrieve a TSL template.

Introduction to Bluetooth feature APIs

Because of connection constraints, Bluetooth devices often cannot connect directly to the Alibaba Cloud IoT Platform. They require a gateway device to establish a connection channel. A mobile phone can function as this gateway.

This SDK provides the following additional capabilities.

  • Discover and connect to Bluetooth devices
  • Provide a cloud channel for Bluetooth devices to send and receive data
  • Control Bluetooth devices and retrieve data from them

To connect a Bluetooth device, import the following dependencies.

Dependent SDKOverview
Bluetooth Breeze SDKThe Breeze SDK 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 SDKThe Mobile Device Gateway SDK is a sub-device gateway that runs on an app. For sub-devices that cannot connect to the network directly, such as Bluetooth devices, it provides sub-device management features. These features include adding and deleting sub-devices from the topology, bringing them online or offline, and managing data transmission.
  • Initialize the Mobile Device Gateway SDK

    This feature module depends on the Mobile Device Gateway SDK. You must initialize this SDK before using the module.

  • Discover Bluetooth devices
    #import <IMSThingCapability/IMSThingCapability.h>
    
    [[IMSThingDiscoveryRegistry sharedRegistry] startDiscoveryWithFilter:filterParams
                                                               didFoundBlock:^(NSArray * _Nullable result, NSError * _Nullable error) {
                                                                   if ([result count]) {
                                                                       [result enumerateObjectsUsingBlock:^(id<IMSLocalDevice> item, NSUInteger idx, BOOL * _Nonnull stop) {
                                                                           NSString * productKey = item.productKey;
                                                                           NSString * bleMac = item.deviceName; // For a Breeze Bluetooth device, this returns the device's MAC address.
    
                                                                       }];
                                                                   }
        }];
  • Add and attach a Bluetooth device
    1. Start the Bluetooth connection. You must call this method before you use the Bluetooth device.
      #import <IMSThingCapability/IMSThingCapability.h>
      
      IMSThing * thing = [[IMSThingManager sharedManager] buildThing:iotId];
      [thing startLocalConnect];
    2. Disconnect from Bluetooth. Call this method when you no longer need to use the Bluetooth device.
      #import <IMSThingCapability/IMSThingCapability.h>
      
      IMSThing * thing = [[IMSThingManager sharedManager] buildThing:iotId];
      [thing stopLocalConnect];
    3. Pass a delegate to handle changes in the Bluetooth connection status.
      IMSThing * thing = [[IMSThingManager sharedManager] buildThing:iotId];
      [thing registerThingObserver:self]; // See IMSThingObserver.
  • 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 previous sections of this document.