Senselink connection

Link API is a series of interface methods for cloud capability encapsulation of SenseLink platform (For JCV Senselink Cloud, please refer to https://docs.japancv.co.jp/senselink/ (Japanese only)). There are two major types of interface methods, one is encapsulation for the platform RESTful interface, and the other is encapsulation for the platform’s Mqtt message push mechanism. Users can use the cloud capability provided by the platform just like calling common Java methods.

The Link API mainly provides two core types, namely, HttpApiClient and MqttApiClient, and by using the methods provided by these two types, direct communication with the SenseLink platform can be achieved. The brief introduction is as follows:

  • HttpApiClient: For encapsulation of platform RESTful API, use Http protocol for communication, both are synchronized methods and need to be used in the worker thread;

  • MqttApiClient: For encapsulation of the platform message push mechanism, use Mqtt protocol for communication, and receive platform message push by establishing a long connection and subscribing to the message Topic.

For the detailed definition of the RESTful API interface and Mqtt Topic involved in the interface method, please refer to the "Thunder SDK API Document".

Link API provides a unified initialization entry, you need to set the Url of the server, the read and write timeout of the request, the language type returned by the interface, etc. The specific use is as follows:

// Initialize   
LinkSDKHelper.getInstance().init(“https://link.japancv.co.jp/sl/”, this)
         .setConnectTimeout(10 * 1000)
         .setReadTimeout(30 * 1000)
         .setWriteTimeout(10 * 1000)
         .setLanguage(LinkSDKHelper.LanguageTypeEnum.ZH)  // Set the language of return information from the server
         .addInterceptor(new ResponseInterceptor())  // Set interceptors
         .setDebug(true);

After initialization, specific methods can be called to perform specific services.

RESTful API encapsulation method

Each RESTful API interface encapsulates the corresponding Java method execution. Specific entities class was encapsulated by both the parameter passing value required by the request and the result data of the request. For example, when executing the v2/record request to upload the identification record

    // Parameter entity class
    RecordParameter recordParameter = new RecordParameter();
    recordParameter.setUserId(2547);
    recordParameter.setMode(2);
    recordParameter.setSignTime((int) (System.currentTimeMillis() / 1000));
    recordParameter.setType(1);
    recordParameter.setInTime(0);
    recordParameter.setEntryMode(1);
    Bitmap bitmap = BitmapFactory.decodeStream(mAppContext.getAssets().open("test.jpg"));
    recordParameter.setUsername("testUserName");
    // Error occurs when uploading incorrect base64 string
    recordParameter.setSignBgAvatar(Base64Utils.bitmapToBase64(bitmap));
    recordParameter.setSignAvatar(Base64Utils.bitmapToBase64(bitmap));
    recordParameter.setDocPhoto(Base64Utils.bitmapToBase64(bitmap));
    recordParameter.setIcNumber("235113");
    recordParameter.setIdNumber("460003199809086744");

    // Call the encapsulated method to execute the specific request. Result refers to the unified wrapper class for the result of the request
    Result<RecordResult> recordResultResult = HttpApiClient.uploadRecord(recordParameter);
    if(recordResultResult.isSuccess()){
        // Get the request result data and process it, RecordResult refers to the entity class of the request result data
            RecordResult body = recordResultResult.getBody(RecordResult.class);
        // todo: the execution of specific operations
  } else {
          // Request exception. Please see the API documentation for details
  }
}

Multiple parameters can be passed in directly to the API interface with relatively simple parameters for execution, specified as below:

  • Device login operation

// Request parameters
// Synchronize method calls, which need to be executed in the work thread
Result<LoginResult> loginResult = HttpApiClient.login(
                                  "account", "password", "SPS", AppUtils.getAndroidId(ContextUtils.getContext()));
  • Get detailed user information based on the user ID

int userId = 5;
Result result = HttpApiClient.getUserInfo(userId);

For more details on "RESTful API interface definition" and "correspondence between API and methods", please refer to the Thunder SDK API Document .

Mqtt push mechanism encapsulation method

Each Mqtt message push Topic encapsulates the corresponding Java method. Topic subscribed messages are received by registering callbacks, specified as below

  • Establish a Mqtt long connection with the server, shown as below:

    MqttApiClient.connectMqtt(new IMqttActionListener() {
    
         @Override
         public void onSuccess(IMqttToken iMqttToken) {
           // Connection successful
         }
    
         @Override
         public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
           // Connection failed
         }
    
       }, new IConnectionLost() {
    
         @Override
         public void onConnectionLost(Throwable cause) {
                  // Connection lost
         }
    });
  • Subscribe to the personnel group change of the device

    // Subscribe to the personnel group change
    MqttApiClient.registerGroupChangeListener(new MessageCallback() {

       @Override
       public void success(MqttMessage msg) {

                 // json data is the body of the push message.
                  String json = new String(msg.getPayload());
              // Delete the device in the background and push an empty string without processing.
            if (TextUtils.isEmpty(json)) {
                    return;
            }

            // Get the data. Group class is the entity class corresponding to the message data.
            Pair<List<Group>, Boolean> pushGroupList = 
                                          DataConverter.convertJsonToGroupList(json);
            // Process data according to specific business
         }

       @Override
       public void error(int code, String msg, Throwable throwable) {
                         // Subscription exceptions / Message push exceptions
       }
    });
  • Unsubscribe to the personnel group change of the device

    MqttApiClient.unRegisterGroupChangeListener();

For more details on "Mqtt Topic definition" and "correspondence between topic subscribe and methods", please refer to the Thunder SDK API Document.

Introduction of key use processes

Link API provides easy communication with Senselink platform, however, certain process steps need to be followed while using some functions, in other words, both the use of RESTful API interface and the subscriptions to MQTT topics follow a sequence. Below mainly describes the main functional flow steps from the perspective of the sequence of use.

Login and registration steps

Login and registration operations are required to use the functions of SenseLink platform, so that device can be included into the platform for unified management. A brief communication process is stated as follows:

The main steps are described below:

(1) Device login: requestHttpApiClient.getRsa() interface to obtain a public key from the platform first, then use the public key to encrypt the cleartext password, and then request HttpApiClient.login() interface for login operation. The two steps are completed by using the HttpApiClient.login () method, which only needs to pass in the account number, encrypted password, device type and device DUID as method parameters.

  • token: all interface requests need to use token, which is valid for 7 days. After expiration, 403 error will be returned, in this case, you need to log in again to obtain it;

  • newDeviceKey: If it is true, it means that the current device has not been included in the unified management of the platform, in this case, device registration operation needs to be performed.

(2) Device registration: the HttpApiClient.register() interface should be requested first for registration, and then the HttpApiClient.bindDefaultGroup() interface should be requested to bind the device and personnel group after successful registration (for subsequent personnel data distribution management). The two steps are completed by applying HttpApiClient.register () method, and parameters such as device name, device location, entrance and exit direction of access control need to be passed in.

  • device ldid: the unique identification code of the device on the platform, which is used to distinguish device;

  • companyId: the company id corresponding to the device, and each company has several personnel groups.

Synchronization strategy of object model

Object model related functions are only supported in SenseLink 2.3.0 and above versions. You need to determine the version number of the server before using these functions. On the premise that the server supports these functions, object model can be synchronized without unexpected exceptions. This operation should be placed before the configuration synchronization, the flow chart is shown in the figure below.

(1) Get the version number of the currently connected server by calling HttpApiClient.getServerVersion() to determine whether or not object model related functions are supported by the server. If the version number of the server is greater than or equal to 2.3.0, these functions are supported and you can continue the subsequent operations, otherwise skip directly to step (5);

(2) Calculate the MD5 of the local object model, and call HttpApiClient.checkTslExist() as an input parameter to get the flag zone bit and check whether the local object model exists in the cloud at the same time. When flag==1, it means that the object model already exists and does not need to be uploaded. Otherwise, call HttpApiClient.uploadTsl() to upload the object model;

(3) Call HttpApiClient.checkTslLanguageExist( language ) (zh: Simplified Chinese, zh-tw: Traditional Chinese, en: English) Check whether there is a corresponding language package in the cloud, and get the zone bit and MD5 of the cloud language package. When flag==1 and the MD5 of the cloud language package is consistent with the MD5 of the local language package, it means that the language package already exists and does not need to be uploaded. Otherwise, call HttpApiClient.uploadTslLanguage() to upload the language package;

(4) If there are multiple language packages, repeat step (3);

(5) Perform related operations for configuration synchronization.

Device configuration synchronization strategy

There are two ways to set device configuration parameters: set through the UI interface and set and issue via SenseLink cloud. The brief communication is shown in the figure below:

(1) After the user modifies the configuration through the setting page, the system setting module will upload the modified configuration parameters to the background, and finally broadcast the configuration change;

(2) When the configuration is modified in the background, it will send a configuration change push through MQTT. After receiving the notification, the system setting module will obtain the latest server configuration through HTTP, update the device configuration parameters, and finally broadcast the configuration change;

(3) When the device configuration is reset in the background, it will send a restore default configuration push through MQTT. The system setting module will reset all configurations after receiving the notification, upload the reset configuration to the background, and finally broadcast the configuration change.

Personnel data synchronization strategy

Personnel data synchronization means that the device side obtains the company's corresponding personnel data from the platform side, the data mainly includes the basic information of the personnel and the face photo library required for recognition. The brief communication process of data synchronization is as follows:

(1) After the device logs in successfully and establishes a long Mqtt connection with Mqtt Broker, you need to actively subscribe to the "Device Personnel Group Change Topic". After subscribing, you can immediately receive the message push and obtain all the personnel group information belonging to the device (the key field is the id of the personnel group). You can unsubscribe to the Topic after receiving the data;

(2) With all the personnel group ids obtained in (1), continue to subscribe to "Single personnel group under all personnel data Topic", after subscribing, all personnel information of the personnel group can be obtained (key fields are user_id and image_url). You can unsubscribe to the Topic after receiving the personnel information of all groups

(3) With the user_id and image_url obtained in (2), detailed personnel information and avatars can be obtained through the RESTFul interface. This step needs to be repeated to obtain all the personnel data;

(4) After initial acquisition of personnel data, it is necessary to subscribe to the "Topic of personnel data change under the single person group". After the subscription, the personnel increment list and the change type will be returned immediately, then you need to process the data correspondingly according to the change type.

Last updated