Git Product home page Git Product logo

aws-iot-device-sdk-arduino-yun's Introduction

AWS IoT Arduino Yún SDK

What is AWS IoT Arduino Yún SDK

The AWS-IoT-Arduino-Yún-SDK allows developers to connect their Arduino Yún compatible Board to AWS IoT. By connecting the device to the AWS IoT, users can securely work with the message broker, rules and the Thing Shadow provided by AWS IoT and with other AWS services like AWS Lambda, Amazon Kinesis, Amazon S3, etc.


Overview

This document provides step by step instructions to install the Arduino Yún SDK and connect your device to the AWS IoT.
The AWS-IoT-Arduino-Yún-SDK consists of two parts, which take use of the resources of the two chips on Arduino Yún, one for native Arduino IDE API access and the other for functionality and connections to the AWS IoT built on top of AWS IoT Device SDK for Python.

MQTT connection

The AWS-IoT-Arduino-Yún-SDK provides APIs to let users publish messages to AWS IoT and subscribe to MQTT topics to receive messages transmitted by other devices or coming from the broker. This allows to interact with the standard MQTT PubSub functionality of AWS IoT. More information on MQTT protocol is available here.

Thing shadow

The AWS-IoT-Arduino-Yún-SDK also provides APIs to provide access to thing shadows in AWS IoT. Using this SDK, users will be able to sync the data/status of their devices as JSON files to the cloud and respond to change of status requested by other applications. More information on Thing Shadow is available here.


Credentials

The SDK supports two types of credentials that correspond to the two connection types:

X.509 certificate

For the certificate-based mutual authentication connection type. Download the AWS IoT root CA. Use the AWS IoT console to create and download the certificate and private key. You must upload these credentials along with the Python runtime code base to AR9331 on Yún board and specify the location of these files in a configuration file aws_iot_config.h.

IAM credentials

For the Websocket with Signature Version 4 authentication type. You will need IAM credentials: an access key ID, a secret access key. You must also download and upload the AWS IoT root CA. A tooling script AWSIoTArduinoYunWebsocketCredentialConfig.sh is provided for Mac OS/Linux users to update the IAM credentials as environment variables on AR9331, Yún board.


Installation

Download AWS-IoT-Arduino-Yún-SDK

Click here to download AWS-IoT-Arduino-Yún-SDK zip package and extract it to AWS-IoT-Arduino-Yun-SDK on your computer.

Set up your Arduino Yún Board

Please follow the instructions from official website: Arduino Yún Guide.

Installation on Mac OS/Linux

Before proceeding to the following steps, please make sure that you have expect installed on your computer and correctly installed the Arduino IDE.
To install expect:
For Ubuntu, simply run sudo apt-get install expect.
For Mac, expect is installed as default.
For Arduino IDE installation on Linux, please visit here.

  1. Setup the Arduino Yún board and connect it to WiFi. Obtain its IP address and password.
  2. Make sure your computer is connected to the same network (local IP address range).
  3. Download the AWS IoT CA file from here.
  4. Put your AWS IoT CA file, private key and certificate into AWS-IoT-Arduino-Yun-SDK/AWS-IoT-Python-Runtime/certs. If you are using MQTT over Websocket, you can put only your AWS IoT CA file into the directory. You should have a correctly configured AWS Identity and Access Management (IAM) role with a proper policy, and a pair of AWS Access Key and AWS Secret Access Key ID, which will be used in step 6. For more information about IAM, please visit AWS IAM home page.
  5. Open a terminal, cd to AWS-IoT-Arduino-Yun-SDK. Do chmod 755 AWSIoTArduinoYunInstallAll.sh and execute it as ./AWSIoTArduinoYunInstallAll.sh <Board IP> <UserName> <Board Password>. By default for Arduino Yún Board, your user name will be root and your password will be arduino.
    This script will upload the python runtime code base and credentials to openWRT running on the more powerful micro-controller on you Arduino Yún board.
    This script will also download and install libraries for openWRT to implement the necessary scripting environment as well as communication protocols.

Step 5 can take 10-15 minutes for the device to download and install the required packages (distribute, python-openssl, pip, AWSIoTPythonSDKv1.0.0).

NOTE: Do NOT close the terminal before the script finishes, otherwise you have to start over with step 5. Make sure you are in your local terminal before repeating step 5.

  1. Optional, only for Websocket. Open a terminal, cd to AWS-IoT-Arduino-Yun-SDK. Do chmod 755 AWSIoTArduinoYunWebsocketCredentialConfig.sh and execute it as ./AWSIoTArduinoYunWebsocketCredentialConfig.sh <Board iP> <UserName> <Board Password> <AWS_ACCESS_KEY_ID_STRING> <AWS_SECRET_ACCESS_KEY_STRING>.
    This script will add the given key ID and secret key onto the OpenWRT as environment variables $AWS_ACCESS_KEY_ID and $AWS_SECRET_ACCESS_KEY.

    NOTE1: You can always use this script to update your IAM credentials used on the board. The script will handle the update of the environment variables for you.

    NOTE2: Please follow the instructions on the screen after the script completes to power-cycle your board to enable all the environment changes on OpenWRT.

  2. Copy and paste AWS-IoT-Arduino-Yun-SDK/AWS-IoT-Arduino-Yun-Library folder into Arduino libraries that was installed with your Arduino SDK installation. For Mac OS default, it should be under Documents/Arduino/libraries.

  3. Restart the Arduino IDE if it was running during the installation. You should be able to see the AWS IoT examples in the Examples folder in your IDE.

There are the other two scripts: AWSIoTArduinoYunScp.sh and AWSIoTArduinoYunSetupEnvironment.sh, which are utilized in AWSIoTArduinoYunInstallAll.sh. You can always use AWSIoTArduinoYunScp.sh to upload your new credentials to your board. When you are in the directory AWS-IoT-Arduino-Yun-SDK/, the command should be something like this:

./AWSIoTArduinoYunScp.sh <Board IP> <UserName> <Board Password> <File> <Destination>


Installation on Windows

Before proceeding to the following steps, please make sure that you have Putty and WinSCP installed on your PC. If you prefer to use other tools for SSH-ing into your Arduino Yún board and transferring files, you will have to adjust the steps below according to your tools.
Putty can be downloaded from here.
WinSCP can be downloaded from here.

  1. Setup the Arduino Yún Cloud board and connect it to WiFi. Obtain its IP address and password.

  2. Make sure your PC is connected to the same network (local IP address range).

  3. Download the AWS IoT CA file from here.

  4. Put your AWS IoT CA file, private key and certificate into AWS-IoT-Arduino-Yun-SDK/AWS-IoT-Python-Runtime/certs. If you are using MQTT over Websocket, you can put only your AWS IoT CA file into the directory. You should have a correctly configured AWS Identity and Access Management (IAM) role with a proper policy, and a pair of AWS Access Key and AWS Secret Access Key ID, which will be used in step 7. For more information about IAM, please visit AWS IAM home page.

  5. Start WinSCP and upload AWS-IoT-Python-Runtime/ folder to /root on the board.

  6. Use Putty to ssh into OpenWRT on your board and execute the following commands to install the necessary libraries:

     opkg update
     opkg install distribute
     opkg install python-openssl
     easy_install pip
     pip install AWSIoTPythonSDK==1.0.0
    

It can take 10-15 minutes for the device to download and install the required packages.

  1. Optional, only for Websocket. Use Putty to ssh into OpenWRT on your board and modify /etc/profile to include your IAM credentials as environment variables:

     ...
     export AWS_ACCESS_KEY_ID=<AWS_ACCES_KEY_ID_STRING>
     export AWS_SECRET_ACCESS_KEY=<AWS_SECRET_ACCESS_KEY_STRING>
     ...
    

After that, run source /etc/profile and power-cycle the board to enable the changes.

  1. Copy and paste AWS-IoT-Arduino-Yun-SDK/AWS-IoT-Arduino-Yun-Library folder into Arduino libraries that was installed with your Arduino SDK installation. For Windows default, it should be under Documents/Arduino/libraries.
  2. Restart the Arduino IDE if it was running during the installation. You should be able to see the AWS IoT examples in the Examples folder in your IDE.

API documentation

Class Name:

aws_iot_mqtt_client

API:

Message Callback:
void(*message_callback)(char*, unsigned int, Message_status_t)

IoT_Error_t setup(const char* client_id, bool clean_session, MQTTv_t MQTT_version, bool useWebsocket)

Description
Start the Python runtime and set up connection for aws_iot_mqtt_client object. Must be called before any of aws_iot_mqtt_client API is called.

Syntax

object.setup("myClientID"); // setup a client with client_id set to "myClientID"
object.setup("myClientID", true, MQTTv31, true); // setup a client with client_id set to "myClientID", with clean_session set to true, using MQTT 3.1, over Websocket

Parameters
client_id - The client id for this connection.
clean_session - Clear the previous connection with this id or not. Default value is true.
MQTT_version - Version of MQTT protocol for this connection, either MQTTv31 (MQTT version 3.1) or MQTTv311 (MQTT version 3.1.1). Default value is MQTTv311.
useWebsocket - Enable the use of Websocket or not. Default value is false. IAM credentials must be included in the environment variables on OpenWRT to make a successful MQTT connection over Websocket.

Returns
NONE_ERROR if the setup on openWRT side and connection settings are correct.
NULL_VALUE_ERROR if input parameters have NULL value.
OVERFLOW_ERROR if input string exceeds the internal buffer size.
SET_UP_ERROR if the setup failed.
SERIAL1_COMMUNICATION_ERROR if there is an error in Serial1 communication between the two chips.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t config(const char* host, unsigned int port, const char* cafile_path, const char* keyfile_path, const char* certfile_path)

Description
Configure host, port and certs location used to connect to AWS IoT. If the input strings for host, cafile_path, keyfile_path and certfile_path are set to NULL, the default value will be used to connect. Must be called to load user settings right after aws_iot_mqtt_client::setup and before connect.

Syntax

object.config("example.awsamazon.com", 1234, "./cafile", "./keyfile", "./certfile");

Parameters
host - The endpoint to connect to. Must be a NULL-terminated string.
port - The port number to connect to.
cafile_path - The path of CA file on OpenWRT. Must be a NULL-terminated string.
keyfile_path - The path of private key file on OpenWRT. Must be a NULL-terminated string.
certfile_path - The path of certificate file on OpenWRT. Must be a NULL-terminated string.

Returns
NONE_ERROR if the configuration is successful.
NO_SET_UP_ERROR if no setup is called before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
CONFIG_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t configWss(const char* host, unsigned int port, const char* cafile_path)

Description
Configure host, port and rootCA location used to connect to AWS IoT over Websocket. If the input strings for host and cafile_path are set to NULL, the default value will be used to connect. Must be called to load user settings right after aws_iot_mqtt_client::setup and before connect. The client must be configured in setup to use Websocket.

Syntax

object.configWss("example.awsamazon.com", 1234, "./cafile");

Parameters
host - The endpoint to connect to. Must be a NULL-terminated string.
port - The port number to connect to.
cafile_path - The path of CA file on OpenWRT. Must be a NULL-terminated string.

Returns
NONE_ERROR if the configuration is successful.
NO_SET_UP_ERROR if no setup is called before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
CONFIG_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t configBackoffTiming(unsigned int baseReconnectQuietTimeSecond, unsigned int maxReconnectQuietTimeSecond, unsigned int stableConnectionTimeSecond)

Description
Configure the progressive back-off timing on reconnect. Time interval for reconnect attempt will increase/double from baseReconnectQuietTimeSecond to maxReconnectQuietTimeSecond. Once a connection is live for longer than stableConnectionTimeSecond, the time interval will be reset to baseReconnectQuietTimeSecond. Note that stableConnectionTimeSecond must be greater than baseReconnectQuietTimeSecond. More details about progressive back-off can be found here.

Note that if this API is not called, the following default values will be used to configure the back-off timing:

baseReconnectQuietTimeSecond = 1;
maxReconnectQuietTimeSecond = 128;
stableConnectionTimeSecond = 20;

Syntax

object.configBackoffTiming(1, 32, 20); // Configure baseReconnectQuietTimeSecond to be 1 second. Configure maxReconnectQuietTimeSecond to be 32 seconds. Configure stableConnectionTimeSecond to be 20 seconds.

Parameters
baseReconnectQuietTimeSecond - Number of seconds to start with for progressive back-off on reconnect.
maxReconnectQuietTimeSecond - Maximum number of seconds for progressive back-off on reconnect.
stableConnectionTimeSecond - Number of seconds for a valid connection to be considered stable.

IoT_Error_t configOfflinePublishQueue(unsigned int queueSize, DropBehavior_t behavior)

Description
Configure the internal queue size and its drop behavior once the queue is full in the Python runtime on the OpenWRT side. When the client is offline, publish requests will be queued up and get resent once the network connection is back. If the number of publish requests exceeds the maximum size of the queue configured, dropping will happen according the drop behavior configured by this API. More details about offline publish requests queuing can be found here.

Syntax

object.configOfflinePublishQueue(20, DROP_OLDEST); // Configure size of the offline publish requests queue to be 20. Configure the queue to drop the oldest requests once the queue is full.
object.configOfflinePublishQueue(20, DROP_NEWEST); // Configure size of the offline publish requests queue to be 20. Configure the queue to drop the newest requests once the queue is full.
object.configOfflinePublishQueue(0, DROP_OLDEST); // Configure size of the offline publish requests queue to be infinite. The queue-full drop behavior is ignored when the size if infinite.
object.configOfflinePublishQueue(-1, DROP_OLDEST); // Disable the offline publish requests queue. The queue-full drop behavior is ignored when the queue is disabled.

Parameters
queueSize - The size of the offline publish requests queue, determining how many publish requests can be queued up while the client it offline.
behavior - The drop behavior when the offline publish requests queue is full. Can be configured to drop the oldest requests or the newest requests in the queue.

Returns
NONE_ERROR if the configuration is successful.
NO_SET_UP_ERROR if no setup is called before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
CONFIG_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t configDrainingInterval(float numberOfSeconds)

Description
Configure the draining interval for requests to be sent out when client is back online and gets connected. This will affect the outbound rate for republish and resubscribe requests. More details about draining can be found here.

Syntax

object.configDrainingInterval(0.5); // Configure the draining interval to be 0.5 seconds. In this way, resubscribe requests, if any, will be sent per 0.5 seconds. Offline publish requests, if any in the queue, will be sent per 0.5 seconds.

Parameters
numberOfSeconds - Number of seconds to wait between every resubscribe/republish request when the client is back online and connected.

Returns
NONE_ERROR if the configuration is successful.
NO_SET_UP_ERROR if no setup is called before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
CONFIG_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t connect(unsigned int keepalive_interval)

Description
Connect to AWS IoT, using user-specific keepalive setting.

Syntax

object.connect(); // connect to AWS IoT with default keepalive set to 60 seconds
object.connect(55); // connect to AWS IoT with keepalive set to 55 seconds

Parameters
keepalive_interval - amount of time for MQTT ping request interval, in seconds. Default is set to 60 seconds.

Returns
NONE_ERROR if the connect is successful.
NO_SET_UP_ERROR if no setup is called before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
CONNECT_SSL_ERROR if the TLS handshake failed.
CONNECT_ERROR if the connection failed.
CONNECT_TIMEOUT if the connection gets timeout.
CONNECT_CREDENTIAL_NOT_FOUND if the specified credentials are not found on OpenWRT.
WEBSOCKET_CREDENTIAL_NOT_FOUND if the IAM credentials do not exist as environment variables on OpenWRT.
CONNECT_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t publish(const char* topic, const char* payload, unsigned int payload_len, unsigned int qos, bool retain)

Description
Publish a new message to the desired topic with qos and retain flag settings using MQTT protocol

Syntax

object.publish("myTopic", "myMessage", strlen("myMessage"), 0, false); // publish "myMessage" to topic "myTopic" in QoS 0 with retain flag set to false

Parameters
topic - Topic name to publish to. Must be a NULL-terminated string.
payload - Payload to publish.
payload_len - Length of payload.
qos - Qualiy of service, could be 0 or 1.
retain - retain flag.

Returns
NONE_ERROR if the publish is successful.
NULL_VALUE_ERROR if input parameters have NULL value.
OVERFLOW_ERROR if topic/payload exceeds the internal buffer size.
NO_SET_UP_ERROR if no setup is called before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
PUBLISH_ERROR if the publish failed.
PUBLISH_TIMEOUT if the publish gets timeout.
PUBLISH_QUEUE_FULL if the internal offline publish requests queue is full.
PUBLISH_QUEUE_DISABLED if the internal offline publish requests queue is disabled.
PUBLISH_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t subscribe(const char* topic, unsigned int qos, message_callback cb)

Description
Subscribe to the desired topic and register a callback for new messages from this topic.

Syntax

object.subscribe("myTopic", 0, myCallbackFunc); // subscribe to topic "myTopic" in QoS 0 and register its callback function as myCallbackFunc

Parameters
topic - The topic to subscribe to. Must be a NULL-terminated string.
qos - Quality of service, could be 0 or 1.
cb - Function pointer to user-specific callback function to call when a new message comes in for the subscribed topic. The callback function should have a parameter list of (char*, unsigned int, Message_status_t) to store the incoming message content and the length of the message.

Returns
NONE_ERROR if the subscribe is successful.
NULL_VALUE_ERROR if input parameters have NULL value.
OVERFLOW_ERROR if topic/payload exceeds the internal buffer size.
OUT_OF_SKETCH_SUBSCRIBE_MEMORY if the number of current subscribe exceeds the configured number in aws_iot_config_SDK.h.
NO_SET_UP_ERROR if no setup is called before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
SUBSCRIBE_ERROR if the subscribe failed.
SUBSCRIBE_TIMEOUT if the subscribe gets timeout.
SUBSCRIBE_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t unsubscribe(const char* topic)

Description
Unsubscribe to the desired topic.

Syntax

object.unsubscribe("myTopic");

Parameters
topic - The topic to unsubscribe to. Must be a NULL-terminated string.

Returns
NONE_ERROR if the unsubscribe is successful.
NULL_VALUE_ERROR if input parameters have NULL value.
OVERFLOW_ERROR if topic exceeds the internal buffer size.
NO_SET_UP_ERROR if no setup is called before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
UNSUBSCRIBE_ERROR if the unsubscribe failed.
UNSUBSCRIBE_TIMEOUT if the unsubscribe gets timeout.
UNSUBSCRIBE_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t yield()

Description
Called in the loop to check if there is a new message from all subscribed topics, as well as thing shadow topics. Registered callback functions will be called according to the sequence of messages if there is any. Specifically, unnecessary shadow thing topics (accepted/rejected) will be unsubscribed according to the incoming new messages to free subscribe slots. Users should call this function frequently to receive new messages and free subscribe slots for new subscribes, especially for shadow thing requests.

Syntax

object.yield();

Parameters
None

Returns
NONE_ERROR if the yield is successful, whether there is a new message or not.
OVERFLOW_ERROR if the new message exceeds the internal buffer size.
YIELD_ERROR if the yield failed.

IoT_Error_t disconnect()

Description
Disconnect from AWS IoT.

Syntax

object.disconnect();

Parameters
None

Returns
NONE_ERROR if disconnect is successful.
NO_SET_UP_ERROR if no setup is called before this call.
DISCONNECT_ERROR if the disconnect failed.
DISCONNECT_TIMEOUT if the disconnect gets timeout.
DISCONNECT_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t shadow_init(const char* thingName)

Description
Initialize thing shadow configuration and a shadow instance with thingName. Should be called before any of the thing shadow API call for thingName shadow operations.

Syntax

object.shadow_init("NewThingName"); // Init thing shadow configuration and set thing name to "NewThingName"

Parameters
thingName - Thing name for the shadow instance to be created. Must be a NULL-terminated string.

Returns
NONE_ERROR if thing shadow is successfully initialized.
NULL_VALUE_ERROR if input parameters have NULL value.
OVERFLOW_ERROR if thing name exceeds the internal buffer size.
SHADOW_INIT_ERROR if thing shadow initialization failed.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t shadow_update(const char* thingName, const char* payload, unsigned int payload_len, message_callback cb, unsigned int timeout)

Description
Update the thing shadow data in the cloud by publishing a new JSON file onto the corresponding thing shadow topic and subscribing accepted/rejected thing shadow topics to get feedback of whether it is a successful/failed request. Timeout can be set in seconds as the maximum waiting time for feedback. Once the request gets timeout, a timeout message will be received. The registered callback function will be called whenever there is an accepted/rejected/timeout feedback. Subscription to accepted/rejected topics will be processed in a persistent manner and will not be unsubscribed once this API is called for this shadow.

Syntax

object.shadow_update("UserThingName", JSON_FILE, strlen(JSON_FILE), UserCallbackFunction, 5); // update the data of "UserThingName" thing shadow in the cloud to JSON_FILE, with a timeout of 5 seconds and UserCallbackFunction as the callback function

Parameters
thingName - The name of the thing shadow in the cloud. Must be a NULL-terminated string.
payload - The data that needs to be updated into the cloud, in JSON file format.
payload_len - Length of payload
cb - Function pointer to user-specific callback function to call when a new message comes in for the subscribed topic. The callback function should have a parameter list of (char*, unsigned int, Message_status_t) to store the incoming message content and the length of the message.
timeout - The maximum time to wait for feedback.

Returns
NONE_ERROR if the shadow update request succeeds.
NULL_VALUE_ERROR if input parameters have NULL value.
OVERFLOW_ERROR if thing name/payload exceeds the internal buffer size.
OUT_OF_SKETCH_SUBSCRIBE_MEMORY if the number of current subscribe exceeds the configured number in aws_iot_config_SDK.h.
NO_SHADOW_INIT_ERROR if the shadow with thingName is initialized before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
SUBSCRIBE_ERROR if the subscribe (accepted/rejected) failed.
SUBSCRIBE_TIMEOUT if the subscribe gets timeout.
PUBLISH_ERROR if the publish (payload) failed.
PUBLISH_TIMEOUT if the publish (payload) gets timeout.
PUBLISH_QUEUE_FULL if the publish action failed because of a full internal offline publish requests queue.
PUBLISH_QUEUE_DISABLED if the publish action failed because of a disabled internal offline publish requests queue.
SHADOW_UPDATE_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t shadow_get(const char* thingName, message_callback cb, unsigned int timeout)

Description
Obtain the thing shadow data in the cloud by publishing an empty JSON file onto the corresponding thing shadow topic and subscribing accepted/rejected thing shadow topics to get feedback of whether it is a successful/failed request. Timeout can be set in seconds as the maximum waiting time for feedback. Once the request gets timeout, a timeout message will be received. The registered callback function will be called whenever there is an accepted/rejected/timeout feedback. Subscription to accepted/rejected topics will be processed in a persistent manner and will not be unsubscribed once this API is called for this shadow. Thing shadow data will be available as a JSON file in the callback.

Syntax

object.shadow_get("UserThingName", UserCallbackFunction, 5); // get the data of the thing shadow "UserThingName", with a timeout of 5 seconds and UserCallbackFunction as the callback function

Parameters
thingName - The name of the thing shadow in the cloud. Must be a NULL-terminated string.
cb - Function pointer to user-specific callback function to call when a new message comes in for the subscribed topic. The callback function should have a parameter list of (char*, unsigned int, Message_status_t) to store the incoming message content and the length of the message.
timeout - The maximum time to wait for feedback.

Returns
NONE_ERROR if the shadow get request succeeds.
NULL_VALUE_ERROR if input parameters have NULL value.
OVERFLOW_ERROR if thing name exceeds the internal buffer size.
OUT_OF_SKETCH_SUBSCRIBE_MEMORY if the number of current subscribe exceeds the configured number in aws_iot_config_SDK.h.
NO_SHADOW_INIT_ERROR if the shadow with thingName is initialized before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
SUBSCRIBE_ERROR if the subscribe (accepted/rejected) failed.
SUBSCRIBE_TIMEOUT if the subscribe gets timeout.
PUBLISH_ERROR if the publish (payload) failed.
PUBLISH_TIMEOUT if the publish (payload) gets timeout.
PUBLISH_QUEUE_FULL if the publish action failed because of a full internal offline publish requests queue.
PUBLISH_QUEUE_DISABLED if the publish action failed because of a disabled internal offline publish requests queue.
SHADOW_GET_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t shadow_delete(const char* thingName, message_callback cb, unsigned int timeout)

Description
Delete the thing shadow data in the cloud by publishing an empty JSON file onto the corresponding thing shadow topic and subscribing accepted/rejected thing shadow topics to get feedback of whether it is a successful/failed request. Timeout can be set in seconds as the maximum waiting time for feedback. Once the request gets timeout, a timeout message will be received. The registered callback function will be called whenever there is an accepted/rejected/timeout feedback. After the feedback comes in, it will automatically unsubscribe accepted/rejected shadow topics.

Syntax

object.shadow_delete("UserThingName", UserCallbackFunction, 5); // delete the data of the thing shadow "UserThingName", with a timeout of 5 seconds and UserCallbackFunction as the callback function

Parameters
thingName - The name of the thing shadow in the cloud. Must be a NULL-terminated string.
cb - Function pointer to user-specific callback function to call when a new message comes in for the subscribed topic. The callback function should have a parameter list of (char*, unsigned int, Message_status_t) to store the incoming message content and the length of the message.
timeout - The maximum time to wait for feedback.

Returns
NONE_ERROR if the shadow delete request succeeds.
NULL_VALUE_ERROR if input parameters have NULL value.
OVERFLOW_ERROR if thing name exceeds the internal buffer size.
OUT_OF_SKETCH_SUBSCRIBE_MEMORY if the number of current subscribe exceeds the configured number in aws_iot_config_SDK.h.
NO_SHADOW_INIT_ERROR if the shadow with thingName is initialized before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
SUBSCRIBE_ERROR if the subscribe (accepted/rejected) failed.
SUBSCRIBE_TIMEOUT if the subscribe gets timeout.
PUBLISH_ERROR if the publish (payload) failed.
PUBLISH_TIMEOUT if the publish (payload) gets timeout.
PUBLISH_QUEUE_FULL if the publish action failed because of a full internal offline publish requests queue.
PUBLISH_QUEUE_DISABLED if the publish action failed because of a disabled internal offline publish requests queue.
SHADOW_DELETE_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t shadow_register_delta_func(const char* thingName, message_callback cb)

Description
Subscribe to the delta topic of the corresponding thing shadow with the given name and register a callback. Whenever there is a difference between the desired and reported state data, the registered callback will be called and the feedback/message will be available in the callback.

Syntax

object.shadow_register_delta_func("UserThingName", UserCallBackFunction); // register UserCallbackFunction as the  delta callback function for the thing shadow "UserThingName"

Parameters
thingName - The name of the thing shadow in the cloud. Must be a NULL-terminated string.
cb - Function pointer to user-specific callback function to call when a new message comes in for the subscribed topic. The callback function should have a parameter list of (char*, unsigned int, Message_status_t) to store the incoming message content and the length of the message.

Return
NONE_ERROR if the shadow delta topic is successfully subscribed and the callback function is successfully registered.
NULL_VALUE_ERROR if input parameters have NULL value.
OVERFLOW_ERROR if thing name exceeds the internal buffer size.
OUT_OF_SKETCH_SUBSCRIBE_MEMORY if the number of current subscribe exceeds the configured number in aws_iot_config_SDK.h.
NO_SHADOW_INIT_ERROR if the shadow with thingName is initialized before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
SUBSCRIBE_ERROR if the subscribe (accepted/rejected) failed.
SUBSCRIBE_TIMEOUT if the subscribe gets timeout.
SHADOW_REGISTER_DELTA_CALLBACK_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t shadow_unregister_delta_func(const char* thingName)

Description
Unsubscribe to the delta topic of the corresponding thing shadow with the given name and unregister the callback. There will be no message coming after this API call if another difference occurs between the desired and reported state data for this thing shadow.

Syntax

object.shadow_unregister_delta_func("UserThingName"); // unregister the delta topic of the thing shadow "UserThingName"

Parameters
thingName - The name of the thing shadow in the cloud. Must be a NULL-terminated string.

Returns
NONE_ERROR if the shadow delta topic is successfully unsubscribed and the callback function is successfully unregistered.
NULL_VALUE_ERROR if input parameters have NULL value.
OVERFLOW_ERROR if thing name exceeds the internal buffer size.
NO_SHADOW_INIT_ERROR if the shadow with thingName is initialized before this call.
WRONG_PARAMETER_ERROR if there is an error for the Python Runtime to get enough input parameters for this command.
UNSUBSCRIBE_ERROR if the subscribe (accepted/rejected) failed.
UNSUBSCRIBE_TIMEOUT if the subscribe gets timeout.
SHADOW_UNREGISTER_DELTA_CALLBACK_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t getDesiredValueByKey(const char* JSONIdentifier, const char* key, char* externalJSONBuf, unsigned int bufSize)

Description
Get the value by key in the desired section in the shadow JSON document denoted by the provided identifier. The corresponding value will be stored as a string into a user-specified externalBuffer. Nested key-value access is available. More information can be found here.

Syntax

object.getDesiredValueByKey("JSON-0", "property1", someBuffer, someBufferSize); // Access JSONDocument["state"]["desired"]["property1"] denoted by JSONIdentifier "JSON-0" and store the value in someBuffer
object.getDesiredValueByKey("JSON-0", "property2\"subproperty", someBuffer, someBufferSize); // Access JSONDocument["state"]["desired"]["property2"]["subproperty"] denoted by JSONIdentifier "JSON-0" and store the value in someBuffer 

Parameters
JSONIdentifier - The JSON Identifier string to access a certain JSON document stored in Python runtime on the OpenWRT side. This is obtained from the registered shadow callback as shadow responses.
key - The key for dereferencing out the value in the desired section of the JSON document. Nested key can be specified using " as the delimiter.
externalJSONBuf - Buffer specified by the user to store the incoming value, as string.
bufSize - Size of the buffer to store the incoming value, as string.

Returns
NONE_ERROR if the value is retrieved successfully.
NO_SET_UP_ERROR if no setup is called before this call.
OVERFLOW_ERROR if the length of the incoming value exceeds the size of the provided externalJSONBuf.
JSON_FILE_NOT_FOUND if the JSON document with the provided JSON identifier does not exist.
JSON_KEY_NOT_FOUND if the specified key does not exist in the JSON document denoted by the provided JSON identifier.
JSON_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t getReportedValueByKey(const char* JSONIdentifier, const char* key, char* externalJSONBuf, unsigned int bufSize)]

Description
Get the value by key in the reported section in the shadow JSON document denoted by the provided identifier. The corresponding value will be stored as a string into a user-specified externalBuffer. Nested key-value access is available. More information can be found here.

Syntax

object.getReportedValueByKey("JSON-0", "property1", someBuffer, someBufferSize); // Access JSONDocument["state"]["reported"]["property1"] denoted by JSONIdentifier "JSON-0" and store the value in someBuffer
object.getReportedValueByKey("JSON-0", "property2\"subproperty", someBuffer, someBufferSize); // Access JSONDocument["state"]["reported"]["property2"]["subproperty"] denoted by JSONIdentifier "JSON-0" and store the value in someBuffer 

Parameters
JSONIdentifier - The JSON Identifier string to access a certain JSON document stored in Python runtime on the OpenWRT side. This is obtained from the registered shadow callback as shadow responses.
key - The key for dereferencing out the value in the reported section of the JSON document. Nested key can be specified using " as the delimiter.
externalJSONBuf - Buffer specified by the user to store the incoming value, as string.
bufSize - Size of the buffer to store the incoming value, as string.

Returns
NONE_ERROR if the value is retrieved successfully.
NO_SET_UP_ERROR if no setup is called before this call.
OVERFLOW_ERROR if the length of the incoming value exceeds the size of the provided externalJSONBuf.
JSON_FILE_NOT_FOUND if the JSON document with the provided JSON identifier does not exist.
JSON_KEY_NOT_FOUND if the spedified key does not exist in the JSON document denoted by the provided JSON identifier.
JSON_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t getDeltaValueByKey(const char* JSONIdentifier, const char* key, char* externalJSONBuf, unsigned int bufSize)]

Description
Get the value by key in the state section in the shadow JSON document denoted by the provided identifier. The corresponding value will be stored as a string into a user-specified externalBuffer. Nested key-value access is available. More information can be found here.

Syntax

object.getDeltaValueByKey("JSON-0", "property1", someBuffer, someBufferSize); // Access JSONDocument["state"]["property1"] denoted by JSONIdentifier "JSON-0" and store the value in someBuffer
object.getDeltaValueByKey("JSON-0", "property2\"subproperty", someBuffer, someBufferSize); // Access JSONDocument["state"]["property2"]["subproperty"] denoted by JSONIdentifier "JSON-0" and store the value in someBuffer 

Parameters
JSONIdentifier - The JSON Identifier string to access a certain JSON document stored in Python runtime on the OpenWRT side. This is obtained from the registered shadow callback as shadow responses.
key - The key for dereferencing out the value in the state section of the JSON document. Nested key can be specified using " as the delimiter.
externalJSONBuf - Buffer specified by the user to store the incoming value, as string.
bufSize - Size of the buffer to store the incoming value, as string.

Returns
NONE_ERROR if the value is retrieved successfully.
NO_SET_UP_ERROR if no setup is called before this call.
OVERFLOW_ERROR if the length of the incoming value exceeds the size of the provided externalJSONBuf.
JSON_FILE_NOT_FOUND if the JSON document with the provided JSON identifier does not exist.
JSON_KEY_NOT_FOUND if the specified key does not exist in the JSON document denoted by the provided JSON identifier.
JSON_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

IoT_Error_t getValueByKey(const char* JSONIdentifier, const char* key, char* externalJSONBuf, unsigned int bufSize)]

Description
Get the value by key in the shadow JSON document denoted by the provided identifier. The corresponding value will be stored as a string into a user-specified externalBuffer. Nested key-value access is available. More information can be found here.

Syntax

object.getValueByKey("JSON-0", "property1", someBuffer, someBufferSize); // Access JSONDocument["property1"] denoted by JSONIdentifier "JSON-0" and store the value in someBuffer
object.getValueByKey("JSON-0", "property2\"subproperty", someBuffer, someBufferSize); // Access JSONDocument["property2"]["subproperty"] denoted by JSONIdentifier "JSON-0" and store the value in someBuffer 

Parameters
JSONIdentifier - The JSON Identifier string to access a certain JSON document stored in Python runtime on the OpenWRT side. This is obtained from the registered shadow callback as shadow responses.
key - The key for dereferencing out the value in the JSON document. Nested key can be specified using " as the delimiter.
externalJSONBuf - Buffer specified by the user to store the incoming value, as string.
bufSize - Size of the buffer to store the incoming value, as string.

Returns
NONE_ERROR if the value is retrieved successfully.
NO_SET_UP_ERROR if no setup is called before this call.
OVERFLOW_ERROR if the length of the incoming value exceeds the size of the provided externalJSONBuf.
JSON_FILE_NOT_FOUND if the JSON document with the provided JSON identifier does not exist.
JSON_KEY_NOT_FOUND if the specified key does not exist in the JSON document denoted by the provided JSON identifier.
JSON_GENERIC_ERROR if there is an error in executing the command in Python Runtime.
GENERIC_ERROR if an unknown error happens.

void(*message_callback)(char*, unsigned int, Message_status_t)]

Description
Callback function for received MQTT messages, used for plain MQTT communications as well as shadow communications.
For plain MQTT messages, message payload and size will be passed into the callback. Message_status_t will be STATUS_NORMAL. See Parameters below for more details.
For shadow messages, JSON identifier and its size will be passed into the callback. Message_status_t varies for shadow messages from different topics. For accept shadow responses, Message_status_t will be STATUS_SHADOW_ACCEPTED. For reject shadow responses, Message_status_t will be STATUS_SHADOW_REJECTED. For delta shadow responses, Message_status_t will be STATUS_NORMAL. See Parameters below for more details.

Syntax

void custom_message_callback(char* msg, unsigned int length, Message_status_t status) {
	// * Access the incoming message from msg, length
	// Message payload for plain MQTT messages
	// JSON identifer for shadow messages
	// * Access the message status from status
	// STATUS_NORMAL for plain MQTT/shadow delta messages
	// STATUS_SHADOW_ACCEPTED for shadow accept responses
	// STATUS_SHADOW_REJECTED for shadow reject responses
}

Parameters
char* - Incoming message. Message payload for plain MQTT messages and JSON identifier for shadow message/responses.
unsigned int - Length of bytes of the incoming message.
Message_status_t - Status of the incoming responses/messages. It has the following values:

typedef enum {
	STATUS_DEBUG = -1,
	STATUS_NORMAL = 0,
	STATUS_SHADOW_TIMEOUT = 1,
	STATUS_SHADOW_ACCEPTED = 2,
	STATUS_SHADOW_REJECTED = 3,
	STATUS_MESSAGE_OVERFLOW = 4
} Message_status_t;

STATUS_NORMAL indicates that a new plain MQTT message/shadow delta message has arrived.
STATUS_SHADOW_TIMEOUT indicates that the incoming message is a shadow response for an operation timeout. There was no response received for the corresponding shadow operation within the preconfigured timeout.
STATUS_SHADOW_ACCEPTED indicates that the incoming message is a shadow response for accept. The corresponding shadow operation was accepted by the AWS IoT service and has succeeded.
STATUS_SHADOW_REJECTED indicates that the incoming message is a shadow response for reject. The corresponding shadow operation was rejected by the AWS IoT service and has failed.
STATUS_MESSAGE_OVERFLOW indicates that the size of the incoming message has exceeded the size of the internal message buffer. Internal message buffer size, configured in aws_iot_config_SDK.h, needs to be increased to receive the complete incoming message.
STATUS_DEBUG is for SDK internal use.

Returns
No returns.


Key features

Individual Key Value Access for Shadow

As for shadow operations (Get/Update/Delete) and shadow delta messages, instead of detailed the message content for shadow JSON document, a JSON identifier will be passed through into the registered callback so that it can be used for key/value pair access on demand through the individual key/value pair access APIs. A JSON identifier of a shadow JSON response received looks like this:

JSON-i

where i is an integer number.

Note that there is a limitation on the total number of history JSON documents that can be kept on the OpenWRT side for key/value pair retrieval. The limits are:

512 entries for shadow JSON accepted responses
512 entries for shadow JSON rejected responses
512 entries for shadow JSON delta messages

Once the limits are exceeded, new incoming shadow JSON documents will overwrite history entries starting from the beginning (JSON-0, JSON-1 and JSON-2).

The following APIs are provided for uses to access shadow JSON key value pair from Arduino sketch in an easier manner:
IoT_Error_t getDesiredValueByKey(const char* JSONIdentifier, const char* key, char* externalJSONBuf, unsigned int bufSize)
IoT_Error_t getReportedValueByKey(const char* JSONIdentifier, const char* key, char* externalJSONBuf, unsigned int bufSize)
IoT_Error_t getDeltaValueByKey(const char* JSONIdentifier, const char* key, char* externalJSONBuf, unsigned int bufSize)
IoT_Error_t getValueByKey(const char* JSONIdentifier, const char* key, char* externalJSONBuf, unsigned int bufSize)

For a typical shadow JSON document (responses for get/update/delete), it should look like this:

{
	"state": {
		"desired": {
			...
		},
		"reported": {
			...
		}
	},
	...
}

getDesiredValueByKey and getReportedValueByKey can be used to access the key value pair in the desired/reported section respectively.

For a typical shadow JSON document (messages for delta), it should look like this:

{
	"state": {
		...
	},
	...
}

getDeltaValueByKey can be used to access the key value pair in the delta shadow JSON messages.

More generally, getValueByKey can be used to access key value pair in a more generic way where users can specify their own key patterns. Nested JSON key is denoted using " as the delimiter.

For example, we have the following shadow JSON document with a JSON identifier JSON-0:

{
	"state": {
		"desired": {
			"property1": "value1",
			"property2": {
				"subproperty": "value2"
			}
		},
		"reported": {
			"property3": "value3"
		}
	},
	...
}

To access a series of key value pair, we can use the following function calls:

object.getDesiredValueByKey("JSON-0", "property1", buffer, bufferSize); // Access JSONDocument["state"]["desired"]["property1"]
object.getReportedValueByKey("JSON-0", "property3", buffer, bufferSize); // Access JSONDocument["state"]["reported"]["property3"]
object.getDesiredValueByKey("JSON-0", "property2\"subproperty", buffer, bufferSize); // Access JSONDocument["state"]["desired"]["property2"]["subproperty"]

Note that the following two function calls are equivalent. They both access the nested JSON key value pair JSONDocument["state"]["desired"]["property2"]["subproperty"]:

object.getDesiredValueByKey("JSON-0", "property2\"subproperty", buffer, bufferSize);
object.getValueByKey("JSON-0", "state\"desired\"property2\"subproperty", buffer, bufferSize);

See that getValueByKey is a more generic way for shadow JSON key value access.

For detailed use cases, please check out Examples.

Progressive Reconnect Back-off

API is provided to configure the progressive back-off timing parameters:
IoT_Error_t configBackoffTiming(unsigned int baseReconnectQuietTimeSecond, unsigned int maxReconnectQuietTimeSecond, unsigned int stableConnectionTimeSecond)

The auto-reconnect happens with a progressive back-off, which follows the following mechanism for reconnect quiet time:

tcurrent = min(2ntbase, tmax),

where tcurrent is the current reconnect quiet time, tbase is the base reconnect quiet time, tmax is the maximum reconnect quiet time.

The reconnect quiet time will be doubled on disconnect and reconnect attempt until it reaches the preconfigured maximum reconnect quiet time. Once the connection is stable for over the stableConnectionTime, the reconnect quiet time will be reset to the baseReconnectQuietTime.

If no configBackoffTiming gets called, the following default configuration for back-off timing will be done on setup call:

baseReconnectQuietTimeSecond = 1;
maxReconnectQuietTimeSecond = 128;
stableConnectionTimeSecond = 20;

Offline publish requests queuing with draining

APIs are provided to configure the offline publish requests queuing (size and drop behavior) as well as draining intervals:
IoT_Error_t configOfflinePublishQueue(unsigned int queueSize, DropBehavior_t behavior)
IoT_Error_t configDrainingInterval(float numberOfSeconds)

When the client is temporarily offline and gets disconnected due to some network failure, publish requests will be queued up into an internal queue in the Python runtime on the OpenWRT side until the number of queued-up requests reaches to the size limit of the queue. Once the queue is full, offline publish requests will be discarded or replaced according to different configuration of the drop behavior:

typedef enum {
	DROP_OLDEST = 0,
	DROP_NEWEST = 1
} DropBehavior_t;

Lets say we configure the size of offlinePublishQueue to be 5 and we have 7 offline publish requests coming in...

In a DROP_OLDEST configuration:

myClient.configOfflinePublishQueue(5, DROP_OLDEST);

The internal queue should be like this when the queue is just full:

HEAD ['pub_req0', 'pub_req1', 'pub_req2', 'pub_req3', 'pub_req4']

When the 6th and the 7th publish requests are made offline, the internal queue will be like this:

HEAD ['pub_req2', 'pub_req3', 'pub_req4', 'pub_req5', 'pub_req6']

Since the queue is already full, the oldest requests pub_req0 and pub_req1 are discarded.

In a DROP_NEWEST configuration:

myClient.configOfflinePublishQueue(5, DROP_NEWEST);

The internal queue should be like this when the queue is just full:

HEAD ['pub_req0', 'pub_req1', 'pub_req2', 'pub_req3', 'pub_req4']

When the 6th and the 7th publish requests are made offline, the internal queue will be like this:

HEAD ['pub_req0', 'pub_req1', 'pub_req2', 'pub_req3', 'pub_req4']

Since the queue is already full, the newest requests pub_req5 and pub_req6 are discarded.

When the client is back online, connected and resubscribed to all topics that it has previously subscribed to, the draining starts. All requests in the offline publish queue will be resent at the configured draining rate.

if no configOfflinePublishQueue or configDrainingInterval is called, the following default configuration for offline publish queuing and draining will be done on setup call:

offlinePublishQueueSize = 20
dropBehavior = DROP_NEWEST
drainingInterval = 0.5 sec

Note that before the draining process finishes, any new publish request within this time will be added to the queue. Therefore, draining rate should be higher than the normal publish rate to avoid an endless draining process after reconnect.

Also note that disconnect event is detected based on PINGRESP MQTT packet loss. Offline publish queuing will NOT be triggered until the disconnect event gets detected. Configuring a shorter keep-alive interval allows the client to detect disconnects more quickly. Any QoS0 publish requests issued after the network failure and before the detection of the PINGRESP loss will be lost.

Using the SDK

Make sure you have properly installed the AWS-IoT-Arduino-Yún-SDK and setup the board.

Make sure to start the sketch after openWRT is ready and gets connected to WiFi. It takes about 80-90 seconds for Arduino Yún board to start the openWRT and get connected to WiFi for each power cycle.

Make sure you have properly configured SDK settings in aws_iot_config.h inside each sketch directory:

//===============================================================
#define AWS_IOT_MQTT_HOST "<RANDOM_STRING>.iot.<REGION>.amazonaws.com" 	// your endpoint
#define AWS_IOT_MQTT_PORT 8883									// your port, use 443 for MQTT over Websocket
#define AWS_IOT_CLIENT_ID	"My_ClientID"						// your client ID
#define AWS_IOT_MY_THING_NAME "My_Board"						// your thing name
#define AWS_IOT_ROOT_CA_FILENAME "aws-iot-rootCA.crt"           // your root-CA filename
#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem"                 // your certificate filename
#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem"              // your private key filename
//===============================================================

These settings can be downloaded from the AWS IoT console after you created a device and clicked on "Connect a device".

Make sure you have included the AWS-IoT-Arduino-Yún-SDK library:

#include <aws_iot_mqtt.h>

Make sure you have included your configuration header file:

#include "aws_iot_config.h"

Make sure you have enough memory for subscribe, messages and sketch runtime. Internal buffer size is defined in SDK library source directory libraries/AWS-IoT-Arduino-Yun-Library/aws_iot_config_SDK.h. The following are default settings:

#define MAX_BUF_SIZE 256										// maximum number of bytes to publish/receive
#define MAX_SUB 15 												// maximum number of subscribe
#define CMD_TIME_OUT 200										// maximum time to wait for feedback from AR9331, 200 = 10 sec

Make sure you setup the client, configure it using your configuration and connect it to AWS IoT first. Remember to use certs path macros for configuration:

aws_iot_mqtt_client myClient;
myClient.setup(AWS_IOT_CLIENT_ID);
// myClient.setup(AWS_IOT_CLIENT_ID, true, MQTTv31, true); // Use Websocket
myClient.config(AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, AWS_IOT_ROOT_CA_PATH, AWS_IOT_PRIVATE_KEY_PATH, AWS_IOT_CERTIFICATE_PATH);
// myClient.configWss(AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, AWS_IOT_ROOT_CA_PATH); // Use Websocket
myClient.connnect();

Remember to check incoming messages in a loop:

void loop() { 
  ...  
  myClient.yield();
  ...
}

When you are using thing shadow API for a specific device shadow name, make sure you initialize the shadow with your device shadow name first:

myClient.shadow_init(AWS_IOT_MY_THING_NAME); // For shadow of this device
myClient.shadow_init("AnotherDevice"); // For another shadow

When you are using thing shadow API, always make sure MAX_SUB is big enough for a thing shadow request in the loop:

...
myClient.shadow_get("myThingName", myCallback, 5); // need 2 in MAX_SUB
...
void loop() {
	...
	myClient.shadow_get("myThingName", myCallback, 5); // need 4 in MAX_SUB
	myClient.yield(); // unsubscribe thing shadow topics when necessary
	...
}

When you are using thing shadow API, make sure you set the timeout to a proper value and frequently call yield to free subscribe resources. Long timeout with low rate of yielding and high rate of shadow request will result in exhaustion of subscribe resources:

void loop() {
	...
	myClient.shadow_get("myThingName", myCallback, 5); // 5 sec timeout is fine for a request per 5 sec
	
	// myClient.shadow_get("myThingName", myCallback, 50);
	// 50 sec timeout is too long. When missing feedback happens frequently, with a rate of 1 request per 5 sec, subscribed topics will soon accumulate and exceed MAX_SUB before any of the previously-subscribed topic gets timeout and unsubscribed
	
	myClient.yield();
	
	delay(5000); // 5 sec delay
	...
}

Enjoy the Internet of Things!


Example

BasicPubSub

This example demonstrates a simple MQTT publish/subscribe using AWS IoT from Arduino Yún board. It first subscribes to a topic once and registers a callback to print out new messages to Serial monitor and then publishes to the topic in a loop. Whenever it receives a new message, it will be printed out to Serial monitor indicating the callback function has been called.

  • Hardware Required
    Arduino Yún
    Computer connected with Arduino Yún using USB serial

  • Software Required
    None

  • Circuit Required
    None

  • Attention
    Please make sure to start the example sketch after the board is fully set up and openWRT is up and connected to WiFi. See here.

  • Code
    Create an instance of aws_iot_mqtt_client.

      aws_iot_mqtt_client myClient;
    

    In setup(), open the Serial. Set the instance up and connect it to the AWS IoT.

      Serial.begin(115200);
      ...
      if((rc = myClient.setup(AWS_IOT_CLIENT_ID)) == 0) {
      	// Load user configuration
      	if((rc = myClient.config(AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, AWS_IOT_ROOT_CA_PATH, AWS_IOT_PRIVATE_KEY_PATH, AWS_IOT_CERTIFICATE_PATH)) == 0) {
    			// Use default connect: 60 sec for keepalive
    			if((rc = myClient.connect()) == 0) {
      			success_connect = true;
      			...
      		}
      		else {...}
      	}
      	else {...}
      }
      else {...}
      ...
    

    In setup(), subscribe to the desired topic and wait for some delay time.

    	if((rc = myClient.subscribe("topic1", 1, msg_callback)) != 0) {
      	Serial.println(F("Subscribe failed!"));
      	Serial.println(rc);
      }
      delay(2000);
    

    In loop(), publish to this topic and call yield function to receive the message every 5 seconds.

      sprintf(msg, "new message %d", cnt);
      if((rc = myClient.publish("topic1", msg, strlen(msg), 1, false)) != 0) {
      	Serial.println(F("Publish failed!"));
      	Serial.println(rc);
      }
      if((rc = myClient.yield()) != 0) {
      	Serial.println(F("Yield failed!"));
      	Serial.println(rc);
      }
      ...
      delay(5000);
    

    The full sketch can be found in AWS-IoT-Arduino-Yun-Library/examples/BasicPubSub.

ThingShadowEcho sample app

This example demonstrates Arduino Yún board as a device communicating with AWS IoT, syncing data into the thing shadow in the cloud and receiving commands from an app. Whenever there is a new command from the app side to change the desired state of the device, the board will receive this request and apply the change by publishing it as the reported state. By registering a delta callback function, users will be able to see this incoming message and notice the syncing of the state.

  • Hardware Required
    Arduino Yún
    Computer connected with Arduino Yún using USB serial

  • Software Required
    App-side code that updates the state of the corresponding thing shadow in the cloud
    Note: You can also use AWS IoT console to update the shadow data.

  • Circuit Required
    None

  • Attention
    Please make sure to start the example sketch after the board is fully set up and openWRT is up and connected to WiFi. See here.

  • Code
    Create an instance of aws_iot_mqtt_client.

      aws_iot_mqtt_client myClient;
    

    Create logging function for execution tracking.

      bool print_log(const char* src, int code) {
      	...
      }
    

    In setup(), open the Serial. Set the instance up and connect it to the AWS IoT. Init the shadow and register a delta callback function. All steps are tracked using logging function.

      if(print_log("setup", myClient.setup(AWS_IOT_CLIENT_ID))) {
      	if(print_log("config", myClient.config(AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, AWS_IOT_ROOT_CA_PATH, AWS_IOT_PRIVATE_KEY_PATH, AWS_IOT_CERTIFICATE_PATH))) {
      		if(print_log("connect", myClient.connect())) {
      			success_connect = true;
      			print_log("shadow init", myClient.shadow_init(AWS_IOT_MY_THING_NAME));
      			print_log("register thing shadow delta function", myClient.shadow_register_delta_func(AWS_IOT_MY_THING_NAME, msg_callback_delta));
    			}
      	}
      }
    

    In loop(), yield to check and receive new incoming messages every 1 second.

      if(myClient.yield()) {
      	Serial.println("Yield failed.");
      }
      delay(1000);
    

    For delta callback function, obtain the desired/delta state and put it as the reported state in the JSON file that needs to be updated.

      void msg_callback_delta(const char* src, unsigned int len, Message_status_t flag) {
      	if(flag == STATUS_NORMAL) {
      		// Get the whole delta section
      		print_log("getDeltaKeyValue", myClient.getDeltaValueByKey(src, "", JSON_buf, 100));
      		String payload = "{\"state\":{\"reported\":";
      		payload += delta;
      		payload += "}}";
      		payload.toCharArray(JSON_buf, 100);
      		print_log("update thing shadow", myClient.shadow_update(AWS_IOT_MY_THING_NAME, JSON_buf, strlen(JSON_buf), NULL, 5));
      	}
      }
    

    Once an update of the desired state for this device is received, a delta message will be received and displayed in the Serial monitor. The device will update this data into the cloud.

    The full sketch can be found in AWS-IoT-Arduino-Yun-Library/examples/ThingShadowEcho.

Simple Thermostat Simulator

This example demonstrates Arduino Yún as a device accepting instructions and syncing reported state in shadow in AWS IoT, which simulates a thermostat to control the temperature of a room. With the provided example App script, users will be able to get real-time temperature data coming from the board and be able to remotely set the desired temperature. This example also demonstrates how to retrieve shadow JSON data received on Arduino Yún Board.
AWS IoT Device SDK for Python is used in App scripts for MQTT connections. Users can modify it to use other MQTT library according to their needs.

  • Hardware Required
    Arduino Yún
    Computer connected with Arduino Yún using USB serial and running example App scripts

  • Software Required
    Tkinter for App GUI
    AWS IoT Device SDK for Python for MQTT connectivity
    Example App script, which is included in the ExampleAppScripts/ThermostatSimulatorApp/

  • Circuit Required
    None

  • Attention
    Please make sure to start the example sketch after the board is fully set up and openWRT is up and connected to WiFi. See here.

  • Getting started
    Before proceeding to the following steps, please make sure you have your board set up, with all code base and credentials properly installed. Please make sure you attach the correct policy to your certificate.

    1. Modify your configuration file to match your own credentials and host address.
    2. Start the sketch when the board boots up. It should pass the initialization steps and then start to update shadow data. It should have a similar display in the serial monitor as follows:

    3. On the App side, please make sure you have [Tkinter](http://tkinter.unpythonic.net/wiki/How_to_install_Tkinter) and [AWS IoT Device SDK for Python](https://github.com/aws/aws-iot-device-sdk-python) pre-installed on your computer. 4. Copy and paste your credentials (certificate, private key and rootCA) into `ThermostatSimulatorApp/certs/`. Please make sure to keep the file names as they are downloaded and make sure the CA file name ends with `CA.crt`. 5. In the directory `ThermostatSimulatorApp/`, start the App script by executing:
      	python ThermostatSimulatorApp.py -e <Your AWS IoT Endpoint>  # For X.509 certificate based mutual authentication
      	python ThermostatSimulatorApp.py -e <Your AWS IoT Endpoint> -w  # For MQTT over WebSocket using IAM credentials
      	
      	
      For more details about command line options, you can use the following command:  
      
      	python ThermostatSimulatorApp.py -h
      
      You should be able to see a GUI prompt up with default reported temperature:<p/>
    
    6. Try to input a desired temperature and click SET. If it succeeds, you should be able to see the desired temperature on the panel and a log printed out in the console space. The board will start continuously syncing temperature settings:

    *Note:* The temperature is configured to be lower than 100 F and higher than -100 F. Error message will be printed out if there is a malformed setting:

  • Code
    Create an instance of aws_iot_mqtt_client.

      aws_iot_mqtt_client myClient;
    

    Create logging function for execution tracking.

      bool print_log(const char* src, int code) {
      	...
      }
    

    In setup(), open the Serial. Set the instance up and connect it to the AWS IoT. Init the shadow and register a delta callback function. All steps are tracked using logging function.

      if(print_log("setup", myClient.setup(AWS_IOT_CLIENT_ID))) {
        if(print_log("config", myClient.config(AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, AWS_IOT_ROOT_CA_PATH, AWS_IOT_PRIVATE_KEY_PATH, AWS_IOT_CERTIFICATE_PATH))) {
          if(print_log("connect", myClient.connect())) {
            success_connect = true;
            print_log("shadow init", myClient.shadow_init(AWS_IOT_MY_THING_NAME));
            print_log("register thing shadow delta function", myClient.shadow_register_delta_func(AWS_IOT_MY_THING_NAME, msg_callback_delta));
          }
        }
      }
    

    In loop(), simulate the behavior of a thermostat. Check to see the difference between the desired and the reported temperature. If the desired temperature is higher, increase the reported temperature by 0.1 degree per 1 second (per loop). If the desired one is lower, decrease the reported temperature by 0.1 degree per 1 second (per loop). Increase/Decrease action will happen until the reported reaches the desired. Update the reported temperature and then yield to check if there is any new delta message.

      void loop() {
        if(success_connect) {
          if(desiredTemp - reportedTemp > 0.001) {reportedTemp += 0.1;}
          else if(reportedTemp - desiredTemp > 0.001) {reportedTemp -= 0.1;}
          dtostrf(reportedTemp, 4, 1, float_buf);
          float_buf[4] = '\0';
          sprintf_P(JSON_buf, PSTR("{\"state\":{\"reported\":{\"Temp\":%s}}}"), float_buf);
          print_log("shadow update", myClient.shadow_update(AWS_IOT_MY_THING_NAME, JSON_buf, strlen(JSON_buf), NULL, 5));
          if(myClient.yield()) {
            Serial.println("Yield failed.");
          }
          delay(1000); // check for incoming delta per 1000 ms
        }
      }
    

    For delta callback function, get the desired state and the desired temperature data in it. Update the desired temperature record on board so that the board knows what to do, heating or cooling.

      void msg_callback_delta(const char* src, unsigned int len, Message_status_t flag) {
      	if(flag == STATUS_NORMAL) {
      		// Get Temp section in delta messages
      		print_log("getDeltaKeyValue", myClient.getDeltaValueByKey(src, "Temp", JSON_buf, 50));				String delta = data.substring(st, ed);
      		desiredTemp = String(JSON_buf).toFloat();
      	}
      }
    

    Each time the board receives a new desired temperature different from its reported temperature. Changes will happen, synced into shadow and captured by the example App. Users will be able to see the whole process of temperature updating from the App side.

    The full sketch can be found in AWS-IoT-Arduino-Yun-Library/examples/ThermostatSimulatorDevice.

Error code

The following error codes are defined in AWS-IoT-Arduino-Yun-Library/aws_iot_error.h:

typedef enum {
	NONE_ERROR = 0,
	GENERIC_ERROR = -1,
	NULL_VALUE_ERROR = -2,
	OVERFLOW_ERROR = -3,
	OUT_OF_SKETCH_SUBSCRIBE_MEMORY = -4,
	SERIAL1_COMMUNICATION_ERROR = -5,
	SET_UP_ERROR = -6,
	NO_SET_UP_ERROR = -7,
	WRONG_PARAMETER_ERROR = -8,
	CONFIG_GENERIC_ERROR = -9,
	CONNECT_SSL_ERROR = -10,
	CONNECT_ERROR = -11,
	CONNECT_TIMEOUT = -12,
	CONNECT_CREDENTIAL_NOT_FOUND = -13,
	CONNECT_GENERIC_ERROR = -14,
	PUBLISH_ERROR = -15,
	PUBLISH_TIMEOUT = -16,
	PUBLISH_GENERIC_ERROR = -17,
	SUBSCRIBE_ERROR = -18,
	SUBSCRIBE_TIMEOUT = -19,
	SUBSCRIBE_GENERIC_ERROR = -20,
	UNSUBSCRIBE_ERROR = -21,
	UNSUBSCRIBE_TIMEOUT = -22,
	UNSUBSCRIBE_GENERIC_ERROR = -23,
	DISCONNECT_ERROR = -24,
	DISCONNECT_TIMEOUT = -25,
	DISCONNECT_GENERIC_ERROR = -26,
	SHADOW_INIT_ERROR = -27,
	NO_SHADOW_INIT_ERROR = -28,
	SHADOW_GET_GENERIC_ERROR = -29,
	SHADOW_UPDATE_GENERIC_ERROR = -30,
	SHADOW_UPDATE_INVALID_JSON_ERROR = -31,
	SHADOW_DELETE_GENERIC_ERROR = -32,
	SHADOW_REGISTER_DELTA_CALLBACK_GENERIC_ERROR = -33,
	SHADOW_UNREGISTER_DELTA_CALLBACK_GENERIC_ERROR = -34,
	YIELD_ERROR = -35,
	WEBSOCKET_CREDENTIAL_NOT_FOUND = -36,
	JSON_FILE_NOT_FOUND = -37,
	JSON_KEY_NOT_FOUND = -38,
	JSON_GENERIC_ERROR = -39,
	PUBLISH_QUEUE_FULL = -40,
	PUBLISH_QUEUE_DISABLED = -41
} IoT_Error_t;

Support

If you have technical questions about AWS IoT Device SDK, please use AWS IoT forum.
For any other questions on AWS IoT, please contact AWS Support.

aws-iot-device-sdk-arduino-yun's People

Contributors

christophsaalfeld avatar huguesbouvier avatar hyandell avatar liuszeng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-iot-device-sdk-arduino-yun's Issues

SSL Connection Error -10

Using a Seeeduino Cloud (essentially like the Arduino Yun). My code was working fine. I got everything to how I wanted it. Then, I did not plug it in for a couple weeks. AWS, it appears (this is a guess) clears out all records of an IoT Thing after no activity for two weeks. So when I logged back in one day, I found nothing registered, no certificates, no policy, everything gone.

So, I had to create it all again.

Uploaded the new certificate files onto the board. Changed the file names in the sketch's aws_iot_config.h . Now it gives an error -10 when running the example sketches, which I see is CONNECT_SSL_ERROR = -10.

Any idea what would cause this? Any way to "reset" the Dragino board to pristine condition and then do everything over? But perhaps that would not solve it -- it may be a problem on the cloud end? I did set up IAM in the meantime -- would that break it?

ThingShadowEcho not registering shadow delta function on SDK 2.1.1

Hi, I have an Arduino Yún with SDK 2.1.1 installed where I have successfully tested BasicPubSub example with no problems.

However, ThingShadowEcho example gets stuck after printing "shadow init completed", without any error message. I have configured "aws_iot_config.h" the same way as in BasicPubSub example, so I think everything is in its place.

This is the what the serial monitor shows:
AWS IoT SDK Version(dev) 2.1.1-

[LOG] command: setup completed.
[LOG] command: config completed.
[LOG] command: connect completed.
[LOG] command: shadow init completed.

Any insights? Thanks.

Arduino Yun AWS IoT - BasicPubSub Connect Failed -10

Hi,

I tried to follow the instructions on github aws-iot-device-sdk-arduino-yun to set up my Arduino Yun using my Windows machine. Everything seems okay and I have loaded my certs into /root/AWS-IoT-Python-Runtime/certs with corresponding filenames in the aws_iot_config.h file that was uploaded to the Arduino Yun board in the BasicPubSub example. Upon opening serial monitor, the message displayed was Connect Failed! -10.

Appreciate any advice, thanks!
Joseph

Failed to connect to the AWS IoT

Hi,

I upload the BasicPubSub example to the Arduino Yún board. But it connected failed!
We could see the serial port printed as shown below:
Uploading failed.png…

We also see the python file run.
Uploading python client.png…

And Yesterday evening the connection was successful.
Uploading success.jpg…

Please give the answer to us. Thanks!

Connect Failed! (-1) issue using BasicPubSub

Hello, I am trying to connect my YUN (with OpenWrt) to AWS IoT using this SDK. I have followed every step carefully, when I try using BasicPubSub Example .
When teh sketch runs I receive a response "Connect failed" with code "-1".
I read the issue #28, but my problem is not solved.
I use the Windows platform to update the YUn system.
Thanks

Adruino yun sdk setup issue

Hello, recently i got an arduino yun and downloaded aws arduino yun sdk and followed the installation steps on windows environment. I am getting setup failed, config failed, connect failed messages when trying to start the basic pub sub example, instead of serial monitor i am using console for printing information. I have verified that my yun is on the same network as my computer and tried couple of other small non aws programs which seems to be working alright. The CA root certificate, private key and certificate which i got from AWS console, which i am using with yun, if i use the same with Raspberry pi, its working correctly with the c sdk. Any pointers on what else i can check for the setup to work on yun would be a great help.

Getting Key/Values from reported device shadow states

Hi All,

I would like to use this function to get the reported property of my device shadow. Something like this:
https://github.com/aws/aws-iot-device-sdk-arduino-yun#getValueByKey

char internalMessage[32];
myClient.getValueByKey("JSON-0", "state"desired"message", &internalMessage, 32);

I get a compile error - 'class aws_iot_mqtt_client' has no member named 'getValueByKey'.

I couldn't find the getValueByKey function defined anywhere in the SDK.

Am I doing something obviously wrong? How am I supposed to get properties of my state?

Thanks

PubSub example not working

Hi,

I'm having the same issue described on other closed issues. When running this basic example I get:

AWS IoT SDK Version(dev) 2.2.0-
Setup failed!
-5

I added the line

Serial.println(rw_buf);

after this one and the output was:

AWS IoT SDK Version(dev) 2.2.0-





















Setup failed!
-5

I also run cat /proc/cmdline on the board and the out put was:

board=linino-yun console=ttyATH0,250000 mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env),14656k(rootfs),1280k(kernel),64k(nvram),64k(art),15936k@0x50000(firmware) rootfstype=squashfs,jffs2 noinitrd mem=64M rootfstype=squashfs,jffs2 noinitrd

I also confirmed having an internet connection by doing ping:

root@mydevice:~/AWS-IoT-Python-Runtime/lib# ping github.com
PING github.com (192.30.253.112): 56 data bytes
64 bytes from 192.30.253.112: seq=0 ttl=52 time=79.618 ms
64 bytes from 192.30.253.112: seq=1 ttl=52 time=68.120 ms
64 bytes from 192.30.253.112: seq=2 ttl=52 time=70.041 ms
64 bytes from 192.30.253.112: seq=3 ttl=52 time=70.931 ms
^C
--- github.com ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max = 68.120/72.177/79.618 ms

I'm using WiFi and I cannot use the Ethernet port to test.

Errors while Compiling in Arduino

So I am trying to run (just clicking on the check mark to verify) the Pub\Sub Example through Arduino and I get the following errors:

C:\Users..\Documents\Arduino\libraries\AWS-IoT-Arduino-Yun-Library\aws_iot_mqtt.cpp: In member function 'IoT_Error_t aws_iot_mqtt_client::configDrainingInterval(float)':

C:\Users..\Documents\Arduino\libraries\AWS-IoT-Arduino-Yun-Library\aws_iot_mqtt.cpp:211:39: error: 'dtostrf' was not declared in this scope

dtostrf(numberOfSeconds, 5, 2, rw_buf); // Only support XX.XX (including sign+/-)

                                   ^

Using library AWS-IoT-Arduino-Yun-Library in folder: C:\Users..\Documents\Arduino\libraries\AWS-IoT-Arduino-Yun-Library (legacy)
exit status 1
Error compiling for board Intel® Edison.

Looks like I need to specify config, but sure where. I have tried a couple things but to no avail only get other errors. figured I would ask.

Serial1 error on re-upload

I kept getting SERIAL1_COMMUNICATION_ERROR (-5) on re-upload. Always had to reset the Yun over again.


void setup() {

    Serial.begin(115200);
    while(!Serial);

    if ((rc = myClient.setup(AWS_IOT_CLIENT_ID)) == 0) {
        Serial.println(F("Begin setup..."));

        // ... 
    } else {

        // This two lines print out rc = -5
        Serial.println(F("Setup failed"));
        Serial.println(rc);
    }

Tried to add a few extra variables to the json but keep getting a error

Wanted to add a few extra variables to the json but keep getting an error. Am i treating the different variable correctly

#include <aws_iot_mqtt.h>
#include <aws_iot_version.h>
#include "aws_iot_config.h"

aws_iot_mqtt_client myClient;
char JSON_buf[400];
char float_buf[5];
char float_buf1[5];
char float_buf2[5];
char float_buf3[5];
char float_buf4[5];
char float_buf5[5];
char float_buf6[5];
char float_buf7[5];
float reportedTemp = 70.0;
float desiredTemp = 70.0;
float TRHtemp = 0;
float TRHhumid = 0;
float BMP = 0;
float BMPtemp = 0;
float BMPalt = 0;
float CO2 = 0;
float Therm = 0;

int cnt = 0;
int rc = 1;
bool success_connect = false;

bool print_log(const char* src, int code) {
  bool ret = true;
  if(code == 0) {
    #ifdef AWS_IOT_DEBUG
       Serial.print(F("[LOG] command: "));
       Serial.print(src);
       Serial.println(F(" completed."));
    #endif
    ret = true;
   }
  else {
    #ifdef AWS_IOT_DEBUG
      Serial.print(F("[ERR] command: "));
      Serial.print(src);
      Serial.print(F(" code: "));
      Serial.println(code);
    #endif
    ret = false;
   }
  Serial.flush();
  return ret;
}

void msg_callback_delta(char* src, unsigned int len, Message_status_t flag) {
  if(flag == STATUS_NORMAL) {
    // Get Temp section in delta messages
    print_log("getDeltaKeyValue", myClient.getDeltaValueByKey(src, "Temp", JSON_buf, 50));
    desiredTemp = String(JSON_buf).toFloat();
  }
}

void setup() {
  Serial.begin(115200);
  while(!Serial);

  char curr_version[80];
  snprintf_P(curr_version, 80, PSTR("AWS IoT SDK Version(dev) %d.%d.%d-%s\n"), VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
  Serial.println(curr_version);

  if(print_log("setup", myClient.setup(AWS_IOT_CLIENT_ID))) {
    if(print_log("config", myClient.config(AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, AWS_IOT_ROOT_CA_PATH, AWS_IOT_PRIVATE_KEY_PATH, AWS_IOT_CERTIFICATE_PATH))) {
      if(print_log("connect", myClient.connect())) {
        success_connect = true;
        print_log("shadow init", myClient.shadow_init(AWS_IOT_MY_THING_NAME));
        print_log("register thing shadow delta function", myClient.shadow_register_delta_func(AWS_IOT_MY_THING_NAME, msg_callback_delta));
      }
    }
  }
}

void loop() {
  if(success_connect) {
    // If the desired temperature is set to a higher value, start heating.
    if(desiredTemp - reportedTemp > 0.001) {reportedTemp += 0.1;}
    // If the desired temperature is set to a lower value, start cooling.
    else if(reportedTemp - desiredTemp > 0.001) {reportedTemp -= 0.1;}
    TRHtemp = random(10, 100);
    TRHhumid = random(10, 100);
    BMP = random(10, 100);
    BMPtemp = random(10, 100);
    BMPalt = random(10, 100);
    CO2 = random(10, 100);
    Therm = random(10, 100);

    dtostrf(reportedTemp, 4, 1, float_buf);
    dtostrf(TRHtemp, 4, 1, float_buf1);
    dtostrf(TRHhumid, 4, 1, float_buf2);
    dtostrf(BMP, 4, 1, float_buf3);
    dtostrf(BMPtemp, 4, 1, float_buf4);
    dtostrf(BMPalt, 4, 1, float_buf5);
    dtostrf(CO2, 4, 1, float_buf6);
    dtostrf(Therm, 4, 1, float_buf7);
    float_buf[4] = '\0';
    float_buf1[4] = '\0';
    float_buf2[4] = '\0';
    float_buf3[4] = '\0';
    float_buf4[4] = '\0';
    float_buf5[4] = '\0';
    float_buf6[4] = '\0';
    float_buf7[4] = '\0';

    sprintf_P(JSON_buf, PSTR("{\"state\":{\"reported\":{\"TRHtemp\":%s,\"TRHhumid\":%s,\"BMP\":%s,\"BMPtemp\":%s,\"BMPalt\":%s,\"CO2\":%s,\"Therm\":%s}}}"), float_buf1,float_buf2,float_buf3,float_buf4,float_buf5,float_buf6,float_buf7);
    print_log("shadow update", myClient.shadow_update(AWS_IOT_MY_THING_NAME, JSON_buf, strlen(JSON_buf), NULL, 5));
    if(myClient.yield()) {
      Serial.println("Yield failed.");
    }
    delay(1000); // check for incoming delta per 1000 ms
  }
}

Shadow Upadate problems

I am experiencing a situation where the shadow_update function seems to work once, but will then fail. I believe it returns GENERIC_ERROR (-1). This is the output from serial monitor:

eption in thread Thread-4 (most likely raised during interpr5
/bin/ash: su: not found
/bin/ash: my-thing-name: not found
}
/bin/ash: 1: not found
/bin/ash: 5: not found

and...

: No messages.
/bin/ash: su: not found
/bin/ash: my-thing-name: not found
}
/bin/ash: 2: not found
/bin/ash: 5: not found

and

/bin/ash: 5: not found
/bin/ash: su: not found
/bin/ash: my-thing-name: not found
}
/bin/ash: 2: not found
/bin/ash: 5: not found

Later I am getting a yield error:

/bin/ash: 1: not found
/bin/ash: z: not found
Yield failed.
-35

...where -35 is the result of myClient.yield()

This is from my log:

DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Started a subscribe request 1
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:_resubscribeCount: -1
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Subscribe request 1 sent.
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Subscribe request 1 succeeded. Time consumption: 40.0ms.
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Recover subscribe context for the next request: subscribeSent: False
INFO:AWSIoTPythonSDK.core.shadow.deviceShadow:Subscribed to delta topic for deviceShadow: my-thing-name
DEBUG:comm.serialCommunicationServer:Updated serialCommunicationServer internal protocolMessageQueue by inserting a new message. Size: 1
DEBUG:comm.serialCommunicationServer:Send through serial to remote client: S_RD T Size: 6
DEBUG:comm.serialCommunicationServer:Clear internal list. Size: 0
DEBUG:comm.serialCommunicationServer:Accept-timer starts, with acceptTimeout: 10 second(s).
DEBUG:comm.serialCommunicationServer:5 lines to be received. Loop begins.
DEBUG:comm.serialCommunicationServer:Received: 1/5 Message is: su
DEBUG:comm.serialCommunicationServer:Received: 2/5 Message is: my-thing-name
DEBUG:comm.serialCommunicationServer:Received: 3/5 Message is: {"state":{"reported":{"something": 0.00}}}
DEBUG:comm.serialCommunicationServer:Received: 4/5 Message is: 1
DEBUG:comm.serialCommunicationServer:Received: 5/5 Message is: 5
DEBUG:comm.serialCommunicationServer:Finish reading from remote client. Accept-timer ends.
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Started a subscribe request 2
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:_resubscribeCount: -1
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Subscribe request 2 sent.
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Subscribe request 2 succeeded. Time consumption: 30.0ms.
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Recover subscribe context for the next request: subscribeSent: False
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Started a subscribe request 3
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:_resubscribeCount: -1
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Subscribe request 3 sent.
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Subscribe request 3 succeeded. Time consumption: 80.0ms.
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Recover subscribe context for the next request: subscribeSent: False
INFO:AWSIoTPythonSDK.core.shadow.deviceShadow:Subscribed to update accepted/rejected topics for deviceShadow: my-thing-name
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Try to put a publish request 4 in the TCP stack.
DEBUG:AWSIoTPythonSDK.core.protocol.mqttCore:Publish request 4 succeeded.
DEBUG:comm.serialCommunicationServer:Updated serialCommunicationServer internal yieldMessageQueue by inserting a new message. Size: 1
DEBUG:AWSIoTPythonSDK.core.shadow.deviceShadow:shadow message clientToken: seeed02_my-thing-name_0_bnpyc
DEBUG:comm.serialCommunicationServer:Updated serialCommunicationServer internal protocolMessageQueue by inserting a new message. Size: 1
DEBUG:AWSIoTPythonSDK.core.shadow.deviceShadow:Token is in the pool. Type: accepted
DEBUG:comm.serialCommunicationServer:Send through serial to remote client: SU T Size: 4
DEBUG:comm.serialCommunicationServer:Updated serialCommunicationServer internal yieldMessageQueue by inserting a new message. Size: 2
DEBUG:comm.serialCommunicationServer:Clear internal list. Size: 0
DEBUG:comm.serialCommunicationServer:Accept-timer starts, with acceptTimeout: 10 second(s).
DEBUG:comm.serialCommunicationServer:1 lines to be received. Loop begins.
DEBUG:comm.serialCommunicationServer:Received: 1/1 Message is: z
DEBUG:comm.serialCommunicationServer:Finish reading from remote client. Accept-timer ends.
DEBUG:comm.serialCommunicationServer:Updated serialCommunicationServer internal protocolMessageQueue by inserting a new message. Size: 1
DEBUG:comm.serialCommunicationServer:Send through serial to remote client: Z T Size: 3
DEBUG:comm.serialCommunicationServer:Clear internal list. Size: 0
DEBUG:comm.serialCommunicationServer:Accept-timer starts, with acceptTimeout: 10 second(s).
DEBUG:comm.serialCommunicationServer:1 lines to be received. Loop begins.
DEBUG:comm.serialCommunicationServer:Received: 1/1 Message is: y
DEBUG:comm.serialCommunicationServer:Finish reading from remote client. Accept-timer ends.
DEBUG:comm.serialCommunicationServer:Start sending a new message to remote client: Y 0 0 JSON-2
DEBUG:comm.serialCommunicationServer:Send through serial to remote client. Chunk: Y 0 0 JSON-2 Size: 12
DEBUG:comm.serialCommunicationServer:Clear internal list. Size: 0
DEBUG:comm.serialCommunicationServer:Accept-timer starts, with acceptTimeout: 10 second(s).
DEBUG:comm.serialCommunicationServer:4 lines to be received. Loop begins.
DEBUG:comm.serialCommunicationServer:Received: 1/4 Message is: j
DEBUG:comm.serialCommunicationServer:Received: 2/4 Message is: JSON-2
DEBUG:comm.serialCommunicationServer:Received: 3/4 Message is: state"target
DEBUG:comm.serialCommunicationServer:Received: 4/4 Message is: 1
DEBUG:comm.serialCommunicationServer:Finish reading from remote client. Accept-timer ends.
DEBUG:comm.serialCommunicationServer:Updated serialCommunicationServer internal json buffer with a new JSON payload of size: 5
DEBUG:comm.serialCommunicationServer:JSON: Send through serial to remote client. Chunk: J 9.9 Size: 5
DEBUG:comm.serialCommunicationServer:Clear internal list. Size: 0
DEBUG:comm.serialCommunicationServer:Accept-timer starts, with acceptTimeout: 10 second(s).
DEBUG:comm.serialCommunicationServer:4 lines to be received. Loop begins.
DEBUG:comm.serialCommunicationServer:Received: 1/4 Message is: j
DEBUG:comm.serialCommunicationServer:Received: 2/4 Message is: JSON-2
DEBUG:comm.serialCommunicationServer:Received: 3/4 Message is: state"target
DEBUG:comm.serialCommunicationServer:Received: 4/4 Message is: 0
DEBUG:comm.serialCommunicationServer:Finish reading from remote client. Accept-timer ends.
DEBUG:comm.serialCommunicationServer:No more chunks for this JSON payload. Exiting writeToExternalJSON.
DEBUG:comm.serialCommunicationServer:Clear internal list. Size: 0
DEBUG:comm.serialCommunicationServer:Accept-timer starts, with acceptTimeout: 10 second(s).
DEBUG:comm.serialCommunicationServer:1 lines to be received. Loop begins.
DEBUG:comm.serialCommunicationServer:Received: 1/1 Message is: y
DEBUG:comm.serialCommunicationServer:Finish reading from remote client. Accept-timer ends.
DEBUG:comm.serialCommunicationServer:Start sending a new message to remote client: Y 1 0 JSON-0
DEBUG:comm.serialCommunicationServer:Send through serial to remote client. Chunk: Y 1 0 JSON-0 Size: 12
DEBUG:comm.serialCommunicationServer:Clear internal list. Size: 0
DEBUG:comm.serialCommunicationServer:Accept-timer starts, with acceptTimeout: 10 second(s).
DEBUG:comm.serialCommunicationServer:1 lines to be received. Loop begins.
DEBUG:comm.serialCommunicationServer:Received: 1/1 Message is: y
DEBUG:comm.serialCommunicationServer:Finish reading from remote client. Accept-timer ends.
DEBUG:comm.serialCommunicationServer:No more messages for yield. Exiting writeToExternalYield.
DEBUG:comm.serialCommunicationServer:Clear internal list. Size: 0
DEBUG:comm.serialCommunicationServer:Accept-timer starts, with acceptTimeout: 10 second(s).
DEBUG:comm.serialCommunicationServer:Raise a custom exception for accept timeout.

The BasicPubSub Example gives Generic Error and Yield Error when delay is > 10,000

Hi,

I was trying the BasicPubSub example and everything was fine in the beginning. However, after I changed the delay in the loop from 1000ms to 10000ms, the program started reporting generic error and yield error. Only the first message was delivered.

I've tried several different delay time, this only happen when the delay is greater then 10000.

Thanks.

Connect Failed! (-10) issue using BasicPubSub Example

Hello, I am trying to connect my YUN (with OpenWrt) to AWS IoT using this SDK. I have followed every step carefully, and sometime i got success and sometime it return "Connect failed" with code "-10" when I try using BasicPubSub Example.
I have tried to run script on YUN to connect AWS IoT, it also sometimes success and sometimes fail.

My config is:
//=======================================================
#define AWS_IOT_MQTT_HOST "ae83bn430lcel.iot.ap-southeast-1.amazonaws.com" // your endpoint
#define AWS_IOT_MQTT_PORT 8883 // your port
#define AWS_IOT_CLIENT_ID "DS01" // your client ID
#define AWS_IOT_MY_THING_NAME "Testing03" // your thing name
#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" // your root-CA filename
#define AWS_IOT_CERTIFICATE_FILENAME "certificate.pem.crt" // your certificate filename
#define AWS_IOT_PRIVATE_KEY_FILENAME "private.pem.key" // your private key filename
//===============================================================
// SDK config, DO NOT modify it
#define AWS_IOT_PATH_PREFIX "../certs/"
#define AWS_IOT_ROOT_CA_PATH AWS_IOT_PATH_PREFIX AWS_IOT_ROOT_CA_FILENAME // use this in config call
#define AWS_IOT_CERTIFICATE_PATH AWS_IOT_PATH_PREFIX AWS_IOT_CERTIFICATE_FILENAME // use this in config call
#define AWS_IOT_PRIVATE_KEY_PATH AWS_IOT_PATH_PREFIX AWS_IOT_PRIVATE_KEY_FILENAME // use this in config call
#endif

//--------------------------------------------------------------------
Here is the log of success when i use script to connect AWS IoT:
root@DS:~/aws-iot-device-sdk-python-master/samples/basicPubSub# python basicPubSub.py -e ae83bn430lcel.iot.ap-southeast-1.amazonaws.com -r /root/AWS-IoT-Python-Runtime/certs/rootCA.crt -c /root/AWS-IoT-Python-Runtime/certs/certificate.pem.crt -k /root/AWS-IoT-Python-Runtime/certs/private.pem.key
2017-03-20 04:31:12,006 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Paho MQTT Client init.
2017-03-20 04:31:12,010 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - ClientID: basicPubSub
2017-03-20 04:31:12,013 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Protocol: MQTTv3.1.1
2017-03-20 04:31:12,017 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Register Paho MQTT Client callbacks.
2017-03-20 04:31:12,019 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - mqttCore init.
2017-03-20 04:31:12,022 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load CAFile from: /root/AWS-IoT-Python-Runtime/certs/rootCA.crt
2017-03-20 04:31:12,024 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Key from: /root/AWS-IoT-Python-Runtime/certs/private.pem.key
2017-03-20 04:31:12,031 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Cert from: /root/AWS-IoT-Python-Runtime/certs/certificate.pem.crt
2017-03-20 04:31:12,035 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: baseReconnectTime = 1 sec
2017-03-20 04:31:12,038 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: maximumReconnectTime = 32 sec
2017-03-20 04:31:12,042 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: minimumConnectTime = 20 sec
2017-03-20 04:31:12,046 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: queueSize = -1
2017-03-20 04:31:12,049 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: dropBehavior = Drop Newest
2017-03-20 04:31:12,053 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for draining interval: 0.5 sec
2017-03-20 04:31:12,056 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum connect/disconnect timeout to be 10 second.
2017-03-20 04:31:12,059 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum MQTT operation timeout to be 5 second
2017-03-20 04:31:12,065 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Connection type: TLSv1.2 Mutual Authentication
2017-03-20 04:31:14,216 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Connected to AWS IoT.
2017-03-20 04:31:14,219 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Connect time consumption: 260.0ms.
2017-03-20 04:31:14,214 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Connect result code 0
2017-03-20 04:31:14,229 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Started a subscribe request 1
2017-03-20 04:31:15,100 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - _resubscribeCount: -1
2017-03-20 04:31:15,103 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Subscribe request 1 sent.
2017-03-20 04:31:15,107 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Subscribe request 1 succeeded. Time consumption: 860.0ms.
2017-03-20 04:31:15,110 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Recover subscribe context for the next request: subscribeSent: False
2017-03-20 04:31:17,120 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Try to put a publish request 2 in the TCP stack.
2017-03-20 04:31:17,123 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Publish request 2 succeeded.
Received a new message:
New Message 0
from topic:
sdk/test/Python

2017-03-20 04:31:18,129 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Try to put a publish request 3 in the TCP stack.
2017-03-20 04:31:18,132 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Publish request 3 succeeded.
Received a new message:
New Message 1
from topic:
sdk/test/Python

//---------------------------------------------------
Here is the log of failure when i use script to connect AWS IoT:
root@DS:/aws-iot-device-sdk-python-master/samples/basicPubSub# python -V
Python 2.7.3
root@DS:
/aws-iot-device-sdk-python-master/samples/basicPubSub# openssl version -v
OpenSSL 1.0.1h 5 Jun 2014
root@DS:~/aws-iot-device-sdk-python-master/samples/basicPubSub# python basicPubSub.py -e ae83bn430lcel.iot.ap-southeast-1.amazonaws.com -r /root/AWS-IoT-Python-Runtime/certs/rootCA.crt -c /root/AWS-IoT-Python-Runtime/certs/certificate.pem.crt -k /root/AWS-IoT-Python-Runtime/certs/private.pem.key
2016-04-07 12:21:39,823 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Paho MQTT Client init.
2016-04-07 12:21:39,826 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - ClientID: basicPubSub
2016-04-07 12:21:39,830 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Protocol: MQTTv3.1.1
2016-04-07 12:21:39,833 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Register Paho MQTT Client callbacks.
2016-04-07 12:21:39,837 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - mqttCore init.
2016-04-07 12:21:39,841 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load CAFile from: /root/AWS-IoT-Python-Runtime/certs/rootCA.crt
2016-04-07 12:21:39,844 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Key from: /root/AWS-IoT-Python-Runtime/certs/private.pem.key
2016-04-07 12:21:39,848 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Cert from: /root/AWS-IoT-Python-Runtime/certs/certificate.pem.crt
2016-04-07 12:21:39,852 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: baseReconnectTime = 1 sec
2016-04-07 12:21:39,854 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: maximumReconnectTime = 32 sec
2016-04-07 12:21:39,857 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: minimumConnectTime = 20 sec
2016-04-07 12:21:39,859 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: queueSize = -1
2016-04-07 12:21:39,864 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: dropBehavior = Drop Newest
2016-04-07 12:21:39,868 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for draining interval: 0.5 sec
2016-04-07 12:21:39,871 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum connect/disconnect timeout to be 10 second.
2016-04-07 12:21:39,875 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum MQTT operation timeout to be 5 second
2016-04-07 12:21:39,879 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Connection type: TLSv1.2 Mutual Authentication
Traceback (most recent call last):
File "basicPubSub.py", line 133, in
myAWSIoTMQTTClient.connect()
File "/usr/lib/python2.7/site-packages/AWSIoTPythonSDK/MQTTLib.py", line 403, in connect
return self._mqttCore.connect(keepAliveIntervalSecond)
File "/usr/lib/python2.7/site-packages/AWSIoTPythonSDK/core/protocol/mqttCore.py", line 290, in connect
self._pahoClient.connect(self._host, self._port, keepAliveInterval) # Throw exception...
File "/usr/lib/python2.7/site-packages/AWSIoTPythonSDK/core/protocol/paho/client.py", line 655, in connect
return self.reconnect()
File "/usr/lib/python2.7/site-packages/AWSIoTPythonSDK/core/protocol/paho/client.py", line 798, in reconnect
ciphers=self._tls_ciphers)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 143, in init
self.do_handshake()
File "/usr/lib/python2.7/ssl.py", line 305, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [Errno 1] _ssl.c:504: error:14090086:lib(20):func(144):reason(134)

Please help me, thanks!
@liuszeng

Beyond AWS IoT?

I'm looking for tutorial suggestions for the next steps, like

  • How to store data from Arduino Yun to DynamoDB or any other database.
  • Is Lambda or Kinesis necessary and how configure them with Yun? What applications would need these two services?

Can not figure out what is going on with message I am trying to publish

So I am trying to publish 4 ct measures to my topic but it seems to not publish when the title length is too long. Below is my code

#include <aws_iot_mqtt.h>
#include <aws_iot_version.h>
#include "aws_iot_config.h"
#include <Process.h>
#include "EmonLib.h"                   
EnergyMonitor emon1;
EnergyMonitor emon2;
EnergyMonitor emon3;
EnergyMonitor emon4;
aws_iot_mqtt_client myClient; // init iot_mqtt_client
char msg[32]; // read-write buffer
char data[100];
Process date;  
int cnt = 0; // loop counts
int rc = -100; // return value placeholder
bool success_connect = false; // whether it is connected

// Basic callback function that prints out the message
void msg_callback(char* src, unsigned int len, Message_status_t flag) {
  if(flag == STATUS_NORMAL) {
    Serial.println("CALLBACK:");
    int i;
    for(i = 0; i < (int)(len); i++) {
      Serial.print(src[i]);
    }
    Serial.println("");
  }
}

void setup() {
  // Start Serial for print-out and wait until it's ready
  Serial.begin(115200);
  while(!Serial)
  //
  emon1.current(0, 111.1);
  emon2.current(1, 111.1);
  emon3.current(2, 111.1);
  emon4.current(3, 111.1);
  char curr_version[80];
  snprintf_P(curr_version, 80, PSTR("AWS IoT SDK Version(dev) %d.%d.%d-%s\n"), VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
  Serial.println(curr_version);
  // Set up the client
  if((rc = myClient.setup(AWS_IOT_CLIENT_ID)) == 0) {
    // Load user configuration
    if((rc = myClient.config(AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, AWS_IOT_ROOT_CA_PATH, AWS_IOT_PRIVATE_KEY_PATH, AWS_IOT_CERTIFICATE_PATH)) == 0) {
      // Use default connect: 60 sec for keepalive
      if((rc = myClient.connect()) == 0) {
        success_connect = true;
        // Subscribe to "topic1"
        if((rc = myClient.subscribe("greenhouse/ct_sensor", 1, msg_callback)) != 0) {
          Serial.println("Subscribe failed!");
          Serial.println(rc);
        }
      }
      else {
        Serial.println(F("Connect failed!"));
        Serial.println(rc);
      }
    }
    else {
      Serial.println(F("Config failed!"));
      Serial.println(rc);
    }
  }
  else {
    Serial.println(F("Setup failed!"));
    Serial.println(rc);
  }
  // Delay to make sure SUBACK is received, delay time could vary according to the server
  delay(2000);
}

void loop() {
  if(success_connect) {

    double Irms = emon1.calcIrms(1480);
    double Irms2 = emon2.calcIrms(1480);
    double Irms3 = emon3.calcIrms(1480);
    //double Irms4 = emon4.calcIrms(1480);
    int IrmsShadow = Irms/4.67;
    int IrmsShadow2 = Irms2/4.67;
    int IrmsShadow3 = Irms2/4.67;
    int IrmsShadow4 = Irms2/4.67;
     //Creating the JSON payload  
    String thing_id = "\"id\": \""  +String(AWS_IOT_MY_THING_NAME) +"\"" ;
    String currentcurrent = ", \"ct_1\": " + String(IrmsShadow) ;
    String currentcurrent2 = ", \"ct_2\": " + String(IrmsShadow2) ;
    String currentcurrent3 = ", \"ct_3\": " + String(IrmsShadow3) ;
    String currentcurrent4 = ", \"ct_4\": " + String(IrmsShadow4) ;
    // Add both value together to send as one string. 
    String value = thing_id + currentcurrent + currentcurrent2 + currentcurrent3 + currentcurrent4;
    Serial.println(value);
    String payload = "{" + value + "}";
    payload.toCharArray(data, (payload.length() + 1));
    Serial.println(strlen(data));

    if((rc = myClient.publish("greenhouse/ct_sensor", data, strlen(data), 1, false)) != 0) {
      Serial.println(F("Publish failed!"));
      Serial.println(rc);
    }
  
    // Get a chance to run a callback
    if((rc = myClient.yield()) != 0) {
      Serial.println("Yield failed!");
      Serial.println(rc);
    }
  
    // Done with the current loop
    sprintf_P(msg, PSTR("loop %d done"), cnt++);
    Serial.println(msg);
  
    delay(1000);
  }
}

By changing id to thing_id it will not publish my message. when i do Serial.println(strlen(data)); it goes from 66 to 0. I have now clue what I'm doing wrong.

ThingShadowEcho example problems

Trying to adapt the "ThingShadow" example, but I keep getting these errors:

AWS IoT SDK Version(dev) 2.2.0-

root@Seeed:~/AWS-IoT-Python-Runtime/runtime# 
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
Linux
/

Later (I think when I expect the sketch to get shadow), I get this:

Exception in thread Thread-4 (most likely raised during interpr
Yield failed.
/bin/ash: 1: not found
/bin/ash: z: not found
Yield failed.

How best to diagnose these?

PubSub example fails with logging enabled.

Hi, I've tried to enable logging for the PubSub example.

I replaced the following code in the runtimeHub.py init function
from;

    self._logManagerHub.disable()                                                                     

to;

     self._logManagerHub.enable()                                                                     
     self._logManagerHub.enableFileOutput()  

The previously running example now fails consistently with a -1 error.

    AWS IoT SDK Version(dev) 1.0.3-

    Setup failed!
    -1

The logger does create a new log;

[2016-03-04 14:10:41.256372] Register timeout signal handler.
[2016-03-04 14:10:41.272485] serialCommunicationServer init.
[2016-03-04 14:10:41.277257] serialCommunicationServer set accept timeout to 15
[2016-03-04 14:10:41.282366] serialCommunicationServer set chunk size to 50
[2016-03-04 14:10:41.287254] Clear internal list. Size: 0
[2016-03-04 14:10:41.291974] Accept-timer starts, with acceptTimeout: 15 second(s).
[2016-03-04 14:10:41.296875] 4 lines to be received. Loop begins.
[2016-03-04 14:10:41.301735] Received: 1/4 Message is: i
[2016-03-04 14:10:41.306648] Received: 2/4 Message is: cvmon1
[2016-03-04 14:10:41.311479] Received: 3/4 Message is: 1
[2016-03-04 14:10:41.316364] Received: 4/4 Message is: 4
[2016-03-04 14:10:41.321048] Finish reading from remote client. Accept-timer ends.
[2016-03-04 14:10:41.330683] Paho MQTT Client init.
[2016-03-04 14:10:41.337009] Register Paho MQTT Client callbacks.
[2016-03-04 14:10:41.341630] mqttCore init.
[2016-03-04 14:10:41.346389] Set maximum connect/disconnect timeout to be 10 second.
[2016-03-04 14:10:41.351113] Set maximum MQTT operation timeout to be 5 second
[2016-03-04 14:10:41.356251] Updated serialCommunicationServer internal protocolMessageQueue by inserting a new message. Size: 1
[2016-03-04 14:10:41.361421] Send through serial to remote client: I T Size: 3
[2016-03-04 14:10:41.366106] Clear internal list. Size: 0
[2016-03-04 14:10:41.370721] Accept-timer starts, with acceptTimeout: 15 second(s).
[2016-03-04 14:10:56.370924] Raise a custom exception for accept timeout.
[2016-03-04 14:10:56.373646] Accept Timeout

Have I missed something in enabling logging?

Thanks,

Jeff

Error when trying to run basicPubSub

Hi! I'm trying your basicPubSub example and keep running into this error. Could you help me out?

I run the command:

python basicPubSub.py -e <host> -r ../../../root-CA.crt -c ../../../izac_listener.cert.pem -k ../../../izac_listener.private.key

2017-05-08 22:58:35,694 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Paho MQTT Client init.
2017-05-08 22:58:35,694 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - ClientID: basicPubSub
2017-05-08 22:58:35,694 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Protocol: MQTTv3.1.1
2017-05-08 22:58:35,694 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Register Paho MQTT Client callbacks.
2017-05-08 22:58:35,694 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - mqttCore init.
2017-05-08 22:58:35,694 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load CAFile from: ../../../root-CA.crt
2017-05-08 22:58:35,694 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Key from: ../../../izac_listener.private.key
2017-05-08 22:58:35,694 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Cert from: ../../../izac_listener.cert.pem
2017-05-08 22:58:35,694 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: baseReconnectTime = 1 sec
2017-05-08 22:58:35,695 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: maximumReconnectTime = 32 sec
2017-05-08 22:58:35,695 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: minimumConnectTime = 20 sec
2017-05-08 22:58:35,695 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: queueSize = -1
2017-05-08 22:58:35,695 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: dropBehavior = Drop Newest
2017-05-08 22:58:35,695 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for draining interval: 0.5 sec
2017-05-08 22:58:35,695 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum connect/disconnect timeout to be 10 second.
2017-05-08 22:58:35,695 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum MQTT operation timeout to be 5 second
2017-05-08 22:58:35,695 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Connection type: TLSv1.2 Mutual Authentication
Traceback (most recent call last):
  File "basicPubSub.py", line 133, in <module>
    myAWSIoTMQTTClient.connect()
  File "/Users/Ryan/virtualenvs/alexa/lib/python3.6/site-packages/AWSIoTPythonSDK/MQTTLib.py", line 403, in connect
    return self._mqttCore.connect(keepAliveIntervalSecond)
  File "/Users/Ryan/virtualenvs/alexa/lib/python3.6/site-packages/AWSIoTPythonSDK/core/protocol/mqttCore.py", line 290, in connect
    self._pahoClient.connect(self._host, self._port, keepAliveInterval)  # Throw exception...
  File "/Users/Ryan/virtualenvs/alexa/lib/python3.6/site-packages/AWSIoTPythonSDK/core/protocol/paho/client.py", line 655, in connect
    return self.reconnect()
  File "/Users/Ryan/virtualenvs/alexa/lib/python3.6/site-packages/AWSIoTPythonSDK/core/protocol/paho/client.py", line 798, in reconnect
    ciphers=self._tls_ciphers)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1142, in wrap_socket
    ciphers=ciphers)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 808, in __init__
    self.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1061, in do_handshake
    self._sslobj.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 683, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_CERTIFICATE_UNKNOWN] sslv3 alert certificate unknown (_ssl.c:749)

I generated all the certificates with AWS IoT.
I am running Python3.6 and my ssl version:

>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.2j  26 Sep 2016'

Thank you in advance!

Feature Request: Allow use of SoftwareSerial

Hey guys, thanks for the library.

I was hacking on getting the library running on the Dragino and Arduino Uno but ran into the issue where the Serial1 port was not available as the Uno has only one Serial port.

It seems like it should be possible to run with an Uno if we could configure SoftwareSerial and use some of the other Arduino digital pins for the second Serial port. However, this library has hardcoded the use of Serial1 (seems to be exclusively in aws_iot_mqtt.cpp) for communication to the Dragino.

If we could set some config values for SoftwareSerial in the config of our sketch (like we do for AWS_IOT_CLIENT_ID), it seems like it would be straight forward to make this library work with much more hardware. I know we can solve this with different hardware, but it'd be great to have this software solution as well.

Thanks!

CONNECT_CREDENTIAL_NOT_FOUND

Hello,

I have uploaded my certs and verified they are in ~/AWS-IoT-Python-Runtime/runtime/certs

I have configured my aws_iot_config.h with the names of the cert and key files. When I run the BasicPubSub example, the connection fails with the error CONNECT_CREDENTIAL_NOT_FOUND.

AWS IoT SDK Version(dev) 2.2.0-

Connect failed!
-13

What causes this error?

Thanks!

Keep getting "Out of buffer size" during callback for shadow_get

Guys, I keep getting "Out of buffer size" during callback for myClient.shadow_get("xxxx", myCallback, 5);

Im not sure whether I putting it wrong for my callback function as shown below:

void myCallback(char* src, int len) {
    String data = String(src);
    Serial.println(data);
}

ThermostatSimulator device

HI, i have problem running the ThermoStatSimulator.py. it provides an invalid syntax error on line 7.

image
image

And on my serial monitor the setup monitor just hang on the following.

image
image

However, i have shadow updates on the AWS IOT console. i believe the connection to the AWS IOT console is successful.

image
image

thanks in advance for your help.

Setup Failed! -5 PubSub example

I recently was able to get my Raspberry Pi to connect to AWS, but I'm new and having trouble connecting my Arduino YUN. I've made sure to follow the instructions for the SDK and that WiFi works but, whenever I run the example PubSub code my serial monitor shows the following output:

AWS IoT SDK Version(dev) 2.2.0-

Setup failed!
-5

I'm unsure as how to fix this issue. My closest understanding is that this is related to SERIAL1_COMMUNICATION_ERROR. I've run the YunSerialTerminal sketch a few times to confirm that the Arduino Serial Monitor can see data from the OpenWRT side.

Setup failed! -1

Hello, I want to use Amazon AWS IoT with my Arduino Yun, but it failed still after 4 Days working. I got some fails and follows instruktions from #28 and #25 but no success. fresh openWRT is installed.

First I got this:

root@ichair:~/AWS-IoT-Python-Runtime/runtime#
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
Linux
/

I T

G T

Connect failed!
-1

Then I installed the python SDK and let basicPubSub sample running and got this:

root@Arduino:~/aws-iot-device-sdk-python-master/samples/basicPubSub# python basicPubSub.py -e .iot.eu-central-1.amazonaws.com -r /root/AWS-IoT-
Python-Runtime/certs/rootCA.crt -c /root/AWS-IoT-Python-Runtime/certs/-certificate.pem.crt -k /root/AWS-IoT-Python-Runtime/certs/-private
.pem.key
2017-06-23 13:04:22,960 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Paho MQTT Client init.
2017-06-23 13:04:22,963 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - ClientID: basicPubSub
2017-06-23 13:04:22,967 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Protocol: MQTTv3.1.1
2017-06-23 13:04:22,970 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Register Paho MQTT Client callbacks.
2017-06-23 13:04:22,974 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - mqttCore init.
2017-06-23 13:04:22,978 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load CAFile from: /root/AWS-IoT-Python-Runtime/certs/rootCA.crt
2017-06-23 13:04:22,981 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Key from: /root/AWS-IoT-Python-Runtime/certs/454c742925-private.pem.key
2017-06-23 13:04:22,985 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Cert from: /root/AWS-IoT-Python-Runtime/certs/454c742925-certificate.pem.crt
2017-06-23 13:04:22,988 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: baseReconnectTime = 1 sec
2017-06-23 13:04:22,992 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: maximumReconnectTime = 32 sec
2017-06-23 13:04:22,996 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: minimumConnectTime = 20 sec
2017-06-23 13:04:23,000 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: queueSize = -1
2017-06-23 13:04:23,003 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: dropBehavior = Drop Newest
2017-06-23 13:04:23,007 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for draining interval: 0.5 sec
2017-06-23 13:04:23,011 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum connect/disconnect timeout to be 10 second.
2017-06-23 13:04:23,015 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum MQTT operation timeout to be 5 second
2017-06-23 13:04:23,019 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Connection type: TLSv1.2 Mutual Authentication
Traceback (most recent call last):
File "basicPubSub.py", line 87, in
myAWSIoTMQTTClient.connect()
File "/usr/lib/python2.7/site-packages/AWSIoTPythonSDK/MQTTLib.py", line 405, in connect
return self._mqttCore.connect(keepAliveIntervalSecond)
File "/usr/lib/python2.7/site-packages/AWSIoTPythonSDK/core/protocol/mqttCore.py", line 290, in connect
self._pahoClient.connect(self._host, self._port, keepAliveInterval) # Throw exception...
File "/usr/lib/python2.7/site-packages/AWSIoTPythonSDK/core/protocol/paho/client.py", line 655, in connect
return self.reconnect()
File "/usr/lib/python2.7/site-packages/AWSIoTPythonSDK/core/protocol/paho/client.py", line 777, in reconnect
sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 145] Connection timed out

What doese this meen?
And if now the Arduino SDK is running I got a different failure:

AWS IoT SDK Version(dev) 2.2.0-

root@Arduino:~/AWS-IoT-Python-Runtime/runtime#
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
/bin/ash: 1: not found
/bin/ash: /root: Permission denied
Linux
/

Traceback (most recent call last):
Setup failed!
-1

I really dont know what can I do more, can somebody help me?
Maybee @liuszeng ?

Thanks
Skrixx

SDK Interference with Bridge Library's Process

I am attempting to build a gateway with the Yun (my LAN on one end, AWS IoT on the other). Specifically, I have a set of Philips Hue bulbs, the state of which I'd like to keep in Device Shadows. (Also, remote control would be awesome.)

I have set up the SDK on my Yun and successfully connected, set up the Shadow, updated it, and registered my delta function callback. However, when I try to integrate this with Philips Hue control, it breaks.

My Hue communication code:

void setup() {
  // Initialize Bridge
  Bridge.begin();

  // Initialize Serial
  Serial.begin(9600);

  // Wait until a Serial Monitor is connected.
  while (!Serial);

  // Authenticate with Hue bridge (uncomment this if connecting to bridge for first time).
  //authenticate();

  // Turn lights on
  runCurl(true);
}

/*
 * Launches "curl" command and sends state to lights
 */
void runCurl(boolean on) {
  // Create process over Yun's bridge
  Process p;
  // Launch curl command
  p.begin("curl"); 
  String s1 = String(" -d ");
  String quote = String('"');

  // Set payload
  String payload;
  if (on) {
    if (isOn) {
      // Update color with transition time
      payload = String("{\"hue\":" + String(hue) + ",\"bri\":" + String(sat) +  ",\"transitiontime\":" + String(50) + "}");
    }
    else {
      // Turn light on
      payload = String("{\"on\":true,\"hue\":" + String(hue) + ",\"bri\":" + String(sat) + "}");
    }
  }
  else {
    // Turn light off
    payload = String("{\"on\":false,\"hue\":" + String(hue) + ",\"bri\":" + String(sat) + "}");
  }

  // Set new state
  isOn = on;

  // Build request
  String url = String("http:/");
  String url2 = String("/" + BRIDGE_IP + "/api/19aa6134f32d16f3fa3e75cdc0ed7/groups/0/action");
  String params = s1 + quote + payload + quote  + url + url2;
  p.addParameter("-d");
  p.addParameter(payload);
  p.addParameter("-X");
  p.addParameter("PUT");
  p.addParameter(url + url2);

  // Run the process and synchronously wait for its terimination
  p.run();

  // Read process output stream; uncomment to print stream over serial
  while (p.available()>0) {
    char c = p.read();
//    Serial.print(c);
  }

  // Ensure the last bit of data is sent
  Serial.flush();
}

It seems that both the Hue communication and the AWS IoT SDK require access to the Bridge in such a way that they cannot coexist. Is this correct? If so, is there any way to send a web request (using a CURL Process or not) while the SDK is running? If not, this would be a huge bummer....

Received [ERR] command: setup code: -1 with Arduino Yun example: ThermostatSimulatorDevice

I have setup my Arduino Yun as instructed in the Readme file in https://github.com/aws/aws-iot-device-sdk-arduino-yun.

Caveat:

  • I updated OpenWrt to version Nov 14, 2014.
  • I did not specify the AWSIoTPythonSDK version. So it must have installed the latest version. Would this be a problem?

I am using Win 7 64-bit. I could upload the blink example to the Yun for sanity check.

I could get Yun to commuicate with AWS IoT through the python examples. But it did not work with the Arduino code. The serial monitor returned a setup error -1. There are probably some steps or configurations that I have missed or incorrectly done but I could not find what they were.

AWS IoT SDK Version(dev) 2.2.0-

YunTestTwo
YunTestTwo
a*************8.iot.us-east-2.amazonaws.com  (I intentionally covered the my endpoint on this post)
8883
/root/AWS-IoT-Python-Runtime/certs/root-CA.crt
/root/AWS-IoT-Python-Runtime/certs/YunTestTwo.private.key
/root/AWS-IoT-Python-Runtime/certs/YunTestTwo.cert.pem
[ERR] command: setup code: -1

My initial setup with AWS IoT was to follow the instructions in Connect from the IoT menu. My steps were

  • Selected Linux and Python
  • Downloaded and copied the certificate and key to Yun: /root/AWS-IoT-Python-Runtime/certs. The files are root-CA.crt, YunTestTwo.cert.pem, YunTestTwo.private.key.
  • Downloaded and copied the SDK Python from https://github.com/aws/aws-iot-device-sdk-python to the certs directory. I did not use git clone because I did not install git in Yun.
  • Installed the SDK using python setup.py install
  • Ran the test script: basicPubSub.py from the certs directory.
  • It worked.
  • I opened MQTT client (under Test) and subscribed to topic: sdk/test/Python.
  • I ran the test script again and it worked even though it complained "We cannot display the message as JSON, and are instead displaying it as UTF-8 String."

Next, in the Arduino code, I opened the ThermostatSimulatorDevice example and modified aws_iot_config.h.

#define AWS_IOT_MQTT_HOST "a***********8.iot.us-east-2.amazonaws.com" 	// your endpoint
#define AWS_IOT_MQTT_PORT 8883									// your port
#define AWS_IOT_CLIENT_ID	"YunTestTwo"						// your client ID
#define AWS_IOT_MY_THING_NAME "YunTestTwo"						// your thing name
#define AWS_IOT_ROOT_CA_FILENAME "root-CA.crt"           // your root-CA filename
#define AWS_IOT_CERTIFICATE_FILENAME "YunTestTwo.cert.pem"                 // your certificate filename
#define AWS_IOT_PRIVATE_KEY_FILENAME "YunTestTwo.private.key"              // your private key filename

I even modified AWS_IOT_PATH_PREFIX from "../certs/" to "/root/AWS-IoT-Python-Runtime/certs/" but still got the same error.

Thank you in advance for reading my issue and helping me.

Cannot read Keyed items beginning with 'F'

Hi All,

I have noticed there is a bug whereby you can't access key/value pairs when the value begins with an uppercase F.

Shadow state
{"state":{"desired":{"text":"Foxtrot"}}}
myClient.getDeltaValueByKey("JSON-0", "text", buffer, 32);
buffer = '0'

Shadow state
{"state":{"desired":{"text":"Golf"}}}
myClient.getDeltaValueByKey("JSON-0", "text", buffer, 32);
buffer = "Golf"

PubSub Not working related to issue #39

I had tried the procedure layout as per issue #39. However, I still encountered the same issue as setup failed (-5). Had run the YunSerialTerminal example and still got the same result. Checked the certificates, keys and policies and they are OK.

Connect to Yun via terminal and run the python program directly (basicPubSub.py) and got a return error of [Errno -2] Name or service not known.

Any help will be appreciated.

Install instructions fail: opkg_install_cmd: Cannot install package distribute.

Hi,

I have a new Arduino UNO with the Yun shield. I'm trying to get the SDK installed, I'm running AWSIoTArduinoYunInstallAll.sh as in the install instructions, the full output:

./AWSIoTArduinoYunInstallAll.sh 172.20.0.62 root xxx
This script will install all of the depencies and upload the codebase and credentials to the targeted Arduino Yun Board for the AWS IoT Arduino Yun SDK, which includes:
- Install dependencies
- Upload codebase
- Upload credentials
Please make sure you have included your credentials (private key, certificate and rootCA) in AWS-IoT-Python-Runtime/certs/
Changing permissions for functional scripts...
Done.
Uploading codebase and credentials...
Arduino Yun IP is: 172.20.0.62
Arduino Yun User Name is: root

Now start transmitting ./AWS-IoT-Python-Runtime to remote directory: [email protected]:/root/ ...
spawn scp -r ./AWS-IoT-Python-Runtime [email protected]:/root/
[email protected]'s password: 
.DS_Store                                                                                                         100% 6148     6.0KB/s   00:00    
3bb6658c3c-certificate.pem.crt                                                                                    100% 1220     1.2KB/s   00:00    
3bb6658c3c-private.pem.key                                                                                        100% 1675     1.6KB/s   00:00    
VeriSign-Class 3-Public-Primary-Certification-Authority-G5.pem                                                    100% 1758     1.7KB/s   00:00    
__init__.py                                                                                                       100%    0     0.0KB/s   00:00    
communicationServer.py                                                                                            100% 1165     1.1KB/s   00:00    
serialCommunicationServer.py                                                                                      100% 7211     7.0KB/s   00:00    
__init__.py                                                                                                       100%    0     0.0KB/s   00:00    
AWSIoTCommand.py                                                                                                  100% 1324     1.3KB/s   00:00    
commandConfig.py                                                                                                  100% 2050     2.0KB/s   00:00    
commandConnect.py                                                                                                 100% 2441     2.4KB/s   00:00    
commandDisconnect.py                                                                                              100% 2000     2.0KB/s   00:00    
commandJSONKeyVal.py                                                                                              100% 3393     3.3KB/s   00:00    
commandLockSize.py                                                                                                100% 1559     1.5KB/s   00:00    
commandPublish.py                                                                                                 100% 2544     2.5KB/s   00:00    
commandSetBackoffTiming.py                                                                                        100% 2049     2.0KB/s   00:00    
commandSetDrainingIntervalSecond.py                                                                               100% 1932     1.9KB/s   00:00    
commandSetOfflinePublishQueueing.py                                                                               100% 2553     2.5KB/s   00:00    
commandShadowDelete.py                                                                                            100% 4075     4.0KB/s   00:00    
commandShadowGet.py                                                                                               100% 4063     4.0KB/s   00:00    
commandShadowRegisterDeltaCallback.py                                                                             100% 3257     3.2KB/s   00:00    
commandShadowUnregisterDeltaCallback.py                                                                           100% 3284     3.2KB/s   00:00    
commandShadowUpdate.py                                                                                            100% 4231     4.1KB/s   00:00    
commandSubscribe.py                                                                                               100% 2908     2.8KB/s   00:00    
commandUnsubscribe.py                                                                                             100% 2673     2.6KB/s   00:00    
commandYield.py                                                                                                   100% 1178     1.2KB/s   00:00    
__init__.py                                                                                                       100%    0     0.0KB/s   00:00    
AWSIoTExceptions.py                                                                                               100%  786     0.8KB/s   00:00    
operationError.py                                                                                                 100%  703     0.7KB/s   00:00    
operationTimeoutException.py                                                                                      100%  716     0.7KB/s   00:00    
__init__.py                                                                                                       100%    0     0.0KB/s   00:00    
jsonManager.py                                                                                                    100% 4360     4.3KB/s   00:00    
delete.me                                                                                                         100%    0     0.0KB/s   00:00    
__init__.py                                                                                                       100%    0     0.0KB/s   00:00    
run.py                                                                                                            100%  721     0.7KB/s   00:00    
runtimeHub.py                                                                                                     100%   18KB  18.0KB/s   00:00    
Completed!
Done.
Installing dependencies on Arduino Yun...
Arduino Yun IP is: 172.20.0.62
Arduino Yun User Name is: root

The following dependencies will be remotely installed on Arduino Yun:
distribute
python-openssl

Please wait until the installation completes and the program exits.

spawn ssh [email protected]
[email protected]'s password: 


BusyBox v1.23.2 (2016-03-23 22:30:11 UTC) built-in shell (ash)

  _______                     ________        __
 |       |.-----.-----.-----.|  |  |  |.----.|  |_
 |   -   ||  _  |  -__|     ||  |  |  ||   _||   _|
 |_______||   __|_____|__|__||________||__|  |____|
          |__| W I R E L E S S   F R E E D O M
 -----------------------------------------------------
 CHAOS CALMER (1.6.1, r48749) - Arduino Yun101 and Yun Shield
root@YunArduino:~# opkg update
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/base/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaoscalmer_base.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/base/Packages.sig.
Signature check passed.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/arduino/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaoscalmer_arduino.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/arduino/Packages.sig.
Signature check passed.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/custom/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaoscalmer_custom.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/custom/Packages.sig.
Signature check passed.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/juci/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaoscalmer_juci.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/juci/Packages.sig.
Signature check passed.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/luci/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaoscalmer_luci.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/luci/Packages.sig.
Signature check passed.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/management/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaoscalmer_management.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/management/Packages.sig.
Signature check passed.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/owrt_pub_feeds/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaoscalmer_owrt_pub_feeds.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/owrt_pub_feeds/Packages.sig.
Signature check passed.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/packages/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaoscalmer_packages.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/packages/Packages.sig.
Signature check passed.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/routing/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaoscalmer_routing.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/routing/Packages.sig.
Signature check passed.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/telephony/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaoscalmer_telephony.
Downloading http://downloads.arduino.cc/openwrtyun/1.6.1/packages/telephony/Packages.sig.
Signature check passed.
root@YunArduino:~# opkg install distribute
Unknown package 'distribute'.
Collected errors:
 * opkg_install_cmd: Cannot install package distribute.
root@YunArduino:~# opkg install python-openssl
Package python-openssl (2.7.9-6) installed in root is up to date.
root@YunArduino:~# easy_install pip
-ash: easy_install: not found
root@YunArduino:~# pip install AWSIoTPythonSDK==1.0.0
-ash: pip: not found
root@YunArduino:~# exit
Connection to 172.20.0.62 closed.
Done.
Execution completed!

I tried running opkg update and opkg install distribute manually (via ssh), fails the same.
opkg search distribute returns nothing.

Has the package been moved, renamed, deleted?

Thanks.

Can I use AWS IoT and use the bridge?

Can I use the Bridge library to acess the digital and analog pins ond the board through REST calls (192.xxx.xxx.xxx/digital/13) ?

I try to use this while sending msg to AWS and it doesn't work.

Saving readings to SD card

Hi, was wondering if there was any way to save my readings I am getting to a file on the SD card while using aws iot sdk?

THanks

setup Failed with error -5

Just installed the sdk in arduino yun and got this setup failed! message from the Serial monitor as below :-

Setup failed!
-5

What is -5 and what is the possible cause ? I am using arduino 1.6.12 IDE. Any help will be appreciated.

basic PubSub Error connect failed -1

config is as follows
AWS_IOT_MQTT_HOST "**************.iot.ap-northeast-1.amazonaws.com"

define AWS_IOT_MQTT_PORT 8883 // your port

define AWS_IOT_CLIENT_ID "seeeduino" // your client ID

define AWS_IOT_MY_THING_NAME "seeeduino" // your thing name

define AWS_IOT_ROOT_CA_FILENAME "rootCA.pem" // your root-CA filename

define AWS_IOT_CERTIFICATE_FILENAME "certificate.pem.crt" // your certificate filename

define AWS_IOT_PRIVATE_KEY_FILENAME "private.pem.key" // your private key filename

Setup failed! - PubSub sample

Can you offer any advice on the best way to diagnose this error:

AWS IoT SDK Version(dev) 2.2.0-

Setup failed!
-1

My config file is:

//===============================================================
#define AWS_IOT_MQTT_HOST "a27sg7ieezj192.iot.us-east-1.amazonaws.com"	// your endpoint
#define AWS_IOT_MQTT_PORT 8883	// your port
#define AWS_IOT_CLIENT_ID "seeed02"	// your client ID
#define AWS_IOT_MY_THING_NAME "seeed-czajk02"	// your thing name
#define AWS_IOT_ROOT_CA_FILENAME "root-CA.crt"	// your root-CA filename
#define AWS_IOT_CERTIFICATE_FILENAME "hashed-certificate.pem.crt"	// your certificate filename
#define AWS_IOT_PRIVATE_KEY_FILENAME "hashed-private.pem.key"	// your private key filename
//===============================================================

Seems like I have been successful running the python sdk example, as a test (as was suggested in #28):

root@Seeed:~/aws-iot-device-sdk-python/samples/basicPubSub# python basicPubSub.py -e a27sg7ieezj192.iot.us-east-1.amazonaws.com -r ../../../AWS-IoT-Python-Runtime/certs/root-CA.crt -c
../../../AWS-IoT-Python-Runtime/certs/c51fbd44a5-certificate.pem.crt -k ../../../AWS-IoT-Python-Runtime/certs/c51fbd44a5-private.pem.key
2017-01-30 14:40:59,759 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Paho MQTT Client init.
2017-01-30 14:40:59,763 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - ClientID: basicPubSub
2017-01-30 14:40:59,767 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Protocol: MQTTv3.1.1
2017-01-30 14:40:59,770 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Register Paho MQTT Client callbacks.
2017-01-30 14:40:59,773 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - mqttCore init.
2017-01-30 14:40:59,777 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load CAFile from: ../../../AWS-IoT-Python-Runtime/certs/root-CA.crt
2017-01-30 14:40:59,780 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Key from: ../../../AWS-IoT-Python-Runtime/certs/c51fbd44a5-private.pem.key
2017-01-30 14:40:59,783 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Cert from: ../../../AWS-IoT-Python-Runtime/certs/c51fbd44a5-certificate.pem.crt
2017-01-30 14:40:59,788 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: baseReconnectTime = 1 sec
2017-01-30 14:40:59,791 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: maximumReconnectTime = 32 sec
2017-01-30 14:40:59,795 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: minimumConnectTime = 20 sec
2017-01-30 14:40:59,799 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: queueSize = -1
2017-01-30 14:40:59,802 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: dropBehavior = Drop Newest
2017-01-30 14:40:59,806 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for draining interval: 0.5 sec
2017-01-30 14:40:59,810 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum connect/disconnect timeout to be 10 second.
2017-01-30 14:40:59,813 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum MQTT operation timeout to be 5 second
2017-01-30 14:40:59,817 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Connection type: TLSv1.2 Mutual Authentication
2017-01-30 14:41:00,579 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Connected to AWS IoT.
2017-01-30 14:41:00,581 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Connect time consumption: 60.0ms.
2017-01-30 14:41:00,578 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Connect result code 0
2017-01-30 14:41:00,590 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Started a subscribe request 1
2017-01-30 14:41:00,882 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - _resubscribeCount: -1
2017-01-30 14:41:00,887 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Subscribe request 1 succeeded. Time consumption: 290.0ms.
2017-01-30 14:41:00,890 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Recover subscribe context for the next request: subscribeSent: False
2017-01-30 14:41:00,885 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Subscribe request 1 sent.
2017-01-30 14:41:02,898 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Try to put a publish request 2 in the TCP stack.
2017-01-30 14:41:02,901 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Publish request 2 succeeded.
Received a new message:
New Message 0
from topic:
sdk/test/Python
--------------


2017-01-30 14:41:03,909 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Try to put a publish request 3 in the TCP stack.
2017-01-30 14:41:03,912 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Publish request 3 succeeded.
Received a new message:
New Message 1
from topic:
sdk/test/Python
--------------

Shadow update fails after 10 seconds

I modified the ThermostatSimulatorDevice such that the delay at the end of the loop is 10 seconds instead of 1 second. For some reason, for any delay time less than 10 seconds works as intended but as soon as the delay is 10 seconds or higher I get this error:

Exception in thread Thread-4 (most likely raised during interpr
[ERR] command: shadow update code: -1

And shadow updates no longer work. I'd ideally like to add some trigger in the arduino that would update the shadow, which might have a delay time of more than 10 seconds. I also changed the CMD_TIME_OUT to 400 in the config file, but the code is still timing out after 10 seconds.

Setup Failed (-1) BasicPubSub

I am stuck and getting nowhere, please could someone help?

When running the BasicPubSub example it stops at the first stage with a Setup Fail -1

AWS IoT SDK Version(dev) 2.2.0-

<RANDOM_STRING>.iot.us-west-2.amazonaws.com
8883
/AWS-IoT-Python-Runtime/certs/root-CA.crt
/AWS-IoT-Python-Runtime/certs/<SOME_HASH>-private.pem.key
/AWS-IoT-Python-Runtime/certs/<SOME_HASH>-certificate.pem.crt
yun
Setup failed!
-1

I have set-up an AWS IoT account and generated the keys and certificates which I loaded into the directory on yun.

root@yun:/AWS-IoT-Python-Runtime/certs# ls
<SOME_HASH>-certificate.pem.crt <SOME_HASH>-public.pem.key
<SOME_HASH>-private.pem.key root-CA.crt

I can connect to yun via WiFi and can use PuTTY and WinSCP.

I expect that it is something simple that I have not done - any pointers would be appreciated!

I have checked the keys and certificates by using MTTQ.fx and can publish and subscribe OK to AWS.

The code seems to be failing at the myClient.setup phase - not sure why this would be? Client id is "yun".

if((rc = myClient.setup(AWS_IOT_CLIENT_ID)) == 0) { // Load user configuration

Arduino Uno + Ethernet Shield

Hi, can I use Arduino Uno + Ethernet Shield?
Or there is something library that can I use with that configuration?

If I can't I want also know if I can use Arduino Uno + Ethernet Shield with one of the MQTT library available open source for Arduino without certificate, so disable certificate for my thing on AWS IOT.

Thanks

Problem with Demos

Good evening im having problems when running the Sample bits of code.

Im using and Arduino yun, and I keep getting


AWS IoT SDK Version(dev) 1.0.3-

Connect failed!

-13

When trying to run BasicPubSub.

Pls advise

Connect Failed! (-1) issue using BasicPubSub Example

Hello, I am trying to connect my YUN (with OpenWrt) to AWS IoT using this SDK. I have followed every step carefully, when I try using BasicPubSub Example I face an issue of "Connect failed" with code "-1".

One thing that is in my notice is when i used:
"easy_install pip &
pip install AWSIoTPythonSDK==1.0.0"
, I received few warnings include missing SNI and insecure platform. (I just don't know that they matter or not)

I am very new to this stuff and with very basic knowledge, Please Help!!

I have followed this issue: #25
but still without any way out.

High memory usage

Hi All,

Thanks for all your great work on the aws yun SDK. It's been fun working with it so far!

I would like to make some suggestions about reducing the memory footprint of the MQTT driver. At the moment the example with shadow states takes up 75% of the memory on the ATmega. This leaves little room for other things to run alongside.

I have some suggestions which I would like to make sincerely. I know the driver is a work in progress, so maybe this is already planned.

1: I noticed there are a lot of string literals in aws_iot_mqtt.cpp - these are stored in SRAM when they could be offloaded to the flash. EG:
Instead of: sprintf(rw_buf, "state"reported"%s\n", key);
Use: sprintf_P(rw_buf, PSTR("state"reported"%s\n"), key);

2: The keyed functions will clear the data in the buffer if the value isn't returned correctly. This means I need to use an intermediate buffer and check the error code before copying again. This is a waste of resources, and could be avoided if the client left the target buffers alone on error

Now I have:
if(myClient.getDeltaValueByKey("JSON-0", "text", buffer, 32) == ERROR_NONE)
{ strcpy(theData, buffer); }

Better:
myClient.getDeltaValueByKey("JSON-0", "text", theData, THE_DATA_SIZE)
// I cant do this because myClient clears theData if the result is not ERROR_NONE

3: I still have to construct the return messages on the ATmega, to report the state back up to AWS. This means I need a huge buffer to hold a JSON document. It would be better to have some kind of function similar to the getValueByKey to construct a JSON doc on the linux host.

eg:
myClient.setValueByKey("JSON-R", "state"reported"text", theData)
myClient.sendMessage("JSON-R");

Thanks!

BasicPubSub: Connection Failed -13

To try solve this I had a look at this issue and also verified my file names were correct. After I SSH'd into the Arduino, my root CA (Symantec website one), IoT Certificate, and IoT private key (both generated through 1-Click certificate create in AWS IoT) were located in:

/root/AWS-IoT-Python-Runtime/certs

My aws_iot_config.h (which is on my local computer) has AWS_IOT_PATH_PREFIX set as "../certs/", which is default. I tried changing file endings to match the format of the original file but that did not work.

Any ideas? Does the -13 error strictly mean it cannot locate the certs and key file? Thanks for the help.

PubSub Example only works when Yun connected to computer

I have a yun setup with the AWS SDK. When pushing the script through my computer, I get a Subscribe failed -1, but the arduino is still able to publish messages to AWS IoT. If I plug in the arduino to a power adapter only, nothing us pushed to AWS. I tried resetting the arduino and re-launching the script by pressing the 32U4 button twice but nothing. As soon as I launch the script from my computer it works again. Any suggestions?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.