

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Gunakan AWS IoT Device SDK untuk berkomunikasi dengan inti Greengrass, komponen lain, dan AWS IoT Core
<a name="interprocess-communication"></a>

Komponen yang berjalan pada perangkat inti Anda dapat menggunakan pustaka komunikasi interproses AWS IoT Greengrass Inti (IPC) AWS IoT Device SDK untuk berkomunikasi dengan AWS IoT Greengrass inti dan komponen Greengrass lainnya. Untuk mengembangkan dan menjalankan komponen khusus yang menggunakan IPC, Anda harus menggunakan AWS IoT Device SDK untuk terhubung ke layanan AWS IoT Greengrass Core IPC dan melakukan operasi IPC.

Antarmuka IPC mendukung dua jenis operasi:
+ **Permintaan/tanggapan**

  Komponen mengirim permintaan ke layanan IPC dan menerima respons yang berisi hasil permintaan.
+ **Berlangganan**

  Komponen mengirim permintaan berlangganan ke layanan IPC dan mengharapkan aliran pesan peristiwa sebagai tanggapan. Komponen menyediakan bagian yang menangani langganan yang menangani pesan peristiwa, kesalahan, dan penutupan aliran. AWS IoT Device SDK Termasuk antarmuka handler dengan respon yang benar dan jenis peristiwa untuk setiap operasi IPC. Untuk informasi selengkapnya, lihat [Berlangganan pengaliran peristiwa IPC](#ipc-subscribe-operations).

**Topics**
+ [Versi klien IPC](#ipc-client-versions)
+ [Didukung SDKs untuk komunikasi antar proses](#ipc-requirements)
+ [Connect ke layanan AWS IoT Greengrass Core IPC](#ipc-service-connect)
+ [Otorisasi komponen untuk melakukan operasi IPC](#ipc-authorization-policies)
+ [Berlangganan pengaliran peristiwa IPC](#ipc-subscribe-operations)
+ [Praktik terbaik IPC](#ipc-best-practices)
+ [Pesan lokal publikasi/berlangganan](ipc-publish-subscribe.md)
+ [Terbitkan/berlangganan pesan MQTT AWS IoT Core](ipc-iot-core-mqtt.md)
+ [Berinteraksilah dengan siklus hidup komponen](ipc-component-lifecycle.md)
+ [Berinteraksilah dengan konfigurasi komponen](ipc-component-configuration.md)
+ [Ambil nilai-nilai rahasia](ipc-secret-manager.md)
+ [Berinteraksi dengan bayangan lokal](ipc-local-shadows.md)
+ [Mengelola penerapan dan komponen lokal](ipc-local-deployments-components.md)
+ [Otentikasi dan otorisasi perangkat klien](ipc-client-device-auth.md)

## Versi klien IPC
<a name="ipc-client-versions"></a>

Dalam versi Java dan Python yang lebih baru SDKs, AWS IoT Greengrass menyediakan versi perbaikan dari klien IPC, yang disebut klien IPC V2. Klien IPC V2:
+ Mengurangi jumlah kode yang perlu Anda tulis untuk menggunakan operasi IPC dan membantu menghindari kesalahan umum yang dapat terjadi dengan klien IPC V1.
+ Memanggil callback handler langganan di thread terpisah, sehingga Anda sekarang dapat menjalankan kode pemblokiran, termasuk panggilan fungsi IPC tambahan, dalam callback handler langganan. Klien IPC V1 menggunakan thread yang sama untuk berkomunikasi dengan server IPC dan memanggil callback handler langganan.
+ Memungkinkan Anda memanggil operasi berlangganan menggunakan ekspresi Lambda (Java) atau fungsi (Python). Klien IPC V1 mengharuskan Anda untuk menentukan kelas handler berlangganan.
+ Menyediakan versi sinkron dan asinkron dari setiap operasi IPC. Klien IPC V1 hanya menyediakan versi asinkron dari setiap operasi.

Kami menyarankan Anda menggunakan klien IPC V2 untuk memanfaatkan peningkatan ini. Namun, banyak contoh dalam dokumentasi ini dan dalam beberapa konten online hanya menunjukkan bagaimana menggunakan klien IPC V1. Anda dapat menggunakan contoh dan tutorial berikut untuk melihat komponen sampel yang menggunakan klien IPC V2:
+ [PublishToTopiccontoh](ipc-publish-subscribe.md#ipc-operation-publishtotopic-examples)
+ [SubscribeToTopiccontoh](ipc-publish-subscribe.md#ipc-operation-subscribetotopic-examples)
+ [Tutorial: Mengembangkan komponen Greengrass yang menunda pembaruan komponen](defer-component-updates-tutorial.md)
+ [Tutorial: Berinteraksi dengan perangkat IoT lokal melalui MQTT](client-devices-tutorial.md)

Saat ini, AWS IoT Device SDK untuk C\$1\$1 v2 hanya mendukung klien IPC V1.

## Didukung SDKs untuk komunikasi antar proses
<a name="ipc-requirements"></a>

Pustaka AWS IoT Greengrass Core IPC disertakan dalam versi berikut AWS IoT Device SDK .


| SDK | Versi minimum | Penggunaan | 
| --- | --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.6.0  |  Lihat [Gunakan AWS IoT Device SDK untuk Java v2 (klien IPC V2)](#ipc-java-v2)  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.9.0  |  Lihat [Gunakan AWS IoT Device SDK untuk Python v2 (klien IPC V2)](#ipc-python-v2)  | 
|  [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  |  Lihat [Gunakan AWS IoT Device SDK untuk C\$1\$1 v2](#ipc-cpp)  | 
|  [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  |  Lihat [Gunakan AWS IoT Device SDK untuk JavaScript v2 (klien IPC V1)](#ipc-nodejs)  | 

## Connect ke layanan AWS IoT Greengrass Core IPC
<a name="ipc-service-connect"></a>

Untuk menggunakan komunikasi interprocess dalam komponen kustom Anda, Anda harus membuat koneksi ke soket server IPC yang dijalankan oleh perangkat lunak AWS IoT Greengrass Core. Selesaikan tugas-tugas berikut untuk mengunduh dan menggunakan AWS IoT Device SDK dalam bahasa pilihan Anda. 

### Gunakan AWS IoT Device SDK untuk Java v2 (klien IPC V2)
<a name="ipc-java-v2"></a>

**Untuk menggunakan AWS IoT Device SDK untuk Java v2 (klien IPC V2)**

1. Unduh [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2) (v1.6.0 atau yang lebih baru).

1. <a name="use-ipc-java-component-install-step"></a>Lakukan salah satu dari berikut ini untuk menjalankan kode kustom Anda dalam komponen Anda:
   + Bangun komponen Anda sebagai file JAR yang menyertakan AWS IoT Device SDK, dan jalankan file JAR ini dalam resep komponen Anda.
   + Tentukan AWS IoT Device SDK JAR sebagai artefak komponen, dan tambahkan artefak itu ke classpath saat Anda menjalankan aplikasi dalam resep komponen Anda.

1. Gunakan kode berikut untuk membuat klien 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);
   }
   ```

### Gunakan AWS IoT Device SDK untuk Python v2 (klien IPC V2)
<a name="ipc-python-v2"></a>

**Untuk menggunakan AWS IoT Device SDK untuk Python v2 (klien IPC V2)**

1. Unduh [AWS IoT Device SDK untuk Python](https://github.com/aws/aws-iot-device-sdk-python-v2) (v1.9.0 atau yang lebih baru).

1. <a name="use-ipc-python-component-install-step"></a>Tambahkan [langkah instalasi](https://github.com/aws/aws-iot-device-sdk-python-v2#installation) SDK ke siklus hidup instalasi dalam resep komponen Anda.

1. Buat koneksi ke layanan AWS IoT Greengrass Core IPC. Gunakan kode berikut untuk membuat klien 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)
   ```

### Gunakan AWS IoT Device SDK untuk C\$1\$1 v2
<a name="ipc-cpp"></a>

<a name="iot-device-sdk-cpp-v2-build-requirements-intro"></a>Untuk membangun AWS IoT Device SDK v2 untuk C \$1\$1, perangkat harus memiliki alat berikut:<a name="iot-device-sdk-cpp-v2-build-requirements"></a>
+ C\$1\$1 11 atau yang lebih baru
+ CMake 3.1 atau yang lebih baru
+ Salah satu penyusun berikut:
  + GCC 4.8 atau yang lebih baru
  + Clang 3.9 atau yang lebih baru
  + MSVC 2015 atau yang lebih baru

**Untuk menggunakan AWS IoT Device SDK untuk C\$1\$1 v2**

1. Unduh [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2) (v1.17.0 atau yang lebih baru).

1. Ikuti [petunjuk penginstalan di README](https://github.com/aws/aws-iot-device-sdk-cpp-v2#Installation) untuk membangun C\$1\$1 v2 dari sumber. AWS IoT Device SDK 

1. Dalam alat bangun C \$1\$1 Anda, tautkan pustaka IPC Greengrass, `AWS::GreengrassIpc-cpp`, yang telah Anda bangun pada langkah sebelumnya. `CMakeLists.txt`Contoh berikut menautkan pustaka Greengrass IPC ke proyek yang Anda bangun. 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. Dalam kode komponen Anda, buat koneksi ke layanan AWS IoT Greengrass Core IPC untuk membuat klien IPC ()`Aws::Greengrass::GreengrassCoreIpcClient`. Anda harus menentukan pengelola siklus hidup koneksi IPC yang menangani koneksi IPC, pemutusan, dan peristiwa kesalahan. Contoh berikut membuat klien IPC dan pengelola siklus hidup koneksi IPC yang mencetak ketika klien IPC terhubung, terputus, dan menemukan kesalahan.

   ```
   #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. Untuk menjalankan kode kustom Anda dalam komponen Anda, bangun kode Anda sebagai artefak biner, dan jalankan artefak biner dalam resep komponen Anda. Atur `Execute` izin artefak `OWNER` untuk mengaktifkan perangkat lunak AWS IoT Greengrass Core menjalankan artefak biner.

   Bagian `Manifests` resep komponen Anda ini mungkin terlihat serupa dengan yang berikut ini.

------
#### [ 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
   ```

------

### Gunakan AWS IoT Device SDK untuk JavaScript v2 (klien IPC V1)
<a name="ipc-nodejs"></a>

<a name="iot-device-sdk-nodejs-build-requirements-intro"></a>Untuk membangun AWS IoT Device SDK for JavaScript v2 untuk digunakan dengan NodeJS, perangkat harus memiliki alat berikut:<a name="iot-device-sdk-nodejs-build-requirements"></a>
+ NodeJS 10.0 atau yang lebih baru
  + Jalankan `node -v` untuk memeriksa versi Node.
+ CMake 3.1 atau yang lebih baru

**Untuk menggunakan AWS IoT Device SDK for JavaScript v2 (klien IPC V1)**

1. Unduh [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2) (v1.12.10 atau yang lebih baru).

1. Ikuti [petunjuk penginstalan di README](https://github.com/aws/aws-iot-device-sdk-js-v2/tree/v1.12.1#installation) untuk membangun AWS IoT Device SDK for JavaScript v2 dari sumber.

1. Buat koneksi ke layanan AWS IoT Greengrass Core IPC. Selesaikan langkah-langkah berikut untuk membuat klien IPC dan membuat sambungan.

1. Gunakan kode berikut untuk membuat klien IPC.

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

1. Gunakan kode berikut untuk membuat sambungan dari komponen Anda ke inti Greengrass.

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

## Otorisasi komponen untuk melakukan operasi IPC
<a name="ipc-authorization-policies"></a>

Untuk mengizinkan komponen kustom Anda untuk menggunakan beberapa operasi IPC, Anda harus menentukan *kebijakan otorisasi* yang memungkinkan komponen untuk melakukan operasi pada sumber daya tertentu. Setiap kebijakan otorisasi menentukan daftar operasi dan daftar sumber daya yang diizinkan oleh kebijakan. Misalnya, layanan IPC publish/subscribe perpesanan mendefinisikan operasi publikasi dan berlangganan untuk sumber daya topik. Anda dapat menentukan wildcard `*` untuk mengizinkan akses ke semua operasi atau semua sumber daya.

Anda menentukan kebijakan otorisasi dengan parameter `accessControl` konfigurasi, yang dapat Anda atur dalam resep komponen atau saat Anda menerapkan komponen. Objek `accessControl` memetakan pengidentifikasi layanan IPC pada daftar kebijakan otorisasi. Anda dapat menentukan beberapa kebijakan otorisasi untuk setiap layanan IPC untuk mengontrol akses. Setiap kebijakan otorisasi memiliki ID kebijakan, yang harus unik di antara semua komponen.

**Tip**  
Untuk membuat kebijakan unik IDs, Anda dapat menggabungkan nama komponen, nama layanan IPC, dan penghitung. Misalnya, komponen bernama `com.example.HelloWorld` mungkin mendefinisikan dua kebijakan publish/subscribe otorisasi dengan yang berikut: IDs  
`com.example.HelloWorld:pubsub:1`
`com.example.HelloWorld:pubsub:2`

Kebijakan otorisasi menggunakan format berikut. Objek ini adalah parameter konfigurasi `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
```

------

### Wildcard dalam kebijakan otorisasi
<a name="ipc-authorization-policy-wildcards"></a>

Anda dapat menggunakan `*` wildcard dalam `resources` elemen kebijakan otorisasi IPC untuk mengizinkan akses ke beberapa sumber daya dalam satu kebijakan otorisasi.
+ Di semua versi inti [Greengrass](greengrass-nucleus-component.md), Anda dapat menentukan `*` satu karakter sebagai sumber daya untuk memungkinkan akses ke semua sumber daya.
+ Di [Greengrass](greengrass-nucleus-component.md) nucleus v2.6.0 dan yang lebih baru, Anda dapat menentukan karakter dalam sumber daya agar sesuai `*` dengan kombinasi karakter apa pun. Misalnya, Anda dapat menentukan `factory/1/devices/Thermostat*/status` untuk mengizinkan akses ke topik status untuk semua perangkat termostat di pabrik, tempat nama setiap perangkat dimulai`Thermostat`.

Saat menentukan kebijakan otorisasi untuk layanan AWS IoT Core MQTT IPC, Anda juga dapat menggunakan wildcard MQTT (dan) untuk mencocokkan beberapa sumber daya. `+` `#` Untuk informasi selengkapnya, lihat [wildcard MQTT dalam kebijakan otorisasi AWS IoT Core MQTT](ipc-iot-core-mqtt.md#ipc-iot-core-mqtt-authorization-mqtt-wildcards) IPC.

### Variabel resep dalam kebijakan otorisasi
<a name="ipc-authorization-policy-recipe-variables"></a>

[Jika Anda menggunakan [Greengrass](greengrass-nucleus-component.md) nucleus v2.6.0 atau yang lebih baru, dan Anda menyetel opsi konfigurasi Greengrass nucleus ke, Anda dapat menggunakan variabel resep dalam kebijakan [interpolateComponentConfiguration](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-interpolate-component-configuration)otorisasi. `true``{iot:thingName}`](component-recipe-reference.md#recipe-variables) Bila Anda memerlukan kebijakan otorisasi yang menyertakan nama perangkat inti, seperti untuk topik MQTT atau bayangan perangkat, Anda dapat menggunakan variabel resep ini untuk mengonfigurasi kebijakan otorisasi tunggal untuk sekelompok perangkat inti. Misalnya, Anda dapat mengizinkan akses komponen ke sumber daya berikut untuk operasi IPC bayangan.

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

### Karakter khusus dalam kebijakan otorisasi
<a name="ipc-authorization-policy-special-characters"></a>

Untuk menentukan literal `*` atau `?` karakter dalam kebijakan otorisasi, Anda harus menggunakan urutan escape. Urutan escape berikut menginstruksikan perangkat lunak AWS IoT Greengrass Core untuk menggunakan nilai literal alih-alih makna khusus karakter. Misalnya, `*` karakter adalah [wildcard](#ipc-authorization-policy-wildcards) yang cocok dengan kombinasi karakter apa pun.


| Karakter literal | Karakter pelarian | Catatan | 
| --- | --- | --- | 
|  `*`  |  `${*}`  |  | 
|  `?`  |  `${?}`  |  AWS IoT Greengrass saat ini tidak mendukung `?` wildcard, yang cocok dengan karakter tunggal mana pun.  | 
|  `$`  |  `${$}`  |  Gunakan urutan escape ini untuk mencocokkan sumber daya yang berisi`${`. Misalnya, untuk mencocokkan sumber daya bernama`${resourceName}`, Anda harus menentukan`${$}{resourceName}`. Jika tidak, untuk mencocokkan sumber daya yang berisi`$`, Anda dapat menggunakan literal`$`, seperti untuk mengizinkan akses ke topik yang dimulai dengan`$aws`.  | 

### Contoh kebijakan otorisasi
<a name="ipc-authorization-policy-examples"></a>

Anda dapat mereferensikan contoh kebijakan otorisasi berikut untuk membantu Anda mengonfigurasi kebijakan otorisasi untuk komponen Anda.

**Example Contoh resep komponen dengan kebijakan otorisasi**  
Contoh resep komponen berikut meliputi objek `accessControl` yang menentukan kebijakan otorisasi. Kebijakan ini mengotorisasi komponen `com.example.HelloWorld` untuk dipublikasikan ke topik `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 Contoh pembaruan konfigurasi komponen dengan kebijakan otorisasi**  
Contoh pembaruan konfigurasi berikut dalam penerapan menentukan untuk mengonfigurasi komponen dengan `accessControl` objek yang mendefinisikan kebijakan otorisasi. Kebijakan ini mengotorisasi komponen `com.example.HelloWorld` untuk dipublikasikan ke topik `test/topic`.    
**Konfigurasi untuk digabungkan**  

```
{
  "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"
        ]
      }
    }
  }
}
```
Perintah berikut membuat penyebaran ke perangkat inti.  

```
aws greengrassv2 create-deployment --cli-input-json file://hello-world-deployment.json
```
`hello-world-deployment.json`File berisi dokumen JSON berikut.  

```
{
  "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\"]}}}}"
      }
    }
  }
}
```
Perintah [Greengrass CLI](greengrass-cli-component.md) berikut membuat penerapan lokal pada perangkat inti.  

```
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`File berisi dokumen JSON berikut.  

```
{
  "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"
            ]
          }
        }
      }
    }
  }
}
```

## Berlangganan pengaliran peristiwa IPC
<a name="ipc-subscribe-operations"></a>

Anda dapat menggunakan operasi IPC untuk berlangganan aliran peristiwa pada perangkat inti Greengrass. Untuk menggunakan operasi berlangganan, tentukan *penanganan langganan* dan buat permintaan ke layanan IPC. Kemudian, klien IPC menjalankan fungsi penanganan langganan setiap kali perangkat inti mengalirkan pesan peristiwa ke komponen Anda.

Anda dapat menutup suatu langganan untuk menghentikan pemrosesan pesan peristiwa. Untuk melakukannya, hubungi `closeStream()` (Java), `close()` (Python), atau `Close()` (C\$1\$1) pada objek operasi langganan yang Anda gunakan untuk membuka langganan.

Layanan AWS IoT Greengrass Core IPC mendukung operasi berlangganan berikut:
+ [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**
+ [Tentukan penanganan langganan](#ipc-define-subscription-handlers)
+ [Contoh penanganan langganan](#ipc-subscription-handler-examples)

### Tentukan penanganan langganan
<a name="ipc-define-subscription-handlers"></a>

Untuk menentukan handler langganan, tentukan fungsi callback yang menangani pesan peristiwa, kesalahan, dan penutupan aliran. Jika Anda menggunakan klien IPC V1, Anda harus mendefinisikan fungsi-fungsi ini di kelas. Jika Anda menggunakan IPC client V2, yang tersedia di versi Java dan SDKs Python yang lebih baru, Anda dapat menentukan fungsi-fungsi ini tanpa membuat kelas handler berlangganan.

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

Jika Anda menggunakan klien IPC V1, Anda harus mengimplementasikan antarmuka generik`software.amazon.awssdk.eventstreamrpc.StreamResponseHandler<StreamEventType>`. *StreamEventType*adalah jenis pesan acara untuk operasi berlangganan. Tentukan fungsi berikut untuk menangani pesan peristiwa, kesalahan, dan penutupan aliran.

Jika Anda menggunakan klien IPC V2, Anda dapat menentukan fungsi-fungsi ini di luar kelas handler langganan atau menggunakan ekspresi [lambda](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html).

`void onStreamEvent(StreamEventType event)`  
Callback yang dipanggil oleh klien IPC ketika menerima pesan peristiwa, seperti pesan MQTT atau notifikasi pembaruan komponen.

`boolean onStreamError(Throwable error)`  
Callback yang dipanggil oleh klien IPC ketika terjadi kesalahan aliran.  
<a name="ipc-subscription-handler-on-stream-error-return-value"></a>Kembali BETUL untuk menutup aliran langganan sebagai akibat dari kesalahan, atau kembali SALAH untuk membuat aliran tetap terbuka.

`void onStreamClosed()`  
Callback yang dipanggil oleh klien IPC ketika aliran menutup.

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

Jika Anda menggunakan klien IPC V1, Anda harus memperluas kelas penangan respons aliran yang sesuai dengan operasi langganan. AWS IoT Device SDK Termasuk kelas handler berlangganan untuk setiap operasi berlangganan. *StreamEventType*adalah jenis pesan acara untuk operasi berlangganan. Tentukan fungsi berikut untuk menangani pesan peristiwa, kesalahan, dan penutupan aliran.

Jika Anda menggunakan klien IPC V2, Anda dapat menentukan fungsi-fungsi ini di luar kelas handler langganan atau menggunakan ekspresi [lambda](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions).

`def on_stream_event(self, event: StreamEventType) -> None`  
Callback yang dipanggil oleh klien IPC ketika menerima pesan peristiwa, seperti pesan MQTT atau notifikasi pembaruan komponen.

`def on_stream_error(self, error: Exception) -> bool`  
Callback yang dipanggil oleh klien IPC ketika terjadi kesalahan aliran.  
<a name="ipc-subscription-handler-on-stream-error-return-value"></a>Kembali BETUL untuk menutup aliran langganan sebagai akibat dari kesalahan, atau kembali SALAH untuk membuat aliran tetap terbuka.

`def on_stream_closed(self) -> None`  
Callback yang dipanggil oleh klien IPC ketika aliran menutup.

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

Terapkan kelas yang diturunkan dari penanganan respons aliran yang sesuai dengan operasi berlangganan. AWS IoT Device SDK Termasuk kelas dasar handler berlangganan untuk setiap operasi berlangganan. *StreamEventType*adalah jenis pesan acara untuk operasi berlangganan. Tentukan fungsi berikut untuk menangani pesan peristiwa, kesalahan, dan penutupan aliran.

`void OnStreamEvent(StreamEventType *event)`  
Callback yang dipanggil oleh klien IPC ketika menerima pesan peristiwa, seperti pesan MQTT atau notifikasi pembaruan komponen.

`bool OnStreamError(OperationError *error)`  
Callback yang dipanggil oleh klien IPC ketika terjadi kesalahan aliran.  
<a name="ipc-subscription-handler-on-stream-error-return-value"></a>Kembali BETUL untuk menutup aliran langganan sebagai akibat dari kesalahan, atau kembali SALAH untuk membuat aliran tetap terbuka.

`void OnStreamClosed()`  
Callback yang dipanggil oleh klien IPC ketika aliran menutup.

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

Terapkan kelas yang diturunkan dari penanganan respons aliran yang sesuai dengan operasi berlangganan. AWS IoT Device SDK Termasuk kelas dasar handler berlangganan untuk setiap operasi berlangganan. *StreamEventType*adalah jenis pesan acara untuk operasi berlangganan. Tentukan fungsi berikut untuk menangani pesan peristiwa, kesalahan, dan penutupan aliran.

`on(event: 'ended', listener: StreamingOperationEndedListener)`  
Callback yang dipanggil oleh klien IPC ketika aliran menutup.

`on(event: 'streamError', listener: StreamingRpcErrorListener)`  
Callback yang dipanggil oleh klien IPC ketika terjadi kesalahan aliran.  
<a name="ipc-subscription-handler-on-stream-error-return-value"></a>Kembali BETUL untuk menutup aliran langganan sebagai akibat dari kesalahan, atau kembali SALAH untuk membuat aliran tetap terbuka.

`on(event: 'message', listener: (message: InboundMessageType) => void)`  
Callback yang dipanggil oleh klien IPC ketika menerima pesan peristiwa, seperti pesan MQTT atau notifikasi pembaruan komponen.

------

### Contoh penanganan langganan
<a name="ipc-subscription-handler-examples"></a>

Contoh berikut menunjukkan cara menggunakan operasi [SubscribeToTopic](ipc-publish-subscribe.md#ipc-operation-subscribetotopic) dan penanganan langganan pada pesan publikasi/langganan lokal.

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

**Example Contoh: Berlangganan publish/subscribe pesan lokal**  <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 Contoh: Berlangganan publish/subscribe pesan lokal**  <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 Contoh: Berlangganan publish/subscribe pesan lokal**  <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 Contoh: Berlangganan publish/subscribe pesan lokal**  <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 Contoh: Berlangganan publish/subscribe pesan lokal**  

```
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 Contoh: Berlangganan publish/subscribe pesan lokal**  

```
#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 Contoh: Berlangganan publish/subscribe pesan lokal**  

```
#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);
    }
}
```

------

## Praktik terbaik IPC
<a name="ipc-best-practices"></a>

Praktik terbaik untuk menggunakan IPC dalam komponen khusus berbeda antara klien IPC V1 dan klien IPC V2. Ikuti praktik terbaik untuk versi klien IPC yang Anda gunakan.

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

Klien IPC V2 menjalankan fungsi callback di thread terpisah, jadi dibandingkan dengan klien IPC V1, ada lebih sedikit pedoman yang harus Anda ikuti saat Anda menggunakan IPC dan menulis fungsi penangan langganan.
+ <a name="ipc-best-practice-reuse-one-client"></a>**Gunakan kembali satu klien IPC**

  Setelah Anda membuat klien IPC, tetap buka dan gunakan kembali untuk semua operasi IPC. Membuat beberapa klien menggunakan sumber daya tambahan dan dapat mengakibatkan kebocoran sumber daya.
+ **Tangani pengecualian**

  Klien IPC V2 mencatat pengecualian yang tidak tertangkap dalam fungsi penangan langganan. Anda harus menangkap pengecualian dalam fungsi handler Anda untuk menangani kesalahan yang terjadi dalam kode Anda.

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

Klien IPC V1 menggunakan utas tunggal yang berkomunikasi dengan server IPC dan memanggil penangan langganan. Anda harus mempertimbangkan perilaku sinkron ini ketika Anda menuliskan fungsi penanganan langganan.
+ <a name="ipc-best-practice-reuse-one-client"></a>**Gunakan kembali satu klien IPC**

  Setelah Anda membuat klien IPC, tetap buka dan gunakan kembali untuk semua operasi IPC. Membuat beberapa klien menggunakan sumber daya tambahan dan dapat mengakibatkan kebocoran sumber daya.
+ **Jalankan kode pemblokiran secara asinkron**

  Klien IPC V1 tidak dapat mengirim permintaan baru atau memproses pesan acara baru saat utas diblokir. Anda harus menjalankan kode pemblokiran di thread terpisah yang Anda jalankan dari fungsi handler. Kode pemblokiran mencakup `sleep` panggilan, loop yang terus berjalan, dan I/O permintaan sinkron yang membutuhkan waktu untuk diselesaikan.
+ **Kirim permintaan IPC baru secara asinkron**

  Klien IPC V1 tidak dapat mengirim permintaan baru dari dalam fungsi handler langganan, karena permintaan memblokir fungsi handler jika Anda menunggu respons. Anda harus mengirim permintaan IPC di thread terpisah yang Anda jalankan dari fungsi handler.
+ **Tangani pengecualian**

  Klien IPC V1 tidak menangani pengecualian yang tidak tertangkap dalam fungsi penangan langganan. Jika fungsi penanganan Anda melempar pengecualian, langganan tersebut akan menutup, dan pengecualian tidak akan muncul dalam log komponen Anda. Anda harus menangkap pengecualian dalam fungsi handler Anda untuk menjaga langganan tetap terbuka dan mencatat kesalahan yang terjadi dalam kode Anda.

------

# Pesan lokal publikasi/berlangganan
<a name="ipc-publish-subscribe"></a>

Olah pesan publikasi/berlangganan (pubsub) memungkinkan Anda untuk mengirim dan menerima pesan ke topik. Komponen dapat mempublikasikan pesan pada topik untuk mengirim pesan ke komponen lain. Kemudian, komponen yang berlangganan topik itu dapat bertindak atas pesan yang diterimanya.

**catatan**  
Anda tidak dapat menggunakan layanan publish/subscribe IPC ini untuk mempublikasikan atau berlangganan AWS IoT Core MQTT. Untuk informasi selengkapnya tentang cara bertukar pesan dengan AWS IoT Core MQTT, lihat. [Terbitkan/berlangganan pesan MQTT AWS IoT Core](ipc-iot-core-mqtt.md)

**Topics**
+ [SDK (Versi Minimum)](#ipc-publish-subscribe-sdk-versions)
+ [Otorisasi](#ipc-publish-subscribe-authorization)
+ [PublishToTopic](#ipc-operation-publishtotopic)
+ [SubscribeToTopic](#ipc-operation-subscribetotopic)
+ [Contoh](#ipc-publish-subscribe-examples)

## SDK (Versi Minimum)
<a name="ipc-publish-subscribe-sdk-versions"></a>

Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk mempublikasikan dan berlangganan pesan ke dan dari topik lokal.


| SDK | Versi minimum | 
| --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK untuk 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  | 

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

Untuk menggunakan publish/subscribe pesan lokal dalam komponen kustom, Anda harus menentukan kebijakan otorisasi yang memungkinkan komponen Anda mengirim dan menerima pesan ke topik. Untuk informasi tentang cara menentukan kebijakan otorisasi, lihat [Otorisasi komponen untuk melakukan operasi IPC](interprocess-communication.md#ipc-authorization-policies).

Kebijakan otorisasi untuk publish/subscribe pengiriman pesan memiliki properti berikut.

**Pengenal layanan IPC:** `aws.greengrass.ipc.pubsub`


| Operasi | Deskripsi | Sumber daya | 
| --- | --- | --- | 
|  `aws.greengrass#PublishToTopic`  |  Memungkinkan komponen untuk mempublikasikan pesan ke topik MQTT yang Anda tentukan.  |  String topik, seperti`test/topic`. Gunakan `*` untuk mencocokkan kombinasi karakter apa pun dalam suatu topik. String topik ini mendukung wildcard topik MQTT (`#` dan `+`).  | 
|  `aws.greengrass#SubscribeToTopic`  |  Memungkinkan komponen untuk berlangganan pesan untuk topik yang Anda tentukan.  |  String topik, seperti`test/topic`. Gunakan `*` untuk mencocokkan kombinasi karakter apa pun dalam suatu topik. <a name="ipc-local-publish-subscribe-authorization-mqtt-wildcards"></a>Di [Greengrass](greengrass-nucleus-component.md) nucleus v2.6.0 dan yang lebih baru, Anda dapat berlangganan topik yang berisi wildcard topik MQTT (dan). `#` `+` String topik ini mendukung wildcard topik MQTT sebagai karakter literal. Misalnya, jika kebijakan otorisasi komponen memberikan akses ke`test/topic/#`, komponen dapat berlangganan`test/topic/#`, tetapi tidak dapat berlangganan. `test/topic/filter`  | 
|  `*`  |  Memungkinkan komponen untuk mempublikasikan dan berlanggan pesan untuk topik yang Anda tentukan.  |  String topik, seperti`test/topic`. Gunakan `*` untuk mencocokkan kombinasi karakter apa pun dalam suatu topik. <a name="ipc-local-publish-subscribe-authorization-mqtt-wildcards"></a>Di [Greengrass](greengrass-nucleus-component.md) nucleus v2.6.0 dan yang lebih baru, Anda dapat berlangganan topik yang berisi wildcard topik MQTT (dan). `#` `+` String topik ini mendukung wildcard topik MQTT sebagai karakter literal. Misalnya, jika kebijakan otorisasi komponen memberikan akses ke`test/topic/#`, komponen dapat berlangganan`test/topic/#`, tetapi tidak dapat berlangganan. `test/topic/filter`  | 

### Contoh kebijakan otorisasi
<a name="ipc-publish-subscribe-authorization-policy-examples"></a>

Anda dapat mereferensikan contoh kebijakan otorisasi berikut untuk membantu Anda mengonfigurasi kebijakan otorisasi untuk komponen Anda.

**Example Contoh kebijakan otorisasi**  
Kebijakan otorisasi contoh berikut ini memungkinkan komponen untuk mempublikasikan dan berlangganan semua topik.  

```
{
  "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>

Publikasikan pesan ke topik.

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

Permintaan operasi ini memiliki parameter berikut:

`topic`  
Topik yang pesannya dipublikasikan.

`publishMessage`(Python:) `publish_message`  
Pesan yang akan dipublikasikan. Objek ini, `PublishMessage`, berisi informasi berikut. Anda harus menentukan salah satu dari `jsonMessage` dan `binaryMessage`.  <a name="ipc-publish-subscribe-message-shape"></a>  
`jsonMessage`(Python:) `json_message`  
(Opsional) Sebuah pesan JSON. Objek ini, `JsonMessage`, berisi informasi berikut:    
`message`  
Pesan JSON sebagai objek.  
`context`  <a name="ipc-publish-subscribe-message-context-variable"></a>
Konteks pesan, seperti topik di mana pesan itu diterbitkan.  
[Fitur ini tersedia untuk v2.6.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md) Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk mengakses konteks pesan.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-publish-subscribe.html)
Perangkat lunak AWS IoT Greengrass Core menggunakan objek pesan yang sama dalam `PublishToTopic` dan `SubscribeToTopic` operasi. Perangkat lunak AWS IoT Greengrass Core menetapkan objek konteks ini dalam pesan saat Anda berlangganan, dan mengabaikan objek konteks ini dalam pesan yang Anda terbitkan.
Objek ini, `MessageContext`, berisi informasi berikut:    
`topic`  
Topik di mana pesan itu diterbitkan.  
`binaryMessage`(Python:) `binary_message`  
(Opsional) Sebuah pesan biner. Objek ini, `BinaryMessage`, berisi informasi berikut:    
`message`  
Pesan biner sebagai gumpalan.  
`context`  <a name="ipc-publish-subscribe-message-context-variable"></a>
Konteks pesan, seperti topik di mana pesan itu diterbitkan.  
[Fitur ini tersedia untuk v2.6.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md) Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk mengakses konteks pesan.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-publish-subscribe.html)
Perangkat lunak AWS IoT Greengrass Core menggunakan objek pesan yang sama dalam `PublishToTopic` dan `SubscribeToTopic` operasi. Perangkat lunak AWS IoT Greengrass Core menetapkan objek konteks ini dalam pesan saat Anda berlangganan, dan mengabaikan objek konteks ini dalam pesan yang Anda terbitkan.
Objek ini, `MessageContext`, berisi informasi berikut:    
`topic`  
Topik di mana pesan itu diterbitkan.

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

Operasi ini tidak memberikan informasi apa pun dalam tanggapannya.

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

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Publikasikan pesan biner**  

```
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 Contoh: Publikasikan pesan biner**  

```
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 Contoh: Publikasikan pesan biner**  

```
#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 Contoh: Publikasikan pesan biner**  

```
    
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 Contoh: Publikasikan pesan biner**  

```
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 Contoh: Publikasikan pesan biner**  

```
#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 Contoh: Publikasikan pesan biner**  

```
#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>

Berlangganan pesan tentang suatu topik.

<a name="ipc-subscribe-operation-note"></a>Operasi ini adalah operasi berlangganan di mana Anda berlangganan aliran pesan peristiwa. Untuk menggunakan operasi ini, tentukan bagian yang menangani respons aliran dengan fungsi yang menangani pesan peristiwa, kesalahan, dan penutupan aliran. Untuk informasi selengkapnya, lihat [Berlangganan pengaliran peristiwa IPC](interprocess-communication.md#ipc-subscribe-operations).

**Jenis pesan peristiwa:** `SubscriptionResponseMessage`

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

Permintaan operasi ini memiliki parameter berikut:

`topic`  
Topik yang harus dijadikan langganan.  
Di [Greengrass](greengrass-nucleus-component.md) nucleus v2.6.0 dan yang lebih baru, topik ini mendukung wildcard topik MQTT (dan). `#` `+`

`receiveMode`(Python:) `receive_mode`  
(Opsional) Perilaku yang menentukan apakah komponen menerima pesan dari dirinya sendiri. Anda dapat mengubah perilaku ini agar komponen dapat bertindak berdasarkan pesannya sendiri. Perilaku default tergantung pada apakah topik berisi wildcard MQTT. Pilih dari salah satu pilihan berikut:  
+ `RECEIVE_ALL_MESSAGES`— Menerima semua pesan yang cocok dengan topik, termasuk pesan dari komponen yang berlangganan.

  Mode ini adalah opsi default saat Anda berlangganan topik yang tidak berisi wildcard MQTT.
+ `RECEIVE_MESSAGES_FROM_OTHERS`— Menerima semua pesan yang cocok dengan topik, kecuali pesan dari komponen yang berlangganan.

  Mode ini adalah opsi default saat Anda berlangganan topik yang berisi wildcard MQTT.
[Fitur ini tersedia untuk v2.6.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md) Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk mengatur mode terima.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-publish-subscribe.html)

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

Tanggapan operasi ini memiliki informasi berikut:

`messages`  
Aliran pesan. Objek ini, `SubscriptionResponseMessage`, berisi informasi berikut. Setiap pesan berisi `jsonMessage` atau `binaryMessage`.  <a name="ipc-publish-subscribe-message-shape"></a>  
`jsonMessage`(Python:) `json_message`  
(Opsional) Sebuah pesan JSON. Objek ini, `JsonMessage`, berisi informasi berikut:    
`message`  
Pesan JSON sebagai objek.  
`context`  <a name="ipc-publish-subscribe-message-context-variable"></a>
Konteks pesan, seperti topik di mana pesan itu diterbitkan.  
[Fitur ini tersedia untuk v2.6.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md) Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk mengakses konteks pesan.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-publish-subscribe.html)
Perangkat lunak AWS IoT Greengrass Core menggunakan objek pesan yang sama dalam `PublishToTopic` dan `SubscribeToTopic` operasi. Perangkat lunak AWS IoT Greengrass Core menetapkan objek konteks ini dalam pesan saat Anda berlangganan, dan mengabaikan objek konteks ini dalam pesan yang Anda terbitkan.
Objek ini, `MessageContext`, berisi informasi berikut:    
`topic`  
Topik di mana pesan itu diterbitkan.  
`binaryMessage`(Python:) `binary_message`  
(Opsional) Sebuah pesan biner. Objek ini, `BinaryMessage`, berisi informasi berikut:    
`message`  
Pesan biner sebagai gumpalan.  
`context`  <a name="ipc-publish-subscribe-message-context-variable"></a>
Konteks pesan, seperti topik di mana pesan itu diterbitkan.  
[Fitur ini tersedia untuk v2.6.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md) Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk mengakses konteks pesan.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-publish-subscribe.html)
Perangkat lunak AWS IoT Greengrass Core menggunakan objek pesan yang sama dalam `PublishToTopic` dan `SubscribeToTopic` operasi. Perangkat lunak AWS IoT Greengrass Core menetapkan objek konteks ini dalam pesan saat Anda berlangganan, dan mengabaikan objek konteks ini dalam pesan yang Anda terbitkan.
Objek ini, `MessageContext`, berisi informasi berikut:    
`topic`  
Topik di mana pesan itu diterbitkan.

`topicName`(Python:) `topic_name`  
Topik yang pesannya dipublikasikan.  
Properti ini saat ini tidak digunakan. Di [Greengrass](greengrass-nucleus-component.md) nucleus v2.6.0 dan yang lebih baru, Anda bisa mendapatkan nilai dari `SubscriptionResponseMessage` a untuk mendapatkan topik `(jsonMessage|binaryMessage).context.topic` di mana pesan itu diterbitkan.

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

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Berlangganan publish/subscribe pesan lokal**  <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 Contoh: Berlangganan publish/subscribe pesan lokal**  <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 Contoh: Berlangganan publish/subscribe pesan lokal**  <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 Contoh: Berlangganan publish/subscribe pesan lokal**  <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 Contoh: Berlangganan publish/subscribe pesan lokal**  

```
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 Contoh: Berlangganan publish/subscribe pesan lokal**  

```
#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 Contoh: Berlangganan publish/subscribe pesan lokal**  

```
#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);
    }
}
```

------

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

Gunakan contoh berikut untuk mempelajari cara menggunakan layanan publish/subscribe IPC di komponen Anda.

### Contoh publish/subscribe penerbit (Java, klien IPC V1)
<a name="ipc-publish-subscribe-example-publisher-java"></a>

Contoh resep berikut memungkinkan komponen untuk mempublikasikan ke semua topik.

------
#### [ 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
```

------

Aplikasi contoh Java berikut ini menunjukkan cara menggunakan layanan IPC publikasi/berlangganan untuk mempublikasikan pesan ke komponen lain.

```
/* 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);
        }
    }
}
```

### Contoh publish/subscribe pelanggan (Java, klien IPC V1)
<a name="ipc-publish-subscribe-example-subscriber-java"></a>

Contoh resep berikut memungkinkan komponen untuk berlangganan semua topik.

------
#### [ 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
```

------

Aplikasi contoh Java berikut ini menunjukkan cara menggunakan layanan IPC publikasi/berlangganan untuk berlangganan pesan ke komponen lain.

```
/* 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.");
        }
    }
}
```

### Contoh publish/subscribe penerbit (Python, klien IPC V1)
<a name="ipc-publish-subscribe-example-publisher-python"></a>

Contoh resep berikut memungkinkan komponen untuk mempublikasikan ke semua topik.

------
#### [ 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
```

------

Aplikasi contoh Python berikut ini menunjukkan cara menggunakan layanan IPC publikasi/berlangganan untuk mempublikasikan pesan ke komponen lain.

```
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)
```

### Contoh publish/subscribe pelanggan (Python, klien IPC V1)
<a name="ipc-publish-subscribe-example-subscriber-python"></a>

Contoh resep berikut memungkinkan komponen untuk berlangganan semua topik.

------
#### [ 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
```

------

Aplikasi contoh Python berikut ini menunjukkan cara menggunakan layanan IPC publikasi/berlangganan untuk berlangganan pesan ke komponen lain.

```
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)
```

### Contoh publish/subscribe penerbit (C \$1\$1, klien IPC V1)
<a name="ipc-publish-subscribe-example-publisher-cpp"></a>

Contoh resep berikut memungkinkan komponen untuk mempublikasikan ke semua topik.

------
#### [ 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
```

------

Aplikasi contoh C\$1\$1 berikut ini menunjukkan cara menggunakan layanan IPC publikasi/berlangganan untuk mempublikasikan pesan ke komponen lain.

```
#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;
}
```

### Contoh publish/subscribe pelanggan (C \$1\$1, klien IPC V1)
<a name="ipc-publish-subscribe-example-subscriber-cpp"></a>

Contoh resep berikut memungkinkan komponen untuk berlangganan semua topik.

------
#### [ 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
```

------

Aplikasi contoh C\$1\$1 berikut ini menunjukkan cara menggunakan layanan IPC publikasi/berlangganan untuk berlangganan pesan ke komponen lain.

```
#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;
}
```

### Contoh publish/subscribe penerbit (Rust)
<a name="ipc-publish-subscribe-example-publisher-rust"></a>

Contoh resep berikut memungkinkan komponen untuk mempublikasikan ke semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut aplikasi Rust menunjukkan bagaimana menggunakan layanan IPC terbitkan/berlangganan untuk mempublikasikan pesan ke komponen lain.

```
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}");
}
```

### Contoh publish/subscribe pelanggan (Rust)
<a name="ipc-publish-subscribe-example-subscriber-rust"></a>

Contoh resep berikut memungkinkan komponen untuk berlangganan semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut aplikasi Rust menunjukkan cara menggunakan layanan IPC terbitkan/berlangganan untuk berlangganan pesan dari komponen lain.

```
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));
    }
}
```

### Contoh publish/subscribe penerbit (C)
<a name="ipc-publish-subscribe-example-publisher-c"></a>

Contoh resep berikut memungkinkan komponen untuk mempublikasikan ke semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut C aplikasi menunjukkan bagaimana menggunakan layanan IPC terbitkan/berlangganan untuk mempublikasikan pesan ke komponen lain.

```
#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
    );
}
```

### Contoh publish/subscribe pelanggan (C)
<a name="ipc-publish-subscribe-example-subscriber-c"></a>

Contoh resep berikut memungkinkan komponen untuk berlangganan semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut C aplikasi menunjukkan bagaimana menggunakan layanan IPC terbitkan/berlangganan untuk berlangganan pesan dari komponen lain.

```
#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);
}
```

### Contoh publish/subscribe penerbit (C \$1\$1, SDK Komponen)
<a name="ipc-publish-subscribe-example-publisher-cpp-component-sdk"></a>

Contoh resep berikut memungkinkan komponen untuk mempublikasikan ke semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Aplikasi contoh C\$1\$1 berikut ini menunjukkan cara menggunakan layanan IPC publikasi/berlangganan untuk mempublikasikan pesan ke komponen lain.

```
#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";
}
```

### Contoh publish/subscribe pelanggan (C \$1\$1, Component SDK)
<a name="ipc-publish-subscribe-example-subscriber-cpp-component-sdk"></a>

Contoh resep berikut memungkinkan komponen untuk berlangganan semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut aplikasi C\$1\$1 menunjukkan bagaimana menggunakan layanan IPC terbitkan/berlangganan untuk berlangganan pesan dari komponen lain.

```
#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);
    }
}
```

# Terbitkan/berlangganan pesan MQTT AWS IoT Core
<a name="ipc-iot-core-mqtt"></a>

Layanan AWS IoT Core MQTT messaging IPC memungkinkan Anda mengirim dan menerima pesan MQTT ke dan dari. AWS IoT Core Komponen dapat mempublikasikan pesan ke AWS IoT Core dan berlangganan topik untuk bertindak atas pesan MQTT dari sumber lain. *Untuk informasi selengkapnya tentang AWS IoT Core implementasi MQTT, lihat [MQTT](https://docs.aws.amazon.com/iot/latest/developerguide/mqtt.html) di Panduan Pengembang.AWS IoT Core *

**catatan**  
Layanan MQTT messaging IPC ini memungkinkan Anda bertukar pesan dengan. AWS IoT Core Untuk informasi selengkapnya tentang cara bertukar pesan antar komponen, lihat [Pesan lokal publikasi/berlangganan](ipc-publish-subscribe.md).

**Topics**
+ [SDK (Versi Minimum)](#ipc-iot-core-mqtt-sdk-versions)
+ [Otorisasi](#ipc-iot-core-mqtt-authorization)
+ [PublishToIoTCore](#ipc-operation-publishtoiotcore)
+ [SubscribeToIoTCore](#ipc-operation-subscribetoiotcore)
+ [Contoh](#ipc-iot-core-mqtt-examples)

## SDK (Versi Minimum)
<a name="ipc-iot-core-mqtt-sdk-versions"></a>

Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk mempublikasikan dan berlangganan pesan MQTT ke dan dari. AWS IoT Core


| SDK | Versi minimum | 
| --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

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

Untuk menggunakan pesan AWS IoT Core MQTT dalam komponen kustom, Anda harus menentukan kebijakan otorisasi yang memungkinkan komponen Anda mengirim dan menerima pesan tentang topik. Untuk informasi tentang cara menentukan kebijakan otorisasi, lihat [Otorisasi komponen untuk melakukan operasi IPC](interprocess-communication.md#ipc-authorization-policies).

Kebijakan otorisasi untuk pesan AWS IoT Core MQTT memiliki properti berikut.

**Pengenal layanan IPC:** `aws.greengrass.ipc.mqttproxy`


| Operasi | Deskripsi | Sumber daya | 
| --- | --- | --- | 
|  `aws.greengrass#PublishToIoTCore`  |  Memungkinkan komponen untuk mempublikasikan pesan AWS IoT Core pada topik MQTT yang Anda tentukan.  |  Topik string, seperti `test/topic`, atau `*` untuk mengizinkan akses ke semua topik. Anda dapat menggunakan wildcard topik MQTT (`#`dan`+`) untuk mencocokkan beberapa sumber daya.  | 
|  `aws.greengrass#SubscribeToIoTCore`  |  Memungkinkan komponen untuk berlangganan pesan dari AWS IoT Core topik yang Anda tentukan.  |  Topik string, seperti `test/topic`, atau `*` untuk mengizinkan akses ke semua topik. Anda dapat menggunakan wildcard topik MQTT (`#`dan`+`) untuk mencocokkan beberapa sumber daya.  | 
|  `*`  |  Memungkinkan komponen untuk mempublikasikan dan berlangganan pesan AWS IoT Core MQTT untuk topik yang Anda tentukan.  |  Topik string, seperti `test/topic`, atau `*` untuk mengizinkan akses ke semua topik. Anda dapat menggunakan wildcard topik MQTT (`#`dan`+`) untuk mencocokkan beberapa sumber daya.  | 

### Wildcard MQTT dalam kebijakan otorisasi MQTT AWS IoT Core
<a name="ipc-iot-core-mqtt-authorization-mqtt-wildcards"></a>

Anda dapat menggunakan wildcard MQTT dalam kebijakan otorisasi AWS IoT Core MQTT IPC. Komponen dapat mempublikasikan dan berlangganan topik yang cocok dengan filter topik yang Anda izinkan dalam kebijakan otorisasi. Misalnya, jika kebijakan otorisasi komponen memberikan akses ke`test/topic/#`, komponen dapat berlangganan`test/topic/#`, dan dapat mempublikasikan dan berlangganan. `test/topic/filter`

### Variabel resep dalam kebijakan AWS IoT Core otorisasi MQTT
<a name="ipc-iot-core-mqtt-authorization-recipe-variables"></a>

Jika Anda menggunakan v2.6.0 atau yang lebih baru dari [inti Greengrass, Anda dapat menggunakan variabel resep](greengrass-nucleus-component.md) dalam kebijakan otorisasi. `{iot:thingName}` Fitur ini memungkinkan Anda mengonfigurasi kebijakan otorisasi tunggal untuk sekelompok perangkat inti, di mana setiap perangkat inti hanya dapat mengakses topik yang berisi namanya sendiri. Misalnya, Anda dapat mengizinkan akses komponen ke sumber daya topik berikut.

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

Untuk informasi selengkapnya, lihat [Variabel resep](component-recipe-reference.md#recipe-variables) dan [Gunakan variabel resep dalam menggabungkan pembaruan](update-component-configurations.md#merge-configuration-update-recipe-variables).

### Contoh kebijakan otorisasi
<a name="ipc-iot-core-mqtt-authorization-policy-examples"></a>

Anda dapat mereferensikan contoh kebijakan otorisasi berikut untuk membantu Anda mengonfigurasi kebijakan otorisasi untuk komponen Anda.

**Example Contoh kebijakan otorisasi dengan akses tidak terbatas**  
Kebijakan otorisasi contoh berikut ini memungkinkan komponen untuk mempublikasikan dan berlangganan semua topik.  

```
{
  "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 Contoh kebijakan otorisasi dengan akses terbatas**  
Contoh kebijakan otorisasi berikut memungkinkan komponen untuk menerbitkan dan berlangganan dua topik bernama `factory/1/events` dan`factory/1/actions`.  

```
{
  "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 Contoh kebijakan otorisasi untuk sekelompok perangkat inti**  
[Contoh ini menggunakan fitur yang tersedia untuk v2.6.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md) Greengrass nucleus v2.6.0 menambahkan dukungan untuk [sebagian besar variabel resep](component-recipe-reference.md#recipe-variables), seperti, dalam konfigurasi komponen. `{iot:thingName}`
Contoh kebijakan otorisasi berikut memungkinkan komponen untuk menerbitkan dan berlangganan topik yang berisi nama perangkat inti yang menjalankan komponen.  

```
{
  "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>

Menerbitkan pesan MQTT ke AWS IoT Core topik.

Saat Anda mempublikasikan pesan MQTT ke AWS IoT Core, ada kuota 100 transaksi per detik. Jika Anda melebihi kuota ini, pesan akan diantrian untuk diproses di perangkat Greengrass. Ada juga kuota 512 Kb data per detik dan kuota akun sebesar 20.000 publikasi per detik (2.000 di beberapa). Wilayah AWS Untuk informasi selengkapnya tentang batas broker pesan MQTT AWS IoT Core, lihat batas dan [AWS IoT Core kuota broker pesan dan protokol](https://docs.aws.amazon.com/general/latest/gr/iot-core.html#message-broker-limits). 

Jika Anda melebihi kuota ini, perangkat Greengrass membatasi penerbitan pesan. AWS IoT Core Pesan disimpan dalam spooler di memori. Secara default, memori yang dialokasikan ke spooler adalah 2,5 Mb. Jika spooler terisi, pesan baru ditolak. Anda dapat meningkatkan ukuran spooler. Untuk informasi lebih lanjut, lihat [Konfigurasi](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration) di [Inti Greengrass](greengrass-nucleus-component.md) dokumentasi. Untuk menghindari pengisian spooler dan perlu menambah memori yang dialokasikan, batasi permintaan publikasi tidak lebih dari 100 permintaan per detik.

Ketika aplikasi Anda perlu mengirim pesan pada tingkat yang lebih tinggi, atau pesan yang lebih besar, pertimbangkan untuk menggunakan pesan [Manajer pengaliran](stream-manager-component.md) untuk mengirim pesan ke Kinesis Data Streams. Komponen manajer aliran dirancang untuk mentransfer data volume tinggi ke file. AWS Cloud Untuk informasi selengkapnya, lihat [Kelola aliran data di perangkat inti Greengrass](manage-data-streams.md).

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

Permintaan operasi ini memiliki parameter berikut:

`topicName`(Python:) `topic_name`  
Topik untuk mempublikasikan pesan.

`qos`  <a name="ipc-iot-core-mqtt-qos"></a>
QoS MQTT yang akan digunakan. Enum ini, `QOS`, memiliki nilai-nilai berikut:  
+ `AT_MOST_ONCE` – QoS 0. Pesan MQTT dikirim paling banyak sekali.
+ `AT_LEAST_ONCE` – QoS 1. Pesan MQTT dikirim paling sedikit sekali.

`payload`  
(Opsional) Pesan muatan sebagai gumpalan.

Fitur-fitur berikut tersedia untuk v2.10.0 dan yang lebih baru [Inti Greengrass](greengrass-nucleus-component.md) saat menggunakan MQTT 5. Fitur-fitur ini diabaikan saat Anda menggunakan MQTT 3.1.1. Tabel berikut mencantumkan versi minimum SDK AWS IoT perangkat yang harus Anda gunakan untuk mengakses fitur ini.


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

`payloadFormat`  
(Opsional) Format payload pesan. Jika Anda tidak menyetel`payloadFormat`, jenisnya diasumsikan`BYTES`. Enum memiliki nilai-nilai berikut:   
+ `BYTES`— Isi muatan adalah gumpalan biner.
+ `UTF8`— Isi muatan adalah UTF8 serangkaian karakter.

`retain`  
(Opsional) Menunjukkan apakah akan menyetel opsi penyimpanan MQTT saat menerbitkan. `true`

`userProperties`  
(Opsional) Daftar `UserProperty` objek khusus aplikasi untuk dikirim. `UserProperty`Objek didefinisikan sebagai berikut:  

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

`messageExpiryIntervalSeconds`  
(Opsional) Jumlah detik sebelum pesan berakhir dan dihapus oleh server. Jika nilai ini tidak disetel, pesan tidak kedaluwarsa.

`correlationData`  
(Opsional) Informasi ditambahkan ke permintaan yang dapat digunakan untuk mengaitkan permintaan dengan respons.

`responseTopic`  
(Opsional) Topik yang harus digunakan untuk pesan respons.

`contentType`  
(Opsional) Pengidentifikasi khusus aplikasi dari jenis konten pesan.

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

Operasi ini tidak memberikan informasi apa pun dalam tanggapannya.

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

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Publikasikan pesan**  

```
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 Contoh: Publikasikan pesan**  
Contoh ini mengasumsikan bahwa Anda menggunakan versi 1.5.4 atau yang lebih baru untuk AWS IoT Device SDK Python v2. 

```
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 Contoh: Publikasikan pesan**  
Contoh ini menggunakan `IPCUtils` kelas untuk membuat koneksi ke layanan AWS IoT Greengrass Core IPC. Untuk informasi selengkapnya, lihat [Connect ke layanan 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 Contoh: Publikasikan pesan**  
Contoh ini mengasumsikan bahwa Anda menggunakan versi 1.5.4 atau yang lebih baru untuk AWS IoT Device SDK Python v2. 

```
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 Contoh: Publikasikan pesan**  

```
#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 Contoh: Publikasikan pesan**  

```
    
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 Contoh: Publikasikan pesan**  

```
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 Contoh: Publikasikan pesan**  

```
#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 Contoh: Publikasikan pesan**  

```
#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>

Berlangganan pesan MQTT dari AWS IoT Core topik atau filter topik. Perangkat lunak AWS IoT Greengrass Core menghapus langganan saat komponen mencapai akhir siklus hidupnya.

<a name="ipc-subscribe-operation-note"></a>Operasi ini adalah operasi berlangganan di mana Anda berlangganan aliran pesan peristiwa. Untuk menggunakan operasi ini, tentukan bagian yang menangani respons aliran dengan fungsi yang menangani pesan peristiwa, kesalahan, dan penutupan aliran. Untuk informasi selengkapnya, lihat [Berlangganan pengaliran peristiwa IPC](interprocess-communication.md#ipc-subscribe-operations).

**Jenis pesan peristiwa:** `IoTCoreMessage`

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

Permintaan operasi ini memiliki parameter berikut:

`topicName`(Python:) `topic_name`  
Topik yang harus dijadikan langganan. Anda dapat menggunakan wildcard topik MQTT (`#` dan `+`) untuk berlangganan beberapa topik.

`qos`  <a name="ipc-iot-core-mqtt-qos"></a>
QoS MQTT yang akan digunakan. Enum ini, `QOS`, memiliki nilai-nilai berikut:  
+ `AT_MOST_ONCE` – QoS 0. Pesan MQTT dikirim paling banyak sekali.
+ `AT_LEAST_ONCE` – QoS 1. Pesan MQTT dikirim paling sedikit sekali.

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

Tanggapan operasi ini memiliki informasi berikut:

`messages`  
Aliran pesan MQTT. Objek ini, `IoTCoreMessage`, berisi informasi berikut:    
`message`  
Pesan MQTT. Objek ini, `MQTTMessage`, berisi informasi berikut:    
`topicName`(Python:) `topic_name`  
Topik yang pesannya dipublikasikan.  
`payload`  
(Opsional) Pesan muatan sebagai gumpalan.
Fitur-fitur berikut tersedia untuk v2.10.0 dan yang lebih baru [Inti Greengrass](greengrass-nucleus-component.md) saat menggunakan MQTT 5. Fitur-fitur ini diabaikan saat Anda menggunakan MQTT 3.1.1. Tabel berikut mencantumkan versi minimum SDK AWS IoT perangkat yang harus Anda gunakan untuk mengakses fitur ini.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-iot-core-mqtt.html)  
`payloadFormat`  
(Opsional) Format payload pesan. Jika Anda tidak menyetel`payloadFormat`, jenisnya diasumsikan`BYTES`. Enum memiliki nilai-nilai berikut:   
+ `BYTES`— Isi muatan adalah gumpalan biner.
+ `UTF8`— Isi muatan adalah UTF8 serangkaian karakter.  
`retain`  
(Opsional) Menunjukkan apakah akan menyetel opsi penyimpanan MQTT saat menerbitkan. `true`  
`userProperties`  
(Opsional) Daftar `UserProperty` objek khusus aplikasi untuk dikirim. `UserProperty`Objek didefinisikan sebagai berikut:  

```
UserProperty:
  key: string
  value: string
```  
`messageExpiryIntervalSeconds`  
(Opsional) Jumlah detik sebelum pesan berakhir dan dihapus oleh server. Jika nilai ini tidak disetel, pesan tidak kedaluwarsa.  
`correlationData`  
(Opsional) Informasi ditambahkan ke permintaan yang dapat digunakan untuk mengaitkan permintaan dengan respons.  
`responseTopic`  
(Opsional) Topik yang harus digunakan untuk pesan respons.  
`contentType`  
(Opsional) Pengidentifikasi khusus aplikasi dari jenis konten pesan.

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

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Berlangganan pesan**  

```
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 Contoh: berlangganan pesan**  
Contoh ini mengasumsikan bahwa Anda menggunakan versi 1.5.4 atau yang lebih baru untuk AWS IoT Device SDK Python v2. 

```
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 Contoh: Berlangganan pesan**  
Contoh ini menggunakan `IPCUtils` kelas untuk membuat koneksi ke layanan AWS IoT Greengrass Core IPC. Untuk informasi selengkapnya, lihat [Connect ke layanan 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 Contoh: Berlangganan pesan**  
Contoh ini mengasumsikan bahwa Anda menggunakan versi 1.5.4 atau yang lebih baru untuk AWS IoT Device SDK Python v2. 

```
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 Contoh: Berlangganan pesan**  

```
#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 Contoh: Berlangganan pesan**  

```
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 Contoh: Berlangganan pesan**  

```
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 Contoh: Berlangganan pesan**  

```
#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 Contoh: Berlangganan pesan**  

```
#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);
    }
}
```

------

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

Gunakan contoh berikut untuk mempelajari cara menggunakan layanan AWS IoT Core MQTT IPC di komponen Anda.

### Contoh penerbit AWS IoT Core MQTT (C \$1\$1, klien IPC V1)
<a name="ipc-iot-core-mqtt-example-publisher-cpp"></a>

Contoh resep berikut memungkinkan komponen untuk mempublikasikan ke semua topik.

------
#### [ 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
```

------

Contoh berikut aplikasi C\$1\$1 menunjukkan bagaimana menggunakan layanan AWS IoT Core MQTT IPC untuk mempublikasikan pesan ke. 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;
}
```

### Contoh pelanggan AWS IoT Core MQTT (C \$1\$1, klien IPC V1)
<a name="ipc-iot-core-mqtt-example-subscriber-cpp"></a>

Contoh resep berikut memungkinkan komponen untuk berlangganan semua topik.

------
#### [ 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
```

------

Contoh berikut aplikasi C\$1\$1 menunjukkan bagaimana menggunakan layanan AWS IoT Core MQTT IPC untuk berlangganan pesan dari. 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;
}
```

### Contoh penerbit AWS IoT Core MQTT (Rust)
<a name="ipc-iot-core-mqtt-example-publisher-rust"></a>

Contoh resep berikut memungkinkan komponen untuk mempublikasikan ke semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut aplikasi Rust menunjukkan bagaimana menggunakan layanan AWS IoT Core MQTT IPC untuk mempublikasikan pesan ke. 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}");
}
```

### Contoh pelanggan AWS IoT Core MQTT (Rust)
<a name="ipc-iot-core-mqtt-example-subscriber-rust"></a>

Contoh resep berikut memungkinkan komponen untuk berlangganan semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut aplikasi Rust menunjukkan bagaimana menggunakan layanan AWS IoT Core MQTT IPC untuk berlangganan pesan dari. 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));
    }
}
```

### Contoh penerbit AWS IoT Core MQTT (C)
<a name="ipc-iot-core-mqtt-example-publisher-c"></a>

Contoh resep berikut memungkinkan komponen untuk mempublikasikan ke semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut C aplikasi menunjukkan bagaimana menggunakan layanan AWS IoT Core MQTT IPC untuk mempublikasikan pesan ke. 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
    );
}
```

### Contoh pelanggan AWS IoT Core MQTT (C)
<a name="ipc-iot-core-mqtt-example-subscriber-c"></a>

Contoh resep berikut memungkinkan komponen untuk berlangganan semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut C aplikasi menunjukkan bagaimana menggunakan layanan AWS IoT Core MQTT IPC untuk berlangganan pesan dari. 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);
}
```

### Contoh penerbit AWS IoT Core MQTT (C \$1\$1, SDK Komponen)
<a name="ipc-iot-core-mqtt-example-publisher-cpp-component-sdk"></a>

Contoh resep berikut memungkinkan komponen untuk mempublikasikan ke semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut aplikasi C\$1\$1 menunjukkan bagaimana menggunakan layanan AWS IoT Core MQTT IPC untuk mempublikasikan pesan ke. 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";
}
```

### Contoh pelanggan AWS IoT Core MQTT (C \$1\$1, SDK Komponen)
<a name="ipc-iot-core-mqtt-example-subscriber-cpp-component-sdk"></a>

Contoh resep berikut memungkinkan komponen untuk berlangganan semua topik.

```
{
  "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"
          }
        }
      ]
    }
  ]
}
```

Contoh berikut aplikasi C\$1\$1 menunjukkan bagaimana menggunakan layanan AWS IoT Core MQTT IPC untuk berlangganan pesan dari. 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);
    }
}
```

# Berinteraksilah dengan siklus hidup komponen
<a name="ipc-component-lifecycle"></a>

Gunakan layanan IPC siklus hidup komponen untuk:
+ Perbarui status komponen pada perangkat inti.
+ Berlangganan pembaruan status komponen.
+ Mencegah nukleus menghentikan komponen untuk menerapkan pembaruan selama penerapan.
+ Jeda dan lanjutkan proses komponen.

**Topics**
+ [SDK (Versi Minimum)](#ipc-component-lifecycle-sdk-versions)
+ [Otorisasi](#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 (Versi Minimum)
<a name="ipc-component-lifecycle-sdk-versions"></a>

Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk berinteraksi dengan siklus hidup komponen.


| SDK | Versi minimum | 
| --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

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

Untuk menjeda atau melanjutkan komponen lain dari komponen kustom, Anda harus menentukan kebijakan otorisasi yang memungkinkan komponen Anda mengelola komponen lain. Untuk informasi tentang cara menentukan kebijakan otorisasi, lihat [Otorisasi komponen untuk melakukan operasi IPC](interprocess-communication.md#ipc-authorization-policies).

Kebijakan otorisasi untuk manajemen siklus hidup komponen memiliki properti berikut.

**Pengenal layanan IPC:** `aws.greengrass.ipc.lifecycle`


| Operasi | Deskripsi | Sumber daya | 
| --- | --- | --- | 
|  `aws.greengrass#PauseComponent`  |  Memungkinkan komponen untuk menjeda komponen yang Anda tentukan.  |  Nama komponen, atau `*` untuk mengizinkan akses ke semua komponen.  | 
|  `aws.greengrass#ResumeComponent`  |  Memungkinkan komponen untuk melanjutkan komponen yang Anda tentukan.  |  Nama komponen, atau `*` untuk mengizinkan akses ke semua komponen.  | 
|  `*`  |  Memungkinkan komponen untuk menjeda dan melanjutkan komponen yang Anda tentukan.  |  Nama komponen, atau `*` untuk mengizinkan akses ke semua komponen.  | 

### Contoh kebijakan otorisasi
<a name="ipc-component-lifecycle-authorization-policy-examples"></a>

Anda dapat mereferensikan contoh kebijakan otorisasi berikut untuk membantu Anda mengonfigurasi kebijakan otorisasi untuk komponen Anda.

**Example Contoh kebijakan otorisasi**  
Contoh kebijakan otorisasi berikut memungkinkan komponen untuk menjeda dan melanjutkan semua komponen.  

```
{
  "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>

Memperbarui keadaan komponen pada perangkat inti.

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

Permintaan operasi ini memiliki parameter berikut:

`state`  
Keadaan yang akan diatur. Enum ini, `LifecycleState`, memiliki nilai-nilai berikut:  
+ `RUNNING`
+ `ERRORED`

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

Operasi ini tidak memberikan informasi apa pun dalam tanggapannya.

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

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Perbarui status**  

```
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 Contoh: Perbarui status**  

```
#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 Contoh: Perbarui status**  

```
#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>

Berlangganan untuk menerima pemberitahuan sebelum perangkat lunak AWS IoT Greengrass Core memperbarui komponen. Notifikasi tersebut menentukan apakah nukleus akan di-restart sebagai bagian dari pembaruan.

Inti tersebut mengirimkan notifikasi pembaruan hanya jika komponen kebijakan pembaruan komponen deployment menentukan untuk menotifikasi komponen. Perilaku defaultnya adalah menotifikasi komponen. Untuk informasi selengkapnya, lihat [Buat deployment](create-deployments.md) dan [DeploymentComponentUpdatePolicy](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_DeploymentComponentUpdatePolicy.html)objek yang dapat Anda berikan saat Anda memanggil [CreateDeployment](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_CreateDeployment.html)operasi.

**penting**  
Deployment lokal tidak menotifikasi komponen sebelum pembaruan.

<a name="ipc-subscribe-operation-note"></a>Operasi ini adalah operasi berlangganan di mana Anda berlangganan aliran pesan peristiwa. Untuk menggunakan operasi ini, tentukan bagian yang menangani respons aliran dengan fungsi yang menangani pesan peristiwa, kesalahan, dan penutupan aliran. Untuk informasi selengkapnya, lihat [Berlangganan pengaliran peristiwa IPC](interprocess-communication.md#ipc-subscribe-operations).

**Jenis pesan peristiwa:** `ComponentUpdatePolicyEvents`

**Tip**  
Anda dapat mengikuti tutorial untuk mempelajari cara mengembangkan komponen yang secara kondisional menunda pembaruan komponen. Untuk informasi selengkapnya, lihat [Tutorial: Mengembangkan komponen Greengrass yang menunda pembaruan komponen](defer-component-updates-tutorial.md).

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

Operasi ini tidak memiliki parameter apa pun.

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

Tanggapan operasi ini memiliki informasi berikut:

`messages`  
Aliran pesan notifikasi. Objek ini, `ComponentUpdatePolicyEvents`, berisi informasi berikut:    
`preUpdateEvent`(Python:) `pre_update_event`  
(Opsional) Sebuah peristiwa yang menunjukkan bahwa inti ingin memperbarui komponen. Anda dapat merespons dengan operasi [DeferComponentUpdate](#ipc-operation-defercomponentupdate) untuk mengakui atau menunda pembaruan sampai komponen Anda siap untuk memulai ulang. Objek ini, `PreComponentUpdateEvent`, berisi informasi berikut:    
`deploymentId`(Python:) `deployment_id`  
ID AWS IoT Greengrass penyebaran yang memperbarui komponen.  
`isGgcRestarting`(Python:) `is_ggc_restarting`  
Apakah nukleus perlu me-restart untuk menerapkan pembaruan.  
`postUpdateEvent`(Python:) `post_update_event`  
(Opsional) Sebuah peristiwa yang menunjukkan bahwa inti telah memperbarui komponen. Objek ini, `PostComponentUpdateEvent`, berisi informasi berikut:    
`deploymentId`(Python:) `deployment_id`  
ID AWS IoT Greengrass penyebaran yang memperbarui komponen.  
Fitur ini membutuhkan v2.7.0 atau yang lebih baru dari komponen inti Greengrass.

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

Mengakui atau menunda pembaruan komponen yang Anda temukan dengan [SubscribeToComponentUpdates](#ipc-operation-subscribetocomponentupdates). Anda menentukan jumlah waktu untuk menunggu sebelum nukleus memeriksa lagi apakah komponen Anda siap untuk membiarkan pembaruan komponen dilanjutkan. Anda juga dapat menggunakan operasi ini untuk memberi tahu nukleus bahwa komponen Anda siap untuk pembaruan.

Jika komponen tidak menanggapi notifikasi pembaruan komponen, inti tersebut akan menunggu sejumlah waktu yang Anda tentukan dalam kebijakan pembaruan komponen deployment. Setelah batas waktu itu, nukleus akan melanjutkan deployment. Pembaruan komponen default adalah 60 detik. Untuk informasi selengkapnya, lihat [Buat deployment](create-deployments.md) dan [DeploymentComponentUpdatePolicy](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_DeploymentComponentUpdatePolicy.html)objek yang dapat Anda berikan saat Anda memanggil [CreateDeployment](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_CreateDeployment.html)operasi.

**Tip**  
Anda dapat mengikuti tutorial untuk mempelajari cara mengembangkan komponen yang secara kondisional menunda pembaruan komponen. Untuk informasi selengkapnya, lihat [Tutorial: Mengembangkan komponen Greengrass yang menunda pembaruan komponen](defer-component-updates-tutorial.md).

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

Permintaan operasi ini memiliki parameter berikut:

`deploymentId`(Python:) `deployment_id`  
ID AWS IoT Greengrass penyebaran untuk menunda.

`message`  
(Opsional) Nama komponen untuk menunda pembaruan.  
Default untuk nama komponen yang membuat permintaan.

`recheckAfterMs`(Python:) `recheck_after_ms`  
Jumlah waktu dalam milidetik untuk menunda pembaruan. Nukleus menunggu selama jumlah waktu ini dan kemudian mengirimkan `PreComponentUpdateEvent` lainnya yang dapat Anda temukan dengan [SubscribeToComponentUpdates](#ipc-operation-subscribetocomponentupdates).  
Tentukan `0` untuk membenarkan pembaruan. Hal ini akan memberi tahu nukleus bahwa komponen Anda siap untuk diperbarui.  
Default nol milidetik, yang berarti mengakui pembaruan.

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

Operasi ini tidak memberikan informasi apa pun dalam tanggapannya.

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

[Fitur ini tersedia untuk v2.4.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md) AWS IoT Greengrass saat ini tidak mendukung fitur ini di perangkat inti Windows. 

Menjeda proses komponen pada perangkat inti. Untuk melanjutkan komponen, gunakan [ResumeComponent](#ipc-operation-resumecomponent)operasi.

Anda hanya dapat menjeda komponen generik. Jika Anda mencoba menjeda jenis komponen lainnya, operasi ini akan menampilkan file. `InvalidRequestError`

**catatan**  
Operasi ini tidak dapat menjeda proses kontainer, seperti kontainer Docker. [Untuk menjeda dan melanjutkan container Docker, Anda dapat menggunakan perintah docker [pause dan docker unpause](https://docs.docker.com/engine/reference/commandline/pause/).](https://docs.docker.com/engine/reference/commandline/unpause/)

Operasi ini tidak menjeda dependensi komponen atau komponen yang bergantung pada komponen yang Anda jeda. Pertimbangkan perilaku ini ketika Anda menjeda komponen yang merupakan ketergantungan komponen lain, karena komponen dependen mungkin mengalami masalah saat ketergantungannya dijeda.

Saat Anda memulai ulang atau mematikan komponen yang dijeda, seperti melalui penerapan, inti Greengrass melanjutkan komponen dan menjalankan siklus hidup shutdown-nya. Untuk informasi selengkapnya tentang memulai ulang komponen, lihat. [RestartComponent](ipc-local-deployments-components.md#ipc-operation-restartcomponent)

**penting**  
Untuk menggunakan operasi ini, Anda harus menentukan kebijakan otorisasi yang memberikan izin untuk menggunakan operasi ini. Untuk informasi selengkapnya, lihat [Otorisasi](#ipc-component-lifecycle-authorization).

### SDK (Versi Minimum)
<a name="ipc-operation-pausecomponent-sdk-versions"></a>

Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk menjeda dan melanjutkan komponen.


| SDK | Versi minimum | 
| --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.4.3  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.6.2  | 
|  [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.13.1  | 
|  [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

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

Permintaan operasi ini memiliki parameter berikut:

`componentName`(Python:) `component_name`  
Nama komponen untuk jeda, yang harus menjadi komponen generik. Untuk informasi selengkapnya, lihat [Jenis komponen](develop-greengrass-components.md#component-types).

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

Operasi ini tidak memberikan informasi apa pun dalam tanggapannya.

## ResumeComponent
<a name="ipc-operation-resumecomponent"></a>

[Fitur ini tersedia untuk v2.4.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md) AWS IoT Greengrass saat ini tidak mendukung fitur ini di perangkat inti Windows. 

Melanjutkan proses komponen pada perangkat inti. Untuk menjeda komponen, gunakan [PauseComponent](#ipc-operation-pausecomponent)operasi.

Anda hanya dapat melanjutkan komponen yang dijeda. Jika Anda mencoba melanjutkan komponen yang tidak dijeda, operasi ini akan menampilkan file. `InvalidRequestError`

**penting**  
Untuk menggunakan operasi ini, Anda harus menentukan kebijakan otorisasi yang memberikan izin untuk melakukannya. Untuk informasi selengkapnya, lihat [Otorisasi](#ipc-component-lifecycle-authorization).

### SDK (Versi Minimum)
<a name="ipc-operation-resumecomponent-sdk-versions"></a>

Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk menjeda dan melanjutkan komponen.


| SDK | Versi minimum | 
| --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.4.3  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.6.2  | 
|  [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.13.1  | 
|  [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

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

Permintaan operasi ini memiliki parameter berikut:

`componentName`(Python:) `component_name`  
Nama komponen yang akan dilanjutkan.

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

Operasi ini tidak memberikan informasi apa pun dalam tanggapannya.

# Berinteraksilah dengan konfigurasi komponen
<a name="ipc-component-configuration"></a>

Layanan IPC konfigurasi komponen memungkinkan Anda melakukan hal berikut:
+ Dapatkan dan atur parameter konfigurasi komponen.
+ Berlangganan pembaruan konfigurasi komponen.
+ Validasi pembaruan konfigurasi komponen sebelum nukleus menerapkannya.

**Topics**
+ [SDK (Versi Minimum)](#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 (Versi Minimum)
<a name="ipc-component-configuration-sdk-versions"></a>

Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk berinteraksi dengan konfigurasi komponen.


| SDK | Versi minimum | 
| --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## GetConfiguration
<a name="ipc-operation-getconfiguration"></a>

Dapatkan nilai konfigurasi untuk komponen pada perangkat inti. Anda menentukan jalur kunci untuk mendapatkan nilai konfigurasi.

### Permintaan
<a name="ipc-operation-getconfiguration-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`componentName`(Python:) `component_name`  <a name="ipc-configuration-request-component-name"></a>
(Opsional) Nama komponen.  
Default untuk nama komponen yang membuat permintaan.

`keyPath`(Python:) `key_path`  
Path kunci untuk nilai konfigurasi. Tentukan daftar di mana setiap entri adalah kunci untuk satu tingkat dalam objek konfigurasi. Sebagai contoh, tentukan `["mqtt", "port"]` untuk mendapatkan nilai `port` dalam konfigurasi berikut.  

```
{
  "mqtt": {
    "port": 443
  }
}
```
Untuk mendapatkan konfigurasi lengkap komponen, tentukan daftar kosong.

### Respons
<a name="ipc-operation-getconfiguration-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`componentName`(Python:) `component_name`  <a name="ipc-configuration-response-component-name"></a>
Nama komponen.

`value`  
Konfigurasi yang diminta sebagai objek.

### Contoh
<a name="ipc-operation-getconfiguration-examples"></a>

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Dapatkan konfigurasi**  

```
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 Contoh: Dapatkan konfigurasi**  

```
#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 Contoh: Dapatkan konfigurasi**  

```
#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>

Memperbarui nilai konfigurasi untuk komponen ini pada perangkat inti.

### Permintaan
<a name="ipc-operation-updateconfiguration-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`keyPath`(Python:) `key_path`  
(Opsional) Path kunci untuk node kontainer (objek) yang akan diperbarui. Tentukan daftar di mana setiap entri adalah kunci untuk satu tingkat dalam objek konfigurasi. Sebagai contoh, tentukan path kunci `["mqtt"]` dan nilai merge `{ "port": 443 }` untuk mengatur nilai `port` dalam konfigurasi berikut.  

```
{
  "mqtt": {
    "port": 443
  }
}
```
Path kunci harus menentukan node kontainer (objek) dalam konfigurasi tersebut. Jika node tidak ada dalam konfigurasi komponen, operasi ini akan membuatnya dan menetapkan nilainya ke objek tersebut di `valueToMerge`.  
Default ke akar dari objek konfigurasi.

`timestamp`  
Jangka waktu Unix saat ini dalam milidetik. Operasi ini menggunakan ini stempel waktu untuk menyelesaikan pembaruan bersamaan untuk kunci. Jika kunci dalam konfigurasi komponen memiliki cap waktu yang lebih besar dari cap waktu dalam permintaan, maka permintaan akan gagal.

`valueToMerge`(Python:) `value_to_merge`  
Objek konfigurasi yang akan digabungkan di lokasi yang Anda tentukan di `keyPath`. Untuk informasi selengkapnya, lihat [Perbarui konfigurasi komponen](update-component-configurations.md).

### Respons
<a name="ipc-operation-updateconfiguration-response"></a>

Operasi ini tidak memberikan informasi apa pun dalam tanggapannya.

### Contoh
<a name="ipc-operation-updateconfiguration-examples"></a>

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Perbarui konfigurasi**  

```
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 Contoh: Perbarui konfigurasi**  

```
#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 Contoh: Perbarui konfigurasi**  

```
#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>

Berlanggananlah untuk menerima notifikasi ketika konfigurasi komponen diperbarui. Ketika Anda berlangganan kunci, Anda akan menerima notifikasi ketika setiap anak dari kunci tersebut melakukan pembaruan.

<a name="ipc-subscribe-operation-note"></a>Operasi ini adalah operasi berlangganan di mana Anda berlangganan aliran pesan peristiwa. Untuk menggunakan operasi ini, tentukan bagian yang menangani respons aliran dengan fungsi yang menangani pesan peristiwa, kesalahan, dan penutupan aliran. Untuk informasi selengkapnya, lihat [Berlangganan pengaliran peristiwa IPC](interprocess-communication.md#ipc-subscribe-operations).

**Jenis pesan peristiwa:** `ConfigurationUpdateEvents`

### Permintaan
<a name="ipc-operation-subscribetoconfigurationupdate-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`componentName`(Python:) `component_name`  <a name="ipc-configuration-request-component-name"></a>
(Opsional) Nama komponen.  
Default untuk nama komponen yang membuat permintaan.

`keyPath`(Python:) `key_path`  
Path kunci untuk nilai konfigurasi yang akan dijadikan langganan. Tentukan daftar di mana setiap entri adalah kunci untuk satu tingkat dalam objek konfigurasi. Sebagai contoh, tentukan `["mqtt", "port"]` untuk mendapatkan nilai `port` dalam konfigurasi berikut.  

```
{
  "mqtt": {
    "port": 443
  }
}
```
Untuk berlangganan pembaruan untuk semua nilai dalam konfigurasi komponen, tentukan daftar kosong.

### Respons
<a name="ipc-operation-subscribetoconfigurationupdate-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`messages`  
Aliran pesan notifikasi. Objek ini, `ConfigurationUpdateEvents`, berisi informasi berikut:    
`configurationUpdateEvent`(Python:) `configuration_update_event`  
Peristiwa pembaruan konfigurasi. Objek ini, `ConfigurationUpdateEvent`, berisi informasi berikut:    
`componentName`(Python:) `component_name`  <a name="ipc-configuration-response-component-name"></a>
Nama komponen.  
`keyPath`(Python:) `key_path`  
Path kunci untuk nilai konfigurasi yang diperbarui.

### Contoh
<a name="ipc-operation-subscribetoconfigurationupdate-examples"></a>

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Berlangganan pembaruan konfigurasi**  

```
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 Contoh: Berlangganan pembaruan konfigurasi**  

```
#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 Contoh: Berlangganan pembaruan konfigurasi**  

```
#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>

Berlanggananlah untuk menerima notifikasi sebelum konfigurasi komponen diperbarui. Hal ini memungkinkan komponen memvalidasi pembaruan konfigurasinya sendiri. Gunakan operasi [SendConfigurationValidityReport](#ipc-operation-sendconfigurationvalidityreport) untuk memberitahu nukleus apakah konfigurasi tersebut valid atau tidak.

**penting**  
Deployment lokal tidak menotifikasi komponen tentang pembaruan.

<a name="ipc-subscribe-operation-note"></a>Operasi ini adalah operasi berlangganan di mana Anda berlangganan aliran pesan peristiwa. Untuk menggunakan operasi ini, tentukan bagian yang menangani respons aliran dengan fungsi yang menangani pesan peristiwa, kesalahan, dan penutupan aliran. Untuk informasi selengkapnya, lihat [Berlangganan pengaliran peristiwa IPC](interprocess-communication.md#ipc-subscribe-operations).

**Jenis pesan peristiwa:** `ValidateConfigurationUpdateEvents`

### Permintaan
<a name="ipc-operation-subscribetovalidateconfigurationupdates-request"></a>

Operasi ini tidak memiliki parameter apa pun.

### Respons
<a name="ipc-operation-subscribetovalidateconfigurationupdates-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`messages`  
Aliran pesan notifikasi. Objek ini, `ValidateConfigurationUpdateEvents`, berisi informasi berikut:    
`validateConfigurationUpdateEvent`(Python:) `validate_configuration_update_event`  
Peristiwa pembaruan konfigurasi. Objek ini, `ValidateConfigurationUpdateEvent`, berisi informasi berikut:    
`deploymentId`(Python:) `deployment_id`  
ID AWS IoT Greengrass penyebaran yang memperbarui komponen.  
`configuration`  
Objek yang berisi konfigurasi baru.

## SendConfigurationValidityReport
<a name="ipc-operation-sendconfigurationvalidityreport"></a>

Beritahu nukleus apakah pembaruan konfigurasi komponen ini valid atau tidak. Deployment tersebut gagal jika Anda memberitahu nukleus bahwa konfigurasi baru tidak valid. Gunakan operasi [SubscribeToValidateConfigurationUpdates](#ipc-operation-subscribetovalidateconfigurationupdates) untuk berlangganan untuk memvalidasi pembaruan konfigurasi.

Jika komponen tidak menanggapi notifikasi pembaruan konfigurasi yang tervalidasi, inti akan menunggu sejumlah waktu yang Anda tentukan dalam kebijakan validasi konfigurasi deployment. Setelah batas waktu itu, nukleus akan melanjutkan deployment. Batas waktu validasi komponen default adalah 20 detik. Untuk informasi selengkapnya, lihat [Buat deployment](create-deployments.md) dan [DeploymentConfigurationValidationPolicy](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_DeploymentConfigurationValidationPolicy.html)objek yang dapat Anda berikan saat Anda memanggil [CreateDeployment](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_CreateDeployment.html)operasi.

### Permintaan
<a name="ipc-operation-sendconfigurationvalidityreport-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`configurationValidityReport`(Python:) `configuration_validity_report`  
Laporan tersebut yang memberitahu inti apakah pembaruan konfigurasi valid atau tidak. Objek ini, `ConfigurationValidityReport`, berisi informasi berikut:    
`status`  
Status validitas. Enum ini, `ConfigurationValidityStatus`, memiliki nilai-nilai berikut:  
+ `ACCEPTED` – Konfigurasi ini valid dan nukleus dapat menerapkannya pada komponen ini.
+ `REJECTED` – Konfigurasi ini tidak valid dan deployment ini gagal.  
`deploymentId`(Python:) `deployment_id`  
ID AWS IoT Greengrass penyebaran yang meminta pembaruan konfigurasi.  
`message`  
(Opsional) Pesan yang melaporkan mengapa konfigurasi tidak valid.

### Respons
<a name="ipc-operation-sendconfigurationvalidityreport-response"></a>

Operasi ini tidak memberikan informasi apa pun dalam tanggapannya.

# Ambil nilai-nilai rahasia
<a name="ipc-secret-manager"></a>

Gunakan layanan IPC secret manager untuk mengambil nilai-nilai rahasia dari rahasia pada perangkat inti. Anda menggunakan [komponen secret manager](secret-manager-component.md) untuk men-deploy rahasia terenkripsi ke perangkat inti. Kemudian, Anda dapat menggunakan operasi IPC untuk mendekripsi rahasia itu dan menggunakan nilainya dalam komponen kustom Anda.

**Topics**
+ [SDK (Versi Minimum)](#ipc-secret-manager-sdk-versions)
+ [Otorisasi](#ipc-secret-manager-authorization)
+ [GetSecretValue](#ipc-operation-getsecretvalue)
+ [Contoh](#ipc-secret-manager-examples)

## SDK (Versi Minimum)
<a name="ipc-secret-manager-sdk-versions"></a>

Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk mengambil nilai rahasia dari rahasia pada perangkat inti.


| SDK | Versi minimum | 
| --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## Otorisasi
<a name="ipc-secret-manager-authorization"></a>

Untuk menggunakan secrets manager dalam komponen kustom, Anda harus menentukan kebijakan otorisasi yang memungkinkan komponen Anda untuk mendapatkan nilai rahasia yang Anda simpan pada perangkat inti. Untuk informasi tentang cara menentukan kebijakan otorisasi, lihat [Otorisasi komponen untuk melakukan operasi IPC](interprocess-communication.md#ipc-authorization-policies).

Kebijakan otorisasi untuk secrets manager memiliki properti berikut.

**Pengenal layanan IPC:** `aws.greengrass.SecretManager`


| Operasi | Deskripsi | Sumber daya | 
| --- | --- | --- | 
|  `aws.greengrass#GetSecretValue` atau `*`  |  Memungkinkan komponen untuk mendapatkan nilai rahasia yang dienkripsi pada perangkat inti.  |  ARN rahasia Secrets Manager, atau `*` untuk memungkinkan akses ke semua rahasia.  | 

### Contoh kebijakan otorisasi
<a name="ipc-secret-manager-authorization-policy-examples"></a>

Anda dapat mereferensikan contoh kebijakan otorisasi berikut untuk membantu Anda mengonfigurasi kebijakan otorisasi untuk komponen Anda.

**Example Contoh kebijakan otorisasi**  
Kebijakan otorisasi contoh berikut memungkinkan komponen untuk mendapatkan nilai rahasia apa pun pada perangkat inti.  
Kami merekomendasikan bahwa dalam lingkungan produksi, Anda mengurangi cakupan kebijakan otorisasi, sehingga komponen hanya mengambil rahasia yang digunakannya. Anda dapat mengubah `*` wildcard menjadi daftar rahasia ARNs saat Anda menerapkan komponen.

```
{
  "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>

Mendapatkan nilai rahasia yang Anda simpan pada perangkat inti.

Operasi ini mirip dengan operasi Secrets Manager yang dapat Anda gunakan untuk mendapatkan nilai rahasia di AWS Cloud. Untuk informasi selengkapnya, lihat [GetSecretValue](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html) di dalam *Referensi API AWS Secrets Manager *. 

### Permintaan
<a name="ipc-operation-getsecretvalue-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`refresh`(Python:) `refresh`  
(opsional): Apakah akan menyinkronkan rahasia yang diminta dengan nilai terbaru dari AWS Secrets Manager layanan.  
Ketika disetel ke true, manajer rahasia akan meminta AWS Secrets Manager layanan untuk nilai terbaru dari label rahasia yang ditentukan dan mengembalikan nilai itu sebagai respons. Jika tidak, nilai rahasia yang disimpan secara lokal akan dikembalikan.  
 Parameter ini tidak akan bekerja bersama dengan `versionId` parameter dalam permintaan. Parameter ini bekerja bila digunakan bersama dengan Nucleus 2.13.0 dan di atasnya.

`secretId`(Python:) `secret_id`  
Nama layanan yang akan didapat. Anda dapat menentukan Amazon Resource Name (ARN) atau nama yang ramah untuk rahasia tersebut.

`versionId`(Python:) `version_id`  
(Opsional) ID dari versi yang akan didapatkan.  
Anda dapat menentukan `versionId` atau `versionStage`.  
Jika Anda tidak menentukan `versionId` atau `versionStage`, operasi ini default ke versi dengan label `AWSCURRENT`.

`versionStage`(Python:) `version_stage`  
(Opsional) Label penahapan dari versi yang akan didapatkan.  
Anda dapat menentukan `versionId` atau `versionStage`.  
Jika Anda tidak menentukan `versionId` atau `versionStage`, operasi ini default ke versi dengan label `AWSCURRENT`.

### Respons
<a name="ipc-operation-getsecretvalue-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`secretId`(Python:) `secret_id`  
ID dari rahasia tersebut.

`versionId`(Python:) `version_id`  
ID dari versi rahasia ini.

`versionStage`(Python:) `version_stage`  
Daftar label penahapan yang melekat pada versi rahasia ini.

`secretValue`(Python:) `secret_value`  
Nilai dari versi rahasia ini. Objek ini, `SecretValue`, berisi informasi berikut.    
`secretString`(Python:) `secret_string`  
Bagian yang didekripsi dari informasi rahasia terlindungi yang Anda berikan kepada Secrets Manager sebagai string.  
`secretBinary`(Python:) `secret_binary`  
(Opsional) Bagian yang didekripsi dari informasi rahasia terlindungi yang Anda berikan kepada Secrets Manager sebagai data biner dalam bentuk himpunan byte. Properti ini berisi data biner sebagai string base64-encoded.  
Properti ini tidak digunakan jika Anda membuat rahasia di konsol Secrets Manager.

### Contoh
<a name="ipc-operation-getsecretvalue-examples"></a>

Contoh berikut ini mendemonstrasikan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Dapatkan nilai rahasia**  
Contoh ini menggunakan `IPCUtils` kelas untuk membuat koneksi ke layanan AWS IoT Greengrass Core IPC. Untuk informasi selengkapnya, lihat [Connect ke layanan 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 Contoh: Dapatkan nilai rahasia**  
Contoh ini mengasumsikan bahwa Anda menggunakan versi 1.5.4 atau yang lebih baru untuk AWS IoT Device SDK Python v2. 

```
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 Contoh: Dapatkan nilai rahasia**  

```
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();
```

------

## Contoh
<a name="ipc-secret-manager-examples"></a>

Gunakan contoh berikut untuk mempelajari cara menggunakan layanan IPC secret manager dalam komponen Anda.

### Contoh: Cetak rahasia (Python, klien IPC V1)
<a name="ipc-secret-manager-example-print-secret-python"></a>

Contoh komponen ini mencetak nilai suatu rahasia yang Anda deploy ke perangkat inti tersebut.

**penting**  
Contoh komponen ini mencetak nilai rahasia, jadi gunakan hanya dengan rahasia yang menyimpan data uji. Jangan gunakan komponen ini untuk mencetak nilai rahasia yang menyimpan informasi penting.

**Topics**
+ [Resep](#ipc-secret-manager-example-print-secret-python-recipe)
+ [Artifacts](#ipc-secret-manager-example-print-secret-python-artifacts)
+ [Penggunaan](#ipc-secret-manager-example-print-secret-python-usage)

#### Resep
<a name="ipc-secret-manager-example-print-secret-python-recipe"></a>

Contoh resep berikut menentukan parameter konfigurasi ARN rahasia dan memungkinkan komponen untuk mendapatkan nilai rahasia apa pun pada perangkat inti.

**catatan**  <a name="ipc-secret-manager-authorization-policy-resource-wildcard"></a>
Kami merekomendasikan bahwa dalam lingkungan produksi, Anda mengurangi cakupan kebijakan otorisasi, sehingga komponen hanya mengambil rahasia yang digunakannya. Anda dapat mengubah `*` wildcard menjadi daftar rahasia ARNs saat Anda menerapkan komponen.

------
#### [ 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}"
```

------

#### Artifacts
<a name="ipc-secret-manager-example-print-secret-python-artifacts"></a>

Contoh aplikasi Python berikut menunjukkan cara menggunakan layanan IPC secret manager untuk mendapatkan nilai rahasia pada perangkat inti.

```
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)
```

#### Penggunaan
<a name="ipc-secret-manager-example-print-secret-python-usage"></a>

Anda dapat menggunakan komponen contoh ini dengan [komponen secret manager](secret-manager-component.md) untuk men-deploy dan mencetak nilai rahasia pada perangkat inti Anda.

**Untuk membuat, men-deploy, dan mencetak rahasia uji**

1. Buat rahasia Secrets Manager dengan data uji.

------
#### [ 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"}'
   ```

------

   Simpan ARN rahasia baru untuk digunakan dalam langkah-langkah berikut.

   Untuk informasi selengkapnya, lihat [Membuat rahasia](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html) di *Panduan Pengguna AWS Secrets Manager *.

1. Deploy [komponen secret manager](secret-manager-component.md) (`aws.greengrass.SecretManager`) dengan pembaruan gabungan konfigurasi berikut. Tentukan ARN rahasia yang Anda buat sebelumnya.

   ```
   {
     "cloudSecrets": [
       {
         "arn": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestGreengrassSecret-abcdef"
       }
     ]
   }
   ```

   Untuk informasi selengkapnya, lihat [Menyebarkan AWS IoT Greengrass komponen ke perangkat](manage-deployments.md) atau [perintah deployment Greengrass CLI](gg-cli-deployment.md).

1. Buat dan deploy komponen contoh pada bagian ini dengan pembaruan gabungan konfigurasi berikut. Tentukan ARN rahasia yang Anda buat sebelumnya.

   ```
   {
     "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"
           ]
         }
       }
     }
   }
   ```

   Untuk informasi selengkapnya, lihat [Buat AWS IoT Greengrass komponen](create-components.md)

1. Lihat log perangkat lunak AWS IoT Greengrass Inti untuk memverifikasi bahwa penerapan berhasil, dan lihat log `com.example.PrintSecret` komponen untuk melihat nilai rahasia yang dicetak. Lihat informasi yang lebih lengkap di [Memantau AWS IoT Greengrass log](monitor-logs.md).

# Berinteraksi dengan bayangan lokal
<a name="ipc-local-shadows"></a>

Gunakan layanan IPC bayangan untuk berinteraksi dengan bayangan lokal pada perangkat. Perangkat yang Anda pilih untuk berinteraksi dapat berupa perangkat inti atau perangkat klien yang terhubung. 

Untuk menggunakan operasi IPC ini, sertakan [komponen shadow manager](shadow-manager-component.md) sebagai dependensi dalam komponen kustom Anda. Anda kemudian dapat menggunakan operasi IPC di komponen kustom Anda untuk berinteraksi dengan bayangan lokal di perangkat Anda melalui manajer bayangan. Untuk mengaktifkan komponen kustom bereaksi terhadap perubahan status bayangan lokal, Anda juga dapat menggunakan layanan publish/subscribe IPC untuk berlangganan peristiwa bayangan. Untuk informasi selengkapnya tentang penggunaan publish/subscribe layanan, lihat[Pesan lokal publikasi/berlangganan](ipc-publish-subscribe.md).

**catatan**  <a name="note-requirement-enable-shadow-manager-client-devices"></a>
Untuk mengaktifkan perangkat inti berinteraksi dengan bayangan perangkat klien, Anda juga harus mengonfigurasi dan menerapkan komponen jembatan MQTT. Untuk informasi selengkapnya, lihat [Mengaktifkan pengelola bayangan untuk berkomunikasi dengan perangkat klien](work-with-client-device-shadows.md).

**Topics**
+ [SDK (Versi Minimum)](#ipc-local-shadows-sdk-versions)
+ [Otorisasi](#ipc-local-shadow-authorization)
+ [GetThingShadow](#ipc-operation-getthingshadow)
+ [UpdateThingShadow](#ipc-operation-updatethingshadow)
+ [DeleteThingShadow](#ipc-operation-deletethingshadow)
+ [ListNamedShadowsForThing](#ipc-operation-listnamedshadowsforthing)

## SDK (Versi Minimum)
<a name="ipc-local-shadows-sdk-versions"></a>

Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk berinteraksi dengan bayangan lokal.


| SDK | Versi minimum | 
| --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.4.0  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.6.0  | 
|  [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## Otorisasi
<a name="ipc-local-shadow-authorization"></a>

Untuk menggunakan layanan IPC bayangan dalam komponen kustom, Anda harus menentukan kebijakan otorisasi yang memungkinkan komponen Anda untuk berinteraksi dengan bayangan. Untuk informasi tentang cara menentukan kebijakan otorisasi, lihat [Otorisasi komponen untuk melakukan operasi IPC](interprocess-communication.md#ipc-authorization-policies).

Kebijakan otorisasi untuk interaksi bayangan memiliki properti berikut.

**Pengenal layanan IPC:** `aws.greengrass.ShadowManager`


| Operasi | Deskripsi | Sumber daya | 
| --- | --- | --- | 
|  `aws.greengrass#GetThingShadow`  |  Memungkinkan komponen untuk mengambil bayangan suatu objek.  |  Salah satu string berikut:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-local-shadows.html)  | 
|  `aws.greengrass#UpdateThingShadow`  |  Memungkinkan komponen untuk memperbarui bayangan suatu objek.  |  Salah satu string berikut:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-local-shadows.html)  | 
|  `aws.greengrass#DeleteThingShadow`  |  Memungkinkan komponen untuk menghapus bayangan suatu objek.  |  Salah satu string berikut:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-local-shadows.html)  | 
|  `aws.greengrass#ListNamedShadowsForThing`  |  Memungkinkan komponen untuk mengambil daftar bayangan bernama untuk suatu objek.  |  Sebuah string nama objek yang memungkinkan akses ke objek untuk mencantumkan bayangannya. Gunakan `*` untuk memungkinkan akses ke semua hal.  | 

**Pengenal layanan IPC:** `aws.greengrass.ipc.pubsub`


| Operasi | Deskripsi | Sumber daya | 
| --- | --- | --- | 
|  `aws.greengrass#SubscribeToTopic`  |  Memungkinkan komponen untuk berlangganan pesan untuk topik yang Anda tentukan.  |  Salah satu string berikut: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-local-shadows.html) Nilai awalan topik `shadowTopicPrefix` tergantung pada jenis bayangan:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/greengrass/v2/developerguide/ipc-local-shadows.html) Gunakan `*` untuk mengizinkan akses semua topik. <a name="ipc-local-publish-subscribe-authorization-mqtt-wildcards"></a>Di [Greengrass](greengrass-nucleus-component.md) nucleus v2.6.0 dan yang lebih baru, Anda dapat berlangganan topik yang berisi wildcard topik MQTT (dan). `#` `+` String topik ini mendukung wildcard topik MQTT sebagai karakter literal. Misalnya, jika kebijakan otorisasi komponen memberikan akses ke`test/topic/#`, komponen dapat berlangganan`test/topic/#`, tetapi tidak dapat berlangganan. `test/topic/filter`  | 

### Variabel resep dalam kebijakan otorisasi bayangan lokal
<a name="ipc-local-shadow-authorization-recipe-variables"></a>

[Jika Anda menggunakan v2.6.0 atau yang lebih baru dari inti Greengrass, dan Anda [menyetel opsi konfigurasi inti](greengrass-nucleus-component.md) Greengrass ke, Anda dapat menggunakan variabel resep dalam kebijakan [interpolateComponentConfiguration](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-interpolate-component-configuration)otorisasi. `true``{iot:thingName}`](component-recipe-reference.md#recipe-variables) Fitur ini memungkinkan Anda mengonfigurasi kebijakan otorisasi tunggal untuk sekelompok perangkat inti, di mana setiap perangkat inti hanya dapat mengakses bayangannya sendiri. Misalnya, Anda dapat mengizinkan akses komponen ke sumber daya berikut untuk operasi IPC bayangan.

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

### Contoh kebijakan otorisasi
<a name="ipc-local-shadow-authorization-policy-examples"></a>

Anda dapat mereferensikan contoh kebijakan otorisasi berikut untuk membantu Anda mengonfigurasi kebijakan otorisasi untuk komponen Anda.

**Example Contoh: Izinkan sekelompok perangkat inti berinteraksi dengan bayangan lokal**  
 <a name="phrase-example-uses-recipe-variables-in-configuration"></a>[Contoh ini menggunakan fitur yang tersedia untuk v2.6.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md) Greengrass nucleus v2.6.0 menambahkan dukungan untuk [sebagian besar variabel resep](component-recipe-reference.md#recipe-variables), seperti, dalam konfigurasi komponen. `{iot:thingName}` Untuk mengaktifkan fitur ini, atur opsi konfigurasi Greengrass nucleus ke [interpolateComponentConfiguration](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-interpolate-component-configuration). `true` Untuk contoh yang berfungsi untuk semua versi inti Greengrass, lihat [contoh kebijakan otorisasi untuk](#ipc-local-shadows-authorization-example-single-device) perangkat inti tunggal.
Contoh kebijakan otorisasi berikut `com.example.MyShadowInteractionComponent` memungkinkan komponen berinteraksi dengan bayangan perangkat klasik dan bayangan bernama `myNamedShadow` untuk perangkat inti yang menjalankan komponen. Kebijakan ini juga memungkinkan komponen ini untuk menerima pesan pada topik lokal untuk bayangan ini.  

```
{
  "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 Contoh: Izinkan sekelompok perangkat inti berinteraksi dengan bayangan perangkat klien**  
[Fitur ini membutuhkan [Greengrass](greengrass-nucleus-component.md) nucleus v2.6.0 atau yang lebih baru, [shadow manager v2.2.0 atau yang lebih baru,](shadow-manager-component.md) dan MQTT bridge v2.2.0 atau yang lebih baru.](mqtt-bridge-component.md) Anda harus mengkonfigurasi jembatan MQTT untuk [mengaktifkan shadow manager untuk berkomunikasi dengan](work-with-client-device-shadows.md#enable-shadow-manager-client-devices) perangkat klien.
Contoh kebijakan otorisasi berikut memungkinkan komponen `com.example.MyShadowInteractionComponent` berinteraksi dengan semua bayangan perangkat untuk perangkat klien yang namanya dimulai`MyClientDevice`.  
Untuk mengaktifkan perangkat inti berinteraksi dengan bayangan perangkat klien, Anda juga harus mengonfigurasi dan menerapkan komponen jembatan MQTT. Untuk informasi selengkapnya, lihat [Mengaktifkan pengelola bayangan untuk berkomunikasi dengan perangkat klien](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 Contoh: Izinkan perangkat inti tunggal berinteraksi dengan bayangan lokal**  
Kebijakan otorisasi contoh berikut memungkinkan komponen `com.example.MyShadowInteractionComponent` untuk berinteraksi dengan bayangan perangkat klasik dan bayangan bernama `myNamedShadow` untuk perangkat `MyThingName`. Kebijakan ini juga memungkinkan komponen ini untuk menerima pesan pada topik lokal untuk bayangan ini.   

```
{
  "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 Contoh: Izinkan sekelompok perangkat inti bereaksi terhadap perubahan status bayangan lokal**  
 <a name="phrase-example-uses-recipe-variables-in-configuration"></a>[Contoh ini menggunakan fitur yang tersedia untuk v2.6.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md) Greengrass nucleus v2.6.0 menambahkan dukungan untuk [sebagian besar variabel resep](component-recipe-reference.md#recipe-variables), seperti, dalam konfigurasi komponen. `{iot:thingName}` Untuk mengaktifkan fitur ini, atur opsi konfigurasi Greengrass nucleus ke [interpolateComponentConfiguration](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-interpolate-component-configuration). `true` Untuk contoh yang berfungsi untuk semua versi inti Greengrass, lihat [contoh kebijakan otorisasi untuk](#interact-with-shadows-react-example-authorization-policy-single-device) perangkat inti tunggal.
Contoh kebijakan kontrol akses berikut memungkinkan kustom `com.example.MyShadowReactiveComponent` menerima pesan tentang `/update/delta` topik untuk bayangan perangkat klasik dan bayangan bernama `myNamedShadow` pada setiap perangkat inti yang menjalankan komponen.  

```
{
  "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 Contoh: Izinkan perangkat inti tunggal bereaksi terhadap perubahan status bayangan lokal**  
Contoh kebijakan kontrol akses berikut memungkinkan kustom `com.example.MyShadowReactiveComponent` menerima pesan tentang `/update/delta` topik untuk bayangan perangkat klasik dan bayangan bernama `myNamedShadow` untuk perangkat`MyThingName`.  

```
{
  "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>

Dapatkan bayangan untuk objek tertentu.

### Permintaan
<a name="ipc-operation-getthingshadow-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`thingName`(Python:) `thing_name`  <a name="ipc-local-shadows-thing-name"></a>
Nama sesuatu .  
Tipe: `string`

`shadowName`(Python:) `shadow_name`  <a name="ipc-local-shadows-shadow-name"></a>
Nama bayangan. Untuk menentukan bayangan klasik benda itu, atur parameter ini ke string kosong (`""`).  
 AWS IoT Greengrass Layanan ini menggunakan bayangan `AWSManagedGreengrassV2Deployment` bernama untuk mengelola penerapan yang menargetkan perangkat inti individual. Bayangan bernama ini dicadangkan untuk digunakan oleh AWS IoT Greengrass layanan. Jangan perbarui atau hapus bayangan bernama ini.
Tipe: `string`

### Respons
<a name="ipc-operation-getthingshadow-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`payload`  
Dokumen keadaan respons sebagai gumpalan.  
Jenis: `object` yang berisi informasi berikut:    
`state`  
Informasi keadaan.  
Objek ini berisi informasi berikut.    
`desired`  
Properti keadaan dan nilai-nilai yang diminta untuk diperbarui di perangkat.  
Jenis: `map` pasangan nilai kunci  
`reported`  
Properti keadaan dan nilai yang dilaporkan oleh perangkat.  
Jenis: `map` pasangan nilai kunci  
`delta`  
Perbedaan antara properti dan nilai yang diinginkan dan yang dilaporkan. Properti ini hadir hanya jika keadaan `desired` dan `reported` berbeda.  
Jenis: `map` pasangan nilai kunci  
`metadata`  
Cap waktu untuk setiap atribut dalam bagian `desired` dan `reported` agar Anda dapat menentukan kapan keadaan diperbarui.   
Tipe: `string`  
`timestamp`  
Tanggal dan jangka waktu respons dihasilkan.  
Tipe: `integer`  
`clientToken`(Python:) `clientToken`  
Token yang digunakan untuk mencocokkan permintaan tersebut dan respons yang sesuai.  
Tipe: `string`  
`version`  
Versi dokumen bayangan lokal.  
Tipe: `integer`

### Kesalahan
<a name="ipc-operation-getthingshadow-errors"></a>

Operasi ini dapat mengembalikan kesalahan berikut.

`InvalidArgumentsError`  <a name="ipc-invalidargumentserror"></a>
<a name="ipc-invalidargumentserror-para"></a>Layanan bayangan lokal tidak dapat memvalidasi parameter permintaan. Hal ini dapat terjadi jika permintaan berisi JSON yang salah bentuk atau karakter yang tidak didukung. 

`ResourceNotFoundError`  <a name="ipc-resourcenotfounderror"></a>
Dokumen bayangan lokal yang diminta tidak dapat ditemukan.

`ServiceError`  <a name="ipc-serviceerror"></a>
Terjadi kesalahan layanan internal, atau jumlah permintaan ke layanan IPC melebihi batas yang ditentukan dalam parameter konfigurasi `maxLocalRequestsPerSecondPerThing` dan `maxTotalLocalRequestsRate` di komponen manajer bayangan.

`UnauthorizedError`  <a name="ipc-unauthorizederror"></a>
Kebijakan otorisasi komponen tidak mencakup izin yang diperlukan untuk operasi ini.

### Contoh
<a name="ipc-operation-getthingshadow-examples"></a>

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Dapatkan bayangan benda**  
Contoh ini menggunakan `IPCUtils` kelas untuk membuat koneksi ke layanan AWS IoT Greengrass Core IPC. Untuk informasi selengkapnya, lihat [Connect ke layanan 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 Contoh: Dapatkan bayangan benda**  

```
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 Contoh: Dapatkan bayangan benda**  

```
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>

Perbarui bayangan untuk objek tertentu. Jika bayangan tidak ada, satu dibuat.

### Permintaan
<a name="ipc-operation-updatethingshadow-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`thingName`(Python:) `thing_name`  <a name="ipc-local-shadows-thing-name"></a>
Nama sesuatu .  
Tipe: `string`

`shadowName`(Python:) `shadow_name`  <a name="ipc-local-shadows-shadow-name"></a>
Nama bayangan. Untuk menentukan bayangan klasik benda itu, atur parameter ini ke string kosong (`""`).  
 AWS IoT Greengrass Layanan ini menggunakan bayangan `AWSManagedGreengrassV2Deployment` bernama untuk mengelola penerapan yang menargetkan perangkat inti individual. Bayangan bernama ini dicadangkan untuk digunakan oleh AWS IoT Greengrass layanan. Jangan perbarui atau hapus bayangan bernama ini.
Tipe: `string`

`payload`  
Dokumen keadaan permintaan sebagai gumpalan.  
Jenis: `object` yang berisi informasi berikut:    
`state`  
Informasi keadaan yang akan diperbarui. Operasi IPC ini hanya mempengaruhi kolom tertentu.  
Objek ini berisi informasi berikut. Biasanya, Anda akan menggunakan properti `desired` atau properti `reported`, tetapi tidak keduanya dalam permintaan yang sama.    
`desired`  
Properti keadaan dan nilai-nilai yang diminta untuk diperbarui di perangkat.  
Jenis: `map` pasangan nilai kunci  
`reported`  
Properti keadaan dan nilai yang dilaporkan oleh perangkat.  
Jenis: `map` pasangan nilai kunci  
`clientToken`(Python:) `client_token`  
(Opsional) Token yang digunakan untuk mencocokkan permintaan dan respons yang sesuai dengan token klien.  
Tipe: `string`  
`version`  
(Opsional) Versi dokumen bayangan lokal yang akan diperbarui. Layanan bayangan akan memproses pembaruan hanya jika versi tertentu cocok dengan versi terbaru yang dimilikinya.  
Tipe: `integer`

### Respons
<a name="ipc-operation-updatethingshadow-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`payload`  
Dokumen keadaan respons sebagai gumpalan.  
Jenis: `object` yang berisi informasi berikut:    
`state`  
Informasi keadaan.  
Objek ini berisi informasi berikut.    
`desired`  
Properti keadaan dan nilai-nilai yang diminta untuk diperbarui di perangkat.  
Jenis: `map` pasangan nilai kunci  
`reported`  
Properti keadaan dan nilai yang dilaporkan oleh perangkat.  
Jenis: `map` pasangan nilai kunci  
`delta`  
Properti keadaan dan nilai yang dilaporkan oleh perangkat.  
Jenis: `map` pasangan nilai kunci  
`metadata`  
Cap waktu untuk setiap atribut dalam bagian `desired` dan `reported` agar Anda dapat menentukan kapan keadaan diperbarui.   
Tipe: `string`  
`timestamp`  
Tanggal dan jangka waktu respons dihasilkan.  
Tipe: `integer`  
`clientToken`(Python:) `client_token`  
Token yang digunakan untuk mencocokkan permintaan dan respons yang sesuai.  
Tipe: `string`  
`version`  
Versi dokumen bayangan lokal setelah pembaruan selesai.  
Tipe: `integer`

### Kesalahan
<a name="ipc-operation-updatethingshadow-errors"></a>

Operasi ini dapat mengembalikan kesalahan berikut.

`ConflictError`  
Layanan bayangan lokal mengalami konflik versi selama operasi pembaruan. Hal ini terjadi ketika versi dalam permintaan muatan tidak cocok dengan versi dalam dokumen bayangan lokal terbaru yang tersedia.

`InvalidArgumentsError`  
<a name="ipc-invalidargumentserror-para"></a>Layanan bayangan lokal tidak dapat memvalidasi parameter permintaan. Hal ini dapat terjadi jika permintaan berisi JSON yang salah bentuk atau karakter yang tidak didukung.   
`payload` yang valid memiliki properti berikut:  
+ Simpul `state` ada, dan merupakan objek yang berisi informasi keadaan `desired` atau `reported`. 
+ Node `desired` dan `reported` merupakan objek atau tidak sah. Setidaknya salah satu dari objek-objek ini harus berisi informasi keadaan yang valid. 
+ Kedalaman objek `desired` dan `reported` tidak dapat melebihi delapan node. 
+ Panjang nilai `clientToken` tidak dapat melebihi 64 karakter. 
+  Nilai `version` harus `1` atau lebih tinggi. 

`ServiceError`  <a name="ipc-serviceerror"></a>
Terjadi kesalahan layanan internal, atau jumlah permintaan ke layanan IPC melebihi batas yang ditentukan dalam parameter konfigurasi `maxLocalRequestsPerSecondPerThing` dan `maxTotalLocalRequestsRate` di komponen manajer bayangan.

`UnauthorizedError`  <a name="ipc-unauthorizederror"></a>
Kebijakan otorisasi komponen tidak mencakup izin yang diperlukan untuk operasi ini.

### Contoh
<a name="ipc-operation-updatethingshadow-examples"></a>

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Perbarui bayangan sesuatu**  
Contoh ini menggunakan `IPCUtils` kelas untuk membuat koneksi ke layanan AWS IoT Greengrass Core IPC. Untuk informasi selengkapnya, lihat [Connect ke layanan 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 Contoh: Perbarui bayangan sesuatu**  

```
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 Contoh: Perbarui bayangan sesuatu**  

```
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>

Menghapus bayangan untuk objek yang ditentukan. 

Dimulai di shadow manager v2.0.4, menghapus bayangan menambah nomor versi. Misalnya, ketika Anda menghapus bayangan `MyThingShadow` di versi 1, versi bayangan yang dihapus adalah 2. Jika Anda kemudian membuat ulang bayangan dengan nama`MyThingShadow`, versi untuk bayangan itu adalah 3. 

### Permintaan
<a name="ipc-operation-deletethingshadow-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`thingName`(Python:) `thing_name`  <a name="ipc-local-shadows-thing-name"></a>
Nama sesuatu .  
Tipe: `string`

`shadowName`(Python:) `shadow_name`  <a name="ipc-local-shadows-shadow-name"></a>
Nama bayangan. Untuk menentukan bayangan klasik benda itu, atur parameter ini ke string kosong (`""`).  
 AWS IoT Greengrass Layanan ini menggunakan bayangan `AWSManagedGreengrassV2Deployment` bernama untuk mengelola penerapan yang menargetkan perangkat inti individual. Bayangan bernama ini dicadangkan untuk digunakan oleh AWS IoT Greengrass layanan. Jangan perbarui atau hapus bayangan bernama ini.
Tipe: `string`

### Respons
<a name="ipc-operation-deletethingshadow-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`payload`  
Dokumen keadaan tanpa respons.

### Kesalahan
<a name="ipc-operation-deletethingshadow-errors"></a>

Operasi ini dapat mengembalikan kesalahan berikut.

`InvalidArgumentsError`  <a name="ipc-invalidargumentserror"></a>
<a name="ipc-invalidargumentserror-para"></a>Layanan bayangan lokal tidak dapat memvalidasi parameter permintaan. Hal ini dapat terjadi jika permintaan berisi JSON yang salah bentuk atau karakter yang tidak didukung. 

`ResourceNotFoundError`  <a name="ipc-resourcenotfounderror"></a>
Dokumen bayangan lokal yang diminta tidak dapat ditemukan.

`ServiceError`  <a name="ipc-serviceerror"></a>
Terjadi kesalahan layanan internal, atau jumlah permintaan ke layanan IPC melebihi batas yang ditentukan dalam parameter konfigurasi `maxLocalRequestsPerSecondPerThing` dan `maxTotalLocalRequestsRate` di komponen manajer bayangan.

`UnauthorizedError`  <a name="ipc-unauthorizederror"></a>
Kebijakan otorisasi komponen tidak mencakup izin yang diperlukan untuk operasi ini.

### Contoh
<a name="ipc-operation-deletethingshadow-examples"></a>

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Hapus bayangan benda**  
Contoh ini menggunakan `IPCUtils` kelas untuk membuat koneksi ke layanan AWS IoT Greengrass Core IPC. Untuk informasi selengkapnya, lihat [Connect ke layanan 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 Contoh: Hapus bayangan benda**  

```
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 Contoh: Hapus bayangan benda**  

```
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>

Daftar bayangan bernama untuk objek yang ditentukan.

### Permintaan
<a name="ipc-operation-listnamedshadowsforthing-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`thingName`(Python:) `thing_name`  <a name="ipc-local-shadows-thing-name"></a>
Nama sesuatu .  
Tipe: `string`

`pageSize`(Python:) `page_size`  
(Opsional) Jumlah nama bayangan yag akan dikembalikan pada setiap panggilan.   
Tipe: `integer`  
Default: 25  
Maksimum: 100

`nextToken`(Python:) `next_token`  
(Opsional) Token untuk mengambil rangkaian hasil berikutnya. Nilai ini dikembalikan pada hasil berhalaman dan digunakan dalam panggilan yang mengembalikan halaman berikutnya.  
Tipe: `string`

### Respons
<a name="ipc-operation-listnamedshadowsforthing-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`results`  
Daftar nama bayangan.   
Tipe: `array`

`timestamp`  
(Opsional) Tanggal dan waktu respons tersebut dihasilkan.   
Tipe: `integer`

`nextToken`(Python:) `next_token`  
(Opsional) Nilai token yang akan digunakan dalam permintaan berhalaman untuk mengambil halaman berikutnya secara berurutan. Token ini tidak hadir ketika tidak terdapat lagi nama bayangan yang akan dikembalikan.  
Tipe: `string`  
Jika ukuran halaman yang diminta persis sesuai dengan jumlah nama bayangan di respons, maka token ini hadir; Namun, ketika digunakan, token tersebut akan mengembalikan daftar kosong.

### Kesalahan
<a name="ipc-operation-listnamedshadowsforthing-errors"></a>

Operasi ini dapat mengembalikan kesalahan berikut.

`InvalidArgumentsError`  <a name="ipc-invalidargumentserror"></a>
<a name="ipc-invalidargumentserror-para"></a>Layanan bayangan lokal tidak dapat memvalidasi parameter permintaan. Hal ini dapat terjadi jika permintaan berisi JSON yang salah bentuk atau karakter yang tidak didukung. 

`ResourceNotFoundError`  <a name="ipc-resourcenotfounderror"></a>
Dokumen bayangan lokal yang diminta tidak dapat ditemukan.

`ServiceError`  <a name="ipc-serviceerror"></a>
Terjadi kesalahan layanan internal, atau jumlah permintaan ke layanan IPC melebihi batas yang ditentukan dalam parameter konfigurasi `maxLocalRequestsPerSecondPerThing` dan `maxTotalLocalRequestsRate` di komponen manajer bayangan.

`UnauthorizedError`  <a name="ipc-unauthorizederror"></a>
Kebijakan otorisasi komponen tidak mencakup izin yang diperlukan untuk operasi ini.

### Contoh
<a name="ipc-operation-listnamedshadowsforthing-examples"></a>

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Daftar benda bernama bayangan**  
Contoh ini menggunakan `IPCUtils` kelas untuk membuat koneksi ke layanan AWS IoT Greengrass Core IPC. Untuk informasi selengkapnya, lihat [Connect ke layanan 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 Contoh: Daftar benda bernama bayangan**  

```
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 Contoh: Daftar benda bernama bayangan**  

```
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();
```

------

# Mengelola penerapan dan komponen lokal
<a name="ipc-local-deployments-components"></a>

**catatan**  
[Fitur ini tersedia untuk v2.6.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md)

Gunakan layanan Greengrass CLI IPC untuk mengelola penerapan lokal dan komponen Greengrass pada perangkat inti.

Untuk menggunakan operasi IPC ini, sertakan versi 2.6.0 atau yang lebih baru dari komponen [CLI Greengrass sebagai ketergantungan dalam komponen kustom](greengrass-cli-component.md) Anda. Anda kemudian dapat menggunakan operasi IPC di komponen kustom Anda untuk melakukan hal berikut:
+ Buat penerapan lokal untuk memodifikasi dan mengonfigurasi komponen Greengrass pada perangkat inti.
+ Mulai ulang dan hentikan komponen Greengrass pada perangkat inti.
+ Buat kata sandi yang dapat Anda gunakan untuk masuk ke [konsol debug lokal](local-debug-console-component.md).

**Topics**
+ [SDK (Versi Minimum)](#ipc-local-deployments-components-sdk-versions)
+ [Otorisasi](#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 (Versi Minimum)
<a name="ipc-local-deployments-components-sdk-versions"></a>

Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk berinteraksi dengan layanan Greengrass CLI IPC.


| SDK | Versi minimum | 
| --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.2.10  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.5.3  | 
|  [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.17.0  | 
|  [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## Otorisasi
<a name="ipc-local-deployments-components-authorization"></a>

Untuk menggunakan layanan Greengrass CLI IPC dalam komponen kustom, Anda harus menentukan kebijakan otorisasi yang memungkinkan komponen Anda mengelola penerapan dan komponen lokal. Untuk informasi tentang cara menentukan kebijakan otorisasi, lihat [Otorisasi komponen untuk melakukan operasi IPC](interprocess-communication.md#ipc-authorization-policies).

Kebijakan otorisasi untuk CLI Greengrass memiliki properti berikut.

**Pengenal layanan IPC:** `aws.greengrass.Cli`


| Operasi | Deskripsi | Sumber daya | 
| --- | --- | --- | 
|  `aws.greengrass#CreateLocalDeployment`  |  Memungkinkan komponen untuk membuat penyebaran lokal pada perangkat inti.  |  `*`  | 
|  `aws.greengrass#ListLocalDeployments`  |  Memungkinkan komponen untuk mencantumkan penerapan lokal pada perangkat inti.  |  `*`  | 
|  `aws.greengrass#GetLocalDeploymentStatus`  |  Memungkinkan komponen untuk mendapatkan status penyebaran lokal pada perangkat inti.  |  ID penyebaran lokal, atau `*` untuk mengizinkan akses ke semua penerapan lokal.  | 
|  `aws.greengrass#ListComponents`  |  Memungkinkan komponen untuk daftar komponen pada perangkat inti.  |  `*`  | 
|  `aws.greengrass#GetComponentDetails`  |  Memungkinkan komponen untuk mendapatkan detail tentang komponen pada perangkat inti.  |  Nama komponen, seperti`com.example.HelloWorld`, atau `*` untuk memungkinkan akses ke semua komponen.  | 
|  `aws.greengrass#RestartComponent`  |  Memungkinkan komponen untuk me-restart komponen pada perangkat inti.  |  Nama komponen, seperti`com.example.HelloWorld`, atau `*` untuk memungkinkan akses ke semua komponen.  | 
|  `aws.greengrass#StopComponent`  |  Memungkinkan komponen untuk menghentikan komponen pada perangkat inti.  |  Nama komponen, seperti`com.example.HelloWorld`, atau `*` untuk memungkinkan akses ke semua komponen.  | 
|  `aws.greengrass#CreateDebugPassword`  |  Mengizinkan komponen menghasilkan kata sandi yang akan digunakan untuk masuk ke [komponen konsol debug lokal](local-debug-console-component.md).  |  `*`  | 

**Example Contoh kebijakan otorisasi**  
Contoh kebijakan otorisasi berikut memungkinkan komponen untuk membuat penerapan lokal, melihat semua penerapan dan komponen lokal, dan memulai ulang dan menghentikan komponen bernama. `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>

Buat atau perbarui deployment lokal menggunakan resep komponen tertentu, artefak, dan argumen waktu aktif.

Operasi ini menyediakan fungsionalitas yang sama dengan [perintah deployment create](gg-cli-deployment.md#deployment-create) di Greengrass CLI.

### Permintaan
<a name="ipc-operation-createlocaldeployment-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`recipeDirectoryPath`(Python:) `recipe_directory_path`  
(Opsional) Jalur absolut ke folder yang berisi file resep komponen.

`artifactDirectoryPath`(Python:) `artifact_directory_path`  
(Opsional) Jalur absolut ke folder yang berisi file artefak untuk disertakan dalam penerapan. Folder artefak harus berisi struktur folder berikut:  

```
/path/to/artifact/folder/component-name/component-version/artifacts
```

`rootComponentVersionsToAdd`(Python:) `root_component_versions_to_add`  
(Opsional) Versi komponen yang akan diinstal pada perangkat inti. Objek ini,`ComponentToVersionMap`, adalah peta yang berisi pasangan kunci-nilai berikut:    
`key`  
Nama komponen.  
`value`  
Versi komponen.

`rootComponentsToRemove`(Python:) `root_components_to_remove`  
(Opsional) Komponen yang akan dihapus dari perangkat inti. Tentukan daftar di mana setiap entri adalah nama komponen.

`componentToConfiguration`(Python:) `component_to_configuration`  
(Opsional) Pembaruan konfigurasi untuk setiap komponen dalam penerapan. Objek ini,`ComponentToConfiguration`, adalah peta yang berisi pasangan kunci-nilai berikut:    
`key`  
Nama komponen.  
`value`  
Konfigurasi memperbarui objek JSON untuk komponen. Objek JSON harus memiliki format berikut.  

```
{ 
  "MERGE": {
    "config-key": "config-value"
  },
  "RESET": [
    "path/to/reset/"
  ]
}
```
Untuk informasi selengkapnya tentang pembaruan konfigurasi, lihat [Perbarui konfigurasi komponen](update-component-configurations.md).

`componentToRunWithInfo`(Python:) `component_to_run_with_info`  
(Opsional) Konfigurasi runtime untuk setiap komponen dalam penerapan. Konfigurasi ini mencakup pengguna sistem yang memiliki proses masing-masing komponen dan batas sistem untuk diterapkan pada setiap komponen. Objek ini,`ComponentToRunWithInfo`, adalah peta yang berisi pasangan kunci-nilai berikut:    
`key`  
Nama komponen.  
`value`  
Konfigurasi runtime untuk komponen. [Jika Anda menghilangkan parameter konfigurasi runtime, perangkat lunak AWS IoT Greengrass Core menggunakan nilai default yang Anda konfigurasikan pada inti Greengrass.](greengrass-nucleus-component.md) Objek ini, `RunWithInfo`, berisi informasi berikut:    
`posixUser`(Python:) `posix_user`  
(Opsional) <a name="deployment-posix-user-definition"></a>Pengguna sistem POSIX dan, secara opsional, grup untuk digunakan untuk menjalankan komponen ini pada perangkat inti Linux. Pengguna, dan grup jika ditentukan, harus ada di setiap perangkat inti Linux. Tentukan pengguna dan grup yang dipisahkan dengan titik dua (`:`) dalam format berikut: `user:group`. Grup ini opsional. Jika Anda tidak menentukan grup, perangkat lunak AWS IoT Greengrass Core menggunakan grup utama untuk pengguna. Untuk informasi selengkapnya, lihat [Konfigurasikan pengguna yang menjalankan komponen](configure-greengrass-core-v2.md#configure-component-user).   
`windowsUser`(Python:) `windows_user`  
(Opsional) <a name="deployment-windows-user-definition"></a>Pengguna Windows yang digunakan untuk menjalankan komponen ini pada perangkat inti Windows. Pengguna harus ada di setiap perangkat inti Windows, dan nama serta kata sandinya harus disimpan dalam instance Credentials Manager LocalSystem akun. Untuk informasi selengkapnya, lihat [Konfigurasikan pengguna yang menjalankan komponen](configure-greengrass-core-v2.md#configure-component-user).   
`systemResourceLimits`(Python:) `system_resource_limits`  
(Opsional) <a name="deployment-system-resource-limits-definition"></a>Batas sumber daya sistem untuk diterapkan pada proses komponen ini. Anda dapat menerapkan batas sumber daya sistem ke komponen Lambda generik dan non-kontainer. Untuk informasi selengkapnya, lihat [Konfigurasikan batas sumber daya sistem untuk komponen](configure-greengrass-core-v2.md#configure-component-system-resource-limits).   
AWS IoT Greengrass saat ini tidak mendukung fitur ini di perangkat inti Windows.   
Objek ini, `SystemResourceLimits`, berisi informasi berikut:    
`cpus`  
(Opsional) <a name="system-resource-limits-cpu-definition-this"></a>Jumlah maksimum waktu CPU yang dapat digunakan proses komponen ini pada perangkat inti. Total waktu CPU perangkat inti setara dengan jumlah inti CPU perangkat. Misalnya, pada perangkat inti dengan 4 core CPU, Anda dapat mengatur nilai ini `2` untuk membatasi proses komponen ini hingga 50 persen penggunaan setiap inti CPU. Pada perangkat dengan 1 inti CPU, Anda dapat mengatur nilai ini `0.25` untuk membatasi proses komponen ini hingga 25 persen penggunaan CPU. Jika Anda menetapkan nilai ini ke angka yang lebih besar dari jumlah inti CPU, perangkat lunak AWS IoT Greengrass Core tidak membatasi penggunaan CPU komponen.   
`memory`  
(Opsional) <a name="system-resource-limits-memory-definition-this"></a>Jumlah maksimum RAM (dalam kilobyte) yang dapat digunakan proses komponen ini pada perangkat inti. 

`groupName`(Python:) `group_name`  
(Opsional) Nama grup hal yang akan ditargetkan dengan penerapan ini.

### Respons
<a name="ipc-operation-createlocaldeployment-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`deploymentId`(Python:) `deployment_id`  
ID penyebaran lokal yang dibuat oleh permintaan.

## ListLocalDeployments
<a name="ipc-operation-listlocaldeployments"></a>

Mendapat status 10 penerapan lokal terakhir.

Operasi ini menyediakan fungsionalitas yang sama dengan [perintah daftar penerapan](gg-cli-deployment.md#deployment-list) di CLI Greengrass.

### Permintaan
<a name="ipc-operation-listlocaldeployments-request"></a>

Operasi ini tidak memiliki parameter apa pun.

### Respons
<a name="ipc-operation-listlocaldeployments-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`localDeployments`(Python:) `local_deployments`  
Daftar penyebaran lokal. Setiap objek dalam daftar ini adalah `LocalDeployment` objek, yang berisi informasi berikut:  <a name="ipc-local-deployment-object-shape"></a>  
`deploymentId`(Python:) `deployment_id`  
ID penyebaran lokal.  
`status`  
Status penyebaran lokal. Enum ini, `DeploymentStatus`, memiliki nilai-nilai berikut:  
+ `QUEUED`
+ `IN_PROGRESS`
+ `SUCCEEDED`
+ `FAILED`

## GetLocalDeploymentStatus
<a name="ipc-operation-getlocaldeploymentstatus"></a>

Mendapat status penyebaran lokal.

Operasi ini menyediakan fungsionalitas yang sama dengan [perintah status penerapan](gg-cli-deployment.md#deployment-status) di CLI Greengrass.

### Permintaan
<a name="ipc-operation-getlocaldeploymentstatus-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`deploymentId`(Python:) `deployment_id`  
ID penyebaran lokal untuk mendapatkan.

### Respons
<a name="ipc-operation-getlocaldeploymentstatus-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`deployment`  
Penyebaran lokal. Objek ini, `LocalDeployment`, berisi informasi berikut:  <a name="ipc-local-deployment-object-shape"></a>  
`deploymentId`(Python:) `deployment_id`  
ID penyebaran lokal.  
`status`  
Status penyebaran lokal. Enum ini, `DeploymentStatus`, memiliki nilai-nilai berikut:  
+ `QUEUED`
+ `IN_PROGRESS`
+ `SUCCEEDED`
+ `FAILED`

## ListComponents
<a name="ipc-operation-listcomponents"></a>

Mendapat nama, versi, status, dan konfigurasi setiap komponen root pada perangkat inti. *Komponen root* adalah komponen yang Anda tentukan dalam penerapan. Respons ini tidak termasuk komponen yang diinstal sebagai dependensi komponen lain.

Operasi ini menyediakan fungsionalitas yang sama dengan [perintah daftar komponen](gg-cli-component.md#component-list) di CLI Greengrass.

### Permintaan
<a name="ipc-operation-listcomponents-request"></a>

Operasi ini tidak memiliki parameter apa pun.

### Respons
<a name="ipc-operation-listcomponents-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`components`  
Daftar komponen root pada perangkat inti. Setiap objek dalam daftar ini adalah `ComponentDetails` objek, yang berisi informasi berikut:  <a name="ipc-component-details-object-shape"></a>  
`componentName`(Python:) `component_name`  
Nama komponen.  
`version`  
Versi komponen.  
`state`  
Keadaan komponen. Keadaan ini dapat menjadi salah satu dari yang berikut:  
+ `BROKEN`
+ `ERRORED`
+ `FINISHED`
+ `INSTALLED`
+ `NEW`
+ `RUNNING`
+ `STARTING`
+ `STOPPING`  
`configuration`  
Konfigurasi komponen sebagai objek JSON.

## GetComponentDetails
<a name="ipc-operation-getcomponentdetails"></a>

Mendapat versi, status, dan konfigurasi komponen pada perangkat inti.

Operasi ini menyediakan fungsionalitas yang sama dengan [perintah detail komponen](gg-cli-component.md#component-details) di CLI Greengrass.

### Permintaan
<a name="ipc-operation-getcomponentdetails-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`componentName`(Python:) `component_name`  
Nama komponen yang akan didapat.

### Respons
<a name="ipc-operation-getcomponentdetails-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`componentDetails`(Python:) `component_details`  
Detail komponen. Objek ini, `ComponentDetails`, berisi informasi berikut:  <a name="ipc-component-details-object-shape"></a>  
`componentName`(Python:) `component_name`  
Nama komponen.  
`version`  
Versi komponen.  
`state`  
Keadaan komponen. Keadaan ini dapat menjadi salah satu dari yang berikut:  
+ `BROKEN`
+ `ERRORED`
+ `FINISHED`
+ `INSTALLED`
+ `NEW`
+ `RUNNING`
+ `STARTING`
+ `STOPPING`  
`configuration`  
Konfigurasi komponen sebagai objek JSON.

## RestartComponent
<a name="ipc-operation-restartcomponent"></a>

Memulai ulang komponen pada perangkat inti.

**catatan**  
Meskipun Anda dapat me-restart komponen apa pun, kami sarankan Anda hanya me-restart [komponen generik](develop-greengrass-components.md#component-types).

Operasi ini menyediakan fungsionalitas yang sama dengan [perintah restart komponen](gg-cli-component.md#component-restart) di CLI Greengrass.

### Permintaan
<a name="ipc-operation-restartcomponent-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`componentName`(Python:) `component_name`  
Nama komponen.

### Respons
<a name="ipc-operation-restartcomponent-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`restartStatus`(Python:) `restart_status`  
Status permintaan restart. Status permintaan dapat berupa salah satu dari yang berikut:  
+ `SUCCEEDED`
+ `FAILED`

`message`  
Pesan tentang mengapa komponen gagal memulai ulang, jika permintaan gagal.

### Contoh
<a name="ipc-operation-restartcomponent-examples"></a>

Contoh-contoh berikut ini menunjukkan cara memanggil operasi ini dalam kode komponen kustom.

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

**Example Contoh: Mulai ulang komponen**  

```
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 Contoh: Mulai ulang komponen**  

```
#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 Contoh: Mulai ulang komponen**  

```
#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>

Menghentikan proses komponen pada perangkat inti.

**catatan**  
Meskipun Anda dapat menghentikan komponen apa pun, kami sarankan Anda menghentikan hanya [komponen generik](develop-greengrass-components.md#component-types).

Operasi ini menyediakan fungsionalitas yang sama dengan [perintah stop komponen](gg-cli-component.md#component-stop) di CLI Greengrass.

### Permintaan
<a name="ipc-operation-stopcomponent-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`componentName`(Python:) `component_name`  
Nama komponen.

### Respons
<a name="ipc-operation-stopcomponent-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`stopStatus`(Python:) `stop_status`  
Status permintaan berhenti. Status permintaan dapat berupa salah satu dari yang berikut:  
+ `SUCCEEDED`
+ `FAILED`

`message`  
Pesan tentang mengapa komponen gagal berhenti, jika permintaan gagal.

## CreateDebugPassword
<a name="ipc-operation-createdebugpassword"></a>

Menghasilkan kata sandi acak yang dapat Anda gunakan untuk masuk ke [komponen konsol debug lokal](local-debug-console-component.md). Kata sandi kedaluwarsa 8 jam setelah dibuat.

Operasi ini menyediakan fungsionalitas yang sama dengan [get-debug-password perintah](gg-cli-get-debug-password.md) di CLI Greengrass.

### Permintaan
<a name="ipc-operation-createdebugpassword-request"></a>

Operasi ini tidak memiliki parameter apa pun.

### Respons
<a name="ipc-operation-createdebugpassword-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`username`  
Nama pengguna yang digunakan untuk masuk.

`password`  
Kata sandi yang digunakan untuk masuk.

`passwordExpiration`(Python:) `password_expiration`  
Waktu ketika kata sandi kedaluwarsa.

`certificateSHA256Hash`(Python:) `certificate_sha256_hash`  
Sidik jari SHA-256 untuk sertifikat yang ditandatangani sendiri yang digunakan konsol debug lokal saat HTTPS diaktifkan. Saat Anda membuka konsol debug lokal, gunakan sidik jari ini untuk memverifikasi bahwa sertifikat tersebut sah dan koneksi aman.

`certificateSHA1Hash`(Python:) `certificate_sha1_hash`  
Sidik jari SHA-1 untuk sertifikat yang ditandatangani sendiri yang digunakan konsol debug lokal saat HTTPS diaktifkan. Saat Anda membuka konsol debug lokal, gunakan sidik jari ini untuk memverifikasi bahwa sertifikat tersebut sah dan koneksi aman.

# Otentikasi dan otorisasi perangkat klien
<a name="ipc-client-device-auth"></a>

**catatan**  
[Fitur ini tersedia untuk v2.6.0 dan yang lebih baru dari komponen inti Greengrass.](greengrass-nucleus-component.md)

Gunakan layanan IPC autentikasi perangkat klien untuk mengembangkan komponen broker lokal khusus di mana perangkat IoT lokal, seperti perangkat klien, dapat terhubung.

Untuk menggunakan operasi IPC ini, sertakan versi 2.2.0 atau yang lebih baru dari [komponen autentikasi perangkat klien sebagai dependensi dalam komponen](client-device-auth-component.md) kustom Anda. Anda kemudian dapat menggunakan operasi IPC di komponen kustom Anda untuk melakukan hal berikut:
+ Verifikasi identitas perangkat klien yang terhubung ke perangkat inti.
+ Buat sesi untuk perangkat klien untuk terhubung ke perangkat inti.
+ Verifikasi apakah perangkat klien memiliki izin untuk melakukan tindakan.
+ Menerima pemberitahuan saat sertifikat server perangkat inti berputar.

**Topics**
+ [SDK (Versi Minimum)](#ipc-client-device-auth-sdk-versions)
+ [Otorisasi](#ipc-client-device-auth-authorization)
+ [VerifyClientDeviceIdentity](#ipc-operation-verifyclientdeviceidentity)
+ [GetClientDeviceAuthToken](#ipc-operation-getclientdeviceauthtoken)
+ [AuthorizeClientDeviceAction](#ipc-operation-authorizeclientdeviceaction)
+ [SubscribeToCertificateUpdates](#ipc-operation-subscribetocertificateupdates)

## SDK (Versi Minimum)
<a name="ipc-client-device-auth-sdk-versions"></a>

Tabel berikut mencantumkan versi minimum AWS IoT Device SDK yang harus Anda gunakan untuk berinteraksi dengan layanan IPC autentikasi perangkat klien.


| SDK | Versi minimum | 
| --- | --- | 
|  [AWS IoT Device SDK untuk Java v2](https://github.com/aws/aws-iot-device-sdk-java-v2)  |  v1.9.3  | 
|  [AWS IoT Device SDK untuk Python v2](https://github.com/aws/aws-iot-device-sdk-python-v2)  |  v1.11.3  | 
|  [AWS IoT Device SDK untuk C\$1\$1 v2](https://github.com/aws/aws-iot-device-sdk-cpp-v2)  |  v1.18.3  | 
|  [AWS IoT Device SDK untuk JavaScript v2](https://github.com/aws/aws-iot-device-sdk-js-v2)  |  v1.12.0  | 

## Otorisasi
<a name="ipc-client-device-auth-authorization"></a>

Untuk menggunakan layanan IPC autentikasi perangkat klien dalam komponen kustom, Anda harus menentukan kebijakan otorisasi yang memungkinkan komponen Anda melakukan operasi ini. Untuk informasi tentang cara menentukan kebijakan otorisasi, lihat [Otorisasi komponen untuk melakukan operasi IPC](interprocess-communication.md#ipc-authorization-policies).

Kebijakan otorisasi untuk otentikasi dan otorisasi perangkat klien memiliki properti berikut.

**Pengenal layanan IPC:** `aws.greengrass.clientdevices.Auth`


| Operasi | Deskripsi | Sumber daya | 
| --- | --- | --- | 
|  `aws.greengrass#VerifyClientDeviceIdentity`  |  Memungkinkan komponen untuk memverifikasi identitas perangkat klien.  |  `*`  | 
|  `aws.greengrass#GetClientDeviceAuthToken`  |  Memungkinkan komponen untuk memvalidasi kredensi perangkat klien dan membuat sesi untuk perangkat klien tersebut.  |  `*`  | 
|  `aws.greengrass#AuthorizeClientDeviceAction`  |  Memungkinkan komponen untuk memverifikasi apakah perangkat klien memiliki izin untuk melakukan tindakan.  |  `*`  | 
|  `aws.greengrass#SubscribeToCertificateUpdates`  |  Memungkinkan komponen untuk menerima pemberitahuan ketika sertifikat server perangkat inti berputar.  |  `*`  | 
|  `*`  |  Memungkinkan komponen untuk melakukan semua operasi layanan IPC autentikasi perangkat klien.  |  `*`  | 

### Contoh kebijakan otorisasi
<a name="ipc-client-device-auth-authorization-policy-examples"></a>

Anda dapat mereferensikan contoh kebijakan otorisasi berikut untuk membantu Anda mengonfigurasi kebijakan otorisasi untuk komponen Anda.

**Example Contoh kebijakan otorisasi**  
Contoh kebijakan otorisasi berikut memungkinkan komponen untuk melakukan semua operasi IPC autentikasi perangkat klien.  

```
{
  "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>

Verifikasi identitas perangkat klien. Operasi ini memverifikasi apakah perangkat klien adalah AWS IoT hal yang valid.

### Permintaan
<a name="ipc-operation-verifyclientdeviceidentity-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`credential`  
Kredensi perangkat klien. Objek ini, `ClientDeviceCredential`, berisi informasi berikut:    
`clientDeviceCertificate`(Python:) `client_device_certificate`  
Sertifikat perangkat X.509 perangkat klien.

### Respons
<a name="ipc-operation-verifyclientdeviceidentity-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`isValidClientDevice`(Python:) `is_valid_client_device`  
Apakah identitas perangkat klien valid.

## GetClientDeviceAuthToken
<a name="ipc-operation-getclientdeviceauthtoken"></a>

Memvalidasi kredensi perangkat klien dan membuat sesi untuk perangkat klien. Operasi ini mengembalikan token sesi yang dapat Anda gunakan dalam permintaan berikutnya untuk [mengotorisasi tindakan perangkat klien](#ipc-operation-authorizeclientdeviceaction).

Agar berhasil menghubungkan perangkat klien, [komponen autentikasi perangkat klien](client-device-auth-component.md#client-device-auth-component-configuration) harus memberikan `mqtt:connect` izin untuk ID klien yang digunakan perangkat klien.

### Permintaan
<a name="ipc-operation-getclientdeviceauthtoken-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`credential`  
Kredensi perangkat klien. Objek ini, `CredentialDocument`, berisi informasi berikut:    
`mqttCredential`(Python:) `mqtt_credential`  
Kredensi MQTT perangkat klien. Tentukan ID klien dan sertifikat yang digunakan perangkat klien untuk terhubung. Objek ini, `MQTTCredential`, berisi informasi berikut:    
`clientId`(Python:) `client_id`  
ID klien yang digunakan untuk terhubung.  
`certificatePem`(Python:) `certificate_pem`  
Sertifikat perangkat X.509 yang digunakan untuk menghubungkan.  
`username`  
Properti ini saat ini tidak digunakan.  
`password`  
Properti ini saat ini tidak digunakan.

### Respons
<a name="ipc-operation-getclientdeviceauthtoken-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`clientDeviceAuthToken`(Python:) `client_device_auth_token`  
Token sesi untuk perangkat klien. Anda dapat menggunakan token sesi ini dalam permintaan berikutnya untuk mengotorisasi tindakan perangkat klien ini.

## AuthorizeClientDeviceAction
<a name="ipc-operation-authorizeclientdeviceaction"></a>

Verifikasi apakah perangkat klien memiliki izin untuk melakukan tindakan pada sumber daya. *Kebijakan otorisasi perangkat klien* menentukan izin yang dapat dilakukan perangkat klien saat terhubung ke perangkat inti. Anda menentukan kebijakan otorisasi perangkat klien saat mengonfigurasi komponen [autentikasi perangkat klien](client-device-auth-component.md#client-device-auth-component-configuration).

### Permintaan
<a name="ipc-operation-authorizeclientdeviceaction-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`clientDeviceAuthToken`(Python:) `client_device_auth_token`  
Token sesi untuk perangkat klien.

`operation`  
Operasi untuk mengotorisasi.

`resource`  
Sumber daya tempat perangkat klien melakukan operasi.

### Respons
<a name="ipc-operation-authorizeclientdeviceaction-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`isAuthorized`(Python:) `is_authorized`  
Apakah perangkat klien berwenang untuk melakukan operasi pada sumber daya.

## SubscribeToCertificateUpdates
<a name="ipc-operation-subscribetocertificateupdates"></a>

Berlangganan untuk menerima sertifikat server baru perangkat inti setiap kali berputar. Ketika sertifikat server berputar, broker harus memuat ulang menggunakan sertifikat server baru.

[Komponen autentikasi perangkat klien](client-device-auth-component.md) memutar sertifikat server setiap 7 hari secara default. Anda dapat mengkonfigurasi interval rotasi antara 2 dan 10 hari.

<a name="ipc-subscribe-operation-note"></a>Operasi ini adalah operasi berlangganan di mana Anda berlangganan aliran pesan peristiwa. Untuk menggunakan operasi ini, tentukan bagian yang menangani respons aliran dengan fungsi yang menangani pesan peristiwa, kesalahan, dan penutupan aliran. Untuk informasi selengkapnya, lihat [Berlangganan pengaliran peristiwa IPC](interprocess-communication.md#ipc-subscribe-operations).

**Jenis pesan peristiwa:** `CertificateUpdateEvent`

### Permintaan
<a name="ipc-operation-subscribetocertificateupdates-request"></a>

Permintaan operasi ini memiliki parameter berikut:

`certificateOptions`(Python:) `certificate_options`  
Jenis pembaruan sertifikat untuk berlangganan. Objek ini, `CertificateOptions`, berisi informasi berikut:    
`certificateType`(Python:) `certificate_type`  
Jenis pembaruan sertifikat untuk berlangganan. Pilih opsi berikut:  
+ `SERVER`

### Respons
<a name="ipc-operation-subscribetocertificateupdates-response"></a>

Tanggapan operasi ini memiliki informasi berikut:

`messages`  
Aliran pesan. Objek ini, `CertificateUpdateEvent`, berisi informasi berikut:    
`certificateUpdate`(Python:) `certificate_update`  
Informasi tentang sertifikat baru. Objek ini, `CertificateUpdate`, berisi informasi berikut:    
`certificate`  
Sertifikat.  
`privateKey`(Python:) `private_key`  
Kunci pribadi sertifikat.  
`publicKey`(Python:) `public_key`  
Kunci publik sertifikat.  
`caCertificates`(Python:) `ca_certificates`  
Daftar sertifikat otoritas sertifikat (CA) dalam rantai sertifikat CA sertifikat.