Publish/subscribe AWS IoT Core MQTT messages
The AWS IoT Core MQTT messaging IPC service lets you send and receive MQTT messages to and from AWS IoT Core. Components can publish messages to AWS IoT Core and subscribe to topics to act on MQTT messages from other sources. For more information about the AWS IoT Core implementation of MQTT, see MQTT in the AWS IoT Core Developer Guide.
Note
This MQTT messaging IPC service lets you exchange messages with AWS IoT Core. For more information about how to exchange messages between components, see Publish/subscribe local messages.
Topics
Minimum SDK versions
The following table lists the minimum versions of the SDKs that you can use to publish and subscribe to MQTT messages to and from AWS IoT Core.
| SDK | Minimum version |
|---|---|
|
v1.0.0 |
|
|
v1.2.10 |
|
|
v1.5.3 |
|
|
v1.17.0 |
|
|
v1.12.0 |
Authorization
To use AWS IoT Core MQTT messaging in a custom component, you must define authorization policies that allow your component to send and receive messages on topics. For information about defining authorization policies, see Authorize components to perform IPC operations.
Authorization policies for AWS IoT Core MQTT messaging have the following properties.
IPC service identifier:
aws.greengrass.ipc.mqttproxy
| Operation | Description | Resources |
|---|---|---|
|
|
Allows a component to publish messages to AWS IoT Core on the MQTT topics that you specify. |
A topic string, such as |
|
|
Allows a component to subscribe to messages from AWS IoT Core on the topics that you specify. |
A topic string, such as |
|
|
Allows a component to publish and subscribe to AWS IoT Core MQTT messages for the topics that you specify. |
A topic string, such as |
MQTT wildcards in AWS IoT Core MQTT authorization policies
You can use MQTT wildcards in AWS IoT Core MQTT IPC authorization policies. Components can
publish and subscribe to topics that match the topic filter that you allow in an
authorization policy. For example, if a component's authorization policy grants access to
test/topic/#, the component can subscribe to test/topic/#, and
it can publish and subscribe to test/topic/filter.
Recipe variables in AWS IoT Core MQTT authorization policies
If you use v2.6.0 or later of the Greengrass nucleus, you can use the
{iot:thingName} recipe variable in authorization policies. This feature
enables you to configure a single authorization policy for a group of core devices, where
each core device can access only topics that contain its own name. For example, you can
allow a component access to the following topic resource.
devices/{iot:thingName}/messages
For more information, see Recipe variables and Use recipe variables in merge updates.
Authorization policy examples
You can reference the following authorization policy examples to help you configure authorization policies for your components.
Example authorization policy with unrestricted access
The following example authorization policy allows a component to publish and subscribe to all topics.
Example authorization policy with limited access
The following example authorization policy allows a component to publish and subscribe
to two topics named factory/1/events and
factory/1/actions.
Example authorization policy for a group of core devices
Important
This example uses a feature that is available for v2.6.0 and later of the Greengrass nucleus component. Greengrass nucleus
v2.6.0 adds support for most recipe variables,
such as {iot:thingName}, in component configurations.
The following example authorization policy allows a component to publish and subscribe to a topic that contains the name of the core device that runs the component.
PublishToIoTCore
Publishes an MQTT message to AWS IoT Core on a topic.
When you publish MQTT messages to AWS IoT Core, there is a quota of 100 transactions per second. If you exceed this quota, messages are queued for processing on the Greengrass device. There is also a quota of 512 Kb of data per second and an account-wide quota of 20,000 publishes per second (2,000 in some AWS Regions). For more information about MQTT message broker limits in AWS IoT Core, see AWS IoT Core message broker and protocol limits and quotas.
If you exceed these quotas, the Greengrass device limits publishing messages to AWS IoT Core. Messages are stored in a spooler in memory. By default, the memory allocated to the spooler is 2.5 Mb. If the spooler fills up, new messages are rejected. You can increase the size of the spooler. For more information, see Configuration in the Greengrass nucleus documentation. To avoid filling the spooler and needing to increase the allocated memory, limit publish requests to no more than 100 requests per second.
When your application needs to send messages at a higher rate, or larger messages, consider using the Stream manager to send messages to Kinesis Data Streams. The stream manager component is designed to transfer high-volume data to the AWS Cloud. For more information, see Manage data streams on Greengrass core devices.
Request
This operation's request has the following parameters:
topicName(Python:topic_name)-
The topic to which to publish the message.
qos-
The MQTT QoS to use. This enum,
QOS, has the following values:-
AT_MOST_ONCE– QoS 0. The MQTT message is delivered at most once. -
AT_LEAST_ONCE– QoS 1. The MQTT message is delivered at least once.
-
payload-
(Optional) The message payload as a blob.
The following features are available for v2.10.0 and later of the Greengrass nucleus when using MQTT 5. These features are ignored when you are using MQTT 3.1.1. The following table lists the minimum version of the AWS IoT device SDK that you must use to access these features.
| SDK | Minimum version |
|---|---|
| AWS IoT Device SDK for Python
v2 |
v1.15.0 |
| AWS IoT Device SDK for Java
v2 |
v1.13.0 |
| AWS IoT Device SDK for C++
v2 |
v1.24.0 |
| AWS IoT Device SDK for JavaScript v2 |
v1.13.0 |
payloadFormat-
(Optional) The format of the message payload. If you don't set the
payloadFormat, the type is assumed to beBYTES. The enum has the following values:-
BYTES– The content of the payload is a binary blob. -
UTF8– The content of the payload is a UTF8 string of characters.
-
retain-
(Optional) Indicates whether to set the MQTT retain option to
truewhen publishing. userProperties-
(Optional) A list of application-specific
UserPropertyobjects to send. TheUserPropertyobject is defined as follows:UserProperty: key: string value: string messageExpiryIntervalSeconds-
(Optional) The number of seconds before the message expires and is deleted by the server. If this value is not set, the message doesn't expire.
correlationData-
(Optional) Information added to the request that can be used to associate a request with a response.
responseTopic-
(Optional) The topic that should be used for the response message.
contentType-
(Optional) An application-specific identifier of the content type of the message.
Response
This operation doesn't provide any information in its response.
Examples
The following examples demonstrate how to call this operation in custom component code.
SubscribeToIoTCore
Subscribe to MQTT messages from AWS IoT Core on a topic or topic filter. The AWS IoT Greengrass Core software removes subscriptions when the component reaches the end of its lifecycle.
This operation is a subscription operation where you subscribe to a stream of event messages. To use this operation, define a stream response handler with functions that handle event messages, errors, and stream closure. For more information, see Subscribe to IPC event streams.
Event message type:
IoTCoreMessage
Request
This operation's request has the following parameters:
topicName(Python:topic_name)-
The topic to which to subscribe. You can use MQTT topic wildcards (
#and+) to subscribe to multiple topics. qos-
The MQTT QoS to use. This enum,
QOS, has the following values:-
AT_MOST_ONCE– QoS 0. The MQTT message is delivered at most once. -
AT_LEAST_ONCE– QoS 1. The MQTT message is delivered at least once.
-
Response
This operation's response has the following information:
messages-
The stream of MQTT messages. This object,
IoTCoreMessage, contains the following information:message-
The MQTT message. This object,
MQTTMessage, contains the following information:topicName(Python:topic_name)-
The topic to which the message was published.
payload-
(Optional) The message payload as a blob.
The following features are available for v2.10.0 and later of the Greengrass nucleus when using MQTT 5. These features are ignored when you are using MQTT 3.1.1. The following table lists the minimum version of the AWS IoT device SDK that you must use to access these features.
SDK Minimum version AWS IoT Device SDK for Python v2 v1.15.0 AWS IoT Device SDK for Java v2 v1.13.0 AWS IoT Device SDK for C++ v2 v1.24.0 AWS IoT Device SDK for JavaScript v2 v1.13.0 payloadFormat-
(Optional) The format of the message payload. If you don't set the
payloadFormat, the type is assumed to beBYTES. The enum has the following values:-
BYTES– The content of the payload is a binary blob. -
UTF8– The content of the payload is a UTF8 string of characters.
-
retain-
(Optional) Indicates whether to set the MQTT retain option to
truewhen publishing. userProperties-
(Optional) A list of application-specific
UserPropertyobjects to send. TheUserPropertyobject is defined as follows:UserProperty: key: string value: string messageExpiryIntervalSeconds-
(Optional) The number of seconds before the message expires and is deleted by the server. If this value is not set, the message doesn't expire.
correlationData-
(Optional) Information added to the request that can be used to associate a request with a response.
responseTopic-
(Optional) The topic that should be used for the response message.
contentType-
(Optional) An application specific identifier of the content type of the message.
Examples
The following examples demonstrate how to call this operation in custom component code.
SubscribeToIoTCoreConnectionStatus
Use this operation to subscribe to the status of the MQTT connection between the core device and AWS IoT Core. After you subscribe, you receive the current connection status as the first event. Then, you receive an event each time the core device connects to or disconnects from AWS IoT Core.
This operation is a subscription operation where you subscribe to a stream of event messages. To use this operation, define a stream response handler with functions that handle event messages, errors, and stream closure. For more information, see Subscribe to IPC event streams.
Event message type:
IoTCoreConnectionStatusEvent
Note
This operation doesn't require an authorization policy, because it's an informational,
local-only operation that doesn't expose MQTT topic data. You can call this operation in
your components without an accessControl entry in the component
recipe.
Request
This operation's request doesn't have any parameters.
Response
This operation's response has the following information:
connectionStatusEvent(Python:connection_status_event)-
The
ConnectionStatusEventobject in each streamedIoTCoreConnectionStatusEvent. This object reports the MQTT connection state of the core device, and contains the following information:status-
The status of the MQTT connection between the core device and AWS IoT Core. This enum,
ConnectionStatus, has the following values:-
CONNECTED– The core device is connected to AWS IoT Core. -
DISCONNECTED– The core device is disconnected from AWS IoT Core.
-
Example events
Each event in the stream is the JSON serialization of an
IoTCoreConnectionStatusEvent object. The
connectionStatusEvent key identifies the type of event in the
stream.
After you subscribe, you receive the following example event when the core device is connected to AWS IoT Core. You also receive this event when the connection resumes.
{ "connectionStatusEvent": { "status": "CONNECTED" } }
You receive the following example event when the core device loses its MQTT connection.
{ "connectionStatusEvent": { "status": "DISCONNECTED" } }
Examples
Use the following examples to learn how to use the AWS IoT Core MQTT IPC service in your components.
The following example recipe allows the component to publish to all topics.
The following example C++ application demonstrates how to use the AWS IoT Core MQTT IPC service to publish messages to 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; }
The following example recipe allows the component to subscribe to all topics.
The following example C++ application demonstrates how to use the AWS IoT Core MQTT IPC service to subscribe to messages from 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; }
The following example recipe allows the component to publish to all topics.
{ "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" } } ] } ] }
The following example Rust application demonstrates how to use the AWS IoT Core MQTT IPC service to publish messages to 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}"); }
The following example recipe allows the component to subscribe to all topics.
{ "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" } } ] } ] }
The following example Rust application demonstrates how to use the AWS IoT Core MQTT IPC service to subscribe to messages from 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)); } }
The following example recipe allows the component to publish to all topics.
{ "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" } } ] } ] }
The following example C application demonstrates how to use the AWS IoT Core MQTT IPC service to publish messages to 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 ); }
The following example recipe allows the component to subscribe to all topics.
{ "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" } } ] } ] }
The following example C application demonstrates how to use the AWS IoT Core MQTT IPC service to subscribe to messages from 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); }
The following example recipe allows the component to publish to all topics.
{ "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" } } ] } ] }
The following example C++ application demonstrates how to use the AWS IoT Core MQTT IPC service to publish messages to 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"; }
The following example recipe allows the component to subscribe to all topics.
{ "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" } } ] } ] }
The following example C++ application demonstrates how to use the AWS IoT Core MQTT IPC service to subscribe to messages from 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); } }