Skip to content

Commit

Permalink
add shadow demo
Browse files Browse the repository at this point in the history
  • Loading branch information
xiazhvera committed Sep 27, 2023
1 parent 0939bac commit 2867761
Show file tree
Hide file tree
Showing 6 changed files with 125 additions and 151 deletions.
2 changes: 0 additions & 2 deletions identity/source/IotIdentityClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,9 @@ namespace Aws
{
}


IotIdentityClient::IotIdentityClient(const std::shared_ptr<Aws::Crt::Mqtt5::Mqtt5Client> &mqtt5Client)
{
m_connection = Aws::Crt::Mqtt::MqttConnection::NewConnectionFromMqtt5Client(mqtt5Client);

}

IotIdentityClient::operator bool() const noexcept { return m_connection && *m_connection; }
Expand Down
122 changes: 61 additions & 61 deletions samples/fleet_provisioning/fleet_provisioning/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
#include <aws/crt/JsonObject.h>
#include <aws/crt/UUID.h>
#include <aws/crt/io/HostResolver.h>

#include <aws/crt/mqtt/Mqtt5Packets.h>
#include <aws/iot/Mqtt5Client.h>
#include <aws/iot/MqttClient.h>

#include <aws/iotidentity/CreateCertificateFromCsrRequest.h>
Expand Down Expand Up @@ -76,80 +77,79 @@ int main(int argc, char *argv[])
csrFile = getFileData(cmdData.input_csrPath.c_str()).c_str();
}

/**
* In a real world application you probably don't want to enforce synchronous behavior
* but this is a sample console application, so we'll just do that with a condition variable.
*/
std::promise<bool> connectionCompletedPromise;
std::promise<void> connectionClosedPromise;
// Create the MQTT5 builder and populate it with data from cmdData.
Aws::Iot::Mqtt5ClientBuilder *builder = Aws::Iot::Mqtt5ClientBuilder::NewMqtt5ClientBuilderWithMtlsFromPath(
cmdData.input_endpoint, cmdData.input_cert.c_str(), cmdData.input_key.c_str());

// Invoked when a MQTT connect has completed or failed
auto onConnectionCompleted = [&](Mqtt::MqttConnection &, int errorCode, Mqtt::ReturnCode returnCode, bool) {
if (errorCode)
{
fprintf(stdout, "Connection failed with error %s\n", ErrorDebugString(errorCode));
connectionCompletedPromise.set_value(false);
}
else
{
fprintf(stdout, "Connection completed with return code %d\n", returnCode);
connectionCompletedPromise.set_value(true);
}
};

// Invoked when a disconnect has been completed
auto onDisconnect = [&](Mqtt::MqttConnection & /*conn*/) {
{
fprintf(stdout, "Disconnect completed\n");
connectionClosedPromise.set_value();
}
};

// Create the MQTT builder and populate it with data from cmdData.
auto clientConfigBuilder =
Aws::Iot::MqttClientConnectionConfigBuilder(cmdData.input_cert.c_str(), cmdData.input_key.c_str());
clientConfigBuilder.WithEndpoint(cmdData.input_endpoint);
if (cmdData.input_ca != "")
// Check if the builder setup correctly.
if (builder == nullptr)
{
clientConfigBuilder.WithCertificateAuthority(cmdData.input_ca.c_str());
printf(
"Failed to setup mqtt5 client builder with error code %d: %s", LastError(), ErrorDebugString(LastError()));
return -1;
}

// Create the MQTT connection from the MQTT builder
auto clientConfig = clientConfigBuilder.Build();
if (!clientConfig)
// Setup connection options
std::shared_ptr<Mqtt5::ConnectPacket> connectOptions = std::make_shared<Mqtt5::ConnectPacket>();
connectOptions->WithClientId(cmdData.input_clientId);
builder->WithConnectOptions(connectOptions);
if (cmdData.input_port != 0)
{
fprintf(
stderr,
"Client Configuration initialization failed with error %s\n",
Aws::Crt::ErrorDebugString(clientConfig.LastError()));
exit(-1);
}
Aws::Iot::MqttClient client = Aws::Iot::MqttClient();
auto connection = client.NewConnection(clientConfig);
if (!*connection)
{
fprintf(
stderr,
"MQTT Connection Creation failed with error %s\n",
Aws::Crt::ErrorDebugString(connection->LastError()));
exit(-1);
builder->WithPort(static_cast<uint16_t>(cmdData.input_port));
}

connection->OnConnectionCompleted = std::move(onConnectionCompleted);
connection->OnDisconnect = std::move(onDisconnect);
std::promise<bool> connectionPromise;
std::promise<void> stoppedPromise;
std::promise<void> disconnectPromise;
std::promise<bool> subscribeSuccess;

// Setup lifecycle callbacks
builder->WithClientConnectionSuccessCallback(
[&connectionPromise](const Mqtt5::OnConnectionSuccessEventData &eventData)
{
fprintf(
stdout,
"Mqtt5 Client connection succeed, clientid: %s.\n",
eventData.negotiatedSettings->getClientId().c_str());
connectionPromise.set_value(true);
});
builder->WithClientConnectionFailureCallback(
[&connectionPromise](const Mqtt5::OnConnectionFailureEventData &eventData)
{
fprintf(
stdout, "Mqtt5 Client connection failed with error: %s.\n", aws_error_debug_str(eventData.errorCode));
connectionPromise.set_value(false);
});
builder->WithClientStoppedCallback(
[&stoppedPromise](const Mqtt5::OnStoppedEventData &)
{
fprintf(stdout, "Mqtt5 Client stopped.\n");
stoppedPromise.set_value();
});
builder->WithClientAttemptingConnectCallback([](const Mqtt5::OnAttemptingConnectEventData &)
{ fprintf(stdout, "Mqtt5 Client attempting connection...\n"); });
builder->WithClientDisconnectionCallback(
[&disconnectPromise](const Mqtt5::OnDisconnectionEventData &eventData)
{
fprintf(stdout, "Mqtt5 Client disconnection with reason: %s.\n", aws_error_debug_str(eventData.errorCode));
disconnectPromise.set_value();
});

// Create Mqtt5Client
std::shared_ptr<Aws::Crt::Mqtt5::Mqtt5Client> client = builder->Build();
delete builder;
/************************ Run the sample ****************************/

fprintf(stdout, "Connecting...\n");
if (!connection->Connect(cmdData.input_clientId.c_str(), true, 0))
if (!client->Start())
{
fprintf(stderr, "MQTT Connection failed with error %s\n", ErrorDebugString(connection->LastError()));
fprintf(stderr, "MQTT5 Connection failed to start");
exit(-1);
}

if (connectionCompletedPromise.get_future().get())
if (connectionPromise.get_future().get())
{
IotIdentityClient identityClient(connection);
IotIdentityClient identityClient(client);

std::promise<void> csrPublishCompletedPromise;
std::promise<void> csrAcceptedCompletedPromise;
Expand Down Expand Up @@ -465,9 +465,9 @@ int main(int argc, char *argv[])
}

// Disconnect
if (connection->Disconnect())
if (client->Stop())
{
connectionClosedPromise.get_future().wait();
stoppedPromise.get_future().wait();
}

return 0;
Expand Down
21 changes: 7 additions & 14 deletions samples/jobs/describe_job_execution/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,6 @@ int main(int argc, char *argv[])

std::promise<bool> connectionPromise;
std::promise<void> stoppedPromise;
std::promise<void> disconnectPromise;
std::promise<bool> subscribeSuccess;

// Setup lifecycle callbacks
builder->WithClientConnectionSuccessCallback(
Expand All @@ -82,21 +80,16 @@ int main(int argc, char *argv[])
fprintf(stdout, "Mqtt5 Client connection failed with error: %s.\n", aws_error_debug_str(eventData.errorCode));
connectionPromise.set_value(false);
});
builder->WithClientStoppedCallback([&stoppedPromise](const Mqtt5::OnStoppedEventData &) {
fprintf(stdout, "Mqtt5 Client stopped.\n");
stoppedPromise.set_value();
});
builder->WithClientAttemptingConnectCallback([](const Mqtt5::OnAttemptingConnectEventData &) {
fprintf(stdout, "Mqtt5 Client attempting connection...\n");
});
builder->WithClientDisconnectionCallback([&disconnectPromise](const Mqtt5::OnDisconnectionEventData &eventData) {
fprintf(stdout, "Mqtt5 Client disconnection with reason: %s.\n", aws_error_debug_str(eventData.errorCode));
disconnectPromise.set_value();
});
builder->WithClientStoppedCallback(
[&stoppedPromise](const Mqtt5::OnStoppedEventData &)
{
fprintf(stdout, "Mqtt5 Client stopped.\n");
stoppedPromise.set_value();
});

// Create Mqtt5Client
std::shared_ptr<Aws::Crt::Mqtt5::Mqtt5Client> client = builder->Build();

delete builder;
/************************ Run the sample ****************************/

fprintf(stdout, "Connecting...\n");
Expand Down
125 changes: 51 additions & 74 deletions samples/shadow/shadow_sync/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
#include <aws/crt/JsonObject.h>
#include <aws/crt/UUID.h>
#include <aws/crt/io/HostResolver.h>

#include <aws/crt/mqtt/Mqtt5Packets.h>
#include <aws/iot/Mqtt5Client.h>
#include <aws/iot/MqttClient.h>

#include <aws/iotshadow/ErrorResponse.h>
Expand Down Expand Up @@ -102,93 +103,69 @@ int main(int argc, char *argv[])
*/
Utils::cmdData cmdData = Utils::parseSampleInputShadow(argc, argv, &apiHandle);

// Create the MQTT builder and populate it with data from cmdData.
auto clientConfigBuilder =
Aws::Iot::MqttClientConnectionConfigBuilder(cmdData.input_cert.c_str(), cmdData.input_key.c_str());
clientConfigBuilder.WithEndpoint(cmdData.input_endpoint);
if (cmdData.input_ca != "")
{
clientConfigBuilder.WithCertificateAuthority(cmdData.input_ca.c_str());
}
if (cmdData.input_proxyHost != "")
{
Aws::Crt::Http::HttpClientConnectionProxyOptions proxyOptions;
proxyOptions.HostName = cmdData.input_proxyHost;
proxyOptions.Port = static_cast<uint16_t>(cmdData.input_proxyPort);
proxyOptions.AuthType = Aws::Crt::Http::AwsHttpProxyAuthenticationType::None;
clientConfigBuilder.WithHttpProxyOptions(proxyOptions);
}
if (cmdData.input_port != 0)
{
clientConfigBuilder.WithPortOverride(static_cast<uint16_t>(cmdData.input_port));
}
// Create the MQTT5 builder and populate it with data from cmdData.
Aws::Iot::Mqtt5ClientBuilder *builder = Aws::Iot::Mqtt5ClientBuilder::NewMqtt5ClientBuilderWithMtlsFromPath(
cmdData.input_endpoint, cmdData.input_cert.c_str(), cmdData.input_key.c_str());

// Create the MQTT connection from the MQTT builder
auto clientConfig = clientConfigBuilder.Build();
if (!clientConfig)
// Check if the builder setup correctly.
if (builder == nullptr)
{
fprintf(
stderr,
"Client Configuration initialization failed with error %s\n",
Aws::Crt::ErrorDebugString(clientConfig.LastError()));
exit(-1);
printf(
"Failed to setup mqtt5 client builder with error code %d: %s", LastError(), ErrorDebugString(LastError()));
return -1;
}
Aws::Iot::MqttClient client = Aws::Iot::MqttClient();
auto connection = client.NewConnection(clientConfig);
if (!*connection)

// Setup connection options
std::shared_ptr<Mqtt5::ConnectPacket> connectOptions = std::make_shared<Mqtt5::ConnectPacket>();
connectOptions->WithClientId(cmdData.input_clientId);
builder->WithConnectOptions(connectOptions);
if (cmdData.input_port != 0)
{
fprintf(
stderr,
"MQTT Connection Creation failed with error %s\n",
Aws::Crt::ErrorDebugString(connection->LastError()));
exit(-1);
builder->WithPort(static_cast<uint16_t>(cmdData.input_port));
}

/**
* In a real world application you probably don't want to enforce synchronous behavior
* but this is a sample console application, so we'll just do that with a condition variable.
*/
std::promise<bool> connectionCompletedPromise;
std::promise<void> connectionClosedPromise;
std::promise<bool> connectionPromise;
std::promise<void> stoppedPromise;

// Invoked when a MQTT connect has completed or failed
auto onConnectionCompleted =
[&](Aws::Crt::Mqtt::MqttConnection &, int errorCode, Aws::Crt::Mqtt::ReturnCode returnCode, bool) {
if (errorCode)
{
fprintf(stdout, "Connection failed with error %s\n", Aws::Crt::ErrorDebugString(errorCode));
connectionCompletedPromise.set_value(false);
}
else
{
fprintf(stdout, "Connection completed with return code %d\n", returnCode);
connectionCompletedPromise.set_value(true);
}
};

// Invoked when a disconnect message has completed.
auto onDisconnect = [&](Aws::Crt::Mqtt::MqttConnection &) {
fprintf(stdout, "Disconnect completed\n");
connectionClosedPromise.set_value();
};

// Assign callbacks
connection->OnConnectionCompleted = std::move(onConnectionCompleted);
connection->OnDisconnect = std::move(onDisconnect);
// Setup lifecycle callbacks
builder->WithClientConnectionSuccessCallback(
[&connectionPromise](const Mqtt5::OnConnectionSuccessEventData &eventData)
{
fprintf(
stdout,
"Mqtt5 Client connection succeed, clientid: %s.\n",
eventData.negotiatedSettings->getClientId().c_str());
connectionPromise.set_value(true);
});
builder->WithClientConnectionFailureCallback(
[&connectionPromise](const Mqtt5::OnConnectionFailureEventData &eventData)
{
fprintf(
stdout, "Mqtt5 Client connection failed with error: %s.\n", aws_error_debug_str(eventData.errorCode));
connectionPromise.set_value(false);
});
builder->WithClientStoppedCallback(
[&stoppedPromise](const Mqtt5::OnStoppedEventData &)
{
fprintf(stdout, "Mqtt5 Client stopped.\n");
stoppedPromise.set_value();
});

// Create Mqtt5Client
std::shared_ptr<Aws::Crt::Mqtt5::Mqtt5Client> client = builder->Build();
delete builder;
/************************ Run the sample ****************************/

// Connect
fprintf(stdout, "Connecting...\n");
if (!connection->Connect(cmdData.input_clientId.c_str(), true, 0))
if (!client->Start())
{
fprintf(stderr, "MQTT Connection failed with error %s\n", ErrorDebugString(connection->LastError()));
fprintf(stderr, "MQTT5 Connection failed to start");
exit(-1);
}

if (connectionCompletedPromise.get_future().get())
if (connectionPromise.get_future().get())
{
Aws::Iotshadow::IotShadowClient shadowClient(connection);
Aws::Iotshadow::IotShadowClient shadowClient(client);

/********************** Shadow Delta Updates ********************/
// This section is for when a Shadow document updates/changes, whether it is on the server side or client side.
Expand Down Expand Up @@ -494,9 +471,9 @@ int main(int argc, char *argv[])
}

// Disconnect
if (connection->Disconnect())
if (client->Stop())
{
connectionClosedPromise.get_future().wait();
stoppedPromise.get_future().wait();
}
return 0;
}
2 changes: 2 additions & 0 deletions shadow/include/aws/iotshadow/IotShadowClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <aws/crt/StlAllocator.h>
#include <aws/crt/Types.h>

#include <aws/crt/mqtt/Mqtt5Client.h>
#include <aws/crt/mqtt/MqttClient.h>

namespace Aws
Expand Down Expand Up @@ -103,6 +104,7 @@ namespace Aws
{
public:
IotShadowClient(const std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> &connection);
IotShadowClient(const std::shared_ptr<Aws::Crt::Mqtt5::Mqtt5Client> &mqtt5client);

operator bool() const noexcept;
int GetLastError() const noexcept;
Expand Down
4 changes: 4 additions & 0 deletions shadow/source/IotShadowClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ namespace Aws
: m_connection(connection)
{
}
IotShadowClient::IotShadowClient(const std::shared_ptr<Aws::Crt::Mqtt5::Mqtt5Client> &mqtt5client)
{
m_connection = Aws::Crt::Mqtt::MqttConnection::NewConnectionFromMqtt5Client(mqtt5client);
}

IotShadowClient::operator bool() const noexcept { return m_connection && *m_connection; }

Expand Down

0 comments on commit 2867761

Please sign in to comment.