

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# を使用して AWS IoT Device SDK Greengrass nucleus、その他のコンポーネント、および と通信します。 AWS IoT Core
<a name="interprocess-communication"></a>

コアデバイスで実行されているコンポーネントは、 の AWS IoT Greengrass Core プロセス間通信 (IPC) ライブラリを使用して AWS IoT Device SDK 、nucleus やその他の Greengrass AWS IoT Greengrass コンポーネントと通信できます。IPC を使用するカスタムコンポーネントを開発して実行するには、 AWS IoT Device SDK を使用して AWS IoT Greengrass Core IPC サービスに接続し、IPC オペレーションを実行する必要があります。

IPC インターフェイスは、以下の 2 種類のオペレーションをサポートします。
+ **リクエスト/レスポンス**

  コンポーネントは IPC サービスにリクエストを送信し、リクエストの結果を含むレスポンスを受け取ります。
+ **サブスクリプション**

  コンポーネントはサブスクリプション要求を IPC サービスに送信し、イベントメッセージのストリームをレスポンスとして期待します。コンポーネントは、イベントメッセージ、エラー、およびストリームクロージャを処理するサブスクリプションハンドラーを提供します。には、IPC オペレーションごとに正しいレスポンスとイベントタイプを持つハンドラーインターフェイス AWS IoT Device SDK が含まれています。詳細については、「[IPC イベントストリームへのサブスクライブ](#ipc-subscribe-operations)」を参照してください。

**Topics**
+ [IPC クライアントのバージョン](#ipc-client-versions)
+ [プロセス間通信でサポートされている SDK](#ipc-requirements)
+ [AWS IoT Greengrass Core IPC サービスに接続する](#ipc-service-connect)
+ [コンポーネントに IPC オペレーションの実行を許可する](#ipc-authorization-policies)
+ [IPC イベントストリームへのサブスクライブ](#ipc-subscribe-operations)
+ [IPC ベストプラクティス](#ipc-best-practices)
+ [ローカルメッセージをパブリッシュ/サブスクライブする](ipc-publish-subscribe.md)
+ [AWS IoT Core MQTT メッセージを発行/サブスクライブする](ipc-iot-core-mqtt.md)
+ [コンポーネントライフサイクルの操作](ipc-component-lifecycle.md)
+ [コンポーネント設定とやり取り](ipc-component-configuration.md)
+ [シークレット値を取得する](ipc-secret-manager.md)
+ [ローカルシャドウとやり取り](ipc-local-shadows.md)
+ [ローカルデプロイおよびコンポーネントの管理](ipc-local-deployments-components.md)
+ [クライアントデバイスを認証して認可する](ipc-client-device-auth.md)

## IPC クライアントのバージョン
<a name="ipc-client-versions"></a>

Java および Python SDKs の以降のバージョンでは、 は IPC クライアント V2 と呼ばれる IPC クライアントの改良バージョン AWS IoT Greengrass を提供します。IPC クライアント V2
+ IPC オペレーションの使用に必要なコードの記述を削減し、IPC クライアント V1 で発生する一般的なエラーの回避に役立ちます。
+ サブスクリプションハンドラーコールバックを別のスレッドで呼び出すため、IPC 関数呼び出しの追加呼び出しを含めたブロッキングコードを、サブスクリプションハンドラーコールバック内で実行できるようになりました。IPC クライアント V1 は同じスレッドを使用して、IPC サーバーとの通信とサブスクリプションハンドラーの呼び出しを行います。
+ Lambda 式 (Java の場合) または関数 (Python の場合) を使用して、サブスクリプションオペレーションを呼び出せます。IPC クライアント V1 では、サブスクリプションハンドラクラスの定義が必要です。
+ 同期バージョンと非同期バージョンの IPC オペレーションを提供します。IPC クライアント V1 では、非同期バージョンのオペレーションのみ提供します。

これらの機能改善を利用するには、IPC クライアント V2 の使用をお勧めします。ただし、このドキュメントやオンラインコンテンツに掲載されている例の多くは、IPC クライアント V1 の使用方法のみ紹介しています。次の例とチュートリアルから、IPC クライアント V2 を使用するサンプルのコンポーネントを確認できます。
+ [PublishToTopic の例](ipc-publish-subscribe.md#ipc-operation-publishtotopic-examples)
+ [SubscribeToTopic の例](ipc-publish-subscribe.md#ipc-operation-subscribetotopic-examples)
+ [チュートリアル: コンポーネントの更新を延期する Greengrass コンポーネントを開発する](defer-component-updates-tutorial.md)
+ [チュートリアル: MQTT 経由でローカル IoT デバイスとやり取りする](client-devices-tutorial.md)

現在、 AWS IoT Device SDK for C\$1\$1 v2 は IPC クライアント V1 のみをサポートしています。

## プロセス間通信でサポートされている SDK
<a name="ipc-requirements"></a>

 AWS IoT Greengrass Core IPC ライブラリは、次の AWS IoT Device SDK バージョンに含まれています。


| SDK | 最小バージョン | 使用方法 | 
| --- | --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.6.0  |  「[for Java v2 (IPC クライアント V2) AWS IoT Device SDK の使用](#ipc-java-v2)」を参照してください。  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.9.0  |  「[for AWS IoT Device SDK Python v2 (IPC クライアント V2)](#ipc-python-v2)」を参照してください。  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  |  「[C\$1\$1 v2 AWS IoT Device SDK で を使用する](#ipc-cpp)」を参照してください。  | 
|  [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  |  「[JavaScript v2 AWS IoT Device SDK で を使用する (IPC クライアント V1)](#ipc-nodejs)」を参照してください。  | 

## AWS IoT Greengrass Core IPC サービスに接続する
<a name="ipc-service-connect"></a>

カスタムコンポーネントでプロセス間通信を使用するには、 AWS IoT Greengrass Core ソフトウェアが実行する IPC サーバーソケットへの接続を作成する必要があります。選択した言語で をダウンロードして使用するには AWS IoT Device SDK 、次のタスクを実行します。

### for Java v2 (IPC クライアント V2) AWS IoT Device SDK の使用
<a name="ipc-java-v2"></a>

**AWS IoT Device SDK for Java v2 (IPC クライアント V2) を使用するには**

1. [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2) (v1.6.0 以降) をダウンロードします。

1. <a name="use-ipc-java-component-install-step"></a>以下のいずれかを行って、コンポーネントでカスタムコードを実行します。
   + コンポーネントを を含む JAR ファイルとして構築し AWS IoT Device SDK、この JAR ファイルをコンポーネントレシピで実行します。
   +  AWS IoT Device SDK JAR をコンポーネントアーティファクトとして定義し、コンポーネントレシピでアプリケーションを実行するときにそのアーティファクトをクラスパスに追加します。

1. 以下のコードを使用して IPC クライアントを作成します。

   ```
   try (GreengrassCoreIPCClientV2 ipcClient = GreengrassCoreIPCClientV2.builder().build()) {
       // Use client.
   } catch (Exception e) {
       LOGGER.log(Level.SEVERE, "Exception occurred when using IPC.", e);
       System.exit(1);
   }
   ```

### for AWS IoT Device SDK Python v2 (IPC クライアント V2)
<a name="ipc-python-v2"></a>

**for Python v2 (IPC クライアント V2) AWS IoT Device SDK を使用するには**

1. [AWS IoT Device SDK for Python](https://github.com/aws/aws-iot-device-sdk-python-v2) (v1.9.0 以降) をダウンロードします。

1. <a name="use-ipc-python-component-install-step"></a>SDK の[インストール手順](https://github.com/aws/aws-iot-device-sdk-python-v2#installation)を、コンポーネントの recipe のインストールライフサイクルに追加します。

1.  AWS IoT Greengrass Core IPC サービスへの接続を作成します。以下のコードを使用して IPC クライアントを作成します。

   ```
   from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2
   
   try:
       ipc_client = GreengrassCoreIPCClientV2()
       # Use IPC client.
   except Exception:
       print('Exception occurred when using IPC.', file=sys.stderr)
       traceback.print_exc()
       exit(1)
   ```

### C\$1\$1 v2 AWS IoT Device SDK で を使用する
<a name="ipc-cpp"></a>

<a name="iot-device-sdk-cpp-v2-build-requirements-intro"></a> AWS IoT Device SDK v2 for C\$1\$1 を構築するには、デバイスに次のツールが必要です。<a name="iot-device-sdk-cpp-v2-build-requirements"></a>
+ C\$1\$1 11 以降
+ CMake 3.1 以降
+ 以下のいずれかのコンパイラ:
  + GCC 4.8 以降
  + Clang 3.9 以降
  + MSVC 2015 以降

**for AWS IoT Device SDK C\$1\$1 v2 を使用するには**

1. [AWS IoT Device SDK for C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2) (v1.17.0 以降) をダウンロードします。

1. [README のインストール手順に従って](https://github.com/aws/aws-iot-device-sdk-cpp-v2#Installation)、ソースから AWS IoT Device SDK for C\$1\$1 v2 を構築します。

1. C\$1\$1 ビルドツールで、前の手順でビルドした Greengrass IPC ライブラリ (`AWS::GreengrassIpc-cpp`) をリンクします。以下の `CMakeLists.txt` の例は、Greengrass IPC ライブラリを CMake でビルドしたプロジェクトにリンクします。

   ```
   cmake_minimum_required(VERSION 3.1)
   project (greengrassv2_pubsub_subscriber)
   
   file(GLOB MAIN_SRC
           "*.h"
           "*.cpp"
           )
   add_executable(${PROJECT_NAME} ${MAIN_SRC})
   
   set_target_properties(${PROJECT_NAME} PROPERTIES
           LINKER_LANGUAGE CXX
           CXX_STANDARD 11)
   find_package(aws-crt-cpp PATHS ~/sdk-cpp-workspace/build)
   find_package(EventstreamRpc-cpp PATHS ~/sdk-cpp-workspace/build)
   find_package(GreengrassIpc-cpp PATHS ~/sdk-cpp-workspace/build)
   target_link_libraries(${PROJECT_NAME} AWS::GreengrassIpc-cpp)
   ```

1. コンポーネントコードで、 AWS IoT Greengrass Core IPC サービスへの接続を作成して IPC クライアント () を作成します`Aws::Greengrass::GreengrassCoreIpcClient`。IPC の接続、切断、およびエラーイベントを処理する IPC 接続ライフサイクルハンドラーを定義する必要があります。次の例は、IPC クライアントの接続、切断、およびエラーの発生時に出力される IPC クライアントおよび IPC 接続ライフサイクルハンドラーを作成します。

   ```
   #include <iostream>
   
   #include <aws/crt/Api.h>
   #include <aws/greengrass/GreengrassCoreIpcClient.h>
   
   using namespace Aws::Crt;
   using namespace Aws::Greengrass;
   
   class IpcClientLifecycleHandler : public ConnectionLifecycleHandler {
       void OnConnectCallback() override {
           std::cout << "OnConnectCallback" << std::endl;
       }
   
       void OnDisconnectCallback(RpcError error) override {
           std::cout << "OnDisconnectCallback: " << error.StatusToString() << std::endl;
           exit(-1);
       }
   
       bool OnErrorCallback(RpcError error) override {
           std::cout << "OnErrorCallback: " << error.StatusToString() << std::endl;
           return true;
       }
   };
   
   int main() {
       // Create the IPC client.
       ApiHandle apiHandle(g_allocator);
       Io::EventLoopGroup eventLoopGroup(1);
       Io::DefaultHostResolver socketResolver(eventLoopGroup, 64, 30);
       Io::ClientBootstrap bootstrap(eventLoopGroup, socketResolver);
       IpcClientLifecycleHandler ipcLifecycleHandler;
       GreengrassCoreIpcClient ipcClient(bootstrap);
       auto connectionStatus = ipcClient.Connect(ipcLifecycleHandler).get();
       if (!connectionStatus) {
           std::cerr << "Failed to establish IPC connection: " << connectionStatus.StatusToString() << std::endl;
           exit(-1);
       }
       
       // Use the IPC client to create an operation request.
       
       // Activate the operation request.
       auto activate = operation.Activate(request, nullptr);
       activate.wait();
   
       // Wait for Greengrass Core to respond to the request.
       auto responseFuture = operation.GetResult();
       if (responseFuture.wait_for(std::chrono::seconds(timeout)) == std::future_status::timeout) {
           std::cerr << "Operation timed out while waiting for response from Greengrass Core." << std::endl;
           exit(-1);
       }
   
       // Check the result of the request.
       auto response = responseFuture.get();
       if (response) {
           std::cout << "Successfully published to topic: " << topic << std::endl;
       } else {
           // An error occurred.
           std::cout << "Failed to publish to topic: " << topic << std::endl;
           auto errorType = response.GetResultType();
           if (errorType == OPERATION_ERROR) {
               auto *error = response.GetOperationError();
               std::cout << "Operation error: " << error->GetMessage().value() << std::endl;
           } else {
               std::cout << "RPC error: " << response.GetRpcError() << std::endl;
           }
           exit(-1);
       }
       
       return 0;
   }
   ```

1. コンポーネントでカスタムコードを実行するには、コードをバイナリアーティファクトとしてビルドし、コンポーネント recipe でバイナリアーティファクトを実行します。Core AWS IoT Greengrass ソフトウェアがバイナリアーティファクトを実行`OWNER`できるようにするには、アーティファクトの`Execute`アクセス許可を に設定します。

   コンポーネント recipe の `Manifests` セクションは、次の例のようになります。

------
#### [ JSON ]

   ```
   {
     ...
     "Manifests": [
       {
         "Lifecycle": {
           "Run": "{artifacts:path}/greengrassv2_pubsub_subscriber"
         },
         "Artifacts": [
           {
             "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubSubscriberCpp/1.0.0/greengrassv2_pubsub_subscriber",
             "Permission": {
               "Execute": "OWNER"
             }
           }
         ]
       }
     ]
   }
   ```

------
#### [ YAML ]

   ```
   ...
   Manifests:
     - Lifecycle:
         Run: {artifacts:path}/greengrassv2_pubsub_subscriber
       Artifacts:
         - URI: s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubSubscriberCpp/1.0.0/greengrassv2_pubsub_subscriber
           Permission:
             Execute: OWNER
   ```

------

### JavaScript v2 AWS IoT Device SDK で を使用する (IPC クライアント V1)
<a name="ipc-nodejs"></a>

<a name="iot-device-sdk-nodejs-build-requirements-intro"></a>NodeJS で使用する AWS IoT Device SDK for JavaScript v2 を構築するには、デバイスに次のツールが必要です。<a name="iot-device-sdk-nodejs-build-requirements"></a>
+ NodeJS 10.0 以降
  + `node -v` を実行して Node のバージョンを確認します。
+ CMake 3.1 以降

**for JavaScript v2 (IPC クライアント V1) AWS IoT Device SDK を使用するには**

1. [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2) (v1.12.10 以降) をダウンロードします。

1. [README のインストール手順に従って](https://github.com/aws/aws-iot-device-sdk-js-v2/tree/v1.12.1#installation)、ソースから AWS IoT Device SDK for JavaScript v2 を構築します。

1.  AWS IoT Greengrass Core IPC サービスへの接続を作成します。次の手順を実行して、IPC クライアントを作成し、接続を確立します。

1. 以下のコードを使用して IPC クライアントを作成します。

   ```
   import * as greengrascoreipc from 'aws-iot-device-sdk-v2';
   
   let client = greengrascoreipc.createClient();
   ```

1. 次のコードを使用して、コンポーネントから Greengrass nucleus への接続を確立します。

   ```
   await client.connect();
   ```

## コンポーネントに IPC オペレーションの実行を許可する
<a name="ipc-authorization-policies"></a>

カスタムコンポーネントが IPC オペレーションの一部を使用できるようにするには、コンポーネントが特定のリソースに対しオペレーションを実行できるようにする*認可ポリシー*を定義する必要があります。各承認ポリシーは、ポリシーが許可するオペレーションのリストとリソースのリストを定義します。たとえば、パブリッシュ/サブスクライブメッセージング IPC サービスは、トピックリソースの発行およびサブスクライブのオペレーションを定義します。`*` ワイルドカードを使用すると、すべてのオペレーションまたはすべてのリソースへのアクセスを許可できます。

承認ポリシーは `accessControl` 設定パラメータで定義しますが、これはコンポーネント recipe で、またはコンポーネントをデプロイするときに設定できます。`accessControl` オブジェクトは、IPC サービス識別子を承認ポリシーのリストにマッピングします。各 IPC サービスに対しては、複数の承認ポリシーを定義してアクセスを制御できます。各承認ポリシーにはポリシー ID があり、すべてのコンポーネントで一意である必要があります。

**ヒント**  
一意のポリシー ID を作成するには、コンポーネント名、IPC サービス名、およびカウンターを組み合わせることができます。たとえば `com.example.HelloWorld` という名前のコンポーネントには、以下の ID を持つ 2 つのパブリッシュ/サブスクライブ承認ポリシーを定義できます。  
`com.example.HelloWorld:pubsub:1`
`com.example.HelloWorld:pubsub:2`

承認ポリシーは以下の形式を使用します。このオブジェクトは `accessControl` 設定パラメータです。

------
#### [ JSON ]

```
{
  "IPC service identifier": {
    "policyId": {
      "policyDescription": "description",
      "operations": [
        "operation1",
        "operation2"
      ],
      "resources": [
        "resource1",
        "resource2"
      ]
    }
  }
}
```

------
#### [ YAML ]

```
IPC service identifier:
  policyId:
    policyDescription: description
    operations:
      - operation1
      - operation2
    resources:
      - resource1
      - resource2
```

------

### 承認ポリシー内のワイルドカード
<a name="ipc-authorization-policy-wildcards"></a>

IPC 承認ポリシーの `resources` エレメントで `*` ワイルドカードを使うと、1 つの承認ポリシーにある複数のリソースにアクセスできます。
+ [Greengrass nucleus](greengrass-nucleus-component.md) の全てのバージョンにおいて、リソースとして `*` の文字を指定すると、全てのリソースにアクセスできます。
+ [Greengrass nucleus](greengrass-nucleus-component.md) の v2.6.0 以降では、リソースで `*` の文字を指定すると、どの文字列の組み合わせにも一致します。例えば `factory/1/devices/Thermostat*/status` と指定すると、工場内のサーモスタットデバイスのうち、名前が `Thermostat` で始まるすべてのデバイスのステータストピックへアクセスできます。

 AWS IoT Core MQTT IPC サービスの認可ポリシーを定義する場合、MQTT ワイルドカード (`+` および `#`) を使用して複数のリソースを照合することもできます。詳細については、[「MQTT IPC 認可ポリシー」の AWS IoT Core 「MQTT ワイルドカード](ipc-iot-core-mqtt.md#ipc-iot-core-mqtt-authorization-mqtt-wildcards)」を参照してください。

### 承認ポリシーの recipe 変数
<a name="ipc-authorization-policy-recipe-variables"></a>

[Greengrass nucleus](greengrass-nucleus-component.md) の v2.6.0 以降を使用していて、Greengrass nucleus の [interpolateComponentConfiguration](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-interpolate-component-configuration) 設定オプションを `true` に設定している場合、認可ポリシーで `{iot:thingName}` [レシピ変数](component-recipe-reference.md#recipe-variables)を使用できます。MQTT トピックやデバイスシャドウなど、コアデバイスの名前を含む承認ポリシーが必要な場合、この recipe 変数を使用すると、複数のコアデバイスからなるグループに対して、1 つの承認ポリシーを設定できます。例えば、シャドウ IPC オペレーションのために、コンポーネントに次のリソースへのアクセスを許可することができます。

```
$aws/things/{iot:thingName}/shadow/
```

### 承認ポリシーの特殊文字
<a name="ipc-authorization-policy-special-characters"></a>

承認ポリシーで `*` または `?` をリテラル文字として指定するには、エスケープシーケンスを使う必要があります。次のエスケープシーケンスは、キャラクターの特別な意味の代わりにリテラル値を使用するように AWS IoT Greengrass Core ソフトウェアに指示します。例えば、 `*` の文字は任意の文字の組み合わせに一致する[ワイルドカード](#ipc-authorization-policy-wildcards)です。


| リテラル文字 | エスケープシーケンス | 注意事項 | 
| --- | --- | --- | 
|  `*`  |  `${*}`  |  | 
|  `?`  |  `${?}`  |  AWS IoT Greengrass は現在、任意の 1 文字に一致する`?`ワイルドカードをサポートしていません。  | 
|  `$`  |  `${$}`  |  このエスケープシーケンスを使用すると、`${` を含むリソースに一致します。例えば、`${resourceName}` という名前のリソースに一致させるには、`${$}{resourceName}` と指定する必要があります。もしくは、`$aws` で始まるトピックへアクセスできるように、リテラルの `$` を使って `$` を含むリソースに一致させます。  | 

### 承認ポリシーの例
<a name="ipc-authorization-policy-examples"></a>

次の承認ポリシーの例を参照して、コンポーネントの承認ポリシー設定の参考にできます。

**Example 承認ポリシーを使用したコンポーネント recipe の例**  
次のコンポーネント recipe の例には、承認ポリシーを定義する `accessControl` オブジェクトが含まれます。このポリシーは `com.example.HelloWorld` コンポーネントを承認して `test/topic` トピックに発行します。  

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.HelloWorld",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.HelloWorld:pubsub:1": {
            "policyDescription": "Allows access to publish to test/topic.",
            "operations": [
              "aws.greengrass#PublishToTopic"
            ],
            "resources": [
              "test/topic"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Lifecycle": {
        "Run": "java -jar {artifacts:path}/HelloWorld.jar"
      }
    }
  ]
}
```

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.HelloWorld
ComponentVersion: '1.0.0'
ComponentDescription: A component that publishes messages.
ComponentPublisher: Amazon
ComponentConfiguration:
  DefaultConfiguration:
    accessControl:
      aws.greengrass.ipc.pubsub:
        "com.example.HelloWorld:pubsub:1":
          policyDescription: Allows access to publish to test/topic.
          operations:
            - "aws.greengrass#PublishToTopic"
          resources:
            - "test/topic"
Manifests:
  - Lifecycle:
      Run: |-
        java -jar {artifacts:path}/HelloWorld.jar
```

**Example 承認ポリシーを使用したコンポーネント設定更新の例**  
次のデプロイの設定更新の例では、承認ポリシーを定義する `accessControl` オブジェクトでコンポーネントを設定することが指定されています。このポリシーは `com.example.HelloWorld` コンポーネントを承認して `test/topic` トピックに発行します。    
**マージする設定**  

```
{
  "accessControl": {
    "aws.greengrass.ipc.pubsub": {
      "com.example.HelloWorld:pubsub:1": {
        "policyDescription": "Allows access to publish to test/topic.",
        "operations": [
          "aws.greengrass#PublishToTopic"
        ],
        "resources": [
          "test/topic"
        ]
      }
    }
  }
}
```
次のコマンドは、コアデバイスにデプロイを作成します。  

```
aws greengrassv2 create-deployment --cli-input-json file://hello-world-deployment.json
```
`hello-world-deployment.json` ファイルには、次の JSON ドキュメントが含まれています。  

```
{
  "targetArn": "arn:aws:iot:us-west-2:123456789012:thing/MyGreengrassCore",
  "deploymentName": "Deployment for MyGreengrassCore",
  "components": {
    "com.example.HelloWorld": {
      "componentVersion": "1.0.0",
      "configurationUpdate": {
        "merge": "{\"accessControl\":{\"aws.greengrass.ipc.pubsub\":{\"com.example.HelloWorld:pubsub:1\":{\"policyDescription\":\"Allows access to publish to test/topic.\",\"operations\":[\"aws.greengrass#PublishToTopic\"],\"resources\":[\"test/topic\"]}}}}"
      }
    }
  }
}
```
次の [Greengrass CLI](greengrass-cli-component.md) コマンドは、コアデバイスにローカルデプロイを作成します。  

```
sudo greengrass-cli deployment create \
  --recipeDir recipes \
  --artifactDir artifacts \
  --merge "com.example.HelloWorld=1.0.0" \
  --update-config hello-world-configuration.json
```
`hello-world-configuration.json` ファイルには、次の JSON ドキュメントが含まれています。  

```
{
  "com.example.HelloWorld": {
    "MERGE": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.HelloWorld:pubsub:1": {
            "policyDescription": "Allows access to publish to test/topic.",
            "operations": [
              "aws.greengrass#PublishToTopic"
            ],
            "resources": [
              "test/topic"
            ]
          }
        }
      }
    }
  }
}
```

## IPC イベントストリームへのサブスクライブ
<a name="ipc-subscribe-operations"></a>

IPC オペレーションを使用して、Greengrass コアデバイスのイベントのストリームにサブスクライブできます。サブスクライブオペレーションを使用するには、*サブスクリプションハンドラー*を定義して、IPC サービスへのリクエストを作成します。これで IPC クライアントは、コアデバイスがコンポーネントにイベントメッセージをストリーミングするたびに、サブスクリプションハンドラーの関数が実行するようになります。

サブスクリプションを閉じると、イベントメッセージの処理を停止できます。これを行うには、サブスクリプションを開くときに使用したサブスクリプションオペレーションオブジェクトで、`closeStream()` (Java)、`close()` (Python)、または `Close()` (C\$1\$1) を呼び出します。

 AWS IoT Greengrass Core IPC サービスは、次のサブスクライブオペレーションをサポートしています。
+ [SubscribeToTopic](ipc-publish-subscribe.md#ipc-operation-subscribetotopic)
+ [SubscribeToIoTCore](ipc-iot-core-mqtt.md#ipc-operation-subscribetoiotcore)
+ [SubscribeToComponentUpdates](ipc-component-lifecycle.md#ipc-operation-subscribetocomponentupdates)
+ [SubscribeToConfigurationUpdate](ipc-component-configuration.md#ipc-operation-subscribetoconfigurationupdate)
+ [SubscribeToValidateConfigurationUpdates](ipc-component-configuration.md#ipc-operation-subscribetovalidateconfigurationupdates)

**Topics**
+ [サブスクリプションハンドラーの定義](#ipc-define-subscription-handlers)
+ [サブスクリプションハンドラーの例](#ipc-subscription-handler-examples)

### サブスクリプションハンドラーの定義
<a name="ipc-define-subscription-handlers"></a>

サブスクリプションハンドラーを定義するには、イベントメッセージ、エラー、およびストリームクロージャを処理するコールバック関数を定義します。IPC クライアント V1 を使用する場合は、クラス内でこれらの関数を定義する必要があります。最近の Java または Python SDK で利用可能な IPC クライアント V2 を使用している場合、サブスクリプションハンドラークラスを作成しなくても、これらの関数を定義できます。

------
#### [ Java ]

IPC クライアント V1 を使用している場合は、一般的な `software.amazon.awssdk.eventstreamrpc.StreamResponseHandler<StreamEventType>` インターフェイスを実装する必要があります。*StreamEventType* は、サブスクリプションオペレーションのイベントメッセージのタイプです。次の関数を定義して、イベントメッセージ、エラー、およびストリームクロージャを処理します。

IPC クライアント V2 を使用している場合は、サブスクリプションハンドラクラスの外部でこれらの関数を定義するか、[Lambda 式](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html)を使います。

`void onStreamEvent(StreamEventType event)`  
IPC クライアントが MQTT メッセージやコンポーネント更新通知などのイベントメッセージを受信したときに呼び出すコールバック。

`boolean onStreamError(Throwable error)`  
ストリームエラーが発生したときに IPC クライアントが呼び出すコールバック。  
<a name="ipc-subscription-handler-on-stream-error-return-value"></a>エラーの結果としてサブスクリプションストリームを閉じるには true を返し、ストリームを開いたままにするには false を返します。

`void onStreamClosed()`  
ストリームが閉じたときに IPC クライアントが呼び出すコールバック。

------
#### [ Python ]

IPC クライアント V1 を使用している場合、サブスクリプションオペレーションに対応するストリームレスポンスハンドラークラスを拡張する必要があります。には、各サブスクリプションオペレーションのサブスクリプションハンドラークラス AWS IoT Device SDK が含まれています。*StreamEventType* は、サブスクリプションオペレーションのイベントメッセージのタイプです。次の関数を定義して、イベントメッセージ、エラー、およびストリームクロージャを処理します。

IPC クライアント V2 を使用している場合は、サブスクリプションハンドラクラスの外部でこれらの関数を定義するか、[Lambda 式](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions)を使います。

`def on_stream_event(self, event: StreamEventType) -> None`  
IPC クライアントが MQTT メッセージやコンポーネント更新通知などのイベントメッセージを受信したときに呼び出すコールバック。

`def on_stream_error(self, error: Exception) -> bool`  
ストリームエラーが発生したときに IPC クライアントが呼び出すコールバック。  
<a name="ipc-subscription-handler-on-stream-error-return-value"></a>エラーの結果としてサブスクリプションストリームを閉じるには true を返し、ストリームを開いたままにするには false を返します。

`def on_stream_closed(self) -> None`  
ストリームが閉じたときに IPC クライアントが呼び出すコールバック。

------
#### [ C\$1\$1 (IPC client V1) ]

サブスクリプションオペレーションに対応するストリームレスポンスハンドラークラスから派生したクラスを実装します。には、各サブスクリプションオペレーションのサブスクリプションハンドラーベースクラス AWS IoT Device SDK が含まれています。*StreamEventType* は、サブスクリプションオペレーションのイベントメッセージのタイプです。次の関数を定義して、イベントメッセージ、エラー、およびストリームクロージャを処理します。

`void OnStreamEvent(StreamEventType *event)`  
IPC クライアントが MQTT メッセージやコンポーネント更新通知などのイベントメッセージを受信したときに呼び出すコールバック。

`bool OnStreamError(OperationError *error)`  
ストリームエラーが発生したときに IPC クライアントが呼び出すコールバック。  
<a name="ipc-subscription-handler-on-stream-error-return-value"></a>エラーの結果としてサブスクリプションストリームを閉じるには true を返し、ストリームを開いたままにするには false を返します。

`void OnStreamClosed()`  
ストリームが閉じたときに IPC クライアントが呼び出すコールバック。

------
#### [ JavaScript ]

サブスクリプションオペレーションに対応するストリームレスポンスハンドラークラスから派生したクラスを実装します。には、各サブスクリプションオペレーションのサブスクリプションハンドラーベースクラス AWS IoT Device SDK が含まれています。*StreamEventType* は、サブスクリプションオペレーションのイベントメッセージのタイプです。次の関数を定義して、イベントメッセージ、エラー、およびストリームクロージャを処理します。

`on(event: 'ended', listener: StreamingOperationEndedListener)`  
ストリームが閉じたときに IPC クライアントが呼び出すコールバック。

`on(event: 'streamError', listener: StreamingRpcErrorListener)`  
ストリームエラーが発生したときに IPC クライアントが呼び出すコールバック。  
<a name="ipc-subscription-handler-on-stream-error-return-value"></a>エラーの結果としてサブスクリプションストリームを閉じるには true を返し、ストリームを開いたままにするには false を返します。

`on(event: 'message', listener: (message: InboundMessageType) => void)`  
IPC クライアントが MQTT メッセージやコンポーネント更新通知などのイベントメッセージを受信したときに呼び出すコールバック。

------

### サブスクリプションハンドラーの例
<a name="ipc-subscription-handler-examples"></a>

次の例は、[SubscribeToTopic](ipc-publish-subscribe.md#ipc-operation-subscribetotopic) オペレーションと、ローカルのパブリッシュ/サブスクライブメッセージにサブスクライブするためのサブスクリプションハンドラーの使用方法を示します。

------
#### [ Java (IPC client V2) ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  <a name="ipc-operation-subscribetotopic-example-java-v2"></a>

```
package com.aws.greengrass.docs.samples.ipc;

import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClientV2;
import software.amazon.awssdk.aws.greengrass.SubscribeToTopicResponseHandler;
import software.amazon.awssdk.aws.greengrass.model.*;

import java.nio.charset.StandardCharsets;
import java.util.Optional;

public class SubscribeToTopicV2 {

    public static void main(String[] args) {
        String topic = args[0];
        try (GreengrassCoreIPCClientV2 ipcClient = GreengrassCoreIPCClientV2.builder().build()) {
            SubscribeToTopicRequest request = new SubscribeToTopicRequest().withTopic(topic);
            GreengrassCoreIPCClientV2.StreamingResponse<SubscribeToTopicResponse,
                    SubscribeToTopicResponseHandler> response =
                    ipcClient.subscribeToTopic(request, SubscribeToTopicV2::onStreamEvent,
                            Optional.of(SubscribeToTopicV2::onStreamError),
                            Optional.of(SubscribeToTopicV2::onStreamClosed));
            SubscribeToTopicResponseHandler responseHandler = response.getHandler();
            System.out.println("Successfully subscribed to topic: " + topic);

            // Keep the main thread alive, or the process will exit.
            try {
                while (true) {
                    Thread.sleep(10000);
                }
            } catch (InterruptedException e) {
                System.out.println("Subscribe interrupted.");
            }

            // To stop subscribing, close the stream.
            responseHandler.closeStream();
        } catch (Exception e) {
            if (e.getCause() instanceof UnauthorizedError) {
                System.err.println("Unauthorized error while publishing to topic: " + topic);
            } else {
                System.err.println("Exception occurred when using IPC.");
            }
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static void onStreamEvent(SubscriptionResponseMessage subscriptionResponseMessage) {
        try {
            BinaryMessage binaryMessage = subscriptionResponseMessage.getBinaryMessage();
            String message = new String(binaryMessage.getMessage(), StandardCharsets.UTF_8);
            String topic = binaryMessage.getContext().getTopic();
            System.out.printf("Received new message on topic %s: %s%n", topic, message);
        } catch (Exception e) {
            System.err.println("Exception occurred while processing subscription response " +
                    "message.");
            e.printStackTrace();
        }
    }

    public static boolean onStreamError(Throwable error) {
        System.err.println("Received a stream error.");
        error.printStackTrace();
        return false; // Return true to close stream, false to keep stream open.
    }

    public static void onStreamClosed() {
        System.out.println("Subscribe to topic stream closed.");
    }
}
```

------
#### [ Python (IPC client V2) ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  <a name="ipc-operation-subscribetotopic-example-python-v2"></a>

```
import sys
import time
import traceback

from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2
from awsiot.greengrasscoreipc.model import (
    SubscriptionResponseMessage,
    UnauthorizedError
)


def main():
    args = sys.argv[1:]
    topic = args[0]

    try:
        ipc_client = GreengrassCoreIPCClientV2()
        # Subscription operations return a tuple with the response and the operation.
        _, operation = ipc_client.subscribe_to_topic(topic=topic, on_stream_event=on_stream_event,
                                                     on_stream_error=on_stream_error, on_stream_closed=on_stream_closed)
        print('Successfully subscribed to topic: ' + topic)

        # Keep the main thread alive, or the process will exit.
        try:
            while True:
                time.sleep(10)
        except InterruptedError:
            print('Subscribe interrupted.')

        # To stop subscribing, close the stream.
        operation.close()
    except UnauthorizedError:
        print('Unauthorized error while subscribing to topic: ' +
              topic, file=sys.stderr)
        traceback.print_exc()
        exit(1)
    except Exception:
        print('Exception occurred', file=sys.stderr)
        traceback.print_exc()
        exit(1)


def on_stream_event(event: SubscriptionResponseMessage) -> None:
    try:
        message = str(event.binary_message.message, 'utf-8')
        topic = event.binary_message.context.topic
        print('Received new message on topic %s: %s' % (topic, message))
    except:
        traceback.print_exc()


def on_stream_error(error: Exception) -> bool:
    print('Received a stream error.', file=sys.stderr)
    traceback.print_exc()
    return False  # Return True to close stream, False to keep stream open.


def on_stream_closed() -> None:
    print('Subscribe to topic stream closed.')


if __name__ == '__main__':
    main()
```

------
#### [ C\$1\$1 (IPC client V1) ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  <a name="ipc-operation-subscribetotopic-example-cpp"></a>

```
#include <iostream>

#include </crt/Api.h>
#include <aws/greengrass/GreengrassCoreIpcClient.h>

using namespace Aws::Crt;
using namespace Aws::Greengrass;

class SubscribeResponseHandler : public SubscribeToTopicStreamHandler {
    public:
        virtual ~SubscribeResponseHandler() {}

    private:
        void OnStreamEvent(SubscriptionResponseMessage *response) override {
            auto jsonMessage = response->GetJsonMessage();
            if (jsonMessage.has_value() && jsonMessage.value().GetMessage().has_value()) {
                auto messageString = jsonMessage.value().GetMessage().value().View().WriteReadable();
                // Handle JSON message.
            } else {
                auto binaryMessage = response->GetBinaryMessage();
                if (binaryMessage.has_value() && binaryMessage.value().GetMessage().has_value()) {
                    auto messageBytes = binaryMessage.value().GetMessage().value();
                    std::string messageString(messageBytes.begin(), messageBytes.end());
                    // Handle binary message.
                }
            }
        }

        bool OnStreamError(OperationError *error) override {
            // Handle error.
            return false; // Return true to close stream, false to keep stream open.
        }

        void OnStreamClosed() override {
            // Handle close.
        }
};

class IpcClientLifecycleHandler : public ConnectionLifecycleHandler {
    void OnConnectCallback() override {
        // Handle connection to IPC service.
    }

    void OnDisconnectCallback(RpcError error) override {
        // Handle disconnection from IPC service.
    }

    bool OnErrorCallback(RpcError error) override {
        // Handle IPC service connection error.
        return true;
    }
};

int main() {
    ApiHandle apiHandle(g_allocator);
    Io::EventLoopGroup eventLoopGroup(1);
    Io::DefaultHostResolver socketResolver(eventLoopGroup, 64, 30);
    Io::ClientBootstrap bootstrap(eventLoopGroup, socketResolver);
    IpcClientLifecycleHandler ipcLifecycleHandler;
    GreengrassCoreIpcClient ipcClient(bootstrap);
    auto connectionStatus = ipcClient.Connect(ipcLifecycleHandler).get();
    if (!connectionStatus) {
        std::cerr << "Failed to establish IPC connection: " << connectionStatus.StatusToString() << std::endl;
        exit(-1);
    }

    String topic("my/topic");
    int timeout = 10;

    SubscribeToTopicRequest request;
    request.SetTopic(topic);

    //SubscribeResponseHandler streamHandler;
    auto streamHandler = MakeShared<SubscribeResponseHandler>(DefaultAllocator());
    auto operation = ipcClient.NewSubscribeToTopic(streamHandler);
    auto activate = operation->Activate(request, nullptr);
    activate.wait();

    auto responseFuture = operation->GetResult();
    if (responseFuture.wait_for(std::chrono::seconds(timeout)) == std::future_status::timeout) {
        std::cerr << "Operation timed out while waiting for response from Greengrass Core." << std::endl;
        exit(-1);
    }

    auto response = responseFuture.get();
    if (!response) {
        // Handle error.
        auto errorType = response.GetResultType();
        if (errorType == OPERATION_ERROR) {
            auto *error = response.GetOperationError();
            (void)error;
            // Handle operation error.
        } else {
            // Handle RPC error.
        }
        exit(-1);
    }

    // Keep the main thread alive, or the process will exit.
    while (true) {
        std::this_thread::sleep_for(std::chrono::seconds(10));
    }

    operation->Close();
    return 0;
}
```

------
#### [ JavaScript ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  <a name="ipc-operation-subscribetotopic-example-nodejs"></a>

```
import * as greengrasscoreipc from "aws-iot-device-sdk-v2/dist/greengrasscoreipc";
import {SubscribeToTopicRequest, SubscriptionResponseMessage} from "aws-iot-device-sdk-v2/dist/greengrasscoreipc/model";
import {RpcError} from "aws-iot-device-sdk-v2/dist/eventstream_rpc";
 
class SubscribeToTopic {
    private ipcClient : greengrasscoreipc.Client
    private readonly topic : string;
 
    constructor() {
        // define your own constructor, e.g.
        this.topic = "<define_your_topic>";
        this.subscribeToTopic().then(r => console.log("Started workflow"));
    }
 
    private async subscribeToTopic() {
        try {
            this.ipcClient = await getIpcClient();
 
            const subscribeToTopicRequest : SubscribeToTopicRequest = {
                topic: this.topic,
            }
 
            const streamingOperation = this.ipcClient.subscribeToTopic(subscribeToTopicRequest, undefined); // conditionally apply options
 
            streamingOperation.on("message", (message: SubscriptionResponseMessage) => {
                // parse the message depending on your use cases, e.g.
                if(message.binaryMessage && message.binaryMessage.message) {
                    const receivedMessage = message.binaryMessage?.message.toString();
                }
            });
 
            streamingOperation.on("streamError", (error : RpcError) => {
                // define your own error handling logic
            })
 
            streamingOperation.on("ended", () => {
                // define your own logic
            })
 
            await streamingOperation.activate();
 
            // Keep the main thread alive, or the process will exit.
            await new Promise((resolve) => setTimeout(resolve, 10000))
        } catch (e) {
            // parse the error depending on your use cases
            throw e
        }
    }
}
 
export async function getIpcClient(){
    try {
        const ipcClient = greengrasscoreipc.createClient();
        await ipcClient.connect()
            .catch(error => {
                // parse the error depending on your use cases
                throw error;
            });
        return ipcClient
    } catch (err) {
        // parse the error depending on your use cases
        throw err
    }
}
 
// starting point
const subscribeToTopic = new SubscribeToTopic();
```

------
#### [ Rust ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  

```
use gg_sdk::{Sdk, SubscribeToTopicPayload};
use std::{thread, time::Duration};

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    let topic = "my/topic";

    let callback = |topic: &str, payload: SubscribeToTopicPayload| match payload
    {
        SubscribeToTopicPayload::Binary(message) => {
            let message = String::from_utf8_lossy(message);
            println!("Received new message on topic {topic}: {message}");
        }
        SubscribeToTopicPayload::Json(_) => {
            println!("Received new message on topic {topic}: (JSON message)");
        }
    };

    let _sub = sdk
        .subscribe_to_topic(topic, &callback)
        .expect("Failed to subscribe to topic");

    println!("Successfully subscribed to topic: {topic}");

    // Keep the main thread alive, or the process will exit.
    loop {
        thread::sleep(Duration::from_secs(10));
    }
}
```

------
#### [ C ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  

```
#include <assert.h>
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/object.h>
#include <gg/sdk.h>
#include <gg/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static void on_subscription_response(
    void *ctx, GgBuffer topic, GgObject payload, GgIpcSubscriptionHandle handle
) {
    (void) ctx;
    (void) handle;

    if (gg_obj_type(payload) == GG_TYPE_BUF) {
        GgBuffer message = gg_obj_into_buf(payload);
        printf(
            "Received new message on topic %.*s: %.*s\n",
            (int) topic.len,
            topic.data,
            (int) message.len,
            message.data
        );
    } else {
        assert(gg_obj_type(payload) == GG_TYPE_MAP);
        printf(
            "Received new message on topic %.*s: (JSON message)\n",
            (int) topic.len,
            topic.data
        );
    }
}

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    GgBuffer topic = GG_STR("my/topic");

    GgIpcSubscriptionHandle handle;
    err = ggipc_subscribe_to_topic(
        topic, on_subscription_response, NULL, &handle
    );
    if (err != GG_ERR_OK) {
        fprintf(
            stderr,
            "Failed to subscribe to topic: %.*s\n",
            (int) topic.len,
            topic.data
        );
        exit(-1);
    }

    printf(
        "Successfully subscribed to topic: %.*s\n", (int) topic.len, topic.data
    );

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }

    // To stop subscribing, close the stream.
    ggipc_close_subscription(handle);
}
```

------
#### [ C\$1\$1 (Component SDK) ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  

```
#include <gg/ipc/client.hpp>
#include <gg/object.hpp>
#include <unistd.h>
#include <cassert>
#include <iostream>

class ResponseHandler : public gg::ipc::LocalTopicCallback {
    void operator()(
        std::string_view topic,
        gg::Object payload,
        gg::ipc::Subscription &handle
    ) override {
        (void) handle;
        if (payload.index() == GG_TYPE_BUF) {
            std::cout << "Received new message on topic " << topic << ": "
                      << get<gg::Buffer>(payload) << "\n";
        } else {
            assert(payload.index() == GG_TYPE_MAP);
            std::cout << "Received new message on topic " << topic
                      << ": (JSON message)\n";
        }
    }
};

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    std::string_view topic = "my/topic";

    static ResponseHandler handler;
    error = client.subscribe_to_topic(topic, handler);
    if (error) {
        std::cerr << "Failed to subscribe to topic: " << topic << "\n";
        exit(-1);
    }

    std::cout << "Successfully subscribed to topic: " << topic << "\n";

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }
}
```

------

## IPC ベストプラクティス
<a name="ipc-best-practices"></a>

カスタムコンポーネントで IPC を使用する場合のベストプラクティスは、IPC クライアント V1 と IPC クライアント V2 とで異なります。使用する IPC クライアントのバージョンのベストプラクティスに従ってください。

------
#### [ IPC client V2 ]

IPC クライアント V2 は、別のスレッドでコールバック関数を実行するため、IPC クライアント V1 と比較すると、IPC を使用する場合や、サブスクリプションハンドラ関数を記述する場合に、従うべきガイドラインが少なくなります。
+ <a name="ipc-best-practice-reuse-one-client"></a>**1 つの IPC クライアントを再利用する**

  IPC クライアントを作成したら、そのクライアントを開いたままにして、全ての IPC オペレーションに再利用します。複数のクライアントを作成すると、リソースが余分に消費され、リソースリークが発生する可能性があります。
+ **例外を処理する**

  IPC クライアント V2 は、サブスクリプションハンドラー関数でキャッチされない例外をログに記録します。コードで発生したエラーを処理するには、ハンドラー関数で例外をキャッチする必要があります。

------
#### [ IPC client V1 ]

IPC クライアント V1 は単一のスレッドを使用し、IPC サーバーとの通信とサブスクリプションハンドラーの呼び出しを行います。サブスクリプションハンドラー関数を記述するときは、この同期動作を考慮する必要があります。
+ <a name="ipc-best-practice-reuse-one-client"></a>**1 つの IPC クライアントを再利用する**

  IPC クライアントを作成したら、そのクライアントを開いたままにして、全ての IPC オペレーションに再利用します。複数のクライアントを作成すると、リソースが余分に消費され、リソースリークが発生する可能性があります。
+ **ブロッキングコードを非同期で実行する**

  IPC クライアント V1 は、スレッドがブロックされている間は、新しいリクエストの送信や新しいイベントメッセージの処理を行うことはできません。ブロッキングコードは、ハンドラー関数から実行する別個のスレッドで実行するべきです。ブロックコードには `sleep` 呼び出し、連続して実行されるループ、および完了までに時間がかかる同期 I/O リクエストなどがあります。
+ **新しい IPC 要求を非同期で送信する**

  IPC クライアント V1 はサブスクリプションハンドラー関数内から新しいリクエストを送信できません。これは、応答を待機するとリクエストによってハンドラー関数がブロックされるためです。IPC リクエストの送信は、ハンドラー関数から実行する別個のスレッドで行うべきです。
+ **例外を処理する**

  IPC クライアント V1 は、キャッチされない例外はサブスクリプションハンドラー関数で処理しません。ハンドラー関数が例外をスローすると、サブスクリプションが閉じて、例外はコンポーネントログに表示されません。ハンドラー関数で例外をキャッチして、サブスクリプションを開いたままにし、コードで発生したエラーをログに記録してください。

------

# ローカルメッセージをパブリッシュ/サブスクライブする
<a name="ipc-publish-subscribe"></a>

パブリッシュ/サブスクライブ (pubsub) メッセージを使用すると、トピックにメッセージを送受信できます。コンポーネントはメッセージをトピックに発行して、他のコンポーネントにメッセージを送信できます。その後、そのトピックをサブスクライブしているコンポーネントは、受信したメッセージに対応できます。

**注記**  
このパブリッシュ/サブスクライブ IPC サービスを使用して、 AWS IoT Core MQTT を公開またはサブスクライブすることはできません。 AWS IoT Core MQTT とメッセージを交換する方法の詳細については、「」を参照してください[AWS IoT Core MQTT メッセージを発行/サブスクライブする](ipc-iot-core-mqtt.md)。

**Topics**
+ [最小 SDK バージョン](#ipc-publish-subscribe-sdk-versions)
+ [Authorization](#ipc-publish-subscribe-authorization)
+ [PublishToTopic](#ipc-operation-publishtotopic)
+ [SubscribeToTopic](#ipc-operation-subscribetotopic)
+ [例](#ipc-publish-subscribe-examples)

## 最小 SDK バージョン
<a name="ipc-publish-subscribe-sdk-versions"></a>

次の表に、ローカルトピックとの間でメッセージを発行およびサブスクライブするために使用 AWS IoT Device SDK する必要がある の最小バージョンを示します。


| SDK | 最小バージョン | 
| --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK for JavaScript](https://github.com/aws/aws-iot-device-sdk-js-v2) v2  |  v1.12.0  | 

## Authorization
<a name="ipc-publish-subscribe-authorization"></a>

ローカルのパブリッシュ/サブスクライブメッセージングをカスタムコンポーネントで使用するには、コンポーネントがトピックにメッセージを送受信できるようにする承認ポリシーを定義する必要があります。承認ポリシーの定義については、「[コンポーネントに IPC オペレーションの実行を許可する](interprocess-communication.md#ipc-authorization-policies)」を参照してください。

パブリッシュ/サブスクライブメッセージングの承認ポリシーには以下のプロパティがあります。

**IPC サービス識別子:** `aws.greengrass.ipc.pubsub`


| 運用 | 説明 | リソース | 
| --- | --- | --- | 
|  `aws.greengrass#PublishToTopic`  |  コンポーネントが指定したトピックにメッセージを発行できるようにします。  |  `test/topic` などのトピック文字列。トピック内の任意の文字の組み合わせに一致させるには `*` を使用します。 このトピック文字列は、MQTT トピックのワイルドカード (`#` および `+`) をサポートしません。  | 
|  `aws.greengrass#SubscribeToTopic`  |  コンポーネントが、指定したトピックに関するメッセージをサブスクライブできるようにします。  |  `test/topic` などのトピック文字列。トピック内の任意の文字の組み合わせに一致させるには `*` を使用します。 <a name="ipc-local-publish-subscribe-authorization-mqtt-wildcards"></a>[Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 以降では、MQTT トピックワイルドカード (`#` および `+`) を含むトピックをサブスクライブできます。このトピック文字列は MQTT トピックのワイルドカードを文字そのものとしてサポートします。例えば、コンポーネントの承認ポリシーで `test/topic/#` へのアクセス権が付与されている場合、コンポーネントは `test/topic/#` をサブスクライブできますが、`test/topic/filter` はサブスクライブできません。  | 
|  `*`  |  コンポーネントが、指定したトピックのメッセージを発行およびサブスクライブできるようにします。  |  `test/topic` などのトピック文字列。トピック内の任意の文字の組み合わせに一致させるには `*` を使用します。 <a name="ipc-local-publish-subscribe-authorization-mqtt-wildcards"></a>[Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 以降では、MQTT トピックワイルドカード (`#` および `+`) を含むトピックをサブスクライブできます。このトピック文字列は MQTT トピックのワイルドカードを文字そのものとしてサポートします。例えば、コンポーネントの承認ポリシーで `test/topic/#` へのアクセス権が付与されている場合、コンポーネントは `test/topic/#` をサブスクライブできますが、`test/topic/filter` はサブスクライブできません。  | 

### 承認ポリシーの例
<a name="ipc-publish-subscribe-authorization-policy-examples"></a>

次の承認ポリシーの例を参照して、コンポーネントの承認ポリシーの設定に役立てることができます。

**Example 承認ポリシーの例**  
以下の承認ポリシーの例では、コンポーネントがすべてのトピックを公開およびサブスクライブすることを許可します。  

```
{
  "accessControl": {
    "aws.greengrass.ipc.pubsub": {
      "com.example.MyLocalPubSubComponent:pubsub:1": {
        "policyDescription": "Allows access to publish/subscribe to all topics.",
        "operations": [
          "aws.greengrass#PublishToTopic",
          "aws.greengrass#SubscribeToTopic"
        ],
        "resources": [
          "*"
        ]
      }
    }
  }
}
```

## PublishToTopic
<a name="ipc-operation-publishtotopic"></a>

トピックへのメッセージの発行

### リクエスト
<a name="ipc-operation-publishtotopic-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`topic`  
メッセージの発行先として指定するトピック。

`publishMessage` (Python: `publish_message`)  
発行するメッセージ。このオブジェクト (`PublishMessage`) には、次の情報が含まれます。`jsonMessage` と `binaryMessage` のどちらか 1 つを指定する必要があります。  <a name="ipc-publish-subscribe-message-shape"></a>  
`jsonMessage` (Python: `json_message`)  
(オプション) JSON メッセージ。このオブジェクト (`JsonMessage`) には、次の情報が含まれます。    
`message`  
オブジェクトとしての JSON メッセージ。  
`context`  <a name="ipc-publish-subscribe-message-context-variable"></a>
メッセージが公開されたトピックなど、メッセージのコンテキスト。  
この機能は、[Greengrass nucleus コンポーネント](greengrass-nucleus-component.md)の v2.6.0 以降で利用できます。次の表に、メッセージコンテキストへのアクセスに使用する必要がある AWS IoT Device SDK の最小バージョンを示します。      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-publish-subscribe.html)
 AWS IoT Greengrass Core ソフトウェアは、 `PublishToTopic` および `SubscribeToTopic`オペレーションで同じメッセージオブジェクトを使用します。 AWS IoT Greengrass Core ソフトウェアは、サブスクライブ時にこのコンテキストオブジェクトをメッセージに設定し、発行するメッセージではこのコンテキストオブジェクトを無視します。
このオブジェクト (`MessageContext`) には、次の情報が含まれます。    
`topic`  
メッセージが発行されたトピック。  
`binaryMessage` (Python: `binary_message`)  
(オプション) バイナリメッセージ。このオブジェクト (`BinaryMessage`) には、次の情報が含まれます。    
`message`  
BLOB としてのバイナリメッセージ。  
`context`  <a name="ipc-publish-subscribe-message-context-variable"></a>
メッセージが公開されたトピックなど、メッセージのコンテキスト。  
この機能は、[Greengrass nucleus コンポーネント](greengrass-nucleus-component.md)の v2.6.0 以降で利用できます。次の表に、メッセージコンテキストへのアクセスに使用する必要がある AWS IoT Device SDK の最小バージョンを示します。      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-publish-subscribe.html)
 AWS IoT Greengrass Core ソフトウェアは、 `PublishToTopic` および `SubscribeToTopic`オペレーションで同じメッセージオブジェクトを使用します。 AWS IoT Greengrass Core ソフトウェアは、サブスクライブ時にこのコンテキストオブジェクトをメッセージに設定し、発行するメッセージではこのコンテキストオブジェクトを無視します。
このオブジェクト (`MessageContext`) には、次の情報が含まれます。    
`topic`  
メッセージが発行されたトピック。

### 応答
<a name="ipc-operation-publishtotopic-response"></a>

このオペレーションはレスポンスで一切の情報を提供しません。

### 例
<a name="ipc-operation-publishtotopic-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Java (IPC client V2) ]

**Example 例: バイナリメッセージを発行する**  

```
package com.aws.greengrass.docs.samples.ipc;

import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClientV2;
import software.amazon.awssdk.aws.greengrass.model.BinaryMessage;
import software.amazon.awssdk.aws.greengrass.model.PublishMessage;
import software.amazon.awssdk.aws.greengrass.model.PublishToTopicRequest;
import software.amazon.awssdk.aws.greengrass.model.PublishToTopicResponse;
import software.amazon.awssdk.aws.greengrass.model.UnauthorizedError;

import java.nio.charset.StandardCharsets;

public class PublishToTopicV2 {

    public static void main(String[] args) {
        String topic = args[0];
        String message = args[1];
        try (GreengrassCoreIPCClientV2 ipcClient = GreengrassCoreIPCClientV2.builder().build()) {
            PublishToTopicV2.publishBinaryMessageToTopic(ipcClient, topic, message);
            System.out.println("Successfully published to topic: " + topic);
        } catch (Exception e) {
            if (e.getCause() instanceof UnauthorizedError) {
                System.err.println("Unauthorized error while publishing to topic: " + topic);
            } else {
                System.err.println("Exception occurred when using IPC.");
            }
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static PublishToTopicResponse publishBinaryMessageToTopic(
            GreengrassCoreIPCClientV2 ipcClient, String topic, String message) throws InterruptedException {
        BinaryMessage binaryMessage =
                new BinaryMessage().withMessage(message.getBytes(StandardCharsets.UTF_8));
        PublishMessage publishMessage = new PublishMessage().withBinaryMessage(binaryMessage);
        PublishToTopicRequest publishToTopicRequest =
                new PublishToTopicRequest().withTopic(topic).withPublishMessage(publishMessage);
        return ipcClient.publishToTopic(publishToTopicRequest);
    }
}
```

------
#### [ Python (IPC client V2) ]

**Example 例: バイナリメッセージを発行する**  

```
import sys
import traceback

from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2
from awsiot.greengrasscoreipc.model import (
    PublishMessage,
    BinaryMessage
)


def main():
    args = sys.argv[1:]
    topic = args[0]
    message = args[1]

    try:
        ipc_client = GreengrassCoreIPCClientV2()
        publish_binary_message_to_topic(ipc_client, topic, message)
        print('Successfully published to topic: ' + topic)
    except Exception:
        print('Exception occurred', file=sys.stderr)
        traceback.print_exc()
        exit(1)


def publish_binary_message_to_topic(ipc_client, topic, message):
    binary_message = BinaryMessage(message=bytes(message, 'utf-8'))
    publish_message = PublishMessage(binary_message=binary_message)
    return ipc_client.publish_to_topic(topic=topic, publish_message=publish_message)


if __name__ == '__main__':
    main()
```

------
#### [ C\$1\$1 (IPC client V1) ]

**Example 例: バイナリメッセージを発行する**  

```
#include <iostream>

#include <aws/crt/Api.h>
#include <aws/greengrass/GreengrassCoreIpcClient.h>

using namespace Aws::Crt;
using namespace Aws::Greengrass;

class IpcClientLifecycleHandler : public ConnectionLifecycleHandler {
    void OnConnectCallback() override {
        // Handle connection to IPC service.
    }

    void OnDisconnectCallback(RpcError error) override {
        // Handle disconnection from IPC service.
    }

    bool OnErrorCallback(RpcError error) override {
        // Handle IPC service connection error.
        return true;
    }
};

int main() {
    ApiHandle apiHandle(g_allocator);
    Io::EventLoopGroup eventLoopGroup(1);
    Io::DefaultHostResolver socketResolver(eventLoopGroup, 64, 30);
    Io::ClientBootstrap bootstrap(eventLoopGroup, socketResolver);
    IpcClientLifecycleHandler ipcLifecycleHandler;
    GreengrassCoreIpcClient ipcClient(bootstrap);
    auto connectionStatus = ipcClient.Connect(ipcLifecycleHandler).get();
    if (!connectionStatus) {
        std::cerr << "Failed to establish IPC connection: " << connectionStatus.StatusToString() << std::endl;
        exit(-1);
    }

    String topic("my/topic");
    String message("Hello, World!");
    int timeout = 10;

    PublishToTopicRequest request;
    Vector<uint8_t> messageData({message.begin(), message.end()});
    BinaryMessage binaryMessage;
    binaryMessage.SetMessage(messageData);
    PublishMessage publishMessage;
    publishMessage.SetBinaryMessage(binaryMessage);
    request.SetTopic(topic);
    request.SetPublishMessage(publishMessage);

    auto operation = ipcClient.NewPublishToTopic();
    auto activate = operation->Activate(request, nullptr);
    activate.wait();

    auto responseFuture = operation->GetResult();
    if (responseFuture.wait_for(std::chrono::seconds(timeout)) == std::future_status::timeout) {
        std::cerr << "Operation timed out while waiting for response from Greengrass Core." << std::endl;
        exit(-1);
    }

    auto response = responseFuture.get();
    if (!response) {
        // Handle error.
        auto errorType = response.GetResultType();
        if (errorType == OPERATION_ERROR) {
            auto *error = response.GetOperationError();
            (void)error;
            // Handle operation error.
        } else {
            // Handle RPC error.
        }
    }
    return 0;
}
```

------
#### [ JavaScript ]

**Example 例: バイナリメッセージを発行する**  

```
    
import * as greengrasscoreipc from "aws-iot-device-sdk-v2/dist/greengrasscoreipc";
import {BinaryMessage, PublishMessage, PublishToTopicRequest} from "aws-iot-device-sdk-v2/dist/greengrasscoreipc/model";
 
class PublishToTopic {
    private ipcClient : greengrasscoreipc.Client
    private readonly topic : string;
    private readonly messageString : string;
 
    constructor() {
        // define your own constructor, e.g.
        this.topic = "<define_your_topic>";
        this.messageString = "<define_your_message_string>";
        this.publishToTopic().then(r => console.log("Started workflow"));
    }
 
    private async publishToTopic() {
        try {
            this.ipcClient = await getIpcClient();
 
            const binaryMessage : BinaryMessage = {
                message: this.messageString
            }
 
            const publishMessage : PublishMessage = {
                binaryMessage: binaryMessage
            }
 
            const request : PublishToTopicRequest = {
                topic: this.topic,
                publishMessage: publishMessage
            }
 
            this.ipcClient.publishToTopic(request).finally(() => console.log(`Published message ${publishMessage.binaryMessage?.message} to topic`))
 
        } catch (e) {
            // parse the error depending on your use cases
            throw e
        }
    }
}
 
 
export async function getIpcClient(){
    try {
        const ipcClient = greengrasscoreipc.createClient();
        await ipcClient.connect()
            .catch(error => {
                // parse the error depending on your use cases
                throw error;
            });
        return ipcClient
    } catch (err) {
        // parse the error depending on your use cases
        throw err
    }
}
 
// starting point
const publishToTopic = new PublishToTopic();
```

------
#### [ Rust ]

**Example 例: バイナリメッセージを発行する**  

```
use gg_sdk::Sdk;

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    let message = b"Hello, World";
    let topic = "my/topic";

    sdk.publish_to_topic_binary(topic, message)
        .expect("Failed to publish to topic");

    println!("Successfully published to topic: {topic}");
}
```

------
#### [ C ]

**Example 例: バイナリメッセージを発行する**  

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/sdk.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    GgBuffer message = GG_STR("Hello, World");
    GgBuffer topic = GG_STR("my/topic");

    err = ggipc_publish_to_topic_binary(topic, message);
    if (err != GG_ERR_OK) {
        fprintf(
            stderr,
            "Failed to publish to topic: %.*s\n",
            (int) topic.len,
            topic.data
        );
        exit(-1);
    }

    printf(
        "Successfully published to topic: %.*s\n", (int) topic.len, topic.data
    );
}
```

------
#### [ C\$1\$1 (Component SDK) ]

**Example 例: バイナリメッセージを発行する**  

```
#include <gg/ipc/client.hpp>
#include <iostream>

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    std::string_view message = "Hello, World";
    std::string_view topic = "my/topic";

    error = client.publish_to_topic(topic, message);
    if (error) {
        std::cerr << "Failed to publish to topic: " << topic << "\n";
        exit(-1);
    }

    std::cout << "Successfully published to topic: " << topic << "\n";
}
```

------

## SubscribeToTopic
<a name="ipc-operation-subscribetotopic"></a>

トピックのメッセージをサブスクライブする。

<a name="ipc-subscribe-operation-note"></a>このオペレーションはサブスクリプションオペレーションで、イベントメッセージのストリームをサブスクライブするというものです。このオペレーションを使用するには、イベントメッセージ、エラー、およびストリームクロージャを処理する関数を使用して、ストリームレスポンスハンドラーを定義します。(詳細については、[IPC イベントストリームへのサブスクライブ](interprocess-communication.md#ipc-subscribe-operations) を参照してください)。

**イベントメッセージの種類:** `SubscriptionResponseMessage`

### リクエスト
<a name="ipc-operation-subscribetotopic-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`topic`  
サブスクライブ先のトピック。  
[Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 以降では、このトピックは MQTT トピックのワイルドカード (`#` と `+`) をサポートします。

`receiveMode` (Python: `receive_mode`)  
(オプション) コンポーネントが自身からのメッセージを受信するかどうかを指定する動作。この動作を変更して、コンポーネントが自身のメッセージに基づいて動作できるようにすることができます。デフォルトの動作は、トピックに MQTT ワイルドカードが含まれているかどうかによって異なります。次のオプションから選択します。  
+ `RECEIVE_ALL_MESSAGES` – サブスクライブするコンポーネントからのメッセージを含む、トピックに一致するすべてのメッセージを受信します。

  このモードは、MQTT ワイルドカードを含まないトピックをサブスクライブする場合のデフォルトオプションです。
+ `RECEIVE_MESSAGES_FROM_OTHERS` – サブスクライブするコンポーネントからのメッセージを除き、トピックに一致するすべてのメッセージを受信します。

  このモードは、MQTT ワイルドカードを含むトピックをサブスクライブする場合のデフォルトオプションです。
この機能は、[Greengrass nucleus コンポーネント](greengrass-nucleus-component.md)の v2.6.0 以降で利用できます。次の表 AWS IoT Device SDK に、受信モードの設定に使用する必要がある の最小バージョンを示します。      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-publish-subscribe.html)

### 応答
<a name="ipc-operation-subscribetotopic-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`messages`  
メッセージのストリーム。このオブジェクト (`SubscriptionResponseMessage`) には、次の情報が含まれます。各メッセージには `jsonMessage` または `binaryMessage` が含まれます。  <a name="ipc-publish-subscribe-message-shape"></a>  
`jsonMessage` (Python: `json_message`)  
(オプション) JSON メッセージ。このオブジェクト (`JsonMessage`) には、次の情報が含まれます。    
`message`  
オブジェクトとしての JSON メッセージ。  
`context`  <a name="ipc-publish-subscribe-message-context-variable"></a>
メッセージが公開されたトピックなど、メッセージのコンテキスト。  
この機能は、[Greengrass nucleus コンポーネント](greengrass-nucleus-component.md)の v2.6.0 以降で利用できます。次の表に、メッセージコンテキストへのアクセスに使用する必要がある AWS IoT Device SDK の最小バージョンを示します。      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-publish-subscribe.html)
 AWS IoT Greengrass Core ソフトウェアは、 `PublishToTopic` および `SubscribeToTopic`オペレーションで同じメッセージオブジェクトを使用します。 AWS IoT Greengrass Core ソフトウェアは、サブスクライブ時にこのコンテキストオブジェクトをメッセージに設定し、発行するメッセージではこのコンテキストオブジェクトを無視します。
このオブジェクト (`MessageContext`) には、次の情報が含まれます。    
`topic`  
メッセージが発行されたトピック。  
`binaryMessage` (Python: `binary_message`)  
(オプション) バイナリメッセージ。このオブジェクト (`BinaryMessage`) には、次の情報が含まれます。    
`message`  
BLOB としてのバイナリメッセージ。  
`context`  <a name="ipc-publish-subscribe-message-context-variable"></a>
メッセージが公開されたトピックなど、メッセージのコンテキスト。  
この機能は、[Greengrass nucleus コンポーネント](greengrass-nucleus-component.md)の v2.6.0 以降で利用できます。次の表に、メッセージコンテキストへのアクセスに使用する必要がある AWS IoT Device SDK の最小バージョンを示します。      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-publish-subscribe.html)
 AWS IoT Greengrass Core ソフトウェアは、 `PublishToTopic` および `SubscribeToTopic`オペレーションで同じメッセージオブジェクトを使用します。 AWS IoT Greengrass Core ソフトウェアは、サブスクライブ時にこのコンテキストオブジェクトをメッセージに設定し、発行するメッセージではこのコンテキストオブジェクトを無視します。
このオブジェクト (`MessageContext`) には、次の情報が含まれます。    
`topic`  
メッセージが発行されたトピック。

`topicName` (Python: `topic_name`)  
メッセージが発行されたトピック。  
このプロパティは現在使用されていません。[Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 以降では、`SubscriptionResponseMessage` からの `(jsonMessage|binaryMessage).context.topic` の値を取得して、メッセージが発行されたトピックを取得できます。

### 例
<a name="ipc-operation-subscribetotopic-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Java (IPC client V2) ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  <a name="ipc-operation-subscribetotopic-example-java-v2"></a>

```
package com.aws.greengrass.docs.samples.ipc;

import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClientV2;
import software.amazon.awssdk.aws.greengrass.SubscribeToTopicResponseHandler;
import software.amazon.awssdk.aws.greengrass.model.*;

import java.nio.charset.StandardCharsets;
import java.util.Optional;

public class SubscribeToTopicV2 {

    public static void main(String[] args) {
        String topic = args[0];
        try (GreengrassCoreIPCClientV2 ipcClient = GreengrassCoreIPCClientV2.builder().build()) {
            SubscribeToTopicRequest request = new SubscribeToTopicRequest().withTopic(topic);
            GreengrassCoreIPCClientV2.StreamingResponse<SubscribeToTopicResponse,
                    SubscribeToTopicResponseHandler> response =
                    ipcClient.subscribeToTopic(request, SubscribeToTopicV2::onStreamEvent,
                            Optional.of(SubscribeToTopicV2::onStreamError),
                            Optional.of(SubscribeToTopicV2::onStreamClosed));
            SubscribeToTopicResponseHandler responseHandler = response.getHandler();
            System.out.println("Successfully subscribed to topic: " + topic);

            // Keep the main thread alive, or the process will exit.
            try {
                while (true) {
                    Thread.sleep(10000);
                }
            } catch (InterruptedException e) {
                System.out.println("Subscribe interrupted.");
            }

            // To stop subscribing, close the stream.
            responseHandler.closeStream();
        } catch (Exception e) {
            if (e.getCause() instanceof UnauthorizedError) {
                System.err.println("Unauthorized error while publishing to topic: " + topic);
            } else {
                System.err.println("Exception occurred when using IPC.");
            }
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static void onStreamEvent(SubscriptionResponseMessage subscriptionResponseMessage) {
        try {
            BinaryMessage binaryMessage = subscriptionResponseMessage.getBinaryMessage();
            String message = new String(binaryMessage.getMessage(), StandardCharsets.UTF_8);
            String topic = binaryMessage.getContext().getTopic();
            System.out.printf("Received new message on topic %s: %s%n", topic, message);
        } catch (Exception e) {
            System.err.println("Exception occurred while processing subscription response " +
                    "message.");
            e.printStackTrace();
        }
    }

    public static boolean onStreamError(Throwable error) {
        System.err.println("Received a stream error.");
        error.printStackTrace();
        return false; // Return true to close stream, false to keep stream open.
    }

    public static void onStreamClosed() {
        System.out.println("Subscribe to topic stream closed.");
    }
}
```

------
#### [ Python (IPC client V2) ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  <a name="ipc-operation-subscribetotopic-example-python-v2"></a>

```
import sys
import time
import traceback

from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2
from awsiot.greengrasscoreipc.model import (
    SubscriptionResponseMessage,
    UnauthorizedError
)


def main():
    args = sys.argv[1:]
    topic = args[0]

    try:
        ipc_client = GreengrassCoreIPCClientV2()
        # Subscription operations return a tuple with the response and the operation.
        _, operation = ipc_client.subscribe_to_topic(topic=topic, on_stream_event=on_stream_event,
                                                     on_stream_error=on_stream_error, on_stream_closed=on_stream_closed)
        print('Successfully subscribed to topic: ' + topic)

        # Keep the main thread alive, or the process will exit.
        try:
            while True:
                time.sleep(10)
        except InterruptedError:
            print('Subscribe interrupted.')

        # To stop subscribing, close the stream.
        operation.close()
    except UnauthorizedError:
        print('Unauthorized error while subscribing to topic: ' +
              topic, file=sys.stderr)
        traceback.print_exc()
        exit(1)
    except Exception:
        print('Exception occurred', file=sys.stderr)
        traceback.print_exc()
        exit(1)


def on_stream_event(event: SubscriptionResponseMessage) -> None:
    try:
        message = str(event.binary_message.message, 'utf-8')
        topic = event.binary_message.context.topic
        print('Received new message on topic %s: %s' % (topic, message))
    except:
        traceback.print_exc()


def on_stream_error(error: Exception) -> bool:
    print('Received a stream error.', file=sys.stderr)
    traceback.print_exc()
    return False  # Return True to close stream, False to keep stream open.


def on_stream_closed() -> None:
    print('Subscribe to topic stream closed.')


if __name__ == '__main__':
    main()
```

------
#### [ C\$1\$1 (IPC client V1) ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  <a name="ipc-operation-subscribetotopic-example-cpp"></a>

```
#include <iostream>

#include </crt/Api.h>
#include <aws/greengrass/GreengrassCoreIpcClient.h>

using namespace Aws::Crt;
using namespace Aws::Greengrass;

class SubscribeResponseHandler : public SubscribeToTopicStreamHandler {
    public:
        virtual ~SubscribeResponseHandler() {}

    private:
        void OnStreamEvent(SubscriptionResponseMessage *response) override {
            auto jsonMessage = response->GetJsonMessage();
            if (jsonMessage.has_value() && jsonMessage.value().GetMessage().has_value()) {
                auto messageString = jsonMessage.value().GetMessage().value().View().WriteReadable();
                // Handle JSON message.
            } else {
                auto binaryMessage = response->GetBinaryMessage();
                if (binaryMessage.has_value() && binaryMessage.value().GetMessage().has_value()) {
                    auto messageBytes = binaryMessage.value().GetMessage().value();
                    std::string messageString(messageBytes.begin(), messageBytes.end());
                    // Handle binary message.
                }
            }
        }

        bool OnStreamError(OperationError *error) override {
            // Handle error.
            return false; // Return true to close stream, false to keep stream open.
        }

        void OnStreamClosed() override {
            // Handle close.
        }
};

class IpcClientLifecycleHandler : public ConnectionLifecycleHandler {
    void OnConnectCallback() override {
        // Handle connection to IPC service.
    }

    void OnDisconnectCallback(RpcError error) override {
        // Handle disconnection from IPC service.
    }

    bool OnErrorCallback(RpcError error) override {
        // Handle IPC service connection error.
        return true;
    }
};

int main() {
    ApiHandle apiHandle(g_allocator);
    Io::EventLoopGroup eventLoopGroup(1);
    Io::DefaultHostResolver socketResolver(eventLoopGroup, 64, 30);
    Io::ClientBootstrap bootstrap(eventLoopGroup, socketResolver);
    IpcClientLifecycleHandler ipcLifecycleHandler;
    GreengrassCoreIpcClient ipcClient(bootstrap);
    auto connectionStatus = ipcClient.Connect(ipcLifecycleHandler).get();
    if (!connectionStatus) {
        std::cerr << "Failed to establish IPC connection: " << connectionStatus.StatusToString() << std::endl;
        exit(-1);
    }

    String topic("my/topic");
    int timeout = 10;

    SubscribeToTopicRequest request;
    request.SetTopic(topic);

    //SubscribeResponseHandler streamHandler;
    auto streamHandler = MakeShared<SubscribeResponseHandler>(DefaultAllocator());
    auto operation = ipcClient.NewSubscribeToTopic(streamHandler);
    auto activate = operation->Activate(request, nullptr);
    activate.wait();

    auto responseFuture = operation->GetResult();
    if (responseFuture.wait_for(std::chrono::seconds(timeout)) == std::future_status::timeout) {
        std::cerr << "Operation timed out while waiting for response from Greengrass Core." << std::endl;
        exit(-1);
    }

    auto response = responseFuture.get();
    if (!response) {
        // Handle error.
        auto errorType = response.GetResultType();
        if (errorType == OPERATION_ERROR) {
            auto *error = response.GetOperationError();
            (void)error;
            // Handle operation error.
        } else {
            // Handle RPC error.
        }
        exit(-1);
    }

    // Keep the main thread alive, or the process will exit.
    while (true) {
        std::this_thread::sleep_for(std::chrono::seconds(10));
    }

    operation->Close();
    return 0;
}
```

------
#### [ JavaScript ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  <a name="ipc-operation-subscribetotopic-example-nodejs"></a>

```
import * as greengrasscoreipc from "aws-iot-device-sdk-v2/dist/greengrasscoreipc";
import {SubscribeToTopicRequest, SubscriptionResponseMessage} from "aws-iot-device-sdk-v2/dist/greengrasscoreipc/model";
import {RpcError} from "aws-iot-device-sdk-v2/dist/eventstream_rpc";
 
class SubscribeToTopic {
    private ipcClient : greengrasscoreipc.Client
    private readonly topic : string;
 
    constructor() {
        // define your own constructor, e.g.
        this.topic = "<define_your_topic>";
        this.subscribeToTopic().then(r => console.log("Started workflow"));
    }
 
    private async subscribeToTopic() {
        try {
            this.ipcClient = await getIpcClient();
 
            const subscribeToTopicRequest : SubscribeToTopicRequest = {
                topic: this.topic,
            }
 
            const streamingOperation = this.ipcClient.subscribeToTopic(subscribeToTopicRequest, undefined); // conditionally apply options
 
            streamingOperation.on("message", (message: SubscriptionResponseMessage) => {
                // parse the message depending on your use cases, e.g.
                if(message.binaryMessage && message.binaryMessage.message) {
                    const receivedMessage = message.binaryMessage?.message.toString();
                }
            });
 
            streamingOperation.on("streamError", (error : RpcError) => {
                // define your own error handling logic
            })
 
            streamingOperation.on("ended", () => {
                // define your own logic
            })
 
            await streamingOperation.activate();
 
            // Keep the main thread alive, or the process will exit.
            await new Promise((resolve) => setTimeout(resolve, 10000))
        } catch (e) {
            // parse the error depending on your use cases
            throw e
        }
    }
}
 
export async function getIpcClient(){
    try {
        const ipcClient = greengrasscoreipc.createClient();
        await ipcClient.connect()
            .catch(error => {
                // parse the error depending on your use cases
                throw error;
            });
        return ipcClient
    } catch (err) {
        // parse the error depending on your use cases
        throw err
    }
}
 
// starting point
const subscribeToTopic = new SubscribeToTopic();
```

------
#### [ Rust ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  

```
use gg_sdk::{Sdk, SubscribeToTopicPayload};
use std::{thread, time::Duration};

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    let topic = "my/topic";

    let callback = |topic: &str, payload: SubscribeToTopicPayload| match payload
    {
        SubscribeToTopicPayload::Binary(message) => {
            let message = String::from_utf8_lossy(message);
            println!("Received new message on topic {topic}: {message}");
        }
        SubscribeToTopicPayload::Json(_) => {
            println!("Received new message on topic {topic}: (JSON message)");
        }
    };

    let _sub = sdk
        .subscribe_to_topic(topic, &callback)
        .expect("Failed to subscribe to topic");

    println!("Successfully subscribed to topic: {topic}");

    // Keep the main thread alive, or the process will exit.
    loop {
        thread::sleep(Duration::from_secs(10));
    }
}
```

------
#### [ C ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  

```
#include <assert.h>
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/object.h>
#include <gg/sdk.h>
#include <gg/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static void on_subscription_response(
    void *ctx, GgBuffer topic, GgObject payload, GgIpcSubscriptionHandle handle
) {
    (void) ctx;
    (void) handle;

    if (gg_obj_type(payload) == GG_TYPE_BUF) {
        GgBuffer message = gg_obj_into_buf(payload);
        printf(
            "Received new message on topic %.*s: %.*s\n",
            (int) topic.len,
            topic.data,
            (int) message.len,
            message.data
        );
    } else {
        assert(gg_obj_type(payload) == GG_TYPE_MAP);
        printf(
            "Received new message on topic %.*s: (JSON message)\n",
            (int) topic.len,
            topic.data
        );
    }
}

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    GgBuffer topic = GG_STR("my/topic");

    GgIpcSubscriptionHandle handle;
    err = ggipc_subscribe_to_topic(
        topic, on_subscription_response, NULL, &handle
    );
    if (err != GG_ERR_OK) {
        fprintf(
            stderr,
            "Failed to subscribe to topic: %.*s\n",
            (int) topic.len,
            topic.data
        );
        exit(-1);
    }

    printf(
        "Successfully subscribed to topic: %.*s\n", (int) topic.len, topic.data
    );

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }

    // To stop subscribing, close the stream.
    ggipc_close_subscription(handle);
}
```

------
#### [ C\$1\$1 (Component SDK) ]

**Example 例: ローカルのパブリッシュ/サブスクライブメッセージをサブスクライブする**  

```
#include <gg/ipc/client.hpp>
#include <gg/object.hpp>
#include <unistd.h>
#include <cassert>
#include <iostream>

class ResponseHandler : public gg::ipc::LocalTopicCallback {
    void operator()(
        std::string_view topic,
        gg::Object payload,
        gg::ipc::Subscription &handle
    ) override {
        (void) handle;
        if (payload.index() == GG_TYPE_BUF) {
            std::cout << "Received new message on topic " << topic << ": "
                      << get<gg::Buffer>(payload) << "\n";
        } else {
            assert(payload.index() == GG_TYPE_MAP);
            std::cout << "Received new message on topic " << topic
                      << ": (JSON message)\n";
        }
    }
};

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    std::string_view topic = "my/topic";

    static ResponseHandler handler;
    error = client.subscribe_to_topic(topic, handler);
    if (error) {
        std::cerr << "Failed to subscribe to topic: " << topic << "\n";
        exit(-1);
    }

    std::cout << "Successfully subscribed to topic: " << topic << "\n";

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }
}
```

------

## 例
<a name="ipc-publish-subscribe-examples"></a>

コンポーネントのパブリッシュ/サブスクライブ IPC サービスの使用方法については、以下の例を参照してください。

### パブリッシュ/サブスクライブパブリッシャー (Java、IPC クライアント V1) の例
<a name="ipc-publish-subscribe-example-publisher-java"></a>

以下の recipe の例は、コンポーネントをすべてのトピックに発行できるようにします。

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubPublisherJava",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubPublisherJava:pubsub:1": {
            "policyDescription": "Allows access to publish to all topics.",
            "operations": [
              "aws.greengrass#PublishToTopic"
            ],
            "resources": [
              "*"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Lifecycle": {
        "Run": "java -jar {artifacts:path}/PubSubPublisher.jar"
      }
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.PubSubPublisherJava
ComponentVersion: '1.0.0'
ComponentDescription: A component that publishes messages.
ComponentPublisher: Amazon
ComponentConfiguration:
  DefaultConfiguration:
    accessControl:
      aws.greengrass.ipc.pubsub:
        'com.example.PubSubPublisherJava:pubsub:1':
          policyDescription: Allows access to publish to all topics.
          operations:
            - 'aws.greengrass#PublishToTopic'
          resources:
            - '*'
Manifests:
  - Lifecycle:
      Run: |-
        java -jar {artifacts:path}/PubSubPublisher.jar
```

------

以下の Java アプリケーションの例は、パブリッシュ/サブスクライブ IPC サービスを使用して、他コンポーネントにメッセージを発行する方法を示します。

```
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0 */

package com.example.ipc.pubsub;

import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient;
import software.amazon.awssdk.aws.greengrass.model.*;
import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection;

import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class PubSubPublisher {

    public static void main(String[] args) {
        String message = "Hello from the pub/sub publisher (Java).";
        String topic = "test/topic/java";

        try (EventStreamRPCConnection eventStreamRPCConnection = IPCUtils.getEventStreamRpcConnection()) {
            GreengrassCoreIPCClient ipcClient = new GreengrassCoreIPCClient(eventStreamRPCConnection);

            while (true) {
                PublishToTopicRequest publishRequest = new PublishToTopicRequest();
                PublishMessage publishMessage = new PublishMessage();
                BinaryMessage binaryMessage = new BinaryMessage();
                binaryMessage.setMessage(message.getBytes(StandardCharsets.UTF_8));
                publishMessage.setBinaryMessage(binaryMessage);
                publishRequest.setPublishMessage(publishMessage);
                publishRequest.setTopic(topic);
                CompletableFuture<PublishToTopicResponse> futureResponse = ipcClient
                        .publishToTopic(publishRequest, Optional.empty()).getResponse();

                try {
                    futureResponse.get(10, TimeUnit.SECONDS);
                    System.out.println("Successfully published to topic: " + topic);
                } catch (TimeoutException e) {
                    System.err.println("Timeout occurred while publishing to topic: " + topic);
                } catch (ExecutionException e) {
                    if (e.getCause() instanceof UnauthorizedError) {
                        System.err.println("Unauthorized error while publishing to topic: " + topic);
                    } else {
                        System.err.println("Execution exception while publishing to topic: " + topic);
                    }
                    throw e;
                }
                Thread.sleep(5000);
            }
        } catch (InterruptedException e) {
            System.out.println("Publisher interrupted.");
        } catch (Exception e) {
            System.err.println("Exception occurred when using IPC.");
            e.printStackTrace();
            System.exit(1);
        }
    }
}
```

### パブリッシュ/サブスクライブサブスクライバー (Java、IPC クライアント V1) の例
<a name="ipc-publish-subscribe-example-subscriber-java"></a>

以下の recipe の例は、コンポーネントをすべてのトピックをサブスクライブできるようにします。

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubSubscriberJava",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that subscribes to messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubSubscriberJava:pubsub:1": {
            "policyDescription": "Allows access to subscribe to all topics.",
            "operations": [
              "aws.greengrass#SubscribeToTopic"
            ],
            "resources": [
              "*"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Lifecycle": {
        "Run": "java -jar {artifacts:path}/PubSubSubscriber.jar"
      }
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.PubSubSubscriberJava
ComponentVersion: '1.0.0'
ComponentDescription: A component that subscribes to messages.
ComponentPublisher: Amazon
ComponentConfiguration:
  DefaultConfiguration:
    accessControl:
      aws.greengrass.ipc.pubsub:
        'com.example.PubSubSubscriberJava:pubsub:1':
          policyDescription: Allows access to subscribe to all topics.
          operations:
            - 'aws.greengrass#SubscribeToTopic'
          resources:
            - '*'
Manifests:
  - Lifecycle:
      Run: |-
        java -jar {artifacts:path}/PubSubSubscriber.jar
```

------

以下の Java アプリケーションの例は、パブリッシュ/サブスクライブ IPC サービスを使用して、他コンポーネントのメッセージをサブスクライブする方法を示します。

```
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0 */

package com.example.ipc.pubsub;

import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient;
import software.amazon.awssdk.aws.greengrass.SubscribeToTopicResponseHandler;
import software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest;
import software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse;
import software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage;
import software.amazon.awssdk.aws.greengrass.model.UnauthorizedError;
import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection;
import software.amazon.awssdk.eventstreamrpc.StreamResponseHandler;

import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class PubSubSubscriber {

    public static void main(String[] args) {
        String topic = "test/topic/java";

        try (EventStreamRPCConnection eventStreamRPCConnection = IPCUtils.getEventStreamRpcConnection()) {
            GreengrassCoreIPCClient ipcClient = new GreengrassCoreIPCClient(eventStreamRPCConnection);

            SubscribeToTopicRequest subscribeRequest = new SubscribeToTopicRequest();
            subscribeRequest.setTopic(topic);
            SubscribeToTopicResponseHandler operationResponseHandler = ipcClient
                    .subscribeToTopic(subscribeRequest, Optional.of(new SubscribeResponseHandler()));
            CompletableFuture<SubscribeToTopicResponse> futureResponse = operationResponseHandler.getResponse();

            try {
                futureResponse.get(10, TimeUnit.SECONDS);
                System.out.println("Successfully subscribed to topic: " + topic);
            } catch (TimeoutException e) {
                System.err.println("Timeout occurred while subscribing to topic: " + topic);
                throw e;
            } catch (ExecutionException e) {
                if (e.getCause() instanceof UnauthorizedError) {
                    System.err.println("Unauthorized error while subscribing to topic: " + topic);
                } else {
                    System.err.println("Execution exception while subscribing to topic: " + topic);
                }
                throw e;
            }

            // Keep the main thread alive, or the process will exit.
            try {
                while (true) {
                    Thread.sleep(10000);
                }
            } catch (InterruptedException e) {
                System.out.println("Subscribe interrupted.");
            }
        } catch (Exception e) {
            System.err.println("Exception occurred when using IPC.");
            e.printStackTrace();
            System.exit(1);
        }
    }

    private static class SubscribeResponseHandler implements StreamResponseHandler<SubscriptionResponseMessage> {

        @Override
        public void onStreamEvent(SubscriptionResponseMessage subscriptionResponseMessage) {
            try {
                String message = new String(subscriptionResponseMessage.getBinaryMessage()
                        .getMessage(), StandardCharsets.UTF_8);
                System.out.println("Received new message: " + message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public boolean onStreamError(Throwable error) {
            System.err.println("Received a stream error.");
            error.printStackTrace();
            return false; // Return true to close stream, false to keep stream open.
        }

        @Override
        public void onStreamClosed() {
            System.out.println("Subscribe to topic stream closed.");
        }
    }
}
```

### パブリッシュ/サブスクライブパブリッシャー (Python、IPC クライアント V1) の例
<a name="ipc-publish-subscribe-example-publisher-python"></a>

以下の recipe の例は、コンポーネントをすべてのトピックに発行できるようにします。

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubPublisherPython",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubPublisherPython:pubsub:1": {
            "policyDescription": "Allows access to publish to all topics.",
            "operations": [
              "aws.greengrass#PublishToTopic"
            ],
            "resources": [
              "*"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux"
      },
      "Lifecycle": {
        "install": "python3 -m pip install --user awsiotsdk",
        "Run": "python3 -u {artifacts:path}/pubsub_publisher.py"
      }
    },
    {
      "Platform": {
        "os": "windows"
      },
      "Lifecycle": {
        "install": "py -3 -m pip install --user awsiotsdk",
        "Run": "py -3 -u {artifacts:path}/pubsub_publisher.py"
      }
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.PubSubPublisherPython
ComponentVersion: 1.0.0
ComponentDescription: A component that publishes messages.
ComponentPublisher: Amazon
ComponentConfiguration:
  DefaultConfiguration:
    accessControl:
      aws.greengrass.ipc.pubsub:
        com.example.PubSubPublisherPython:pubsub:1:
          policyDescription: Allows access to publish to all topics.
          operations:
            - aws.greengrass#PublishToTopic
          resources:
            - "*"
Manifests:
  - Platform:
      os: linux
    Lifecycle:
      install: python3 -m pip install --user awsiotsdk
      Run: python3 -u {artifacts:path}/pubsub_publisher.py
  - Platform:
      os: windows
    Lifecycle:
      install: py -3 -m pip install --user awsiotsdk
      Run: py -3 -u {artifacts:path}/pubsub_publisher.py
```

------

以下の Python アプリケーションの例は、パブリッシュ/サブスクライブ IPC サービスを使用して、他コンポーネントにメッセージを発行する方法を示します。

```
import concurrent.futures
import sys
import time
import traceback

import awsiot.greengrasscoreipc
from awsiot.greengrasscoreipc.model import (
    PublishToTopicRequest,
    PublishMessage,
    BinaryMessage,
    UnauthorizedError
)

                    
topic = "test/topic/python"
message = "Hello from the pub/sub publisher (Python)."
TIMEOUT = 10

try:
    ipc_client = awsiot.greengrasscoreipc.connect()

    while True:
        request = PublishToTopicRequest()
        request.topic = topic
        publish_message = PublishMessage()
        publish_message.binary_message = BinaryMessage()
        publish_message.binary_message.message = bytes(message, "utf-8")
        request.publish_message = publish_message
        operation = ipc_client.new_publish_to_topic()
        operation.activate(request)
        future_response = operation.get_response()

        try:
            future_response.result(TIMEOUT)
            print('Successfully published to topic: ' + topic)
        except concurrent.futures.TimeoutError:
            print('Timeout occurred while publishing to topic: ' + topic, file=sys.stderr)
        except UnauthorizedError as e:
            print('Unauthorized error while publishing to topic: ' + topic, file=sys.stderr)
            raise e
        except Exception as e:
            print('Exception while publishing to topic: ' + topic, file=sys.stderr)
            raise e
        time.sleep(5)
except InterruptedError:
    print('Publisher interrupted.')
except Exception:
    print('Exception occurred when using IPC.', file=sys.stderr)
    traceback.print_exc()
    exit(1)
```

### パブリッシュ/サブスクライブサブスクライバー (Python、IPC クライアント V1) の例
<a name="ipc-publish-subscribe-example-subscriber-python"></a>

以下の recipe の例は、コンポーネントをすべてのトピックをサブスクライブできるようにします。

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubSubscriberPython",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that subscribes to messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubSubscriberPython:pubsub:1": {
            "policyDescription": "Allows access to subscribe to all topics.",
            "operations": [
              "aws.greengrass#SubscribeToTopic"
            ],
            "resources": [
              "*"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux"
      },
      "Lifecycle": {
        "install": "python3 -m pip install --user awsiotsdk",
        "Run": "python3 -u {artifacts:path}/pubsub_subscriber.py"
      }
    },
    {
      "Platform": {
        "os": "windows"
      },
      "Lifecycle": {
        "install": "py -3 -m pip install --user awsiotsdk",
        "Run": "py -3 -u {artifacts:path}/pubsub_subscriber.py"
      }
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.PubSubSubscriberPython
ComponentVersion: 1.0.0
ComponentDescription: A component that subscribes to messages.
ComponentPublisher: Amazon
ComponentConfiguration:
  DefaultConfiguration:
    accessControl:
      aws.greengrass.ipc.pubsub:
        com.example.PubSubSubscriberPython:pubsub:1:
          policyDescription: Allows access to subscribe to all topics.
          operations:
            - aws.greengrass#SubscribeToTopic
          resources:
            - "*"
Manifests:
  - Platform:
      os: linux
    Lifecycle:
      install: python3 -m pip install --user awsiotsdk
      Run: python3 -u {artifacts:path}/pubsub_subscriber.py
  - Platform:
      os: windows
    Lifecycle:
      install: py -3 -m pip install --user awsiotsdk
      Run: py -3 -u {artifacts:path}/pubsub_subscriber.py
```

------

以下の Python アプリケーションの例は、パブリッシュ/サブスクライブ IPC サービスを使用して、他コンポーネントのメッセージをサブスクライブする方法を示します。

```
import concurrent.futures
import sys
import time
import traceback

import awsiot.greengrasscoreipc
import awsiot.greengrasscoreipc.client as client
from awsiot.greengrasscoreipc.model import (
    SubscribeToTopicRequest,
    SubscriptionResponseMessage,
    UnauthorizedError
)

topic = "test/topic/python"
TIMEOUT = 10

                    
class StreamHandler(client.SubscribeToTopicStreamHandler):
    def __init__(self):
        super().__init__()

    def on_stream_event(self, event: SubscriptionResponseMessage) -> None:
        try:
            message = str(event.binary_message.message, "utf-8")
            print("Received new message: " + message)
        except:
            traceback.print_exc()

    def on_stream_error(self, error: Exception) -> bool:
        print("Received a stream error.", file=sys.stderr)
        traceback.print_exc()
        return False  # Return True to close stream, False to keep stream open.

    def on_stream_closed(self) -> None:
        print('Subscribe to topic stream closed.')


try:
    ipc_client = awsiot.greengrasscoreipc.connect()

    request = SubscribeToTopicRequest()
    request.topic = topic
    handler = StreamHandler()
    operation = ipc_client.new_subscribe_to_topic(handler)
    operation.activate(request)
    future_response = operation.get_response()
    
    try:
        future_response.result(TIMEOUT)
        print('Successfully subscribed to topic: ' + topic)
    except concurrent.futures.TimeoutError as e:
        print('Timeout occurred while subscribing to topic: ' + topic, file=sys.stderr)
        raise e
    except UnauthorizedError as e:
        print('Unauthorized error while subscribing to topic: ' + topic, file=sys.stderr)
        raise e
    except Exception as e:
        print('Exception while subscribing to topic: ' + topic, file=sys.stderr)
        raise e

    # Keep the main thread alive, or the process will exit.
    try:
        while True:
            time.sleep(10)
    except InterruptedError:
        print('Subscribe interrupted.')
except Exception:
    print('Exception occurred when using IPC.', file=sys.stderr)
    traceback.print_exc()
    exit(1)
```

### パブリッシュ/サブスクライブパブリッシャーの例 (C\$1\$1、IPC クライアント V1)
<a name="ipc-publish-subscribe-example-publisher-cpp"></a>

以下の recipe の例は、コンポーネントをすべてのトピックに発行できるようにします。

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubPublisherCpp",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubPublisherCpp:pubsub:1": {
            "policyDescription": "Allows access to publish to all topics.",
            "operations": [
              "aws.greengrass#PublishToTopic"
            ],
            "resources": [
              "*"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Lifecycle": {
        "Run": "{artifacts:path}/greengrassv2_pubsub_publisher"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubPublisherCpp/1.0.0/greengrassv2_pubsub_publisher",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.PubSubPublisherCpp
ComponentVersion: 1.0.0
ComponentDescription: A component that publishes messages.
ComponentPublisher: Amazon
ComponentConfiguration:
  DefaultConfiguration:
    accessControl:
      aws.greengrass.ipc.pubsub:
        com.example.PubSubPublisherCpp:pubsub:1:
          policyDescription: Allows access to publish to all topics.
          operations:
            - aws.greengrass#PublishToTopic
          resources:
            - "*"
Manifests:
  - Lifecycle:
      Run: "{artifacts:path}/greengrassv2_pubsub_publisher"
    Artifacts:
      - URI: s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubPublisherCpp/1.0.0/greengrassv2_pubsub_publisher
        Permission:
          Execute: OWNER
```

------

以下の C\$1\$1 アプリケーションの例は、パブリッシュ/サブスクライブ IPC サービスを使用して、他コンポーネントにメッセージを発行する方法を示します。

```
#include <iostream>

#include <aws/crt/Api.h>
#include <aws/greengrass/GreengrassCoreIpcClient.h>

using namespace Aws::Crt;
using namespace Aws::Greengrass;

class IpcClientLifecycleHandler : public ConnectionLifecycleHandler {
    void OnConnectCallback() override {
        std::cout << "OnConnectCallback" << std::endl;
    }

    void OnDisconnectCallback(RpcError error) override {
        std::cout << "OnDisconnectCallback: " << error.StatusToString() << std::endl;
        exit(-1);
    }

    bool OnErrorCallback(RpcError error) override {
        std::cout << "OnErrorCallback: " << error.StatusToString() << std::endl;
        return true;
    }
};

int main() {
    String message("Hello from the pub/sub publisher (C++).");
    String topic("test/topic/cpp");
    int timeout = 10;

    ApiHandle apiHandle(g_allocator);
    Io::EventLoopGroup eventLoopGroup(1);
    Io::DefaultHostResolver socketResolver(eventLoopGroup, 64, 30);
    Io::ClientBootstrap bootstrap(eventLoopGroup, socketResolver);
    IpcClientLifecycleHandler ipcLifecycleHandler;
    GreengrassCoreIpcClient ipcClient(bootstrap);
    auto connectionStatus = ipcClient.Connect(ipcLifecycleHandler).get();
    if (!connectionStatus) {
        std::cerr << "Failed to establish IPC connection: " << connectionStatus.StatusToString() << std::endl;
        exit(-1);
    }

    while (true) {
        PublishToTopicRequest request;
        Vector<uint8_t> messageData({message.begin(), message.end()});
        BinaryMessage binaryMessage;
        binaryMessage.SetMessage(messageData);
        PublishMessage publishMessage;
        publishMessage.SetBinaryMessage(binaryMessage);
        request.SetTopic(topic);
        request.SetPublishMessage(publishMessage);

        auto operation = ipcClient.NewPublishToTopic();
        auto activate = operation->Activate(request, nullptr);
        activate.wait();

        auto responseFuture = operation->GetResult();
        if (responseFuture.wait_for(std::chrono::seconds(timeout)) == std::future_status::timeout) {
            std::cerr << "Operation timed out while waiting for response from Greengrass Core." << std::endl;
            exit(-1);
        }

        auto response = responseFuture.get();
        if (response) {
            std::cout << "Successfully published to topic: " << topic << std::endl;
        } else {
            // An error occurred.
            std::cout << "Failed to publish to topic: " << topic << std::endl;
            auto errorType = response.GetResultType();
            if (errorType == OPERATION_ERROR) {
                auto *error = response.GetOperationError();
                std::cout << "Operation error: " << error->GetMessage().value() << std::endl;
            } else {
                std::cout << "RPC error: " << response.GetRpcError() << std::endl;
            }
            exit(-1);
        }

        std::this_thread::sleep_for(std::chrono::seconds(5));
    }

    return 0;
}
```

### パブリッシュ/サブスクライブサブスクライバーの例 (C\$1\$1、IPC クライアント V1)
<a name="ipc-publish-subscribe-example-subscriber-cpp"></a>

以下の recipe の例は、コンポーネントをすべてのトピックをサブスクライブできるようにします。

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubSubscriberCpp",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that subscribes to messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubSubscriberCpp:pubsub:1": {
            "policyDescription": "Allows access to subscribe to all topics.",
            "operations": [
              "aws.greengrass#SubscribeToTopic"
            ],
            "resources": [
              "*"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Lifecycle": {
        "Run": "{artifacts:path}/greengrassv2_pub_sub_subscriber"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubSubscriberCpp/1.0.0/greengrassv2_pub_sub_subscriber",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.PubSubSubscriberCpp
ComponentVersion: 1.0.0
ComponentDescription: A component that subscribes to messages.
ComponentPublisher: Amazon
ComponentConfiguration:
  DefaultConfiguration:
    accessControl:
      aws.greengrass.ipc.pubsub:
        com.example.PubSubSubscriberCpp:pubsub:1:
          policyDescription: Allows access to subscribe to all topics.
          operations:
            - aws.greengrass#SubscribeToTopic
          resources:
            - "*"
Manifests:
  - Lifecycle:
      Run: "{artifacts:path}/greengrassv2_pub_sub_subscriber"
    Artifacts:
      - URI: s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubSubscriberCpp/1.0.0/greengrassv2_pub_sub_subscriber
        Permission:
          Execute: OWNER
```

------

以下の C\$1\$1 アプリケーションの例は、パブリッシュ/サブスクライブ IPC サービスを使用して、他コンポーネントのメッセージをサブスクライブする方法を示します。

```
#include <iostream>

#include <aws/crt/Api.h>
#include <aws/greengrass/GreengrassCoreIpcClient.h>

using namespace Aws::Crt;
using namespace Aws::Greengrass;

class SubscribeResponseHandler : public SubscribeToTopicStreamHandler {
    public:
        virtual ~SubscribeResponseHandler() {}

    private:
        void OnStreamEvent(SubscriptionResponseMessage *response) override {
            auto jsonMessage = response->GetJsonMessage();
            if (jsonMessage.has_value() && jsonMessage.value().GetMessage().has_value()) {
                auto messageString = jsonMessage.value().GetMessage().value().View().WriteReadable();
                std::cout << "Received new message: " << messageString << std::endl;
            } else {
                auto binaryMessage = response->GetBinaryMessage();
                if (binaryMessage.has_value() && binaryMessage.value().GetMessage().has_value()) {
                    auto messageBytes = binaryMessage.value().GetMessage().value();
                    std::string messageString(messageBytes.begin(), messageBytes.end());
                    std::cout << "Received new message: " << messageString << std::endl;
                }
            }
        }

        bool OnStreamError(OperationError *error) override {
            std::cout << "Received an operation error: ";
            if (error->GetMessage().has_value()) {
                std::cout << error->GetMessage().value();
            }
            std::cout << std::endl;
            return false; // Return true to close stream, false to keep stream open.
        }

        void OnStreamClosed() override {
            std::cout << "Subscribe to topic stream closed." << std::endl;
        }
};

class IpcClientLifecycleHandler : public ConnectionLifecycleHandler {
    void OnConnectCallback() override {
        std::cout << "OnConnectCallback" << std::endl;
    }

    void OnDisconnectCallback(RpcError error) override {
        std::cout << "OnDisconnectCallback: " << error.StatusToString() << std::endl;
        exit(-1);
    }

    bool OnErrorCallback(RpcError error) override {
        std::cout << "OnErrorCallback: " << error.StatusToString() << std::endl;
        return true;
    }
};

int main() {
    String topic("test/topic/cpp");
    int timeout = 10;

    ApiHandle apiHandle(g_allocator);
    Io::EventLoopGroup eventLoopGroup(1);
    Io::DefaultHostResolver socketResolver(eventLoopGroup, 64, 30);
    Io::ClientBootstrap bootstrap(eventLoopGroup, socketResolver);
    IpcClientLifecycleHandler ipcLifecycleHandler;
    GreengrassCoreIpcClient ipcClient(bootstrap);
    auto connectionStatus = ipcClient.Connect(ipcLifecycleHandler).get();
    if (!connectionStatus) {
        std::cerr << "Failed to establish IPC connection: " << connectionStatus.StatusToString() << std::endl;
        exit(-1);
    }

    SubscribeToTopicRequest request;
    request.SetTopic(topic);
    auto streamHandler = MakeShared<SubscribeResponseHandler>(DefaultAllocator());
    auto operation = ipcClient.NewSubscribeToTopic(streamHandler);
    auto activate = operation->Activate(request, nullptr);
    activate.wait();

    auto responseFuture = operation->GetResult();
    if (responseFuture.wait_for(std::chrono::seconds(timeout)) == std::future_status::timeout) {
        std::cerr << "Operation timed out while waiting for response from Greengrass Core." << std::endl;
        exit(-1);
    }

    auto response = responseFuture.get();
    if (response) {
        std::cout << "Successfully subscribed to topic: " << topic << std::endl;
    } else {
        // An error occurred.
        std::cout << "Failed to subscribe to topic: " << topic << std::endl;
        auto errorType = response.GetResultType();
        if (errorType == OPERATION_ERROR) {
            auto *error = response.GetOperationError();
            std::cout << "Operation error: " << error->GetMessage().value() << std::endl;
        } else {
            std::cout << "RPC error: " << response.GetRpcError() << std::endl;
        }
        exit(-1);
    }

    // Keep the main thread alive, or the process will exit.
    while (true) {
        std::this_thread::sleep_for(std::chrono::seconds(10));
    }

    operation->Close();
    return 0;
}
```

### パブリッシュ/サブスクライブパブリッシャーの例 (Rust)
<a name="ipc-publish-subscribe-example-publisher-rust"></a>

以下の recipe の例は、コンポーネントをすべてのトピックに発行できるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubPublisherRust",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubPublisherRust:pubsub:1": {
            "policyDescription": "Allows access to publish to all topics.",
            "operations": ["aws.greengrass#PublishToTopic"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/publish_to_topic"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubPublisherRust/1.0.0/publish_to_topic",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の Rust アプリケーション例は、パブリッシュ/サブスクライブ IPC サービスを使用して他のコンポーネントにメッセージを発行する方法を示しています。

```
use gg_sdk::Sdk;

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    let message = b"Hello, World";
    let topic = "my/topic";

    sdk.publish_to_topic_binary(topic, message)
        .expect("Failed to publish to topic");

    println!("Successfully published to topic: {topic}");
}
```

### パブリッシュ/サブスクライブサブスクライバーの例 (Rust)
<a name="ipc-publish-subscribe-example-subscriber-rust"></a>

以下の recipe の例は、コンポーネントをすべてのトピックをサブスクライブできるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubSubscriberRust",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that subscribes to messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubSubscriberRust:pubsub:1": {
            "policyDescription": "Allows access to subscribe to all topics.",
            "operations": ["aws.greengrass#SubscribeToTopic"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/subscribe_to_topic"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubSubscriberRust/1.0.0/subscribe_to_topic",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の Rust アプリケーションの例は、パブリッシュ/サブスクライブ IPC サービスを使用して他のコンポーネントからのメッセージをサブスクライブする方法を示しています。

```
use gg_sdk::{Sdk, SubscribeToTopicPayload};
use std::{thread, time::Duration};

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    let topic = "my/topic";

    let callback = |topic: &str, payload: SubscribeToTopicPayload| match payload
    {
        SubscribeToTopicPayload::Binary(message) => {
            let message = String::from_utf8_lossy(message);
            println!("Received new message on topic {topic}: {message}");
        }
        SubscribeToTopicPayload::Json(_) => {
            println!("Received new message on topic {topic}: (JSON message)");
        }
    };

    let _sub = sdk
        .subscribe_to_topic(topic, &callback)
        .expect("Failed to subscribe to topic");

    println!("Successfully subscribed to topic: {topic}");

    // Keep the main thread alive, or the process will exit.
    loop {
        thread::sleep(Duration::from_secs(10));
    }
}
```

### パブリッシュ/サブスクライブパブリッシャーの例 (C)
<a name="ipc-publish-subscribe-example-publisher-c"></a>

以下の recipe の例は、コンポーネントをすべてのトピックに発行できるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubPublisherC",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubPublisherC:pubsub:1": {
            "policyDescription": "Allows access to publish to all topics.",
            "operations": ["aws.greengrass#PublishToTopic"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/sample_publish_to_topic"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubPublisherC/1.0.0/sample_publish_to_topic",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の C アプリケーション例は、パブリッシュ/サブスクライブ IPC サービスを使用して他のコンポーネントにメッセージを発行する方法を示しています。

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/sdk.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    GgBuffer message = GG_STR("Hello, World");
    GgBuffer topic = GG_STR("my/topic");

    err = ggipc_publish_to_topic_binary(topic, message);
    if (err != GG_ERR_OK) {
        fprintf(
            stderr,
            "Failed to publish to topic: %.*s\n",
            (int) topic.len,
            topic.data
        );
        exit(-1);
    }

    printf(
        "Successfully published to topic: %.*s\n", (int) topic.len, topic.data
    );
}
```

### パブリッシュ/サブスクライブサブスクライバーの例 (C)
<a name="ipc-publish-subscribe-example-subscriber-c"></a>

以下の recipe の例は、コンポーネントをすべてのトピックをサブスクライブできるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubSubscriberC",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that subscribes to messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubSubscriberC:pubsub:1": {
            "policyDescription": "Allows access to subscribe to all topics.",
            "operations": ["aws.greengrass#SubscribeToTopic"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/sample_subscribe_to_topic"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubSubscriberC/1.0.0/sample_subscribe_to_topic",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の C アプリケーション例は、パブリッシュ/サブスクライブ IPC サービスを使用して他のコンポーネントからのメッセージをサブスクライブする方法を示しています。

```
#include <assert.h>
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/object.h>
#include <gg/sdk.h>
#include <gg/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static void on_subscription_response(
    void *ctx, GgBuffer topic, GgObject payload, GgIpcSubscriptionHandle handle
) {
    (void) ctx;
    (void) handle;

    if (gg_obj_type(payload) == GG_TYPE_BUF) {
        GgBuffer message = gg_obj_into_buf(payload);
        printf(
            "Received new message on topic %.*s: %.*s\n",
            (int) topic.len,
            topic.data,
            (int) message.len,
            message.data
        );
    } else {
        assert(gg_obj_type(payload) == GG_TYPE_MAP);
        printf(
            "Received new message on topic %.*s: (JSON message)\n",
            (int) topic.len,
            topic.data
        );
    }
}

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    GgBuffer topic = GG_STR("my/topic");

    GgIpcSubscriptionHandle handle;
    err = ggipc_subscribe_to_topic(
        topic, on_subscription_response, NULL, &handle
    );
    if (err != GG_ERR_OK) {
        fprintf(
            stderr,
            "Failed to subscribe to topic: %.*s\n",
            (int) topic.len,
            topic.data
        );
        exit(-1);
    }

    printf(
        "Successfully subscribed to topic: %.*s\n", (int) topic.len, topic.data
    );

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }

    // To stop subscribing, close the stream.
    ggipc_close_subscription(handle);
}
```

### パブリッシュ/サブスクライブパブリッシャーの例 (C\$1\$1、コンポーネント SDK)
<a name="ipc-publish-subscribe-example-publisher-cpp-component-sdk"></a>

以下の recipe の例は、コンポーネントをすべてのトピックに発行できるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubPublisherCpp",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubPublisherCpp:pubsub:1": {
            "policyDescription": "Allows access to publish to all topics.",
            "operations": ["aws.greengrass#PublishToTopic"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/sample_cpp_publish_to_topic"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubPublisherCpp/1.0.0/sample_cpp_publish_to_topic",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

以下の C\$1\$1 アプリケーションの例は、パブリッシュ/サブスクライブ IPC サービスを使用して、他コンポーネントにメッセージを発行する方法を示します。

```
#include <gg/ipc/client.hpp>
#include <iostream>

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    std::string_view message = "Hello, World";
    std::string_view topic = "my/topic";

    error = client.publish_to_topic(topic, message);
    if (error) {
        std::cerr << "Failed to publish to topic: " << topic << "\n";
        exit(-1);
    }

    std::cout << "Successfully published to topic: " << topic << "\n";
}
```

### パブリッシュ/サブスクライブサブスクライバーの例 (C\$1\$1、コンポーネント SDK)
<a name="ipc-publish-subscribe-example-subscriber-cpp-component-sdk"></a>

以下の recipe の例は、コンポーネントをすべてのトピックをサブスクライブできるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PubSubSubscriberCpp",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that subscribes to messages.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.pubsub": {
          "com.example.PubSubSubscriberCpp:pubsub:1": {
            "policyDescription": "Allows access to subscribe to all topics.",
            "operations": ["aws.greengrass#SubscribeToTopic"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/sample_cpp_subscribe_to_topic"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.PubSubSubscriberCpp/1.0.0/sample_cpp_subscribe_to_topic",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の C\$1\$1 アプリケーションの例は、パブリッシュ/サブスクライブ IPC サービスを使用して他のコンポーネントからのメッセージをサブスクライブする方法を示しています。

```
#include <gg/ipc/client.hpp>
#include <gg/object.hpp>
#include <unistd.h>
#include <cassert>
#include <iostream>

class ResponseHandler : public gg::ipc::LocalTopicCallback {
    void operator()(
        std::string_view topic,
        gg::Object payload,
        gg::ipc::Subscription &handle
    ) override {
        (void) handle;
        if (payload.index() == GG_TYPE_BUF) {
            std::cout << "Received new message on topic " << topic << ": "
                      << get<gg::Buffer>(payload) << "\n";
        } else {
            assert(payload.index() == GG_TYPE_MAP);
            std::cout << "Received new message on topic " << topic
                      << ": (JSON message)\n";
        }
    }
};

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    std::string_view topic = "my/topic";

    static ResponseHandler handler;
    error = client.subscribe_to_topic(topic, handler);
    if (error) {
        std::cerr << "Failed to subscribe to topic: " << topic << "\n";
        exit(-1);
    }

    std::cout << "Successfully subscribed to topic: " << topic << "\n";

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }
}
```

# AWS IoT Core MQTT メッセージを発行/サブスクライブする
<a name="ipc-iot-core-mqtt"></a>

 AWS IoT Core MQTT メッセージング IPC サービスを使用すると、 との間で MQTT メッセージを送受信できます AWS IoT Core。コンポーネントは、 にメッセージを発行 AWS IoT Core し、トピックをサブスクライブして、他のソースからの MQTT メッセージに対応できます。MQTT の AWS IoT Core 実装の詳細については、「 *AWS IoT Core デベロッパーガイド*」の[「MQTT](https://docs.aws.amazon.com/iot/latest/developerguide/mqtt.html)」を参照してください。

**注記**  
この MQTT メッセージング IPC サービスを使用すると、 とメッセージを交換できます AWS IoT Core。コンポーネント間でメッセージを交換する方法の詳細については、「[ローカルメッセージをパブリッシュ/サブスクライブする](ipc-publish-subscribe.md)」を参照してください。

**Topics**
+ [最小 SDK バージョン](#ipc-iot-core-mqtt-sdk-versions)
+ [Authorization](#ipc-iot-core-mqtt-authorization)
+ [PublishToIoTCore](#ipc-operation-publishtoiotcore)
+ [SubscribeToIoTCore](#ipc-operation-subscribetoiotcore)
+ [例](#ipc-iot-core-mqtt-examples)

## 最小 SDK バージョン
<a name="ipc-iot-core-mqtt-sdk-versions"></a>

次の表 AWS IoT Device SDK に、MQTT メッセージの発行とサブスクライブに使用する必要がある の最小バージョンを示します AWS IoT Core。


| SDK | 最小バージョン | 
| --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## Authorization
<a name="ipc-iot-core-mqtt-authorization"></a>

カスタムコンポーネントで AWS IoT Core MQTT メッセージングを使用するには、コンポーネントがトピックに関するメッセージを送受信できるようにする承認ポリシーを定義する必要があります。承認ポリシーの定義については、「[コンポーネントに IPC オペレーションの実行を許可する](interprocess-communication.md#ipc-authorization-policies)」を参照してください。

 AWS IoT Core MQTT メッセージングの承認ポリシーには、次のプロパティがあります。

**IPC サービス識別子:** `aws.greengrass.ipc.mqttproxy`


| 運用 | 説明 | リソース | 
| --- | --- | --- | 
|  `aws.greengrass#PublishToIoTCore`  |  コンポーネントが、指定した MQTT トピック AWS IoT Core で にメッセージを発行できるようにします。  |  `test/topic` などのトピック文字列、または `*` ですべてのトピックへのアクセスを許可します。MQTT トピックのワイルドカード (`#` および `+`) を使用して、複数のリソースを一致させることができます。  | 
|  `aws.greengrass#SubscribeToIoTCore`  |  コンポーネントが、指定したトピック AWS IoT Core で からのメッセージをサブスクライブできるようにします。  |  `test/topic` などのトピック文字列、または `*` ですべてのトピックへのアクセスを許可します。MQTT トピックのワイルドカード (`#` および `+`) を使用して、複数のリソースを一致させることができます。  | 
|  `*`  |  コンポーネントが、指定したトピックの AWS IoT Core MQTT メッセージを発行およびサブスクライブできるようにします。  |  `test/topic` などのトピック文字列、または `*` ですべてのトピックへのアクセスを許可します。MQTT トピックのワイルドカード (`#` および `+`) を使用して、複数のリソースを一致させることができます。  | 

### MQTT 認可ポリシーの AWS IoT Core MQTT ワイルドカード
<a name="ipc-iot-core-mqtt-authorization-mqtt-wildcards"></a>

MQTT IPC 認可ポリシーで AWS IoT Core MQTT ワイルドカードを使用できます。これによりコンポーネントは、承認ポリシーで許可するトピックフィルターに一致するトピックを発行およびサブスクライブできます。例えば、コンポーネントの承認ポリシーで `test/topic/#` へのアクセス権が付与されている場合、コンポーネントは `test/topic/#` をサブスクライブでき、`test/topic/filter` を発行およびサブスクライブできます。

### AWS IoT Core MQTT 認可ポリシーのレシピ変数
<a name="ipc-iot-core-mqtt-authorization-recipe-variables"></a>

v2.6.0 以降の [Greengrass nucleus](greengrass-nucleus-component.md) を使用している場合、承認ポリシーの `{iot:thingName}` recipe 変数を使用できます。この機能を使用すると、コアデバイスのグループに対して 1 つの承認ポリシーを設定できます。各コアデバイスは自身の名前を含むトピックにのみアクセスできます。例えば、コンポーネントに次のトピックリソースへのアクセスを許可できます。

```
devices/{iot:thingName}/messages
```

詳細については、「[レシピ変数](component-recipe-reference.md#recipe-variables)」および「[マージ更新で recipe 変数を使用する](update-component-configurations.md#merge-configuration-update-recipe-variables)」を参照してください。

### 承認ポリシーの例
<a name="ipc-iot-core-mqtt-authorization-policy-examples"></a>

次の承認ポリシーの例を参照して、コンポーネントの承認ポリシー設定の参考にできます。

**Example アクセスが制限されていない承認ポリシーの例**  
以下の承認ポリシーの例では、コンポーネントがすべてのトピックを公開およびサブスクライブすることを許可します。  

```
{
  "accessControl": {
    "aws.greengrass.ipc.mqttproxy": {
      "com.example.MyIoTCorePubSubComponent:mqttproxy:1": {
        "policyDescription": "Allows access to publish/subscribe to all topics.",
        "operations": [
          "aws.greengrass#PublishToIoTCore",
          "aws.greengrass#SubscribeToIoTCore"
        ],
        "resources": [
          "*"
        ]
      }
    }
  }
}
```

```
---
accessControl:
  aws.greengrass.ipc.mqttproxy:
    com.example.MyIoTCorePubSubComponent:mqttproxy:1:
      policyDescription: Allows access to publish/subscribe to all topics.
      operations:
        - aws.greengrass#PublishToIoTCore
        - aws.greengrass#SubscribeToIoTCore
      resources:
        - "*"
```

**Example アクセスが制限されている承認ポリシーの例**  
次の承認ポリシーの例では、コンポーネントが、`factory/1/events` および `factory/1/actions` という名前の 2 つのトピックを公開およびサブスクライブすることを許可します。  

```
{
  "accessControl": {
    "aws.greengrass.ipc.mqttproxy": {
      "com.example.MyIoTCorePubSubComponent:mqttproxy:1": {
        "policyDescription": "Allows access to publish/subscribe to factory 1 topics.",
        "operations": [
          "aws.greengrass#PublishToIoTCore",
          "aws.greengrass#SubscribeToIoTCore"
        ],
        "resources": [
          "factory/1/actions",
          "factory/1/events"
        ]
      }
    }
  }
}
```

```
---
accessControl:
  aws.greengrass.ipc.mqttproxy:
    "com.example.MyIoTCorePubSubComponent:mqttproxy:1":
      policyDescription: Allows access to publish/subscribe to factory 1 topics.
      operations:
        - aws.greengrass#PublishToIoTCore
        - aws.greengrass#SubscribeToIoTCore
      resources:
        - factory/1/actions
        - factory/1/events
```

**Example コアデバイスのグループに対する承認ポリシーの例**  
この例では、v2.6.0 以降の [Greengrass nucleus コンポーネント](greengrass-nucleus-component.md)で利用できる機能を使用しています。Greengrass nucleus v2.6.0 では、コンポーネント設定に、ほとんどの [recipe 変数](component-recipe-reference.md#recipe-variables) (`{iot:thingName}` など) のサポートが追加されました。
次の承認ポリシーの例は、コンポーネントが実行されているコアデバイスの名前を含むトピックを、コンポーネントが発行およびサブスクライブできるようにします。  

```
{
  "accessControl": {
    "aws.greengrass.ipc.mqttproxy": {
      "com.example.MyIoTCorePubSubComponent:mqttproxy:1": {
        "policyDescription": "Allows access to publish/subscribe to all topics.",
        "operations": [
          "aws.greengrass#PublishToIoTCore",
          "aws.greengrass#SubscribeToIoTCore"
        ],
        "resources": [
          "factory/1/devices/{iot:thingName}/controls"
        ]
      }
    }
  }
}
```

```
---
accessControl:
  aws.greengrass.ipc.mqttproxy:
    "com.example.MyIoTCorePubSubComponent:mqttproxy:1":
      policyDescription: Allows access to publish/subscribe to all topics.
      operations:
        - aws.greengrass#PublishToIoTCore
        - aws.greengrass#SubscribeToIoTCore
      resources:
        - factory/1/devices/{iot:thingName}/controls
```

## PublishToIoTCore
<a name="ipc-operation-publishtoiotcore"></a>

トピック AWS IoT Core で MQTT メッセージを に発行します。

MQTT メッセージを に発行する場合 AWS IoT Core、1 秒あたり 100 トランザクションのクォータがあります。このクォータを超えると、メッセージは Greengrass デバイスでの処理のためにキューに入れられます。また、1 秒あたり 512 KB のデータクォータと、1 秒あたり 20,000 パブリッシュ (一部は 2,000) のアカウント全体のクォータがあります AWS リージョン。 AWS IoT Core の MQTT メッセージブローカー制限の詳細については、「[AWS IoT Core  メッセージブローカーとプロトコルの制限とクォータ](https://docs.aws.amazon.com/general/latest/gr/iot-core.html#message-broker-limits)」を参照してください。

これらのクォータを超えると、Greengrass デバイスはメッセージの発行を制限します AWS IoT Core。メッセージはメモリ内のスプーラに保存されます。デフォルトでは、スプーラに割り当てられるメモリは 2.5 MB です。スプーラがいっぱいになると、新しいメッセージは拒否されます。スプーラのサイズを増やすことができます。詳細については、[Greengrass nucleus](greengrass-nucleus-component.md) ドキュメントの「[設定](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration)」を参照してください。スプーラがいっぱいになり、割り当てられるメモリを増やす必要がないように、公開要求は 1 秒あたり 100 要求以下に制限してください。

アプリケーションがメッセージをより高いレートで送信したり、より大きなメッセージを送信したりする必要がある場合は、[ストリームマネージャー](stream-manager-component.md) を使用して Kinesis データストリームにメッセージを送信することを検討してください。ストリームマネージャーコンポーネントは、大量のデータを  AWS クラウド に転送するように設計されています。詳細については、「[Greengrass コアデバイスでのデータストリームの管理](manage-data-streams.md)」を参照してください。

### リクエスト
<a name="ipc-operation-publishtoiotcore-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`topicName` (Python: `topic_name`)  
メッセージの発行先として指定するトピック。

`qos`  <a name="ipc-iot-core-mqtt-qos"></a>
使用する MQTT QoS。この列挙型 (`QOS`) には以下の値があります。  
+ `AT_MOST_ONCE` – QoS 0。MQTT メッセージが配信されるのは 1 回以下です。
+ `AT_LEAST_ONCE` – QoS 1。MQTT メッセージが配信されるのは 1 回以上です。

`payload`  
(オプション) BLOB としてのメッセージペイロード。

MQTT 5 を使用する際、[Greengrass nucleus](greengrass-nucleus-component.md) の v2.10.0 以降で以下の機能が使用できます。MQTT 3.1.1 を使用している場合、これらの機能は無視されます。次の表に、これらの機能にアクセスするために使用する必要がある AWS IoT デバイス SDK の最小バージョンを示します。


| SDK | 最小バージョン | 
| --- | --- | 
| [AWS IoT Device SDK for Python](https://github.com/aws/aws-iot-device-sdk-python-v2) v2 | v1.15.0 | 
| [AWS IoT Device SDK for Java](https://github.com/aws/aws-iot-device-sdk-java-v2) v2 | v1.13.0 | 
| [AWS IoT Device SDK for C\$1\$1](https://github.com/aws/aws-iot-device-sdk-cpp-v2) v2 | v1.24.0 | 
| [AWS IoT Device SDK for JavaScript](https://github.com/aws/aws-iot-device-sdk-js-v2) v2  | v1.13.0 | 

`payloadFormat`  
(オプション) メッセージペイロードのフォーマット。`payloadFormat` を設定しない場合、タイプは `BYTES` とみなされます。この列挙型には以下の値があります。  
+ `BYTES`— ペイロードのコンテンツは、バイナリ BLOB です。
+ `UTF8`— ペイロードのコンテンツは UTF8 の文字列です。

`retain`  
(オプション) 発行時に MQTT 保持オプションを `true` に設定するか否かを示します。

`userProperties`  
(オプション) 送信するアプリケーション固有の `UserProperty` オブジェクトのリストです。`UserProperty` オブジェクトは次のように定義されます。  

```
UserProperty:
  key: string
  value: string
```

`messageExpiryIntervalSeconds`  
(オプション) メッセージが期限切れとなり、サーバーによって削除されるまでの秒数です。この値を設定しない場合、メッセージに有効期限は設定されません。

`correlationData`  
(オプション) リクエストに付加される情報で、リクエストとレスポンスの関連付けに使用できます。

`responseTopic`  
(オプション) レスポンスメッセージに使用するトピックです。

`contentType`  
(オプション) メッセージのコンテンツタイプを示すアプリケーション固有の識別子です。

### 応答
<a name="ipc-operation-publishtoiotcore-response"></a>

このオペレーションはレスポンスで一切の情報を提供しません。

### 例
<a name="ipc-operation-publishtoiotcore-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Java (IPC client V2) ]

**Example 例:メッセージを発行する**  

```
package com.aws.greengrass.docs.samples.ipc;

import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClientV2;
import software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreRequest;
import software.amazon.awssdk.aws.greengrass.model.QOS;
import java.nio.charset.StandardCharsets;

public class PublishToIoTCore {

    public static void main(String[] args) {
        String topic = args[0];
        String message = args[1];
        QOS qos = QOS.get(args[2]);

        try (GreengrassCoreIPCClientV2 ipcClientV2 = GreengrassCoreIPCClientV2.builder().build()) {
            ipcClientV2.publishToIoTCore(new PublishToIoTCoreRequest()
                    .withTopicName(topic)
                    .withPayload(message.getBytes(StandardCharsets.UTF_8))
                    .withQos(qos));
            System.out.println("Successfully published to topic: " + topic);
        } catch (Exception e) {
            System.err.println("Exception occurred.");
            e.printStackTrace();
            System.exit(1);
        }
    }
}
```

------
#### [ Python (IPC client V2) ]

**Example 例:メッセージを発行する**  
この例では、 AWS IoT Device SDK for Python v2 のバージョン 1.5.4 以降を使用していることを前提としています。

```
import awsiot.greengrasscoreipc.clientv2 as clientV2
                    
topic = 'my/topic'
qos = '1'
payload = 'Hello, World'

ipc_client = clientV2.GreengrassCoreIPCClientV2()
resp = ipc_client.publish_to_iot_core(topic_name=topic, qos=qos, payload=payload)
ipc_client.close()
```

------
#### [ Java (IPC client V1) ]

**Example 例:メッセージを発行する**  
この例では、 `IPCUtils` クラスを使用して AWS IoT Greengrass Core IPC サービスへの接続を作成します。詳細については、「[AWS IoT Greengrass Core IPC サービスに接続する](interprocess-communication.md#ipc-service-connect)」を参照してください。

```
package com.aws.greengrass.docs.samples.ipc;

import com.aws.greengrass.docs.samples.ipc.util.IPCUtils;
import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient;
import software.amazon.awssdk.aws.greengrass.PublishToIoTCoreResponseHandler;
import software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreRequest;
import software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreResponse;
import software.amazon.awssdk.aws.greengrass.model.QOS;
import software.amazon.awssdk.aws.greengrass.model.UnauthorizedError;
import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection;

import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class PublishToIoTCore {

    public static final int TIMEOUT_SECONDS = 10;

    public static void main(String[] args) {
        String topic = args[0];
        String message = args[1];
        QOS qos = QOS.get(args[2]);
        try (EventStreamRPCConnection eventStreamRPCConnection =
                     IPCUtils.getEventStreamRpcConnection()) {
            GreengrassCoreIPCClient ipcClient =
                    new GreengrassCoreIPCClient(eventStreamRPCConnection);
            PublishToIoTCoreResponseHandler responseHandler =
                    PublishToIoTCore.publishBinaryMessageToTopic(ipcClient, topic, message, qos);
            CompletableFuture<PublishToIoTCoreResponse> futureResponse =
                    responseHandler.getResponse();
            try {
                futureResponse.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
                System.out.println("Successfully published to topic: " + topic);
            } catch (TimeoutException e) {
                System.err.println("Timeout occurred while publishing to topic: " + topic);
            } catch (ExecutionException e) {
                if (e.getCause() instanceof UnauthorizedError) {
                    System.err.println("Unauthorized error while publishing to topic: " + topic);
                } else {
                    throw e;
                }
            }
        } catch (InterruptedException e) {
            System.out.println("IPC interrupted.");
        } catch (ExecutionException e) {
            System.err.println("Exception occurred when using IPC.");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static PublishToIoTCoreResponseHandler publishBinaryMessageToTopic(GreengrassCoreIPCClient greengrassCoreIPCClient, String topic, String message, QOS qos) {
        PublishToIoTCoreRequest publishToIoTCoreRequest = new PublishToIoTCoreRequest();
        publishToIoTCoreRequest.setTopicName(topic);
        publishToIoTCoreRequest.setPayload(message.getBytes(StandardCharsets.UTF_8));
        publishToIoTCoreRequest.setQos(qos);
        return greengrassCoreIPCClient.publishToIoTCore(publishToIoTCoreRequest, Optional.empty());
    }
}
```

------
#### [ Python (IPC client V1) ]

**Example 例:メッセージを発行する**  
この例では、 AWS IoT Device SDK for Python v2 のバージョン 1.5.4 以降を使用していることを前提としています。

```
import awsiot.greengrasscoreipc
import awsiot.greengrasscoreipc.client as client
from awsiot.greengrasscoreipc.model import (
    QOS,
    PublishToIoTCoreRequest
)

TIMEOUT = 10

ipc_client = awsiot.greengrasscoreipc.connect()
                    
topic = "my/topic"
message = "Hello, World"
qos = QOS.AT_LEAST_ONCE

request = PublishToIoTCoreRequest()
request.topic_name = topic
request.payload = bytes(message, "utf-8")
request.qos = qos
operation = ipc_client.new_publish_to_iot_core()
operation.activate(request)
future_response = operation.get_response()
future_response.result(TIMEOUT)
```

------
#### [ C\$1\$1 (IPC client V1) ]

**Example 例:メッセージを発行する**  

```
#include <iostream>

#include <aws/crt/Api.h>
#include <aws/greengrass/GreengrassCoreIpcClient.h>

using namespace Aws::Crt;
using namespace Aws::Greengrass;

class IpcClientLifecycleHandler : public ConnectionLifecycleHandler {
    void OnConnectCallback() override {
        // Handle connection to IPC service.
    }

    void OnDisconnectCallback(RpcError error) override {
        // Handle disconnection from IPC service.
    }

    bool OnErrorCallback(RpcError error) override {
        // Handle IPC service connection error.
        return true;
    }
};

int main() {
    ApiHandle apiHandle(g_allocator);
    Io::EventLoopGroup eventLoopGroup(1);
    Io::DefaultHostResolver socketResolver(eventLoopGroup, 64, 30);
    Io::ClientBootstrap bootstrap(eventLoopGroup, socketResolver);
    IpcClientLifecycleHandler ipcLifecycleHandler;
    GreengrassCoreIpcClient ipcClient(bootstrap);
    auto connectionStatus = ipcClient.Connect(ipcLifecycleHandler).get();
    if (!connectionStatus) {
        std::cerr << "Failed to establish IPC connection: " << connectionStatus.StatusToString() << std::endl;
        exit(-1);
    }

    String message("Hello, World!");
    String topic("my/topic");
    QOS qos = QOS_AT_MOST_ONCE;
    int timeout = 10;

    PublishToIoTCoreRequest request;
    Vector<uint8_t> messageData({message.begin(), message.end()});
    request.SetTopicName(topic);
    request.SetPayload(messageData);
    request.SetQos(qos);

    auto operation = ipcClient.NewPublishToIoTCore();
    auto activate = operation->Activate(request, nullptr);
    activate.wait();

    auto responseFuture = operation->GetResult();
    if (responseFuture.wait_for(std::chrono::seconds(timeout)) == std::future_status::timeout) {
        std::cerr << "Operation timed out while waiting for response from Greengrass Core." << std::endl;
        exit(-1);
    }

    auto response = responseFuture.get();
    if (!response) {
        // Handle error.
        auto errorType = response.GetResultType();
        if (errorType == OPERATION_ERROR) {
            auto *error = response.GetOperationError();
            (void)error;
            // Handle operation error.
        } else {
            // Handle RPC error.
        }
    }

    return 0;
}
```

------
#### [ JavaScript ]

**Example 例:メッセージを発行する**  

```
    
import * as greengrasscoreipc from "aws-iot-device-sdk-v2/dist/greengrasscoreipc";
import {QOS, PublishToIoTCoreRequest} from "aws-iot-device-sdk-v2/dist/greengrasscoreipc/model";
 
class PublishToIoTCore {
    private ipcClient: greengrasscoreipc.Client
    private readonly topic: string;
 
    constructor() {
        // define your own constructor, e.g.
        this.topic = "<define_your_topic>";
        this.publishToIoTCore().then(r => console.log("Started workflow"));
    }
 
    private async publishToIoTCore() {
        try {
            const request: PublishToIoTCoreRequest = {
                topicName: this.topic,
                qos: QOS.AT_LEAST_ONCE, // you can change this depending on your use case
            }
 
            this.ipcClient = await getIpcClient();
 
            await this.ipcClient.publishToIoTCore(request);
        } catch (e) {
            // parse the error depending on your use cases
            throw e
        }
    }
}
 
 
export async function getIpcClient(){
    try {
        const ipcClient = greengrasscoreipc.createClient();
        await ipcClient.connect()
            .catch(error => {
                // parse the error depending on your use cases
                throw error;
            });
        return ipcClient
    } catch (err) {
        // parse the error depending on your use cases
        throw err
    }
}
 
// starting point
const publishToIoTCore = new PublishToIoTCore();
```

------
#### [ Rust ]

**Example 例:メッセージを発行する**  

```
use gg_sdk::{Qos, Sdk};

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    let message = b"Hello, World";
    let topic = "my/topic";
    let qos = Qos::AtLeastOnce;

    sdk.publish_to_iot_core(topic, message, qos)
        .expect("Failed to publish to topic");

    println!("Successfully published to topic: {topic}");
}
```

------
#### [ C ]

**Example 例:メッセージを発行する**  

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/sdk.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    GgBuffer message = GG_STR("Hello, World");
    GgBuffer topic = GG_STR("my/topic");
    uint8_t qos = 1;

    err = ggipc_publish_to_iot_core(topic, message, qos);
    if (err != GG_ERR_OK) {
        fprintf(
            stderr,
            "Failed to publish to topic: %.*s\n",
            (int) topic.len,
            topic.data
        );
        exit(-1);
    }

    printf(
        "Successfully published to topic: %.*s\n", (int) topic.len, topic.data
    );
}
```

------
#### [ C\$1\$1 (Component SDK) ]

**Example 例:メッセージを発行する**  

```
#include <gg/ipc/client.hpp>
#include <iostream>

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    std::string_view message = "Hello, World";
    std::string_view topic = "my/topic";
    uint8_t qos = 1;

    error = client.publish_to_iot_core(topic, message, qos);
    if (error) {
        std::cerr << "Failed to publish to topic: " << topic << "\n";
        exit(-1);
    }

    std::cout << "Successfully published to topic: " << topic << "\n";
}
```

------

## SubscribeToIoTCore
<a name="ipc-operation-subscribetoiotcore"></a>

トピックまたはトピックフィルター AWS IoT Core で から MQTT メッセージをサブスクライブします。 AWS IoT Greengrass Core ソフトウェアは、コンポーネントがライフサイクルの終了に達するとサブスクリプションを削除します。

<a name="ipc-subscribe-operation-note"></a>このオペレーションはサブスクリプションオペレーションで、イベントメッセージのストリームをサブスクライブするというものです。このオペレーションを使用するには、イベントメッセージ、エラー、およびストリームクロージャを処理する関数を使用して、ストリームレスポンスハンドラーを定義します。(詳細については、[IPC イベントストリームへのサブスクライブ](interprocess-communication.md#ipc-subscribe-operations) を参照してください)。

**イベントメッセージの種類:** `IoTCoreMessage`

### リクエスト
<a name="ipc-operation-subscribetoiotcore-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`topicName` (Python: `topic_name`)  
サブスクライブ先のトピック。MQTT トピックのワイルドカード (`#` および `+`) を使用して、複数のトピックにサブスクライブできます。

`qos`  <a name="ipc-iot-core-mqtt-qos"></a>
使用する MQTT QoS。この列挙型 (`QOS`) には以下の値があります。  
+ `AT_MOST_ONCE` – QoS 0。MQTT メッセージが配信されるのは 1 回以下です。
+ `AT_LEAST_ONCE` – QoS 1。MQTT メッセージが配信されるのは 1 回以上です。

### 応答
<a name="ipc-operation-subscribetoiotcore-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`messages`  
MQTT メッセージのストリーム。このオブジェクト (`IoTCoreMessage`) には、次の情報が含まれます。    
`message`  
MQTT メッセージ。このオブジェクト (`MQTTMessage`) には、次の情報が含まれます。    
`topicName` (Python: `topic_name`)  
メッセージが発行されたトピック。  
`payload`  
(オプション) BLOB としてのメッセージペイロード。
MQTT 5 を使用する際、[Greengrass nucleus](greengrass-nucleus-component.md) の v2.10.0 以降で以下の機能が使用できます。MQTT 3.1.1 を使用している場合、これらの機能は無視されます。次の表に、これらの機能にアクセスするために使用する必要がある AWS IoT デバイス SDK の最小バージョンを示します。      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-iot-core-mqtt.html)  
`payloadFormat`  
(オプション) メッセージペイロードのフォーマット。`payloadFormat` を設定しない場合、タイプは `BYTES` とみなされます。この列挙型には以下の値があります。  
+ `BYTES`— ペイロードのコンテンツは、バイナリ BLOB です。
+ `UTF8`— ペイロードのコンテンツは UTF8 の文字列です。  
`retain`  
(オプション) 発行時に MQTT 保持オプションを `true` に設定するか否かを示します。  
`userProperties`  
(オプション) 送信するアプリケーション固有の `UserProperty` オブジェクトのリストです。`UserProperty` オブジェクトは次のように定義されます。  

```
UserProperty:
  key: string
  value: string
```  
`messageExpiryIntervalSeconds`  
(オプション) メッセージが期限切れとなり、サーバーによって削除されるまでの秒数です。この値を設定しない場合、メッセージに有効期限は設定されません。  
`correlationData`  
(オプション) リクエストに付加される情報で、リクエストとレスポンスの関連付けに使用できます。  
`responseTopic`  
(オプション) レスポンスメッセージに使用するトピックです。  
`contentType`  
(オプション)メッセージのコンテンツタイプのアプリケーション固有の識別子です。

### 例
<a name="ipc-operation-subscribetoiotcore-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Java (IPC client V2) ]

**Example 例:メッセージをサブスクライブする**  

```
package com.aws.greengrass.docs.samples.ipc;

import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClientV2;
import software.amazon.awssdk.aws.greengrass.SubscribeToIoTCoreResponseHandler;
import software.amazon.awssdk.aws.greengrass.model.QOS;
import software.amazon.awssdk.aws.greengrass.model.IoTCoreMessage;
import software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest;
import software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreResponse;

import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;


public class SubscribeToIoTCore {

    public static void main(String[] args) {
        String topic = args[0];
        QOS qos = QOS.get(args[1]);

        Consumer<IoTCoreMessage> onStreamEvent = ioTCoreMessage ->
                System.out.printf("Received new message on topic %s: %s%n",
                        ioTCoreMessage.getMessage().getTopicName(),
                        new String(ioTCoreMessage.getMessage().getPayload(), StandardCharsets.UTF_8));

        Optional<Function<Throwable, Boolean>> onStreamError =
                Optional.of(e -> {
                    System.err.println("Received a stream error.");
                    e.printStackTrace();
                    return false;
                });

        Optional<Runnable> onStreamClosed = Optional.of(() ->
                System.out.println("Subscribe to IoT Core stream closed."));

        try (GreengrassCoreIPCClientV2 ipcClientV2 = GreengrassCoreIPCClientV2.builder().build()) {
            SubscribeToIoTCoreRequest request = new SubscribeToIoTCoreRequest()
                    .withTopicName(topic)
                    .withQos(qos);

            GreengrassCoreIPCClientV2.StreamingResponse<SubscribeToIoTCoreResponse, SubscribeToIoTCoreResponseHandler>
                    streamingResponse = ipcClientV2.subscribeToIoTCore(request, onStreamEvent, onStreamError, onStreamClosed);

            streamingResponse.getResponse();
            System.out.println("Successfully subscribed to topic: " + topic);

            // Keep the main thread alive, or the process will exit.
            while (true) {
                Thread.sleep(10000);
            }

            // To stop subscribing, close the stream.
            streamingResponse.getHandler().closeStream();
        } catch (InterruptedException e) {
            System.out.println("Subscribe interrupted.");
        } catch (Exception e) {
            System.err.println("Exception occurred.");
            e.printStackTrace();
            System.exit(1);
        }
    }
}
```

------
#### [ Python (IPC client V2) ]

**Example 例: メッセージをサブスクライブする**  
この例では、 AWS IoT Device SDK for Python v2 のバージョン 1.5.4 以降を使用していることを前提としています。

```
import threading
import traceback

import awsiot.greengrasscoreipc.clientv2 as clientV2
                    
topic = 'my/topic'
qos = '1'

def on_stream_event(event):
    try:
        topic_name = event.message.topic_name
        message = str(event.message.payload, 'utf-8')
        print(f'Received new message on topic {topic_name}:  {message}')
    except:
        traceback.print_exc()

def on_stream_error(error):
    # Return True to close stream, False to keep stream open.
    return True  

def on_stream_closed():
    pass

ipc_client = clientV2.GreengrassCoreIPCClientV2()
resp, operation = ipc_client.subscribe_to_iot_core(
    topic_name=topic,
    qos=qos, 
    on_stream_event=on_stream_event,
    on_stream_error=on_stream_error,
    on_stream_closed=on_stream_closed
)

# Keep the main thread alive, or the process will exit.
event = threading.Event()
event.wait()

# To stop subscribing, close the operation stream.
operation.close()
ipc_client.close()
```

------
#### [ Java (IPC client V1) ]

**Example 例:メッセージをサブスクライブする**  
この例では、 `IPCUtils` クラスを使用して AWS IoT Greengrass Core IPC サービスへの接続を作成します。詳細については、「[AWS IoT Greengrass Core IPC サービスに接続する](interprocess-communication.md#ipc-service-connect)」を参照してください。

```
package com.aws.greengrass.docs.samples.ipc;

import com.aws.greengrass.docs.samples.ipc.util.IPCUtils;
import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient;
import software.amazon.awssdk.aws.greengrass.SubscribeToIoTCoreResponseHandler;
import software.amazon.awssdk.aws.greengrass.model.*;
import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection;
import software.amazon.awssdk.eventstreamrpc.StreamResponseHandler;

import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class SubscribeToIoTCore {

    public static final int TIMEOUT_SECONDS = 10;

    public static void main(String[] args) {
        String topic = args[0];
        QOS qos = QOS.get(args[1]);
        try (EventStreamRPCConnection eventStreamRPCConnection =
                     IPCUtils.getEventStreamRpcConnection()) {
            GreengrassCoreIPCClient ipcClient =
                    new GreengrassCoreIPCClient(eventStreamRPCConnection);
            StreamResponseHandler<IoTCoreMessage> streamResponseHandler =
                    new SubscriptionResponseHandler();
            SubscribeToIoTCoreResponseHandler responseHandler =
                    SubscribeToIoTCore.subscribeToIoTCore(ipcClient, topic, qos,
                            streamResponseHandler);
            CompletableFuture<SubscribeToIoTCoreResponse> futureResponse =
                    responseHandler.getResponse();
            try {
                futureResponse.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
                System.out.println("Successfully subscribed to topic: " + topic);
            } catch (TimeoutException e) {
                System.err.println("Timeout occurred while subscribing to topic: " + topic);
            } catch (ExecutionException e) {
                if (e.getCause() instanceof UnauthorizedError) {
                    System.err.println("Unauthorized error while subscribing to topic: " + topic);
                } else {
                    throw e;
                }
            }

            // Keep the main thread alive, or the process will exit.
            try {
                while (true) {
                    Thread.sleep(10000);
                }
            } catch (InterruptedException e) {
                System.out.println("Subscribe interrupted.");
            }

            // To stop subscribing, close the stream.
            responseHandler.closeStream();
        } catch (InterruptedException e) {
            System.out.println("IPC interrupted.");
        } catch (ExecutionException e) {
            System.err.println("Exception occurred when using IPC.");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static SubscribeToIoTCoreResponseHandler subscribeToIoTCore(GreengrassCoreIPCClient greengrassCoreIPCClient, String topic, QOS qos, StreamResponseHandler<IoTCoreMessage> streamResponseHandler) {
        SubscribeToIoTCoreRequest subscribeToIoTCoreRequest = new SubscribeToIoTCoreRequest();
        subscribeToIoTCoreRequest.setTopicName(topic);
        subscribeToIoTCoreRequest.setQos(qos);
        return greengrassCoreIPCClient.subscribeToIoTCore(subscribeToIoTCoreRequest,
                Optional.of(streamResponseHandler));
    }

    public static class SubscriptionResponseHandler implements StreamResponseHandler<IoTCoreMessage> {

        @Override
        public void onStreamEvent(IoTCoreMessage ioTCoreMessage) {
            try {
                String topic = ioTCoreMessage.getMessage().getTopicName();
                String message = new String(ioTCoreMessage.getMessage().getPayload(),
                        StandardCharsets.UTF_8);
                System.out.printf("Received new message on topic %s: %s%n", topic, message);
            } catch (Exception e) {
                System.err.println("Exception occurred while processing subscription response " +
                        "message.");
                e.printStackTrace();
            }
        }

        @Override
        public boolean onStreamError(Throwable error) {
            System.err.println("Received a stream error.");
            error.printStackTrace();
            return false;
        }

        @Override
        public void onStreamClosed() {
            System.out.println("Subscribe to IoT Core stream closed.");
        }
    }
}
```

------
#### [ Python (IPC client V1) ]

**Example 例:メッセージをサブスクライブする**  
この例では、 AWS IoT Device SDK for Python v2 のバージョン 1.5.4 以降を使用していることを前提としています。

```
import time
import traceback

import awsiot.greengrasscoreipc
import awsiot.greengrasscoreipc.client as client
from awsiot.greengrasscoreipc.model import (
    IoTCoreMessage,
    QOS,
    SubscribeToIoTCoreRequest
)

TIMEOUT = 10

ipc_client = awsiot.greengrasscoreipc.connect()

class StreamHandler(client.SubscribeToIoTCoreStreamHandler):
    def __init__(self):
        super().__init__()

    def on_stream_event(self, event: IoTCoreMessage) -> None:
        try:
            message = str(event.message.payload, "utf-8")
            topic_name = event.message.topic_name
            # Handle message.
        except:
            traceback.print_exc()

    def on_stream_error(self, error: Exception) -> bool:
        # Handle error.
        return True  # Return True to close stream, False to keep stream open.

    def on_stream_closed(self) -> None:
        # Handle close.
        pass


topic = "my/topic"
qos = QOS.AT_MOST_ONCE

request = SubscribeToIoTCoreRequest()
request.topic_name = topic
request.qos = qos
handler = StreamHandler()
operation = ipc_client.new_subscribe_to_iot_core(handler)
operation.activate(request)
future_response = operation.get_response() 
future_response.result(TIMEOUT)

# Keep the main thread alive, or the process will exit.
while True:
    time.sleep(10)
                  
# To stop subscribing, close the operation stream.
operation.close()
```

------
#### [ C\$1\$1 (IPC client V1) ]

**Example 例:メッセージをサブスクライブする**  

```
#include <iostream>

#include <aws/crt/Api.h>
#include <aws/greengrass/GreengrassCoreIpcClient.h>

using namespace Aws::Crt;
using namespace Aws::Greengrass;

class IoTCoreResponseHandler : public SubscribeToIoTCoreStreamHandler {

    public:
        virtual ~IoTCoreResponseHandler() {}

    private:
        void OnStreamEvent(IoTCoreMessage *response) override {
            auto message = response->GetMessage();
            if (message.has_value() && message.value().GetPayload().has_value()) {
                auto messageBytes = message.value().GetPayload().value();
                std::string messageString(messageBytes.begin(), messageBytes.end());
                std::string topicName = message.value().GetTopicName().value().c_str();
                // Handle message.
            }
        }

        bool OnStreamError(OperationError *error) override {
            // Handle error.
            return false; // Return true to close stream, false to keep stream open.
        }

        void OnStreamClosed() override {
            // Handle close.
        }
};

class IpcClientLifecycleHandler : public ConnectionLifecycleHandler {
    void OnConnectCallback() override {
        // Handle connection to IPC service.
    }

    void OnDisconnectCallback(RpcError error) override {
        // Handle disconnection from IPC service.
    }

    bool OnErrorCallback(RpcError error) override {
        // Handle IPC service connection error.
        return true;
    }
};

int main() {
    ApiHandle apiHandle(g_allocator);
    Io::EventLoopGroup eventLoopGroup(1);
    Io::DefaultHostResolver socketResolver(eventLoopGroup, 64, 30);
    Io::ClientBootstrap bootstrap(eventLoopGroup, socketResolver);
    IpcClientLifecycleHandler ipcLifecycleHandler;
    GreengrassCoreIpcClient ipcClient(bootstrap);
    auto connectionStatus = ipcClient.Connect(ipcLifecycleHandler).get();
    if (!connectionStatus) {
        std::cerr << "Failed to establish IPC connection: " << connectionStatus.StatusToString() << std::endl;
        exit(-1);
    }

    String topic("my/topic");
    QOS qos = QOS_AT_MOST_ONCE;
    int timeout = 10;

    SubscribeToIoTCoreRequest request;
    request.SetTopicName(topic);
    request.SetQos(qos);
    auto streamHandler = MakeShared<IoTCoreResponseHandler>(DefaultAllocator());
    auto operation = ipcClient.NewSubscribeToIoTCore(streamHandler);
    auto activate = operation->Activate(request, nullptr);
    activate.wait();

    auto responseFuture = operation->GetResult();
    if (responseFuture.wait_for(std::chrono::seconds(timeout)) == std::future_status::timeout) {
        std::cerr << "Operation timed out while waiting for response from Greengrass Core." << std::endl;
        exit(-1);
    }

    auto response = responseFuture.get();
    if (!response) {
        // Handle error.
        auto errorType = response.GetResultType();
        if (errorType == OPERATION_ERROR) {
            auto *error = response.GetOperationError();
            (void)error;
            // Handle operation error.
        } else {
            // Handle RPC error.
        }
        exit(-1);
    }

    // Keep the main thread alive, or the process will exit.
    while (true) {
        std::this_thread::sleep_for(std::chrono::seconds(10));
    }

    operation->Close();
    return 0;
}
```

------
#### [ JavaScript ]

**Example 例:メッセージをサブスクライブする**  

```
import * as greengrasscoreipc from "aws-iot-device-sdk-v2/dist/greengrasscoreipc";
import {IoTCoreMessage, QOS, SubscribeToIoTCoreRequest} from "aws-iot-device-sdk-v2/dist/greengrasscoreipc/model";
import {RpcError} from "aws-iot-device-sdk-v2/dist/eventstream_rpc";
 
class SubscribeToIoTCore {
    private ipcClient: greengrasscoreipc.Client
    private readonly topic: string;
 
    constructor() {
        // define your own constructor, e.g.
        this.topic = "<define_your_topic>";
        this.subscribeToIoTCore().then(r => console.log("Started workflow"));
    }
 
    private async subscribeToIoTCore() {
        try {
            const request: SubscribeToIoTCoreRequest = {
                topicName: this.topic,
                qos: QOS.AT_LEAST_ONCE, // you can change this depending on your use case
            }
 
            this.ipcClient = await getIpcClient();
 
            const streamingOperation = this.ipcClient.subscribeToIoTCore(request);
 
            streamingOperation.on('message', (message: IoTCoreMessage) => {
                // parse the message depending on your use cases, e.g.
                if (message.message && message.message.payload) {
                    const receivedMessage = message.message.payload.toString();
                }
            });
 
            streamingOperation.on('streamError', (error : RpcError) => {
                // define your own error handling logic
            });
 
            streamingOperation.on('ended', () => {
                // define your own logic
            });
 
            await streamingOperation.activate();
 
            // Keep the main thread alive, or the process will exit.
            await new Promise((resolve) => setTimeout(resolve, 10000))
        } catch (e) {
            // parse the error depending on your use cases
            throw e
        }
    }
}
 
export async function getIpcClient(){
    try {
        const ipcClient = greengrasscoreipc.createClient();
        await ipcClient.connect()
            .catch(error => {
                // parse the error depending on your use cases
                throw error;
            });
        return ipcClient
    } catch (err) {
        // parse the error depending on your use cases
        throw err
    }
}
 
// starting point
const subscribeToIoTCore = new SubscribeToIoTCore();
```

------
#### [ Rust ]

**Example 例:メッセージをサブスクライブする**  

```
use gg_sdk::{Qos, Sdk};
use std::{thread, time::Duration};

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    let topic = "my/topic";
    let qos = Qos::AtLeastOnce;

    let callback = |topic: &str, payload: &[u8]| {
        let message = String::from_utf8_lossy(payload);
        println!("Received new message on topic {topic}: {message}");
    };

    let _sub = sdk
        .subscribe_to_iot_core(topic, qos, &callback)
        .expect("Failed to subscribe to topic");

    println!("Successfully subscribed to topic: {topic}");

    // Keep the main thread alive, or the process will exit.
    loop {
        thread::sleep(Duration::from_secs(10));
    }
}
```

------
#### [ C ]

**Example 例:メッセージをサブスクライブする**  

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/sdk.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static void on_subscription_response(
    void *ctx, GgBuffer topic, GgBuffer payload, GgIpcSubscriptionHandle handle
) {
    (void) ctx;
    (void) handle;

    printf(
        "Received new message on topic %.*s: %.*s\n",
        (int) topic.len,
        topic.data,
        (int) payload.len,
        payload.data
    );
}

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    GgBuffer topic = GG_STR("my/topic");
    uint8_t qos = 1;

    GgIpcSubscriptionHandle handle;
    err = ggipc_subscribe_to_iot_core(
        topic, qos, on_subscription_response, NULL, &handle
    );
    if (err != GG_ERR_OK) {
        fprintf(
            stderr,
            "Failed to subscribe to topic: %.*s\n",
            (int) topic.len,
            topic.data
        );
        exit(-1);
    }

    printf(
        "Successfully subscribed to topic: %.*s\n", (int) topic.len, topic.data
    );

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }

    // To stop subscribing, close the subscription handle.
    ggipc_close_subscription(handle);
}
```

------
#### [ C\$1\$1 (Component SDK) ]

**Example 例:メッセージをサブスクライブする**  

```
#include <gg/ipc/client.hpp>
#include <unistd.h>
#include <iostream>

class ResponseHandler : public gg::ipc::IotTopicCallback {
    void operator()(
        std::string_view topic,
        gg::Buffer payload,
        gg::ipc::Subscription &handle
    ) override {
        (void) handle;
        std::cout << "Received new message on topic " << topic << ": "
                  << payload << "\n";
    }
};

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    std::string_view topic = "my/topic";
    uint8_t qos = 1;

    static ResponseHandler handler;
    error = client.subscribe_to_iot_core(topic, qos, handler);
    if (error) {
        std::cerr << "Failed to subscribe to topic: " << topic << "\n";
        exit(-1);
    }

    std::cout << "Successfully subscribed to topic: " << topic << "\n";

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }
}
```

------

## 例
<a name="ipc-iot-core-mqtt-examples"></a>

コンポーネントで AWS IoT Core MQTT IPC サービスを使用する方法については、次の例を参照してください。

### AWS IoT Core MQTT パブリッシャーの例 (C\$1\$1、IPC クライアント V1)
<a name="ipc-iot-core-mqtt-example-publisher-cpp"></a>

以下の recipe の例は、コンポーネントをすべてのトピックに発行できるようにします。

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.IoTCorePublisherCpp",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes MQTT messages to IoT Core.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.mqttproxy": {
          "com.example.IoTCorePublisherCpp:mqttproxy:1": {
            "policyDescription": "Allows access to publish to all topics.",
            "operations": [
              "aws.greengrass#PublishToIoTCore"
            ],
            "resources": [
              "*"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Lifecycle": {
        "Run": "{artifacts:path}/greengrassv2_iotcore_publisher"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.IoTCorePublisherCpp/1.0.0/greengrassv2_iotcore_publisher",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.IoTCorePublisherCpp
ComponentVersion: 1.0.0
ComponentDescription: A component that publishes MQTT messages to IoT Core.
ComponentPublisher: Amazon
ComponentConfiguration:
  DefaultConfiguration:
    accessControl:
      aws.greengrass.ipc.mqttproxy:
        com.example.IoTCorePublisherCpp:mqttproxy:1:
          policyDescription: Allows access to publish to all topics.
          operations:
            - aws.greengrass#PublishToIoTCore
          resources:
            - "*"
Manifests:
  - Lifecycle:
      Run: "{artifacts:path}/greengrassv2_iotcore_publisher"
    Artifacts:
      - URI: s3://amzn-s3-demo-bucket/artifacts/com.example.IoTCorePublisherCpp/1.0.0/greengrassv2_iotcore_publisher
        Permission:
          Execute: OWNER
```

------

次の C\$1\$1 アプリケーションの例は、 AWS IoT Core MQTT IPC サービスを使用してメッセージを発行する方法を示しています AWS IoT Core。

```
#include <iostream>

#include <aws/crt/Api.h>
#include <aws/greengrass/GreengrassCoreIpcClient.h>

using namespace Aws::Crt;
using namespace Aws::Greengrass;

class IpcClientLifecycleHandler : public ConnectionLifecycleHandler {
    void OnConnectCallback() override {
        std::cout << "OnConnectCallback" << std::endl;
    }

    void OnDisconnectCallback(RpcError error) override {
        std::cout << "OnDisconnectCallback: " << error.StatusToString() << std::endl;
        exit(-1);
    }

    bool OnErrorCallback(RpcError error) override {
        std::cout << "OnErrorCallback: " << error.StatusToString() << std::endl;
        return true;
    }
};

int main() {
    String message("Hello from the Greengrass IPC MQTT publisher (C++).");
    String topic("test/topic/cpp");
    QOS qos = QOS_AT_LEAST_ONCE;
    int timeout = 10;

    ApiHandle apiHandle(g_allocator);
    Io::EventLoopGroup eventLoopGroup(1);
    Io::DefaultHostResolver socketResolver(eventLoopGroup, 64, 30);
    Io::ClientBootstrap bootstrap(eventLoopGroup, socketResolver);
    IpcClientLifecycleHandler ipcLifecycleHandler;
    GreengrassCoreIpcClient ipcClient(bootstrap);
    auto connectionStatus = ipcClient.Connect(ipcLifecycleHandler).get();
    if (!connectionStatus) {
        std::cerr << "Failed to establish IPC connection: " << connectionStatus.StatusToString() << std::endl;
        exit(-1);
    }

    while (true) {
        PublishToIoTCoreRequest request;
        Vector<uint8_t> messageData({message.begin(), message.end()});
        request.SetTopicName(topic);
        request.SetPayload(messageData);
        request.SetQos(qos);

        auto operation = ipcClient.NewPublishToIoTCore();
        auto activate = operation->Activate(request, nullptr);
        activate.wait();

        auto responseFuture = operation->GetResult();
        if (responseFuture.wait_for(std::chrono::seconds(timeout)) == std::future_status::timeout) {
            std::cerr << "Operation timed out while waiting for response from Greengrass Core." << std::endl;
            exit(-1);
        }

        auto response = responseFuture.get();
        if (response) {
            std::cout << "Successfully published to topic: " << topic << std::endl;
        } else {
            // An error occurred.
            std::cout << "Failed to publish to topic: " << topic << std::endl;
            auto errorType = response.GetResultType();
            if (errorType == OPERATION_ERROR) {
                auto *error = response.GetOperationError();
                std::cout << "Operation error: " << error->GetMessage().value() << std::endl;
            } else {
                std::cout << "RPC error: " << response.GetRpcError() << std::endl;
            }
            exit(-1);
        }

        std::this_thread::sleep_for(std::chrono::seconds(5));
    }

    return 0;
}
```

### AWS IoT Core MQTT サブスクライバーの例 (C\$1\$1、IPC クライアント V1)
<a name="ipc-iot-core-mqtt-example-subscriber-cpp"></a>

以下の recipe の例は、コンポーネントをすべてのトピックをサブスクライブできるようにします。

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.IoTCoreSubscriberCpp",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that subscribes to MQTT messages from IoT Core.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.mqttproxy": {
          "com.example.IoTCoreSubscriberCpp:mqttproxy:1": {
            "policyDescription": "Allows access to subscribe to all topics.",
            "operations": [
              "aws.greengrass#SubscribeToIoTCore"
            ],
            "resources": [
              "*"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Lifecycle": {
        "Run": "{artifacts:path}/greengrassv2_iotcore_subscriber"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.IoTCoreSubscriberCpp/1.0.0/greengrassv2_iotcore_subscriber",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.IoTCoreSubscriberCpp
ComponentVersion: 1.0.0
ComponentDescription: A component that subscribes to MQTT messages from IoT Core.
ComponentPublisher: Amazon
ComponentConfiguration:
  DefaultConfiguration:
    accessControl:
      aws.greengrass.ipc.mqttproxy:
        com.example.IoTCoreSubscriberCpp:mqttproxy:1:
          policyDescription: Allows access to subscribe to all topics.
          operations:
            - aws.greengrass#SubscribeToIoTCore
          resources:
            - "*"
Manifests:
  - Lifecycle:
      Run: "{artifacts:path}/greengrassv2_iotcore_subscriber"
    Artifacts:
      - URI: s3://amzn-s3-demo-bucket/artifacts/com.example.IoTCoreSubscriberCpp/1.0.0/greengrassv2_iotcore_subscriber
        Permission:
          Execute: OWNER
```

------

次の C\$1\$1 アプリケーションの例は、 AWS IoT Core MQTT IPC サービスを使用してメッセージをサブスクライブする方法を示しています AWS IoT Core。

```
#include <iostream>

#include <aws/crt/Api.h>
#include <aws/greengrass/GreengrassCoreIpcClient.h>

using namespace Aws::Crt;
using namespace Aws::Greengrass;

class IoTCoreResponseHandler : public SubscribeToIoTCoreStreamHandler {

    public:
        virtual ~IoTCoreResponseHandler() {}

    private:

        void OnStreamEvent(IoTCoreMessage *response) override {
            auto message = response->GetMessage();
            if (message.has_value() && message.value().GetPayload().has_value()) {
                auto messageBytes = message.value().GetPayload().value();
                std::string messageString(messageBytes.begin(), messageBytes.end());
                std::string messageTopic = message.value().GetTopicName().value().c_str();
                std::cout << "Received new message on topic: " << messageTopic << std::endl;
                std::cout << "Message: " << messageString << std::endl;
            }
        }

        bool OnStreamError(OperationError *error) override {
            std::cout << "Received an operation error: ";
            if (error->GetMessage().has_value()) {
                std::cout << error->GetMessage().value();
            }
            std::cout << std::endl;
            return false; // Return true to close stream, false to keep stream open.
        }

        void OnStreamClosed() override {
            std::cout << "Subscribe to IoT Core stream closed." << std::endl;
        }
};

class IpcClientLifecycleHandler : public ConnectionLifecycleHandler {
    void OnConnectCallback() override {
        std::cout << "OnConnectCallback" << std::endl;
    }

    void OnDisconnectCallback(RpcError error) override {
        std::cout << "OnDisconnectCallback: " << error.StatusToString() << std::endl;
        exit(-1);
    }

    bool OnErrorCallback(RpcError error) override {
        std::cout << "OnErrorCallback: " << error.StatusToString() << std::endl;
        return true;
    }
};

int main() {
    String topic("test/topic/cpp");
    QOS qos = QOS_AT_LEAST_ONCE;
    int timeout = 10;

    ApiHandle apiHandle(g_allocator);
    Io::EventLoopGroup eventLoopGroup(1);
    Io::DefaultHostResolver socketResolver(eventLoopGroup, 64, 30);
    Io::ClientBootstrap bootstrap(eventLoopGroup, socketResolver);
    IpcClientLifecycleHandler ipcLifecycleHandler;
    GreengrassCoreIpcClient ipcClient(bootstrap);
    auto connectionStatus = ipcClient.Connect(ipcLifecycleHandler).get();
    if (!connectionStatus) {
        std::cerr << "Failed to establish IPC connection: " << connectionStatus.StatusToString() << std::endl;
        exit(-1);
    }

    SubscribeToIoTCoreRequest request;
    request.SetTopicName(topic);
    request.SetQos(qos);
    auto streamHandler = MakeShared<IoTCoreResponseHandler>(DefaultAllocator());
    auto operation = ipcClient.NewSubscribeToIoTCore(streamHandler);
    auto activate = operation->Activate(request, nullptr);
    activate.wait();

    auto responseFuture = operation->GetResult();
    if (responseFuture.wait_for(std::chrono::seconds(timeout)) == std::future_status::timeout) {
        std::cerr << "Operation timed out while waiting for response from Greengrass Core." << std::endl;
        exit(-1);
    }

    auto response = responseFuture.get();
    if (response) {
        std::cout << "Successfully subscribed to topic: " << topic << std::endl;
    } else {
        // An error occurred.
        std::cout << "Failed to subscribe to topic: " << topic << std::endl;
        auto errorType = response.GetResultType();
        if (errorType == OPERATION_ERROR) {
            auto *error = response.GetOperationError();
            std::cout << "Operation error: " << error->GetMessage().value() << std::endl;
        } else {
            std::cout << "RPC error: " << response.GetRpcError() << std::endl;
        }
        exit(-1);
    }

    // Keep the main thread alive, or the process will exit.
    while (true) {
        std::this_thread::sleep_for(std::chrono::seconds(10));
    }

    operation->Close();
    return 0;
}
```

### AWS IoT Core MQTT パブリッシャーの例 (Rust)
<a name="ipc-iot-core-mqtt-example-publisher-rust"></a>

以下の recipe の例は、コンポーネントをすべてのトピックに発行できるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.IoTCorePublisherRust",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes MQTT messages to IoT Core.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.mqttproxy": {
          "com.example.IoTCorePublisherRust:mqttproxy:1": {
            "policyDescription": "Allows access to publish to all topics.",
            "operations": ["aws.greengrass#PublishToIoTCore"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/publish_to_iot_core"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.IoTCorePublisherRust/1.0.0/publish_to_iot_core",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の Rust アプリケーション例は、 AWS IoT Core MQTT IPC サービスを使用してメッセージを発行する方法を示しています AWS IoT Core。

```
use gg_sdk::{Qos, Sdk};

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    let message = b"Hello, World";
    let topic = "my/topic";
    let qos = Qos::AtLeastOnce;

    sdk.publish_to_iot_core(topic, message, qos)
        .expect("Failed to publish to topic");

    println!("Successfully published to topic: {topic}");
}
```

### AWS IoT Core MQTT サブスクライバーの例 (Rust)
<a name="ipc-iot-core-mqtt-example-subscriber-rust"></a>

以下の recipe の例は、コンポーネントをすべてのトピックをサブスクライブできるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.IoTCoreSubscriberRust",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that subscribes to MQTT messages from IoT Core.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.mqttproxy": {
          "com.example.IoTCoreSubscriberRust:mqttproxy:1": {
            "policyDescription": "Allows access to subscribe to all topics.",
            "operations": ["aws.greengrass#SubscribeToIoTCore"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/subscribe_to_iot_core"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.IoTCoreSubscriberRust/1.0.0/subscribe_to_iot_core",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の Rust アプリケーションの例は、 AWS IoT Core MQTT IPC サービスを使用してメッセージをサブスクライブする方法を示しています AWS IoT Core。

```
use gg_sdk::{Qos, Sdk};
use std::{thread, time::Duration};

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    let topic = "my/topic";
    let qos = Qos::AtLeastOnce;

    let callback = |topic: &str, payload: &[u8]| {
        let message = String::from_utf8_lossy(payload);
        println!("Received new message on topic {topic}: {message}");
    };

    let _sub = sdk
        .subscribe_to_iot_core(topic, qos, &callback)
        .expect("Failed to subscribe to topic");

    println!("Successfully subscribed to topic: {topic}");

    // Keep the main thread alive, or the process will exit.
    loop {
        thread::sleep(Duration::from_secs(10));
    }
}
```

### AWS IoT Core MQTT パブリッシャーの例 (C)
<a name="ipc-iot-core-mqtt-example-publisher-c"></a>

以下の recipe の例は、コンポーネントをすべてのトピックに発行できるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.IoTCorePublisherC",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes MQTT messages to IoT Core.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.mqttproxy": {
          "com.example.IoTCorePublisherC:mqttproxy:1": {
            "policyDescription": "Allows access to publish to all topics.",
            "operations": ["aws.greengrass#PublishToIoTCore"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/sample_publish_to_iot_core"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.IoTCorePublisherC/1.0.0/sample_publish_to_iot_core",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の C アプリケーション例は、 AWS IoT Core MQTT IPC サービスを使用してメッセージを発行する方法を示しています AWS IoT Core。

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/sdk.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    GgBuffer message = GG_STR("Hello, World");
    GgBuffer topic = GG_STR("my/topic");
    uint8_t qos = 1;

    err = ggipc_publish_to_iot_core(topic, message, qos);
    if (err != GG_ERR_OK) {
        fprintf(
            stderr,
            "Failed to publish to topic: %.*s\n",
            (int) topic.len,
            topic.data
        );
        exit(-1);
    }

    printf(
        "Successfully published to topic: %.*s\n", (int) topic.len, topic.data
    );
}
```

### AWS IoT Core MQTT サブスクライバーの例 (C)
<a name="ipc-iot-core-mqtt-example-subscriber-c"></a>

以下の recipe の例は、コンポーネントをすべてのトピックをサブスクライブできるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.IoTCoreSubscriberC",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that subscribes to MQTT messages from IoT Core.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.mqttproxy": {
          "com.example.IoTCoreSubscriberC:mqttproxy:1": {
            "policyDescription": "Allows access to subscribe to all topics.",
            "operations": ["aws.greengrass#SubscribeToIoTCore"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/sample_subscribe_to_iot_core"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.IoTCoreSubscriberC/1.0.0/sample_subscribe_to_iot_core",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の C アプリケーション例は、 AWS IoT Core MQTT IPC サービスを使用してメッセージをサブスクライブする方法を示しています AWS IoT Core。

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/sdk.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static void on_subscription_response(
    void *ctx, GgBuffer topic, GgBuffer payload, GgIpcSubscriptionHandle handle
) {
    (void) ctx;
    (void) handle;

    printf(
        "Received new message on topic %.*s: %.*s\n",
        (int) topic.len,
        topic.data,
        (int) payload.len,
        payload.data
    );
}

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    GgBuffer topic = GG_STR("my/topic");
    uint8_t qos = 1;

    GgIpcSubscriptionHandle handle;
    err = ggipc_subscribe_to_iot_core(
        topic, qos, on_subscription_response, NULL, &handle
    );
    if (err != GG_ERR_OK) {
        fprintf(
            stderr,
            "Failed to subscribe to topic: %.*s\n",
            (int) topic.len,
            topic.data
        );
        exit(-1);
    }

    printf(
        "Successfully subscribed to topic: %.*s\n", (int) topic.len, topic.data
    );

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }

    // To stop subscribing, close the subscription handle.
    ggipc_close_subscription(handle);
}
```

### AWS IoT Core MQTT パブリッシャーの例 (C\$1\$1、コンポーネント SDK)
<a name="ipc-iot-core-mqtt-example-publisher-cpp-component-sdk"></a>

以下の recipe の例は、コンポーネントをすべてのトピックに発行できるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.IoTCorePublisherCpp",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that publishes MQTT messages to IoT Core.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.mqttproxy": {
          "com.example.IoTCorePublisherCpp:mqttproxy:1": {
            "policyDescription": "Allows access to publish to all topics.",
            "operations": ["aws.greengrass#PublishToIoTCore"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/sample_cpp_publish_to_iot_core"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.IoTCorePublisherCpp/1.0.0/sample_cpp_publish_to_iot_core",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の C\$1\$1 アプリケーションの例は、 AWS IoT Core MQTT IPC サービスを使用してメッセージを発行する方法を示しています AWS IoT Core。

```
#include <gg/ipc/client.hpp>
#include <iostream>

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    std::string_view message = "Hello, World";
    std::string_view topic = "my/topic";
    uint8_t qos = 1;

    error = client.publish_to_iot_core(topic, message, qos);
    if (error) {
        std::cerr << "Failed to publish to topic: " << topic << "\n";
        exit(-1);
    }

    std::cout << "Successfully published to topic: " << topic << "\n";
}
```

### AWS IoT Core MQTT サブスクライバーの例 (C\$1\$1、コンポーネント SDK)
<a name="ipc-iot-core-mqtt-example-subscriber-cpp-component-sdk"></a>

以下の recipe の例は、コンポーネントをすべてのトピックをサブスクライブできるようにします。

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.IoTCoreSubscriberCpp",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that subscribes to MQTT messages from IoT Core.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "accessControl": {
        "aws.greengrass.ipc.mqttproxy": {
          "com.example.IoTCoreSubscriberCpp:mqttproxy:1": {
            "policyDescription": "Allows access to subscribe to all topics.",
            "operations": ["aws.greengrass#SubscribeToIoTCore"],
            "resources": ["*"]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "runtime": "*"
      },
      "Lifecycle": {
        "run": "{artifacts:path}/sample_cpp_subscribe_to_iot_core"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.IoTCoreSubscriberCpp/1.0.0/sample_cpp_subscribe_to_iot_core",
          "Permission": {
            "Execute": "OWNER"
          }
        }
      ]
    }
  ]
}
```

次の C\$1\$1 アプリケーションの例は、 AWS IoT Core MQTT IPC サービスを使用してメッセージをサブスクライブする方法を示しています AWS IoT Core。

```
#include <gg/ipc/client.hpp>
#include <unistd.h>
#include <iostream>

class ResponseHandler : public gg::ipc::IotTopicCallback {
    void operator()(
        std::string_view topic,
        gg::Buffer payload,
        gg::ipc::Subscription &handle
    ) override {
        (void) handle;
        std::cout << "Received new message on topic " << topic << ": "
                  << payload << "\n";
    }
};

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    std::string_view topic = "my/topic";
    uint8_t qos = 1;

    static ResponseHandler handler;
    error = client.subscribe_to_iot_core(topic, qos, handler);
    if (error) {
        std::cerr << "Failed to subscribe to topic: " << topic << "\n";
        exit(-1);
    }

    std::cout << "Successfully subscribed to topic: " << topic << "\n";

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }
}
```

# コンポーネントライフサイクルの操作
<a name="ipc-component-lifecycle"></a>

コンポーネントライフサイクルの IPC サービスを使用して、次を行います。
+ コアデバイスのコンポーネント状態の更新。
+ コンポーネント状態の更新のサブスクライブ。
+ デプロイ中に nucleus によりコンポーネントが停止され、更新が適用されることの防止。
+ コンポーネントのプロセスの一時停止と再開。

**Topics**
+ [最小 SDK バージョン](#ipc-component-lifecycle-sdk-versions)
+ [Authorization](#ipc-component-lifecycle-authorization)
+ [UpdateState](#ipc-operation-updatestate)
+ [SubscribeToComponentUpdates](#ipc-operation-subscribetocomponentupdates)
+ [DeferComponentUpdate](#ipc-operation-defercomponentupdate)
+ [PauseComponent](#ipc-operation-pausecomponent)
+ [ResumeComponent](#ipc-operation-resumecomponent)

## 最小 SDK バージョン
<a name="ipc-component-lifecycle-sdk-versions"></a>

次の表に、コンポーネントのライフサイクルを操作するために使用 AWS IoT Device SDK する必要がある の最小バージョンを示します。


| SDK | 最小バージョン | 
| --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## Authorization
<a name="ipc-component-lifecycle-authorization"></a>

カスタムコンポーネントから他のコンポーネントを一時停止または再開するには、コンポーネントが他のコンポーネントを管理できるようにする承認ポリシーを定義する必要があります。承認ポリシーの定義については、「[コンポーネントに IPC オペレーションの実行を許可する](interprocess-communication.md#ipc-authorization-policies)」を参照してください。

コンポーネントライフサイクル管理の承認ポリシーには、次のプロパティがあります。

**IPC サービス識別子:** `aws.greengrass.ipc.lifecycle`


| 運用 | 説明 | リソース | 
| --- | --- | --- | 
|  `aws.greengrass#PauseComponent`  |  コンポーネントが、指定したコンポーネントを一時停止できるようにします。  |  すべてのコンポーネントへのアクセスを許可するコンポーネント名または `*`。  | 
|  `aws.greengrass#ResumeComponent`  |  コンポーネントが、指定したコンポーネントを再開できるようにします。  |  すべてのコンポーネントへのアクセスを許可するコンポーネント名または `*`。  | 
|  `*`  |  コンポーネントが、指定したコンポーネントを一時停止および再開できるようにします。  |  すべてのコンポーネントへのアクセスを許可するコンポーネント名または `*`。  | 

### 承認ポリシーの例
<a name="ipc-component-lifecycle-authorization-policy-examples"></a>

次の承認ポリシーの例を参照して、コンポーネントの承認ポリシーの設定に役立てることができます。

**Example 承認ポリシーの例**  
次の承認ポリシーの例では、コンポーネントが、すべてのコンポーネントを一時停止および再開できるようにします。  

```
{
  "accessControl": {
    "aws.greengrass.ipc.lifecycle": {
      "com.example.MyLocalLifecycleComponent:lifecycle:1": {
        "policyDescription": "Allows access to pause/resume all components.",
        "operations": [
          "aws.greengrass#PauseComponent",
          "aws.greengrass#ResumeComponent"
        ],
        "resources": [
          "*"
        ]
      }
    }
  }
}
```

## UpdateState
<a name="ipc-operation-updatestate"></a>

コアデバイスのコンポーネントの状態を更新します。

### リクエスト
<a name="ipc-operation-updatestate-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`state`  
設定する状態。この列挙型 (`LifecycleState`) には以下の値があります。  
+ `RUNNING`
+ `ERRORED`

### 応答
<a name="ipc-operation-updatestate-response"></a>

このオペレーションはレスポンスで一切の情報を提供しません。

### 例
<a name="ipc-operation-updatestate-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Rust ]

**Example 例: 更新状態**  

```
use gg_sdk::{ComponentState, Sdk};

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    // Update component state to RUNNING
    sdk.update_state(ComponentState::Running)
        .expect("Failed to update component state");

    println!("Successfully updated component state to RUNNING.");
}
```

------
#### [ C ]

**Example 例: 更新状態**  

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/sdk.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    // Update component state to RUNNING
    err = ggipc_update_state(GG_COMPONENT_STATE_RUNNING);
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to update component state.\n");
        exit(-1);
    }

    printf("Successfully updated component state to RUNNING.\n");
}
```

------
#### [ C\$1\$1 (Component SDK) ]

**Example 例: 更新状態**  

```
#include <gg/ipc/client.hpp>
#include <iostream>

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    // Update component state to RUNNING
    error = client.update_component_state(GG_COMPONENT_STATE_RUNNING);
    if (error) {
        std::cerr << "Failed to update component state.\n";
        exit(-1);
    }

    std::cout << "Successfully updated component state to RUNNING.\n";
}
```

------

## SubscribeToComponentUpdates
<a name="ipc-operation-subscribetocomponentupdates"></a>

 AWS IoT Greengrass Core ソフトウェアがコンポーネントを更新する前に通知を受信するには、サブスクライブします。通知では、更新の一部として nucleus を再起動するかどうかを指定します。

nucleus は、デプロイのコンポーネント更新ポリシーがコンポーネントに通知するように指定されている場合のみ、更新通知を送信します。デフォルトの動作では、コンポーネントに通知を行います。詳細については、[デプロイの作成](create-deployments.md) および [CreateDeployment](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_CreateDeployment.html) オペレーションを呼び出すときに提供できる [DeploymentComponentUpdatePolicy](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_DeploymentComponentUpdatePolicy.html) オブジェクトを参照してください。

**重要**  
更新前にローカルデプロイがコンポーネントに通知を行うことばありません。

<a name="ipc-subscribe-operation-note"></a>このオペレーションはサブスクリプションオペレーションで、イベントメッセージのストリームをサブスクライブするというものです。このオペレーションを使用するには、イベントメッセージ、エラー、およびストリームクロージャを処理する関数を使用して、ストリームレスポンスハンドラーを定義します。(詳細については、[IPC イベントストリームへのサブスクライブ](interprocess-communication.md#ipc-subscribe-operations) を参照してください)。

**イベントメッセージの種類:** `ComponentUpdatePolicyEvents`

**ヒント**  
チュートリアルに従って、条件付きでコンポーネントの更新を延期するコンポーネントを開発する方法を説明します。(詳細については、[チュートリアル: コンポーネントの更新を延期する Greengrass コンポーネントを開発する](defer-component-updates-tutorial.md) を参照してください)。

### リクエスト
<a name="ipc-operation-subscribetocomponentupdates-request"></a>

このオペレーションのリクエストはパラメータを持ちません。

### 応答
<a name="ipc-operation-subscribetocomponentupdates-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`messages`  
通知メッセージのストリーム。このオブジェクト (`ComponentUpdatePolicyEvents`) には、次の情報が含まれます。    
`preUpdateEvent` (Python: `pre_update_event`)  
(オプション) nucleus がコンポーネントの更新を希望することを示すイベント。[DeferComponentUpdate](#ipc-operation-defercomponentupdate) オペレーションで応答して更新を承認するか、コンポーネントを再起動する準備が整うまで延期するかを選択できます。このオブジェクト (`PreComponentUpdateEvent`) には、次の情報が含まれます。    
`deploymentId` (Python: `deployment_id`)  
コンポーネントを更新する AWS IoT Greengrass デプロイの ID。  
`isGgcRestarting` (Python: `is_ggc_restarting`)  
更新を適用するために nucleus を再起動する必要があるかどうか。  
`postUpdateEvent` (Python: `post_update_event`)  
(オプション) nucleus がコンポーネントを更新したことを示すイベント。このオブジェクト (`PostComponentUpdateEvent`) には、次の情報が含まれます。    
`deploymentId` (Python: `deployment_id`)  
コンポーネントを更新した AWS IoT Greengrass デプロイの ID。  
この機能を使用するには、Greengrass nucleus コンポーネントの v2.7.0 以降が必要です。

## DeferComponentUpdate
<a name="ipc-operation-defercomponentupdate"></a>

[SubscribeToComponentUpdates](#ipc-operation-subscribetocomponentupdates) で検出したコンポーネントの更新を承認または延期します。コンポーネントが更新を進める準備ができているかどうか、nucleus が再度チェックするまで待機する時間を指定します。このオペレーションを使用して、コンポーネントが更新の準備ができていることを nucleus に通知することもできます。

コンポーネントがコンポーネント更新通知に応答しない場合、nucleus はデプロイのコンポーネント更新ポリシーで指定した時間だけ待機します。これがタイムアウトした後、nucleus はデプロイを続行します。デフォルトのコンポーネント更新のタイムアウトは 60 秒です。詳細については、[デプロイの作成](create-deployments.md) および [CreateDeployment](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_CreateDeployment.html) オペレーションを呼び出すときに提供できる [DeploymentComponentUpdatePolicy](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_DeploymentComponentUpdatePolicy.html) オブジェクトを参照してください。

**ヒント**  
チュートリアルに従って、条件付きでコンポーネントの更新を延期するコンポーネントを開発する方法を説明します。(詳細については、[チュートリアル: コンポーネントの更新を延期する Greengrass コンポーネントを開発する](defer-component-updates-tutorial.md) を参照してください)。

### リクエスト
<a name="ipc-operation-defercomponentupdate-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`deploymentId` (Python: `deployment_id`)  
延期する AWS IoT Greengrass デプロイの ID。

`message`  
(オプション) 更新を延期するコンポーネントの名前。  
デフォルトでは、リクエストを実行するコンポーネントの名前になっています。

`recheckAfterMs` (Python: `recheck_after_ms`)  
更新を延期する時間 (ミリ秒)。nucleus はこの時間だけ待機してから、[SubscribeToComponentUpdates](#ipc-operation-subscribetocomponentupdates) で発見できる別の `PreComponentUpdateEvent` を送信します。  
`0` を指定すると更新が承認されます。これにより、コンポーネントが更新の準備ができていることが nucleus に通知されます。  
デフォルトは 0 ミリ秒で、これは更新を承認することを意味します。

### 応答
<a name="ipc-operation-defercomponentupdate-response"></a>

このオペレーションはレスポンスで一切の情報を提供しません。

## PauseComponent
<a name="ipc-operation-pausecomponent"></a>

この機能は、[Greengrass nucleus コンポーネントの](greengrass-nucleus-component.md) v2.4.0 以降で使用できます。現在、この機能は Windows AWS IoT Greengrass コアデバイスでサポートされていません。

コアデバイスのコンポーネントのプロセスを一時停止します。コンポーネントを再開するには、[ResumeComponent](#ipc-operation-resumecomponent) オペレーションを使用します。

一時停止できるのはジェネリックコンポーネントのみです。他の種類のコンポーネントを一時停止しようとすると、オペレーションは `InvalidRequestError` をスローします。

**注記**  
この操作は、Docker コンテナなどのコンテナ化されたプロセスは一時停止できません。Docker コンテナの一時停止および再開を行うには、[docker pause](https://docs.docker.com/engine/reference/commandline/pause/) および [docker unpause](https://docs.docker.com/engine/reference/commandline/unpause/) コマンドを使用できます。

このオペレーションは、コンポーネントの依存関係や、一時停止するコンポーネントに依存するコンポーネントに対しては、一時停止を行いません。別のコンポーネントの依存関係であるコンポーネントを一時停止するときは、この動作を検討してください。依存するコンポーネントは、依存関係が一時停止されたときに問題が発生する可能性があるためです。

デプロイ経由などで一時停止したコンポーネントを再起動またはシャットダウンすると、Greengrass nucleus はコンポーネントを再開し、シャットダウンライフサイクルを実行します。コンポーネントの再起動についての詳細は、「[RestartComponent](ipc-local-deployments-components.md#ipc-operation-restartcomponent)」を参照してください。

**重要**  
このオペレーションを使用するには、このオペレーションを使用する権限を付与する承認ポリシーを定義する必要があります。(詳細については、[Authorization](#ipc-component-lifecycle-authorization) を参照してください)。

### 最小 SDK バージョン
<a name="ipc-operation-pausecomponent-sdk-versions"></a>

次の表 AWS IoT Device SDK に、コンポーネントの一時停止と再開に使用する必要がある の最小バージョンを示します。


| SDK | 最小バージョン | 
| --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.4.3  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.6.2  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.13.1  | 
|  [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

### リクエスト
<a name="ipc-operation-defercomponentupdate-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`componentName` (Python: `component_name`)  
一時停止するコンポーネントの名前。ジェネリックコンポーネントである必要があります。(詳細については、[コンポーネントタイプ](develop-greengrass-components.md#component-types) を参照してください)。

### 応答
<a name="ipc-operation-defercomponentupdate-response"></a>

このオペレーションはレスポンスで一切の情報を提供しません。

## ResumeComponent
<a name="ipc-operation-resumecomponent"></a>

この機能は、[Greengrass nucleus コンポーネントの](greengrass-nucleus-component.md) v2.4.0 以降で使用できます。現在、この機能は Windows AWS IoT Greengrass コアデバイスでサポートされていません。

コアデバイスのコンポーネントのプロセスを再開します。コンポーネントを一時停止するには、[PauseComponent](#ipc-operation-pausecomponent) オペレーションを使用します。

再開できるのは一時停止しているコンポーネントのみです。一時停止していないコンポーネントを再開しようとすると、このオペレーションは `InvalidRequestError` をスローします。

**重要**  
このオペレーションを使用するには、そうするための権限を付与する承認ポリシーを定義する必要があります。(詳細については、[Authorization](#ipc-component-lifecycle-authorization) を参照してください)。

### 最小 SDK バージョン
<a name="ipc-operation-resumecomponent-sdk-versions"></a>

次の表 AWS IoT Device SDK に、コンポーネントの一時停止と再開に使用する必要がある の最小バージョンを示します。


| SDK | 最小バージョン | 
| --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.4.3  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.6.2  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.13.1  | 
|  [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

### リクエスト
<a name="ipc-operation-defercomponentupdate-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`componentName` (Python: `component_name`)  
再開するコンポーネントの名前。

### 応答
<a name="ipc-operation-defercomponentupdate-response"></a>

このオペレーションはレスポンスで一切の情報を提供しません。

# コンポーネント設定とやり取り
<a name="ipc-component-configuration"></a>

コンポーネント設定 IPC サービスでは以下のことが行えます。
+ コンポーネント設定パラメータを取得および設定します。
+ コンポーネント設定の更新をサブスクライブします。
+ コンポーネント設定の更新を、nucleus が適用する前に検証します。

**Topics**
+ [最小 SDK バージョン](#ipc-component-configuration-sdk-versions)
+ [GetConfiguration](#ipc-operation-getconfiguration)
+ [UpdateConfiguration](#ipc-operation-updateconfiguration)
+ [SubscribeToConfigurationUpdate](#ipc-operation-subscribetoconfigurationupdate)
+ [SubscribeToValidateConfigurationUpdates](#ipc-operation-subscribetovalidateconfigurationupdates)
+ [SendConfigurationValidityReport](#ipc-operation-sendconfigurationvalidityreport)

## 最小 SDK バージョン
<a name="ipc-component-configuration-sdk-versions"></a>

次の表に、コンポーネント設定を操作するために使用 AWS IoT Device SDK する必要がある の最小バージョンを示します。


| SDK | 最小バージョン | 
| --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## GetConfiguration
<a name="ipc-operation-getconfiguration"></a>

コアデバイス上のコンポーネントの設定値を取得します。設定値を取得するためのキーパスを指定します。

### リクエスト
<a name="ipc-operation-getconfiguration-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`componentName` (Python: `component_name`)  <a name="ipc-configuration-request-component-name"></a>
(オプション) コンポーネントの名前。  
デフォルトでは、リクエストを実行するコンポーネントの名前になっています。

`keyPath` (Python: `key_path`)  
設定値へのキーパス。各エントリが設定オブジェクトの単一レベルのキーとなるリストを指定します。たとえば、以下の設定で `port` の値を取得するには、`["mqtt", "port"]` を指定します。  

```
{
  "mqtt": {
    "port": 443
  }
}
```
コンポーネントの完全な設定を取得するには、空のリストを指定します。

### 応答
<a name="ipc-operation-getconfiguration-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`componentName` (Python: `component_name`)  <a name="ipc-configuration-response-component-name"></a>
コンポーネントの名前。

`value`  
オブジェクトとしてリクエストされた設定。

### 例
<a name="ipc-operation-getconfiguration-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Rust ]

**Example 例: 設定を取得する**  

```
use core::mem::MaybeUninit;
use gg_sdk::{Sdk, UnpackedObject};

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    // Get a configuration value at key path ["mqtt", "port"]
    let mut buf = [MaybeUninit::uninit(); 1024];

    let value = sdk
        .get_config(&["mqtt", "port"], None, &mut buf)
        .expect("Failed to get configuration");

    if let UnpackedObject::I64(port) = value.unpack() {
        println!("Configuration value: {port}");
    }
}
```

------
#### [ C ]

**Example 例: 設定を取得する**  

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/object.h>
#include <gg/sdk.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    // Get a configuration value at key path ["mqtt", "port"]
    uint8_t response_mem[1024];
    GgObject value;

    err = ggipc_get_config(
        GG_BUF_LIST(GG_STR("mqtt"), GG_STR("port")),
        NULL, // component_name (NULL = current component)
        GG_BUF(response_mem),
        &value
    );
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to get configuration.\n");
        exit(-1);
    }

    if (gg_obj_type(value) == GG_TYPE_I64) {
        printf("Configuration value: %" PRId64 "\n", gg_obj_into_i64(value));
    } else if (gg_obj_type(value) == GG_TYPE_BUF) {
        GgBuffer buf = gg_obj_into_buf(value);
        printf("Configuration value: %.*s\n", (int) buf.len, buf.data);
    } else {
        printf("Configuration value is of unexpected type.\n");
    }
}
```

------
#### [ C\$1\$1 (Component SDK) ]

**Example 例: 設定を取得する**  

```
#include <gg/ipc/client.hpp>
#include <iostream>

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    // Get a configuration value at key path ["mqtt", "port"]
    std::array key_path = { gg::Buffer { "mqtt" }, gg::Buffer { "port" } };
    int64_t value = 0;

    error = client.get_config(key_path, std::nullopt, value);
    if (error) {
        std::cerr << "Failed to get configuration.\n";
        exit(-1);
    }

    std::cout << "Configuration value: " << value << "\n";
}
```

------

## UpdateConfiguration
<a name="ipc-operation-updateconfiguration"></a>

コアデバイス上のこのコンポーネントの設定値を更新します。

### リクエスト
<a name="ipc-operation-updateconfiguration-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`keyPath` (Python: `key_path`)  
(オプション) 更新するコンテナノード (オブジェクト) へのキーパス。各エントリが設定オブジェクトの単一レベルのキーとなるリストを指定します。たとえば、キーパス `["mqtt"]` とマージ値 `{ "port": 443 }` を指定して、以下の設定に `port` の値を設定します。  

```
{
  "mqtt": {
    "port": 443
  }
}
```
キーパスは、設定内のコンテナノード (オブジェクト) を指定する必要があります。コンポーネントの設定にノードが存在しない場合、このオペレーションによってノードが作成され、`valueToMerge` のオブジェクトにその値が設定されます。  
設定オブジェクトのルートに対するデフォルトです。

`timestamp`  
現在の UNIX エポック時間 (ミリ秒)。このオペレーションにおけるキーの同時更新の解決には、このタイムスタンプが使用されます。コンポーネント設定のキーのタイムスタンプがリクエストのタイムスタンプよりも大きい場合、リクエストは失敗します。

`valueToMerge` (Python: `value_to_merge`)  
`keyPath` で指定した場所でマージする設定オブジェクト。(詳細については、[コンポーネント設定の更新](update-component-configurations.md) を参照してください)。

### 応答
<a name="ipc-operation-updateconfiguration-response"></a>

このオペレーションはレスポンスで一切の情報を提供しません。

### 例
<a name="ipc-operation-updateconfiguration-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Rust ]

**Example 例: 設定の更新**  

```
use gg_sdk::Sdk;

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    // Update configuration value at key path ["mqtt", "port"] to 443
    sdk.update_config(&["mqtt", "port"], None, 443)
        .expect("Failed to update configuration");

    println!("Successfully updated configuration.");
}
```

------
#### [ C ]

**Example 例: 設定の更新**  

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/object.h>
#include <gg/sdk.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    // Update configuration value at key path ["mqtt", "port"] to 443
    err = ggipc_update_config(
        GG_BUF_LIST(GG_STR("mqtt"), GG_STR("port")),
        NULL, // timestamp (NULL = current time)
        gg_obj_i64(443)
    );
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to update configuration.\n");
        exit(-1);
    }

    printf("Successfully updated configuration.\n");
}
```

------
#### [ C\$1\$1 (Component SDK) ]

**Example 例: 設定の更新**  

```
#include <gg/ipc/client.hpp>
#include <iostream>

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    // Update configuration value at key path ["mqtt", "port"] to 443
    std::array key_path = { gg::Buffer { "mqtt" }, gg::Buffer { "port" } };

    error = client.update_config(key_path, 443);
    if (error) {
        std::cerr << "Failed to update configuration.\n";
        exit(-1);
    }

    std::cout << "Successfully updated configuration.\n";
}
```

------

## SubscribeToConfigurationUpdate
<a name="ipc-operation-subscribetoconfigurationupdate"></a>

サブスクライブして、コンポーネントの設定更新時に通知を受け取るようにします。キーをサブスクライブすると、そのキーの子が更新されたとき通知を受けます。

<a name="ipc-subscribe-operation-note"></a>このオペレーションはサブスクリプションオペレーションで、イベントメッセージのストリームをサブスクライブするというものです。このオペレーションを使用するには、イベントメッセージ、エラー、およびストリームクロージャを処理する関数を使用して、ストリームレスポンスハンドラーを定義します。(詳細については、[IPC イベントストリームへのサブスクライブ](interprocess-communication.md#ipc-subscribe-operations) を参照してください)。

**イベントメッセージの種類:** `ConfigurationUpdateEvents`

### リクエスト
<a name="ipc-operation-subscribetoconfigurationupdate-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`componentName` (Python: `component_name`)  <a name="ipc-configuration-request-component-name"></a>
(オプション) コンポーネントの名前。  
デフォルトでは、リクエストを実行するコンポーネントの名前になっています。

`keyPath` (Python: `key_path`)  
サブスクライブする設定値のキーパス。各エントリが設定オブジェクトの単一レベルのキーとなるリストを指定します。たとえば、以下の設定で `port` の値を取得するには、`["mqtt", "port"]` を指定します。  

```
{
  "mqtt": {
    "port": 443
  }
}
```
コンポーネント設定のすべての値の更新をサブスクライブするには、空のリストを指定します。

### 応答
<a name="ipc-operation-subscribetoconfigurationupdate-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`messages`  
通知メッセージのストリーム。このオブジェクト (`ConfigurationUpdateEvents`) には、次の情報が含まれます。    
`configurationUpdateEvent` (Python: `configuration_update_event`)  
設定更新イベント。このオブジェクト (`ConfigurationUpdateEvent`) には、次の情報が含まれます。    
`componentName` (Python: `component_name`)  <a name="ipc-configuration-response-component-name"></a>
コンポーネントの名前。  
`keyPath` (Python: `key_path`)  
更新された設定値へのキーパス。

### 例
<a name="ipc-operation-subscribetoconfigurationupdate-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Rust ]

**Example 例: 設定更新をサブスクライブする**  

```
use gg_sdk::Sdk;
use std::{thread, time::Duration};

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    // Subscribe to configuration updates for key path ["mqtt"]
    let callback = |component_name: &str, key_path: &[&str]| {
        println!(
            "Received configuration update for component: {component_name}"
        );
        println!("Key path: {key_path:?}");
    };

    let _sub = sdk
        .subscribe_to_configuration_update(None, &["mqtt"], &callback)
        .expect("Failed to subscribe to configuration updates");

    println!("Successfully subscribed to configuration updates.");

    // Keep the main thread alive, or the process will exit.
    loop {
        thread::sleep(Duration::from_secs(10));
    }
}
```

------
#### [ C ]

**Example 例: 設定更新をサブスクライブする**  

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/object.h>
#include <gg/sdk.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static void on_subscription_response(
    void *ctx,
    GgBuffer component_name,
    GgList key_path,
    GgIpcSubscriptionHandle handle
) {
    (void) ctx;
    (void) handle;

    printf(
        "Received configuration update for component: %.*s\n",
        (int) component_name.len,
        component_name.data
    );

    printf("Key path: [");
    for (size_t i = 0; i < key_path.len; i++) {
        if (i > 0) {
            printf(", ");
        }
        GgObject *obj = &key_path.items[i];
        if (gg_obj_type(*obj) == GG_TYPE_BUF) {
            GgBuffer key = gg_obj_into_buf(*obj);
            printf("\"%.*s\"", (int) key.len, key.data);
        }
    }
    printf("]\n");
}

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    // Subscribe to configuration updates for key path ["mqtt"]
    GgIpcSubscriptionHandle handle;
    err = ggipc_subscribe_to_configuration_update(
        NULL, // component_name (NULL = current component)
        GG_BUF_LIST(GG_STR("mqtt")),
        on_subscription_response,
        NULL,
        &handle
    );
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to subscribe to configuration updates.\n");
        exit(-1);
    }

    printf("Successfully subscribed to configuration updates.\n");

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }

    // To stop subscribing, close the stream.
    ggipc_close_subscription(handle);
}
```

------
#### [ C\$1\$1 (Component SDK) ]

**Example 例: 設定更新をサブスクライブする**  

```
#include <gg/ipc/client.hpp>
#include <unistd.h>
#include <iostream>

class ResponseHandler : public gg::ipc::ConfigurationUpdateCallback {
    void operator()(
        std::string_view component_name,
        gg::List key_path,
        gg::ipc::Subscription &handle
    ) override {
        (void) handle;
        std::cout << "Received configuration update for component: "
                  << component_name << "\n";
        std::cout << "Key path: [";
        for (size_t i = 0; i < key_path.size(); i++) {
            if (i > 0) {
                std::cout << ", ";
            }
            std::cout << "\"" << get<gg::Buffer>(key_path[i]) << "\"";
        }
        std::cout << "]\n";
    }
};

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    // Subscribe to configuration updates for key path ["mqtt"]
    std::array key_path = { gg::Buffer { "mqtt" } };

    static ResponseHandler handler;
    error = client.subscribe_to_configuration_update(
        key_path, std::nullopt, handler
    );
    if (error) {
        std::cerr << "Failed to subscribe to configuration updates.\n";
        exit(-1);
    }

    std::cout << "Successfully subscribed to configuration updates.\n";

    // Keep the main thread alive, or the process will exit.
    while (1) {
        sleep(10);
    }
}
```

------

## SubscribeToValidateConfigurationUpdates
<a name="ipc-operation-subscribetovalidateconfigurationupdates"></a>

サブスクライブして、このコンポーネントの設定更新より前に通知を受け取るようにします。これにより、コンポーネントは各自の設定に対し更新を検証できます。[SendConfigurationValidityReport](#ipc-operation-sendconfigurationvalidityreport) オペレーションを使用して、設定が有効かどうかを nucleus に伝えます。

**重要**  
ローカルデプロイは、コンポーネントに更新を通知しません。

<a name="ipc-subscribe-operation-note"></a>このオペレーションはサブスクリプションオペレーションで、イベントメッセージのストリームをサブスクライブするというものです。このオペレーションを使用するには、イベントメッセージ、エラー、およびストリームクロージャを処理する関数を使用して、ストリームレスポンスハンドラーを定義します。(詳細については、[IPC イベントストリームへのサブスクライブ](interprocess-communication.md#ipc-subscribe-operations) を参照してください)。

**イベントメッセージの種類:** `ValidateConfigurationUpdateEvents`

### リクエスト
<a name="ipc-operation-subscribetovalidateconfigurationupdates-request"></a>

このオペレーションのリクエストはパラメータを持ちません。

### 応答
<a name="ipc-operation-subscribetovalidateconfigurationupdates-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`messages`  
通知メッセージのストリーム。このオブジェクト (`ValidateConfigurationUpdateEvents`) には、次の情報が含まれます。    
`validateConfigurationUpdateEvent` (Python: `validate_configuration_update_event`)  
設定更新イベント。このオブジェクト (`ValidateConfigurationUpdateEvent`) には、次の情報が含まれます。    
`deploymentId` (Python: `deployment_id`)  
コンポーネントを更新する AWS IoT Greengrass デプロイの ID。  
`configuration`  
新しい設定を含むオブジェクト。

## SendConfigurationValidityReport
<a name="ipc-operation-sendconfigurationvalidityreport"></a>

このコンポーネントの設定更新が有効かどうかを nucleus に伝えます。新しい設定が有効でないことを nucleus に伝えると、デプロイは失敗します。[SubscribeToValidateConfigurationUpdates](#ipc-operation-subscribetovalidateconfigurationupdates) オペレーションを使用して、設定更新の検証をサブスクライブします。

コンポーネントが設定更新の検証の通知に応答しない場合、nucleus はデプロイの設定検証ポリシーで指定した時間だけ待機します。これがタイムアウトした後、nucleus はデプロイを続行します。デフォルトのコンポーネント検証のタイムアウトは 20 秒です。詳細については、[デプロイの作成](create-deployments.md) および [CreateDeployment](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_CreateDeployment.html) オペレーションを呼び出すときに提供できる [DeploymentConfigurationValidationPolicy](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_DeploymentConfigurationValidationPolicy.html) オブジェクトを参照してください。

### リクエスト
<a name="ipc-operation-sendconfigurationvalidityreport-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`configurationValidityReport` (Python: `configuration_validity_report`)  
設定更新が有効かどうかを nucleus に伝えるレポート。このオブジェクト (`ConfigurationValidityReport`) には、次の情報が含まれます。    
`status`  
有効性のステータス。この列挙型 (`ConfigurationValidityStatus`) には以下の値があります。  
+ `ACCEPTED` - 設定が有効で、nucleus はこのコンポーネントに適用できます。
+ `REJECTED` - 設定が有効ではなく、デプロイが失敗します。  
`deploymentId` (Python: `deployment_id`)  
設定の更新をリクエストした AWS IoT Greengrass デプロイの ID。  
`message`  
(オプション) 設定が有効でないことの理由を報告するメッセージ。

### 応答
<a name="ipc-operation-sendconfigurationvalidityreport-response"></a>

このオペレーションはレスポンスで一切の情報を提供しません。

# シークレット値を取得する
<a name="ipc-secret-manager"></a>

シークレットマネージャー IPC サービスを使用して、コアデバイスのシークレットからシークレット値を取得します。[シークレットマネージャーコンポーネント](secret-manager-component.md)を使用して、暗号化されたシークレットをコアデバイスにデプロイします。次に、IPC オペレーションを使用してシークレットを復号化し、カスタムコンポーネントでその値を使用できます。

**Topics**
+ [最小 SDK バージョン](#ipc-secret-manager-sdk-versions)
+ [Authorization](#ipc-secret-manager-authorization)
+ [GetSecretValue](#ipc-operation-getsecretvalue)
+ [例](#ipc-secret-manager-examples)

## 最小 SDK バージョン
<a name="ipc-secret-manager-sdk-versions"></a>

次の表 AWS IoT Device SDK に、コアデバイスのシークレットからシークレット値を取得するために使用する必要がある の最小バージョンを示します。


| SDK | 最小バージョン | 
| --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## Authorization
<a name="ipc-secret-manager-authorization"></a>

カスタムコンポーネントでシークレットマネージャーを使用するには、コアデバイスに保存するシークレットの値をコンポーネントが取得できるようにする承認ポリシーを定義する必要があります。承認ポリシーの定義については、「[コンポーネントに IPC オペレーションの実行を許可する](interprocess-communication.md#ipc-authorization-policies)」を参照してください。

シークレットマネージャーの承認ポリシーには以下のプロパティがあります。

**IPC サービス識別子:** `aws.greengrass.SecretManager`


| 運用 | 説明 | リソース | 
| --- | --- | --- | 
|  `aws.greengrass#GetSecretValue`、または `*`  |  コンポーネントがコアデバイスで暗号化されたシークレットの値を取得できるようにします。  |  Secrets Manager のシークレット ARN、または `*` ですべてのシークレットへのアクセスを許可します。  | 

### 承認ポリシーの例
<a name="ipc-secret-manager-authorization-policy-examples"></a>

次の承認ポリシーの例を参照して、コンポーネントの承認ポリシーの設定に役立てることができます。

**Example 承認ポリシーの例**  
以下の承認ポリシーの例は、コンポーネントがコアデバイスのすべてのシークレット値を取得できるようにします。  
実稼働環境では、コンポーネントが使用するシークレットのみ取得するように、承認ポリシーの範囲を小さくすることをお勧めします。コンポーネントをデプロイするとき、`*` ワイルドカードをシークレット ARN のリストに変更できます。

```
{
  "accessControl": {
    "aws.greengrass.SecretManager": {
      "com.example.MySecretComponent:secrets:1": {
        "policyDescription": "Allows access to a secret.",
        "operations": [
          "aws.greengrass#GetSecretValue"
        ],
        "resources": [
          "*"
        ]
      }
    }
  }
}
```

## GetSecretValue
<a name="ipc-operation-getsecretvalue"></a>

コアデバイスに保存するシークレットの値を取得します。

このオペレーションは Secrets Manager のオペレーションと似ていますが、 AWS クラウドのシークレット値を取得するために使用できます。詳細については、「*AWS Secrets Manager API リファレンス*」の「[GetSecretValue](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html)」を参照してください。

### リクエスト
<a name="ipc-operation-getsecretvalue-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`refresh` (Python: `refresh`)  
(オプション): リクエストされたシークレットを AWS Secrets Manager サービスからの最新の値と同期するかどうか。  
true に設定すると、シークレットマネージャーは指定されたシークレットラベルの最新の値を AWS Secrets Manager サービスにリクエストし、その値をレスポンスとして返します。それ以外の場合、ローカルに保存されたシークレット値が返されます。  
 このパラメータは、リクエストの `versionId` パラメータと連動しません。このパラメータは、Nucleus 2.13.0 以降と併用すると機能します。

`secretId` (Python: `secret_id`)  
取得するシークレットの名前。シークレットの Amazon リソースネーム (ARN) またはフレンドリ名を指定します。

`versionId` (Python: `version_id`)  
(オプション) 取得するバージョンの ID。  
`versionId` または `versionStage` のどちらかを指定できます。  
`versionId` または `versionStage` を指定しない場合、このオペレーションはデフォルトで `AWSCURRENT` ラベルのバージョンになります。

`versionStage` (Python: `version_stage`)  
(オプション) 取得するバージョンのステージングラベル。  
`versionId` または `versionStage` のどちらかを指定できます。  
`versionId` または `versionStage` を指定しない場合、このオペレーションはデフォルトで `AWSCURRENT` ラベルのバージョンになります。

### 応答
<a name="ipc-operation-getsecretvalue-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`secretId` (Python: `secret_id`)  
シークレットの ID。

`versionId` (Python: `version_id`)  
このバージョンのシークレットの ID。

`versionStage` (Python: `version_stage`)  
このシークレットのバージョンには、ステージングラベルのリストがアタッチされています。

`secretValue` (Python: `secret_value`)  
このバージョンのシークレットの値。このオブジェクト (`SecretValue`) には、次の情報が含まれます。    
`secretString` (Python: `secret_string`)  
Secrets Manager に文字列として提供した、保護されたシークレット情報の復号化された部分。  
`secretBinary` (Python: `secret_binary`)  
(オプション) Secrets Manager にバイト配列のバイナリデータとして提供した、保護されたシークレット情報の復号化された部分。このプロパティには、base64 エンコードされた文字列としてのバイナリデータが含まれています。  
Secrets Manager コンソールでシークレットを作成した場合、このプロパティは使用されません。

### 例
<a name="ipc-operation-getsecretvalue-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Java (IPC client V1) ]

**Example 例: シークレット値の取得**  
この例では、 `IPCUtils` クラスを使用して AWS IoT Greengrass Core IPC サービスへの接続を作成します。詳細については、「[AWS IoT Greengrass Core IPC サービスに接続する](interprocess-communication.md#ipc-service-connect)」を参照してください。

```
package com.aws.greengrass.docs.samples.ipc;

import com.aws.greengrass.docs.samples.ipc.util.IPCUtils;
import software.amazon.awssdk.aws.greengrass.GetSecretValueResponseHandler;
import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient;
import software.amazon.awssdk.aws.greengrass.model.GetSecretValueRequest;
import software.amazon.awssdk.aws.greengrass.model.GetSecretValueResponse;
import software.amazon.awssdk.aws.greengrass.model.UnauthorizedError;
import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection;

import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class GetSecretValue {

    public static final int TIMEOUT_SECONDS = 10;

    public static void main(String[] args) {
        String secretArn = args[0];
        String versionStage = args[1];
        try (EventStreamRPCConnection eventStreamRPCConnection =
                     IPCUtils.getEventStreamRpcConnection()) {
            GreengrassCoreIPCClient ipcClient =
                    new GreengrassCoreIPCClient(eventStreamRPCConnection);
            GetSecretValueResponseHandler responseHandler =
                    GetSecretValue.getSecretValue(ipcClient, secretArn, versionStage);
            CompletableFuture<GetSecretValueResponse> futureResponse =
                    responseHandler.getResponse();
            try {
                GetSecretValueResponse response = futureResponse.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
                response.getSecretValue().postFromJson();
                String secretString = response.getSecretValue().getSecretString();
                System.out.println("Successfully retrieved secret value: " + secretString);
            } catch (TimeoutException e) {
                System.err.println("Timeout occurred while retrieving secret: " + secretArn);
            } catch (ExecutionException e) {
                if (e.getCause() instanceof UnauthorizedError) {
                    System.err.println("Unauthorized error while retrieving secret: " + secretArn);
                } else {
                    throw e;
                }
            }
        } catch (InterruptedException e) {
            System.out.println("IPC interrupted.");
        } catch (ExecutionException e) {
            System.err.println("Exception occurred when using IPC.");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static GetSecretValueResponseHandler getSecretValue(GreengrassCoreIPCClient greengrassCoreIPCClient, String secretArn, String versionStage) {
        GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest();
        getSecretValueRequest.setSecretId(secretArn);
        getSecretValueRequest.setVersionStage(versionStage);
        return greengrassCoreIPCClient.getSecretValue(getSecretValueRequest, Optional.empty());
    }
}
```

------
#### [ Python (IPC client V1) ]

**Example 例: シークレット値の取得**  
この例では、 AWS IoT Device SDK for Python v2 のバージョン 1.5.4 以降を使用していることを前提としています。

```
import json

import awsiot.greengrasscoreipc
from awsiot.greengrasscoreipc.model import (
    GetSecretValueRequest,
    GetSecretValueResponse,
    UnauthorizedError
)

secret_id = 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyGreengrassSecret-abcdef'
TIMEOUT = 10

ipc_client = awsiot.greengrasscoreipc.connect()

request = GetSecretValueRequest()
request.secret_id = secret_id
request.version_stage = 'AWSCURRENT'
operation = ipc_client.new_get_secret_value()
operation.activate(request)
future_response = operation.get_response()
response = future_response.result(TIMEOUT)
secret_json = json.loads(response.secret_value.secret_string)
# Handle secret value.
```

------
#### [ JavaScript ]

**Example 例: シークレット値の取得**  

```
import {
    GetSecretValueRequest,
} from 'aws-iot-device-sdk-v2/dist/greengrasscoreipc/model';
import * as greengrasscoreipc from "aws-iot-device-sdk-v2/dist/greengrasscoreipc";
 
class GetSecretValue {
    private readonly secretId : string;
    private readonly versionStage : string;
    private ipcClient : greengrasscoreipc.Client
 
    constructor() {
        this.secretId = "<define_your_own_secretId>"
        this.versionStage = "<define_your_own_versionStage>"
 
        this.getSecretValue().then(r => console.log("Started workflow"));
    }
 
    private async getSecretValue() {
        try {
            this.ipcClient = await getIpcClient();
 
            const getSecretValueRequest : GetSecretValueRequest = {
                secretId: this.secretId,
                versionStage: this.versionStage,
            };
 
            const result = await this.ipcClient.getSecretValue(getSecretValueRequest);
            const secretString = result.secretValue.secretString;
            console.log("Successfully retrieved secret value: " + secretString)
        } catch (e) {
            // parse the error depending on your use cases
            throw e
        }
    }
}
 
export async function getIpcClient(){
    try {
        const ipcClient = greengrasscoreipc.createClient();
        await ipcClient.connect()
            .catch(error => {
                // parse the error depending on your use cases
                throw error;
            });
        return ipcClient
    } catch (err) {
        // parse the error depending on your use cases
        throw err
    }
}
 
const getSecretValue = new GetSecretValue();
```

------

## 例
<a name="ipc-secret-manager-examples"></a>

コンポーネントのシークレットマネージャー IPC サービスの使用方法については、以下の例を参照してください。

### 例: シークレットを出力 (Python、IPC クライアント V1)
<a name="ipc-secret-manager-example-print-secret-python"></a>

このコンポーネントの例は、コアデバイスにデプロイしたシークレットの値を出力します。

**重要**  
このコンポーネントの例はシークレットの値を出力するため、テストデータが保存されたシークレットのみで使用してください。このコンポーネントを使用して、重要な情報が保存されたシークレットの値を出力しないでください。

**Topics**
+ [レシピ](#ipc-secret-manager-example-print-secret-python-recipe)
+ [アーティファクト](#ipc-secret-manager-example-print-secret-python-artifacts)
+ [使用方法](#ipc-secret-manager-example-print-secret-python-usage)

#### レシピ
<a name="ipc-secret-manager-example-print-secret-python-recipe"></a>

以下のレシピの例はシークレット ARN 設定パラメータを定義し、コンポーネントがコアデバイスのすべてのシークレット値を取得できるようにします。

**注記**  <a name="ipc-secret-manager-authorization-policy-resource-wildcard"></a>
実稼働環境では、コンポーネントが使用するシークレットのみ取得するように、承認ポリシーの範囲を小さくすることをお勧めします。コンポーネントをデプロイするとき、`*` ワイルドカードをシークレット ARN のリストに変更できます。

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PrintSecret",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "Prints the value of an AWS Secrets Manager secret.",
  "ComponentPublisher": "Amazon",
  "ComponentDependencies": {
    "aws.greengrass.SecretManager": {
      "VersionRequirement": "^2.0.0",
      "DependencyType": "HARD"
    }
  },
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "SecretArn": "",
      "accessControl": {
        "aws.greengrass.SecretManager": {
          "com.example.PrintSecret:secrets:1": {
            "policyDescription": "Allows access to a secret.",
            "operations": [
              "aws.greengrass#GetSecretValue"
            ],
            "resources": [
              "*"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux"
      },
      "Lifecycle": {
        "install": "python3 -m pip install --user awsiotsdk",
        "Run": "python3 -u {artifacts:path}/print_secret.py \"{configuration:/SecretArn}\""
      }
    },
    {
      "Platform": {
        "os": "windows"
      },
      "Lifecycle": {
        "install": "py -3 -m pip install --user awsiotsdk",
        "Run": "py -3 -u {artifacts:path}/print_secret.py \"{configuration:/SecretArn}\""
      }
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.PrintSecret
ComponentVersion: 1.0.0
ComponentDescription: Prints the value of a Secrets Manager secret.
ComponentPublisher: Amazon
ComponentDependencies:
  aws.greengrass.SecretManager:
    VersionRequirement: "^2.0.0"
    DependencyType: HARD
ComponentConfiguration:
  DefaultConfiguration:
    SecretArn: ''
    accessControl:
      aws.greengrass.SecretManager:
        com.example.PrintSecret:secrets:1:
          policyDescription: Allows access to a secret.
          operations:
            - aws.greengrass#GetSecretValue
          resources:
            - "*"
Manifests:
  - Platform:
      os: linux
    Lifecycle:
      install: python3 -m pip install --user awsiotsdk
      Run: python3 -u {artifacts:path}/print_secret.py "{configuration:/SecretArn}"
  - Platform:
      os: windows
    Lifecycle:
      install: py -3 -m pip install --user awsiotsdk
      Run: py -3 -u {artifacts:path}/print_secret.py "{configuration:/SecretArn}"
```

------

#### アーティファクト
<a name="ipc-secret-manager-example-print-secret-python-artifacts"></a>

次の Python アプリケーションの例は、シークレットマネージャー IPC サービスを使用して、コアデバイスのシークレット値を取得する方法を示しています。

```
import concurrent.futures
import json
import sys
import traceback

import awsiot.greengrasscoreipc
from awsiot.greengrasscoreipc.model import (
    GetSecretValueRequest,
    GetSecretValueResponse,
    UnauthorizedError
)

TIMEOUT = 10

if len(sys.argv) == 1:
    print('Provide SecretArn in the component configuration.', file=sys.stdout)
    exit(1)

secret_id = sys.argv[1]

try:
    ipc_client = awsiot.greengrasscoreipc.connect()

    request = GetSecretValueRequest()
    request.secret_id = secret_id
    operation = ipc_client.new_get_secret_value()
    operation.activate(request)
    future_response = operation.get_response()

    try:
        response = future_response.result(TIMEOUT)
        secret_json = json.loads(response.secret_value.secret_string)
        print('Successfully got secret: ' + secret_id)
        print('Secret value: ' + str(secret_json))
    except concurrent.futures.TimeoutError:
        print('Timeout occurred while getting secret: ' + secret_id, file=sys.stderr)
    except UnauthorizedError as e:
        print('Unauthorized error while getting secret: ' + secret_id, file=sys.stderr)
        raise e
    except Exception as e:
        print('Exception while getting secret: ' + secret_id, file=sys.stderr)
        raise e
except Exception:
    print('Exception occurred when using IPC.', file=sys.stderr)
    traceback.print_exc()
    exit(1)
```

#### 使用方法
<a name="ipc-secret-manager-example-print-secret-python-usage"></a>

このコンポーネントの例を[シークレットマネージャーコンポーネント](secret-manager-component.md)と一緒に使用すると、コアデバイスのシークレットの値をデプロイおよび出力できます。

**テストシークレットを作成、デプロイ、および出力するには**

1. テストデータを使用して、Secrets Manager シークレットを作成します。

------
#### [ Linux or Unix ]

   ```
   aws secretsmanager create-secret \
     --name MyTestGreengrassSecret \
     --secret-string '{"my-secret-key": "my-secret-value"}'
   ```

------
#### [ Windows Command Prompt (CMD) ]

   ```
   aws secretsmanager create-secret ^
     --name MyTestGreengrassSecret ^
     --secret-string '{"my-secret-key": "my-secret-value"}'
   ```

------
#### [ PowerShell ]

   ```
   aws secretsmanager create-secret `
     --name MyTestGreengrassSecret `
     --secret-string '{"my-secret-key": "my-secret-value"}'
   ```

------

   次の手順で使用するシークレットの ARN を保存します。

   詳細については、「*AWS Secrets Manager ユーザーガイド*」の「[Creating a secret](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)」を参照してください。

1. 以下の設定マージの更新を使用して、[シークレットマネージャーコンポーネント](secret-manager-component.md) (`aws.greengrass.SecretManager`) をデプロイします。先に作成したシークレットの ARN を指定します。

   ```
   {
     "cloudSecrets": [
       {
         "arn": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestGreengrassSecret-abcdef"
       }
     ]
   }
   ```

   詳細については、「[AWS IoT Greengrass コンポーネントをデバイスにデプロイする](manage-deployments.md)」または「[Greengrass CLI デプロイコマンド](gg-cli-deployment.md)」を参照してください。

1. 以下の設定マージの更新を使用して、このセクションのコンポーネントの例を作成してデプロイします。先に作成したシークレットの ARN を指定します。

   ```
   {
     "SecretArn": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestGreengrassSecret",
     "accessControl": {
       "aws.greengrass.SecretManager": {
         "com.example.PrintSecret:secrets:1": {
           "policyDescription": "Allows access to a secret.",
           "operations": [
             "aws.greengrass#GetSecretValue"
           ],
           "resources": [
             "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestGreengrassSecret-abcdef"
           ]
         }
       }
     }
   }
   ```

   詳細については、[AWS IoT Greengrass コンポーネントを作成する](create-components.md)を参照してください。

1.  AWS IoT Greengrass Core ソフトウェアログを表示してデプロイが成功したことを確認し、`com.example.PrintSecret`コンポーネントログを表示してシークレット値が出力されたことを確認します。詳細については、「[AWS IoT Greengrass ログのモニタリング](monitor-logs.md)」を参照してください。

# ローカルシャドウとやり取り
<a name="ipc-local-shadows"></a>

シャドウ IPC サービスを使用して、デバイスのローカルシャドウとやり取りします。やり取りするデバイスには、コアデバイスまたは接続されたクライアントデバイスを選択できます。

​これらの IPC オペレーションを使用するには、[シャドウマネージャーコンポーネント](shadow-manager-component.md)をカスタムコンポーネントの依存関係として含めます。その後、カスタムコンポーネントの IPC オペレーションを使用して、シャドウマネージャーを介してデバイスのローカルシャドウとやり取りできます。カスタムコンポーネントがローカルシャドウの状態の変更に対応できるようにするには、パブリッシュ/サブスクライブ IPC サービスを使用して、シャドウイベントをサブスクライブすることもできます。パブリッシュ/サブスクライブサービスの使用の詳細については、「[ローカルメッセージをパブリッシュ/サブスクライブする](ipc-publish-subscribe.md)」を参照してください。

**注記**  <a name="note-requirement-enable-shadow-manager-client-devices"></a>
コアデバイスがクライアントデバイスシャドウとやり取りできるようにするには、MQTT ブリッジコンポーネントを設定してデプロイする必要もあります。詳細については、「[Enable shadow manager to communicate with client devices](work-with-client-device-shadows.md)」(シャドウマネージャーがクライアントデバイスと通信できるようにする) を参照してください。

**Topics**
+ [最小 SDK バージョン](#ipc-local-shadows-sdk-versions)
+ [Authorization](#ipc-local-shadow-authorization)
+ [GetThingShadow](#ipc-operation-getthingshadow)
+ [UpdateThingShadow](#ipc-operation-updatethingshadow)
+ [DeleteThingShadow](#ipc-operation-deletethingshadow)
+ [ListNamedShadowsForThing](#ipc-operation-listnamedshadowsforthing)

## 最小 SDK バージョン
<a name="ipc-local-shadows-sdk-versions"></a>

次の表に、ローカルシャドウを操作するために使用 AWS IoT Device SDK する必要がある の最小バージョンを示します。


| SDK | 最小バージョン | 
| --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.4.0  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.6.0  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## Authorization
<a name="ipc-local-shadow-authorization"></a>

カスタムコンポーネントでシャドウ IPC サービスを使用するには、コンポーネントがシャドウとやり取りできるように承認ポリシーを定義する必要があります。承認ポリシーの定義については、「[コンポーネントに IPC オペレーションの実行を許可する](interprocess-communication.md#ipc-authorization-policies)」を参照してください。

シャドウ操作の承認ポリシーには以下のプロパティがあります。

**IPC サービス識別子:** `aws.greengrass.ShadowManager`


| 運用 | 説明 | リソース | 
| --- | --- | --- | 
|  `aws.greengrass#GetThingShadow`  |  コンポーネントがモノのシャドウを取得できるようにします。  |  次の文字列のいずれか。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-local-shadows.html)  | 
|  `aws.greengrass#UpdateThingShadow`  |  コンポーネントがモノのシャドウを更新できるようにします。  |  次の文字列のいずれか。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-local-shadows.html)  | 
|  `aws.greengrass#DeleteThingShadow`  |  コンポーネントがモノのシャドウを削除できるようにします。  |  次の文字列のいずれか。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-local-shadows.html)  | 
|  `aws.greengrass#ListNamedShadowsForThing`  |  コンポーネントがモノの名前付きシャドウのリストを取得できるようにします。  |  モノにアクセスしてそのシャドウを一覧表示できるようにするモノの名前の文字列。 `*` を使用してすべてのモノへのアクセスを許可します。  | 

**IPC サービス識別子:** `aws.greengrass.ipc.pubsub`


| 運用 | 説明 | リソース | 
| --- | --- | --- | 
|  `aws.greengrass#SubscribeToTopic`  |  コンポーネントが、指定したトピックに関するメッセージをサブスクライブできるようにします。  |  次のトピック文字列のいずれか。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-local-shadows.html) トピック接頭辞 `shadowTopicPrefix` の値は、以下に挙げるシャドウのタイプに応じて変化します。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/greengrass/v2/developerguide/ipc-local-shadows.html) すべてのトピックへのアクセスを許可するには、`*` を使用します。 <a name="ipc-local-publish-subscribe-authorization-mqtt-wildcards"></a>[Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 以降では、MQTT トピックワイルドカード (`#` および `+`) を含むトピックをサブスクライブできます。このトピック文字列は MQTT トピックのワイルドカードを文字そのものとしてサポートします。例えば、コンポーネントの承認ポリシーで `test/topic/#` へのアクセス権が付与されている場合、コンポーネントは `test/topic/#` をサブスクライブできますが、`test/topic/filter` はサブスクライブできません。  | 

### ローカルシャドウ承認ポリシーのレシピ変数
<a name="ipc-local-shadow-authorization-recipe-variables"></a>

[Greengrass nucleus](greengrass-nucleus-component.md) の v2.6.0 以降を使用していて、Greengrass nucleus の [interpolateComponentConfiguration](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-interpolate-component-configuration) 設定オプションを `true` に設定している場合、認可ポリシーで `{iot:thingName}` [レシピ変数](component-recipe-reference.md#recipe-variables)を使用できます。この機能を使用すると、コアデバイスのグループに対して 1 つの承認ポリシーを設定できます。各コアデバイスは自身のシャドウにのみアクセスできます。例えば、シャドウ IPC オペレーションのために、コンポーネントに次のリソースへのアクセスを許可することができます。

```
$aws/things/{iot:thingName}/shadow/
```

### 承認ポリシーの例
<a name="ipc-local-shadow-authorization-policy-examples"></a>

次の承認ポリシーの例を参照して、コンポーネントの承認ポリシー設定の参考にできます。

**Example 例: コアデバイスのグループがローカルシャドウとやり取りすることを許可する**  
 <a name="phrase-example-uses-recipe-variables-in-configuration"></a>この例では、機能は、[Greengrass nucleus コンポーネント](greengrass-nucleus-component.md)の v2.6.0 以降で利用できる機能を使用しています。Greengrass nucleus v2.6.0 では、コンポーネント設定に、ほとんどの[レシピ変数](component-recipe-reference.md#recipe-variables) (`{iot:thingName}` など) のサポートが追加されました。この機能を有効にするには、Greengrass nucleus の [interpolateComponentConfiguration](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-interpolate-component-configuration) 設定オプションを `true` に設定します。Greengrass nucleus のすべてのバージョンで機能する例については、「[example authorization policy for a single core device](#ipc-local-shadows-authorization-example-single-device)」(シングルコアデバイスの承認ポリシーの例) を参照してください。
次の承認ポリシーの例では、コンポーネント `com.example.MyShadowInteractionComponent` がクラシックデバイスシャドウ、およびコンポーネントを実行しているコアデバイスの名前付きシャドウ `myNamedShadow` とやり取りできるようにします。このポリシーは、このコンポーネントがこれらのシャドウのローカルトピックに関するメッセージを受信できるようにもします。  

```
{
  "accessControl": {
    "aws.greengrass.ShadowManager": {
      "com.example.MyShadowInteractionComponent:shadow:1": {
        "policyDescription": "Allows access to shadows",
        "operations": [
          "aws.greengrass#GetThingShadow",
          "aws.greengrass#UpdateThingShadow",
          "aws.greengrass#DeleteThingShadow"
        ],
        "resources": [
          "$aws/things/{iot:thingName}/shadow",
          "$aws/things/{iot:thingName}/shadow/name/myNamedShadow"
        ]
      },
      "com.example.MyShadowInteractionComponent:shadow:2": {
        "policyDescription": "Allows access to things with shadows",
        "operations": [
          "aws.greengrass#ListNamedShadowsForThing"
        ],
        "resources": [
          "{iot:thingName}"
        ]
      }    
    },
    "aws.greengrass.ipc.pubsub": {
      "com.example.MyShadowInteractionComponent:pubsub:1": {
        "policyDescription": "Allows access to shadow pubsub topics",
        "operations": [
          "aws.greengrass#SubscribeToTopic"
        ],
        "resources": [
          "$aws/things/{iot:thingName}/shadow/get/accepted",
          "$aws/things/{iot:thingName}/shadow/name/myNamedShadow/get/accepted"
        ]
      }
    }
  }
}
```

```
accessControl:
  aws.greengrass.ShadowManager:
    'com.example.MyShadowInteractionComponent:shadow:1':
      policyDescription: 'Allows access to shadows'
      operations:
        - 'aws.greengrass#GetThingShadow'
        - 'aws.greengrass#UpdateThingShadow'
        - 'aws.greengrass#DeleteThingShadow'
      resources:
        - $aws/things/{iot:thingName}/shadow
        - $aws/things/{iot:thingName}/shadow/name/myNamedShadow
    'com.example.MyShadowInteractionComponent:shadow:2':
      policyDescription: 'Allows access to things with shadows'
      operations:
        - 'aws.greengrass#ListNamedShadowsForThing'
      resources:
        - '{iot:thingName}'
  aws.greengrass.ipc.pubsub:
    'com.example.MyShadowInteractionComponent:pubsub:1':
      policyDescription: 'Allows access to shadow pubsub topics'
      operations:
        - 'aws.greengrass#SubscribeToTopic'
      resources:
        - $aws/things/{iot:thingName}/shadow/get/accepted
        - $aws/things/{iot:thingName}/shadow/name/myNamedShadow/get/accepted
```

**Example 例: コアデバイスのグループがクライアントデバイスシャドウとやり取りすることを許可する**  
この機能には、[Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 以降、[シャドウマネージャー](shadow-manager-component.md) v2.2.0 以降、および [MQTT ブリッジ](mqtt-bridge-component.md) v2.2.0 以降が必要です。[シャドウマネージャーがクライアントデバイスと通信できる](work-with-client-device-shadows.md#enable-shadow-manager-client-devices)ように MQTT ブリッジを設定する必要があります。
次の承認ポリシーの例では、コンポーネント `com.example.MyShadowInteractionComponent` が、名前が `MyClientDevice` で始まるクライアントデバイスのすべてのデバイスシャドウとやり取りできるようにします。  
コアデバイスがクライアントデバイスシャドウとやり取りできるようにするには、MQTT ブリッジコンポーネントを設定してデプロイする必要もあります。詳細については、「[Enable shadow manager to communicate with client devices](work-with-client-device-shadows.md)」(シャドウマネージャーがクライアントデバイスと通信できるようにする) を参照してください。

```
{
  "accessControl": {
    "aws.greengrass.ShadowManager": {
      "com.example.MyShadowInteractionComponent:shadow:1": {
        "policyDescription": "Allows access to shadows",
        "operations": [
          "aws.greengrass#GetThingShadow",
          "aws.greengrass#UpdateThingShadow",
          "aws.greengrass#DeleteThingShadow"
        ],
        "resources": [
          "$aws/things/MyClientDevice*/shadow",
          "$aws/things/MyClientDevice*/shadow/name/*"
        ]
      },
      "com.example.MyShadowInteractionComponent:shadow:2": {
        "policyDescription": "Allows access to things with shadows",
        "operations": [
          "aws.greengrass#ListNamedShadowsForThing"
        ],
        "resources": [
          "MyClientDevice*"
        ]
      }    
    }
  }
}
```

```
accessControl:
  aws.greengrass.ShadowManager:
    'com.example.MyShadowInteractionComponent:shadow:1':
      policyDescription: 'Allows access to shadows'
      operations:
        - 'aws.greengrass#GetThingShadow'
        - 'aws.greengrass#UpdateThingShadow'
        - 'aws.greengrass#DeleteThingShadow'
      resources:
        - $aws/things/MyClientDevice*/shadow
        - $aws/things/MyClientDevice*/shadow/name/*
    'com.example.MyShadowInteractionComponent:shadow:2':
      policyDescription: 'Allows access to things with shadows'
      operations:
        - 'aws.greengrass#ListNamedShadowsForThing'
      resources:
        - MyClientDevice*
```<a name="ipc-local-shadows-authorization-example-single-device"></a>

**Example 例: シングルコアデバイスがローカルシャドウとやり取りすることを許可する**  
以下の承認ポリシーの例は、コンポーネント `com.example.MyShadowInteractionComponent` がクラシックデバイスシャドウ、およびデバイス `MyThingName` の名前付きシャドウ `myNamedShadow` とやり取りできるようにします。このポリシーは、このコンポーネントがこれらのシャドウのローカルトピックに関するメッセージを受信できるようにもします。  

```
{
  "accessControl": {
    "aws.greengrass.ShadowManager": {
      "com.example.MyShadowInteractionComponent:shadow:1": {
        "policyDescription": "Allows access to shadows",
        "operations": [
          "aws.greengrass#GetThingShadow",
          "aws.greengrass#UpdateThingShadow",
          "aws.greengrass#DeleteThingShadow"
        ],
        "resources": [
          "$aws/things/MyThingName/shadow",
          "$aws/things/MyThingName/shadow/name/myNamedShadow"
        ]
      },
      "com.example.MyShadowInteractionComponent:shadow:2": {
        "policyDescription": "Allows access to things with shadows",
        "operations": [
          "aws.greengrass#ListNamedShadowsForThing"
        ],
        "resources": [
          "MyThingName"
        ]
      }    
    },
    "aws.greengrass.ipc.pubsub": {
      "com.example.MyShadowInteractionComponent:pubsub:1": {
        "policyDescription": "Allows access to shadow pubsub topics",
        "operations": [
          "aws.greengrass#SubscribeToTopic"
        ],
        "resources": [
          "$aws/things/MyThingName/shadow/get/accepted",
          "$aws/things/MyThingName/shadow/name/myNamedShadow/get/accepted"
        ]
      }
    }
  }
}
```

```
accessControl:
  aws.greengrass.ShadowManager:
    'com.example.MyShadowInteractionComponent:shadow:1':
      policyDescription: 'Allows access to shadows'
      operations:
        - 'aws.greengrass#GetThingShadow'
        - 'aws.greengrass#UpdateThingShadow'
        - 'aws.greengrass#DeleteThingShadow'
      resources:
        - $aws/things/MyThingName/shadow
        - $aws/things/MyThingName/shadow/name/myNamedShadow
    'com.example.MyShadowInteractionComponent:shadow:2':
      policyDescription: 'Allows access to things with shadows'
      operations:
        - 'aws.greengrass#ListNamedShadowsForThing'
      resources:
        - MyThingName
  aws.greengrass.ipc.pubsub:
    'com.example.MyShadowInteractionComponent:pubsub:1':
      policyDescription: 'Allows access to shadow pubsub topics'
      operations:
        - 'aws.greengrass#SubscribeToTopic'
      resources:
        - $aws/things/MyThingName/shadow/get/accepted
        - $aws/things/MyThingName/shadow/name/myNamedShadow/get/accepted
```<a name="interact-with-shadows-react-example-authorization-policies"></a>

**Example 例: コアデバイスのグループがローカルシャドウの状態変化に反応することを許可する**  
 <a name="phrase-example-uses-recipe-variables-in-configuration"></a>この例では、機能は、[Greengrass nucleus コンポーネント](greengrass-nucleus-component.md)の v2.6.0 以降で利用できる機能を使用しています。Greengrass nucleus v2.6.0 では、コンポーネント設定に、ほとんどの[レシピ変数](component-recipe-reference.md#recipe-variables) (`{iot:thingName}` など) のサポートが追加されました。この機能を有効にするには、Greengrass nucleus の [interpolateComponentConfiguration](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-interpolate-component-configuration) 設定オプションを `true` に設定します。Greengrass nucleus のすべてのバージョンで機能する例については、「[example authorization policy for a single core device](#interact-with-shadows-react-example-authorization-policy-single-device)」(シングルコアデバイスの承認ポリシーの例) を参照してください。
次のアクセスコントロールポリシーの例では、クラシックデバイスシャドウおよび名前付きシャドウ `myNamedShadow` の `/update/delta` トピックに関するメッセージを、コンポーネントを実行している各コアデバイスで、カスタム `com.example.MyShadowReactiveComponent` が受信できるようにします。  

```
{
  "accessControl": {
    "aws.greengrass.ipc.pubsub": {
      "com.example.MyShadowReactiveComponent:pubsub:1": {
        "policyDescription": "Allows access to shadow pubsub topics",
        "operations": [
          "aws.greengrass#SubscribeToTopic"
        ],
        "resources": [
          "$aws/things/{iot:thingName}/shadow/update/delta",
          "$aws/things/{iot:thingName}/shadow/name/myNamedShadow/update/delta"
        ]
      }
    }
  }
}
```

```
accessControl:
  aws.greengrass.ipc.pubsub:
    "com.example.MyShadowReactiveComponent:pubsub:1":
      policyDescription: Allows access to shadow pubsub topics
      operations:
        - 'aws.greengrass#SubscribeToTopic'
      resources:
        - $aws/things/{iot:thingName}/shadow/update/delta
        - $aws/things/{iot:thingName}/shadow/name/myNamedShadow/update/delta
```<a name="interact-with-shadows-react-example-authorization-policy-single-device"></a>

**Example 例: シングルコアデバイスに、ローカルシャドウの状態の変化に反応することを許可する**  
次のアクセスコントロールポリシーの例では、デバイス `MyThingName` について、クラシックデバイスシャドウおよび名前付きシャドウ `myNamedShadow` の `/update/delta` トピックに関するメッセージを、カスタム `com.example.MyShadowReactiveComponent` が受信できるようにします。  

```
{
  "accessControl": {
    "aws.greengrass.ipc.pubsub": {
      "com.example.MyShadowReactiveComponent:pubsub:1": {
        "policyDescription": "Allows access to shadow pubsub topics",
        "operations": [
          "aws.greengrass#SubscribeToTopic"
        ],
        "resources": [
          "$aws/things/MyThingName/shadow/update/delta",
          "$aws/things/MyThingName/shadow/name/myNamedShadow/update/delta"
        ]
      }
    }
  }
}
```

```
accessControl:
  aws.greengrass.ipc.pubsub:
    "com.example.MyShadowReactiveComponent:pubsub:1":
      policyDescription: Allows access to shadow pubsub topics
      operations:
        - 'aws.greengrass#SubscribeToTopic'
      resources:
        - $aws/things/MyThingName/shadow/update/delta
        - $aws/things/MyThingName/shadow/name/myNamedShadow/update/delta
```

## GetThingShadow
<a name="ipc-operation-getthingshadow"></a>

指定したモノのシャドウを取得します。

### リクエスト
<a name="ipc-operation-getthingshadow-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`thingName` (Python: `thing_name`)  <a name="ipc-local-shadows-thing-name"></a>
モノの名前。  
型: `string`

`shadowName` (Python: `shadow_name`)  <a name="ipc-local-shadows-shadow-name"></a>
シャドウの名前。モノのクラシックシャドウを指定するには、このパラメータを空の文字列 (`""`) に設定します。  
この AWS IoT Greengrass サービスは、`AWSManagedGreengrassV2Deployment`名前付きシャドウを使用して、個々のコアデバイスをターゲットとするデプロイを管理します。この名前付きシャドウは、 AWS IoT Greengrass サービスで使用するために予約されています。この名前付きシャドウを更新または削除しないでください。
型: `string`

### 応答
<a name="ipc-operation-getthingshadow-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`payload`  
BLOB としてのレスポンス状態ドキュメント。  
タイプ: 次の情報が含まれる `object`。    
`state`  
状態情報。  
このオブジェクトには、次の情報が含まれます。    
`desired`  
デバイスで更新がリクエストされた state のプロパティと値。  
タイプ: キーバリューペアの `map`  
`reported`  
デバイスによってレポートされた state のプロパティと値。  
タイプ: キーバリューペアの `map`  
`delta`  
望ましい state とレポートされた state のプロパティと値の違い。このプロパティは、`desired` と `reported` の state が異なる場合のみ存在します。  
タイプ: キーバリューペアの `map`  
`metadata`  
いつ状態が更新されたか判別するための、`desired` および `reported` セクションの属性ごとのタイムスタンプ。  
型: `string`  
`timestamp`  
レスポンスが生成された日付と時刻 (エポック時間)。  
型: `integer`  
`clientToken` (Python: `clientToken`)  
リクエストとレスポンスを対応付けるために使用されるトークン  
型: `string`  
`version`  
ローカルシャドウドキュメントのバージョン。  
型: `integer`

### エラー
<a name="ipc-operation-getthingshadow-errors"></a>

このオペレーションは以下のエラーを返す場合があります。

`InvalidArgumentsError`  <a name="ipc-invalidargumentserror"></a>
<a name="ipc-invalidargumentserror-para"></a>ローカルシャドウサービスは、リクエストパラメータを検証できません。これは、リクエストに不正な形式の JSON またはサポートされていない文字が含まれている場合に発生する可能性があります。

`ResourceNotFoundError`  <a name="ipc-resourcenotfounderror"></a>
要求されたローカルシャドウドキュメントが見つかりません。

`ServiceError`  <a name="ipc-serviceerror"></a>
内部サービスエラーが発生したか、IPC サービスへのリクエスト数が、シャドウマネージャーコンポーネントの `maxLocalRequestsPerSecondPerThing` および `maxTotalLocalRequestsRate` の設定パラメータで指定された制限を超えました。

`UnauthorizedError`  <a name="ipc-unauthorizederror"></a>
コンポーネントの承認ポリシーには、このオペレーションに必要な権限が含まれていません。

### 例
<a name="ipc-operation-getthingshadow-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Java (IPC client V1) ]

**Example 例: モノのシャドウを取得する**  
この例では、 `IPCUtils` クラスを使用して AWS IoT Greengrass Core IPC サービスへの接続を作成します。詳細については、「[AWS IoT Greengrass Core IPC サービスに接続する](interprocess-communication.md#ipc-service-connect)」を参照してください。

```
package com.aws.greengrass.docs.samples.ipc;

import com.aws.greengrass.docs.samples.ipc.util.IPCUtils;
import software.amazon.awssdk.aws.greengrass.GetThingShadowResponseHandler;
import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient;
import software.amazon.awssdk.aws.greengrass.model.GetThingShadowRequest;
import software.amazon.awssdk.aws.greengrass.model.GetThingShadowResponse;
import software.amazon.awssdk.aws.greengrass.model.ResourceNotFoundError;
import software.amazon.awssdk.aws.greengrass.model.UnauthorizedError;
import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection;

import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class GetThingShadow {

    public static final int TIMEOUT_SECONDS = 10;

    public static void main(String[] args) {
        // Use the current core device's name if thing name isn't set.
        String thingName = args[0].isEmpty() ? System.getenv("AWS_IOT_THING_NAME") : args[0];
        String shadowName = args[1];
        try (EventStreamRPCConnection eventStreamRPCConnection =
                     IPCUtils.getEventStreamRpcConnection()) {
            GreengrassCoreIPCClient ipcClient =
                    new GreengrassCoreIPCClient(eventStreamRPCConnection);
            GetThingShadowResponseHandler responseHandler =
                    GetThingShadow.getThingShadow(ipcClient, thingName, shadowName);
            CompletableFuture<GetThingShadowResponse> futureResponse =
                    responseHandler.getResponse();
            try {
                GetThingShadowResponse response = futureResponse.get(TIMEOUT_SECONDS,
                        TimeUnit.SECONDS);
                String shadowPayload = new String(response.getPayload(), StandardCharsets.UTF_8);
                System.out.printf("Successfully got shadow %s/%s: %s%n", thingName, shadowName,
                        shadowPayload);
            } catch (TimeoutException e) {
                System.err.printf("Timeout occurred while getting shadow: %s/%s%n", thingName,
                        shadowName);
            } catch (ExecutionException e) {
                if (e.getCause() instanceof UnauthorizedError) {
                    System.err.printf("Unauthorized error while getting shadow: %s/%s%n",
                            thingName, shadowName);
                } else if (e.getCause() instanceof ResourceNotFoundError) {
                    System.err.printf("Unable to find shadow to get: %s/%s%n", thingName,
                            shadowName);
                } else {
                    throw e;
                }
            }
        } catch (InterruptedException e) {
            System.out.println("IPC interrupted.");
        } catch (ExecutionException e) {
            System.err.println("Exception occurred when using IPC.");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static GetThingShadowResponseHandler getThingShadow(GreengrassCoreIPCClient greengrassCoreIPCClient, String thingName, String shadowName) {
        GetThingShadowRequest getThingShadowRequest = new GetThingShadowRequest();
        getThingShadowRequest.setThingName(thingName);
        getThingShadowRequest.setShadowName(shadowName);
        return greengrassCoreIPCClient.getThingShadow(getThingShadowRequest, Optional.empty());
    }
}
```

------
#### [ Python (IPC client V1) ]

**Example 例: モノのシャドウを取得する**  

```
import awsiot.greengrasscoreipc
import awsiot.greengrasscoreipc.client as client
from awsiot.greengrasscoreipc.model import GetThingShadowRequest

TIMEOUT = 10

def sample_get_thing_shadow_request(thingName, shadowName):
    try:
        # set up IPC client to connect to the IPC server
        ipc_client = awsiot.greengrasscoreipc.connect()
                
        # create the GetThingShadow request
        get_thing_shadow_request = GetThingShadowRequest()
        get_thing_shadow_request.thing_name = thingName
        get_thing_shadow_request.shadow_name = shadowName
        
        # retrieve the GetThingShadow response after sending the request to the IPC server
        op = ipc_client.new_get_thing_shadow()
        op.activate(get_thing_shadow_request)
        fut = op.get_response()
        
        result = fut.result(TIMEOUT)
        return result.payload
        
    except InvalidArgumentsError as e:
        # add error handling
        ...
    # except ResourceNotFoundError | UnauthorizedError | ServiceError
```

------
#### [ JavaScript ]

**Example 例: モノのシャドウを取得する**  

```
import {
    GetThingShadowRequest
} from 'aws-iot-device-sdk-v2/dist/greengrasscoreipc/model';
import * as greengrasscoreipc from 'aws-iot-device-sdk-v2/dist/greengrasscoreipc';

class GetThingShadow {
    private ipcClient: greengrasscoreipc.Client;
    private thingName: string;
    private shadowName: string;

    constructor() {
        // Define args parameters here           
        this.thingName = "<define_your_own_thingName>";
        this.shadowName = "<define_your_own_shadowName>";
        this.bootstrap();
    }

    async bootstrap() {
        try {
            this.ipcClient = await getIpcClient();
        } catch (err) {
            // parse the error depending on your use cases
            throw err
        }
        
        try {
            await this.handleGetThingShadowOperation(this.thingName,
                this.shadowName);
        } catch (err) {
            // parse the error depending on your use cases
            throw err
        }
    }

    async handleGetThingShadowOperation(
        thingName: string,
        shadowName: string
    ) {
        const request: GetThingShadowRequest = {
            thingName: thingName,
            shadowName: shadowName
        };
        const response = await this.ipcClient.getThingShadow(request);
    }
}

export async function getIpcClient() {
    try {
        const ipcClient = greengrasscoreipc.createClient();
        await ipcClient.connect()
            .catch(error => {
                // parse the error depending on your use cases
                throw error;
            });
        return ipcClient
    } catch (err) {
        // parse the error depending on your use caseså
        throw err
    }
}

const startScript = new GetThingShadow();
```

------

## UpdateThingShadow
<a name="ipc-operation-updatethingshadow"></a>

指定したモノのシャドウを更新します。Shadow が存在しない場合は作成されます。

### リクエスト
<a name="ipc-operation-updatethingshadow-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`thingName` (Python: `thing_name`)  <a name="ipc-local-shadows-thing-name"></a>
モノの名前。  
型: `string`

`shadowName` (Python: `shadow_name`)  <a name="ipc-local-shadows-shadow-name"></a>
シャドウの名前。モノのクラシックシャドウを指定するには、このパラメータを空の文字列 (`""`) に設定します。  
この AWS IoT Greengrass サービスは、`AWSManagedGreengrassV2Deployment`名前付きシャドウを使用して、個々のコアデバイスをターゲットとするデプロイを管理します。この名前付きシャドウは、 AWS IoT Greengrass サービスで使用するために予約されています。この名前付きシャドウを更新または削除しないでください。
型: `string`

`payload`  
BLOB としてのリクエスト状態ドキュメント。  
タイプ: 次の情報が含まれる `object`。    
`state`  
更新する状態情報。この IPC オペレーションは、指定したフィールドのみに影響します。  
このオブジェクトには、次の情報が含まれます。通常、同じリクエストで `desired` プロパティまたは `reported` プロパティのいずれかを使用しますが、両方を使用することはありません。    
`desired`  
デバイスで更新がリクエストされた state のプロパティと値。  
タイプ: キーバリューペアの `map`  
`reported`  
デバイスによってレポートされた state のプロパティと値。  
タイプ: キーバリューペアの `map`  
`clientToken` (Python: `client_token`)  
(オプション) クライアントトークンによってリクエストとレスポンスを対応付けるために使用されるトークン。  
型: `string`  
`version`  
(オプション) 更新するローカルシャドウドキュメントのバージョン。シャドウサービスは、指定したバージョンが最新バージョンと一致した場合のみ更新を処理します。  
型: `integer`

### 応答
<a name="ipc-operation-updatethingshadow-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`payload`  
BLOB としてのレスポンス状態ドキュメント。  
タイプ: 次の情報が含まれる `object`。    
`state`  
状態情報。  
このオブジェクトには、次の情報が含まれます。    
`desired`  
デバイスで更新がリクエストされた state のプロパティと値。  
タイプ: キーバリューペアの `map`  
`reported`  
デバイスによってレポートされた state のプロパティと値。  
タイプ: キーバリューペアの `map`  
`delta`  
デバイスによってレポートされた state のプロパティと値。  
タイプ: キーバリューペアの `map`  
`metadata`  
いつ状態が更新されたか判別するための、`desired` および `reported` セクションの属性ごとのタイムスタンプ。  
型: `string`  
`timestamp`  
レスポンスが生成された日付と時刻 (エポック時間)。  
型: `integer`  
`clientToken` (Python: `client_token`)  
リクエストとレスポンスを対応付けるために使用されるトークン。  
型: `string`  
`version`  
更新完了後のローカルシャドウドキュメントのバージョン。  
型: `integer`

### エラー
<a name="ipc-operation-updatethingshadow-errors"></a>

このオペレーションは以下のエラーを返す場合があります。

`ConflictError`  
ローカルシャドウサービスで、更新オペレーション中にバージョンの競合が発生しました。これは、リクエストペイロードのバージョンが利用可能な最新のローカルシャドードキュメントのバージョンと一致しない場合に発生します。

`InvalidArgumentsError`  
<a name="ipc-invalidargumentserror-para"></a>ローカルシャドウサービスは、リクエストパラメータを検証できません。これは、リクエストに不正な形式の JSON またはサポートされていない文字が含まれている場合に発生する可能性があります。  
有効な `payload` は以下のプロパティを有します。  
+ `state` ノードが存在すること、そして `desired` または `reported` の状態情報を含むオブジェクトであること。
+ `desired` および `reported` ノードはオブジェクトまたはヌルのいずれかであること。これらのオブジェクトの少なくとも 1 つに有効な状態情報が含まれている必要があります。
+ `desired` および `reported` オブジェクトの深さが 8 ノードを超えることはできません。
+ `clientToken` の値の長さが 64 文字を超えることはできません。
+  `version` の値は `1` 以上である必要があります。

`ServiceError`  <a name="ipc-serviceerror"></a>
内部サービスエラーが発生したか、IPC サービスへのリクエスト数が、シャドウマネージャーコンポーネントの `maxLocalRequestsPerSecondPerThing` および `maxTotalLocalRequestsRate` の設定パラメータで指定された制限を超えました。

`UnauthorizedError`  <a name="ipc-unauthorizederror"></a>
コンポーネントの承認ポリシーには、このオペレーションに必要な権限が含まれていません。

### 例
<a name="ipc-operation-updatethingshadow-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Java (IPC client V1) ]

**Example 例: モノのシャドウを更新する**  
この例では、 `IPCUtils` クラスを使用して AWS IoT Greengrass Core IPC サービスへの接続を作成します。詳細については、「[AWS IoT Greengrass Core IPC サービスに接続する](interprocess-communication.md#ipc-service-connect)」を参照してください。

```
package com.aws.greengrass.docs.samples.ipc;

import com.aws.greengrass.docs.samples.ipc.util.IPCUtils;
import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient;
import software.amazon.awssdk.aws.greengrass.UpdateThingShadowResponseHandler;
import software.amazon.awssdk.aws.greengrass.model.UnauthorizedError;
import software.amazon.awssdk.aws.greengrass.model.UpdateThingShadowRequest;
import software.amazon.awssdk.aws.greengrass.model.UpdateThingShadowResponse;
import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection;

import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateThingShadow {

    public static final int TIMEOUT_SECONDS = 10;

    public static void main(String[] args) {
        // Use the current core device's name if thing name isn't set.
        String thingName = args[0].isEmpty() ? System.getenv("AWS_IOT_THING_NAME") : args[0];
        String shadowName = args[1];
        byte[] shadowPayload = args[2].getBytes(StandardCharsets.UTF_8);
        try (EventStreamRPCConnection eventStreamRPCConnection =
                     IPCUtils.getEventStreamRpcConnection()) {
            GreengrassCoreIPCClient ipcClient =
                    new GreengrassCoreIPCClient(eventStreamRPCConnection);
            UpdateThingShadowResponseHandler responseHandler =
                    UpdateThingShadow.updateThingShadow(ipcClient, thingName, shadowName,
                            shadowPayload);
            CompletableFuture<UpdateThingShadowResponse> futureResponse =
                    responseHandler.getResponse();
            try {
                futureResponse.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
                System.out.printf("Successfully updated shadow: %s/%s%n", thingName, shadowName);
            } catch (TimeoutException e) {
                System.err.printf("Timeout occurred while updating shadow: %s/%s%n", thingName,
                        shadowName);
            } catch (ExecutionException e) {
                if (e.getCause() instanceof UnauthorizedError) {
                    System.err.printf("Unauthorized error while updating shadow: %s/%s%n",
                            thingName, shadowName);
                } else {
                    throw e;
                }
            }
        } catch (InterruptedException e) {
            System.out.println("IPC interrupted.");
        } catch (ExecutionException e) {
            System.err.println("Exception occurred when using IPC.");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static UpdateThingShadowResponseHandler updateThingShadow(GreengrassCoreIPCClient greengrassCoreIPCClient, String thingName, String shadowName, byte[] shadowPayload) {
        UpdateThingShadowRequest updateThingShadowRequest = new UpdateThingShadowRequest();
        updateThingShadowRequest.setThingName(thingName);
        updateThingShadowRequest.setShadowName(shadowName);
        updateThingShadowRequest.setPayload(shadowPayload);
        return greengrassCoreIPCClient.updateThingShadow(updateThingShadowRequest,
                Optional.empty());
    }
}
```

------
#### [ Python (IPC client V1) ]

**Example 例: モノのシャドウを更新する**  

```
import awsiot.greengrasscoreipc
import awsiot.greengrasscoreipc.client as client
from awsiot.greengrasscoreipc.model import UpdateThingShadowRequest

TIMEOUT = 10

def sample_update_thing_shadow_request(thingName, shadowName, payload):
    try:
        # set up IPC client to connect to the IPC server
        ipc_client = awsiot.greengrasscoreipc.connect()
                
        # create the UpdateThingShadow request
        update_thing_shadow_request = UpdateThingShadowRequest()
        update_thing_shadow_request.thing_name = thingName
        update_thing_shadow_request.shadow_name = shadowName
        update_thing_shadow_request.payload = payload
                        
        # retrieve the UpdateThingShadow response after sending the request to the IPC server
        op = ipc_client.new_update_thing_shadow()
        op.activate(update_thing_shadow_request)
        fut = op.get_response()
        
        result = fut.result(TIMEOUT)
        return result.payload
        
    except InvalidArgumentsError as e:
        # add error handling
    ...
    # except ConflictError | UnauthorizedError | ServiceError
```

------
#### [ JavaScript ]

**Example 例: モノのシャドウを更新する**  

```
import {
    UpdateThingShadowRequest
} from 'aws-iot-device-sdk-v2/dist/greengrasscoreipc/model';
import * as greengrasscoreipc from 'aws-iot-device-sdk-v2/dist/greengrasscoreipc';

class UpdateThingShadow {
    private ipcClient: greengrasscoreipc.Client;
    private thingName: string;
    private shadowName: string;
    private shadowDocumentStr: string;

    constructor() {
        // Define args parameters here

        this.thingName = "<define_your_own_thingName>";
        this.shadowName = "<define_your_own_shadowName>";
        this.shadowDocumentStr = "<define_your_own_payload>";

        this.bootstrap();
    }

    async bootstrap() {
        try {
            this.ipcClient = await getIpcClient();
        } catch (err) {
            // parse the error depending on your use cases
            throw err
        }

        try {
            await this.handleUpdateThingShadowOperation(
                this.thingName,
                this.shadowName,
                this.shadowDocumentStr);
        } catch (err) {
            // parse the error depending on your use cases
            throw err
        }
    }

    async handleUpdateThingShadowOperation(
        thingName: string,
        shadowName: string,
        payloadStr: string
    ) {
        const request: UpdateThingShadowRequest = {
            thingName: thingName,
            shadowName: shadowName,
            payload: payloadStr
        }
        // make the UpdateThingShadow request
        const response = await this.ipcClient.updateThingShadow(request);
    }
}

export async function getIpcClient() {
    try {
        const ipcClient = greengrasscoreipc.createClient();
        await ipcClient.connect()
            .catch(error => {
                // parse the error depending on your use cases
                throw error;
            });
        return ipcClient
    } catch (err) {
        // parse the error depending on your use cases
        throw err
    }
}

const startScript = new UpdateThingShadow();
```

------

## DeleteThingShadow
<a name="ipc-operation-deletethingshadow"></a>

指定したモノの Shadow を削除します。

シャドウマネージャー v2.0.4 以降、シャドウを削除するとバージョン番号がインクリメントします。たとえば、バージョン 1 のシャドウ `MyThingShadow` を削除すると、削除されたシャドウのバージョンは 2 になります。その後 `MyThingShadow` の名前でシャドウを作成し直すと、そのシャドウのバージョンは 3 になります。

### リクエスト
<a name="ipc-operation-deletethingshadow-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`thingName` (Python: `thing_name`)  <a name="ipc-local-shadows-thing-name"></a>
モノの名前。  
型: `string`

`shadowName` (Python: `shadow_name`)  <a name="ipc-local-shadows-shadow-name"></a>
シャドウの名前。モノのクラシックシャドウを指定するには、このパラメータを空の文字列 (`""`) に設定します。  
この AWS IoT Greengrass サービスは、`AWSManagedGreengrassV2Deployment`名前付きシャドウを使用して、個々のコアデバイスをターゲットとするデプロイを管理します。この名前付きシャドウは、 AWS IoT Greengrass サービスで使用するために予約されています。この名前付きシャドウを更新または削除しないでください。
型: `string`

### 応答
<a name="ipc-operation-deletethingshadow-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`payload`  
空のレスポンス状態ドキュメント。

### エラー
<a name="ipc-operation-deletethingshadow-errors"></a>

このオペレーションは以下のエラーを返す場合があります。

`InvalidArgumentsError`  <a name="ipc-invalidargumentserror"></a>
<a name="ipc-invalidargumentserror-para"></a>ローカルシャドウサービスは、リクエストパラメータを検証できません。これは、リクエストに不正な形式の JSON またはサポートされていない文字が含まれている場合に発生する可能性があります。

`ResourceNotFoundError`  <a name="ipc-resourcenotfounderror"></a>
要求されたローカルシャドウドキュメントが見つかりません。

`ServiceError`  <a name="ipc-serviceerror"></a>
内部サービスエラーが発生したか、IPC サービスへのリクエスト数が、シャドウマネージャーコンポーネントの `maxLocalRequestsPerSecondPerThing` および `maxTotalLocalRequestsRate` の設定パラメータで指定された制限を超えました。

`UnauthorizedError`  <a name="ipc-unauthorizederror"></a>
コンポーネントの承認ポリシーには、このオペレーションに必要な権限が含まれていません。

### 例
<a name="ipc-operation-deletethingshadow-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Java (IPC client V1) ]

**Example 例: モノのシャドウを削除する**  
この例では、 `IPCUtils` クラスを使用して AWS IoT Greengrass Core IPC サービスへの接続を作成します。詳細については、「[AWS IoT Greengrass Core IPC サービスに接続する](interprocess-communication.md#ipc-service-connect)」を参照してください。

```
package com.aws.greengrass.docs.samples.ipc;

import com.aws.greengrass.docs.samples.ipc.util.IPCUtils;
import software.amazon.awssdk.aws.greengrass.DeleteThingShadowResponseHandler;
import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient;
import software.amazon.awssdk.aws.greengrass.model.DeleteThingShadowRequest;
import software.amazon.awssdk.aws.greengrass.model.DeleteThingShadowResponse;
import software.amazon.awssdk.aws.greengrass.model.ResourceNotFoundError;
import software.amazon.awssdk.aws.greengrass.model.UnauthorizedError;
import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection;

import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteThingShadow {

    public static final int TIMEOUT_SECONDS = 10;

    public static void main(String[] args) {
        // Use the current core device's name if thing name isn't set.
        String thingName = args[0].isEmpty() ? System.getenv("AWS_IOT_THING_NAME") : args[0];
        String shadowName = args[1];
        try (EventStreamRPCConnection eventStreamRPCConnection =
                     IPCUtils.getEventStreamRpcConnection()) {
            GreengrassCoreIPCClient ipcClient =
                    new GreengrassCoreIPCClient(eventStreamRPCConnection);
            DeleteThingShadowResponseHandler responseHandler =
                    DeleteThingShadow.deleteThingShadow(ipcClient, thingName, shadowName);
            CompletableFuture<DeleteThingShadowResponse> futureResponse =
                    responseHandler.getResponse();
            try {
                futureResponse.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
                System.out.printf("Successfully deleted shadow: %s/%s%n", thingName, shadowName);
            } catch (TimeoutException e) {
                System.err.printf("Timeout occurred while deleting shadow: %s/%s%n", thingName,
                        shadowName);
            } catch (ExecutionException e) {
                if (e.getCause() instanceof UnauthorizedError) {
                    System.err.printf("Unauthorized error while deleting shadow: %s/%s%n",
                            thingName, shadowName);
                } else if (e.getCause() instanceof ResourceNotFoundError) {
                    System.err.printf("Unable to find shadow to delete: %s/%s%n", thingName,
                            shadowName);
                } else {
                    throw e;
                }
            }
        } catch (InterruptedException e) {
            System.out.println("IPC interrupted.");
        } catch (ExecutionException e) {
            System.err.println("Exception occurred when using IPC.");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static DeleteThingShadowResponseHandler deleteThingShadow(GreengrassCoreIPCClient greengrassCoreIPCClient, String thingName, String shadowName) {
        DeleteThingShadowRequest deleteThingShadowRequest = new DeleteThingShadowRequest();
        deleteThingShadowRequest.setThingName(thingName);
        deleteThingShadowRequest.setShadowName(shadowName);
        return greengrassCoreIPCClient.deleteThingShadow(deleteThingShadowRequest,
                Optional.empty());
    }
}
```

------
#### [ Python (IPC client V1) ]

**Example 例: モノのシャドウを削除する**  

```
import awsiot.greengrasscoreipc
import awsiot.greengrasscoreipc.client as client
from awsiot.greengrasscoreipc.model import DeleteThingShadowRequest

TIMEOUT = 10

def sample_delete_thing_shadow_request(thingName, shadowName):
    try:
        # set up IPC client to connect to the IPC server
        ipc_client = awsiot.greengrasscoreipc.connect()
                
        # create the DeleteThingShadow request
        delete_thing_shadow_request = DeleteThingShadowRequest()
        delete_thing_shadow_request.thing_name = thingName
        delete_thing_shadow_request.shadow_name = shadowName
                        
        # retrieve the DeleteThingShadow response after sending the request to the IPC server
        op = ipc_client.new_delete_thing_shadow()
        op.activate(delete_thing_shadow_request)
        fut = op.get_response()
        
        result = fut.result(TIMEOUT)
        return result.payload
        
    except InvalidArgumentsError as e:
        # add error handling
    ...
    # except ResourceNotFoundError | UnauthorizedError | ServiceError
```

------
#### [ JavaScript ]

**Example 例: モノのシャドウを削除する**  

```
import {
    DeleteThingShadowRequest
} from 'aws-iot-device-sdk-v2/dist/greengrasscoreipc/model';
import * as greengrasscoreipc from 'aws-iot-device-sdk-v2/dist/greengrasscoreipc';

class DeleteThingShadow {
    private ipcClient: greengrasscoreipc.Client;
    private thingName: string;
    private shadowName: string;

    constructor() {
        // Define args parameters here
        this.thingName = "<define_your_own_thingName>";
        this.shadowName = "<define_your_own_shadowName>";
        this.bootstrap();
    }

    async bootstrap() {
        try {
            this.ipcClient = await getIpcClient();
        } catch (err) {
            // parse the error depending on your use cases
            throw err
        }

        try {
            await this.handleDeleteThingShadowOperation(this.thingName, this.shadowName)
        } catch (err) {
            // parse the error depending on your use cases
            throw err
        }
    }

    async handleDeleteThingShadowOperation(thingName: string, shadowName: string) {
        const request: DeleteThingShadowRequest = {
            thingName: thingName,
            shadowName: shadowName
        }
        // make the DeleteThingShadow request
        const response = await this.ipcClient.deleteThingShadow(request);
    }
}

export async function getIpcClient() {
    try {
        const ipcClient = greengrasscoreipc.createClient();
        await ipcClient.connect()
            .catch(error => {
                // parse the error depending on your use cases
                throw error;
            });
        return ipcClient
    } catch (err) {
        // parse the error depending on your use cases
        throw err
    }
}

const startScript = new DeleteThingShadow();
```

------

## ListNamedShadowsForThing
<a name="ipc-operation-listnamedshadowsforthing"></a>

指定されたモノの名前付きシャドウを一覧表示します。

### リクエスト
<a name="ipc-operation-listnamedshadowsforthing-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`thingName` (Python: `thing_name`)  <a name="ipc-local-shadows-thing-name"></a>
モノの名前。  
型: `string`

`pageSize` (Python: `page_size`)  
(オプション) 各呼び出しで返すシャドウ名の数。  
型: `integer`  
デフォルト: 25  
最大: 100

`nextToken` (Python: `next_token`)  
(オプション) 次の結果セットを取得するためのトークン。この値は、ページングされた結果で返され、次のページを返す呼び出しで使用されます。  
型: `string`

### 応答
<a name="ipc-operation-listnamedshadowsforthing-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`results`  
シャドウ名のリスト。  
型: `array`

`timestamp`  
(オプション) レスポンスが生成された日付と時刻。  
型: `integer`

`nextToken` (Python: `next_token`)  
(オプション) シーケンス内の次のページを取得するためにページングされたリクエストで使用するトークン値。返すシャドウ名がなくなると、このプロパティは存在しません。  
型: `string`  
リクエストされたページサイズがレスポンスのシャドウ名の数と完全に一致する場合、このトークンは存在しますが、使用すると空のリストが返されます。

### エラー
<a name="ipc-operation-listnamedshadowsforthing-errors"></a>

このオペレーションは以下のエラーを返す場合があります。

`InvalidArgumentsError`  <a name="ipc-invalidargumentserror"></a>
<a name="ipc-invalidargumentserror-para"></a>ローカルシャドウサービスは、リクエストパラメータを検証できません。これは、リクエストに不正な形式の JSON またはサポートされていない文字が含まれている場合に発生する可能性があります。

`ResourceNotFoundError`  <a name="ipc-resourcenotfounderror"></a>
要求されたローカルシャドウドキュメントが見つかりません。

`ServiceError`  <a name="ipc-serviceerror"></a>
内部サービスエラーが発生したか、IPC サービスへのリクエスト数が、シャドウマネージャーコンポーネントの `maxLocalRequestsPerSecondPerThing` および `maxTotalLocalRequestsRate` の設定パラメータで指定された制限を超えました。

`UnauthorizedError`  <a name="ipc-unauthorizederror"></a>
コンポーネントの承認ポリシーには、このオペレーションに必要な権限が含まれていません。

### 例
<a name="ipc-operation-listnamedshadowsforthing-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Java (IPC client V1) ]

**Example 例:モノの名前付きシャドウを一覧表示**  
この例では、 `IPCUtils` クラスを使用して AWS IoT Greengrass Core IPC サービスへの接続を作成します。詳細については、「[AWS IoT Greengrass Core IPC サービスに接続する](interprocess-communication.md#ipc-service-connect)」を参照してください。

```
package com.aws.greengrass.docs.samples.ipc;

import com.aws.greengrass.docs.samples.ipc.util.IPCUtils;
import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient;
import software.amazon.awssdk.aws.greengrass.ListNamedShadowsForThingResponseHandler;
import software.amazon.awssdk.aws.greengrass.model.ListNamedShadowsForThingRequest;
import software.amazon.awssdk.aws.greengrass.model.ListNamedShadowsForThingResponse;
import software.amazon.awssdk.aws.greengrass.model.ResourceNotFoundError;
import software.amazon.awssdk.aws.greengrass.model.UnauthorizedError;
import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ListNamedShadowsForThing {

    public static final int TIMEOUT_SECONDS = 10;

    public static void main(String[] args) {
        // Use the current core device's name if thing name isn't set.
        String thingName = args[0].isEmpty() ? System.getenv("AWS_IOT_THING_NAME") : args[0];
        try (EventStreamRPCConnection eventStreamRPCConnection =
                     IPCUtils.getEventStreamRpcConnection()) {
            GreengrassCoreIPCClient ipcClient =
                    new GreengrassCoreIPCClient(eventStreamRPCConnection);
            List<String> namedShadows = new ArrayList<>();
            String nextToken = null;
            try {
                // Send additional requests until there's no pagination token in the response.
                do {
                    ListNamedShadowsForThingResponseHandler responseHandler =
                            ListNamedShadowsForThing.listNamedShadowsForThing(ipcClient, thingName,
                                    nextToken, 25);
                    CompletableFuture<ListNamedShadowsForThingResponse> futureResponse =
                            responseHandler.getResponse();
                    ListNamedShadowsForThingResponse response =
                            futureResponse.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
                    List<String> responseNamedShadows = response.getResults();
                    namedShadows.addAll(responseNamedShadows);
                    nextToken = response.getNextToken();
                } while (nextToken != null);
                System.out.printf("Successfully got named shadows for thing %s: %s%n", thingName,
                        String.join(",", namedShadows));
            } catch (TimeoutException e) {
                System.err.println("Timeout occurred while listing named shadows for thing: " + thingName);
            } catch (ExecutionException e) {
                if (e.getCause() instanceof UnauthorizedError) {
                    System.err.println("Unauthorized error while listing named shadows for " +
                            "thing: " + thingName);
                } else if (e.getCause() instanceof ResourceNotFoundError) {
                    System.err.println("Unable to find thing to list named shadows: " + thingName);
                } else {
                    throw e;
                }
            }
        } catch (InterruptedException e) {
            System.out.println("IPC interrupted.");
        } catch (ExecutionException e) {
            System.err.println("Exception occurred when using IPC.");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static ListNamedShadowsForThingResponseHandler listNamedShadowsForThing(GreengrassCoreIPCClient greengrassCoreIPCClient, String thingName, String nextToken, int pageSize) {
        ListNamedShadowsForThingRequest listNamedShadowsForThingRequest =
                new ListNamedShadowsForThingRequest();
        listNamedShadowsForThingRequest.setThingName(thingName);
        listNamedShadowsForThingRequest.setNextToken(nextToken);
        listNamedShadowsForThingRequest.setPageSize(pageSize);
        return greengrassCoreIPCClient.listNamedShadowsForThing(listNamedShadowsForThingRequest,
                Optional.empty());
    }
}
```

------
#### [ Python (IPC client V1) ]

**Example 例:モノの名前付きシャドウを一覧表示**  

```
import awsiot.greengrasscoreipc
import awsiot.greengrasscoreipc.client as client
from awsiot.greengrasscoreipc.model import ListNamedShadowsForThingRequest

TIMEOUT = 10

def sample_list_named_shadows_for_thing_request(thingName, nextToken, pageSize):
    try:
        # set up IPC client to connect to the IPC server
        ipc_client = awsiot.greengrasscoreipc.connect()
                
        # create the ListNamedShadowsForThingRequest request
        list_named_shadows_for_thing_request = ListNamedShadowsForThingRequest()
        list_named_shadows_for_thing_request.thing_name = thingName
        list_named_shadows_for_thing_request.next_token = nextToken
        list_named_shadows_for_thing_request.page_size = pageSize
        
        # retrieve the ListNamedShadowsForThingRequest response after sending the request to the IPC server
        op = ipc_client.new_list_named_shadows_for_thing()
        op.activate(list_named_shadows_for_thing_request)
        fut = op.get_response()
        
        list_result = fut.result(TIMEOUT)
        
        # additional returned fields
        timestamp = list_result.timestamp
        next_token = result.next_token
        named_shadow_list = list_result.results
        
        return named_shadow_list, next_token, timestamp
                
    except InvalidArgumentsError as e:
        # add error handling
    ...
    # except ResourceNotFoundError | UnauthorizedError | ServiceError
```

------
#### [ JavaScript ]

**Example 例:モノの名前付きシャドウを一覧表示**  

```
import {
    ListNamedShadowsForThingRequest
} from 'aws-iot-device-sdk-v2/dist/greengrasscoreipc/model';
import * as greengrasscoreipc from 'aws-iot-device-sdk-v2/dist/greengrasscoreipc';

class listNamedShadowsForThing {
    private ipcClient: greengrasscoreipc.Client;
    private thingName: string;
    private pageSizeStr: string;
    private nextToken: string;

    constructor() {
        // Define args parameters here
        this.thingName = "<define_your_own_thingName>";
        this.pageSizeStr = "<define_your_own_pageSize>";
        this.nextToken = "<define_your_own_token>";
        this.bootstrap();
    }

    async bootstrap() {
        try {
            this.ipcClient = await getIpcClient();
        } catch (err) {
            // parse the error depending on your use cases
            throw err
        }
        
        try {
            await this.handleListNamedShadowsForThingOperation(this.thingName,
                this.nextToken, this.pageSizeStr);
        } catch (err) {
            // parse the error depending on your use cases
            throw err
        }
    }

    async handleListNamedShadowsForThingOperation(
        thingName: string,
        nextToken: string,
        pageSizeStr: string
    ) {
        let request: ListNamedShadowsForThingRequest = {
            thingName: thingName,
            nextToken: nextToken,
        };
        if (pageSizeStr) {
            request.pageSize = parseInt(pageSizeStr);
        }
        // make the ListNamedShadowsForThing request
        const response = await this.ipcClient.listNamedShadowsForThing(request);
        const shadowNames = response.results;
    }
}

export async function getIpcClient(){
    try {
        const ipcClient = greengrasscoreipc.createClient();
        await ipcClient.connect()
            .catch(error => {
                // parse the error depending on your use cases
                throw error;
            });
        return ipcClient
    } catch (err) {
        // parse the error depending on your use cases
        throw err
    }
}

const startScript = new listNamedShadowsForThing();
```

------

# ローカルデプロイおよびコンポーネントの管理
<a name="ipc-local-deployments-components"></a>

**注記**  
この機能は、[Greengrass nucleus コンポーネント](greengrass-nucleus-component.md)の v2.6.0 以降で利用できます。

Greengrass CLI IPC サービスを使用して、コアデバイスのローカルデプロイおよび Greengrass コンポーネントを管理します。

これらの IPC オペレーションを使用するには、カスタムコンポーネントの依存関係として、バージョン 2.6.0 以降の [Greengrass CLI コンポーネント](greengrass-cli-component.md)を含めます。その後、カスタムコンポーネントの IPC オペレーションを使用して、次の操作を行うことができます。
+ ローカルデプロイを作成し、コアデバイスの Greengrass コンポーネントを変更および設定します。
+ コアデバイスの Greengrass コンポーネントを再起動して停止します。
+ [ローカルデバッグコンソール](local-debug-console-component.md)へのサインインに使用できるパスワードを生成します。

**Topics**
+ [最小 SDK バージョン](#ipc-local-deployments-components-sdk-versions)
+ [Authorization](#ipc-local-deployments-components-authorization)
+ [CreateLocalDeployment](#ipc-operation-createlocaldeployment)
+ [ListLocalDeployments](#ipc-operation-listlocaldeployments)
+ [GetLocalDeploymentStatus](#ipc-operation-getlocaldeploymentstatus)
+ [ListComponents](#ipc-operation-listcomponents)
+ [GetComponentDetails](#ipc-operation-getcomponentdetails)
+ [RestartComponent](#ipc-operation-restartcomponent)
+ [StopComponent](#ipc-operation-stopcomponent)
+ [CreateDebugPassword](#ipc-operation-createdebugpassword)

## 最小 SDK バージョン
<a name="ipc-local-deployments-components-sdk-versions"></a>

次の表に、Greengrass CLI IPC サービスとやり取りするために使用 AWS IoT Device SDK する必要がある の最小バージョンを示します。


| SDK | 最小バージョン | 
| --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## Authorization
<a name="ipc-local-deployments-components-authorization"></a>

Greengrass CLI IPC サービスをカスタムコンポーネントで使用するには、コンポーネントがローカルデプロイとコンポーネントを管理できるように承認ポリシーを定義する必要があります。承認ポリシーの定義については、「[コンポーネントに IPC オペレーションの実行を許可する](interprocess-communication.md#ipc-authorization-policies)」を参照してください。

Greengrass CLI の承認ポリシーには、次のプロパティがあります。

**IPC サービス識別子:** `aws.greengrass.Cli`


| 運用 | 説明 | リソース | 
| --- | --- | --- | 
|  `aws.greengrass#CreateLocalDeployment`  |  コンポーネントがコアデバイスにローカルデプロイを作成できるようにします。  |  `*`  | 
|  `aws.greengrass#ListLocalDeployments`  |  コンポーネントがコアデバイスのローカルデプロイを一覧表示できるようにします。  |  `*`  | 
|  `aws.greengrass#GetLocalDeploymentStatus`  |  コンポーネントがコアデバイスのローカルデプロイのステータスを取得できるようにします。  |  すべてのローカルデプロイへのアクセスを許可するローカルデプロイ ID または `*`。  | 
|  `aws.greengrass#ListComponents`  |  コンポーネントがコアデバイスのコンポーネントを一覧表示できるようにします。  |  `*`  | 
|  `aws.greengrass#GetComponentDetails`  |  コンポーネントがコアデバイスのコンポーネントの詳細を取得できるようにします。  |  すべてのコンポーネントへのアクセスを許可するコンポーネント名 (`com.example.HelloWorld` など) または `*`。  | 
|  `aws.greengrass#RestartComponent`  |  コンポーネントがコアデバイスのコンポーネントを再起動できるようにします。  |  すべてのコンポーネントへのアクセスを許可するコンポーネント名 (`com.example.HelloWorld` など) または `*`。  | 
|  `aws.greengrass#StopComponent`  |  コンポーネントがコアデバイスのコンポーネントを停止できるようにします。  |  すべてのコンポーネントへのアクセスを許可するコンポーネント名 (`com.example.HelloWorld` など) または `*`。  | 
|  `aws.greengrass#CreateDebugPassword`  |  コンポーネントが[ローカルデバッグコンソールコンポーネント](local-debug-console-component.md)へのサインインに使用するパスワードを生成できるようにします。  |  `*`  | 

**Example 承認ポリシーの例**  
次の認可ポリシーの例では、コンポーネントがローカルデプロイを作成し、すべてのローカルデプロイとコンポーネントを表示し、`com.example.HelloWorld`という名前のコンポーネントを再起動および停止できるようにします。  

```
{
  "accessControl": {
    "aws.greengrass.Cli": {
      "com.example.MyLocalManagerComponent:cli:1": {
        "policyDescription": "Allows access to create local deployments and view deployments and components.",
        "operations": [
          "aws.greengrass#CreateLocalDeployment",
          "aws.greengrass#ListLocalDeployments",
          "aws.greengrass#GetLocalDeploymentStatus",
          "aws.greengrass#ListComponents",
          "aws.greengrass#GetComponentDetails"
        ],
        "resources": [
          "*"
        ]
      }
    },
    "aws.greengrass.Cli": {
      "com.example.MyLocalManagerComponent:cli:2": {
        "policyDescription": "Allows access to restart and stop the Hello World component.",
        "operations": [
          "aws.greengrass#RestartComponent",
          "aws.greengrass#StopComponent"
        ],
        "resources": [
          "com.example.HelloWorld"
        ]
      }
    }
  }
}
```

## CreateLocalDeployment
<a name="ipc-operation-createlocaldeployment"></a>

指定されたコンポーネントレシピ、アーティファクト、ランタイム引数を使用して、ローカルデプロイを作成または更新します。

このオペレーションは、Greengrass CLI の[デプロイの create コマンド](gg-cli-deployment.md#deployment-create)と同じ機能を提供します。

### リクエスト
<a name="ipc-operation-createlocaldeployment-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`recipeDirectoryPath` (Python: `recipe_directory_path`)  
(オプション) コンポーネントレシピファイルを含むフォルダへの絶対パス。

`artifactDirectoryPath` (Python: `artifact_directory_path`)  
(オプション) デプロイに含めるアーティファクトファイルを含むフォルダへの絶対パス。アーティファクトフォルダには、次のフォルダ構造が含まれている必要があります。  

```
/path/to/artifact/folder/component-name/component-version/artifacts
```

`rootComponentVersionsToAdd` (Python: `root_component_versions_to_add`)  
(オプション) コアデバイスにインストールするコンポーネントのバージョン。このオブジェクト `ComponentToVersionMap` は、次のキーと値のペアを含むマップです。    
`key`  
コンポーネントの名前。  
`value`  
コンポーネントのバージョン。

`rootComponentsToRemove` (Python: `root_components_to_remove`)  
(オプション) コアデバイスからアンインストールするコンポーネント。各エントリがコンポーネントの名前となるリストを指定します。

`componentToConfiguration` (Python: `component_to_configuration`)  
(オプション) デプロイ内の各コンポーネントの設定更新。このオブジェクト `ComponentToConfiguration` は、次のキーと値のペアを含むマップです。    
`key`  
コンポーネントの名前。  
`value`  
コンポーネントの設定更新の JSON オブジェクト。JSON オブジェクトは次の形式である必要があります。  

```
{ 
  "MERGE": {
    "config-key": "config-value"
  },
  "RESET": [
    "path/to/reset/"
  ]
}
```
設定の更新の詳細については、「[コンポーネント設定の更新](update-component-configurations.md)」を参照してください。

`componentToRunWithInfo` (Python: `component_to_run_with_info`)  
(オプション) デプロイ内の各コンポーネントのランタイム設定。この設定には、各コンポーネントのプロセスを所有するシステムユーザーと、各コンポーネントに適用するシステム制限が含まれます。このオブジェクト `ComponentToRunWithInfo` は、次のキーと値のペアを含むマップです。    
`key`  
コンポーネントの名前。  
`value`  
コンポーネントのランタイム設定。ランタイム設定パラメータを省略すると、 AWS IoT Greengrass Core ソフトウェアは [Greengrass nucleus ](greengrass-nucleus-component.md)で設定したデフォルト値を使用します。このオブジェクト (`RunWithInfo`) には、次の情報が含まれます。    
`posixUser` (Python: `posix_user`)  
(オプション) <a name="deployment-posix-user-definition"></a>Linux コアデバイスでこのコンポーネントを実行する際に使用する POSIX システムユーザーおよびオプションのグループ。ユーザーまたはグループを指定する場合は、各 Linux コアデバイス上に存在している必要があります。ユーザーとグループを `user:group` の形式に従ってコロン (`:`) で区切って指定します。グループはオプションです。グループを指定しない場合、 AWS IoT Greengrass Core ソフトウェアはユーザーのプライマリグループを使用します。詳細については、「[コンポーネントを実行するユーザーを設定する](configure-greengrass-core-v2.md#configure-component-user)」を参照してください。  
`windowsUser` (Python: `windows_user`)  
(オプション) <a name="deployment-windows-user-definition"></a>Windows コアデバイスでこのコンポーネントを実行する際に使用する Windows ユーザー。ユーザーは各 Windows コアデバイスに存在し、その名前とパスワードが LocalSystem アカウントの認証情報マネージャーインスタンスに格納されている必要があります。詳細については、「[コンポーネントを実行するユーザーを設定する](configure-greengrass-core-v2.md#configure-component-user)」を参照してください。  
`systemResourceLimits` (Python: `system_resource_limits`)  
(オプション) <a name="deployment-system-resource-limits-definition"></a>このコンポーネントのプロセスに適用されるシステムリソースの制限。システムリソースの制限を、ジェネリックおよびコンテナ化されていない Lambda コンポーネントプロセスに適用することができます。詳細については、「[コンポーネントのシステムリソース制限を設定する](configure-greengrass-core-v2.md#configure-component-system-resource-limits)」を参照してください。  
AWS IoT Greengrass は現在、Windows コアデバイスでこの機能をサポートしていません。  
このオブジェクト (`SystemResourceLimits`) には、次の情報が含まれます。    
`cpus`  
(オプション) <a name="system-resource-limits-cpu-definition-this"></a>このコンポーネントのプロセスがコアデバイスで使用できる CPU 時間の最大量。コアデバイスの合計 CPU 時間は、デバイスの CPU コア数と同じです。例えば、4 つの CPU コアを持つコアデバイスの場合は、この値を `2` に設定することで、このコンポーネントのプロセスを各 CPU コアの 50% の使用率に制限することができます。CPU コアが 1 つのデバイスの場合は、この値を `0.25` に設定することで、このコンポーネントのプロセスを CPU の 25% の使用率に制限することができます。この値を CPU コア数より大きい数に設定した場合、 AWS IoT Greengrass Core ソフトウェアはコンポーネントの CPU 使用率を制限しません。  
`memory`  
(オプション) <a name="system-resource-limits-memory-definition-this"></a>このコンポーネントのプロセスがコアデバイスで使用できる RAM の最大量 (キロバイト単位)。

`groupName` (Python: `group_name`)  
(オプション) このデプロイでターゲットにするモノのグループの名前。

### 応答
<a name="ipc-operation-createlocaldeployment-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`deploymentId` (Python: `deployment_id`)  
リクエストによって作成されたローカルデプロイの ID。

## ListLocalDeployments
<a name="ipc-operation-listlocaldeployments"></a>

過去 10 回分のローカルデプロイのステータスを取得します。

このオペレーションは、Greengrass CLI の[デプロイの list コマンド](gg-cli-deployment.md#deployment-list)と同じ機能を提供します。

### リクエスト
<a name="ipc-operation-listlocaldeployments-request"></a>

このオペレーションのリクエストはパラメータを持ちません。

### 応答
<a name="ipc-operation-listlocaldeployments-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`localDeployments` (Python: `local_deployments`)  
ローカルデプロイのリスト。このリストの各オブジェクトは、次の情報が含まれる `LocalDeployment` オブジェクトです。  <a name="ipc-local-deployment-object-shape"></a>  
`deploymentId` (Python: `deployment_id`)  
ローカルデプロイの ID。  
`status`  
ローカルデプロイのステータス。この列挙型 (`DeploymentStatus`) には以下の値があります。  
+ `QUEUED`
+ `IN_PROGRESS`
+ `SUCCEEDED`
+ `FAILED`

## GetLocalDeploymentStatus
<a name="ipc-operation-getlocaldeploymentstatus"></a>

ローカルデプロイのステータスを取得します。

このオペレーションは、Greengrass CLI の[デプロイの status コマンド](gg-cli-deployment.md#deployment-status)と同じ機能を提供します。

### リクエスト
<a name="ipc-operation-getlocaldeploymentstatus-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`deploymentId` (Python: `deployment_id`)  
取得するローカルデプロイの ID。

### 応答
<a name="ipc-operation-getlocaldeploymentstatus-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`deployment`  
ローカルデプロイ。このオブジェクト (`LocalDeployment`) には、次の情報が含まれます。  <a name="ipc-local-deployment-object-shape"></a>  
`deploymentId` (Python: `deployment_id`)  
ローカルデプロイの ID。  
`status`  
ローカルデプロイのステータス。この列挙型 (`DeploymentStatus`) には以下の値があります。  
+ `QUEUED`
+ `IN_PROGRESS`
+ `SUCCEEDED`
+ `FAILED`

## ListComponents
<a name="ipc-operation-listcomponents"></a>

コアデバイスの各ルートコンポーネントの名前、バージョン、ステータス、および設定を取得します。*ルートコンポーネント*は、デプロイ時に指定するコンポーネントです。このレスポンスには、他のコンポーネントとの依存関係の中でインストールされるコンポーネントは含まれません。

このオペレーションは、Greengrass CLI の[コンポーネントの list コマンド](gg-cli-component.md#component-list)と同じ機能を提供します。

### リクエスト
<a name="ipc-operation-listcomponents-request"></a>

このオペレーションのリクエストはパラメータを持ちません。

### 応答
<a name="ipc-operation-listcomponents-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`components`  
コアデバイスのルートコンポーネントのリスト。このリストの各オブジェクトは、次の情報が含まれる `ComponentDetails` オブジェクトです。  <a name="ipc-component-details-object-shape"></a>  
`componentName` (Python: `component_name`)  
コンポーネントの名前。  
`version`  
コンポーネントのバージョン。  
`state`  
コンポーネントの状態。これは、次のいずれかの状態になります。  
+ `BROKEN`
+ `ERRORED`
+ `FINISHED`
+ `INSTALLED`
+ `NEW`
+ `RUNNING`
+ `STARTING`
+ `STOPPING`  
`configuration`  
JSON オブジェクトとしてのコンポーネントの設定。

## GetComponentDetails
<a name="ipc-operation-getcomponentdetails"></a>

コアデバイスのコンポーネントのバージョン、ステータス、および設定を取得します。

このオペレーションは、Greengrass CLI の[コンポーネントの details コマンド](gg-cli-component.md#component-details)と同じ機能を提供します。

### リクエスト
<a name="ipc-operation-getcomponentdetails-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`componentName` (Python: `component_name`)  
取得するコンポーネントの名前。

### 応答
<a name="ipc-operation-getcomponentdetails-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`componentDetails` (Python: `component_details`)  
コンポーネントの詳細。このオブジェクト (`ComponentDetails`) には、次の情報が含まれます。  <a name="ipc-component-details-object-shape"></a>  
`componentName` (Python: `component_name`)  
コンポーネントの名前。  
`version`  
コンポーネントのバージョン。  
`state`  
コンポーネントの状態。これは、次のいずれかの状態になります。  
+ `BROKEN`
+ `ERRORED`
+ `FINISHED`
+ `INSTALLED`
+ `NEW`
+ `RUNNING`
+ `STARTING`
+ `STOPPING`  
`configuration`  
JSON オブジェクトとしてのコンポーネントの設定。

## RestartComponent
<a name="ipc-operation-restartcomponent"></a>

コアデバイスのコンポーネントを再起動します。

**注記**  
どのコンポーネントでも再起動できますが、[ジェネリックコンポーネント](develop-greengrass-components.md#component-types)のみを再起動することをお勧めします。

このオペレーションは、Greengrass CLI の[コンポーネントの restart コマンド](gg-cli-component.md#component-restart)と同じ機能を提供します。

### リクエスト
<a name="ipc-operation-restartcomponent-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`componentName` (Python: `component_name`)  
コンポーネントの名前。

### 応答
<a name="ipc-operation-restartcomponent-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`restartStatus` (Python: `restart_status`)  
再起動リクエストのステータス。リクエストのステータスは次のいずれかになります。  
+ `SUCCEEDED`
+ `FAILED`

`message`  
リクエストが失敗した際の、コンポーネントが再起動に失敗した理由に関するメッセージ。

### 例
<a name="ipc-operation-restartcomponent-examples"></a>

以下の例では、カスタムコンポーネントコードでこのオペレーションを呼び出す方法を示します。

------
#### [ Rust ]

**Example 例: コンポーネントを再起動する**  

```
use gg_sdk::Sdk;

fn main() {
    let sdk = Sdk::init();
    sdk.connect().expect("Failed to establish IPC connection");

    let component_name = "com.example.HelloWorld";

    sdk.restart_component(component_name)
        .expect("Failed to restart component");

    println!("Successfully requested restart for component: {component_name}");
}
```

------
#### [ C ]

**Example 例: コンポーネントを再起動する**  

```
#include <gg/error.h>
#include <gg/ipc/client.h>
#include <gg/sdk.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    gg_sdk_init();

    GgError err = ggipc_connect();
    if (err != GG_ERR_OK) {
        fprintf(stderr, "Failed to establish IPC connection.\n");
        exit(-1);
    }

    GgBuffer component_name = GG_STR("com.example.HelloWorld");

    err = ggipc_restart_component(component_name);
    if (err != GG_ERR_OK) {
        fprintf(
            stderr,
            "Failed to restart component: %.*s\n",
            (int) component_name.len,
            component_name.data
        );
        exit(-1);
    }

    printf(
        "Successfully requested restart for component: %.*s\n",
        (int) component_name.len,
        component_name.data
    );
}
```

------
#### [ C\$1\$1 (Component SDK) ]

**Example 例: コンポーネントを再起動する**  

```
#include <gg/ipc/client.hpp>
#include <iostream>

int main() {
    auto &client = gg::ipc::Client::get();

    auto error = client.connect();
    if (error) {
        std::cerr << "Failed to establish IPC connection.\n";
        exit(-1);
    }

    std::string_view component_name = "com.example.HelloWorld";

    error = client.restart_component(component_name);
    if (error) {
        std::cerr << "Failed to restart component: " << component_name << "\n";
        exit(-1);
    }

    std::cout << "Successfully requested restart for component: "
              << component_name << "\n";
}
```

------

## StopComponent
<a name="ipc-operation-stopcomponent"></a>

コアデバイスのコンポーネントのプロセスを停止します。

**注記**  
どのコンポーネントも停止できますが、[ジェネリックコンポーネント](develop-greengrass-components.md#component-types)のみを停止することをお勧めします。

このオペレーションは、Greengrass CLI の[コンポーネントの stop コマンド](gg-cli-component.md#component-stop)と同じ機能を提供します。

### リクエスト
<a name="ipc-operation-stopcomponent-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`componentName` (Python: `component_name`)  
コンポーネントの名前。

### 応答
<a name="ipc-operation-stopcomponent-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`stopStatus` (Python: `stop_status`)  
停止リクエストのステータス。リクエストのステータスは次のいずれかになります。  
+ `SUCCEEDED`
+ `FAILED`

`message`  
リクエストが失敗した際の、コンポーネントが停止に失敗した理由に関するメッセージ。

## CreateDebugPassword
<a name="ipc-operation-createdebugpassword"></a>

[ローカルデバッグコンソールコンポーネント](local-debug-console-component.md)へのサインインに使用できる、ランダムなパスワードを生成します。パスワードは、生成されてから 8 時間後に期限切れになります。

このオペレーションは、Greengrass CLI の [get-debug-password コマンド](gg-cli-get-debug-password.md)と同じ機能を提供します。

### リクエスト
<a name="ipc-operation-createdebugpassword-request"></a>

このオペレーションのリクエストはパラメータを持ちません。

### 応答
<a name="ipc-operation-createdebugpassword-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`username`  
サインインに使用するユーザー名。

`password`  
サインインに使用するパスワード。

`passwordExpiration` (Python: `password_expiration`)  
パスワードの有効期限が切れる時刻。

`certificateSHA256Hash` (Python: `certificate_sha256_hash`)  
HTTPS が有効な場合にローカルデバッグコンソールが使用する自己署名証明書の SHA-256 フィンガープリント。ローカルデバッグコンソールを開く際に、このフィンガープリントを使用して、証明書が正当であり接続が安全であることを確認します。

`certificateSHA1Hash` (Python: `certificate_sha1_hash`)  
HTTPS が有効な場合にローカルデバッグコンソールが使用する自己署名証明書の SHA-1 フィンガープリント。ローカルデバッグコンソールを開く際に、このフィンガープリントを使用して、証明書が正当であり接続が安全であることを確認します。

# クライアントデバイスを認証して認可する
<a name="ipc-client-device-auth"></a>

**注記**  
この機能は、[Greengrass nucleus コンポーネント](greengrass-nucleus-component.md)の v2.6.0 以降で利用できます。

クライアントデバイス認証 IPC サービスを使用して、クライアントデバイスなどのローカル IoT デバイスが接続できるカスタムのローカルブローカーコンポーネントを開発します。

これらの IPC オペレーションを使用するには、カスタムコンポーネントの依存関係として、バージョン 2.2.0 以降の[クライアントデバイス認証コンポーネント](client-device-auth-component.md)を含めます。その後、カスタムコンポーネントの IPC オペレーションを使用して、次の操作を行うことができます。
+ コアデバイスに接続するクライアントデバイスの ID の検証。
+ クライアントデバイスがコアデバイスに接続するためのセッションの作成。
+ クライアントデバイスにアクションを実行するアクセス許可があるかどうかの検証。
+ コアデバイスのサーバー証明書が更新された際の通知の受け取り。

**Topics**
+ [最小 SDK バージョン](#ipc-client-device-auth-sdk-versions)
+ [Authorization](#ipc-client-device-auth-authorization)
+ [VerifyClientDeviceIdentity](#ipc-operation-verifyclientdeviceidentity)
+ [GetClientDeviceAuthToken](#ipc-operation-getclientdeviceauthtoken)
+ [AuthorizeClientDeviceAction](#ipc-operation-authorizeclientdeviceaction)
+ [SubscribeToCertificateUpdates](#ipc-operation-subscribetocertificateupdates)

## 最小 SDK バージョン
<a name="ipc-client-device-auth-sdk-versions"></a>

次の表に、クライアントデバイスの認証 IPC サービスとやり取りするために使用 AWS IoT Device SDK する必要がある の最小バージョンを示します。


| SDK | 最小バージョン | 
| --- | --- | 
|  [AWS IoT Device SDK for Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.9.3  | 
|  [AWS IoT Device SDK Python v2 用](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.11.3  | 
|  [AWS IoT Device SDK C\$1\$1 v2 用](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.18.3  | 
|  [AWS IoT Device SDK for JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## Authorization
<a name="ipc-client-device-auth-authorization"></a>

カスタムコンポーネントでクライアントデバイス認可 IPC サービスを使用するには、コンポーネントがこれらのオペレーションを実行できるように認可ポリシーを定義する必要があります。承認ポリシーの定義については、「[コンポーネントに IPC オペレーションの実行を許可する](interprocess-communication.md#ipc-authorization-policies)」を参照してください。

クライアントデバイスの認証および認可の認可ポリシーには、次のプロパティがあります。

**IPC サービス識別子:** `aws.greengrass.clientdevices.Auth`


| 運用 | 説明 | リソース | 
| --- | --- | --- | 
|  `aws.greengrass#VerifyClientDeviceIdentity`  |  コンポーネントがクライアントデバイスの ID を検証できるようにします。  |  `*`  | 
|  `aws.greengrass#GetClientDeviceAuthToken`  |  コンポーネントがクライアントデバイスの認証情報を検証し、そのクライアントデバイスのセッションを作成できるようにします。  |  `*`  | 
|  `aws.greengrass#AuthorizeClientDeviceAction`  |  クライアントデバイスにアクションを実行するアクセス許可があるかどうかを、コンポーネントが検証できるようにします。  |  `*`  | 
|  `aws.greengrass#SubscribeToCertificateUpdates`  |  コアデバイスのサーバー証明書が更新されたときに、コンポーネントが通知を受け取ることができるようにします。  |  `*`  | 
|  `*`  |  コンポーネントがすべてのクライアントデバイス認証 IPC サービスのオペレーションを実行できるようにします。  |  `*`  | 

### 承認ポリシーの例
<a name="ipc-client-device-auth-authorization-policy-examples"></a>

次の承認ポリシーの例を参照して、コンポーネントの承認ポリシーの設定に役立てることができます。

**Example 承認ポリシーの例**  
次の認可ポリシーの例では、コンポーネントがすべてのクライアントデバイス認可の IPC オペレーションを実行できるようにします。  

```
{
  "accessControl": {
    "aws.greengrass.clientdevices.Auth": {
      "com.example.MyLocalBrokerComponent:clientdevices:1": {
        "policyDescription": "Allows access to authenticate and authorize client devices.",
        "operations": [
          "aws.greengrass#VerifyClientDeviceIdentity",
          "aws.greengrass#GetClientDeviceAuthToken",
          "aws.greengrass#AuthorizeClientDeviceAction",
          "aws.greengrass#SubscribeToCertificateUpdates"
        ],
        "resources": [
          "*"
        ]
      }
    }
  }
}
```

## VerifyClientDeviceIdentity
<a name="ipc-operation-verifyclientdeviceidentity"></a>

クライアントデバイスの ID の検証。このオペレーションは、クライアントデバイスが有効な AWS IoT モノであるかどうかを検証します。

### リクエスト
<a name="ipc-operation-verifyclientdeviceidentity-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`credential`  
クライアントデバイスの認証情報。このオブジェクト (`ClientDeviceCredential`) には、次の情報が含まれます。    
`clientDeviceCertificate` (Python: `client_device_certificate`)  
クライアントデバイスの X.509 デバイス証明書。

### 応答
<a name="ipc-operation-verifyclientdeviceidentity-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`isValidClientDevice` (Python: `is_valid_client_device`)  
クライアントデバイスの ID が有効かどうか。

## GetClientDeviceAuthToken
<a name="ipc-operation-getclientdeviceauthtoken"></a>

クライアントデバイスの認証情報を検証し、クライアントデバイスのセッションを作成します。このオペレーションは、[クライアントデバイスのアクションを承認](#ipc-operation-authorizeclientdeviceaction)するために、後続のリクエストで使用できるセッショントークンを返します。

クライアントデバイスを正常に接続するには、[クライアントデバイス認証コンポーネント](client-device-auth-component.md#client-device-auth-component-configuration)で、クライアントデバイスが使用するクライアント ID の `mqtt:connect` アクセス許可が付与される必要があります。

### リクエスト
<a name="ipc-operation-getclientdeviceauthtoken-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`credential`  
クライアントデバイスの認証情報。このオブジェクト (`CredentialDocument`) には、次の情報が含まれます。    
`mqttCredential` (Python: `mqtt_credential`)  
クライアントデバイスの MQTT 認証情報。クライアントデバイスが接続に使用するクライアント ID と証明書を指定します。このオブジェクト (`MQTTCredential`) には、次の情報が含まれます。    
`clientId` (Python: `client_id`)  
接続に使用するクライアント ID。  
`certificatePem` (Python: `certificate_pem`)  
接続に使用する X.509 デバイス証明書。  
`username`  
このプロパティは現在使用されていません。  
`password`  
このプロパティは現在使用されていません。

### 応答
<a name="ipc-operation-getclientdeviceauthtoken-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`clientDeviceAuthToken` (Python: `client_device_auth_token`)  
クライアントデバイスのセッショントークン。このセッショントークンを後続のリクエストで使用して、このクライアントデバイスのアクションを承認できます。

## AuthorizeClientDeviceAction
<a name="ipc-operation-authorizeclientdeviceaction"></a>

クライアントデバイスに、リソースに対するアクションを実行するアクセス許可があるかどうかを検証します。*クライアントデバイスの認可ポリシー*は、コアデバイスに接続しているときにクライアントデバイスが実行できるアクセス許可を指定します。クライアントデバイスの認可ポリシーは、[クライアントデバイス認可コンポーネント](client-device-auth-component.md#client-device-auth-component-configuration)を設定する際に定義します。

### リクエスト
<a name="ipc-operation-authorizeclientdeviceaction-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`clientDeviceAuthToken` (Python: `client_device_auth_token`)  
クライアントデバイスのセッショントークン。

`operation`  
承認するオペレーション。

`resource`  
クライアントデバイスがオペレーションを実行するリソース。

### 応答
<a name="ipc-operation-authorizeclientdeviceaction-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`isAuthorized` (Python: `is_authorized`)  
クライアントデバイスがリソースに対するオペレーションの実行を許可されているかどうか。

## SubscribeToCertificateUpdates
<a name="ipc-operation-subscribetocertificateupdates"></a>

コアデバイスの新しいサーバー証明書が更新されるたびにそれを受け取るようにサブスクライブします。サーバー証明書が更新されると、新しいサーバー証明書を使用してブローカーをリロードする必要があります。

[クライアントデバイス認証コンポーネント](client-device-auth-component.md)は、デフォルトでは 7 日ごとにサーバー証明書を更新します。更新の間隔は、2 日から 10 日の間で設定できます。

<a name="ipc-subscribe-operation-note"></a>このオペレーションはサブスクリプションオペレーションで、イベントメッセージのストリームをサブスクライブするというものです。このオペレーションを使用するには、イベントメッセージ、エラー、およびストリームクロージャを処理する関数を使用して、ストリームレスポンスハンドラーを定義します。(詳細については、[IPC イベントストリームへのサブスクライブ](interprocess-communication.md#ipc-subscribe-operations) を参照してください)。

**イベントメッセージの種類:** `CertificateUpdateEvent`

### リクエスト
<a name="ipc-operation-subscribetocertificateupdates-request"></a>

このオペレーションのリクエストには以下のパラメータがあります。

`certificateOptions` (Python: `certificate_options`)  
サブスクライブする証明書更新の種類。このオブジェクト (`CertificateOptions`) には、次の情報が含まれます。    
`certificateType` (Python: `certificate_type`)  
サブスクライブする証明書更新の種類。次のオプションを選択します。  
+ `SERVER`

### 応答
<a name="ipc-operation-subscribetocertificateupdates-response"></a>

このオペレーションのレスポンスには以下の情報が含まれます。

`messages`  
メッセージのストリーム。このオブジェクト (`CertificateUpdateEvent`) には、次の情報が含まれます。    
`certificateUpdate` (Python: `certificate_update`)  
新しい証明書に関する情報。このオブジェクト (`CertificateUpdate`) には、次の情報が含まれます。    
`certificate`  
証明書。  
`privateKey` (Python: `private_key`)  
証明書のプライベートキー。  
`publicKey` (Python: `public_key`)  
証明書のパブリックキー。  
`caCertificates` (Python: `ca_certificates`)  
証明書の CA 証明書チェーン内の認証局 (CA) 証明書のリスト。