This repository has been archived by the owner on Jan 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
SAMDUE-Ethernet-Client_SINRIC.ino
331 lines (268 loc) · 8.82 KB
/
SAMDUE-Ethernet-Client_SINRIC.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/****************************************************************************************************************************
SAMDUE-Ethernet-Client_SINRIC.ino
For SAM DUE with Ethernet module/shield, using SINRIC (https://sinric.com/)
Based on and modified from Gil Maimon's ArduinoWebsockets library https://github.com/gilmaimon/ArduinoWebsockets
to support STM32F/L/H/G/WB/MP1, nRF52 and SAMD21/SAMD51 boards besides ESP8266 and ESP32
The library provides simple and easy interface for websockets (Client and Server).
Built by Khoi Hoang https://github.com/khoih-prog/Websockets2_Generic
Licensed under MIT license
*****************************************************************************************************************************/
/****************************************************************************************************************************
SAM DUE Websockets SINRIC Client
This sketch:
1. Connects to a WiFi network
2. Connects to a Websockets SINRIC server
3. Control the LED_BUILTIN using SINRIC/Alexa commands
Hardware:
For this sketch you only need a SAM DUE board.
*****************************************************************************************************************************/
#include "defines.h"
////////////////////////////////////////////////////
#define SINRIC_WEBSERVER "iot.sinric.com"
#define SINRIC_WEBSERVER_PORT 80
#define SINRIC_API_KEY "11111111-2222-3333-4444-555555555555"
#define SINRIC_Device_ID_1 "012345678901234567890123" // Device ID, got from Sinric
const char* websockets_server_host = SINRIC_WEBSERVER; //Enter server address
const uint16_t websockets_server_port = SINRIC_WEBSERVER_PORT; // Enter server port
#ifdef LED_BUILTIN
#define LED_PIN LED_BUILTIN
#else
#define LED_PIN 25
#endif
// Select the IP address according to your local network
IPAddress clientIP(192, 168, 2, 225);
////////////////////////////////////////////////////
#define DEBUG_LOCAL 2
#include <WebSockets2_Generic.h>
#include <ArduinoJson.h> // https://arduinojson.org/ or install via Arduino library manager
using namespace websockets2_generic;
WebsocketsClient client;
#define HEARTBEAT_INTERVAL 300000 // 5 Minutes
bool isConnected = false;
uint64_t heartbeatTimestamp = 0;
uint64_t now = 0;
//To increase no of devices as needed
void turnOn(String deviceId)
{
if (deviceId == SINRIC_Device_ID_1) // Device ID of 1st device
{
#if (DEBUG_LOCAL > 1)
Serial.print("Turn on device id: ");
Serial.println(deviceId);
#endif
digitalWrite(LED_PIN, HIGH);
}
else
{
#if (DEBUG_LOCAL > 1)
Serial.print("Turn on for unknown device id: ");
Serial.println(deviceId);
#endif
}
}
//To increase no of devices as needed
void turnOff(String deviceId)
{
if (deviceId == SINRIC_Device_ID_1) // Device ID of 1st device
{
#if (DEBUG_LOCAL > 1)
Serial.print("Turn off Device ID: ");
Serial.println(deviceId);
#endif
digitalWrite(LED_PIN, LOW);
}
else
{
#if (DEBUG_LOCAL > 1)
Serial.print("Turn off for unknown device id: ");
Serial.println(deviceId);
#endif
}
}
void onEventsCallback(WebsocketsEvent event, String data)
{
(void) data;
if (event == WebsocketsEvent::ConnectionOpened)
{
if (!isConnected)
isConnected = true;
Serial.println("Connnection Opened");
}
else if (event == WebsocketsEvent::ConnectionClosed)
{
if (isConnected)
isConnected = false;
Serial.println("Connnection Closed");
}
else if (event == WebsocketsEvent::GotPing)
{
if (!isConnected)
isConnected = true;
Serial.println("Got a Ping!");
}
else if (event == WebsocketsEvent::GotPong)
{
if (!isConnected)
isConnected = true;
Serial.println("Got a Pong!");
}
}
void onMessagesCallback(WebsocketsMessage message)
{
String SINRIC_message = message.data();
Serial.print("Got Message: ");
Serial.println(SINRIC_message /*message.data()*/);
// Example payloads
// For Switch or Light device types
// {"deviceId": xxxx, "action": "setPowerState", value: "ON"} // https://developer.amazon.com/docs/device-apis/alexa-powercontroller.html
// For Light device type
// Look at the light example in github
#if (ARDUINOJSON_VERSION_MAJOR >= 6)
DynamicJsonDocument json(1024);
//auto deserializeError = deserializeJson(json, (char*)message.data());
auto deserializeError = deserializeJson(json, SINRIC_message);
if ( deserializeError )
{
Serial.println("JSON parseObject() failed");
return;
}
//serializeJson(json, Serial);
#else
DynamicJsonBuffer jsonBuffer;
// Parse JSON string
JsonObject& json = jsonBuffer.parseObject(SINRIC_message);
// Test if parsing succeeds.
if (!json.success())
{
Serial.println("JSON parseObject() failed");
return;
}
#endif
String deviceId = json ["deviceId"];
String action = json ["action"];
if (action == "setPowerState")
{
// Switch or Light
String value = json ["value"];
if (value == "ON")
{
turnOn(deviceId);
}
else
{
turnOff(deviceId);
}
}
}
void initEthernet()
{
#if USE_ETHERNET_GENERIC
LOGWARN(F("=========== USE_ETHERNET_GENERIC ==========="));
#elif USE_ETHERNET_ESP8266
LOGWARN(F("=========== USE_ETHERNET_ESP8266 ==========="));
#elif USE_ETHERNET_ENC
LOGWARN(F("=========== USE_ETHERNET_ENC ==========="));
#else
LOGWARN(F("========================="));
#endif
#if (USING_SPI2)
#if defined(CUR_PIN_MISO)
LOGWARN(F("Default SPI pinout:"));
LOGWARN1(F("MOSI:"), CUR_PIN_MOSI);
LOGWARN1(F("MISO:"), CUR_PIN_MISO);
LOGWARN1(F("SCK:"), CUR_PIN_SCK);
LOGWARN1(F("SS:"), CUR_PIN_SS);
LOGWARN(F("========================="));
#endif
#else
LOGWARN(F("Default SPI pinout:"));
LOGWARN1(F("MOSI:"), MOSI);
LOGWARN1(F("MISO:"), MISO);
LOGWARN1(F("SCK:"), SCK);
LOGWARN1(F("SS:"), SS);
LOGWARN(F("========================="));
#endif
pinMode(USE_THIS_SS_PIN, OUTPUT);
digitalWrite(USE_THIS_SS_PIN, HIGH);
LOGWARN2(BOARD_NAME, F(" setCsPin:"), USE_THIS_SS_PIN);
// For other boards, to change if necessary
#if ( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
// Must use library patch for Ethernet, EthernetLarge libraries
// For RPI Pico using Arduino Mbed RP2040 core
// SCK: GPIO2, MOSI: GPIO3, MISO: GPIO4, SS/CS: GPIO5
// For RPI Pico using E. Philhower RP2040 core
// SCK: GPIO18, MOSI: GPIO19, MISO: GPIO16, SS/CS: GPIO17
// Default pin 5/17 to SS/CS
//Ethernet.setCsPin (USE_THIS_SS_PIN);
Ethernet.init (USE_THIS_SS_PIN);
#endif //( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
LOGWARN(F("========================="));
#if defined(CUR_PIN_MISO)
LOGWARN(F("Currently Used SPI pinout:"));
LOGWARN1(F("MOSI:"), CUR_PIN_MOSI);
LOGWARN1(F("MISO:"), CUR_PIN_MISO);
LOGWARN1(F("SCK:"), CUR_PIN_SCK);
LOGWARN1(F("SS:"), CUR_PIN_SS);
#else
LOGWARN(F("Currently Used SPI pinout:"));
LOGWARN1(F("MOSI:"), MOSI);
LOGWARN1(F("MISO:"), MISO);
LOGWARN1(F("SCK:"), SCK);
LOGWARN1(F("SS:"), SS);
#endif
LOGWARN(F("========================="));
}
void setup()
{
#if (defined(ETHERNET_WITH_SD_CARD) && ETHERNET_WITH_SD_CARD)
pinMode(SDCARD_CS, OUTPUT);
digitalWrite(SDCARD_CS, HIGH); // Deselect the SD card
#endif
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
Serial.begin(115200);
while (!Serial && millis() < 5000);
Serial.println("\nStarting SAMDUE-Ethernet-Client_SINRIC on " + String(BOARD_NAME));
Serial.println("Ethernet using " + String(ETHERNET_TYPE));
Serial.println(WEBSOCKETS2_GENERIC_VERSION);
initEthernet();
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
uint16_t index = millis() % NUMBER_OF_MAC;
// Use Static IP
//Ethernet.begin(mac[index], clientIP);
Ethernet.begin(mac[index]);
Serial.print("WebSockets Client IP address: ");
Serial.println(Ethernet.localIP());
Serial.print("Connecting to WebSockets Server @");
Serial.println(websockets_server_host);
// run callback when events are occuring
client.onMessage(onMessagesCallback);
// try to connect to Websockets server
client.addHeader("apikey", SINRIC_API_KEY);
client.setAuthorization("apikey", SINRIC_API_KEY);
bool connected = client.connect(websockets_server_host, websockets_server_port, "/");
if (connected)
{
Serial.println("Connected!");
}
else
{
Serial.println("Not Connected!");
}
}
void loop()
{
// let the websockets client check for incoming messages
if (client.available())
{
client.poll();
now = millis();
// Send heartbeat in order to avoid disconnections during ISP resetting IPs over night. Thanks @MacSass
if ((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL)
{
heartbeatTimestamp = now;
client.send("H");
}
}
}