-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathxlSmartController.cpp
More file actions
1770 lines (1562 loc) · 46.2 KB
/
xlSmartController.cpp
File metadata and controls
1770 lines (1562 loc) · 46.2 KB
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
/**
* xlSmartController.cpp - contains the major implementation of SmartController.
*
* Created by Baoshi Sun <bs.sun@datatellit.com>
* Copyright (C) 2015-2016 DTIT
* Full contributor list:
*
* Documentation:
* Support Forum:
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
*******************************
*
* REVISION HISTORY
* Version 1.0 - Created by Baoshi Sun <bs.sun@datatellit.com>
*
* DESCRIPTION
* 1.
*
* ToDo:
**/
#include "xlSmartController.h"
#include "xliPinMap.h"
#include "xlxConfig.h"
#include "xlxLogger.h"
#include "xlxRF24Server.h"
#include "xlxSerialConsole.h"
#include "Adafruit_DHT.h"
#include "ArduinoJson.h"
#include "LedLevelBar.h"
#include "LightSensor.h"
#include "MotionSensor.h"
#include "TimeAlarms.h"
//------------------------------------------------------------------
// Global Data Structures & Variables
//------------------------------------------------------------------
// make an instance for main program
SmartControllerClass theSys;
DHT senDHT(PIN_SEN_DHT, SEN_TYPE_DHT);
LightSensor senLight(PIN_SEN_LIGHT);
LedLevelBar indicatorBrightness(ledLBarProgress, 3);
MotionSensor senMotion(PIN_SEN_PIR);
//------------------------------------------------------------------
// Alarm Triggered Actions
//------------------------------------------------------------------
void AlarmTimerTriggered(uint32_t tag)
{
uint8_t rule_uid = (uint8_t)tag;
//search Rule table for matching UID
ListNode<RuleRow_t> *RuleRowptr = theSys.Rule_table.search(rule_uid);
if (RuleRowptr == NULL)
{
LOGE(LOGTAG_MSG, "Error, could not locate Rule Row corresponding to triggered Alarm ID");
return;
}
// read UIDs from Rule row
uint8_t SNT_uid = RuleRowptr->data.SNT_uid;
uint8_t node_id = RuleRowptr->data.node_id;
//get SNT_uid from rule rows and find
ListNode<ScenarioRow_t> *rowptr = theSys.SearchScenario(SNT_uid);
//ToDo: send rf
if (rowptr)
{
String ring1_payload = theSys.CreateColorPayload(1, rowptr->data.ring1.State, rowptr->data.ring1.CW, rowptr->data.ring1.WW, rowptr->data.ring1.R, rowptr->data.ring1.G, rowptr->data.ring1.B);
String ring2_payload = theSys.CreateColorPayload(2, rowptr->data.ring2.State, rowptr->data.ring2.CW, rowptr->data.ring2.WW, rowptr->data.ring2.R, rowptr->data.ring2.G, rowptr->data.ring2.B);
String ring3_payload = theSys.CreateColorPayload(3, rowptr->data.ring3.State, rowptr->data.ring3.CW, rowptr->data.ring3.WW, rowptr->data.ring3.R, rowptr->data.ring3.G, rowptr->data.ring3.B);
char buf[64];
sprintf(buf, "%d;%d;%d;%d;%d;%s", node_id, S_CUSTOM, C_SET, 1, V_STATUS, ring1_payload.c_str());
String ring1_cmd(buf);
theSys.ExecuteLightCommand(ring1_cmd);
sprintf(buf, "%d;%d;%d;%d;%d;%s", node_id, S_CUSTOM, C_SET, 1, V_STATUS, ring2_payload.c_str());
String ring2_cmd(buf);
theSys.ExecuteLightCommand(ring2_cmd);
sprintf(buf, "%d;%d;%d;%d;%d;%s", node_id, S_CUSTOM, C_SET, 1, V_STATUS, ring3_payload.c_str());
String ring3_cmd(buf);
theSys.ExecuteLightCommand(ring3_cmd);
}
else
{
LOGE(LOGTAG_MSG, "Could not change node:%d light's color, scenerio %d not found", node_id, SNT_uid);
return;
}
}
//------------------------------------------------------------------
// Smart Controller Class
//------------------------------------------------------------------
SmartControllerClass::SmartControllerClass()
{
m_isRF = false;
m_isBLE = false;
m_isLAN = false;
m_isWAN = false;
}
// Primitive initialization before loading configuration
void SmartControllerClass::Init()
{
// Open Serial Port
Serial.begin(SERIALPORT_SPEED_DEFAULT);
#ifdef SYS_SERIAL_DEBUG
// Wait Serial connection so that we can see the starting information
while(!Serial.available()) { Particle.process(); }
SERIAL_LN(F("SmartController is starting..."));
#endif
// Get System ID
m_SysID = System.deviceID();
m_SysVersion = System.version();
m_devStatus = STATUS_INIT;
// Initialize Logger
theLog.Init(m_SysID);
theLog.InitFlash(MEM_OFFLINE_DATA_OFFSET, MEM_OFFLINE_DATA_LEN);
LOGN(LOGTAG_MSG, "SmartController is starting...SysID=%s", m_SysID.c_str());
}
// Second level initialization after loading configuration
/// check RF2.4 & BLE
void SmartControllerClass::InitRadio()
{
// Check RF2.4
if( CheckRF() ) {
if (IsRFGood())
{
LOGN(LOGTAG_MSG, F("RF2.4 is working."));
SetStatus(STATUS_BMW);
}
}
// Check BLE
CheckBLE();
if (IsBLEGood())
{
LOGN(LOGTAG_MSG, F("BLE is working."));
}
}
// Third level initialization after loading configuration
/// check LAN & WAN
void SmartControllerClass::InitNetwork()
{
// Check WAN and LAN
if( CheckNetwork() )
{
if (IsWANGood())
{
LOGN(LOGTAG_MSG, F("WAN is working."));
SetStatus(STATUS_NWS);
// Initialize Logger: syslog & cloud log
// ToDo: substitude network parameters
//theLog.InitSysLog();
//theLog.InitCloud();
}
else if (GetStatus() == STATUS_BMW && IsLANGood())
{
LOGN(LOGTAG_MSG, F("LAN is working."));
SetStatus(STATUS_DIS);
}
}
}
// Initialize Pins: check the routine with PCB
void SmartControllerClass::InitPins()
{
// Set Panel pin mode
#ifdef MCU_TYPE_P1
pinMode(PIN_BTN_SETUP, INPUT);
pinMode(PIN_BTN_RESET, INPUT);
pinMode(PIN_LED_RED, OUTPUT);
pinMode(PIN_LED_GREEN, OUTPUT);
pinMode(PIN_LED_BLUE, OUTPUT);
#endif
// Workaround for Paricle Analog Pin mode problem
#ifndef MCU_TYPE_Particle
pinMode(PIN_BTN_UP, INPUT);
pinMode(PIN_BTN_OK, INPUT);
pinMode(PIN_BTN_DOWN, INPUT);
pinMode(PIN_ANA_WKP, INPUT);
// Set Sensors pin Mode
//pinModes are already defined in the ::begin() method of each sensor library, may need to be ommitted from here
pinMode(PIN_SEN_DHT, INPUT);
pinMode(PIN_SEN_LIGHT, INPUT);
pinMode(PIN_SEN_MIC, INPUT);
pinMode(PIN_SEN_PIR, INPUT);
#endif
// Brightness level indicator to LS138
pinMode(PIN_LED_LEVEL_B0, OUTPUT);
pinMode(PIN_LED_LEVEL_B1, OUTPUT);
pinMode(PIN_LED_LEVEL_B2, OUTPUT);
// Set communication pin mode
pinMode(PIN_BLE_RX, INPUT);
pinMode(PIN_BLE_TX, OUTPUT);
}
// Initialize Sensors
void SmartControllerClass::InitSensors()
{
// DHT
if (theConfig.IsSensorEnabled(sensorDHT)) {
senDHT.begin();
LOGD(LOGTAG_MSG, F("DHT sensor works."));
}
// Light
if (theConfig.IsSensorEnabled(sensorALS)) {
senLight.begin(SEN_LIGHT_MIN, SEN_LIGHT_MAX);
LOGD(LOGTAG_MSG, F("Light sensor works."));
}
// Brightness indicator
indicatorBrightness.configPin(0, PIN_LED_LEVEL_B0);
indicatorBrightness.configPin(1, PIN_LED_LEVEL_B1);
indicatorBrightness.configPin(2, PIN_LED_LEVEL_B2);
indicatorBrightness.setLevel(theConfig.GetBrightIndicator());
//PIR
if (theConfig.IsSensorEnabled(sensorPIR)) {
senMotion.begin();
LOGD(LOGTAG_MSG, F("Motion sensor works."));
}
// ToDo:
//...
}
void SmartControllerClass::InitCloudObj()
{
// Set cloud variable initial value
m_tzString = theConfig.GetTimeZoneJSON();
CloudObjClass::InitCloudObj();
LOGN(LOGTAG_MSG, F("Cloud Objects registered."));
}
// Get the controller started
BOOL SmartControllerClass::Start()
{
// ToDo:bring controller up along with all modules (RF, wifi, BLE)
LOGI(LOGTAG_MSG, F("SmartController started."));
LOGI(LOGTAG_MSG, "Product Info: %s-%s-%d",
theConfig.GetOrganization().c_str(), theConfig.GetProductName().c_str(), theConfig.GetVersion());
LOGI(LOGTAG_MSG, "System Info: %s-%s",
GetSysID().c_str(), GetSysVersion().c_str());
return true;
}
UC SmartControllerClass::GetStatus()
{
return (UC)m_devStatus;
}
void SmartControllerClass::SetStatus(UC st)
{
LOGN(LOGTAG_STATUS, F("System status changed from %d to %d"), m_devStatus, st);
if ((UC)m_devStatus != st)
m_devStatus = st;
}
BOOL SmartControllerClass::CheckRF()
{
// RF Server begins
m_isRF = theRadio.ServerBegin();
return m_isRF;
}
BOOL SmartControllerClass::CheckNetwork()
{
// Check Wi-Fi module
if( WiFi.RSSI() > 0 ) {
LOGE(LOGTAG_MSG, F("Wi-Fi chip error!"));
return false;
}
if( !WiFi.ready() ) {
LOGE(LOGTAG_MSG, F("Wi-Fi module error!"));
return false;
}
// Check WAN
m_isWAN = WiFi.resolve("www.google.com");
// Check LAN if WAN is not OK
if( !m_isWAN ) {
m_isLAN = (WiFi.ping(WiFi.gatewayIP(), 3) < 3);
if( !m_isLAN ) {
LOGW(LOGTAG_MSG, F("Cannot reach local gateway!"));
m_isLAN = (WiFi.ping(WiFi.localIP(), 3) < 3);
if( !m_isLAN ) {
LOGE(LOGTAG_MSG, F("Cannot reach itself!"));
}
}
} else {
m_isLAN = true;
}
return true;
}
BOOL SmartControllerClass::CheckBLE()
{
// ToDo: change value of m_isBLE
return true;
}
BOOL SmartControllerClass::SelfCheck(UL ms)
{
static UC tickSaveConfig = 0; // must be static
static UC tickCheckRadio = 0; // must be static
// Check all alarms. This triggers them.
Alarm.delay(ms);
// Save config if it was changed
if (++tickSaveConfig > 10) {
tickSaveConfig = 0;
theConfig.SaveConfig();
}
// Check RF module
if (++tickCheckRadio > 60) {
tickCheckRadio = 0;
if( !IsRFGood() ) {
if( CheckRF() ) {
LOGN(LOGTAG_MSG, F("RF24 module recovered."));
}
}
}
// ToDo:add any other potential problems to check
//...
return true;
}
BOOL SmartControllerClass::IsRFGood()
{
return (m_isRF && theRadio.isValid());
}
BOOL SmartControllerClass::IsBLEGood()
{
return m_isBLE;
}
BOOL SmartControllerClass::IsLANGood()
{
return m_isLAN;
}
BOOL SmartControllerClass::IsWANGood()
{
return m_isWAN;
}
// Process all kinds of commands
void SmartControllerClass::ProcessCommands()
{
// Check and process RF2.4 messages
//m_cmRF24.CheckMessageBuffer();
// Process Console Command
theConsole.processCommand();
// ToDo: process commands from other sources (Wifi, BLE)
// ToDo: Potentially move ReadNewRules here
}
// Collect data from all enabled sensors
/// use tick to control the collection speed of each sensor,
/// and avoid reading too many data in one loop
void SmartControllerClass::CollectData(UC tick)
{
BOOL blnReadDHT = false;
BOOL blnReadALS = false;
BOOL blnReadPIR = false;
switch (GetStatus()) {
case STATUS_DIS:
case STATUS_NWS: // Normal speed
if (theConfig.IsSensorEnabled(sensorDHT)) {
if (tick % SEN_DHT_SPEED_NORMAL == 0)
blnReadDHT = true;
}
if (theConfig.IsSensorEnabled(sensorALS)) {
if (tick % SEN_ALS_SPEED_NORMAL == 0)
blnReadALS = true;
}
if (theConfig.IsSensorEnabled(sensorPIR)) {
if (tick % SEN_PIR_SPEED_NORMAL == 0)
blnReadPIR = true;
}
break;
case STATUS_SLP: // Lower speed in sleep mode
if (theConfig.IsSensorEnabled(sensorDHT)) {
if (tick % SEN_DHT_SPEED_LOW == 0)
blnReadDHT = true;
}
if (theConfig.IsSensorEnabled(sensorALS)) {
if (tick % SEN_ALS_SPEED_LOW == 0)
blnReadALS = true;
}
if (theConfig.IsSensorEnabled(sensorPIR)) {
if (tick % SEN_PIR_SPEED_LOW == 0)
blnReadPIR = true;
}
break;
default:
return;
}
// Read from DHT
if (blnReadDHT) {
float t = senDHT.getTempCelcius();
float h = senDHT.getHumidity();
if (!isnan(t)) {
UpdateTemperature(t);
}
if (!isnan(h)) {
UpdateHumidity(h);
}
}
// Read from ALS
if (blnReadALS) {
UpdateBrightness(senLight.getLevel());
}
// Motion detection
if (blnReadPIR) {
UpdateMotion(senMotion.getMotion());
}
// Update json data and publish on to the cloud
if (blnReadDHT || blnReadALS || blnReadPIR) {
UpdateJSONData();
}
// ToDo: Proximity detection
// from all channels including Wi-Fi, BLE, etc. for MAC addresses and distance to device
}
//------------------------------------------------------------------
// Device Control Functions
//------------------------------------------------------------------
// Turn the switch of specific device and all devices on or off
/// Input parameters:
/// sw: true = on; false = off
/// dev: device id or 0 (all devices under this controller)
int SmartControllerClass::DevSoftSwitch(BOOL sw, UC dev)
{
// ToDo:
//SetStatus();
if (sw)
{
if (dev == 0)
{
//go through list of devices
//turn each on (rf)
//change devstatus
//change brightness indicatr
}
else
{
//turn off just dev
}
}
else
{
if (dev == 0)
{
//go through list of devices
//turn each off (rf)
//change devstatus
//change brightness
}
else
{
//turn off just dev
}
}
return 0;
}
// High speed system timer process
void SmartControllerClass::FastProcess()
{
// Refresh LED brightness indicator
indicatorBrightness.refreshLevelBar();
// ToDo:
}
//------------------------------------------------------------------
// Cloud interface implementation
//------------------------------------------------------------------
int SmartControllerClass::CldSetTimeZone(String tzStr)
{
// Parse JSON string
StaticJsonBuffer<COMMAND_JSON_SIZE> jsonBuf;
JsonObject& root = jsonBuf.parseObject((char *)tzStr.c_str());
if (!root.success())
return -1;
if (root.size() != 3) // Expected 3 KVPs
return -1;
// Set timezone id
if (!theConfig.SetTimeZoneID((US)root["id"]))
return 1;
// Set timezone offset
if (!theConfig.SetTimeZoneOffset((SHORT)root["offset"]))
return 2;
// Set timezone dst
if (!theConfig.SetTimeZoneOffset((UC)root["dst"]))
return 3;
return 0;
}
int SmartControllerClass::CldPowerSwitch(String swStr)
{
//fast, simple control
BOOL blnOn;
swStr.toLowerCase();
if (swStr == "0" || swStr == "off")
{
DevSoftSwitch(false); // Turn the switch off
return 1;
}
else if (swStr == "1" || swStr == "on")
{
DevSoftSwitch(true); // Turn the switch on
return 1;
}
}
// Execute Operations, including SerialConsole commands
/// Format: {type: '', cmd: ''}
int SmartControllerClass::CldJSONCommand(String jsonCmd)
{
SERIAL_LN("Received JSON cmd: %s", jsonCmd.c_str());
int rc = ProcessJSONString(jsonCmd);
if (rc < 0) {
// Error input
LOGE(LOGTAG_MSG, "Error parsing json cmd: %s", jsonCmd.c_str());
return 0;
} else if (rc > 0) {
// Wait for more...
return 1;
}
if (!(*m_jpCldCmd).containsKey("cmd"))
{
LOGE(LOGTAG_MSG, "Error json cmd format: %s", jsonCmd.c_str());
return 0;
}
const COMMAND strCmd = (COMMAND)(*m_jpCldCmd)["cmd"].as<int>();
//COMMAND 0: Use Serial Interface
if( strCmd == CMD_SERIAL) {
// Execute serial port command, and reflect results on cloud variable
if (!(*m_jpCldCmd).containsKey("data")) {
LOGE(LOGTAG_MSG, "Error json cmd format: %s", jsonCmd.c_str());
return 0;
}
if( !theConfig.IsCloudSerialEnabled() ) {
LOGN(LOGTAG_MSG, "Cloud serial command is not allowed. Check system config.");
return 0;
}
const char* strData = (*m_jpCldCmd)["data"];
theConsole.ExecuteCloudCommand(strData);
}
//COMMAND 1: Toggle light switch
if (strCmd == CMD_POWER) {
if (!(*m_jpCldCmd).containsKey("node_id") || !(*m_jpCldCmd).containsKey("state")) {
LOGE(LOGTAG_MSG, "Error json cmd format: %s", jsonCmd.c_str());
return 0;
}
const int node_id = (*m_jpCldCmd)["node_id"].as<int>();
const int state = (*m_jpCldCmd)["state"].as<int>();
char buf[64];
sprintf(buf, "%d;%d;%d;%d;%d;%d", node_id, S_DIMMER, C_SET, 1, V_STATUS, state);
String strCmd(buf);
ExecuteLightCommand(strCmd);
}
//COMMAND 2: Change light color
if (strCmd == CMD_COLOR) {
if (!(*m_jpCldCmd).containsKey("node_id") || !(*m_jpCldCmd).containsKey("ring") || !(*m_jpCldCmd).containsKey("color")) {
LOGE(LOGTAG_MSG, "Error json cmd format: %s", jsonCmd.c_str());
return 0;
}
const int node_id = (*m_jpCldCmd)["node_id"].as<int>();
const uint8_t ring = (*m_jpCldCmd)["ring"].as<int>();
const uint8_t State = (*m_jpCldCmd)["color"][0].as<uint8_t>();
const uint8_t CW = (*m_jpCldCmd)["color"][1].as<uint8_t>();
const uint8_t WW = (*m_jpCldCmd)["color"][2].as<uint8_t>();
const uint8_t R = (*m_jpCldCmd)["color"][3].as<uint8_t>();
const uint8_t G = (*m_jpCldCmd)["color"][4].as<uint8_t>();
const uint8_t B = (*m_jpCldCmd)["color"][5].as<uint8_t>();
String payload = CreateColorPayload(ring, State, CW, WW, R, G, B);
char buf[64];
sprintf(buf, "%d;%d;%d;%d;%d;%s", node_id, S_CUSTOM, C_SET, 1, V_VAR1, payload.c_str());
String strCmd(buf);
ExecuteLightCommand(strCmd);
}
//COMMAND 3: Change brightness
if (strCmd == CMD_BRIGHTNESS) {
if (!(*m_jpCldCmd).containsKey("node_id") || !(*m_jpCldCmd).containsKey("value")) {
LOGE(LOGTAG_MSG, "Error json cmd format: %s", jsonCmd.c_str());
return 0;
}
const int node_id = (*m_jpCldCmd)["node_id"].as<int>();
const int value = (*m_jpCldCmd)["value"].as<int>();
char buf[64];
sprintf(buf, "%d;%d;%d;%d;%d;%d", node_id, S_DIMMER, C_SET, 1, V_DIMMER, value);
String strCmd(buf);
ExecuteLightCommand(strCmd);
}
//COMMAND 4: Change color with scenerio input
if (strCmd == CMD_SCENARIO) {
if (!(*m_jpCldCmd).containsKey("node_id") || !(*m_jpCldCmd).containsKey("SNT_id")) {
LOGE(LOGTAG_MSG, "Error json cmd format: %s", jsonCmd.c_str());
return 0;
}
const int node_id = (*m_jpCldCmd)["node_id"].as<int>();
const int SNT_uid = (*m_jpCldCmd)["SNT_id"].as<int>();
//find hue data of the 3 rings
ListNode<ScenarioRow_t> *rowptr = SearchScenario(SNT_uid);
if (rowptr)
{
String ring1_payload = CreateColorPayload(1, rowptr->data.ring1.State, rowptr->data.ring1.CW, rowptr->data.ring1.WW, rowptr->data.ring1.R, rowptr->data.ring1.G, rowptr->data.ring1.B);
String ring2_payload = CreateColorPayload(2, rowptr->data.ring2.State, rowptr->data.ring2.CW, rowptr->data.ring2.WW, rowptr->data.ring2.R, rowptr->data.ring2.G, rowptr->data.ring2.B);
String ring3_payload = CreateColorPayload(3, rowptr->data.ring3.State, rowptr->data.ring3.CW, rowptr->data.ring3.WW, rowptr->data.ring3.R, rowptr->data.ring3.G, rowptr->data.ring3.B);
char buf[64];
sprintf(buf, "%d;%d;%d;%d;%d;%s", node_id, S_CUSTOM, C_SET, 1, V_VAR1, ring1_payload.c_str());
String ring1_cmd(buf);
ExecuteLightCommand(ring1_cmd);
sprintf(buf, "%d;%d;%d;%d;%d;%s", node_id, S_CUSTOM, C_SET, 1, V_VAR1, ring2_payload.c_str());
String ring2_cmd(buf);
ExecuteLightCommand(ring2_cmd);
sprintf(buf, "%d;%d;%d;%d;%d;%s", node_id, S_CUSTOM, C_SET, 1, V_VAR1, ring3_payload.c_str());
String ring3_cmd(buf);
ExecuteLightCommand(ring3_cmd);
}
else
{
LOGE(LOGTAG_MSG, "Could not change node:%d light's color, scenerio %d not found", node_id, SNT_uid);
return 0;
}
}
return 1;
}
int SmartControllerClass::CldJSONConfig(String jsonData) //future actions
{
//based on the input (ie whether it is a rule, scenario, or schedule), send the json string(s) to appropriate function.
//These functions are responsible for adding the item to the respective, appropriate Chain. If multiple json strings coming through,
//handle each for each respective Chain until end of incoming string
SERIAL_LN("Received JSON config message: %s", jsonData.c_str());
int numRows = 0;
bool bRowsKey = true;
int rc = ProcessJSONString(jsonData);
if (rc < 0) {
// Error input
LOGE(LOGTAG_MSG, "Error parsing json config message: %s", jsonData.c_str());
return 0;
} else if (rc > 0) {
// Wait for more...
//todo: temp, delete after
SERIAL_LN("AHHHHHHHHHHHHHHHHHHHH0 m_strCldCmd: %s", m_strCldCmd.c_str());
return 1;
}
if (!(*m_jpCldCmd).containsKey("rows"))
{
numRows = 1;
bRowsKey = false;
}
else
{
numRows = (*m_jpCldCmd)["rows"].as<int>();
}
int successCount = 0;
for (int j = 0; j < numRows; j++)
{
if (!bRowsKey)
{
if (ParseCmdRow(*m_jpCldCmd))
{
successCount++;
}
}
else
{
JsonObject& data = (*m_jpCldCmd)["data"][j];
if (ParseCmdRow(data))
{
successCount++;
}
}
}
LOGI(LOGTAG_MSG, "%d of %d rows were parsed correctly", successCount, numRows);
return successCount;
}
bool SmartControllerClass::ParseCmdRow(JsonObject& data)
{
bool isSuccess = true;
OP_FLAG op_flag = (OP_FLAG)data["op"].as<int>();
FLASH_FLAG flash_flag = (FLASH_FLAG)data["fl"].as<int>();
RUN_FLAG run_flag = (RUN_FLAG)data["run"].as<int>();
if (op_flag < GET || op_flag > DELETE)
{
LOGE(LOGTAG_MSG, "UID:%s Invalid HTTP command: %d", data["uid"], op_flag);
return 0;
}
if (op_flag != GET)
{
if (flash_flag != UNSAVED)
{
LOGE(LOGTAG_MSG, "UID:%s Invalid FLASH_FLAG", data["uid"]);
return 0;
}
if (run_flag != UNEXECUTED)
{
LOGE(LOGTAG_MSG, "UID:%s Invalid RUN_FLAG", data["uid"]);
return 0;
}
}
//grab first part of uid and store it in uidKey, and convert rest of uid string into int uidNum:
const char* uidWhole = data["uid"];
char uidKey = tolower(uidWhole[0]);
uint8_t uidNum = atoi(&uidWhole[1]);
switch(uidKey)
{
case CLS_RULE: //rule
{
RuleRow_t row;
row.op_flag = op_flag;
row.flash_flag = flash_flag;
row.run_flag = run_flag;
row.uid = uidNum;
row.SCT_uid = data["SCT_uid"];
row.SNT_uid = data["SNT_uid"];
row.notif_uid = data["notif_uid"];
isSuccess = Change_Rule(row);
if (!isSuccess)
{
LOGE(LOGTAG_MSG, "UID:%s Unable to write row to Rule_t", uidWhole);
return 0;
}
else
{
LOGI(LOGTAG_MSG, "UID:%s write row to Rule_t OK", uidWhole);
return 1;
}
break;
}
case CLS_SCHEDULE: //schedule
{
ScheduleRow_t row;
row.op_flag = op_flag;
row.flash_flag = flash_flag;
row.run_flag = run_flag;
row.uid = uidNum;
if (data["isRepeat"] == 1)
{
if (data["weekdays"] < 0 || data["weekdays"] > 7) // [0..7]
{
LOGE(LOGTAG_MSG, "UID:%s Invalid 'weekdays' must between 0 and 7", uidWhole);
return 0;
}
}
else if (data["isRepeat"] == 0)
{
if (data["weekdays"] < 1 || data["weekdays"] > 7) // [1..7]
{
LOGE(LOGTAG_MSG, "UID:%s Invalid 'weekdays' must between 1 and 7", uidWhole);
return 0;
}
}
else
{
LOGE(LOGTAG_MSG, "UID:%s Invalid 'isRepeat' must 0 or 1", uidWhole);
return 0;
}
if (data["hour"] < 0 || data["hour"] > 23)
{
LOGE(LOGTAG_MSG, "UID:%s Invalid 'hour' must between 0 and 23", uidWhole);
return 0;
}
if (data["min"] < 0 || data["min"] > 59)
{
LOGE(LOGTAG_MSG, "UID:%s Invalid 'min' must between 0 and 59", uidWhole);
return 0;
}
row.weekdays = data["weekdays"];
row.isRepeat = data["isRepeat"];
row.hour = data["hour"];
row.min = data["min"];
row.alarm_id = dtINVALID_ALARM_ID;
isSuccess = Change_Schedule(row);
if (!isSuccess)
{
LOGE(LOGTAG_MSG, "UID:%s Unable to write row to Schedule_t", uidWhole);
return 0;
}
else
{
LOGI(LOGTAG_MSG, "UID:%s write row to Schedule_t OK", uidWhole);
return 1;
}
break;
}
case CLS_SCENARIO: //scenario
{
ScenarioRow_t row;
row.op_flag = op_flag;
row.flash_flag = flash_flag;
row.run_flag = run_flag;
row.uid = uidNum;
// Copy JSON array to Hue
Array2Hue(data["ring1"], row.ring1);
Array2Hue(data["ring2"], row.ring2);
Array2Hue(data["ring3"], row.ring3);
row.filter = data["filter"];
isSuccess = Change_Scenario(row);
if (!isSuccess)
{
LOGE(LOGTAG_MSG, "UID:%s Unable to write row to Scenario_t", uidWhole);
return 0;
}
else
{
LOGI(LOGTAG_MSG, "UID:%s write row to Scenario_t OK", uidWhole);
return 1;
}
break;
}
default:
{
LOGE(LOGTAG_MSG, "UID:%s Invalid", uidWhole);
}
}
return 0;
}
//------------------------------------------------------------------
// Cloud Interface Action Types
//------------------------------------------------------------------
bool SmartControllerClass::Change_Rule(RuleRow_t row)
{
int index;
switch (row.op_flag)
{
case DELETE:
//search rules table for uid
index = Rule_table.search_uid(row.uid);
if (index == -1) //uid not found
{
//add row
if (!Rule_table.add(row))
{
LOGE(LOGTAG_MSG, "Error occured while adding Rule UID:%c%d", CLS_RULE, row.uid);
return false;
}
}
else //uid found
{
//update row
if (!Rule_table.set(index, row))
{
LOGE(LOGTAG_MSG, "Error occured while updating Rule UID:%c%d", CLS_RULE, row.uid);
return false;
}
}
break;
case POST:
case PUT:
//search rule table for uid
index = Rule_table.search_uid(row.uid);
if (index == -1) //uid not found
{
//add row
if (!Rule_table.add(row))
{
LOGE(LOGTAG_MSG, "Error occured while adding Rule UID:%c%d", CLS_RULE, row.uid);
return false;
}
if (row.op_flag == PUT)
{
LOGN(LOGTAG_MSG, "PUT found no updatable, Rule added UID:%c%d", CLS_RULE, row.uid);
}
}
else //uid found
{
//update row
if (!Rule_table.set(index, row))
{
LOGE(LOGTAG_MSG, "Error occured while updating Rule UID:%c%d", CLS_RULE, row.uid);
return false;
}
if (row.op_flag == POST)
{
LOGN(LOGTAG_MSG, "POST found duplicate row, overwriting UID:%c%d", CLS_RULE, row.uid);
}
}
break;
}
theConfig.SetRTChanged(true);
return true;
}
bool SmartControllerClass::Change_Schedule(ScheduleRow_t row)
{
int index;
switch (row.op_flag)
{
case DELETE:
//search schedule table for uid
index = Schedule_table.search_uid(row.uid);
if (index == -1) //uid not found