forked from uzbhutta/XlightSmartController
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathxlSmartController.cpp
More file actions
3475 lines (3134 loc) · 95.7 KB
/
xlSmartController.cpp
File metadata and controls
3475 lines (3134 loc) · 95.7 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 "xliNodeConfig.h"
#include "xlxConfig.h"
#include "xlxLogger.h"
#include "xlxPanel.h"
#include "xlxRF24Server.h"
#include "xlxSerialConsole.h"
#include "xlxASRInterface.h"
#include "xlxBLEInterface.h"
#include "Adafruit_DHT.h"
#include "ArduinoJson.h"
#include "clickButton.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);
//MotionSensor senMotion(PIN_SEN_PIR);
// Ext. buttons
#ifdef DISABLE_BLE
#ifdef PIN_BTN_EXT_1
#define EN_BTN_EXT_1
ClickButton btnExt1(PIN_BTN_EXT_1, LOW, CLICKBTN_PULLUP);
#endif
#ifdef PIN_BTN_EXT_2
#define EN_BTN_EXT_2
ClickButton btnExt2(PIN_BTN_EXT_2, LOW, CLICKBTN_PULLUP);
#endif
#ifdef PIN_BTN_EXT_3
#define EN_BTN_EXT_3
ClickButton btnExt3(PIN_BTN_EXT_3, LOW, CLICKBTN_PULLUP);
#endif
#ifdef PIN_BTN_EXT_4
#define EN_BTN_EXT_4
ClickButton btnExt4(PIN_BTN_EXT_4, LOW, CLICKBTN_PULLUP);
#endif
#endif
//------------------------------------------------------------------
// Alarm Triggered Actions
//------------------------------------------------------------------
void AlarmTimerTriggered(uint32_t tag)
{
if( tag == 255 ) return;
uint8_t rule_uid = (uint8_t)tag;
SERIAL_LN("Rule %u Alarm Triggered", rule_uid);
//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;
}
// Execute the rule with init-flag
theSys.Execute_Rule(RuleRowptr, true);
}
//------------------------------------------------------------------
// Smart Controller Class
//------------------------------------------------------------------
SmartControllerClass::SmartControllerClass()
{
m_isRF = false;
m_isLAN = false;
m_isWAN = false;
m_loopKeyCode = 0;
m_tickLoopKeyCode = 0;
m_relaykeyflag = 0x00;
memset(m_mac,0,sizeof(m_mac));
}
// Primitive initialization before loading configuration
void SmartControllerClass::Init()
{
// Open Serial Port
TheSerial.begin(SERIALPORT_SPEED_DEFAULT);
#ifdef SYS_SERIAL_DEBUG
// Wait Serial connection so that we can see the starting information
while(!TheSerial.available()) {
if( Particle.connected() == true ) { Particle.process(); }
}
SERIAL_LN("SmartController is starting...");
#endif
// Get System ID
m_SysID = System.deviceID();
m_SysVersion = System.version();
m_SysStatus = STATUS_INIT;
// Initialize Logger
theLog.Init(m_SysID);
theLog.InitFlash(MEM_OFFLINE_DATA_OFFSET, MEM_OFFLINE_DATA_LEN);
#ifndef DISABLE_ASR
// Open ASR Interface
theASR.Init(SERIALPORT_SPEED_LOW);
#endif
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()
{
// Set NetworkID
while(theRadio.GetNetworkID() == 0) delay(50);
// Check RF2.4
if( CheckRF() ) {
if (IsRFGood())
{
LOGN(LOGTAG_MSG, "RF2.4 is working.");
SetStatus(STATUS_BMW);
}
}
#ifndef DISABLE_BLE
// Open BLE Interface
theBLE.Init(PIN_BLE_STATE, PIN_BLE_EN);
#endif
}
// Third level initialization after loading configuration
/// check LAN & WAN
void SmartControllerClass::InitNetwork()
{
BOOL oldWAN = IsWANGood();
BOOL oldLAN = IsLANGood();
// Check WAN and LAN
CheckNetwork();
if (IsWANGood())
{
if( !oldWAN ) { // Only log when status changed
LOGN(LOGTAG_EVENT, "WAN is working.");
SetStatus(STATUS_NWS);
}
// Initialize Logger: syslog & cloud log
// ToDo: substitude network parameters
//theLog.InitSysLog();
//theLog.InitCloud();
}
else if (IsLANGood())
{
if( !oldLAN ) { // Only log when status changed
LOGN(LOGTAG_EVENT, "LAN is working.");
SetStatus(STATUS_DIS);
}
}
else if (IsRFGood()) {
SetStatus(STATUS_BMW);
}
else {
SetStatus(STATUS_ERR);
}
}
// Initialize Pins: check the routine with PCB
void SmartControllerClass::InitPins()
{
// Workaround for Paricle Analog Pin mode problem
#ifndef MCU_TYPE_Particle
// 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
#ifndef DISABLE_BLE
// Set communication pin mode
pinMode(PIN_BLE_RX, INPUT);
pinMode(PIN_BLE_TX, OUTPUT);
#endif
// Init soft keys
#ifdef DISABLE_ASR
#ifdef PIN_SOFT_KEY_1
pinMode(PIN_SOFT_KEY_1, OUTPUT);
//pinSetFast(PIN_SOFT_KEY_1);
#endif
#ifdef PIN_SOFT_KEY_4
pinMode(PIN_SOFT_KEY_4, OUTPUT);
#endif
#endif
#ifdef PIN_SOFT_KEY_2
pinMode(PIN_SOFT_KEY_2, OUTPUT);
#endif
#ifdef PIN_SOFT_KEY_3
pinMode(PIN_SOFT_KEY_3, OUTPUT);
#endif
#ifdef EN_BTN_EXT_1
btnExt1.debounceTime = 30; // Debounce timer in ms
btnExt1.multiclickTime = 500; // Time limit for multi clicks
btnExt1.longClickTime = 2000; // time until "held-down clicks" register
#endif
#ifdef EN_BTN_EXT_2
btnExt2.debounceTime = 30; // Debounce timer in ms
btnExt2.multiclickTime = 500; // Time limit for multi clicks
btnExt2.longClickTime = 2000; // time until "held-down clicks" register
#endif
#ifdef EN_BTN_EXT_3
btnExt3.debounceTime = 30; // Debounce timer in ms
btnExt3.multiclickTime = 500; // Time limit for multi clicks
btnExt3.longClickTime = 2000; // time until "held-down clicks" register
#endif
#ifdef EN_BTN_EXT_4
btnExt4.debounceTime = 30; // Debounce timer in ms
btnExt4.multiclickTime = 500; // Time limit for multi clicks
btnExt4.longClickTime = 2000; // time until "held-down clicks" register
#endif
// Init Panel components
thePanel.InitPanel();
// Change Panel LED ring to indicate panel is working
thePanel.CheckLEDRing(2);
thePanel.CheckLEDRing(3);
}
// Initialize Sensors
void SmartControllerClass::InitSensors()
{
// DHT
if (theConfig.IsSensorEnabled(sensorDHT)) {
senDHT.begin();
LOGD(LOGTAG_MSG, "DHT sensor works.");
}
// Light
/*if (theConfig.IsSensorEnabled(sensorALS)) {
senLight.begin(SEN_LIGHT_MAX, SEN_LIGHT_MIN); // Reversed threshold
LOGD(LOGTAG_MSG, "Light sensor works.");
}*/
// Brightness indicator
// PIR
/*if (theConfig.IsSensorEnabled(sensorPIR)) {
senMotion.begin();
LOGD(LOGTAG_MSG, "Motion sensor works.");
}*/
// ToDo:
//...
}
void SmartControllerClass::InitCloudObj()
{
// Set cloud variable initial value
m_tzString = theConfig.GetTimeZoneJSON();
if( theConfig.GetUseCloud() != CLOUD_DISABLE ) {
CloudObjClass::InitCloudObj();
LOGN(LOGTAG_MSG, "Cloud Objects registered.");
}
}
// Get the controller started
BOOL SmartControllerClass::Start()
{
UC pre_relay_keys = theConfig.GetRelayKeys();
FindCurrentDevice();
LOGN(LOGTAG_MSG, "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());
#ifndef SYS_SERIAL_DEBUG
ResetSerialPort();
#endif
// Change Panel LED ring to the recent level
thePanel.SetDimmerValue(theConfig.GetBrightIndicator());
// Sync panel with dev-st
if( m_pMainDev ) {
// Set panel ring on or off
thePanel.SetRingOnOff(m_pMainDev->data.ring[0].State);
DevSoftSwitch(m_pMainDev->data.ring[0].State, CURRENT_DEVICE, CURRENT_SUBDEVICE);
// Set CCT or RGBW
if( IS_SUNNY(m_pMainDev->data.type) ) {
// Set CCT
thePanel.UpdateCCTValue(m_pMainDev->data.ring[0].CCT);
ChangeLampCCT(CURRENT_DEVICE, m_pMainDev->data.ring[0].CCT);
} else if( IS_RAINBOW(m_pMainDev->data.type) || IS_MIRAGE(m_pMainDev->data.type) ) {
// Rainbow or Mirage
// ToDo: set RGBW
}
}
// Restore relay key to previous state
theConfig.SetRelayKeys(pre_relay_keys);
relay_restore_keystate();
// Publish local the main device status
if( Particle.connected() == true ) {
UL tm = 0x4ff; // Delay 1.5s in order to publish
while(tm-- > 0){ Particle.process(); }
}
//QueryDeviceStatus(CURRENT_DEVICE);
// Request the main device to report status
RequestDeviceStatus(CURRENT_DEVICE);
// Acts on the Rules rules newly loaded from flash
ReadNewRules(true);
return true;
}
void SmartControllerClass::Restart()
{
theConfig.SaveConfig();
SetStatus(STATUS_RST);
delay(1000);
System.reset();
}
UC SmartControllerClass::GetStatus()
{
return (UC)m_SysStatus;
}
BOOL SmartControllerClass::SetStatus(UC st)
{
if( st > STATUS_ERR ) return false;
LOGN(LOGTAG_STATUS, "System status changed from %d to %d", m_SysStatus, st);
if ((UC)m_SysStatus != st) {
m_SysStatus = st;
}
return true;
}
void SmartControllerClass::GetMac(uint8_t *mac)
{
memcpy(mac,m_mac,sizeof(m_mac));
}
void SmartControllerClass::SetMac(uint8_t *mac)
{
memcpy(m_mac,mac,sizeof(m_mac));
}
// Connect to the Cloud
BOOL SmartControllerClass::connectCloud()
{
BOOL retVal = Particle.connected();
if( !retVal ) {
SERIAL("Cloud connecting...");
Particle.connect();
waitFor(Particle.connected, RTE_CLOUD_CONN_TIMEOUT);
retVal = Particle.connected();
SERIAL_LN("%s", retVal ? "OK" : "Failed");
}
return retVal;
}
// Connect Wi-Fi
BOOL SmartControllerClass::connectWiFi()
{
if( theConfig.GetDisableWiFi() ) return false;
BOOL retVal = WiFi.ready();
if( !retVal ) {
if( WiFi.hasCredentials() ) {
SERIAL("Wi-Fi connecting...");
WiFi.connect();
waitFor(WiFi.ready, RTE_WIFI_CONN_TIMEOUT);
retVal = WiFi.ready();
SERIAL_LN("%s", retVal ? "OK" : "Failed");
}
}
theConfig.SetWiFiStatus(retVal);
return retVal;
}
// Close and reopen serial port to avoid buffer overrun
void SmartControllerClass::ResetSerialPort()
{
TheSerial.end();
TheSerial.begin(SERIALPORT_SPEED_DEFAULT);
}
BOOL SmartControllerClass::CheckRF()
{
// RF Server begins
m_isRF = theRadio.ServerBegin(theConfig.GetRFChannel(), theConfig.GetRFPowerLevel(), theConfig.GetRFDataRate());
if( m_isRF ) {
// Change it if setting is not default value
//theRadio.setChannel(theConfig.GetRFChannel());
//theRadio.setPALevel(theConfig.GetRFPowerLevel());
//theRadio.setDataRate(theConfig.GetRFDataRate());
m_isRF = theRadio.CheckConfig();
}
return m_isRF;
}
// Check Wi-Fi module and connection
BOOL SmartControllerClass::CheckWiFi()
{
if( theConfig.GetDisableWiFi() ) return false;
if( WiFi.RSSI() > 0 ) {
m_isWAN = false;
m_isLAN = false;
LOGE(LOGTAG_MSG, "Wi-Fi chip error!");
return false;
}
if( !WiFi.ready() ) {
m_isWAN = false;
m_isLAN = false;
LOGE(LOGTAG_EVENT, "Wi-Fi module error!");
return false;
}
return true;
}
BOOL SmartControllerClass::CheckNetwork()
{
// Check Wi-Fi module
if( !CheckWiFi() ) {
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, "Cannot reach local gateway!");
m_isLAN = (WiFi.ping(WiFi.localIP(), 3) < 3);
if( !m_isLAN ) {
LOGE(LOGTAG_MSG, "Cannot reach itself!");
}
}
} else {
m_isLAN = true;
}
return true;
}
BOOL SmartControllerClass::SelfCheck(US ms)
{
static US tickSaveConfig = 0; // must be static
static US tickCheckRadio = 0; // must be static
static UC tickAcitveCheck = 0;
static UC tickWiFiOff = 0;
// Check all alarms. This triggers them.
Alarm.delay(ms);
// Save config if it was changed
if (++tickSaveConfig > 30000 / ms) { // once per 30 seconds
tickSaveConfig = 0;
theConfig.SaveConfig();
}
// Scan device list and check keepalive timeout
if( tickSaveConfig % (2000 / ms) == 0 ) { // every 2 second
CheckDevTimeout();
}
// Publish relay key status if changed
if( !theConfig.GetDisableWiFi() ) {
if( Particle.connected() ) PublishRelayKeyFlag();
}
// Slow Checking: once per 60 seconds
if (++tickCheckRadio > 60000 / ms) {
// Check RF module
++tickAcitveCheck;
tickCheckRadio = 0;
if( !IsRFGood() || !theRadio.CheckConfig() ) {
if( CheckRF() ) {
theRadio.switch2BaseNetwork();
delay(10);
theRadio.switch2MyNetwork();
LOGN(LOGTAG_MSG, "RF24 moudle recovered.");
}
} else {
// Try to send testing message
String strCmd = String::format("255:8");
theRadio.ProcessSend(strCmd);
}
// Check Network
if( !theConfig.GetDisableWiFi() ) {
if( theConfig.GetWiFiStatus() ) {
if( !IsWANGood() || tickAcitveCheck % 5 == 0 || GetStatus() == STATUS_DIS ) {
InitNetwork();
}
if( IsWANGood() ) { // WLAN is good
tickWiFiOff = 0;
if( !Particle.connected() ) {
// Cloud disconnected, try to recover
if( theConfig.GetUseCloud() != CLOUD_DISABLE ) {
connectCloud();
}
} else {
if( theConfig.GetUseCloud() == CLOUD_DISABLE ) {
Particle.disconnect();
}
}
} else { // WLAN is wrong
if( ++tickWiFiOff > 5 ) {
theConfig.SetWiFiStatus(false);
if( theConfig.GetUseCloud() == CLOUD_MUST_CONNECT ) {
SERIAL_LN("System is about to reset due to lost of network...");
Restart();
} else {
// Avoid keeping trying
LOGE(LOGTAG_MSG, "Turn off WiFi!");
WiFi.disconnect();
WiFi.off(); // In order to resume Wi-Fi, restart the application
}
}
}
} else if( WiFi.ready() ) {
theConfig.SetWiFiStatus(true);
}
// Daily Cloud Synchronization
/// TimeSync
theConfig.CloudTimeSync(false);
}
}
// Check System Status
if( GetStatus() == STATUS_ERR ) {
LOGE(LOGTAG_MSG, "System is about to reset due to STATUS_ERR...");
Restart();
}
// ToDo:add any other potential problems to check
//...
return true;
}
BOOL SmartControllerClass::CheckRFBaseNetEnableDur()
{
if( theConfig.GetMaxBaseNetworkDur() > 0 ) {
if( theRadio.getBaseNetworkDuration() > theConfig.GetMaxBaseNetworkDur() ) {
theRadio.enableBaseNetwork(false);
LOGI(LOGTAG_MSG, "RF base network enable timeout, disable it automatically");
return true;
}
}
return false;
}
BOOL SmartControllerClass::IsRFGood()
{
return (m_isRF && theRadio.isValid());
}
BOOL SmartControllerClass::IsBLEGood()
{
#ifndef DISABLE_BLE
return theBLE.isGood();
#else
return false;
#endif
}
BOOL SmartControllerClass::IsLANGood()
{
return m_isLAN;
}
BOOL SmartControllerClass::IsWANGood()
{
return m_isWAN;
}
// Process Local bridge commands
void SmartControllerClass::ProcessLocalCommands() {
// Check RF Message
//SERIAL_LN("PeekMessage...");
theRadio.PeekMessage();
//SERIAL_LN("PeekMessage end");
// Process RF2.4 messages
//SERIAL_LN("ProcessMQ...");
theRadio.ProcessMQ();
//SERIAL_LN("ProcessMQ end");
// Process Console Command
//SERIAL_LN("processCommand...");
theConsole.processCommand();
//SERIAL_LN("processCommand end");
#ifndef DISABLE_BLE
// Process BLE commands
theBLE.processCommand();
#endif
}
// Process all kinds of commands
void SmartControllerClass::ProcessCommands()
{
// Process Local Bridge Commands
ProcessLocalCommands();
#ifndef DISABLE_ASR
// Process ASR Command
theASR.processCommand();
#endif
// Process Cloud Commands
ProcessCloudCommands();
// ToDo: process commands from other sources (Wifi)
// ToDo: Potentially move ReadNewRules here
}
// Process Cloud Commands
void SmartControllerClass::ProcessCloudCommands()
{
String _cmd;
while( m_cmdList.size() ) {
_cmd = m_cmdList.shift();
ExeJSONCommand(_cmd);
}
while( m_configList.size() ) {
_cmd = m_configList.shift();
ExeJSONConfig(_cmd);
}
}
// 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_DHT_SPEED_NORMAL == 0)
blnReadALS = true;
}
if (theConfig.IsSensorEnabled(sensorPIR)) {
if (tick % SEN_DHT_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)) t = 255;
if (isnan(h)) h = 255;
UpdateDHT(0, t, h);
}
// Read from ALS
/*if (blnReadALS) {
UpdateBrightness(NODEID_GATEWAY, senLight.getLevel());
}*/
// Motion detection
/*if (blnReadPIR) {
UpdateMotion(NODEID_GATEWAY, 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
}
// Process panel operations, such as key press, knob rotation, etc.
bool SmartControllerClass::ProcessPanel()
{
// Process Panel Encoder
thePanel.ProcessEncoder();
return true;
}
//------------------------------------------------------------------
// Device Control Functions
//------------------------------------------------------------------
// Turn the switch of specific device and all devices on or off
/// Input parameters:
/// sw: true = on; false = off
/// hwsw: hardswitch or softswitch. 0 = soft, 1 = hard, 2 = auto
/// dev: device id or 0 (all devices under this controller)
/// subID: subID mask
int SmartControllerClass::DeviceSwitch(UC sw, UC hwsw, UC dev, const UC subID)
{
UC nKey = 0;
int rc = 0;
// Hard SW or Soft SW
if( hwsw == 1 || (hwsw == 2 && theConfig.GetHardwareSwitch()) ) {
// Lookup Key corresponding to given nid and subID
for( UC _code = 0; _code < MAX_KEY_MAP_ITEMS; _code++ ) {
if( theConfig.IsKeyMatchedItem(_code, dev, subID) ) {
nKey = _code + 1;
rc = DevHardSwitch(nKey, sw);
}
}
}
if( nKey == 0 ) rc = DevSoftSwitch(sw, dev, subID);
return rc;
}
int SmartControllerClass::DevSoftSwitch(UC sw, UC dev, const UC subID)
{
// Turn on hardswitch before turning softswitch on
if( sw > 0 ) {
MakeSureHardSwitchOn(dev, subID);
}
//String strCmd = String::format("%d;%d;%d;%d;%d;%d", dev, S_DIMMER, C_SET, 1, V_STATUS, (sw ? 1:0));
//ExecuteLightCommand(strCmd);
//ToDo: if dev = 0, go through list of devices
// ToDo:
//SetStatus();
String strCmd = String::format("%d:7:%d", dev, sw);
return theRadio.ProcessSend(strCmd, 0, subID);
}
int SmartControllerClass::DevHardSwitch(UC key, UC sw)
{
bool _st = (sw == DEVICE_SW_TOGGLE ? !relay_get_key(key) : sw == DEVICE_SW_ON);
relay_set_key(key, _st);
// Confirm On/Off
UC nID, subID;
nID = theConfig.GetKeyMapItem(key, &subID);
HardConfirmOnOff(nID, subID, _st);
return 1;
}
bool SmartControllerClass::HardConfirmOnOff(UC dev, const UC subID, const UC _st)
{
if( dev > 0 ) {
if( !IS_NOT_DEVICE_NODEID(dev) ) {
ConfirmLampOnOff(dev, _st);
}
// Set panel ring on or off
if( IS_CURRENT_DEVICE(dev) || (dev == NODEID_DUMMY && (subID == 0 || subID == CURRENT_SUBDEVICE)) ) {
thePanel.SetRingOnOff(_st);
if( m_pMainDev ) {
m_pMainDev->data.ring[0].State = _st;
m_pMainDev->data.ring[1].State = _st;
m_pMainDev->data.ring[2].State = _st;
m_pMainDev->data.run_flag = EXECUTED;
m_pMainDev->data.flash_flag = UNSAVED;
m_pMainDev->data.op_flag = POST;
theConfig.SetDSTChanged(true);
}
}
// Publish device status event
String strTemp;
if( subID > 0 ) strTemp = String::format("{'nd':%d,'sid':%d,'State':%d}", dev, subID, _st);
else strTemp = String::format("{'nd':%d,'State':%d}", dev, _st);
PublishDeviceStatus(strTemp.c_str());
return true;
}
return false;
}
bool SmartControllerClass::MakeSureHardSwitchOn(UC dev, const UC subID)
{
for( UC _code = 0; _code < MAX_KEY_MAP_ITEMS; _code++ ) {
if( theConfig.IsKeyMatchedItem(_code, dev, subID) ) {
if( !relay_get_key(_code + 1) ) {
relay_set_key(_code + 1, true);
}
}
}
if(theConfig.GetDisableLamp()) thePanel.SetRingOnOff(true);
return true;
}
bool SmartControllerClass::ToggleLoopHardSwitch()
{
bool bMoveKey = false;
if( m_loopKeyCode == 0 ) {
bMoveKey = ToggleAllHardSwitchs();
if( !bMoveKey ) m_tickLoopKeyCode = Time.now();
} else if( theConfig.IsKeyMapItemAvalaible(m_loopKeyCode - 1) ) {
if(relay_get_key(m_loopKeyCode)) {
// On -> Off
DevHardSwitch(m_loopKeyCode, false);
bMoveKey = true;
} else {
// Off -> On, stay at current relay key
DevHardSwitch(m_loopKeyCode, true);
m_tickLoopKeyCode = Time.now();
}
}
// Move to next avalaible relay key
if( bMoveKey && !IsLoopKeyCodeTimeout() ) {
do {
m_loopKeyCode++;
m_loopKeyCode %= (MAX_KEY_MAP_ITEMS + 1);
} while(!SetLoopKeyCode(m_loopKeyCode));
}
return bMoveKey;
}
bool SmartControllerClass::IsLoopKeyCodeTimeout()
{
if( m_tickLoopKeyCode == 0 ) return true;
if(theConfig.GetTimeLoopKC() > 0 ) {
return(Time.now() - m_tickLoopKeyCode >= theConfig.GetTimeLoopKC());
}
return false;
}
bool SmartControllerClass::ToggleAllHardSwitchs()
{
UC _sw = DEVICE_SW_TOGGLE;
for( UC _code = 0; _code < MAX_KEY_MAP_ITEMS; _code++ ) {
if( theConfig.IsKeyMapItemAvalaible(_code) ) {
if( _sw == DEVICE_SW_TOGGLE ) {
_sw = relay_get_key(_code + 1);
}
DevHardSwitch(_code + 1, _sw == false);
}
}
return(_sw == 1);
}
bool SmartControllerClass::relay_get_key(UC _key)
{
bool rc = FALSE;
UC keyID = 0;
if( _key >= '1' && _key <= '8' ) keyID = _key - '0';
else if( _key >= 1 && _key <= 8 ) keyID = _key;
if( keyID > 0 ) {
rc = theConfig.GetRelayKey(keyID - 1);
}
return rc;
}
bool SmartControllerClass::relay_set_key(UC _key, bool _on)
{
bool rc = FALSE;
UC keyID = 0;
//LOGD(LOGTAG_MSG, "relay set key=%d,onoff=%d",_key,_on);
if( _key >= '1' && _key <= '8' ) keyID = _key - '0';
else if( _key >= 1 && _key <= 8 ) keyID = _key;
if( keyID == 1 ) {
#ifdef DISABLE_ASR
#ifdef PIN_SOFT_KEY_1
// Trigger Relay PIN
digitalWrite(PIN_SOFT_KEY_1, _on ? HIGH : LOW);
//digitalWrite(PIN_SOFT_KEY_1, _on ? LOW : HIGH);
// Update bitmap
SetRelayKeyFlag(keyID - 1, _on);
rc = TRUE;
#endif
#endif
} else if( keyID == 2 ) {
#ifdef PIN_SOFT_KEY_2
// Trigger Relay PIN
digitalWrite(PIN_SOFT_KEY_2, _on ? HIGH : LOW);
// Update bitmap
SetRelayKeyFlag(keyID - 1, _on);
rc = TRUE;
#endif
} else if( keyID == 3 ) {
#ifdef PIN_SOFT_KEY_3
// Trigger Relay PIN
digitalWrite(PIN_SOFT_KEY_3, _on ? HIGH : LOW);
// Update bitmap
SetRelayKeyFlag(keyID - 1, _on);
rc = TRUE;
#endif
} else if( keyID == 4 ) {
#ifdef DISABLE_ASR
#ifdef PIN_SOFT_KEY_4
// Trigger Relay PIN
digitalWrite(PIN_SOFT_KEY_4, _on ? HIGH : LOW);
// Update bitmap
SetRelayKeyFlag(keyID - 1, _on);
rc = TRUE;
#endif
#endif
}
/*
// move to SelfCheck() due to conflict
if( rc ) {
String strTemp = String::format("{'km':%d,'on':%d}", keyID, _on);
PublishDeviceStatus(strTemp.c_str());
}
*/
return rc;
}
// Restore relay key to previous state
void SmartControllerClass::relay_restore_keystate()