-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws-mqtt-websocket-glow.ino
254 lines (209 loc) · 6.31 KB
/
aws-mqtt-websocket-glow.ino
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
#include <Arduino.h>
#include <Stream.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
//AWS
#include "sha256.h"
#include "Utils.h"
#include "AWSClient.h"
//WEBSockets
#include <Hash.h>
#include <WebSocketsClient.h>
//MQTT PAHO
#include <SPI.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>
//AWS MQTT Websocket
#include "Client.h"
#include "AWSWebSocketClient.h"
#include "CircularByteBuffer.h"
#define THING_NAME "yourThingName"
//AWS IOT config, change these:
char wifi_ssid[] = "XXXXXXXXXXXXXXXXXX";
char wifi_password[] = "XXXXXXXXXXX";
char aws_endpoint[] = "XXXXXXXX.iot.us-east-1.amazonaws.com";
char aws_key[] = "XXXXXXXXXXX";
char aws_secret[] = "XXXXXXXXXXXXXXXXXX";
char aws_region[] = "us-east-1";
const char* aws_topic_get = "$aws/things/" THING_NAME "/shadow/get";
int port = 443;
char *subscribeTopic[1] = {
// "$aws/things/" THING_NAME "/shadow/update/accepted",
// "$aws/things/" THING_NAME "/shadow/update/rejected",
// "$aws/things/" THING_NAME "/shadow/update/delta",
"$aws/things/" THING_NAME "/shadow/get/accepted",
// "$aws/things/" THING_NAME "/shadow/get/rejected"
};
char* clientID;
int led_state = 1;
//MQTT config
const int maxMQTTpackageSize = 512;
const int maxMQTTMessageHandlers = 1;
ESP8266WiFiMulti WiFiMulti;
AWSWebSocketClient awsWSclient(1000);
IPStack ipstack(awsWSclient);
MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> *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;
void updateLedState(int desired_led_state) {
printf("change led_state to %d\r\n", desired_led_state);
led_state = desired_led_state;
digitalWrite(2, led_state);
}
//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;
char* payload = msg;
int length = message.payloadlen;
char buf[maxMQTTpackageSize];
char *pch;
int desired_led_state;
strncpy(buf, (const char *)payload, length);
buf[length] = '\0';
// payload format: {"state":{"reported":{"led":1},"desired":{"led":0}},"metadata":{"reported":{"led":{"timestamp":1466996558}},"desired":{"led":{"timestamp":1466996558}}},"version":7,"timestamp":1466996558}
pch = strstr(buf, "\"desired\":{\"led\":");
if (pch != NULL) {
pch += strlen("\"desired\":{\"led\":");
desired_led_state = *pch - '0';
if (desired_led_state != led_state) {
updateLedState(desired_led_state);
}
}
}
//connects to websocket layer and mqtt layer
bool connect () {
if (client == NULL) {
client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
} else {
if (client->isConnected ()) {
client->disconnect ();
}
delete client;
client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
}
//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 = 3;
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_get, MQTT::QOS0, messageArrived);
// if (rc != 0) {
// Serial.print("rc from MQTT subscribe is ");
// Serial.println(rc);
// return;
// }
for (int i=0; i<1; i++) {
printf("subscribe [%s]\r\n", subscribeTopic[i]);
int rc = client->subscribe(subscribeTopic[i], 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];
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_get, message);
}
void setup() {
Serial.begin (115200);
delay (2000);
Serial.setDebugOutput(0);
pinMode(2, OUTPUT);
led_state = digitalRead(2);
//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();
} else {
//handle reconnection
if (connect ()){
subscribe ();
}
}
}