-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRingoHue.ino
299 lines (260 loc) · 9.01 KB
/
RingoHue.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
#include <dummy.h>
#include <MAKERphone.h>
#include "HTTPClient.h"
#include <elapsedMillis.h>
// Eventually add to config folder
int wifiStatus = WL_DISCONNECTED;
File configFile;
MAKERphone mp;
HTTPClient http;
struct ConfigStruct {
char ssid[64];
char wpakey[64];
char hueapikey[64];
char huebridgeip[64];
};
const char* ssid_placeholder = "SSID_HERE";
const char* wpa_key_placeholder = "WPA_KEY_HERE";
const char* hue_api_key_placeholder = "API_KEY_HERE";
const char* hue_bridge_ip_placeholder = "BRIDGE_IP_HERE";
const char* configPath = "/RingoHue/config.json";
ConfigStruct configStruct;
void drawStatusMessage(String title = "", String subtitle = "") {
// Wipe screen
mp.display.fillScreen(TFT_BLACK);
// Set font
//mp.display.setFreeFont(TT1);
// Larger text for title
mp.display.setTextSize(2.5);
// Set datum to middle center
mp.display.setTextDatum(MC_DATUM);
mp.display.setTextColor(TFT_WHITE);
mp.display.setFreeFont(TT1);
// Draw title
// display is 160x128 FYI!
mp.display.drawString(title, 82, 60);
// Smaller text for subtitle
mp.display.setTextSize(2);
// Draw subtitle
mp.display.drawString(subtitle, 82, 75);
// Print what we just made
mp.update();
Serial.println(title);
Serial.println(subtitle);
}
void checkConfig() {
while (String(configStruct.ssid) == String(ssid_placeholder)) {
drawStatusMessage("-- Invalid Config --", "Please set SSID");
Serial.println("SSID not configured!");
delay(10000);
}
while (String(configStruct.wpakey) == String(wpa_key_placeholder)) {
drawStatusMessage("-- Invalid Config --", "Please set WPA password");
Serial.println("WPA password not configured!");
delay(10000);
}
while (String(configStruct.hueapikey) == String(hue_api_key_placeholder)) {
drawStatusMessage("-- Invalid Config --", "Please set Hue API Key");
Serial.println("API Key not configured!");
delay(10000);
}
while (String(configStruct.huebridgeip) == String(hue_bridge_ip_placeholder)) {
drawStatusMessage("-- Invalid Config --", "Please set Bridge IP");
Serial.println("Bridge IP not configured!");
delay(10000);
}
}
// Prints the content of a file to the Serial
void printConfig() {
// Open file for reading
configFile = SD.open(configPath);
if (!configFile) {
Serial.println(F("Failed to read file"));
return;
}
// Extract each characters by one by one
while (configFile.available()) {
Serial.print((char)configFile.read());
}
Serial.println();
// Close the file (File's destructor doesn't close the file)
configFile.close();
}
void loadConfiguration() {
if (mp.SDinsertedFlag) {
// The MAKERphone function is inherently broken because it doesnt set the "FILE_WRITE" flag?
// https://github.com/CircuitMess/CircuitMess-Ringo/pull/50
// mp.writeFile("/RingoHue/config.json", "test");
configFile = SD.open(configPath, FILE_READ);
StaticJsonBuffer<512> jsonBuffer;
// Parse the root object
JsonObject& root = jsonBuffer.parseObject(configFile);
if (!root.success()) {
Serial.println("Failed to read config.json, falling back to, and attempting to write placeholder configuration.");
}
// Copy values from the JsonObject to the Config struct
strlcpy(configStruct.ssid, // <- destination
root["ssid"] | ssid_placeholder, // <- source
sizeof(configStruct.ssid)); // <- destination's capacity
strlcpy(configStruct.wpakey, // <- destination
root["wpakey"] | wpa_key_placeholder, // <- source
sizeof(configStruct.wpakey)); // <- destination's capacity
strlcpy(configStruct.hueapikey, // <- destination
root["hueapikey"] | hue_api_key_placeholder, // <- source
sizeof(configStruct.hueapikey)); // <- destination's capacity
strlcpy(configStruct.huebridgeip, // <- destination
root["huebridgeip"] | hue_bridge_ip_placeholder, // <- source
sizeof(configStruct.huebridgeip)); // <- destination's capacity
// Close the file (File's destructor doesn't close the file)
configFile.close();
}
}
void saveConfiguration() {
//Remove existing file or else config will be appended
SD.remove(configPath);
configFile = SD.open(configPath, FILE_WRITE);
if (!configFile) {
Serial.println(F("Failed to create config.json! Did you have it set up properly in the first place?"));
return;
}
// Allocate the memory pool on the stack
// Don't forget to change the capacity to match your JSON document.
// Use https://arduinojson.org/assistant/ to compute the capacity.
StaticJsonBuffer<512> jsonBuffer;
// Parse the root object
JsonObject& root = jsonBuffer.createObject();
// Set the values
root["ssid"] = configStruct.ssid;
root["wpakey"] = configStruct.wpakey;
root["hueapikey"] = configStruct.hueapikey;
root["huebridgeip"] = configStruct.huebridgeip;
// Serialize JSON to file
if (root.prettyPrintTo(configFile) == 0) {
Serial.println(F("Failed to write to config.json!"));
}
// Close the file (File's destructor doesn't close the file)
configFile.close();
}
void setup() {
// put your setup code here, to run once:
mp.begin();
Serial.begin(115200);
while (!Serial) continue;
Serial.println("Welcome to RingoHue!");
while (!SD.begin(5, SPI, 8000000)) {
Serial.println(F("Failed to initialize SD library. Is your SD card inserted?"));
drawStatusMessage("-- Error --", "Insert SD card!");
delay(10000);
}
// Should load default config if run for the first time
Serial.println(F("Loading configuration..."));
loadConfiguration();
// Create configuration file
Serial.println(F("Saving configuration..."));
saveConfiguration();
// Dump config file
Serial.println(F("Print config file..."));
printConfig();
// Check if config.json is correct.
checkConfig();
connectNetwork();
}
void loop() {
// put your main code here, to run repeatedly:
mp.update();
// When application is resumed from mp's idle state.
if (mp.exitedLockscreen) {
connectNetwork();
}
if (mp.buttons.pressed(BTN_A)) {
testCommand(true);
}
if (mp.buttons.pressed(BTN_B)) {
testCommand(false);
}
drawScreen();
}
void connectNetwork() {
// Retrieve wifi status on function called
wifiStatus = WiFi.status();
Serial.println("Wifi Status: " + String(wifiStatus));
// Evaluate what to do based on WiFi status
switch (wifiStatus) {
case 255: // WL_NO_SHIELD
Serial.println("WiFI not initialized. Reattempting.");
drawStatusMessage("Connecting...", String(configStruct.ssid));
// Attempting reconnect.
WiFi.begin(configStruct.ssid, configStruct.wpakey);
// Wait 1 seconds
delay(3000);
// Check if conditions have changed.
connectNetwork();
break;
case 6: // WL_WRONG_PASSWORD
Serial.println("WiFi password incorrect! Please reconfigure RingoHue.");
drawStatusMessage("Connection Failed", "Check password.");
Serial.println(String(configStruct.ssid) + "didn't work.");
delay(2000);
connectNetwork();
break;
case 0: // WL_IDLE_STATUS
case 7: // WL_DISCONNECTED,
case 5: //WL_CONNECTION_LOST
drawStatusMessage("Connection Lost", "Reconnecting...");
WiFi.begin(configStruct.ssid, configStruct.wpakey);
connectNetwork();
break;
case 4: //WL_CONNECT_FAILED
WiFi.begin(configStruct.ssid, configStruct.wpakey);
drawStatusMessage("Connection Failed!", "Are you in range?");
connectNetwork();
break;
case 3: //WL_CONNECTED
{
drawStatusMessage("Connected", WiFi.localIP().toString());
}
break;
default:
Serial.println("Initializing WiFi...");
WiFi.begin(configStruct.ssid, configStruct.wpakey);
delay(3000);
connectNetwork();
break;
}
}
String PUTCompiler(String state, String hue, String bri) {
if (state == "0") {
state = "false";
} else {
state = "true";
}
String returnString;
returnString = "{\"on\":" + state + ", \"hue\":" + hue + ", \"bri\":" + bri + ", \"sat\":255}";
Serial.println("Built PUT request: " + returnString);
return returnString;
}
String boolToString(bool state) {
if (String(state) == "0") {
return "false";
} else {
return "true";
}
}
void testCommand(bool state) {
//typecasting String() is a memory hog
http.begin("http://" + String(configStruct.huebridgeip) + "/api/" + String(configStruct.hueapikey) + "/groups/0/action");
int httpResponseCode = http.PUT("{\"on\":" + boolToString(state) + "}");
String response = http.getString();
if (httpResponseCode == 200) {
Serial.println("Test command successful.");
}
Serial.println("Code: " + httpResponseCode);
Serial.println("HTTP Response: " + response);
http.end();
}
void drawScreen() {
// display is 160x128 FYI!
if (WiFi.isConnected()) {
mp.display.drawCircle(80, 64, 20, TFT_GREEN);
}
}