[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\nbuy_me_a_coffee: odelot\n"
  },
  {
    "path": "AWSWebSocketClient.cpp",
    "content": "#include \"AWSWebSocketClient.h\"\n\n//work as a singleton to be used by websocket layer message callback\nAWSWebSocketClient* AWSWebSocketClient::instance = NULL;\n\nString AWSWebSocketClient::ntpFixNumber (int number) {\n    String ret = \"\";\n    if (number < 10) {\n        ret = \"0\";\n        ret += number;\n        return ret;\n    }\n    else{\n        ret += number;\n        return ret;\n    } \n}\n\n//assuming you have already configure time with a ntp server (also needed by validate CA)\nString AWSWebSocketClient::getCurrentTimeNTP (void) {\n  time_t now = time(nullptr);\n  struct tm timeinfo;\n  gmtime_r(&now, &timeinfo);  \n  String date = \"\";\n  date += (1900+timeinfo.tm_year);\n  date += ntpFixNumber(timeinfo.tm_mon+1);\n  date += ntpFixNumber(timeinfo.tm_mday);\n  date += ntpFixNumber(timeinfo.tm_hour);\n  date += ntpFixNumber(timeinfo.tm_min);\n  date += ntpFixNumber(timeinfo.tm_sec);  \n  return date;\n}\n\n//callback to handle messages coming from the websocket layer\nvoid AWSWebSocketClient::webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {\n\n    switch(type) {\n        case WStype_DISCONNECTED:\n            DEBUG_WEBSOCKET_MQTT(\"[AWSc] Disconnected!\\n\");\n\t\t\tAWSWebSocketClient::instance->stop (30000);\t\t\t\n            break;\n        case WStype_CONNECTED:            \n            DEBUG_WEBSOCKET_MQTT(\"[AWSc] Connected to url: %d %s\\n\", length, payload);\n\t\t\tAWSWebSocketClient::instance->_connected = true;\n            break;\n        case WStype_TEXT:\n            DEBUG_WEBSOCKET_MQTT(\"[WSc] get text: %s\\n\", payload);\n            AWSWebSocketClient::instance->putMessage (payload, length);\n            break;\n        case WStype_BIN:\n            DEBUG_WEBSOCKET_MQTT(\"[WSc] get binary length: %u\\n\", length);\n            //hexdump(payload, length);\n            AWSWebSocketClient::instance->putMessage (payload, length);\n            break;\n    }\n}\n\n//constructor\nAWSWebSocketClient::AWSWebSocketClient (unsigned int bufferSize, unsigned long connectionTimeout) {\n    useSSL = true;\n    _connectionTimeout = connectionTimeout;\n    AWSWebSocketClient:instance = this;\n    onEvent(AWSWebSocketClient::webSocketEvent);\n    awsRegion = NULL;\n    awsSecKey = NULL;\n    awsKeyID = NULL;\n    awsDomain = NULL;\n    awsToken = NULL;\n    path = NULL;\n    _connected = false;\t\n    bb.init (bufferSize); \n    lastTimeUpdate = 0;\n    _useAmazonTimestamp = true;\n    begin(\"\", 0);\n}\n\n//destructor\nAWSWebSocketClient::~AWSWebSocketClient(void) {\n    if (awsRegion != NULL)\n        delete[] awsRegion;\n    if (awsDomain != NULL)\n        delete[] awsDomain;\n    if (awsSecKey != NULL)\n        delete[] awsSecKey;\n    if (awsKeyID != NULL)\n        delete[] awsKeyID;\n    if (path != NULL)\n        delete[] path;\t\n\tif (awsToken != NULL)\n        delete[] awsToken;\n}\n\n// convert month to digits\nString AWSWebSocketClient::getMonth(String sM) {\n  if(sM==\"Jan\") return \"01\";\n  if(sM==\"Feb\") return \"02\";\n  if(sM==\"Mar\") return \"03\";\n  if(sM==\"Apr\") return \"04\";\n  if(sM==\"May\") return \"05\";\n  if(sM==\"Jun\") return \"06\";\n  if(sM==\"Jul\") return \"07\";\n  if(sM==\"Aug\") return \"08\";\n  if(sM==\"Sep\") return \"09\";\n  if(sM==\"Oct\") return \"10\";\n  if(sM==\"Nov\") return \"11\";\n  if(sM==\"Dec\") return \"12\";\n  return \"01\";\n}\n\n//get current time (UTC) from aws service (used to sign)\nString AWSWebSocketClient::getCurrentTimeAmazon (void) {\n\t\n    int timeout_busy = 0;\n\n    String GmtDate;\n    String dateStamp;\n    dateStamp =\"19860618123600\";\n    \n    if (timeClient.connect((\"aws.amazon.com\"), 80)) {\n\n      // send a bad header on purpose, so we get a 400 with a DATE: timestamp\n      //Send Request\n      timeClient.println(F(\"GET example.com/ HTTP/1.1\"));\n      timeClient.println(F(\"Connection: close\"));\n      timeClient.println();\n\n      while((!timeClient.available()) && (timeout_busy++ < 5000)){\n        // Wait until the client sends some data\n        delay(1);\n      }\n\n      // kill client if timeout\n      if(timeout_busy >= 5000) {\n          timeClient.flush();\n          timeClient.stop();\t\t  \n          DEBUG_WEBSOCKET_MQTT(\"timeout receiving timeserver data\");\n\t\t  \n          return dateStamp;\n      }\n\n      // read the http GET Response\n      String req2 = timeClient.readString();\n\n      // close connection\n      delay(1);\n      timeClient.flush();\n      timeClient.stop();\t \n      int ipos = req2.indexOf(\"Date:\");\n      if(ipos > 0) {\n        String gmtDate = req2.substring(ipos, ipos + 35);\n        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);\n        dateStamp = utctime.substring(0, 14);\n      }\n    }\n    else {\n       DEBUG_WEBSOCKET_MQTT(\"did not connect to timeserver\");\n    }\n   \n    timeout_busy=0;     // reset timeout\n\t\n    return dateStamp;   // Return latest or last good dateStamp\n}\n\n/* Converts an integer value to its hex character*/\nchar to_hex(char code) {\n  static char hex[] = \"0123456789ABCDEF\";\n  return hex[code & 15];\n}\n\n/* Returns a url-encoded version of str */\n/* IMPORTANT: be sure to free() the returned string after use */\nchar* url_encode(const char* str) {\n  const char* pstr = str;\n  char *buf = (char*) malloc(strlen(str) * 3 + 1), *pbuf = buf;\n  while (*pstr) {\n    if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') \n      *pbuf++ = *pstr;\n    else if (*pstr == ' ') \n      *pbuf++ = '+';\n    else \n      *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);\n    pstr++;\n  }\n  *pbuf = '\\0';\n  return buf;\n}\n\n//generate AWS url path, signed using url parameters\nchar* AWSWebSocketClient::generateAWSPath (uint16_t port) {\n    \n    String dateTime;\n    if (_useAmazonTimestamp) {\n        dateTime = getCurrentTimeAmazon ();\n    } else  {\n        dateTime = getCurrentTimeNTP ();\n    }\n    DEBUG_WEBSOCKET_MQTT (dateTime.c_str());    \n    String awsService = F(\"iotdevicegateway\");\n    char awsDate[9];\n    strncpy(awsDate, dateTime.c_str(), 8);\n    awsDate[8] = '\\0';\n    char awsTime[7];\n    strncpy(awsTime, dateTime.c_str() + 8, 6);\n    awsTime[6] = '\\0';\n    \n\tchar credentialScope[strlen(awsDate)+strlen(awsRegion)+strlen(awsService.c_str())+16];\n\tsprintf(credentialScope, \"%s/%s/%s/aws4_request\",awsDate,awsRegion,awsService.c_str());\n\tString key_credential (awsKeyID);\n\tkey_credential+=\"/\";\n\tkey_credential+=credentialScope;\n\t//FIX tried a lot of escape functions, but no one was equal to escapeURL from javascript\n\tchar* ekey_credential = url_encode (key_credential.c_str ());\n\tkey_credential = ekey_credential;\n\tfree (ekey_credential);\n\t\n\tString method = F(\"GET\");\n\tString canonicalUri = F(\"/mqtt\");\n\tString algorithm = F(\"AWS4-HMAC-SHA256\");\n\tString token = \"\";\n\t//adding AWS STS security token for temporary AIM credentials\n\tif (awsToken != NULL) {\n\t\tchar* eToken = url_encode (awsToken);\n\t\ttoken = eToken;\n\t\tfree (eToken);\n\n\t}\n\t\n\tchar canonicalQuerystring [strlen(algorithm.c_str())+strlen(key_credential.c_str())+strlen(awsDate)+strlen(awsTime)+strlen (token.c_str())+225];\n\tsprintf(canonicalQuerystring, \"X-Amz-Algorithm=%s\", algorithm.c_str());\n\tsprintf(canonicalQuerystring, \"%s&X-Amz-Credential=%s\", canonicalQuerystring,key_credential.c_str());\n\tsprintf(canonicalQuerystring, \"%s&X-Amz-Date=%sT%sZ\", canonicalQuerystring, awsDate,awsTime);\n\tsprintf(canonicalQuerystring, \"%s&X-Amz-Expires=86400\", canonicalQuerystring); //sign will last one day\n\tsprintf(canonicalQuerystring, \"%s&X-Amz-SignedHeaders=host\", canonicalQuerystring);\n\n\tString portString = String(port);\n\tchar canonicalHeaders [strlen (awsDomain)+ strlen (portString.c_str())+ 8];\n\n\tsprintf(canonicalHeaders, \"host:%s:%s\\n\", awsDomain,portString.c_str());\n\tSHA256* sha256 = new SHA256();\n\tchar* payloadHash = (*sha256)(\"\", 0);\n\tdelete sha256;\n\tchar canonicalRequest [strlen (method.c_str())+ strlen (canonicalUri.c_str())+strlen(canonicalQuerystring)+strlen(canonicalHeaders)+strlen(payloadHash)+10];\n\n\tsprintf(canonicalRequest, \"%s\\n%s\\n%s\\n%s\\nhost\\n%s\", method.c_str(),canonicalUri.c_str(),canonicalQuerystring,canonicalHeaders,payloadHash);\n\tdelete[] payloadHash;\n\n\tsha256 = new SHA256();\n\tchar* requestHash = (*sha256)(canonicalRequest, strlen (canonicalRequest));\n\tdelete sha256;\n\tchar stringToSign[strlen (algorithm.c_str())+ strlen(awsDate)+strlen (awsTime)+strlen(credentialScope)+strlen(requestHash)+6];\n\tsprintf(stringToSign, \"%s\\n%sT%sZ\\n%s\\n%s\", algorithm.c_str(),awsDate,awsTime,credentialScope,requestHash);\n\tdelete[] requestHash;\n\n\t/* Allocate memory for the signature */\n    char signature [HASH_HEX_LEN2 + 1];\n\n    /* Create the signature key */\n    /* + 4 for \"AWS4\" */\n    int keyLen = strlen(awsSecKey) + 4;\n    char key[keyLen + 1];\n    sprintf(key, \"AWS4%s\", awsSecKey);\n\n    char* k1 = hmacSha256(key, keyLen, awsDate, strlen(awsDate));\t\n    \n    char* k2 = hmacSha256(k1, SHA256_DEC_HASH_LEN, awsRegion,\n            strlen(awsRegion));\n\n    delete[] k1;\n    char* k3 = hmacSha256(k2, SHA256_DEC_HASH_LEN, awsService.c_str(),\n            strlen(awsService.c_str()));\n\n\tdelete[] k2;\n    char* k4 = hmacSha256(k3, SHA256_DEC_HASH_LEN, \"aws4_request\", 12);\n\n\tdelete[] k3;\n    char* k5 = hmacSha256(k4, SHA256_DEC_HASH_LEN, stringToSign, strlen(stringToSign));\n\n\tdelete[] k4;\t\n    // Convert the chars in hash to hex for signature.\n    for (int i = 0; i < SHA256_DEC_HASH_LEN; ++i) {\n        sprintf(signature + 2 * i, \"%02lx\", 0xff & (unsigned long) k5[i]);\n    }\n    delete[] k5;\n\n\tsprintf(canonicalQuerystring, \"%s&X-Amz-Signature=%s\", canonicalQuerystring, signature);\n\t\n\t//adding AWS STS security token for temporary AIM credentials\n\tif (awsToken != NULL) {\t\t\n\t\tsprintf(canonicalQuerystring, \"%s&X-Amz-Security-Token=%s\", canonicalQuerystring,token.c_str());\t\t\n\t}\n\t\n\tchar* requestUri = new char[strlen(canonicalUri.c_str())+strlen(canonicalQuerystring)+2]();\t\n\tsprintf(requestUri, \"%s?%s\", canonicalUri.c_str(),canonicalQuerystring);\n\t\n\treturn requestUri;\n\n}\n\nAWSWebSocketClient& AWSWebSocketClient::setAWSRegion(const char * awsRegion) {\n\tif (this->awsRegion != NULL)\n        delete[] this->awsRegion;\n    int len = strlen(awsRegion) + 1;\n    this->awsRegion = new char[len]();\n    strcpy(this->awsRegion, awsRegion);\n\treturn *this;\n}\n\nAWSWebSocketClient& AWSWebSocketClient::setAWSDomain(const char * awsDomain) {\n\tif (this->awsDomain != NULL)\n        delete[] this->awsDomain;\n    int len = strlen(awsDomain) + 1;\n    this->awsDomain = new char[len]();\n    strcpy(this->awsDomain, awsDomain);\n\treturn *this;\n}\n\nAWSWebSocketClient& AWSWebSocketClient::setAWSSecretKey(const char * awsSecKey) {\n    if (this->awsSecKey != NULL) \n\t{\n\t\tif (strlen (awsSecKey) ==  strlen(this->awsSecKey)){\n\t\t\tstrcpy(this->awsSecKey, awsSecKey);\n\t\t\treturn *this;\n\t\t} else {\t\t\t\n\t\t\tdelete[] this->awsSecKey;\t\n\t\t}\n        \n\t}\n\tint len = strlen(awsSecKey) + 1;\n    this->awsSecKey = new char[len]();\n    strcpy(this->awsSecKey, awsSecKey);\n\treturn *this;\n}\nAWSWebSocketClient& AWSWebSocketClient::setAWSKeyID(const char * awsKeyID) {\n    if (this->awsKeyID != NULL) {\n\t\tif (strlen (awsKeyID) ==  strlen(this->awsKeyID)){\n\t\t\tstrcpy(this->awsKeyID, awsKeyID);\n\t\t\treturn *this;\n\t\t} else {\t\t\t\n\t\t\tdelete[] this->awsKeyID;\t\n\t\t}\t\n\t}\n\t\n\tint len = strlen(awsKeyID) + 1;\n    this->awsKeyID = new char[len]();\n    strcpy(this->awsKeyID, awsKeyID);\n\treturn *this;\n}\n\nAWSWebSocketClient& AWSWebSocketClient::setPath(const char * path) {\n    if (this->path != NULL)\n        delete[] this->path;\n\tint len = strlen(path) + 1;\n    this->path = new char[len]();\n    strcpy(this->path, path);\n\treturn *this;\n}\n\nAWSWebSocketClient& AWSWebSocketClient::setCA(const char * ca) {\n    this->ca = ca;\n    return *this;\n}\n\nAWSWebSocketClient& AWSWebSocketClient::setUseAmazonTimestamp(bool useAmazonTimestamp) {\n  this->_useAmazonTimestamp = useAmazonTimestamp;\n  return *this;\n}\n\nAWSWebSocketClient& AWSWebSocketClient::setAWSToken(const char * awsToken) {\n\tif (this->awsToken != NULL)\n       {\n\t\tif (strlen (awsToken) ==  strlen(this->awsToken)){\n\t\t\tstrcpy(this->awsToken, awsToken);\n\t\t\treturn *this;\n\t\t} else {\t\t\t\n\t\t\tdelete[] this->awsToken;\t\n\t\t}\t\n\t}\n\tint len = strlen(awsToken) + 1;\n    this->awsToken = new char[len]();\n    strcpy(this->awsToken, awsToken);\n\treturn *this;\n}\n\nint AWSWebSocketClient::connect(IPAddress ip, uint16_t port){\n\t  return connect (awsDomain,port);\n}\n\nint AWSWebSocketClient::connect(const String& host, uint16_t port){\n\t  return connect (awsDomain,port);\n}\n\nint AWSWebSocketClient::connect(const char *host, uint16_t port) {\n\t  //disconnect first\n    stop (_connectionTimeout);\t\n\t  char* path = this->path;\n\t  //just need to free path if it was generated to connect to AWS\n\t  bool freePath = false;\n\t  if (this->path == NULL) {\t\t  \n\t\t  //just generate AWS Path if user does not inform its own (to support the lib usage out of aws)\n\t\t  path = generateAWSPath (port);       \n\t\t  freePath = true;\t\t  \n\t  }\n\t  if (useSSL == true)       \n\t\t  beginSslWithCA (host,port,(const char*)path,(const char*)ca,\"mqtt\");\n\t  else\n\t\t  begin (host,port,path,F(\"mqtt\"));\n\t  long now = millis ();\n\t  while ( (millis ()-now) < _connectionTimeout) {\n\t\t  loop ();\t\t  \n\t\t  if (connected () == 1) {\t\t  \n\t\t\t  if (freePath == true)\n\t\t\t\tdelete[] path;\n\t\t\t  return 1;\n\t\t  }\n\t\t  delay (10);\n\t  }\n\t  if (freePath == true)\n\t\tdelete[] path;\n\t  return 0;\n}\n\n//store messages arrived by websocket layer to be consumed by mqtt layer through the read funcion\nvoid AWSWebSocketClient::putMessage (byte* buffer, int length) {\n\tbb.push (buffer,length);\t\n}\n\nsize_t AWSWebSocketClient::write(uint8_t b) {\n\tif (_connected == false)\n\t  return -1;\n  return write (&b,1);\n}\n\n//write through websocket layer\nsize_t AWSWebSocketClient::write(const uint8_t *buf, size_t size) {\n  if (_connected == false)\n\t  return -1;\n  if (sendBIN (buf,size))\n\t  return size;\n  return 0;\n}\n\n//return with there is bytes to consume from the circular buffer (used by mqtt layer)\nint AWSWebSocketClient::available(){\n  //force websocket to handle it messages\n  if (_connected == false)\n\t  return false;\n  loop ();\n  return bb.getSize ();\n}\n\n//read from circular buffer (used by mqtt layer)\nint AWSWebSocketClient::read() {\n\tif (_connected == false)\n\t  return -1;\n\treturn bb.pop ();\n}\n\n//read from circular buffer (used by mqtt layer)\nint AWSWebSocketClient::read(uint8_t *buf, size_t size) {\n\tif (_connected == false)\n\t  return -1;\n\tint s = size;\n\tif (bb.getSize()<s)\n\t\ts = bb.getSize ();\n\n\tbb.pop (buf,s);\t\n\treturn s;\n};\n\nint AWSWebSocketClient::peek() {\n\treturn bb.peek ();\n}\n\nbool AWSWebSocketClient::flush(unsigned int maxWaitMs) {\n  //TODO implementation needed??\n  return true;\n}\n\nbool AWSWebSocketClient::stop(unsigned int maxWaitMs) {\n\tif (_connected == true) {\t\t\n\t\t_connected = false;\t\t\n\t}\n    bb.clear ();\n\tclientDisconnect(&_client);\n\t//disconnect ();\n\n  return true;\n}\n\nuint8_t AWSWebSocketClient::connected() {    \n    return _connected;\n};\n\nAWSWebSocketClient::operator bool() {\n\treturn _connected;\n};\n\n\nbool AWSWebSocketClient::getUseSSL () {\n  return useSSL;\n}\n\nAWSWebSocketClient& AWSWebSocketClient::setUseSSL (bool value) {\n  useSSL = value;\n  return *this;\n}\n"
  },
  {
    "path": "AWSWebSocketClient.h",
    "content": "#ifndef __AWSWEBSOCKETCLIENT_H_\n#define __AWSWEBSOCKETCLIENT_H_\n\n#include <Arduino.h>\n#include <Stream.h>\n#include \"Client.h\"\n#include \"WebSocketsClient.h\"\n#include \"CircularByteBuffer.h\"\n#include \"sha256.h\"\n#include \"Utils.h\"\n#include <time.h>\n\nstatic const int HASH_HEX_LEN2 = 64;\n\n//#define DEBUG_WEBSOCKET_MQTT(...) os_printf( __VA_ARGS__ )\n\n#ifndef DEBUG_WEBSOCKET_MQTT\n#define DEBUG_WEBSOCKET_MQTT(...)\n#define NODEBUG_WEBSOCKET_MQTT\n#endif\n\nclass AWSWebSocketClient : public Client, private WebSocketsClient {\npublic:\n\n  //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\t\n  AWSWebSocketClient (unsigned int bufferSize = 1000, unsigned long connectionTimeout = 50000);\n  ~AWSWebSocketClient();\n  \n  virtual int connect(IPAddress ip, uint16_t port) override;\n  virtual int connect(const char *host, uint16_t port) override;\n  virtual int connect(const String& host, uint16_t port);\n\n  void putMessage (byte* buffer, int length);\n  size_t write(uint8_t b);\n  size_t write(const uint8_t *buf, size_t size);\n  int available();\n  int read();\n  int read(uint8_t *buf, size_t size);\n\n  int peek();\n  bool flush(unsigned int maxWaitMs);\n  bool stop(unsigned int maxWaitMs);\n  virtual void flush() override { (void)flush(0); }\n  virtual void stop() override { (void)stop(0); }\n  uint8_t connected() ;\n  operator bool();\n\n  bool getUseSSL ();\n  \n  AWSWebSocketClient& setUseSSL (bool value);\n  AWSWebSocketClient& setAWSRegion(const char * awsRegion);\n  AWSWebSocketClient& setAWSDomain(const char * awsDomain);  \n  AWSWebSocketClient& setAWSSecretKey(const char * awsSecKey);\n  AWSWebSocketClient& setAWSKeyID(const char * awsKeyID);  \n  AWSWebSocketClient& setPath(const char * path);\n  AWSWebSocketClient& setAWSToken(const char * awsToken);\n  AWSWebSocketClient& setFingerprint(const char * fingerprint);\n  AWSWebSocketClient& setCA(const char * ca);\n  AWSWebSocketClient& setUseAmazonTimestamp(bool useAmazonTimestamp);\n      \n  protected:\n  //generate AWS signed path\n  char* generateAWSPath (uint16_t port);\n  \n  //convert the month info\n  String getMonth(String sM);\n  //get current time (UTC) from aws service (used to sign)\n  String getCurrentTimeAmazon(void);\n\n  String getCurrentTimeNTP(void);\n\n  String ntpFixNumber (int number);\n  \n  //static instance of aws websocket client\n  static AWSWebSocketClient* instance;\n  //keep the connection state\n  bool _connected;  \n  //websocket callback\n  static void webSocketEvent(WStype_t type, uint8_t * payload, size_t length);\n  \n  private:\n  \n  //enable ssl... if your using mqtt over websockets at AWS IoT service, it must be enabled\n  bool useSSL;\n\n  //connection timeout \n  unsigned long _connectionTimeout;\n\n  //useAmazonTimestamp\n  bool _useAmazonTimestamp;\n\n  char* path;\n  /* Name of region, eg. \"us-east-1\" in \"kinesis.us-east-1.amazonaws.com\". */\n  char* awsRegion;\n  /* Domain, optional, eg. \"A2MBBEONHC9LUG.iot.us-east-1.amazonaws.com\". */\n  char* awsDomain;\n  /* The user's AWS Secret Key for accessing the AWS Resource. */\n  char* awsSecKey;\n  /* The user's AWS Access Key ID for accessing the AWS Resource. */\n  char* awsKeyID;\n  /* The user's AWS Security Token for temporary credentials (just use with AWS STS). */\n  char* awsToken;\n  /* root certificate */\n  const char* ca;\n  \n  unsigned long lastTimeUpdate;\n  //circular buffer to keep incoming messages from websocket\n  CircularByteBuffer bb;\n  \n  //connection to get current time\n  WiFiClient timeClient;\n};\n\n#endif\n"
  },
  {
    "path": "CircularByteBuffer.h",
    "content": "#ifndef __CIRCULARBYTEBUFFER_H_\n#define __CIRCULARBYTEBUFFER_H_\n\n//#define DEBUG_CBB(...) os_printf( __VA_ARGS__ )\n\n#ifndef DEBUG_CBB\n#define DEBUG_CBB(...)\n#define NODEBUG_CBB\n#endif\n\nclass CircularByteBuffer {\npublic:\n\n\tCircularByteBuffer () {\n\t\tdata = NULL;\n\t\tsize = 0;\n\t\tcapacity = 0;\n\t}\n\t~CircularByteBuffer(){\n\t\tif (data!=NULL)\n\t\t\tfree (data);\n\t}\n\t\n\tvoid clear ()\n\t{\n\t\tmemset(data,0,capacity);\n\t\tsize = 0;\n\t\tbegin = 0;\n\t\tend = 0;\n\t}\n\t\n\tvoid deallocate () {\n\t\tif (data!=NULL) {\n\t\t\tfree (data);\n\t\t\tdata = NULL;\n\t\t}\n\t}\n\n\tvoid init (long capacity) {\n\t\tif (data!=NULL)\n\t\t\tfree (data);\n\t\tdata = (byte*) malloc (capacity);\n\t\tsize = 0;\n\t\tbegin = 0;\n\t\tend = 0;\n\t\tthis->capacity = capacity;\n\t}\n\n\tlong getSize () {\n\t\treturn size;\n\t}\n\n\tbyte peek () {\n\t\treturn data[begin];\n\t}\n\tvoid push (byte b) {\n\t\tif (size+1 == capacity) {\n\t\t\tDEBUG_CBB (\"buffer full\");\n\t\t\treturn;\n\t\t}\n\t\tdata[end] = b;\n\t\tend = (end+1) % capacity;\n\t\tsize += 1;\n\n\t}\n\n\tbyte pop () {\n\t\tif (size == 0){\n\t\t\tDEBUG_CBB (\"buffer empty\");\n\t\t\treturn 0;\n\t\t}\n\t\tbyte ret = data[begin];\n\t\tbegin = (begin+1) % capacity;\n\t\tsize -= 1;\n\t\treturn ret;\n\n\t}\n\n\tvoid push (byte* b, long len){\n\t\tif (size+len >= capacity) {\n\t\t\tDEBUG_CBB (\"buffer full\");\n\t\t\treturn;\n\t\t}\n\t\tif ( (end + len)  <= capacity ) {\n\t\t\tmemcpy ((void*)&data[end],b,len);\n\t\t\tend += len;\n\t\t} else {\n\t\t\tlong endSide = capacity - end;\n\t\t\tmemcpy ((void*)&data[end],b,endSide);\n\t\t\tend = 0;\n\t\t\tmemcpy ((void*)&data[end],b+endSide,len-endSide);\n\t\t\tend += len-endSide;\n\t\t}\n\t\tsize += len;\n\n\t}\n\n\tbyte* pop (byte* b, long len){\n\t\tif ( (size - len) < 0 ) {\n\t\t\tDEBUG_CBB (\"buffer empty\");\n\t\t\treturn NULL;\n\t\t}\n\t\tif ( (begin + len)  <= capacity ) {\n\t\t\tmemcpy (b,(void*)&data[begin],len);\n\t\t\tbegin += len;\n\t\t} else {\n\t\t\tlong endSide = capacity - begin;\n\t\t\tmemcpy (b,(void*)&data[begin],endSide);\n\t\t\tbegin = 0;\n\t\t\tmemcpy (b+endSide,(void*)&data[begin],len-endSide);\n\t\t\tbegin += len-endSide;\n\t\t}\n\t\tsize -= len;\n\t}\n\nprivate:\n\tbyte* data;\n\tlong capacity;\n\tlong size;\n\tlong begin;\n\tlong end;\n};\n\n\n\n#endif\n"
  },
  {
    "path": "LICENSE",
    "content": "                   GNU LESSER GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n\n  This version of the GNU Lesser General Public License incorporates\nthe terms and conditions of version 3 of the GNU General Public\nLicense, supplemented by the additional permissions listed below.\n\n  0. Additional Definitions.\n\n  As used herein, \"this License\" refers to version 3 of the GNU Lesser\nGeneral Public License, and the \"GNU GPL\" refers to version 3 of the GNU\nGeneral Public License.\n\n  \"The Library\" refers to a covered work governed by this License,\nother than an Application or a Combined Work as defined below.\n\n  An \"Application\" is any work that makes use of an interface provided\nby the Library, but which is not otherwise based on the Library.\nDefining a subclass of a class defined by the Library is deemed a mode\nof using an interface provided by the Library.\n\n  A \"Combined Work\" is a work produced by combining or linking an\nApplication with the Library.  The particular version of the Library\nwith which the Combined Work was made is also called the \"Linked\nVersion\".\n\n  The \"Minimal Corresponding Source\" for a Combined Work means the\nCorresponding Source for the Combined Work, excluding any source code\nfor portions of the Combined Work that, considered in isolation, are\nbased on the Application, and not on the Linked Version.\n\n  The \"Corresponding Application Code\" for a Combined Work means the\nobject code and/or source code for the Application, including any data\nand utility programs needed for reproducing the Combined Work from the\nApplication, but excluding the System Libraries of the Combined Work.\n\n  1. Exception to Section 3 of the GNU GPL.\n\n  You may convey a covered work under sections 3 and 4 of this License\nwithout being bound by section 3 of the GNU GPL.\n\n  2. Conveying Modified Versions.\n\n  If you modify a copy of the Library, and, in your modifications, a\nfacility refers to a function or data to be supplied by an Application\nthat uses the facility (other than as an argument passed when the\nfacility is invoked), then you may convey a copy of the modified\nversion:\n\n   a) under this License, provided that you make a good faith effort to\n   ensure that, in the event an Application does not supply the\n   function or data, the facility still operates, and performs\n   whatever part of its purpose remains meaningful, or\n\n   b) under the GNU GPL, with none of the additional permissions of\n   this License applicable to that copy.\n\n  3. Object Code Incorporating Material from Library Header Files.\n\n  The object code form of an Application may incorporate material from\na header file that is part of the Library.  You may convey such object\ncode under terms of your choice, provided that, if the incorporated\nmaterial is not limited to numerical parameters, data structure\nlayouts and accessors, or small macros, inline functions and templates\n(ten or fewer lines in length), you do both of the following:\n\n   a) Give prominent notice with each copy of the object code that the\n   Library is used in it and that the Library and its use are\n   covered by this License.\n\n   b) Accompany the object code with a copy of the GNU GPL and this license\n   document.\n\n  4. Combined Works.\n\n  You may convey a Combined Work under terms of your choice that,\ntaken together, effectively do not restrict modification of the\nportions of the Library contained in the Combined Work and reverse\nengineering for debugging such modifications, if you also do each of\nthe following:\n\n   a) Give prominent notice with each copy of the Combined Work that\n   the Library is used in it and that the Library and its use are\n   covered by this License.\n\n   b) Accompany the Combined Work with a copy of the GNU GPL and this license\n   document.\n\n   c) For a Combined Work that displays copyright notices during\n   execution, include the copyright notice for the Library among\n   these notices, as well as a reference directing the user to the\n   copies of the GNU GPL and this license document.\n\n   d) Do one of the following:\n\n       0) Convey the Minimal Corresponding Source under the terms of this\n       License, and the Corresponding Application Code in a form\n       suitable for, and under terms that permit, the user to\n       recombine or relink the Application with a modified version of\n       the Linked Version to produce a modified Combined Work, in the\n       manner specified by section 6 of the GNU GPL for conveying\n       Corresponding Source.\n\n       1) Use a suitable shared library mechanism for linking with the\n       Library.  A suitable mechanism is one that (a) uses at run time\n       a copy of the Library already present on the user's computer\n       system, and (b) will operate properly with a modified version\n       of the Library that is interface-compatible with the Linked\n       Version.\n\n   e) Provide Installation Information, but only if you would otherwise\n   be required to provide such information under section 6 of the\n   GNU GPL, and only to the extent that such information is\n   necessary to install and execute a modified version of the\n   Combined Work produced by recombining or relinking the\n   Application with a modified version of the Linked Version. (If\n   you use option 4d0, the Installation Information must accompany\n   the Minimal Corresponding Source and Corresponding Application\n   Code. If you use option 4d1, you must provide the Installation\n   Information in the manner specified by section 6 of the GNU GPL\n   for conveying Corresponding Source.)\n\n  5. Combined Libraries.\n\n  You may place library facilities that are a work based on the\nLibrary side by side in a single library together with other library\nfacilities that are not Applications and are not covered by this\nLicense, and convey such a combined library under terms of your\nchoice, if you do both of the following:\n\n   a) Accompany the combined library with a copy of the same work based\n   on the Library, uncombined with any other library facilities,\n   conveyed under the terms of this License.\n\n   b) Give prominent notice with the combined library that part of it\n   is a work based on the Library, and explaining where to find the\n   accompanying uncombined form of the same work.\n\n  6. Revised Versions of the GNU Lesser General Public License.\n\n  The Free Software Foundation may publish revised and/or new versions\nof the GNU Lesser General Public License from time to time. Such new\nversions will be similar in spirit to the present version, but may\ndiffer in detail to address new problems or concerns.\n\n  Each version is given a distinguishing version number. If the\nLibrary as you received it specifies that a certain numbered version\nof the GNU Lesser General Public License \"or any later version\"\napplies to it, you have the option of following the terms and\nconditions either of that published version or of any later version\npublished by the Free Software Foundation. If the Library as you\nreceived it does not specify a version number of the GNU Lesser\nGeneral Public License, you may choose any version of the GNU Lesser\nGeneral Public License ever published by the Free Software Foundation.\n\n  If the Library as you received it specifies that a proxy can decide\nwhether future versions of the GNU Lesser General Public License shall\napply, that proxy's public statement of acceptance of any version is\npermanent authorization for you to choose that version for the\nLibrary.\n"
  },
  {
    "path": "README.md",
    "content": "# aws-mqtt-websockets\nImplementation of a middleware to use AWS MQTT service through websockets. Aiming the esp8266 platform\n\n## ChangeLog\n* **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\n* 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\n* 1.1.0 - can use AWS STS temporary credentials - change some dynamic to static memory allocation to avoid memory fragmentation\n* 1.0.1 - works with arduinoWebSockets v.2.0.5 and arduino/esp sdk 2.3.0\n* 1.0.alpha - stable - works with arduinoWebSockets v.2.0.2 and arduino/esp sdk 2.1.0\n* 0.3 - own impl of circular buffer\n* 0.2 - auto reconnection\n* 0.1 - has known limitation and it was not extensively tested\n\n## Motivation\n\nAs 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)\n\nThis way we can change the state of your esp8266 devices in realtime, without using the AWS Restful API and busy-waiting inefficient approach.\n\n* 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\n\n## Donate\n\nif you fell like thank me, you can buy me a coffe (or a beer) https://www.buymeacoffee.com/odelot cheers!\n\n## Dependencies\n\n| Library                   | Link                                                            | Use                 |\n|---------------------------|-----------------------------------------------------------------|---------------------|\n|aws-sdk-arduino            |https://github.com/odelot/aws-sdk-arduino                        |aws signing functions|\n|arduinoWebSockets          |https://github.com/Links2004/arduinoWebSockets                   |websocket comm impl  |\n\n**Works with these MQTT clients** - Use one or another - see examples\n\n| Library                       | Link                                                            | Use                 |\n|-------------------------------|-----------------------------------------------------------------|---------------------|\n|PubSubClient (recommended)     |https://github.com/knolleary/pubsubclient                        |mqtt comm impl       |\n|Paho MQTT for Arduino          |https://projects.eclipse.org/projects/technology.paho/downloads  |mqtt comm impl       |\n\n## Installation\n\n1. Configure your arduino ide to compile and upload programs to ESP8266 (Arduino core for ESP8266 - details https://github.com/esp8266/Arduino )\\*\\*\n2. Install all the dependencies as Arduino Libraries\n3. Install aws-mqtt-websockets as Arduino Library as well\n4. Configure the example file with your AWS credencials and endpoints (**remember to grant iot permissions for your user**)\n5. Compile, upload and run!\n\n\\** The library was tested with 2.7.3 version of Arduino core for ESP8266\n\n## Usage\n\nIt 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:\n* ssid and password to connect to wifi\n* domain/endpoint for your aws iot service\n* region of your aws iot service\n* aws user key \\*\\*\n* aws user secret key\n\n \\*\\* 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\n\n ```\n //AWS IOT config, change these:\nchar wifi_ssid[]       = \"your-ssid\";\nchar wifi_password[]   = \"your-password\";\nchar aws_endpoint[]    = \"your-endpoint.iot.eu-west-1.amazonaws.com\";\nchar aws_key[]         = \"your-iam-key\";\nchar aws_secret[]      = \"your-iam-secret-key\";\nchar aws_region[]      = \"eu-west-1\";\nconst char* aws_topic  = \"$aws/things/your-device/shadow/update\";\nint port = 443;\n\n//MQTT config\nconst int maxMQTTpackageSize = 128;\nconst int maxMQTTMessageHandlers = 1;\n ```\n\n ## Grant IoT Permission in AWS Console\n\n* Go to https://console.aws.amazon.com/\n* Then click IAM\n* Then click policy. find your policy or create a new policy\n* set service to IOT\n* set action to iot:*\n* set resouce to all resources\n\n ## AWS STS Temporary Credential\n\n 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).\n\n Using STS you will get a AWS key, AWS secret and AWS token. To inform the AWS token, use the following method\n\n ```\n //it is just an example. As the credential last up to 36 hours, you will need to get temporary credential every 36 hours\n //you won't use it hard coded\n char token[] = 'FQoDYXdzEHgaDN7ZQSxqszH+LgBTXCKsAeU5dsW/g3BK01wyYoBk0vnCfz+D19w2kslSC5drDXyN9Nxx14WcgrOOWNxHsLRDPkcrYhw6DIkW1Nvv1mKu3i86riq19qhBose7v1XngRLBQwgfU/HnlIzJegNEEGgeMAkX0ErF77WfV2pxCzF6ZMRv7kn+a6yE2LURLg/M8eq3lYoyQcJFq55JfVPVUIpx/avEsjgCR/MvlHXlhtJqviClB3mRlvwBcz4vpq4ogpKnzAU=';\n awsWSclient.setAWSToken (token);\n ```\n"
  },
  {
    "path": "examples/aws-DHT-publish-example/DHT-publish.ino",
    "content": "/**\n* Example working with library v1.2\n*\n*/\n\n#include <Arduino.h>\n#include <Stream.h>\n#include <ESP8266WiFi.h>\n#include <ESP8266WiFiMulti.h>\n\n// DHT22 - https://learn.adafruit.com/dht, https://github.com/adafruit/DHT-sensor-library\n#include \"DHT.h\"\n\n//AWS\n#include \"sha256.h\"\n#include \"Utils.h\"\n\n//WEBSockets\n#include <Hash.h>\n#include <WebSocketsClient.h>\n\n//MQTT PAHO\n#include <SPI.h>\n#include <IPStack.h>\n#include <Countdown.h>\n#include <MQTTClient.h>\n\n//AWS MQTT Websocket\n#include \"Client.h\"\n#include \"AWSWebSocketClient.h\"\n#include \"CircularByteBuffer.h\"\n\n//  --------- Config ---------- //\n//AWS IOT config, change these:\nchar wifi_ssid[]       = \"your-ssid\";\nchar wifi_password[]   = \"your-password\";\nchar aws_endpoint[]    = \"your-endpoint.iot.eu-west-1.amazonaws.com\";\nchar aws_key[]         = \"your-iam-key\";\nchar aws_secret[]      = \"your-iam-secret-key\";\nchar aws_region[]      = \"eu-west-1\";\nconst char* aws_topic  = \"$aws/things/your-device/shadow/update\";\nint port = 443;\n\n// If stuff isn't working right, watch the console:\n#define DEBUG_PRINT 1\n\n#define DHTPIN 5\n#define DHTTYPE DHT22 //Set for 11, 21, or 22\n\n//MQTT config\nconst int maxMQTTpackageSize = 512;\nconst int maxMQTTMessageHandlers = 1;\n// ---------- /Config ----------//\n\nDHT dht(DHTPIN, DHTTYPE);\nESP8266WiFiMulti WiFiMulti;\n\nAWSWebSocketClient awsWSclient(1000);\n\nIPStack ipstack(awsWSclient);\nMQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> *client = NULL;\n\n//# of connections\nlong connection = 0;\n\n//generate random mqtt clientID\nchar* generateClientID () {\n  char* cID = new char[23]();\n  for (int i=0; i<22; i+=1)\n    cID[i]=(char)random(1, 256);\n  return cID;\n}\n\n//count messages arrived\nint arrivedcount = 0;\n\n//callback to handle mqtt messages\nvoid messageArrived(MQTT::MessageData& md)\n{\n  MQTT::Message &message = md.message;\n\n  if (DEBUG_PRINT) {\n    Serial.print(\"Message \");\n    Serial.print(++arrivedcount);\n    Serial.print(\" arrived: qos \");\n    Serial.print(message.qos);\n    Serial.print(\", retained \");\n    Serial.print(message.retained);\n    Serial.print(\", dup \");\n    Serial.print(message.dup);\n    Serial.print(\", packetid \");\n    Serial.println(message.id);\n    Serial.print(\"Payload \");\n    char* msg = new char[message.payloadlen+1]();\n    memcpy (msg,message.payload,message.payloadlen);\n    Serial.println(msg);\n    delete msg;\n  }\n}\n\n//connects to websocket layer and mqtt layer\nbool connect () {\n\n    if (client == NULL) {\n      client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);\n    } else {\n\n      if (client->isConnected ()) {    \n        client->disconnect ();\n      }  \n      delete client;\n      client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);\n    }\n\n\n    //delay is not necessary... it just help us to get a \"trustful\" heap space value\n    delay (1000);\n    if (DEBUG_PRINT) {\n      Serial.print (millis ());\n      Serial.print (\" - conn: \");\n      Serial.print (++connection);\n      Serial.print (\" - (\");\n      Serial.print (ESP.getFreeHeap ());\n      Serial.println (\")\");\n    }\n\n   int rc = ipstack.connect(aws_endpoint, port);\n    if (rc != 1)\n    {\n      if (DEBUG_PRINT) {\n        Serial.println(\"error connection to the websocket server\");\n      }\n      return false;\n    } else {\n      if (DEBUG_PRINT) {\n        Serial.println(\"websocket layer connected\");\n      }\n    }\n    \n    if (DEBUG_PRINT) {\n      Serial.println(\"MQTT connecting\");\n    }\n    \n    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;\n    data.MQTTVersion = 3;\n    char* clientID = generateClientID ();\n    data.clientID.cstring = clientID;\n    rc = client->connect(data);\n    delete[] clientID;\n    if (rc != 0)\n    {\n      if (DEBUG_PRINT) {\n        Serial.print(\"error connection to MQTT server\");\n        Serial.println(rc);\n        return false;\n      }\n    }\n    if (DEBUG_PRINT) {\n      Serial.println(\"MQTT connected\");\n    }\n    return true;\n}\n\n//subscribe to a mqtt topic\nvoid subscribe () {\n   //subscrip to a topic\n    int rc = client->subscribe(aws_topic, MQTT::QOS0, messageArrived);\n    if (rc != 0) {\n      if (DEBUG_PRINT) {\n        Serial.print(\"rc from MQTT subscribe is \");\n        Serial.println(rc);\n      }\n      return;\n    }\n    if (DEBUG_PRINT) {\n      Serial.println(\"MQTT subscribed\");\n    }\n}\n\nvoid setup() {\n    Serial.begin (115200);   \n    WiFiMulti.addAP(wifi_ssid, wifi_password);\n    \n    while(WiFiMulti.run() != WL_CONNECTED) {\n        delay(100);\n        if (DEBUG_PRINT) {\n          Serial.print (\". \");\n        }\n    }\n    if (DEBUG_PRINT) {\n      Serial.println (\"\\nconnected to network \" + String(wifi_ssid) + \"\\n\");\n    }\n\n    //fill AWS parameters    \n    awsWSclient.setAWSRegion(aws_region);\n    awsWSclient.setAWSDomain(aws_endpoint);\n    awsWSclient.setAWSKeyID(aws_key);\n    awsWSclient.setAWSSecretKey(aws_secret);\n    awsWSclient.setUseSSL(true);\n\n    dht.begin();\n}\n\nvoid loop() {\n  // Reading temperature or humidity takes about 250 milliseconds!\n  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)\n  delay(10000);\n  String h = String(dht.readHumidity());    // Read temperature as Fahrenheit (isFahrenheit = true)\n  String f = String(dht.readTemperature(true));\n  \n  if (isnan(dht.readHumidity()) || isnan(dht.readTemperature(true))) {\n    Serial.println(\"Failed to read from DHT sensor!\");\n    return;\n  } else {\n    if (DEBUG_PRINT) {\n      Serial.print(\"Humidity: \");\n      Serial.print(h);\n      Serial.print(\" %\\t\");\n      Serial.print(\"Temperature: \");\n      Serial.print(f);\n      Serial.print(\" *F\\t\\n\");\n    }\n  };\n\n  String values = \"{\\\"state\\\":{\\\"reported\\\":{\\\"temp\\\": \" + f + \",\\\"humidity\\\": \" + h + \"}}}\";\n  // http://stackoverflow.com/questions/31614364/arduino-joining-string-and-char\n  const char *publish_message = values.c_str();\n\n  //keep the mqtt up and running\n  if (awsWSclient.connected ()) {    \n      client->yield();\n      \n      subscribe (); \n      //publish \n      MQTT::Message message;\n      char buf[1000];\n      strcpy(buf, publish_message);\n      message.qos = MQTT::QOS0;\n      message.retained = false;\n      message.dup = false;\n      message.payload = (void*)buf;\n      message.payloadlen = strlen(buf)+1;\n      int rc = client->publish(aws_topic, message);  \n  } else {\n    //handle reconnection\n    connect ();\n  }\n}\n"
  },
  {
    "path": "examples/aws-mqtt-websocket-example-paho/aws-mqtt-websocket-example-paho.ino",
    "content": "/**\n* Example working with library v1.2\n*\n*/\n\n#include <Arduino.h>\n#include <Stream.h>\n\n#include <ESP8266WiFi.h>\n#include <ESP8266WiFiMulti.h>\n\n//AWS\n#include \"sha256.h\"\n#include \"Utils.h\"\n\n\n//WEBSockets\n#include <Hash.h>\n#include <WebSocketsClient.h>\n\n//MQTT PAHO\n#include <SPI.h>\n#include <IPStack.h>\n#include <Countdown.h>\n#include <MQTTClient.h>\n\n\n\n//AWS MQTT Websocket\n#include \"Client.h\"\n#include \"AWSWebSocketClient.h\"\n#include \"CircularByteBuffer.h\"\n\nextern \"C\" {\n  #include \"user_interface.h\"\n}\n\n//AWS IOT config, change these:\nchar wifi_ssid[]       = \"your-ssid\";\nchar wifi_password[]   = \"your-password\";\nchar aws_endpoint[]    = \"your-endpoint.iot.eu-west-1.amazonaws.com\";\nchar aws_key[]         = \"your-iam-key\";\nchar aws_secret[]      = \"your-iam-secret-key\";\nchar aws_region[]      = \"eu-west-1\";\nconst char* aws_topic  = \"$aws/things/your-device/shadow/update\";\nint port = 443;\n\n//MQTT config\nconst int maxMQTTpackageSize = 512;\nconst int maxMQTTMessageHandlers = 1;\n\nESP8266WiFiMulti WiFiMulti;\n\nAWSWebSocketClient awsWSclient(1000);\n\nIPStack ipstack(awsWSclient);\nMQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> client(ipstack);\n\n//# of connections\nlong connection = 0;\n\n//generate random mqtt clientID\nchar* generateClientID () {\n  char* cID = new char[23]();\n  for (int i=0; i<22; i+=1)\n    cID[i]=(char)random(1, 256);\n  return cID;\n}\n\n//count messages arrived\nint arrivedcount = 0;\n\n//callback to handle mqtt messages\nvoid messageArrived(MQTT::MessageData& md)\n{\n  MQTT::Message &message = md.message;\n\n  Serial.print(\"Message \");\n  Serial.print(++arrivedcount);\n  Serial.print(\" arrived: qos \");\n  Serial.print(message.qos);\n  Serial.print(\", retained \");\n  Serial.print(message.retained);\n  Serial.print(\", dup \");\n  Serial.print(message.dup);\n  Serial.print(\", packetid \");\n  Serial.println(message.id);\n  Serial.print(\"Payload \");\n  char* msg = new char[message.payloadlen+1]();\n  memcpy (msg,message.payload,message.payloadlen);\n  Serial.println(msg);\n  delete msg;\n}\n\n//connects to websocket layer and mqtt layer\nbool connect () {\n\n\n\n    if (client.isConnected ()) {    \n        client.disconnect ();\n    }  \n    //delay is not necessary... it just help us to get a \"trustful\" heap space value\n    delay (1000);\n    Serial.print (millis ());\n    Serial.print (\" - conn: \");\n    Serial.print (++connection);\n    Serial.print (\" - (\");\n    Serial.print (ESP.getFreeHeap ());\n    Serial.println (\")\");\n\n\n\n\n   int rc = ipstack.connect(aws_endpoint, port);\n    if (rc != 1)\n    {\n      Serial.println(\"error connection to the websocket server\");\n      return false;\n    } else {\n      Serial.println(\"websocket layer connected\");\n    }\n\n\n    Serial.println(\"MQTT connecting\");\n    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;\n    data.MQTTVersion = 4;\n    char* clientID = generateClientID ();\n    data.clientID.cstring = clientID;\n    rc = client.connect(data);\n    delete[] clientID;\n    if (rc != 0)\n    {\n      Serial.print(\"error connection to MQTT server\");\n      Serial.println(rc);\n      return false;\n    }\n    Serial.println(\"MQTT connected\");\n    return true;\n}\n\n//subscribe to a mqtt topic\nvoid subscribe () {\n   //subscript to a topic\n    int rc = client.subscribe(aws_topic, MQTT::QOS0, messageArrived);\n    if (rc != 0) {\n      Serial.print(\"rc from MQTT subscribe is \");\n      Serial.println(rc);\n      return;\n    }\n    Serial.println(\"MQTT subscribed\");\n}\n\n//send a message to a mqtt topic\nvoid sendmessage () {\n    //send a message\n    MQTT::Message message;\n    char buf[100];\n    strcpy(buf, \"{\\\"state\\\":{\\\"reported\\\":{\\\"on\\\": false}, \\\"desired\\\":{\\\"on\\\": false}}}\");\n    message.qos = MQTT::QOS0;\n    message.retained = false;\n    message.dup = false;\n    message.payload = (void*)buf;\n    message.payloadlen = strlen(buf)+1;\n    int rc = client.publish(aws_topic, message); \n}\n\n\nvoid setup() {\n    wifi_set_sleep_type(NONE_SLEEP_T);\n    Serial.begin (115200);\n    delay (2000);\n    Serial.setDebugOutput(1);\n\n    //fill with ssid and wifi password\n    WiFiMulti.addAP(wifi_ssid, wifi_password);\n    Serial.println (\"connecting to wifi\");\n    while(WiFiMulti.run() != WL_CONNECTED) {\n        delay(100);\n        Serial.print (\".\");\n    }\n    Serial.println (\"\\nconnected\");\n\n    //fill AWS parameters    \n    awsWSclient.setAWSRegion(aws_region);\n    awsWSclient.setAWSDomain(aws_endpoint);\n    awsWSclient.setAWSKeyID(aws_key);\n    awsWSclient.setAWSSecretKey(aws_secret);\n    awsWSclient.setUseSSL(true);\n\n    if (connect ()){\n      subscribe ();\n      sendmessage ();\n    }\n\n}\n\nvoid loop() {\n  //keep the mqtt up and running\n  if (awsWSclient.connected ()) {    \n      client.yield(50);\n  } else {\n    //handle reconnection\n    if (connect ()){\n      subscribe ();      \n    }\n  }\n\n}\n"
  },
  {
    "path": "examples/aws-mqtt-websocket-example-pubsubclient/aws-mqtt-websocket-example-pubsubclient.ino",
    "content": "/**\n* Example working with library v1.3\n*\n*/\n#include <Arduino.h>\n#include <Stream.h>\n#include <time.h>\n#include <ESP8266WiFi.h>\n#include <ESP8266WiFiMulti.h>\n\n//AWS\n#include \"sha256.h\"\n#include \"Utils.h\"\n\n\n//WEBSockets\n#include <Hash.h>\n#include <WebSocketsClient.h>\n\n//MQTT PUBSUBCLIENT LIB\n#include <PubSubClient.h>\n\n//AWS MQTT Websocket\n#include \"Client.h\"\n#include \"AWSWebSocketClient.h\"\n#include \"CircularByteBuffer.h\"\n\nextern \"C\" {\n  #include \"user_interface.h\"\n}\n\n//AWS IOT config, change these:\nchar wifi_ssid[]       = \"your-ssid\";\nchar wifi_password[]   = \"your-password\";\nchar aws_endpoint[]    = \"your-endpoint.iot.eu-west-1.amazonaws.com\";\nchar aws_key[]         = \"your-iam-key\";\nchar aws_secret[]      = \"your-iam-secret-key\";\nchar aws_region[]      = \"eu-west-1\";\nconst char* aws_topic  = \"$aws/things/your-device/shadow/update\";\nint port = 443;\n\n/* uncomment the following line to use an alternate root CA if the first one does not work */\n// #define ALTERNATE_ROOT_CA\n\n#ifndef ALTERNATE_ROOT_CA\n\n// AWS root certificate - expires 2037\nconst char ca[] PROGMEM = R\"EOF(\n-----BEGIN CERTIFICATE-----\nMIIEkjCCA3qgAwIBAgITBn+USionzfP6wq4rAfkI7rnExjANBgkqhkiG9w0BAQsF\nADCBmDELMAkGA1UEBhMCVVMxEDAOBgNV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Z\n4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N\nhnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq\n-----END CERTIFICATE-----\n)EOF\";\n\n#endif\n\n\n\n//MQTT config\nconst int maxMQTTpackageSize = 512;\nconst int maxMQTTMessageHandlers = 1;\n\nESP8266WiFiMulti WiFiMulti;\n\nAWSWebSocketClient awsWSclient(1000);\n\nPubSubClient client(awsWSclient);\n\n//# of connections\nlong connection = 0;\n\n//generate random mqtt clientID\nchar* generateClientID () {\n  char* cID = new char[23]();\n  for (int i=0; i<22; i+=1)\n    cID[i]=(char)random(1, 256);\n  return cID;\n}\n\n//count messages arrived\nint arrivedcount = 0;\n\n//callback to handle mqtt messages\nvoid callback(char* topic, byte* payload, unsigned int length) {\n  Serial.print(\"Message arrived [\");\n  Serial.print(topic);\n  Serial.print(\"] \");\n  for (int i = 0; i < length; i++) {\n    Serial.print((char)payload[i]);\n  }\n  Serial.println();\n}\n\n//connects to websocket layer and mqtt layer\nbool connect () {\n    if (client.connected()) {\n        client.disconnect ();\n    }\n    //delay is not necessary... it just help us to get a \"trustful\" heap space value\n    delay (1000);\n    Serial.print (millis ());\n    Serial.print (\" - conn: \");\n    Serial.print (++connection);\n    Serial.print (\" - (\");\n    Serial.print (ESP.getFreeHeap ());\n    Serial.println (\")\");\n\n\n    //creating random client id\n    char* clientID = generateClientID ();\n\n    client.setServer(aws_endpoint, port);\n    if (client.connect(clientID)) {\n      Serial.println(\"connected\");\n      return true;\n    } else {\n      Serial.print(\"failed, rc=\");\n      Serial.print(client.state());\n      return false;\n    }\n\n}\n\n//subscribe to a mqtt topic\nvoid subscribe () {\n    client.setCallback(callback);\n    client.subscribe(aws_topic);\n   //subscript to a topic\n    Serial.println(\"MQTT subscribed\");\n}\n\n//send a message to a mqtt topic\nvoid sendmessage () {\n    //send a message\n    char buf[100];\n    strcpy(buf, \"{\\\"state\\\":{\\\"reported\\\":{\\\"on\\\": false}, \\\"desired\\\":{\\\"on\\\": false}}}\");\n    int rc = client.publish(aws_topic, buf);\n}\n\n\nvoid setClock() {\n  configTime(3 * 3600, 0, \"pool.ntp.org\", \"time.nist.gov\");\n\n  Serial.print(\"Waiting for NTP time sync: \");\n  time_t now = time(nullptr);\n  while (now < 8 * 3600 * 2) {\n    delay(500);\n    Serial.print(\".\");\n    now = time(nullptr);\n  }\n  Serial.println(\"\");\n  struct tm timeinfo;\n  gmtime_r(&now, &timeinfo);\n  Serial.print(\"Current time: \");\n  Serial.print(asctime(&timeinfo));\n}\n\nvoid setup() {\n    wifi_set_sleep_type(NONE_SLEEP_T);\n    Serial.begin (115200);\n    delay (2000);\n    Serial.setDebugOutput(1);\n\n    //fill with ssid and wifi password\n    WiFiMulti.addAP(wifi_ssid, wifi_password);\n    Serial.println (\"connecting to wifi\");\n    while(WiFiMulti.run() != WL_CONNECTED) {\n        delay(100);\n        Serial.print (\".\");\n    }\n    Serial.println (\"\\nconnected\");\n\n    setClock(); // Required for X.509 certificate  validation\n\n    //fill AWS parameters\n    awsWSclient.setAWSRegion(aws_region);\n    awsWSclient.setAWSDomain(aws_endpoint);\n    awsWSclient.setAWSKeyID(aws_key);\n    awsWSclient.setAWSSecretKey(aws_secret);\n    awsWSclient.setUseSSL(true);\n    awsWSclient.setCA(ca);\n    //as we had to configurate ntp time to validate the certificate, we can use it to validate aws connection as well\n    awsWSclient.setUseAmazonTimestamp(false);\n\n\n    if (connect ()){\n      subscribe ();\n      sendmessage ();\n    }\n\n}\n\nvoid loop() {\n  //keep the mqtt up and running\n  if (awsWSclient.connected ()) {\n      client.loop ();\n  } else {\n    //handle reconnection\n    if (connect ()){\n      subscribe ();\n    }\n  }\n\n}\n"
  }
]