1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// ================================================================================================
// C++ Code for Particle Photon to send sensor data (mimicked by "DummyData" in 0~30) to 
// AWS IoT and receive command messages from AWS IoT Core. AWS SNS will be triggered to send 
// a SMS to a phone if the data is greater than 25. Photon blinks a corresponding indicator 
// LED according to the received commands ('Turn Low', 'Turn Mid' or 'Turn High'). 
// This code uses MQTT-TLS library written by Hirotaka Niisato, the library
// version used here is 0.2.20. 
//
// Change the follows for your own use: Authentication info (Root CA certificate, 
// client certificate and private key), AWS IoT ReST API endpoint address, 
// client ID and MQTT topics. 
//
// Extremely important: MQTT connection (client.connect()) may not establish although
// client.enableTLS() succeeds. This is mainly becuase MQTT-TLS library is quite mem hungry, 
// the complied code eats a lot mem which causes Photon no enough memory to run TLS algorithm. 
// To solve this problem, you can use Particle CLI or Particle Workbench to manually 
// edit the MQTT-TLS library "config.h" file to reduce the buffer size and remove SHA1 
// and SHA512 algorithms (because AWS IoT only uses SHA256).
//
// Use Particle CLI: to create a project, copy library into the project, compile remotely, 
// then flash the downloaded binary code to Photon. See Particle CLI Reference for details.

// Author: Dr. X. Li (City tech Robotics Research Lab at CUNY, xhli@citytech.cuny.edu)
// V2.0, 05/09/2019

//This software is released under the MIT License.

//Permission is hereby granted, free of charge, to any person obtaining
//a copy of this software and associated documentation files (the
//"Software"), to deal in the Software without restriction, including
//without limitation the rights to use, copy, modify, merge, publish,
//distribute, sublicense, and/or sell copies of the Software, and to
//permit persons to whom the Software is furnished to do so, subject to
//the following conditions:

//The above copyright notice and this permission notice shall be
//included in all copies or substantial portions of the Software.

// ================================================================================================
#include "MQTT-TLS.h"
//#include "ArduinoJson.h"      //Library for parsing JSON object

// This #include statement was automatically added by the Particle IDE.
//#include <MQTT-TLS.h>

//SYSTEM_THREAD(DISABLED);

void callback(char* topic, byte* payload, unsigned int length);
void BlinkLed(int LedPin, int BlinkTimes, int BlinkPeriod);    //A func to blink LED
String FormMQTTPayload(int reading1, double reading2);         //A func to create JSON object

#define AMAZON_IOT_ROOT_CA_PEM                                          \
"-----BEGIN CERTIFICATE----- \r\n"                                      \
"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\r\n"  \
"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\r\n"  \
"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\r\n"  \
"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\r\n"  \
"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\r\n"  \
"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\r\n"  \
"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\r\n"  \
"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\r\n"  \
"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\r\n"  \
"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\r\n"  \
"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\r\n"  \
"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\r\n"  \
"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\r\n"  \
"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\r\n"  \
"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\r\n"  \
"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\r\n"  \
"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\r\n"  \
"rqXRfboQnoZsG4q5WTP468SQvvG5\r\n"  \
"-----END CERTIFICATE----- "
const char amazonIoTRootCaPem[] = AMAZON_IOT_ROOT_CA_PEM;

#define CELINT_KEY_CRT_PEM                                              \
"-----BEGIN CERTIFICATE----- \r\n"                                      \
" ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... .  \r\n"	\						\
"-----END CERTIFICATE----- "
const char clientKeyCrtPem[] = CELINT_KEY_CRT_PEM;

#define CELINT_KEY_PEM                                                  \
"-----BEGIN RSA PRIVATE KEY-----\r\n"                                   \
" ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... .  \r\n"	\						\
"-----END RSA PRIVATE KEY----- "
const char clientKeyPem[] = CELINT_KEY_PEM;

/**
 * if want to use IP address,
 * byte server[] = { XXX,XXX,XXX,XXX };
 * MQTT client(server, 1883, callback);
 * want to use domain name,
 * MQTT client("www.sample.com", 1883, callback);
 **/
//MQTT client("Your AWS IoT Thing ReST API Endpoint", 8883, callback); //set ReST API endpoint

//Set keep-alive timeout as 60sec. Default is 15sec. 
MQTT client("Your AWS IoT Thing ReST API Endpoint", 8883, 60, callback); //set ReST API endpoint 

//#define ONE_DAY_MILLIS (24 * 60 * 60 * 1000)
//unsigned long lastSync = millis();

int DummyData = 0;   //DummyData used here. Revise this for your own need. 
int LedIndicator_Publish = D7;   //set LED D7 as publishing indicator
int LedIndicator_CommLow = D6;   //set LED connected on D6 as indicator for command “turnlow”
int LedIndicator_CommMid = D5;   //set LED connected on D6 as indicator for command “turnmid”
int LedIndicator_CommHigh = D4;  //set LED connected on D6 as indicator for command “turnhigh”

void setup() 
{
//    if (millis() - lastSync > ONE_DAY_MILLIS) {
//        Particle.syncTime();
//        lastSync = millis();
//    }

  pinMode(LedIndicator_Publish, OUTPUT);
  pinMode(LedIndicator_CommLow, OUTPUT);
  pinMode(LedIndicator_CommMid, OUTPUT);
  pinMode(LedIndicator_CommHigh, OUTPUT);
  
  BlinkLed(LedIndicator_CommLow, 1, 300);
  BlinkLed(LedIndicator_CommMid, 1, 300);
  BlinkLed(LedIndicator_CommHigh, 1, 300);   


   // enable TLS: set Root CA pem, cient certificate, private key file.
   int retn = client.enableTls(amazonIoTRootCaPem, sizeof(amazonIoTRootCaPem),
                     clientKeyCrtPem, sizeof(clientKeyCrtPem),
                     clientKeyPem, sizeof(clientKeyPem));
   if (retn< 0)           //client.enableTls returns 0 if succeed
   {       
       Serial.printlnf("client.enableTls failed with code: %d", retn);
   }
   else  Serial.println("TLS enabled!");
   
    // connect to AWS IoT Core 
    Serial.println("Connect to AWS IoT Core ......");
    if ( client.connect("MyPhotonClientID") )    //client.connect() returns TRUE if succeed
    {
        Serial.println("Connection to AWS IoT Core established! Congratulations!");
    }
    else     Serial.println("client.connect failed");
    Serial.println();

    // verify connection, then publish an initial msg, and subscribe from AWS IoT Core
    if (client.isConnected()) 
    {
        Serial.println("MQTT Client (Photon) is connected.");
        
        client.publish("MyTopics/SensorDataDemo1", "Hi AWS IoT Core, this is from Photon");
        Serial.println("Photon's initial message to AWS:  Hi AWS IoT Core, this is from Photon");
        
        client.subscribe("MyTopics/AWSMsgDemo1");   // Topic of command messages 
    }
}

void loop() 
{
    DummyData ++;
    if(DummyData > 30)  DummyData = 0;      //Reset DummyData when it is >30
    String MQTTPayload=FormMQTTPayload(DummyData,0.0); //Create a JSON object including two fields
    
    if (client.isConnected()) {
        Serial.println("MQTT connection remains!");

        //Publish data in plain-string or JSON format to AWS 
        //client.publish("MyTopics/SensorDataDemo1",(const char *)DummyData); //publish a plain string
        //Serial.printlnf("Message sent to AWS: %d ", DummyData );            //display published number 
       
        client.publish("MyTopics/SensorDataDemo1", MQTTPayload ); //publish a JSON payload        
        Serial.print("Message sent to AWS: ");  //note: printlnf() not working here!
        Serial.println( MQTTPayload ); 
        
        client.loop();
        
        delay(5000);
    }
    delay(5000);   
}

//The func to form a JSON formatted payload
String FormMQTTPayload(int reading1, double reading2=0.0) 
{
  String retnstring = "{";
  retnstring += "\"Sensor1\":";
  retnstring += "\""+String(reading1)+"\",";
  retnstring += "\"Sensor2\":";
  retnstring += "\""+String(reading2)+"\",";
  //retnstring += "\"Sensor3\":";
  //retnstring += "\""+String(reading3)+"\","; 
  retnstring += "}";

  return retnstring;
}

// callback func to process/resp recieved commands sent from AWS IoT
void callback(char* topic, byte* payload, unsigned int length) 
{
   RGB.color(255,10,255);  //blink the RGB LED in pink color
   delay(300); 
   RGB.color(0,0,0);

   char p[length + 1];
   memcpy(p, payload, length);
   p[length] = NULL;
   String message(p);
    
   Serial.println("Received command from AWS is:");
   Serial.println(p);      //display received command
   Serial.println();

   // Respond to plain-string commands:
   if (message.equals("Turn Low"))
             BlinkLed(LedIndicator_CommLow, 1, 100);  //RGB.color(255, 0, 0);
   else if (message.equals("Turn Mid"))
             BlinkLed(LedIndicator_CommMid, 1, 100);  //RGB.color(0, 255, 0);
   else if (message.equals("Turn High"))
              BlinkLed(LedIndicator_CommHigh, 1, 100);  //RGB.color(0, 0, 255);
   else {
     // RGB.color(255,0,255); delay(1000); RGB.color(0,0,0); 
     BlinkLed(LedIndicator_CommLow, 1, 100);
     BlinkLed(LedIndicator_CommMid, 1, 100);
     BlinkLed(LedIndicator_CommHigh, 1, 100);
   }
  
  //// Respond to JSON formatted commands:
  ////Parse received JSON command to obtain specific value:
  //// Note: due to ArduinoJSON library update, the following section may need revision 
  // JsonObject& CommdObj =  CommdJSONBuffer.parseObject(p);   //Parse received command
  ////const char* SpeedCommd = CommdObj["fanspeed"];   // manually set the datatype
  ////int TimeDuration = CommdObj["duration"];
  //auto Command1Value = CommdObj.get<char *>("Command1");
  //auto Command2Value = CommdObj.get<int>("Command2");
  //Serial.println("Parsed command:");   // Display commands parsed from JSON ojbect
  //Serial.print("Command1: ");
  //Serial.print(Command1Value); 
  //Serial.print(";  Command2:  ");
  //Serial.println(Command2Value);

 //Take diff actions according to received commands. Make changes for your needs.
 //if (!strcmp(Command1Value, "turnlow"))      //(!strcmp(p, "turnlow")) 
 // {
 //      // RGB.color(255,0,0);
 //     BlinkLed(LedIndicator_CommLow, 1, 300);
 //}  
 //else if (!strcmp(Command1Value, "turnmid"))    //(!strcmp(p, "turnmid"))  
 // {
 //     // RGB.color(0, 255, 0);
 //     BlinkLed(LedIndicator_CommMid, 1, 300);
 // }
 // else if (!strcmp(Command1Value, "turnhigh"))    //(!strcmp(p, "turnhigh") )          
 // {
 //     // RGB.color(0, 0, 255);
 //     BlinkLed(LedIndicator_CommHigh, 1, 300);
 // }
 // else {
 //     // RGB.color(255,0,255); delay(1000); RGB.color(0,0,0); 
 //     BlinkLed(LedIndicator_CommLow, 1, 100);
 //     BlinkLed(LedIndicator_CommMid, 1, 100);
 //     BlinkLed(LedIndicator_CommHigh, 1, 100);
 //}
}

//A func to blink a LED for BlinkTimes
void BlinkLed(int LedPin, int BlinkTimes, int BlinkPeriod) 
{
  for (int k=0; k<BlinkTimes; k++){
      digitalWrite(LedPin, HIGH);
      delay(BlinkPeriod);
      digitalWrite(LedPin, LOW);
      delay(BlinkPeriod);
  }    
}