-
Notifications
You must be signed in to change notification settings - Fork 0
/
PhotonMasterRemote-7-0-0.cpp
3587 lines (3441 loc) · 111 KB
/
PhotonMasterRemote-7-0-0.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
/******************************************************/
// THIS IS A GENERATED FILE - DO NOT EDIT //
/******************************************************/
#line 1 "/Users/dont/Documents/Photon-Development/Photon-Master-Remote/PhotonMasterRemote-7-0-1/src/PhotonMasterRemote-7-0-0.ino"
/*
Master-Remote alarm system for Particle Photon
@file Alarm-Master.cpp
@author D. Thompson
@license GNU General Public License (see license.txt)
@version 7.0
Copyright (C) 2016 Donald Thompson, Raynham Engineering
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Version 7.0.2
* Redesign of remotes:
* configure has one set of sensors
* device.sys_id identifies which remote system sensor belongs to
* readSensor only reads sensor if it belongs to itself
*/
/* Version 7.0.0
* Redesign of devices:
* Use common set of devices for master and remotes
* upon config load set ??? based on master or remote
* master_idx is no longer needed..idx is same for master and remote
* Other changes to device_t ??
*
* Add new published messages to keep remotes up to date ??
*/
/* Particle Cloud published events:
* alarmState with name of new state any time state changes
*/
// To Do:
// a) fix sysState clearing to shut off blinking Status
// USE a timer in sysState
// Timer ext and in class cause build to fail
// b) fix multiple notifications upon alarm condition
// d) add i-button support as key and as config management
// e) add HTU21 humidity sensor support
// f) second 1-wire buss for i-button support (clear readint)
// or can we skip-rom to just read class 01 == i-button ??
// g) add ds thermometer support
#include "application.h"
#include <queue>
#include <list>
#include "Adafruit_MCP9808.h"
#include "OW.h"
#include "parms.h"
#include "util.h"
#include "sensor.h"
#include "math.h"
#include "stdlib.h"
#include "parse.h"
#include "weather.h"
void qoscallback(unsigned int messageid);
void remoteAlarm(const char *eventName, const char *data);
void remoteHandler(const char *eventName, const char *data);
void masterHandler(const char *eventName, const char *data);
void reset_handler();
void watchdog_reset();
void setup();
void loop();
void loop();
#line 66 "/Users/dont/Documents/Photon-Development/Photon-Master-Remote/PhotonMasterRemote-7-0-1/src/PhotonMasterRemote-7-0-0.ino"
#ifdef HARDWARE_WATCHDOG
#include "hwd.h"
#endif
#ifdef MQTT_REMOTES
#include "MQTT.h"
#endif
//STARTUP(System.enableFeature(FEATURE_RETAINED_MEMORY));
//retained uint8_t testcurState;
int ledStatus = SYSTEM_STATUS_PIN; //blink this LED at each loop pass
int ledNotice = SYSTEM_NOTIFICATION_PIN; //blink this LED at each notification
int trigger3 = TRIGGER_PIN;
int message_countdown = 0;
//#ifdef PHOTON_MASTER
//double temperatureF; remove // to publish
double temp_outside; // to publish
double temp_inside; // to publish
double temp_garage; // to publish
double temp_camper; // to publish
double gallonsO; // published oil gallons (demo)
double remote_temp; // published as temprmt
String stateA;
//#endif
#ifdef PHOTON_REMOTE
uint8_t remoteState;
uint8_t nextState;
char data[80];
String remoteData;
//String debugData = "testing";
int msgSeq = 0;
#endif
#ifdef MQTT_REMOTES
void callback(char* topic, byte* payload, unsigned int length);
/**
* if want to use IP address,
* byte server[] = { XXX,XXX,XXX,XXX };
* MQTT client(server, 1883, callback);
* want to use domain name,
* exp) iot.eclipse.org is Eclipse Open MQTT Broker: https://iot.eclipse.org/getting-start
ed
* MQTT client("mqtt.eclipse.org", 1883, callback);
* MQTT client("test.mosquitto.org", 1883, callback);
* my raspberry pi:
byte server[] = { 192,168,0,50 }; //rpi
MQTT client(server, 1883, callback);
*/
MQTT client("test.mosquitto.org", 1883, callback);
// for QoS2 MQTTPUBREL message.
// this messageid maybe have store list or array structure.
uint16_t qos2messageid = 0;
// recieve message
void callback(char* topic, byte* payload, unsigned int length) {
char p[length + 1];
memcpy(p, payload, length);
p[length] = NULL;
#ifdef SERIAL_DEBUG
Serial.print("MQTT data:");
Serial.println(p);
#endif
/*
if (!strcmp(p, "RED"))
RGB.color(255, 0, 0);
else if (!strcmp(p, "GREEN"))
RGB.color(0, 255, 0);
else if (!strcmp(p, "BLUE"))
RGB.color(0, 0, 255);
else
RGB.color(255, 255, 255);
delay(1000);
*/
}
// QOS ack callback.
// if application use QOS1 or QOS2, MQTT server sendback ack message id.
void qoscallback(unsigned int messageid) {
Serial.print("Ack Message Id:");
Serial.println(messageid);
}
#endif
//#ifdef HARDWARE_REQUIRED_MSCP9808
Adafruit_MCP9808 mcp9808;
//#endif
OW ow(0); //default 0 is 0x18 !!
// OW ow1(1); //NO! testing second ds2483 for iButtons
// iButton ib(1);
// we SHOULD make a specific iButton class, similar to OW
#include "state.h"
State sys;
// remote data stream parser
//constructor with data
Parse::Parse(String d) {
remotedata = d;
idx = 0;
parsePos = 0;
elementDelimiter = ELEMENT_DELIMITER;
endDelimiter = END_DELIMITER;
}
//constructor with data and delimiters
Parse::Parse(char elementd, char endd, String d) {
remotedata = d;
idx = 0;
parsePos = 0;
elementDelimiter = elementd;
endDelimiter = endd;
}
//set data to parse
void Parse::setData(String s) {
idx = 0;
parsePos = 0;
//remotedata.assign(s);
remotedata = String(s);
elementDelimiter = ELEMENT_DELIMITER;
endDelimiter = END_DELIMITER;
}
void Parse::setDelimiters(char d_element, char d_end) {
elementDelimiter = d_element;
endDelimiter = d_end;
}
//set data to parse with special delimiters
void Parse::setData(char elementd, char endd, String s) {
idx = 0;
parsePos = 0;
//remotedata.assign(s);
remotedata = String(s);
elementDelimiter = elementd;
endDelimiter = endd;
}
// get the input string
String Parse::getData() {
return remotedata;
}
int Parse::parseNext(int pos, int end) {
//char lastc;
if(pos) pos++;
element[idx] = remotedata.substring(pos, end);
idx++;
return idx;
}
//find position of next delimiter in remotedata
int Parse::findDelim(char delimiter, int start) {
parsePos = remotedata.indexOf(delimiter, start+1);
return parsePos;
}
String Parse::getElement(int idx) {
return element[idx];
}
//do parse into parsed_elementU
int Parse::doParse() {
int start = 0;
int end = 0;
int n;
for(n=0;n<MAX_PARSED_ITEMS;n++) {
end = findDelim(elementDelimiter, start);
if(end < 0) end = findDelim(endDelimiter, start);
if(end < 0) break;
parseNext(start,end);
start = end;
}
el4=element[4]; //kluge, [] gives error ?????
return n; // parsed n elements
}
#include "notifier.h"
// ADDED new member function to set status ?????
void Sensor::setDeviceStatus(device_t d, bool toPresent) {
if(toPresent)
d.status = DEV_PRESENT; //XXXXXXXXX
else
d.state = DEV_MISSING;
}
void Sensor::setDeviceActive(device_t *d, bool toActive) {
if(toActive)
d->state = SENSOR_ACTIVE;
else {
d->state = SENSOR_DISABLED;
if(d->dev_use >= FIRST_SUB_REMOTE) { //a REMOTE device
d->dev_reading = 0;
d->dev_last_read = 0;
d->tripped = FALSE;
d->reported = FALSE;
}
}
}
//------------------
void Sensor::setDeviceSense(device_t *d, uint8_t newSense) {
if(newSense <= 1)
d->sense= newSense;
}
void Sensor::setDeviceLevel(device_t *d, uint8_t newLevel) {
if(newLevel <= 2)
d->alert_level = newLevel;
//else message
}
//------------------
// set sensor indicator (on PIO_A)
void Sensor::setSensorIndicator(device_t d, uint8_t indval) {
#ifdef SERIAL_DEBUG_SEN
Serial.print("setting indicator:");
Serial.println(indval);
#endif
//#define PIO_A 0
//#define PIO_B 1
//d.port is the sensor read port
//indicator port is the other one ??
uint8_t indicator_port = d.port ? 0 : 1;
//debug
uint8_t op_value = indval ? 0 : 1;
#ifdef SERIAL_DEBUG_SEN
Serial.print("setSensorIndicator:port=");
Serial.print(d.port);
Serial.print(" indicator port=");
Serial.print(indicator_port);
Serial.print(" led=");
Serial.println(indval);
#endif
//debug: (2 lines)
//p_ow->writePIOtest(d.dev_rom, indicator_port, op_value); //WRITE TO PIO-x
//delay(500);
p_ow->writePIOtest(d.dev_rom, indicator_port, indval); //WRITE TO PIO-x
}
// return TRUE if tripped
// TO DO: FIX reading of MCP9808 master vs remote sensor
// master reads device, remote just returns dev_reading
// BUG: ?? dev_last_read not updating for SUB_REMOTE ???
// Prints SUB_REMOTE_SENSOR: ... on every loop ?????
bool Sensor::readSensor(device_t &d) {
uint8_t senval;
uint8_t prev_senval;
//uint8_t sensor_priority = 0; //reporting priority
double tempF;
//double oilL;
bool senret;
bool rok;
bool toSetSensor;
float reading;
// --------
if((REMOTE_SYSTEM_ID) && (d.sys_id != REMOTE_SYSTEM_ID)) {
#ifdef SERIAL_DEBUG_SENXXX
Serial.print("Device Not Ours:");
Serial.print(d.idx);
Serial.print(" :");
Serial.println(d.name);
#endif
return FALSE;
}
//--------
if(d.status != DEV_PRESENT) {
#ifdef SERIAL_DEBUG_SEN
Serial.print("Device Missing:");
Serial.print(d.idx);
Serial.print(" :");
Serial.println(d.name);
#endif
return FALSE;
}
if(d.state == SENSOR_DISABLED) {
#ifdef SERIAL_DEBUG_SEN
Serial.print("Device deactivated - ROM:");
Serial.println(d.dev_rom[7],HEX);
#endif
return FALSE;
}
d.changed = FALSE;
#ifdef SERIAL_DEBUG_SEN_READ
Serial.print("readSensor name=");
Serial.print(d.name);
Serial.print(" port=");
Serial.print(d.port);
Serial.print(" use=");
Serial.print(d.dev_use);
Serial.print(" master=");
Serial.println(d.master_idx);
#endif
switch(d.dev_use) {
case SWITCH: //USE IO_SENSOR
#ifdef SERIAL_DEBUG_SEN_READ
Serial.print("readSensor name=");
Serial.print(d.name);
Serial.print(" port=");
Serial.print(d.port);
Serial.print(" use=");
Serial.print(d.dev_use);
#endif
senval = digitalRead(d.port);
reading = (float)senval;
//move this out of switch
if(abs(d.dev_reading - reading) < 0.1) d.changed = TRUE;
d.dev_reading = reading;
d.dev_last_read = Time.now();
#ifdef SERIAL_DEBUG_SEN_READ
Serial.print(" readvalue=");
Serial.println(senval);
#endif
return senval==d.sense;
break;
case IO_SENSOR: //SAME AS SWITCH ??
// read hardware port d.dev_addr
prev_senval = d.dev_reading;
senval = digitalRead(d.port);
reading = (float)senval;
#ifdef SERIAL_DEBUG_SEN_READ
Serial.print("readSensor name=");
Serial.print(d.name);
Serial.print(" port=");
Serial.print(d.port);
Serial.print(" use=");
Serial.print(d.dev_use);
Serial.print(" sensel=");
Serial.print(d.sense);
Serial.print(" senval=");
Serial.print(senval);
Serial.print(" prev_senval=");
Serial.println(prev_senval);
#endif
d.changed = senval != prev_senval;
d.dev_reading = reading;
d.dev_last_read = Time.now();
senret = senval==d.sense;
#ifdef SERIAL_DEBUG_SEN_READ
if(d.changed) {
Serial.print("readSensor name=");
Serial.print(d.name);
Serial.print(" port=");
Serial.print(d.port);
Serial.print(" use=");
Serial.print(d.dev_use);
Serial.print(" sensel=");
Serial.print(d.sense);
Serial.print(" senval=");
Serial.print(senval);
Serial.print(" prev_senval=");
Serial.print(prev_senval);
Serial.print(" senret=");
Serial.print(senret);
Serial.print(" changed=");
Serial.println(d.changed);
}
#endif
return senret;
break;
case OW_SENSOR:
case OW_INDICATOR: //one-wire device on DS2482-100
senval = p_ow->readPIOX(d.dev_rom, d.port); //??just readPIO and use d.port
toSetSensor = (uint8_t)d.dev_reading != senval;
prev_senval = d.dev_reading;
reading = (float)senval;
d.changed = senval != prev_senval;
d.dev_reading = reading;
//............
d.dev_last_read = Time.now();
senret = senval==d.sense;
#ifdef SERIAL_DEBUG_SEN
if(d.changed) {
Serial.print("readSensor OW_SENSOR name=");
Serial.print(d.name);
Serial.print(" port=");
Serial.print(d.port);
Serial.print(" use=");
Serial.print(d.dev_use);
Serial.print(" sense=");
Serial.print(d.sense);
Serial.print(" senval=");
Serial.print(senval);
Serial.print(" prev_senval=");
Serial.print(prev_senval);
Serial.print(" senret=");
Serial.println(senret);
}
#endif
if(d.dev_use==OW_INDICATOR)
//if(toSetSensor) setSensorIndicator(d, senret);
#ifdef SERIAL_DEBUG_SEN
Serial.print("setSensorIndicator:");
Serial.println(d.idx);
#endif
setSensorIndicator(d, senret);
return senret;
break;
// TODO: Implement??
// This should set 'this' remote active, not just this one device
// Bug: it is NOT this device to set active
// how do we tell it what device ??
// use master_idx ??
case SUB_SET_DEVICE: // DESIGN: set remote active
if(d.dev_last_read > Time.now() - DEVICE_TIMEOUT) {
//if(Time.now - d.dev_last_read > DEVICE_TIIMEOUT) {
if(d.dev_reading > 0.5){
//DO WE REALLY WANT TO DO THIS??
//remote status is controlled by user / cmd RON / ROF ??
sys.setRemoteStatus(d.idx,TRUE);
// and send message it's set ???
//BUG:need alarm1 in scope ?????
//alarm1.tellRemote(d.master_idx,'R');
}
d.dev_reading = 0.0;
}
break;
case SUB_REMOTE_SENSOR:
// validat dev_last_read: DEVICE_TIMEOUT = 1/2 HR TOO long??
if(!sys.getRemoteStatus(d.master_idx)) return FALSE; //REMOTE not enabled (id??)
if(d.dev_last_read > Time.now() - DEVICE_TIMEOUT) {
senval = d.dev_reading;
senret = senval==d.sense;
#ifdef SERIAL_DEBUG_REMOTEXX
Serial.print("SUB_REMOTE_SENSOR: remotesys=");
Serial.print(d.master_idx);
Serial.print(" senretl=");
Serial.println(senret);
#endif
return senret;
}
else {
#ifdef SERIAL_DEBUG_SEN
Serial.println("SUB_REMOTE:time expired ");
#endif
return FALSE;
}
break;
case SUB_REMOTE_THERMOMETER:
if(!sys.getRemoteStatus(d.master_idx)) return FALSE; //REMOTE not enabled (id??)
if(d.dev_last_read > Time.now() - DEVICE_TIMEOUT) {
senval = d.dev_reading;
if(d.alert_max && (senval > d.alert_max)) return TRUE;
if(d.alert_min && (senval < d.alert_min)) return TRUE;
return FALSE;
}
else {
#ifdef SERIAL_DEBUG_SEN
Serial.println("SUB_REMOTE_TH:time expired ");
#endif
return FALSE;
}
break;
case SUB_OIL_GAUGE: //demo particle.subscribe value
//last_oil_level is updated by subscription
//d.dev_reading = last_oil_level;
if(d.dev_reading < -1000.0) return FALSE;
if(d.dev_last_read < Time.now() - DEVICE_TIMEOUT) {
d.dev_reading = -1001.0;
d.state=SENSOR_INACTIVE;
return FALSE;
}
if(d.alert_min !=0 && d.dev_reading <= d.alert_min)
return TRUE;
//sensor can trip based upon notification levels
//green condition = no notification or -1??
//yellow condition = 0
//red condition = priority = 1
return FALSE;
break;
case SUB_CAR_MONITOR: //sub-sensor via particle.subscribe value
//dev_reading is updated by subscription (remoteHandler)
// 1) temp received compared to max setting
if(d.dev_reading < -1000.0) return FALSE;
if(d.dev_last_read < Time.now() - DEVICE_TIMEOUT) {
d.dev_reading = -1001.0;
d.state=SENSOR_INACTIVE;
//notifier.queueMessage(SHORT_HEADER,1,"Car Monitor Inactive");
return FALSE;
}
if(d.alert_max !=0 && d.dev_reading >= d.alert_max)
return TRUE;
// 2) time-stamp of last data received
// 3) return TRUE if alert condition
return FALSE; // TO DO: alert if temp < ??
break;
//#ifdef HARDWARE_REQUIRED_MSCP9808
case MCP9808_THERMOMETER: //precision thermometer on I2C
// readTempF should use config parameters to get device info
// i.e. i2c address etc. This allows multiple devices on bus
last_temp = mcp9808.readTempF();
#ifdef SERIAL_DEBUG_SEN_READ
Serial.print("READ MCP...");
Serial.print(last_temp);
Serial.print(" dev:");
Serial.println(d.dev_reading);
#endif
reading=d.dev_reading;
d.dev_reading = last_temp;
d.dev_last_read = Time.now();
// return value should be tripped if outside temp range ??
// report using priority of sensor ??
//#endif
#ifdef PHOTON_REMOTE
//REPORT to mastert if temp changed
if(abs(last_temp - reading)>0.1) {
//Serial.println("temp diff!");
return TRUE;
}
#else
if((int)last_temp <= d.alert_min) return TRUE;
// readTemp should return an error condition ??
#endif
return FALSE;
break;
case OW_THERMOMETER: //ds1820 thermometer
#ifdef SERIAL_DEBUG_THERM
Serial.print("ds1820 testing-rom:");
for(int i=0;i<8;i++) {
Serial.print(d.dev_rom[i],HEX);
Serial.print("-");
}
Serial.println();
#endif
d.dev_reading = -999.0; //if read fails
rok = p_ow->readThermometer(d.dev_rom, tempF);
if(rok) {
d.dev_reading = tempF;
d.dev_last_read = Time.now();
#ifdef SERIAL_DEBUG_THERM
Serial.print("temp Fahrenheit x100:");
Serial.println((int)tempF*100);
#endif
if((int)tempF <= d.alert_min) return TRUE;
}
return FALSE; //not tripped
break;
default:
break;
}
return FALSE;
}
//clear changedSenbsors
void Sensor::clearChangedSensors() {
changedList.clear();
trippedSensor = FALSE;
}
//add sensor to changedList
void Sensor::addChangedSensor(device_t sp) {
changedList.push_back(sp);
trippedSensor = TRUE;
}
//are there any changed sensors?
bool Sensor::hasChangedSensor() {
return !changedList.empty();
}
//is any sensor tripped (or all clear)
bool Sensor::hasTrippedSensor() {
return trippedSensor;
}
// return formatted string of changedSensors
String Sensor::fmtChangedSensors() {
//FORMAT: @<sensor>^<sensor>^...<sensor>^$
// sensor: <name>:<master_idx>:<dev_reading>:<tripped>
std::list<device_t>::iterator k;
char tempbuf[30];
char changedbuf[100];
changedbuf[0]=0;
#ifdef SERIAL_DEBUG_SEN_READ
Serial.print("fmtChangedSensor: items=");
Serial.println(changedList.size());
#endif
for( k=changedList.begin(); k != changedList.end(); ++k) {
#ifdef SERIAL_DEBUG_SEN_READ
Serial.print("adding sensor: idx=");
Serial.print(k->idx);
Serial.print(" name=");
Serial.println(k->name);
#endif
strcat(changedbuf,"@");
strncat(changedbuf, k->name.c_str(), SENSOR_NAME_SIZE);
sprintf(tempbuf,":%d:%6.4f:%d^",k->master_idx,k->dev_reading,k->tripped); //<<??
strcat(changedbuf, tempbuf);
}
String changed = String(changedbuf);
return changed;
}
//REMOVE THIS...use readSensor()
float Sensor::readTemperature() {
// last_temp should be stored by sensor,
// part of sensor data ??
last_temp = 991.0;
//Bug: This should do readSensor() for define principal thermometer
//#ifdef HARDWARE_REQUIRED_MSCP9808
last_temp = mcp9808.readTempF();
//#endif
return last_temp;
}
float Sensor::getLastTemperature() {
return last_temp;
}
char* Sensor::romFormat(char *buf, uint8_t rom[]) {
char *bp = buf;
int n = 0;
for(int i=0;i<8;i++) {
bp = &buf[n];
int rb = rom[i];
if(rb<16) *bp++='0';
itoa((int)rb, bp, 16);
n+=2;
buf[n++]='-';
}
buf[n-1]=0;
return buf;
}
Sensor sensor(&ow);
// notify hours quiet hours, alarm does not
#include "checkin.h"
Weather weather;
Checkin checkin(alarm_saved_state.checkin_hours);
// How to load the webhooks ???
// for Raynham HOME
//Notifier notify("low_priority","shed_notice","shed_alarm","emergency", &sensor);
// for Henderson
Notifier notify("low_pri_hend","hend_notice","hend_alarm","hend_emerg", &sensor);
#include "alarm.h"
Alarm alarm1;
// lets make a special config class to handle EEPROM config
// allocate configuration with new and dealoc in destructor
// use instance of this class in Alarm routines which handle
// configuration. ???
Alarm::~Alarm(void) {
delete p_config;
}
//scan 1-wire bus and build configuration of devices found
//preserve data (use, name, etc. ) from existing configuration
//if device was previously present
bool Alarm::generateConfiguration() {
return true;
}
//update a specific device based upon user input changes (NAME)
bool Alarm::updateConfiguration(device_t* dev, int n) {
strncpy(configuration.name[n], dev->name.c_str(), SENSOR_NAME_SIZE);
EEPROM_writeAnything(CONFIGURATION_ADDRESS, configuration);
return true;
}
int Alarm::clearingCount() {
return clearing_cnt;
}
//return FALSE if some sensor still tripped
//return TRUE if all now clear
bool Alarm::clearSensorReported() {
// run thru sensor list and clear reporting if not tripped
// send error message if still tripped and leave reported
std::list<device_t>::iterator k;
bool all_clear = TRUE;
for(k=device_list.begin(); k != device_list.end(); ++k) {
//device_t sp = *k;
if(k->reported) {
if (k->tripped) {
all_clear = FALSE;
}
else
k->reported = FALSE;
}
}
return all_clear;
}
//move it to Alarm...
//read temperature sensor from device_list by index
//index must be > 0 (not first)
float Alarm::readTemperature(uint8_t idx) {
std::list<device_t>::iterator k;
float sen_temp = -999.0;
if(idx < 1) return 0.0;
for(k=device_list.begin(); k !=device_list.end(); ++k) {
if(k->idx != idx) continue;
//NOTE, for REMOTE device, readSensor does nothing, dev_reading is already set
//for actual device, MCP9808 device is read and dev_reading is updated
sensor.readSensor(*k);
sen_temp = k->dev_reading;
break;
}
return sen_temp;
}
String Alarm::getLastTemperature() {
return String(sensor.getLastTemperature());
}
uint8_t Alarm::getState() {
return curState;
}
uint8_t Alarm::getbaseState() {
return baseState;
}
//descriptive text of alarm state
String Alarm::getStateDescription(uint8_t st) {
String stateDescr = alarm_state_name_def[st];
if(curState == alarm_armed)
stateDescr = alarm_state_location_def[curLocation];
return stateDescr;
}
String Alarm::getStateDescription() {
return getStateDescription(curState);
}
// new set state based upon new conditions, state machine
// returns -1 if NO state change
int Alarm::setState() {
uint8_t new_state;
/* if alarm_disarmed ==> no change
* if any isTripped and not reported ==> alarm_armed
*/
//BUG..INCLUDE alarm_disarmed in else case, delete here
//need new pvt member baseState ??
//and method to return baseState
if(curState == alarm_off) return -1; //no change
if(isTripped()) {
//can't be all clear with a sensor tripped
if(isReported()) {
new_state = alarm_notifying;
prevTripState = FALSE;
clearing_cnt=0;
}
else
new_state = alarm_tripped;
}
else { //nothing tripped
if(allClear()) //nothing unacknowledged
new_state = baseState; //here use getbaseState()
else //still need to Acknowledge
//sensors all clear but events not Acknowledge
new_state = alarm_clearing;
}
if(curState == new_state) return -1;
#ifdef SERIAL_DEBUG_EVENT
Serial.print("setState() from:");
Serial.print(curState);
Serial.print(" to:");
Serial.println(new_state);
#endif
curState = new_state;
setStatusLED();
stateA = getStateDescription(curState);
Particle.publish("alarmState",stateA,60);
tellRemote(0,curState);
return curState;
}
// rewrite of setState(x)
bool Alarm::setState(uint8_t new_state) {
bool retval = FALSE;
if(curState == new_state) //NO State Change
return FALSE;
#ifdef SERIAL_DEBUG_EVENT
Serial.print("setState(x) to ");
Serial.print(alarm_state_name_def[new_state]);
Serial.print(" :curState =");
Serial.println(alarm_state_name_def[curState]);
#endif
if(new_state == alarm_disarmed || new_state == alarm_off) {
//don't allow if any sensor tripped -- trippedList.empty();
if(!trippedList.empty()) {
//send warning message about outstanding events --event_list.empty();
String msg="sensors tripped!";
notify.queueMessage(SHORT_HEADER,1,msg);
return FALSE;
}
if(!event_list.empty()) {
//message...
String msg = "Warning: unacknowledged events!";
notify.queueMessage(SHORT_HEADER,1,msg);
}
// curState = alarm_disarmed;
curState = new_state;
baseState = curState;
//then clear event_list
event_list.clear();
writeSavedState();
retval = TRUE; //???
}
else if(new_state == alarm_armed) {
curState = alarm_armed;
baseState = curState;
writeSavedState(); //write to eeprom
retval = TRUE;
}
else {
retval = FALSE;
}
setStatusLED();
stateA = getStateDescription(curState);
Particle.publish("alarmState",stateA,60);
//DESIGN: HERE WE need to publish masterdata for remotes:
//remote sysid to be zero (effect all remotes)
//format: <seq?>@<sysid>@<event>@<timestamp>$
//eg: 0@0@H@01:45:0000$
//do this in Alarm::tellRemote(curState);
tellRemote(0,curState);
return retval;
}
// set state of all remotes
void Alarm::setRemotes(uint8_t remotes) {
uint8_t rmask = remotes;
char rstate;
for(int i=0; i< 8; i++) {
if(rmask & 1) rstate = 'X';
else rstate = 'O';
tellRemote(i, rstate); //{O,X}
rmask << 1;
}
}
//update all remotes with new alarm state
void Alarm::tellRemote(uint8_t remoteid, char newstate) {
char data[20];
int msgseq=1; //FROM WHERE??
String time = Time.format("%H:%M:%S");
sprintf(data,"%d@%d@%c@%s$",msgseq++,remoteid,alarm_state_short[newstate],time.c_str());
String mData = String(data);
Particle.publish("masterdata",mData);
}
void Alarm::setStatusLED() {
switch(curState) {
case alarm_disarmed:
ledStatusState = 0;
ledStatusBlink = LED_OFF;
break;
case alarm_armed:
ledStatusState = 1;
ledStatusBlink = LED_SOLID;
break;
case alarm_notifying:
ledStatusState = 1;
ledStatusBlink = LED_FAST;
break;
case alarm_clearing:
ledStatusState = 1;
ledStatusBlink = LED_SLOW;
break;
default:
ledStatusState = 0;
ledStatusBlink = LED_OFF;
}
digitalWrite(ledStatus, ledStatusState);
}
//----------------------
#ifdef PHOTON_REMOTE
void Alarm::setLEDRemote(char rs) {
#ifdef SERIAL_DEBUG_REMOTE
Serial.print("setLEDRemote:");
Serial.println(rs);
#endif
//const char alarm_state_short[9] = {'F','D','A','T','N','C','R','X','O'};
switch(rs) {
case 'F': // System OFF
ledNoticeState = 0;
ledStatusState = 0;
ledStatusBlink = LED_OFF;
break;
case 'D': //DISARMED
ledStatusState = 0;
ledStatusBlink = LED_OFF;
break;
case 'H': //Home
case 'A': //Away
ledStatusState = 1;
ledStatusBlink = LED_SOLID;
break;
case 'T':
ledStatusState = 1;
ledStatusBlink = LED_FAST;
break;
case 'C':
case 'N':
ledStatusState = 1;
ledStatusBlink = LED_SLOW;
break;
case 'O': //Remote Off
ledNoticeState = 0;
break;
case 'X': //Remote On
ledNoticeState = 1;
break;
default:
ledStatusState = 0;
ledStatusBlink = LED_OFF;
}
digitalWrite(ledStatus, ledStatusState);
digitalWrite(ledNotice, ledNoticeState);
}
#endif
uint8_t Alarm::buildDeviceList() {
uint8_t dev_cnt = 0;
char nbuf[30]; //at least SENSOR_NAME_SIZE and SIZE for ROMHEX ??
if(configuration.magic != EE_MAGIC_CONFIG) return 0;
#ifdef SERIAL_DEBUG_CONFIG
Serial.println("buildDeviceList:");
#endif