forked from sticilface/Esp8266-Hue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HueBridge.cpp
1765 lines (1253 loc) · 51.2 KB
/
HueBridge.cpp
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "HueBridge.h"
HueBridge::HueBridge(ESP8266WebServer * HTTP, uint8_t lights, uint8_t groups, HueBridge::HueHandlerFunctionNEW fn):
_HTTP(HTTP),
_LightCount(lights),
_GroupCount(groups),
// _Handler(fn),
_HandlerNEW(fn),
_returnJSON(true),
// _RunningGroupCount(2)
_nextfreegroup(0)
{
if (_GroupCount < 2) _GroupCount = 2; // minimum required
initHUE(_LightCount, _GroupCount); // creates the data structures...
}
HueBridge::~HueBridge() {
if (Lights) delete[] Lights;
if (Groups) delete[] Groups;
Lights = NULL;
Groups = NULL; // Must check these....
_HTTP->onNotFound(NULL);
}
void HueBridge::Begin() {
_macString = String(WiFi.macAddress()); // toDo turn to 4 byte array..
_ipString = StringIPaddress(WiFi.localIP());
_netmaskString = StringIPaddress(WiFi.subnetMask());
_gatewayString = StringIPaddress(WiFi.gatewayIP());
initSSDP();
_HTTP->onNotFound(std::bind(&HueBridge::HandleWebRequest, this)); // register the onNotFound for Webserver to HueBridge
_HTTP->serveStatic("/hue/lights.conf", SPIFFS , "/lights.conf");
_HTTP->serveStatic("/hue/groups.conf", SPIFFS , "/groups.conf");
_HTTP->serveStatic("/hue/test.conf", SPIFFS , "/test.conf");
_HTTP->on("/hue/format", [this]() {
SPIFFS.format();
_HTTP->send ( 200, "text/plain", "DONE" );
} );
Serial.println(F("Philips Hue Started...."));
Serial.print(F("Size Lights = "));
Serial.println(sizeof(HueLight) * _LightCount);
Serial.print(F("Size Groups = "));
Serial.println(sizeof(HueGroup) * _GroupCount);
SPIFFS.begin();
/*------------------------------------------------------------------------------------------------
Import saved Lights from SPIFFS
------------------------------------------------------------------------------------------------*/
File LightsFile = SPIFFS.open("/lights.conf", "r");
if (!LightsFile)
{
Serial.println(F("Failed to open lights.conf"));
} else {
Serial.println(F("Opened lights.conf"));
Serial.print(F("CONFIG FILE CONTENTS----------------------"));
Serial.println();
uint8_t light[sizeof(HueLight)];
size_t size = LightsFile.size();
uint8_t counter = 0;
for(int i=0; i<size; i+=sizeof(HueLight)){
for(int j=0;j<sizeof(HueLight);j++){
light[j] = LightsFile.read();
}
HueLight *thelight = (HueLight *)light;
HueLight *currentlight = &Lights[counter];
memcpy (currentlight , thelight , sizeof(HueLight));
Serial.printf( "Saved Light:%3u, %15s, State = %u, HSB(%5u,%3u,%3u) \n",
counter, thelight->Name, thelight->State, thelight->hsb.H, thelight->hsb.S, thelight->hsb.B);
counter++;
}
LightsFile.close();
}
/*------------------------------------------------------------------------------------------------
Import saved Groups from SPIFFS
------------------------------------------------------------------------------------------------*/
File GroupsFile = SPIFFS.open("/groups.conf", "r");
if (!GroupsFile)
{
Serial.println(F("Failed to open groups.conf"));
} else {
Serial.println(F("Opened groups.conf"));
Serial.print(F("CONFIG FILE CONTENTS----------------------"));
Serial.println();
uint8_t group[sizeof(HueGroup)];
size_t size = GroupsFile.size();
uint8_t counter = 0;
for(int i=0; i<size; i+=sizeof(HueGroup)){
for(int j=0;j<sizeof(HueGroup);j++){
group[j] = GroupsFile.read();
}
HueGroup *thegroup = (HueGroup *)group; // Cast retrieved data as HueGroup...
HueGroup *currentgroup = &Groups[counter]; // pointer to actual array
memcpy (currentgroup , thegroup , sizeof(HueGroup));
Serial.printf( "Saved Group:%3u, %15s, inuse=%u, State=%u, HSB(%5u,%3u,%3u) \n",
counter, thegroup->Name, thegroup->Inuse, thegroup->State, thegroup->Hue, thegroup->Sat, thegroup->Bri);
counter++;
}
GroupsFile.close();
}
_nextfreegroup = find_nextfreegroup();
}
void HueBridge::initHUE(uint8_t Lightcount, uint8_t Groupcount) {
if (Lights) delete[] Lights;
if (Groups) delete[] Groups;
Lights = new HueLight[Lightcount];
Groups = new HueGroup[Groupcount];
for (uint8_t i = 0; i < Lightcount; i++) {
HueLight* currentlight = &Lights[i];
sprintf(currentlight->Name, "Hue Light %u", i+1);
}
for (uint8_t i = 0; i < Groupcount; i++) {
HueGroup *g = &Groups[i];
if ( i == 0 || i == 1) g->Inuse = true; // sets group 0 and 1 to always be in use...
sprintf(g->Name, "Group %u", i);
g->LightsCount = 0 ;
for (uint8_t i = 0; i < MaxLightMembersPerGroup; i++) {
//uint8_t randomlight = random(1,Lightcount + 1 );
g->LightMembers[i] = 0;
}
}
}
void HueBridge::HandleWebRequest() {
//------------------------------------------------------
// Initial web request handles ....
//------------------------------------------------------
HTTPMethod RequestMethod = _HTTP->method();
long startime = millis();
// Serial.print("Uri: ");
// Serial.println(_HTTP->uri());
// if (_lastrequest > 0) {
// long timer = millis() - _lastrequest;
// Serial.print("TSLR = ");
// Serial.print(timer);
// Serial.print(" :");
// }
// _lastrequest = millis();
/////////////////////////////////
//------------------------------------------------------
// Extract User
//------------------------------------------------------
//Hue_Commands Command; // holds command issued by client
if ( _HTTP->uri() != "/api" && _HTTP->uri().charAt(4) == '/' && _HTTP->uri() != "/api/config" ) {
user = _HTTP->uri().substring(5, _HTTP->uri().length());
if (user.indexOf("/") > 0) {
user = user.substring(0, user.indexOf("/"));
}
}
//Serial.print("Session user = ");
//Serial.println(user);
isAuthorized = true;
if (!isAuthorized) return; // exit if none authorised user... toDO...
//------------------------------------------------------
// Determine command
//------------------------------------------------------
// /api/JPnfsdoKSVacEA0f/lights/8 --> renames light
//Serial.print(" ");
size_t sent = 0;
if ( _HTTP->uri() == "/description.xml") {
Handle_Description();
return;
} else if ( _HTTP->uri() == "/api" ) {
Serial.println("CREATE_USER - toDO");
//Command = CREATE_USER;
_HTTP->send(404);
return;
} else if ( _HTTP->uri().endsWith("/config") ) {
//Command = GET_CONFIG;
sent = printer.Send( _HTTP->client() , 200, "text/json", std::bind(&HueBridge::Send_Config_Callback, this) ); // Send_Config_Callback
return;
} else if ( _HTTP->uri() == "/api/" + user ) {
//Command = GET_FULLSTATE;
sent = printer.Send( _HTTP->client() , 200, "text/json", std::bind(&HueBridge::Send_DataStore_Callback, this) );
return;
} else if ( _HTTP->uri().indexOf(user) != -1 && _HTTP->uri().endsWith("/state") ) {
if (RequestMethod == HTTP_PUT) {
//Command = PUT_LIGHT;
//Serial.print("PUT_LIGHT");
Put_light();
} else if (RequestMethod == HTTP_GET) {
//Command = GET_LIGHT;
Serial.print("GET_LIGHT - toDo"); // ToDo
_HTTP->send(404);
} else {
Serial.print("LIGHT Unknown req: ");
Serial.print(HTTPMethod_text[RequestMethod]);
_HTTP->send(404);
}
return;
} else if ( _HTTP->uri().indexOf(user) != -1 && _HTTP->uri().indexOf("/groups/") != -1 ) { // old _HTTP->uri().endsWith("/action")
if (RequestMethod == HTTP_PUT) {
//Command = PUT_GROUP;
//Serial.print("PUT_GROUP");
Put_group();
} else if (RequestMethod == HTTP_GET) {
//Command = GET_GROUP;
Serial.print("GET_GROUP- todo"); // ToDo
_HTTP->send(404);
} else {
Serial.print("GROUP Unknown req: ");
Serial.print(HTTPMethod_text[RequestMethod]);
_HTTP->send(404);
}
return;
} else if (_HTTP->uri().indexOf(user) != -1 && _HTTP->uri().endsWith("/groups") ) {
if (RequestMethod == HTTP_PUT) {
//Command = ADD_GROUP;
Serial.println("ADD_GROUP");
Add_Group();
}
return;
} else if ( _HTTP->uri().substring(0, _HTTP->uri().lastIndexOf("/") ) == "/api/" + user + "/lights" ) {
if (RequestMethod == HTTP_PUT) {
//Command = PUT_LIGHT_ROOT;
Serial.println("PUT_LIGHT_ROOT");
Put_Light_Root();
} else {
//Command = GET_LIGHT_ROOT;
Serial.println("GET_LIGHT_ROOT - todo");
_HTTP->send(404);
}
return;
} else if ( _HTTP->uri() == "/api/" + user + "/lights" ) {
//Command = GET_ALL_LIGHTS;
Serial.println("GET_ALL_LIGHTS- todo");
_HTTP->send(404);
return;
}
else
{
Serial.print("UnknownUri: ");
Serial.print(_HTTP->uri());
Serial.print(" ");
Serial.println(HTTPMethod_text[RequestMethod]);
if (_HTTP->arg("plain") != "" ) {
Serial.print("BODY: ");
Serial.println(_HTTP->arg("plain"));
}
_HTTP->send(404);
return;
}
//------------------------------------------------------
// END OF NEW command PARSING
//------------------------------------------------------
// long _time = millis() - startime;
// Serial.print(" ");
// Serial.print(_time);
// Serial.println("ms");
//Serial.println();
}
/*-------------------------------------------------------------------------------------------
Functions to send out JSON data
-------------------------------------------------------------------------------------------*/
void HueBridge::Send_DataStore_Callback() {
printer.print("{"); // START of JSON
printer.print(F("\"lights\":{ "));
Print_Lights(); // Lights
printer.print("},");
printer.print(F("\"config\":{ "));
Print_Config(); // Config
printer.print("},");
printer.print(F("\"groups\": { "));
Print_Groups(); // Config
printer.print(F("},"));
printer.print(F("\"scenes\" : { }"));
printer.print(",");
printer.print(F("\"schedules\" : { }"));
printer.print("}"); // END of JSON
}
void HueBridge::Send_Config_Callback () {
printer.print("{"); // START of JSON
Print_Config(); // Config
printer.print("}"); // END of JSON
}
void HueBridge::Print_Lights() {
for (uint8_t i = 0; i < _LightCount; i++) {
if (i > 0 ) printer.print(",");
uint8_t LightNumber = i + 1;
HueLight* currentlight = &Lights[i];
printer.print(F("\""));
printer.print(LightNumber);
printer.print(F("\":{"));
printer.print(F("\"type\":\"Extended color light\","));
printer.printf("\"name\":\"%s\",",currentlight->Name);
printer.print(F("\"modelid\":\"LST001\","));
printer.print(F("\"state\":{"));
( currentlight->State == true ) ? printer.print(F("\"on\":true,")) : printer.print(F("\"on\":false,"));
printer.printf("\"bri\":%u,", currentlight->hsb.B);
printer.printf("\"hue\":%u,", currentlight->hsb.H);
printer.printf("\"sat\":%u,", currentlight->hsb.S);
//temporarily holds data from vals
char x[10];
char y[10];
// clear the array
memset(x,0,10);
memset(y,0,10);
// check is a number
// if isnan(currentlight->xy.x) currentlight->xy.x = 0;
// if isnan(currentlight->xy.y) currentlight->xy.y = 0;
//4 is mininum width, 3 is precision; float value is copied onto buf
if (!isnan(currentlight->xy.x)) dtostrf(currentlight->xy.x, 5, 4, x); else x[0] = '0' ;
if (!isnan(currentlight->xy.y)) dtostrf(currentlight->xy.y, 5, 4, y); else y[0] = '0' ;
//dtostrf(currentlight->xy.y, 5, 4, y);
printer.printf("\"xy\":[%s,%s],", x, y );
printer.printf("\"ct\":%u,", currentlight->Ct);
printer.print(F("\"alert\":\"none\","));
printer.print(F("\"effect\":\"none\","));
printer.printf("\"colormode\":\"%s\",", currentlight->Colormode);
printer.print(F("\"reachable\":true}"));
printer.print("}");
}
}
void HueBridge::Print_Groups(){
uint8_t groups_sent = 0;
for (uint8_t GroupNumber = 1; GroupNumber < _GroupCount; GroupNumber++) { // start at 1 to NOT send group 0..
HueGroup* currentgroup = &Groups[GroupNumber];
if ( currentgroup->Inuse || GroupNumber == _nextfreegroup ) {
if (groups_sent > 0 ) printer.print(",");
printer.print(F("\""));
printer.print(GroupNumber);
printer.print(F("\":{"));
printer.printf("\"name\":\"%s\",",currentgroup->Name);
printer.print(F("\"lights\": ["));
for (uint8_t j = 0; j < currentgroup->LightsCount; j++) {
if (j>0) printer.print(",");
printer.printf("\"%u\"", currentgroup->LightMembers[j]);
}
printer.print(F("],"));
printer.print(F("\"type\":\"LightGroup\","));
printer.print(F("\"action\": {"));
( currentgroup->State == true ) ? printer.print(F("\"on\":true,")) : printer.print(F("\"on\":false,"));
printer.printf("\"bri\":%u,", currentgroup->Bri);
printer.printf("\"hue\":%u,", currentgroup->Hue);
printer.printf("\"sat\":%u,", currentgroup->Sat);
printer.print("\"effect\": \"none\",");
//temporarily holds data from vals
char x[10];
char y[10];
//4 is mininum width, 3 is precision; float value is copied onto buff
dtostrf(currentgroup->xy.x, 5, 4, x);
dtostrf(currentgroup->xy.y, 5, 4, y);
printer.printf("\"xy\":[%s,%s],", x, y );
printer.printf("\"ct\":%u,", currentgroup->Ct);
printer.print(F("\"alert\":\"none\","));
printer.printf("\"colormode\":\"%s\"", currentgroup->Colormode);
printer.print("}}");
groups_sent++; // used for comma placement
}
}
}
void HueBridge::Print_Config() {
printer.print("\"name\":\"Hue Emulator\",");
printer.print("\"swversion\":\"0.1\",");
printer.printf("\"mac\": \"%s\",", (char*)_macString.c_str() );
printer.print("\"dhcp\":true,");
printer.printf("\"ipaddress\": \"%s\",", (char*)_ipString.c_str() );
printer.printf("\"netmask\": \"%s\",", (char*)_netmaskString.c_str() );
printer.printf("\"gateway\": \"%s\",", (char*)_gatewayString.c_str() );
printer.print(F("\"swupdate\":{\"text\":\"\",\"notify\":false,\"updatestate\":0,\"url\":\"\"},"));
printer.print(F("\"whitelist\":{\"xyz\":{\"name\":\"clientname#devicename\"}}"));
}
void HueBridge::SendJson(JsonObject& root){
size_t size = 0; // root.measureLength();
//Serial.print(" JSON ");
WiFiClient c = _HTTP->client();
printer.Begin(c);
printer.SetHeader(200, "text/json");
printer.SetCountMode(true);
root.printTo(printer);
size = printer.SetCountMode(false);
root.printTo(printer);
c.stop();
while(c.connected()) yield();
printer.End(); // free memory...
//Serial.printf(" %uB\n", size );
}
void HueBridge::SendJson(JsonArray& root){
size_t size = 0;
//Serial.print(" JSON ");
WiFiClient c = _HTTP->client();
printer.Begin(c);
printer.SetHeader(200, "text/json");
printer.SetCountMode(true);
root.printTo(printer);
size = printer.SetCountMode(false);
root.printTo(printer);
c.stop();
while(c.connected()) yield();
printer.End(); // free memory...
//Serial.printf(" %uB\n", size);
}
void HueBridge::Handle_Description() {
String str = F("<root><specVersion><major>1</major><minor>0</minor></specVersion><URLBase>http://");
str += _ipString;
str += F(":80/</URLBase><device><deviceType>urn:schemas-upnp-org:device:Basic:1</deviceType><friendlyName>Philips hue (");
str += _ipString;
str += F(")</friendlyName><manufacturer>Royal Philips Electronics</manufacturer><manufacturerURL>http://www.philips.com</manufacturerURL><modelDescription>Philips hue Personal Wireless Lighting</modelDescription><modelName>Philips hue bridge 2012</modelName><modelNumber>929000226503</modelNumber><modelURL>http://www.meethue.com</modelURL><serialNumber>00178817122c</serialNumber><UDN>uuid:2f402f80-da50-11e1-9b23-00178817122c</UDN><presentationURL>index.html</presentationURL><iconList><icon><mimetype>image/png</mimetype><height>48</height><width>48</width><depth>24</depth><url>hue_logo_0.png</url></icon><icon><mimetype>image/png</mimetype><height>120</height><width>120</width><depth>24</depth><url>hue_logo_3.png</url></icon></iconList></device></root>");
_HTTP->send(200, "text/plain", str);
Serial.println(F("/Description.xml SENT"));
}
/*-------------------------------------------------------------------------------------------
Functions to process known web request PUT LIGHT
-------------------------------------------------------------------------------------------*/
void HueBridge::Put_light () {
if (_HTTP->arg("plain") == "")
{
return;
}
//------------------------------------------------------
// Extract Light ID ==> Map to LightNumber (toDo)
//------------------------------------------------------
uint8_t numberOfTheLight = Extract_LightID();
String lightID = String(numberOfTheLight + 1);
HueLight* currentlight = &Lights[numberOfTheLight];
struct RgbColor rgb;
//------------------------------------------------------
// JSON set up IN + OUT
//------------------------------------------------------
DynamicJsonBuffer jsonBufferOUT; // create buffer
DynamicJsonBuffer jsonBufferIN; // create buffer
JsonObject& root = jsonBufferIN.parseObject(_HTTP->arg("plain"));
JsonArray& array = jsonBufferOUT.createArray(); // new method
//------------------------------------------------------
// ON / OFF
//------------------------------------------------------
bool onValue{false}, hasHue{false}, hasBri{false}, hasSat{false}, hasXy{false};
// struct HueHSB &hsb = currentlight->hsb; // might be useful method for later.
if (root.containsKey("on"))
{
onValue = root["on"];
String response = F("/lights/"); response += lightID ; response += F("/state/on"); // + onoff;
if (onValue) {
currentlight->State = true;
if (strcmp (currentlight->Colormode,"hs") == 0 ) {
rgb = HUEhsb2rgb(currentlight->hsb); // designed to handle philips hue RGB ALLOCATED FROM JSON REQUEST
} else if (strcmp (currentlight->Colormode,"xy") == 0) {
rgb = XYtorgb(currentlight->xy, currentlight->hsb.B); // set the color to return
}
if (_returnJSON) AddSucessToArray (array, response, F("on") );
} else {
currentlight->State = false;
rgb = RgbColor(0,0,0);
if (_returnJSON) AddSucessToArray (array, response, F("off") ) ;
}
}
//------------------------------------------------------
// HUE / SAT / BRI
//------------------------------------------------------
if (root.containsKey("hue"))
{
currentlight->hsb.H = root["hue"];
String response = "/lights/" + lightID + "/state/hue"; // + onoff;
hasHue = true;
if (_returnJSON) AddSucessToArray (array, response, root["hue"] );
}
if (root.containsKey("sat"))
{
currentlight->hsb.S = root["sat"];
String response = "/lights/" + lightID + "/state/sat"; // + onoff;
hasSat = true;
if (_returnJSON) AddSucessToArray (array, response, root["sat"]);
}
if (root.containsKey("bri"))
{
currentlight->hsb.B = root["bri"];
String response = "/lights/" + lightID + "/state/bri"; // + onoff;
hasBri = true;
if (_returnJSON) AddSucessToArray (array, response, root["bri"]);
}
//------------------------------------------------------
// XY Color Space
//------------------------------------------------------
if (root.containsKey("xy"))
{
currentlight->xy.x = root["xy"][0];
currentlight->xy.y = root["xy"][1];
hasXy = true;
if (_returnJSON) {
JsonObject& nestedObject = array.createNestedObject();
JsonObject& sucess = nestedObject.createNestedObject("success");
JsonArray& xyObject = sucess.createNestedArray("xy");
xyObject.add(currentlight->xy.x, 4); // 4 digits: "3.1415"
xyObject.add(currentlight->xy.x, 4); // 4 digits: "3.1415"
}
}
//------------------------------------------------------
// Ct Colour space
//------------------------------------------------------
if (root.containsKey("ct"))
{
// todo
}
//------------------------------------------------------
// Apply recieved Color data
//------------------------------------------------------
if (hasHue || hasBri || hasSat) {
rgb = HUEhsb2rgb(currentlight->hsb); // designed to handle philips hue RGB ALLOCATED FROM JSON REQUEST
if (!hasXy) currentlight->xy = HUEhsb2xy(currentlight->hsb); // COPYED TO LED STATE incase onother applciation requests colour
strcpy(currentlight->Colormode, "hs");
}
if (hasXy) {
rgb = XYtorgb(currentlight->xy, currentlight->hsb.B); // set the color to return
currentlight->hsb = xy2HUEhsb(currentlight->xy, currentlight->hsb.B); // converts for storage...
strcpy(currentlight->Colormode, "xy");
}
//------------------------------------------------------
// SEND Back changed JSON REPLY
//------------------------------------------------------
// Serial.println();
// array.prettyPrintTo(Serial);
// Serial.println();
if (_returnJSON) SendJson(array);
//printer.print("]");
//printer.Send_Buffer(200,"text/json");
//-------------------------------------
// Print Saved State Buffer to serial
//------------------------------------------------------
// Serial.print("Saved = Hue:");
// Serial.print(StripHueData[numberOfTheLight].Hue);
// Serial.print(", Sat:");
// Serial.print(StripHueData[numberOfTheLight].Sat);
// Serial.print(", Bri:");
// Serial.print(StripHueData[numberOfTheLight].Bri);
// Serial.println();
//------------------------------------------------------
// Set up LEDs... rock and roll....
//------------------------------------------------------
_HandlerNEW(numberOfTheLight + 1, rgb, currentlight);
//------------------------------------------------------
// Save Settings to SPIFFS
//------------------------------------------------------
long start_time_spiffs = millis();
File configFile = SPIFFS.open("/lights.conf", "r+");
if (!configFile)
{
Serial.println(F("Failed to open test.conf, making new"));
configFile = SPIFFS.open("/lights.conf", "w+");
} else {
Serial.println(F("Opened Hue_conf.txt for UPDATE...."));
unsigned char * data = reinterpret_cast<unsigned char*>(Lights); // use unsigned char, as uint8_t is not guarunteed to be same width as char...
size_t bytes = configFile.write(data, sizeof(HueLight) * _LightCount ); // C++ way
configFile.close();
Serial.print("TIME TAKEN: ");
Serial.print(millis() - start_time_spiffs);
Serial.print("ms, ");
Serial.print(bytes);
Serial.println("B");
}
/*---------------------------------------------------------------------------------------------------------------------------------------
Experimental - Per Light saving of settings.. move towards file system based storage, for all hue data.
This is working.. saves only the current light to SPIFFS...
//---------------------------------------------------------------------------------------------------------------------------------------*/
#ifdef EXPERIMENTAL
File testFile;
long t1 = micros();
long h1 = ESP.getFreeHeap();
testFile = SPIFFS.open("/test.conf", "r+");
File lightFile = SPIFFS.open("/lights.conf", "r+");
File groupFile = SPIFFS.open("/groups.conf", "r+");
Serial.printf("Open file time: %uus, heap use = %u \n", micros() - t1 , h1 - ESP.getFreeHeap());
long start_spiffs = micros();
if (!testFile) {
testFile = SPIFFS.open("/test.conf", "w+");
}
if (testFile) {
uint32_t position = numberOfTheLight * sizeof(HueLight);
if(!testFile.seek(position, SeekSet)) { // if seek fails... ie file is too short
testFile.seek(0, SeekEnd); // go to end of file
do {
testFile.write(0); // write 0 until in right place...
} while (testFile.position() < position);
}
unsigned char * data = reinterpret_cast<unsigned char*>(currentlight); // C++ way
size_t bytes = testFile.write(data, sizeof(HueLight));
Serial.printf("newFS Time taken %uus, %uB \n", micros() - start_spiffs, bytes);
long t2 = micros();
long h2 = ESP.getFreeHeap();
testFile.close();
Serial.printf("Open close time: %uus, heap use = %u \n", micros() - t2, ESP.getFreeHeap() - h2);
} else {
Serial.println("FAILED TO WRITE TO + CREATE FILE");
}
#endif
}
/*-------------------------------------------------------------------------------------------
Functions to process known web request PUT GROUP
-------------------------------------------------------------------------------------------*/
void HueBridge::Put_group () {
if (_HTTP->arg("plain") == "")
{
return;
}
// Serial.print("\nREQUEST: ");
// Serial.println(_HTTP->uri());
// Serial.println(_HTTP->arg("plain"));
//------------------------------------------------------
// Extract Light ID ==> Map to LightNumber (toDo)
//------------------------------------------------------
//uint8_t numberOfTheGroup = Extract_LightID();
uint8_t groupNum = atoi(subStr(_HTTP->uri().c_str(), (char*) "/", 4)); //
uint8_t numberOfTheGroup = groupNum;
String groupID = String(groupNum);
// Serial.print("\nGr = ");
// Serial.print(groupID);
// Serial.print(" _RunningGroupCount = ");
// Serial.println(_RunningGroupCount);
if (numberOfTheGroup > _GroupCount) return;
HueGroup* currentgroup;
currentgroup = &Groups[groupNum];
struct RgbColor rgb;
struct HueHSB hsb;
bool colourschanged = false;
//------------------------------------------------------
// JSON set up IN + OUT
//------------------------------------------------------
DynamicJsonBuffer jsonBufferOUT; // create buffer
DynamicJsonBuffer jsonBufferIN; // create buffer
JsonObject& root = jsonBufferIN.parseObject(_HTTP->arg("plain"));
JsonArray& array = jsonBufferOUT.createArray(); // new method
//------------------------------------------------------
// ON / OFF
//------------------------------------------------------
bool onValue = false;
if (root.containsKey("on"))
{
onValue = root["on"];
String response = "/groups/" + groupID + "/state/on"; // + onoff;
if (onValue) {
// Serial.print(" ON :");
currentgroup->State = true;
if (_returnJSON) AddSucessToArray (array, response, F("on") );
} else {
// Serial.print(" OFF :");
currentgroup->State = false;
rgb = RgbColor(0,0,0);
if (_returnJSON) AddSucessToArray (array, response, F("off") ) ;
}
colourschanged = true;
}
//------------------------------------------------------
// HUE / SAT / BRI
//------------------------------------------------------
// To Do Colormode.....
bool hasHue{false}, hasBri{false}, hasSat{false};
uint16_t hue = currentgroup->Hue ;
uint8_t sat = currentgroup->Sat ;
uint8_t bri = currentgroup->Bri ;
if (root.containsKey("hue"))
{
hue = root["hue"];
String response = "/groups/" + groupID + "/state/hue"; // + onoff;
// Serial.print(" HUE -> ");
// Serial.print(hue);
// Serial.print(", ");
hasHue = true;
if (_returnJSON) AddSucessToArray (array, response, root["hue"] );
}
if (root.containsKey("sat"))
{
sat = root["sat"];
String response = "/groups/" + groupID + "/state/sat"; // + onoff;
// Serial.print(" SAT -> ");
// Serial.print(sat);
// Serial.print(", ");
hasSat = true;
if (_returnJSON) AddSucessToArray (array, response, root["sat"]);
}
if (root.containsKey("bri"))
{
bri = root["bri"];
String response = "/groups/" + groupID + "/state/bri"; // + onoff;
// Serial.print(" BRI -> ");
// Serial.print(bri);
// Serial.print(", ");
hasBri = true;
if (_returnJSON) AddSucessToArray (array, response, root["bri"]);
}
//------------------------------------------------------
// XY Color Space
//------------------------------------------------------
HueXYColor xy_instance;
bool hasXy{false};
if (root.containsKey("xy"))
{
xy_instance.x = root["xy"][0];
xy_instance.y = root["xy"][1];
currentgroup->xy = xy_instance;
// Serial.print(" XY (");
// Serial.print(xy_instance.x);
// Serial.print(",");
// Serial.print(xy_instance.y);
// Serial.print(") ");
hasXy = true;
if (_returnJSON) {
JsonObject& nestedObject = array.createNestedObject();
JsonObject& sucess = nestedObject.createNestedObject("success");
JsonArray& xyObject = sucess.createNestedArray("xy");
xyObject.add(xy_instance.x, 4); // 4 digits: "3.1415"
xyObject.add(xy_instance.y, 4); // 4 digits: "3.1415"
}
}
//------------------------------------------------------
// Ct Colour space
//------------------------------------------------------
if (root.containsKey("ct"))
{
}
//------------------------------------------------------
// Apply recieved Color data
//------------------------------------------------------
if (hasHue) currentgroup->Hue = hsb.H = hue;
if (hasBri) currentgroup->Sat = hsb.S = sat;
if (hasSat) currentgroup->Bri = hsb.B = bri;
if (hasHue || hasSat || hasBri) {
rgb = HUEhsb2rgb(hsb); // designed to handle philips hue RGB ALLOCATED FROM JSON REQUEST
currentgroup->xy = HUEhsb2xy(hsb); // COPYED TO LED STATE incase onother applciation requests colour
colourschanged = true;
} else if (hasXy) {
rgb = XYtorgb(xy_instance, bri); // set the color to return
hsb = xy2HUEhsb(xy_instance, bri); // converts for storage...
currentgroup->Hue = hsb.H; ///floor(hsb.H * 182.04 * 360.0);
currentgroup->Sat = hsb.S; //floor(hsb.S * 254);
currentgroup->Bri = hsb.B; // floor(hsb.B * 254);
colourschanged = true;