すべてのプロダクト
Search
ドキュメントセンター

IoT Platform:TSLベースの通信を確立する

最終更新日:Apr 17, 2025

Alinkプロトコルを使用して、デバイスとIoT Platform間のThing Specification Language (TSL) ベースの通信を確立できます。 デバイスはIoT Platformにプロパティまたはイベントを送信し、IoT Platformはデバイスにコマンドを送信してプロパティを設定したり、サービスを呼び出したりします。 このトピックでは、TSLベースの通信を確立する方法を説明するサンプルJavaコードを提供します。

前提条件

  • IoT Platform が有効化されています。
  • Java開発環境がインストールされています。

プロダクトとデバイスを作成する

プロダクトとデバイスを作成し、プロダクトのTSL機能を定義する必要があります。

  1. IoT Platformコンソールにログインします。
  2. [概要] ページで、[すべての環境] をクリックします。 [すべての環境] タブで、管理するインスタンスを見つけ、インスタンスIDまたはインスタンス名をクリックします。

  3. 左側のナビゲーションウィンドウで、[デバイス] > [製品] を選択します。
  4. [プロダクト] ページで、[プロダクトの作成] をクリックします。 [製品の作成] ページで、製品のカスタム名を指定し、[カスタムカテゴリ] を選択します。 他のパラメーターにデフォルト値を使用し、[OK] をクリックします。
    詳細については、「プロダクトの作成」をご参照ください。
  5. 製品の [製品の詳細] ページで、[機能の定義] をクリックします。 [機能の定義] タブで、TSLモデルを定義します。

    この例では、次の図に示すように、イベント、サービス、および2つのプロパティが [既定のモジュール] セクションに追加されます。

    このトピックでは、インポートできるサンプルのTSLモデルを提供します。 TSLモデルをインポートする方法の詳細については、「TSL機能の一括追加」をご参照ください。

    TSL-based communication
  6. 左側のナビゲーションウィンドウで、[デバイス] をクリックします。 [デバイス] ページで、[デバイスの追加] をクリックしてデバイスを作成します。
    サンプルコードを使用して、デバイスプロパティをバッチ設定し、デバイスサービスをバッチ呼び出しできます。 少なくとも2つのデバイスを作成する必要があります。 詳細については、「一度に複数のデバイスを作成する」をご参照ください。

SDKデモのダウンロードとインストール

SDKデモには、サーバー側のサンプルコードとデバイス側のサンプルコードが含まれています。

  1. iotx-api-demoをクリックしてiotx-api-demoパッケージをダウンロードし、パッケージを解凍します。
  2. Java開発ツールを起動し、解凍されたiotx-api-demoフォルダをインポートします。
  3. 次のMaven依存関係をpom.xmlファイルに追加して、IoT Platform SDKとLink SDKをインポートします。
    <!-https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-iot->
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-iot</artifactId>
        <version>7.33.0</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>3.5.1</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun.alink.linksdk</groupId>
      <artifactId>iot-linkkit-java</artifactId>
      <version>1.2.0</version>
      <scope> コンパイル </scope>
    </dependency> 
  4. java/src/main/resources/ ディレクトリでconfigファイルを開き、初期化に必要な情報を指定します。
    user.accessKeyID = <your accessKey ID>
    user.accessKeySecret = <your accessKey Secret>
    iot.regionId = <regionId>
    iot.productCode = Iot
    iot.domain = iot.<regionI d>.aliyuncs.com
    iot.version = 2018-01-20 
    パラメーター説明
    accessKeyIDAlibaba CloudアカウントのAccessKey ID。

    AccessKeyペアを作成または表示するには、次の手順を実行します。Alibaba Cloud管理コンソールにログインします。 ポインタをプロフィール写真の上に移動し、[AccessKey管理] をクリックして [AccessKeyペア] ページに移動します。

    accessKeySecretAlibaba CloudアカウントのAccessKeyシークレット。 AccessKeyシークレットは、AccessKey IDを取得するのと同じ方法で取得できます。
    regionIdIoTデバイスが存在するリージョンのID。 リージョンIDの詳細については、「リージョンとゾーン」をご参照ください。

Link SDKを使用してプロパティとイベントを送信する

IoT Platformに接続し、プロパティとイベントを送信するようにLink SDKを設定します。

java/src/mai n/com.aliyun.iot.api.com mon.de viceApiディレクトリのThingTemplateファイルにサンプルコードが含まれています。

  • 接続情報を指定します。

    サンプルコードのproductKeydeviceName、およびdeviceSecretパラメーターの値を、デバイス証明書に関する情報に置き換えます。 urlパラメーターの値をMQTTエンドポイントに置き換えます。 エンドポイントの取得方法の詳細については、「インスタンスのエンドポイントの管理」をご参照ください。 エンドポイントにポート1883を含める必要があります。

    public static void main(String[] args) {
            /**
             * デバイス証明書に関する情報。 
             */
            String productKey = "your productKey";
            文字列deviceName = "your deviceName";
            文字列deviceSecret = "your deviceSecret";
    
            /* TODO: 次のエンドポイントをインスタンスのエンドポイントに置き換えます。
           */
            文字列url = "iot-6d *** ql.mqtt.iothub.aliyuncs.com:1883";
    
            /**
             * MQTT接続に関する情報。 
             */
            ThingTemplate manager=新しいThingTemplate();
    
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.productKey = productKey;
            deviceInfo.deviceName = deviceName;
            deviceInfo.de viceSecret = deviceSecret;
    
            /**
             * Java HTTPクライアントはTSLv1.2をサポートしています。 
             */
            System.setProperty("https.protocols" 、"TLSv2");
            manager.init(deviceInfo、url);
        }
  • 接続パラメータを初期化します。
    public void init(final DeviceInfo deviceInfo, String url) {
            LinkKitInitParams params = new LinkKitInitParams();
            /**
             * MQTT初期化のパラメーターを設定します。 
             */
            IoTMqttClientConfig config = new IoTMqttClientConfig();
            config.productKey = deviceInfo.productKey;
            config.de viceName = deviceInfo.de viceName;
            config.de viceSecret = deviceInfo.de viceSecret;
            config.channelHost = url;
            /**
             * オフラインメッセージを受信するかどうかを指定します。 
             * MQTT接続に対応するcleanSessionフィールド。 
             */
            config.receiveOfflineMsg = false;
            params.mqttClientConfig = config;
            ALog.setLevel(LEVEL_DEBUG);
            ALog.i(TAG、"mqtt connetcion info=" + params);
    
            /**
             * 初期化パラメーターを設定し、デバイスに関する証明書情報を指定します。 
             */
            params.deviceInfo = deviceInfo;
    
            /**接続を確立します。 **/
            LinkKit.getInstance().init(params, new ILinkKitConnectListener() {
                public void onError(AError aError) {
                    ALog.e(TAG、"Init Error error=" + aError);
                }
    
                public void onInitDone(InitResult initResult) {
                    ALog.i(TAG, "onInitDone result=" + initResult);
    
                    List<Property> properties = LinkKit.getInstance().getDeviceThing().getProperties();
    
                    ALog.i(TAG、"デバイスのプロパティ" + JSON.toJSONString (プロパティ));
    
                    リスト <Event> getEvents = LinkKit.getInstance().getDeviceThing().getEvents();
    
                    ALog.i(TAG、"デバイスイベントのリスト" + JSON.toJSONString(getEvents));
    
                    /* プロパティを送信します。 TODO: 送信するプロパティが製品のTSLモデルで定義されていることを確認します。 例: MicSwitch。 それ以外の場合、エラーメッセージが返されます。 */
                    handlePropertySet("MicSwitch" 、新しいValueWrapper.IntValueWrapper(1));
    
                    /* イベントを送信します。 TODO: 送信するイベントが製品のTSLモデルで定義されていることを確認します。 例: Offline_alarm。 それ以外の場合、エラーメッセージが返されます。 */
                    Map<String,ValueWrapper> values = new HashMap<>();
                    values.put("eventValue",new ValueWrapper.IntValueWrapper(0));
                    OutputParams outputParams=新しいOutputParams (値);
                    handleEventSet("Offline_alarm" 、outputParams);
                }
            });
        }
    説明 コード内のプロパティ識別子とイベント識別子は、TSLモデルで定義されている識別子と同じである必要があります。
  • プロパティを送信するようにLink SDKを設定します。
    /**
         * デバイスはAlink JSON形式でプロパティを送信します。 
         * @ param identifier: プロパティの識別子。 
         * @ param value: プロパティの値。 
         * @return
         */
        private void handlePropertySet (文字列識別子、ValueWrapper値) {
            ALog.i(TAG, "Identifier of the property=" + identifier);
    
            Map<String, ValueWrapper> reportData = new HashMap<>();
            reportData.put (識別子、値);
    
            LinkKit.getInstance().getDeviceThing().thingPropertyPost(reportData, new IPublishResourceListener() {
    
                public void onSuccess(String s, Object o) {
                    // プロパティが送信されます。 
                    ALog.i(TAG, "Submitted.") onSuccess() は: s = ["s +"] 、o = ["o +"]") で呼び出されます。
                }
    
                public void onError(String s, AError aError) {
                    // プロパティ値の送信に失敗しました。 
                    ALog.i(TAG, "送信に失敗しました。 onError() は: s = ["+ s +"] 、aError = ["+ JSON.toJSONString(aError) +"]") で呼び出されます。
                }
            });
        }
  • イベントを送信するようにLink SDKを設定します。
    /**
         * デバイスはAlink JSON形式でイベントを送信します。 
         * @ param identifier: イベントの識別子。 
         * @ param params: イベントのパラメーター。 
         * @return
         */
        private void handleEventSet(String identifyID, OutputParams params ) {
            ALog.i(TAG, "Identifier of the event=" + identifyID + "params=" + JSON.toJSONString(params));
    
    
            LinkKit.getInstance().getDeviceThing().thingEventPost( identifyID, params, new IPublishResourceListener() {
    
                public void onSuccess(String s, Object o) {
                    // イベントが送信されます。 
                    ALog.i(TAG, "Submitted.") onSuccess() は: s = ["s +"] 、o = ["o +"]") で呼び出されます。
                }
    
                public void onError(String s, AError aError) {
                    // イベントの送信に失敗しました。 
                    ALog.i(TAG, "送信に失敗しました。 onError() は: s = ["+ s +"] 、aError = ["+ JSON.toJSONString(aError) +"]") で呼び出されます。
                }
            });
        }

IoT Platform SDKを使用してプロパティを設定し、サービスを呼び出すコマンドを送信する

  • Initialize a client.

    java/src/main/com.aliyun.iot.clientディレクトリのIotClientファイルには、サンプルコードが含まれています。

    パブリッククラスIotClient {
      プライベート静的文字列accessKeyID;
      プライベート静的文字列accessKeySecret;
      プライベート静的文字列regionId;
      プライベート静的Stringドメイン;
      プライベート静的Stringバージョン。
      パブリック静的DefaultAcsClient getClient() {
        DefaultAcsClientクライアント=null;
        Properties prop = new Properties();
        try {
          prop.load(Object.class.getResourceAsStream("/config.properties"));
          accessKeyID = prop.getProperty("user.accessKeyID");
          accessKeySecret = prop.getProperty("user.accessKeySecret");
          regionId = prop.getProperty("iot.regionId");
                domain = prop.getProperty("iot.domain");
                version = prop.getProperty("iot.version");
    
          IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyID, accessKeySecret);
          DefaultProfile.addEndpoint(regionId、regionId、prop.getProperty("iot.productCode")) 、
              prop.getProperty("iot.domain");
          // クライアントを初期化します。 
          client = new DefaultAcsClient(profile);
    
        } catch (Exception e) {
          LogUtil.print("クライアントの初期化に失敗しました。 例外: "+ e.getMessage();
        }
        return client;
      }
        public static String getRegionId() {
            return regionId;
        }
        public static void setRegionId (文字列regionId) {
            IotClient.regionId = regionId;
        }
        public static String getDomain() {
            ドメインを返します。
        }
        public static void setDomain (文字列ドメイン) {
            IotClient.domain=ドメイン;
        }
        public static String getVersion() {
            戻りバージョン;
        }
        public static void setVersion (文字列バージョン) {
            IotClient.version = version;
        }
    }
  • CommonRequestパブリッククラスを初期化します。

    java/src/mai n/com.aliyun.iot.api.com mon.openApiディレクトリのAbstractManagerファイルは、CommonRequestパブリッククラスをカプセル化します。

    パブリッククラスAbstractManager {
        private static DefaultAcsClient client;
        static {
            client = IotClient.getClient();
        }
        /**
         * CommonRequestクラスを初期化します。 action: API操作の名前。 
         * domain: エンドポイント。 
         * version: APIのバージョン。 
         */
        public static CommonRequest executeTests (文字列アクション) {
            CommonRequest request = new CommonRequest();
            request.setDomain(IotClient.getDomain());
            request.setMethod(MethodType.POST);
            request.setVersion(IotClient.getVersion());
            request.setAction(action);
            リターン要求;
        }
  • IoT PlatformのAPI操作を呼び出して、プロパティを設定し、サービスを呼び出します。

    java/src/mai n/com.aliyun.iot.api.com mon.openApiディレクトリのThingManagerForPopSDkファイルにサンプルコードが含まれています。

    • SetDeviceProperty操作を呼び出して、デバイスプロパティを設定します。
      public static void SetDeviceProperty(String InstanceId、String IotId、String ProductKey、String DeviceName、String Items) {
              SetDevicePropertyResponseレスポンス=null;
              SetDevicePropertyRequest request=新しいSetDevicePropertyRequest();
              request.setDeviceName(DeviceName);
              request.setIotId(IotId);
              request.setItems (アイテム);
              request.setProductKey(ProductKey);
              request.setIotInstanceId(InstanceId);
      
              try {
                  response = client.getAcsResponse(request);
      
                  if (response.getSuccess() != null && response.getSuccess()) {
                      LogUtil.print("デバイスプロパティが設定されています。");
                      LogUtil.print(JSON.toJSONString (レスポンス));
                  } else {
                      LogUtil.print("デバイスプロパティの設定に失敗しました。");
                      LogUtil.error(JSON.toJSONString (レスポンス));
                  }
      
              } catch (ClientException e) {
                  e.printStackTrace();
                  LogUtil.error("Failed to configure the device property." + JSON.toJSONString (レスポンス));
              }
          }
    • SetDevicesProperty操作を呼び出して、デバイスのプロパティをバッチ構成します。
      /**
           * デバイスのプロパティをバッチ設定します。 
           *
           * @ param ProductKey: 設定するプロパティを持つデバイスが属する製品のProductKey。 
           * @ param DeviceNames: プロパティを構成するデバイスのDeviceNames。 
           * @ param Items: キーと値のJSON文字列の複数のペアで構成されるプロパティ情報。 This parameter is required. 
           *
           * @ Des: 説明。 
           */
          public static void SetDevicesProperty(String InstanceId, String ProductKey, List<String> DeviceNames, String Items) {
              SetDevicesPropertyResponse応答=新しいSetDevicesPropertyResponse();
              SetDevicesPropertyRequest request=新しいSetDevicesPropertyRequest();
              request.setDeviceNames(DeviceNames);
              request.setItems (アイテム);
              request.setProductKey(ProductKey);
              request.setIotInstanceId(InstanceId);
      
              try {
                  response = client.getAcsResponse(request);
      
                  if (response.getSuccess() != null && response.getSuccess()) {
                      LogUtil.print("プロパティはバッチ設定されています。");
                      LogUtil.print(JSON.toJSONString (レスポンス));
                  } else {
                      LogUtil.print("デバイスのプロパティのバッチ設定に失敗しました。");
                      LogUtil.error(JSON.toJSONString (レスポンス));
                  }
              } catch (ClientException e) {
                  e.printStackTrace();
                  LogUtil.error("デバイスのプロパティのバッチ設定に失敗しました。" + JSON.toJSONString (応答));
              }
          }
    • InvokeThingService操作を呼び出して、デバイスサービスを呼び出します。
           /**
           * @ param Identifier: サービスの識別子。 This parameter is required. 
           * @ param Args: サービスを開始するために必要な入力パラメーター。 This parameter is required. 
           */
          public static InvokeThingServiceResponse.Data InvokeThingService(String InstanceId、String IotId、String ProductKey、String DeviceName、
                                                                           String Identifier, String Args) {
              InvokeThingServiceResponseレスポンス=null;
              InvokeThingServiceRequest request = new InvokeThingServiceRequest();
              request.setArgs(Args);
              request.setDeviceName(DeviceName);
              request.setIotId(IotId);
              request.setIdentifier (識別子);
              request.setProductKey(ProductKey);
              request.setIotInstanceId(InstanceId);
      
              try {
                  response = client.getAcsResponse(request);
      
                  if (response.getSuccess() != null && response.getSuccess()) {
                      LogUtil.print("サービスが実行されます。");
                      LogUtil.print(JSON.toJSONString (レスポンス));
                  } else {
                      LogUtil.print("サービスの実行に失敗しました。");
                      LogUtil.error(JSON.toJSONString (レスポンス));
                  }
                  return response.getData();
      
              } catch (ClientException e) {
                  e.printStackTrace();
                  LogUtil.error("Failed to execute the service." + JSON.toJSONString (レスポンス));
              }
              ヌルを返します。
          }
      説明 サービスを同期的に呼び出す場合は、TSLモデルを定義するときに [呼び出し方法] パラメーターを [同期] に設定します。 デバイスを開発するときは、同期サービス呼び出しを処理するコードを記述する必要があります。
    • InvokeThingsService操作を呼び出して、デバイスサービスを一括呼び出します。
           /**
           * @ param Identifier: サービスの識別子。 This parameter is required. 
           * @ param Args: サービスを開始するために必要な入力パラメーター。 This parameter is required. 
           */
          public static void InvokeThingsService(String InstanceId、String IotId、String ProductKey、List<String> DeviceNames、
                                                 String Identifier, String Args) {
              InvokeThingsServiceResponseレスポンス=null;
              InvokeThingsServiceRequest request = new InvokeThingsServiceRequest();
              request.setArgs(Args);
              request.setIdentifier (識別子);
              request.setDeviceNames(DeviceNames);
              request.setProductKey(ProductKey);
              request.setIotInstanceId(InstanceId);
      
              try {
                  response = client.getAcsResponse(request);
      
                  if (response.getSuccess() != null && response.getSuccess()) {
                      LogUtil.print("サービスは呼び出されます。");
                      LogUtil.print(JSON.toJSONString (レスポンス));
                  } else {
                      LogUtil.print("サービスのバッチ呼び出しに失敗しました。");
                      LogUtil.error(JSON.toJSONString (レスポンス));
                  }
      
              } catch (ClientException e) {
                  e.printStackTrace();
                  LogUtil.error("Failed to batch call the services." + JSON.toJSONString (応答));
              }
          }

サンプル要求:

public static void main(String[] args) {
        /**オンラインデバイスのDeviceNameと、オンラインデバイスが属する製品のProductkey。 */
        文字列deviceName = "2pxuAQB2I7wGPmqq ***";
        文字列deviceProductkey = "a1QbjI2 ***";

        /**Enterprise Editionインスタンスまたは新しいバージョンのパブリックインスタンスを使用する場合は、InstanceIdパラメーターにインスタンスIDを指定します。 インスタンスIDを取得するには、IoT Platformコンソールにログインし、[概要] ページでインスタンスIDを表示します。 
         * 旧バージョンのパブリックインスタンスを使用する場合は、InstanceIdパラメーターを "" 空のままにします。 
         */
        文字列InstanceId = "iot-*** tl02";

        //1. デバイスプロパティを設定します。 
        SetDeviceProperty(InstanceId、null、deviceProductkey、deviceName、"{\" hue\":0}");
        //2. デバイスのプロパティを一括設定します。 
        List<String> deviceNames = new ArrayList<>();
        deviceNames.add(deviceName);
        SetDevicesProperty(InstanceId、deviceProductkey、deviceNames、"{\" hue\":0}");
        //3. デバイスサービスを呼び出します。 
        InvokeThingService(InstanceId、null、deviceProductkey、deviceName、"ModifyVehicleInfo" 、"{}");
        // 4。 デバイスサービスを一括呼び出します。 
        List<String> deviceNamesService = new ArrayList<>();
        deviceNamesService.add(deviceName);
        InvokeThingsService(null、deviceProductkey、deviceNamesService、"ModifyVehicleInfo" 、"{}");
    }

SDKのデバッグ

Link SDKとIoT Platform SDKを設定したら、SDKを実行します。

チェック結果:

  • ローカルログを表示します。 TSL-based communication
  • デバイスの [デバイスの詳細] ページで、[デフォルトモジュール] をクリックします。
    • [ステータス] タブには、デバイスが最近送信したプロパティ値が表示されます。
    • [イベント] タブには、デバイスが最近送信したイベントが表示されます。
    • [サービスの呼び出し] タブには、サービス呼び出しの記録が表示されます。
    TSL-based communication