Repository: odelot/aws-mqtt-websockets Branch: master Commit: 71e9b69bd79f Files: 9 Total size: 51.7 KB Directory structure: gitextract_621_1yce/ ├── .github/ │ └── FUNDING.yml ├── AWSWebSocketClient.cpp ├── AWSWebSocketClient.h ├── CircularByteBuffer.h ├── LICENSE ├── README.md └── examples/ ├── aws-DHT-publish-example/ │ └── DHT-publish.ino ├── aws-mqtt-websocket-example-paho/ │ └── aws-mqtt-websocket-example-paho.ino └── aws-mqtt-websocket-example-pubsubclient/ └── aws-mqtt-websocket-example-pubsubclient.ino ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms buy_me_a_coffee: odelot ================================================ FILE: AWSWebSocketClient.cpp ================================================ #include "AWSWebSocketClient.h" //work as a singleton to be used by websocket layer message callback AWSWebSocketClient* AWSWebSocketClient::instance = NULL; String AWSWebSocketClient::ntpFixNumber (int number) { String ret = ""; if (number < 10) { ret = "0"; ret += number; return ret; } else{ ret += number; return ret; } } //assuming you have already configure time with a ntp server (also needed by validate CA) String AWSWebSocketClient::getCurrentTimeNTP (void) { time_t now = time(nullptr); struct tm timeinfo; gmtime_r(&now, &timeinfo); String date = ""; date += (1900+timeinfo.tm_year); date += ntpFixNumber(timeinfo.tm_mon+1); date += ntpFixNumber(timeinfo.tm_mday); date += ntpFixNumber(timeinfo.tm_hour); date += ntpFixNumber(timeinfo.tm_min); date += ntpFixNumber(timeinfo.tm_sec); return date; } //callback to handle messages coming from the websocket layer void AWSWebSocketClient::webSocketEvent(WStype_t type, uint8_t * payload, size_t length) { switch(type) { case WStype_DISCONNECTED: DEBUG_WEBSOCKET_MQTT("[AWSc] Disconnected!\n"); AWSWebSocketClient::instance->stop (30000); break; case WStype_CONNECTED: DEBUG_WEBSOCKET_MQTT("[AWSc] Connected to url: %d %s\n", length, payload); AWSWebSocketClient::instance->_connected = true; break; case WStype_TEXT: DEBUG_WEBSOCKET_MQTT("[WSc] get text: %s\n", payload); AWSWebSocketClient::instance->putMessage (payload, length); break; case WStype_BIN: DEBUG_WEBSOCKET_MQTT("[WSc] get binary length: %u\n", length); //hexdump(payload, length); AWSWebSocketClient::instance->putMessage (payload, length); break; } } //constructor AWSWebSocketClient::AWSWebSocketClient (unsigned int bufferSize, unsigned long connectionTimeout) { useSSL = true; _connectionTimeout = connectionTimeout; AWSWebSocketClient:instance = this; onEvent(AWSWebSocketClient::webSocketEvent); awsRegion = NULL; awsSecKey = NULL; awsKeyID = NULL; awsDomain = NULL; awsToken = NULL; path = NULL; _connected = false; bb.init (bufferSize); lastTimeUpdate = 0; _useAmazonTimestamp = true; begin("", 0); } //destructor AWSWebSocketClient::~AWSWebSocketClient(void) { if (awsRegion != NULL) delete[] awsRegion; if (awsDomain != NULL) delete[] awsDomain; if (awsSecKey != NULL) delete[] awsSecKey; if (awsKeyID != NULL) delete[] awsKeyID; if (path != NULL) delete[] path; if (awsToken != NULL) delete[] awsToken; } // convert month to digits String AWSWebSocketClient::getMonth(String sM) { if(sM=="Jan") return "01"; if(sM=="Feb") return "02"; if(sM=="Mar") return "03"; if(sM=="Apr") return "04"; if(sM=="May") return "05"; if(sM=="Jun") return "06"; if(sM=="Jul") return "07"; if(sM=="Aug") return "08"; if(sM=="Sep") return "09"; if(sM=="Oct") return "10"; if(sM=="Nov") return "11"; if(sM=="Dec") return "12"; return "01"; } //get current time (UTC) from aws service (used to sign) String AWSWebSocketClient::getCurrentTimeAmazon (void) { int timeout_busy = 0; String GmtDate; String dateStamp; dateStamp ="19860618123600"; if (timeClient.connect(("aws.amazon.com"), 80)) { // send a bad header on purpose, so we get a 400 with a DATE: timestamp //Send Request timeClient.println(F("GET example.com/ HTTP/1.1")); timeClient.println(F("Connection: close")); timeClient.println(); while((!timeClient.available()) && (timeout_busy++ < 5000)){ // Wait until the client sends some data delay(1); } // kill client if timeout if(timeout_busy >= 5000) { timeClient.flush(); timeClient.stop(); DEBUG_WEBSOCKET_MQTT("timeout receiving timeserver data"); return dateStamp; } // read the http GET Response String req2 = timeClient.readString(); // close connection delay(1); timeClient.flush(); timeClient.stop(); int ipos = req2.indexOf("Date:"); if(ipos > 0) { String gmtDate = req2.substring(ipos, ipos + 35); String utctime = gmtDate.substring(18,22) + getMonth(gmtDate.substring(14,17)) + gmtDate.substring(11,13) + gmtDate.substring(23,25) + gmtDate.substring(26,28) + gmtDate.substring(29,31); dateStamp = utctime.substring(0, 14); } } else { DEBUG_WEBSOCKET_MQTT("did not connect to timeserver"); } timeout_busy=0; // reset timeout return dateStamp; // Return latest or last good dateStamp } /* Converts an integer value to its hex character*/ char to_hex(char code) { static char hex[] = "0123456789ABCDEF"; return hex[code & 15]; } /* Returns a url-encoded version of str */ /* IMPORTANT: be sure to free() the returned string after use */ char* url_encode(const char* str) { const char* pstr = str; char *buf = (char*) malloc(strlen(str) * 3 + 1), *pbuf = buf; while (*pstr) { if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') *pbuf++ = *pstr; else if (*pstr == ' ') *pbuf++ = '+'; else *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15); pstr++; } *pbuf = '\0'; return buf; } //generate AWS url path, signed using url parameters char* AWSWebSocketClient::generateAWSPath (uint16_t port) { String dateTime; if (_useAmazonTimestamp) { dateTime = getCurrentTimeAmazon (); } else { dateTime = getCurrentTimeNTP (); } DEBUG_WEBSOCKET_MQTT (dateTime.c_str()); String awsService = F("iotdevicegateway"); char awsDate[9]; strncpy(awsDate, dateTime.c_str(), 8); awsDate[8] = '\0'; char awsTime[7]; strncpy(awsTime, dateTime.c_str() + 8, 6); awsTime[6] = '\0'; char credentialScope[strlen(awsDate)+strlen(awsRegion)+strlen(awsService.c_str())+16]; sprintf(credentialScope, "%s/%s/%s/aws4_request",awsDate,awsRegion,awsService.c_str()); String key_credential (awsKeyID); key_credential+="/"; key_credential+=credentialScope; //FIX tried a lot of escape functions, but no one was equal to escapeURL from javascript char* ekey_credential = url_encode (key_credential.c_str ()); key_credential = ekey_credential; free (ekey_credential); String method = F("GET"); String canonicalUri = F("/mqtt"); String algorithm = F("AWS4-HMAC-SHA256"); String token = ""; //adding AWS STS security token for temporary AIM credentials if (awsToken != NULL) { char* eToken = url_encode (awsToken); token = eToken; free (eToken); } char canonicalQuerystring [strlen(algorithm.c_str())+strlen(key_credential.c_str())+strlen(awsDate)+strlen(awsTime)+strlen (token.c_str())+225]; sprintf(canonicalQuerystring, "X-Amz-Algorithm=%s", algorithm.c_str()); sprintf(canonicalQuerystring, "%s&X-Amz-Credential=%s", canonicalQuerystring,key_credential.c_str()); sprintf(canonicalQuerystring, "%s&X-Amz-Date=%sT%sZ", canonicalQuerystring, awsDate,awsTime); sprintf(canonicalQuerystring, "%s&X-Amz-Expires=86400", canonicalQuerystring); //sign will last one day sprintf(canonicalQuerystring, "%s&X-Amz-SignedHeaders=host", canonicalQuerystring); String portString = String(port); char canonicalHeaders [strlen (awsDomain)+ strlen (portString.c_str())+ 8]; sprintf(canonicalHeaders, "host:%s:%s\n", awsDomain,portString.c_str()); SHA256* sha256 = new SHA256(); char* payloadHash = (*sha256)("", 0); delete sha256; char canonicalRequest [strlen (method.c_str())+ strlen (canonicalUri.c_str())+strlen(canonicalQuerystring)+strlen(canonicalHeaders)+strlen(payloadHash)+10]; sprintf(canonicalRequest, "%s\n%s\n%s\n%s\nhost\n%s", method.c_str(),canonicalUri.c_str(),canonicalQuerystring,canonicalHeaders,payloadHash); delete[] payloadHash; sha256 = new SHA256(); char* requestHash = (*sha256)(canonicalRequest, strlen (canonicalRequest)); delete sha256; char stringToSign[strlen (algorithm.c_str())+ strlen(awsDate)+strlen (awsTime)+strlen(credentialScope)+strlen(requestHash)+6]; sprintf(stringToSign, "%s\n%sT%sZ\n%s\n%s", algorithm.c_str(),awsDate,awsTime,credentialScope,requestHash); delete[] requestHash; /* Allocate memory for the signature */ char signature [HASH_HEX_LEN2 + 1]; /* Create the signature key */ /* + 4 for "AWS4" */ int keyLen = strlen(awsSecKey) + 4; char key[keyLen + 1]; sprintf(key, "AWS4%s", awsSecKey); char* k1 = hmacSha256(key, keyLen, awsDate, strlen(awsDate)); char* k2 = hmacSha256(k1, SHA256_DEC_HASH_LEN, awsRegion, strlen(awsRegion)); delete[] k1; char* k3 = hmacSha256(k2, SHA256_DEC_HASH_LEN, awsService.c_str(), strlen(awsService.c_str())); delete[] k2; char* k4 = hmacSha256(k3, SHA256_DEC_HASH_LEN, "aws4_request", 12); delete[] k3; char* k5 = hmacSha256(k4, SHA256_DEC_HASH_LEN, stringToSign, strlen(stringToSign)); delete[] k4; // Convert the chars in hash to hex for signature. for (int i = 0; i < SHA256_DEC_HASH_LEN; ++i) { sprintf(signature + 2 * i, "%02lx", 0xff & (unsigned long) k5[i]); } delete[] k5; sprintf(canonicalQuerystring, "%s&X-Amz-Signature=%s", canonicalQuerystring, signature); //adding AWS STS security token for temporary AIM credentials if (awsToken != NULL) { sprintf(canonicalQuerystring, "%s&X-Amz-Security-Token=%s", canonicalQuerystring,token.c_str()); } char* requestUri = new char[strlen(canonicalUri.c_str())+strlen(canonicalQuerystring)+2](); sprintf(requestUri, "%s?%s", canonicalUri.c_str(),canonicalQuerystring); return requestUri; } AWSWebSocketClient& AWSWebSocketClient::setAWSRegion(const char * awsRegion) { if (this->awsRegion != NULL) delete[] this->awsRegion; int len = strlen(awsRegion) + 1; this->awsRegion = new char[len](); strcpy(this->awsRegion, awsRegion); return *this; } AWSWebSocketClient& AWSWebSocketClient::setAWSDomain(const char * awsDomain) { if (this->awsDomain != NULL) delete[] this->awsDomain; int len = strlen(awsDomain) + 1; this->awsDomain = new char[len](); strcpy(this->awsDomain, awsDomain); return *this; } AWSWebSocketClient& AWSWebSocketClient::setAWSSecretKey(const char * awsSecKey) { if (this->awsSecKey != NULL) { if (strlen (awsSecKey) == strlen(this->awsSecKey)){ strcpy(this->awsSecKey, awsSecKey); return *this; } else { delete[] this->awsSecKey; } } int len = strlen(awsSecKey) + 1; this->awsSecKey = new char[len](); strcpy(this->awsSecKey, awsSecKey); return *this; } AWSWebSocketClient& AWSWebSocketClient::setAWSKeyID(const char * awsKeyID) { if (this->awsKeyID != NULL) { if (strlen (awsKeyID) == strlen(this->awsKeyID)){ strcpy(this->awsKeyID, awsKeyID); return *this; } else { delete[] this->awsKeyID; } } int len = strlen(awsKeyID) + 1; this->awsKeyID = new char[len](); strcpy(this->awsKeyID, awsKeyID); return *this; } AWSWebSocketClient& AWSWebSocketClient::setPath(const char * path) { if (this->path != NULL) delete[] this->path; int len = strlen(path) + 1; this->path = new char[len](); strcpy(this->path, path); return *this; } AWSWebSocketClient& AWSWebSocketClient::setCA(const char * ca) { this->ca = ca; return *this; } AWSWebSocketClient& AWSWebSocketClient::setUseAmazonTimestamp(bool useAmazonTimestamp) { this->_useAmazonTimestamp = useAmazonTimestamp; return *this; } AWSWebSocketClient& AWSWebSocketClient::setAWSToken(const char * awsToken) { if (this->awsToken != NULL) { if (strlen (awsToken) == strlen(this->awsToken)){ strcpy(this->awsToken, awsToken); return *this; } else { delete[] this->awsToken; } } int len = strlen(awsToken) + 1; this->awsToken = new char[len](); strcpy(this->awsToken, awsToken); return *this; } int AWSWebSocketClient::connect(IPAddress ip, uint16_t port){ return connect (awsDomain,port); } int AWSWebSocketClient::connect(const String& host, uint16_t port){ return connect (awsDomain,port); } int AWSWebSocketClient::connect(const char *host, uint16_t port) { //disconnect first stop (_connectionTimeout); char* path = this->path; //just need to free path if it was generated to connect to AWS bool freePath = false; if (this->path == NULL) { //just generate AWS Path if user does not inform its own (to support the lib usage out of aws) path = generateAWSPath (port); freePath = true; } if (useSSL == true) beginSslWithCA (host,port,(const char*)path,(const char*)ca,"mqtt"); else begin (host,port,path,F("mqtt")); long now = millis (); while ( (millis ()-now) < _connectionTimeout) { loop (); if (connected () == 1) { if (freePath == true) delete[] path; return 1; } delay (10); } if (freePath == true) delete[] path; return 0; } //store messages arrived by websocket layer to be consumed by mqtt layer through the read funcion void AWSWebSocketClient::putMessage (byte* buffer, int length) { bb.push (buffer,length); } size_t AWSWebSocketClient::write(uint8_t b) { if (_connected == false) return -1; return write (&b,1); } //write through websocket layer size_t AWSWebSocketClient::write(const uint8_t *buf, size_t size) { if (_connected == false) return -1; if (sendBIN (buf,size)) return size; return 0; } //return with there is bytes to consume from the circular buffer (used by mqtt layer) int AWSWebSocketClient::available(){ //force websocket to handle it messages if (_connected == false) return false; loop (); return bb.getSize (); } //read from circular buffer (used by mqtt layer) int AWSWebSocketClient::read() { if (_connected == false) return -1; return bb.pop (); } //read from circular buffer (used by mqtt layer) int AWSWebSocketClient::read(uint8_t *buf, size_t size) { if (_connected == false) return -1; int s = size; if (bb.getSize() #include #include "Client.h" #include "WebSocketsClient.h" #include "CircularByteBuffer.h" #include "sha256.h" #include "Utils.h" #include static const int HASH_HEX_LEN2 = 64; //#define DEBUG_WEBSOCKET_MQTT(...) os_printf( __VA_ARGS__ ) #ifndef DEBUG_WEBSOCKET_MQTT #define DEBUG_WEBSOCKET_MQTT(...) #define NODEBUG_WEBSOCKET_MQTT #endif class AWSWebSocketClient : public Client, private WebSocketsClient { public: //bufferSize defines the size of the circular byte buffer that provides the interface between messages arrived in websocket layer and byte reads from mqtt layer AWSWebSocketClient (unsigned int bufferSize = 1000, unsigned long connectionTimeout = 50000); ~AWSWebSocketClient(); virtual int connect(IPAddress ip, uint16_t port) override; virtual int connect(const char *host, uint16_t port) override; virtual int connect(const String& host, uint16_t port); void putMessage (byte* buffer, int length); size_t write(uint8_t b); size_t write(const uint8_t *buf, size_t size); int available(); int read(); int read(uint8_t *buf, size_t size); int peek(); bool flush(unsigned int maxWaitMs); bool stop(unsigned int maxWaitMs); virtual void flush() override { (void)flush(0); } virtual void stop() override { (void)stop(0); } uint8_t connected() ; operator bool(); bool getUseSSL (); AWSWebSocketClient& setUseSSL (bool value); AWSWebSocketClient& setAWSRegion(const char * awsRegion); AWSWebSocketClient& setAWSDomain(const char * awsDomain); AWSWebSocketClient& setAWSSecretKey(const char * awsSecKey); AWSWebSocketClient& setAWSKeyID(const char * awsKeyID); AWSWebSocketClient& setPath(const char * path); AWSWebSocketClient& setAWSToken(const char * awsToken); AWSWebSocketClient& setFingerprint(const char * fingerprint); AWSWebSocketClient& setCA(const char * ca); AWSWebSocketClient& setUseAmazonTimestamp(bool useAmazonTimestamp); protected: //generate AWS signed path char* generateAWSPath (uint16_t port); //convert the month info String getMonth(String sM); //get current time (UTC) from aws service (used to sign) String getCurrentTimeAmazon(void); String getCurrentTimeNTP(void); String ntpFixNumber (int number); //static instance of aws websocket client static AWSWebSocketClient* instance; //keep the connection state bool _connected; //websocket callback static void webSocketEvent(WStype_t type, uint8_t * payload, size_t length); private: //enable ssl... if your using mqtt over websockets at AWS IoT service, it must be enabled bool useSSL; //connection timeout unsigned long _connectionTimeout; //useAmazonTimestamp bool _useAmazonTimestamp; char* path; /* Name of region, eg. "us-east-1" in "kinesis.us-east-1.amazonaws.com". */ char* awsRegion; /* Domain, optional, eg. "A2MBBEONHC9LUG.iot.us-east-1.amazonaws.com". */ char* awsDomain; /* The user's AWS Secret Key for accessing the AWS Resource. */ char* awsSecKey; /* The user's AWS Access Key ID for accessing the AWS Resource. */ char* awsKeyID; /* The user's AWS Security Token for temporary credentials (just use with AWS STS). */ char* awsToken; /* root certificate */ const char* ca; unsigned long lastTimeUpdate; //circular buffer to keep incoming messages from websocket CircularByteBuffer bb; //connection to get current time WiFiClient timeClient; }; #endif ================================================ FILE: CircularByteBuffer.h ================================================ #ifndef __CIRCULARBYTEBUFFER_H_ #define __CIRCULARBYTEBUFFER_H_ //#define DEBUG_CBB(...) os_printf( __VA_ARGS__ ) #ifndef DEBUG_CBB #define DEBUG_CBB(...) #define NODEBUG_CBB #endif class CircularByteBuffer { public: CircularByteBuffer () { data = NULL; size = 0; capacity = 0; } ~CircularByteBuffer(){ if (data!=NULL) free (data); } void clear () { memset(data,0,capacity); size = 0; begin = 0; end = 0; } void deallocate () { if (data!=NULL) { free (data); data = NULL; } } void init (long capacity) { if (data!=NULL) free (data); data = (byte*) malloc (capacity); size = 0; begin = 0; end = 0; this->capacity = capacity; } long getSize () { return size; } byte peek () { return data[begin]; } void push (byte b) { if (size+1 == capacity) { DEBUG_CBB ("buffer full"); return; } data[end] = b; end = (end+1) % capacity; size += 1; } byte pop () { if (size == 0){ DEBUG_CBB ("buffer empty"); return 0; } byte ret = data[begin]; begin = (begin+1) % capacity; size -= 1; return ret; } void push (byte* b, long len){ if (size+len >= capacity) { DEBUG_CBB ("buffer full"); return; } if ( (end + len) <= capacity ) { memcpy ((void*)&data[end],b,len); end += len; } else { long endSide = capacity - end; memcpy ((void*)&data[end],b,endSide); end = 0; memcpy ((void*)&data[end],b+endSide,len-endSide); end += len-endSide; } size += len; } byte* pop (byte* b, long len){ if ( (size - len) < 0 ) { DEBUG_CBB ("buffer empty"); return NULL; } if ( (begin + len) <= capacity ) { memcpy (b,(void*)&data[begin],len); begin += len; } else { long endSide = capacity - begin; memcpy (b,(void*)&data[begin],endSide); begin = 0; memcpy (b+endSide,(void*)&data[begin],len-endSide); begin += len-endSide; } size -= len; } private: byte* data; long capacity; long size; long begin; long end; }; #endif ================================================ FILE: LICENSE ================================================ GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ================================================ FILE: README.md ================================================ # aws-mqtt-websockets Implementation of a middleware to use AWS MQTT service through websockets. Aiming the esp8266 platform ## ChangeLog * **1.3.0** - update lib and pubsubclient example to use the newest versions of arduino/esp (2.7.3), arduinoWebSocket (2.2.0) and pubsubclient (2.8.0) - now you need to use a certificate to connect to AWS - you can use the certificate alternatives in the pubsubclient example that should be valid up to 2036/2037 * 1.2.0 - using pubsubclient there isn't the "many reconnection issue" (see pubsubclient example to migrate from paho) - get time from pool.ntp.org - tested with arduinoWebSockets v.2.1.0, arduino/esp sdk 2.4.1 and pubsubclient version v2.6.0 * 1.1.0 - can use AWS STS temporary credentials - change some dynamic to static memory allocation to avoid memory fragmentation * 1.0.1 - works with arduinoWebSockets v.2.0.5 and arduino/esp sdk 2.3.0 * 1.0.alpha - stable - works with arduinoWebSockets v.2.0.2 and arduino/esp sdk 2.1.0 * 0.3 - own impl of circular buffer * 0.2 - auto reconnection * 0.1 - has known limitation and it was not extensively tested ## Motivation As we cannot use AWS MQTT service directly because of the lack of support for TLS 1.2*, we need to use the websocket communication as a transport layer for MQTT through SSL (supported by esp8266) This way we can change the state of your esp8266 devices in realtime, without using the AWS Restful API and busy-waiting inefficient approach. * now you can use TLS 1.2 and use the certificates generated by amazon. Here is it an example https://github.com/copercini/esp8266-aws_iot if you wanna try ## Donate if you fell like thank me, you can buy me a coffe (or a beer) https://www.buymeacoffee.com/odelot cheers! ## Dependencies | Library | Link | Use | |---------------------------|-----------------------------------------------------------------|---------------------| |aws-sdk-arduino |https://github.com/odelot/aws-sdk-arduino |aws signing functions| |arduinoWebSockets |https://github.com/Links2004/arduinoWebSockets |websocket comm impl | **Works with these MQTT clients** - Use one or another - see examples | Library | Link | Use | |-------------------------------|-----------------------------------------------------------------|---------------------| |PubSubClient (recommended) |https://github.com/knolleary/pubsubclient |mqtt comm impl | |Paho MQTT for Arduino |https://projects.eclipse.org/projects/technology.paho/downloads |mqtt comm impl | ## Installation 1. Configure your arduino ide to compile and upload programs to ESP8266 (Arduino core for ESP8266 - details https://github.com/esp8266/Arduino )\*\* 2. Install all the dependencies as Arduino Libraries 3. Install aws-mqtt-websockets as Arduino Library as well 4. Configure the example file with your AWS credencials and endpoints (**remember to grant iot permissions for your user**) 5. Compile, upload and run! \** The library was tested with 2.7.3 version of Arduino core for ESP8266 ## Usage It is transparent. It is the same as the usage of Paho. There is just some changes in the connection step. See the example for details. Things you should edit in the example: * ssid and password to connect to wifi * domain/endpoint for your aws iot service * region of your aws iot service * aws user key \*\* * aws user secret key \*\* It is a good practice creating a new user (and grant just **iot services permission**). Avoid use the key/secret key of your main aws console user ``` //AWS IOT config, change these: char wifi_ssid[] = "your-ssid"; char wifi_password[] = "your-password"; char aws_endpoint[] = "your-endpoint.iot.eu-west-1.amazonaws.com"; char aws_key[] = "your-iam-key"; char aws_secret[] = "your-iam-secret-key"; char aws_region[] = "eu-west-1"; const char* aws_topic = "$aws/things/your-device/shadow/update"; int port = 443; //MQTT config const int maxMQTTpackageSize = 128; const int maxMQTTMessageHandlers = 1; ``` ## Grant IoT Permission in AWS Console * Go to https://console.aws.amazon.com/ * Then click IAM * Then click policy. find your policy or create a new policy * set service to IOT * set action to iot:* * set resouce to all resources ## AWS STS Temporary Credential To avoid having a long term credential hardcoded in our device, you can create temporary credentials that will last up to 36 hours using the AWS STS service (learn more here http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html). Using STS you will get a AWS key, AWS secret and AWS token. To inform the AWS token, use the following method ``` //it is just an example. As the credential last up to 36 hours, you will need to get temporary credential every 36 hours //you won't use it hard coded char token[] = 'FQoDYXdzEHgaDN7ZQSxqszH+LgBTXCKsAeU5dsW/g3BK01wyYoBk0vnCfz+D19w2kslSC5drDXyN9Nxx14WcgrOOWNxHsLRDPkcrYhw6DIkW1Nvv1mKu3i86riq19qhBose7v1XngRLBQwgfU/HnlIzJegNEEGgeMAkX0ErF77WfV2pxCzF6ZMRv7kn+a6yE2LURLg/M8eq3lYoyQcJFq55JfVPVUIpx/avEsjgCR/MvlHXlhtJqviClB3mRlvwBcz4vpq4ogpKnzAU='; awsWSclient.setAWSToken (token); ``` ================================================ FILE: examples/aws-DHT-publish-example/DHT-publish.ino ================================================ /** * Example working with library v1.2 * */ #include #include #include #include // DHT22 - https://learn.adafruit.com/dht, https://github.com/adafruit/DHT-sensor-library #include "DHT.h" //AWS #include "sha256.h" #include "Utils.h" //WEBSockets #include #include //MQTT PAHO #include #include #include #include //AWS MQTT Websocket #include "Client.h" #include "AWSWebSocketClient.h" #include "CircularByteBuffer.h" // --------- Config ---------- // //AWS IOT config, change these: char wifi_ssid[] = "your-ssid"; char wifi_password[] = "your-password"; char aws_endpoint[] = "your-endpoint.iot.eu-west-1.amazonaws.com"; char aws_key[] = "your-iam-key"; char aws_secret[] = "your-iam-secret-key"; char aws_region[] = "eu-west-1"; const char* aws_topic = "$aws/things/your-device/shadow/update"; int port = 443; // If stuff isn't working right, watch the console: #define DEBUG_PRINT 1 #define DHTPIN 5 #define DHTTYPE DHT22 //Set for 11, 21, or 22 //MQTT config const int maxMQTTpackageSize = 512; const int maxMQTTMessageHandlers = 1; // ---------- /Config ----------// DHT dht(DHTPIN, DHTTYPE); ESP8266WiFiMulti WiFiMulti; AWSWebSocketClient awsWSclient(1000); IPStack ipstack(awsWSclient); MQTT::Client *client = NULL; //# of connections long connection = 0; //generate random mqtt clientID char* generateClientID () { char* cID = new char[23](); for (int i=0; i<22; i+=1) cID[i]=(char)random(1, 256); return cID; } //count messages arrived int arrivedcount = 0; //callback to handle mqtt messages void messageArrived(MQTT::MessageData& md) { MQTT::Message &message = md.message; if (DEBUG_PRINT) { Serial.print("Message "); Serial.print(++arrivedcount); Serial.print(" arrived: qos "); Serial.print(message.qos); Serial.print(", retained "); Serial.print(message.retained); Serial.print(", dup "); Serial.print(message.dup); Serial.print(", packetid "); Serial.println(message.id); Serial.print("Payload "); char* msg = new char[message.payloadlen+1](); memcpy (msg,message.payload,message.payloadlen); Serial.println(msg); delete msg; } } //connects to websocket layer and mqtt layer bool connect () { if (client == NULL) { client = new MQTT::Client(ipstack); } else { if (client->isConnected ()) { client->disconnect (); } delete client; client = new MQTT::Client(ipstack); } //delay is not necessary... it just help us to get a "trustful" heap space value delay (1000); if (DEBUG_PRINT) { Serial.print (millis ()); Serial.print (" - conn: "); Serial.print (++connection); Serial.print (" - ("); Serial.print (ESP.getFreeHeap ()); Serial.println (")"); } int rc = ipstack.connect(aws_endpoint, port); if (rc != 1) { if (DEBUG_PRINT) { Serial.println("error connection to the websocket server"); } return false; } else { if (DEBUG_PRINT) { Serial.println("websocket layer connected"); } } if (DEBUG_PRINT) { Serial.println("MQTT connecting"); } MQTTPacket_connectData data = MQTTPacket_connectData_initializer; data.MQTTVersion = 3; char* clientID = generateClientID (); data.clientID.cstring = clientID; rc = client->connect(data); delete[] clientID; if (rc != 0) { if (DEBUG_PRINT) { Serial.print("error connection to MQTT server"); Serial.println(rc); return false; } } if (DEBUG_PRINT) { Serial.println("MQTT connected"); } return true; } //subscribe to a mqtt topic void subscribe () { //subscrip to a topic int rc = client->subscribe(aws_topic, MQTT::QOS0, messageArrived); if (rc != 0) { if (DEBUG_PRINT) { Serial.print("rc from MQTT subscribe is "); Serial.println(rc); } return; } if (DEBUG_PRINT) { Serial.println("MQTT subscribed"); } } void setup() { Serial.begin (115200); WiFiMulti.addAP(wifi_ssid, wifi_password); while(WiFiMulti.run() != WL_CONNECTED) { delay(100); if (DEBUG_PRINT) { Serial.print (". "); } } if (DEBUG_PRINT) { Serial.println ("\nconnected to network " + String(wifi_ssid) + "\n"); } //fill AWS parameters awsWSclient.setAWSRegion(aws_region); awsWSclient.setAWSDomain(aws_endpoint); awsWSclient.setAWSKeyID(aws_key); awsWSclient.setAWSSecretKey(aws_secret); awsWSclient.setUseSSL(true); dht.begin(); } void loop() { // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) delay(10000); String h = String(dht.readHumidity()); // Read temperature as Fahrenheit (isFahrenheit = true) String f = String(dht.readTemperature(true)); if (isnan(dht.readHumidity()) || isnan(dht.readTemperature(true))) { Serial.println("Failed to read from DHT sensor!"); return; } else { if (DEBUG_PRINT) { Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(f); Serial.print(" *F\t\n"); } }; String values = "{\"state\":{\"reported\":{\"temp\": " + f + ",\"humidity\": " + h + "}}}"; // http://stackoverflow.com/questions/31614364/arduino-joining-string-and-char const char *publish_message = values.c_str(); //keep the mqtt up and running if (awsWSclient.connected ()) { client->yield(); subscribe (); //publish MQTT::Message message; char buf[1000]; strcpy(buf, publish_message); message.qos = MQTT::QOS0; message.retained = false; message.dup = false; message.payload = (void*)buf; message.payloadlen = strlen(buf)+1; int rc = client->publish(aws_topic, message); } else { //handle reconnection connect (); } } ================================================ FILE: examples/aws-mqtt-websocket-example-paho/aws-mqtt-websocket-example-paho.ino ================================================ /** * Example working with library v1.2 * */ #include #include #include #include //AWS #include "sha256.h" #include "Utils.h" //WEBSockets #include #include //MQTT PAHO #include #include #include #include //AWS MQTT Websocket #include "Client.h" #include "AWSWebSocketClient.h" #include "CircularByteBuffer.h" extern "C" { #include "user_interface.h" } //AWS IOT config, change these: char wifi_ssid[] = "your-ssid"; char wifi_password[] = "your-password"; char aws_endpoint[] = "your-endpoint.iot.eu-west-1.amazonaws.com"; char aws_key[] = "your-iam-key"; char aws_secret[] = "your-iam-secret-key"; char aws_region[] = "eu-west-1"; const char* aws_topic = "$aws/things/your-device/shadow/update"; int port = 443; //MQTT config const int maxMQTTpackageSize = 512; const int maxMQTTMessageHandlers = 1; ESP8266WiFiMulti WiFiMulti; AWSWebSocketClient awsWSclient(1000); IPStack ipstack(awsWSclient); MQTT::Client client(ipstack); //# of connections long connection = 0; //generate random mqtt clientID char* generateClientID () { char* cID = new char[23](); for (int i=0; i<22; i+=1) cID[i]=(char)random(1, 256); return cID; } //count messages arrived int arrivedcount = 0; //callback to handle mqtt messages void messageArrived(MQTT::MessageData& md) { MQTT::Message &message = md.message; Serial.print("Message "); Serial.print(++arrivedcount); Serial.print(" arrived: qos "); Serial.print(message.qos); Serial.print(", retained "); Serial.print(message.retained); Serial.print(", dup "); Serial.print(message.dup); Serial.print(", packetid "); Serial.println(message.id); Serial.print("Payload "); char* msg = new char[message.payloadlen+1](); memcpy (msg,message.payload,message.payloadlen); Serial.println(msg); delete msg; } //connects to websocket layer and mqtt layer bool connect () { if (client.isConnected ()) { client.disconnect (); } //delay is not necessary... it just help us to get a "trustful" heap space value delay (1000); Serial.print (millis ()); Serial.print (" - conn: "); Serial.print (++connection); Serial.print (" - ("); Serial.print (ESP.getFreeHeap ()); Serial.println (")"); int rc = ipstack.connect(aws_endpoint, port); if (rc != 1) { Serial.println("error connection to the websocket server"); return false; } else { Serial.println("websocket layer connected"); } Serial.println("MQTT connecting"); MQTTPacket_connectData data = MQTTPacket_connectData_initializer; data.MQTTVersion = 4; char* clientID = generateClientID (); data.clientID.cstring = clientID; rc = client.connect(data); delete[] clientID; if (rc != 0) { Serial.print("error connection to MQTT server"); Serial.println(rc); return false; } Serial.println("MQTT connected"); return true; } //subscribe to a mqtt topic void subscribe () { //subscript to a topic int rc = client.subscribe(aws_topic, MQTT::QOS0, messageArrived); if (rc != 0) { Serial.print("rc from MQTT subscribe is "); Serial.println(rc); return; } Serial.println("MQTT subscribed"); } //send a message to a mqtt topic void sendmessage () { //send a message MQTT::Message message; char buf[100]; strcpy(buf, "{\"state\":{\"reported\":{\"on\": false}, \"desired\":{\"on\": false}}}"); message.qos = MQTT::QOS0; message.retained = false; message.dup = false; message.payload = (void*)buf; message.payloadlen = strlen(buf)+1; int rc = client.publish(aws_topic, message); } void setup() { wifi_set_sleep_type(NONE_SLEEP_T); Serial.begin (115200); delay (2000); Serial.setDebugOutput(1); //fill with ssid and wifi password WiFiMulti.addAP(wifi_ssid, wifi_password); Serial.println ("connecting to wifi"); while(WiFiMulti.run() != WL_CONNECTED) { delay(100); Serial.print ("."); } Serial.println ("\nconnected"); //fill AWS parameters awsWSclient.setAWSRegion(aws_region); awsWSclient.setAWSDomain(aws_endpoint); awsWSclient.setAWSKeyID(aws_key); awsWSclient.setAWSSecretKey(aws_secret); awsWSclient.setUseSSL(true); if (connect ()){ subscribe (); sendmessage (); } } void loop() { //keep the mqtt up and running if (awsWSclient.connected ()) { client.yield(50); } else { //handle reconnection if (connect ()){ subscribe (); } } } ================================================ FILE: examples/aws-mqtt-websocket-example-pubsubclient/aws-mqtt-websocket-example-pubsubclient.ino ================================================ /** * Example working with library v1.3 * */ #include #include #include #include #include //AWS #include "sha256.h" #include "Utils.h" //WEBSockets #include #include //MQTT PUBSUBCLIENT LIB #include //AWS MQTT Websocket #include "Client.h" #include "AWSWebSocketClient.h" #include "CircularByteBuffer.h" extern "C" { #include "user_interface.h" } //AWS IOT config, change these: char wifi_ssid[] = "your-ssid"; char wifi_password[] = "your-password"; char aws_endpoint[] = "your-endpoint.iot.eu-west-1.amazonaws.com"; char aws_key[] = "your-iam-key"; char aws_secret[] = "your-iam-secret-key"; char aws_region[] = "eu-west-1"; const char* aws_topic = "$aws/things/your-device/shadow/update"; int port = 443; /* uncomment the following line to use an alternate root CA if the first one does not work */ // #define ALTERNATE_ROOT_CA #ifndef ALTERNATE_ROOT_CA // AWS root certificate - expires 2037 const char ca[] PROGMEM = R"EOF( -----BEGIN CERTIFICATE----- MIIEkjCCA3qgAwIBAgITBn+USionzfP6wq4rAfkI7rnExjANBgkqhkiG9w0BAQsF ADCBmDELMAkGA1UEBhMCVVMxEDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNj b3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4x OzA5BgNVBAMTMlN0YXJmaWVsZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1 dGhvcml0eSAtIEcyMB4XDTE1MDUyNTEyMDAwMFoXDTM3MTIzMTAxMDAwMFowOTEL MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM 9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L 93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm jgSubJrIqg0CAwEAAaOCATEwggEtMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ BAQDAgGGMB0GA1UdDgQWBBSEGMyFNOy8DJSULghZnMeyEE4KCDAfBgNVHSMEGDAW gBScXwDfqgHXMCs4iKK4bUqc8hGRgzB4BggrBgEFBQcBAQRsMGowLgYIKwYBBQUH MAGGImh0dHA6Ly9vY3NwLnJvb3RnMi5hbWF6b250cnVzdC5jb20wOAYIKwYBBQUH MAKGLGh0dHA6Ly9jcnQucm9vdGcyLmFtYXpvbnRydXN0LmNvbS9yb290ZzIuY2Vy MD0GA1UdHwQ2MDQwMqAwoC6GLGh0dHA6Ly9jcmwucm9vdGcyLmFtYXpvbnRydXN0 LmNvbS9yb290ZzIuY3JsMBEGA1UdIAQKMAgwBgYEVR0gADANBgkqhkiG9w0BAQsF AAOCAQEAYjdCXLwQtT6LLOkMm2xF4gcAevnFWAu5CIw+7bMlPLVvUOTNNWqnkzSW MiGpSESrnO09tKpzbeR/FoCJbM8oAxiDR3mjEH4wW6w7sGDgd9QIpuEdfF7Au/ma eyKdpwAJfqxGF4PcnCZXmTA5YpaP7dreqsXMGz7KQ2hsVxa81Q4gLv7/wmpdLqBK bRRYh5TmOTFffHPLkIhqhBGWJ6bt2YFGpn6jcgAKUj6DiAdjd4lpFw85hdKrCEVN 0FE6/V1dN2RMfjCyVSRCnTawXZwXgWHxyvkQAiSr6w10kY17RSlQOYiypok1JR4U akcjMS9cmvqtmg5iUaQqqcT5NJ0hGA== -----END CERTIFICATE----- )EOF"; #else // AWS root certificate (Verisign) - expires 2036 const char ca[] PROGMEM = R"EOF( -----BEGIN CERTIFICATE----- MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0 aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1 nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+ rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/ NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y 5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ 4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq -----END CERTIFICATE----- )EOF"; #endif //MQTT config const int maxMQTTpackageSize = 512; const int maxMQTTMessageHandlers = 1; ESP8266WiFiMulti WiFiMulti; AWSWebSocketClient awsWSclient(1000); PubSubClient client(awsWSclient); //# of connections long connection = 0; //generate random mqtt clientID char* generateClientID () { char* cID = new char[23](); for (int i=0; i<22; i+=1) cID[i]=(char)random(1, 256); return cID; } //count messages arrived int arrivedcount = 0; //callback to handle mqtt messages void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); } //connects to websocket layer and mqtt layer bool connect () { if (client.connected()) { client.disconnect (); } //delay is not necessary... it just help us to get a "trustful" heap space value delay (1000); Serial.print (millis ()); Serial.print (" - conn: "); Serial.print (++connection); Serial.print (" - ("); Serial.print (ESP.getFreeHeap ()); Serial.println (")"); //creating random client id char* clientID = generateClientID (); client.setServer(aws_endpoint, port); if (client.connect(clientID)) { Serial.println("connected"); return true; } else { Serial.print("failed, rc="); Serial.print(client.state()); return false; } } //subscribe to a mqtt topic void subscribe () { client.setCallback(callback); client.subscribe(aws_topic); //subscript to a topic Serial.println("MQTT subscribed"); } //send a message to a mqtt topic void sendmessage () { //send a message char buf[100]; strcpy(buf, "{\"state\":{\"reported\":{\"on\": false}, \"desired\":{\"on\": false}}}"); int rc = client.publish(aws_topic, buf); } void setClock() { configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov"); Serial.print("Waiting for NTP time sync: "); time_t now = time(nullptr); while (now < 8 * 3600 * 2) { delay(500); Serial.print("."); now = time(nullptr); } Serial.println(""); struct tm timeinfo; gmtime_r(&now, &timeinfo); Serial.print("Current time: "); Serial.print(asctime(&timeinfo)); } void setup() { wifi_set_sleep_type(NONE_SLEEP_T); Serial.begin (115200); delay (2000); Serial.setDebugOutput(1); //fill with ssid and wifi password WiFiMulti.addAP(wifi_ssid, wifi_password); Serial.println ("connecting to wifi"); while(WiFiMulti.run() != WL_CONNECTED) { delay(100); Serial.print ("."); } Serial.println ("\nconnected"); setClock(); // Required for X.509 certificate validation //fill AWS parameters awsWSclient.setAWSRegion(aws_region); awsWSclient.setAWSDomain(aws_endpoint); awsWSclient.setAWSKeyID(aws_key); awsWSclient.setAWSSecretKey(aws_secret); awsWSclient.setUseSSL(true); awsWSclient.setCA(ca); //as we had to configurate ntp time to validate the certificate, we can use it to validate aws connection as well awsWSclient.setUseAmazonTimestamp(false); if (connect ()){ subscribe (); sendmessage (); } } void loop() { //keep the mqtt up and running if (awsWSclient.connected ()) { client.loop (); } else { //handle reconnection if (connect ()){ subscribe (); } } }