forked from opensprinklershop/OpenSprinkler-Firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsensors.cpp
3043 lines (2731 loc) · 83.6 KB
/
sensors.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
/* OpenSprinkler Unified (AVR/RPI/BBB/LINUX) Firmware
* Copyright (C) 2015 by Ray Wang ([email protected])
*
* Utility functions
* Sep 2022 @ OpenSprinklerShop
*
* 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/>.
*/
#include "sensors.h"
#include <stdlib.h>
#include "OpenSprinkler.h"
#ifdef ESP8266
#include "Wire.h"
#else
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <modbus/modbus.h>
#include <modbus/modbus-rtu.h>
#include <errno.h>
#endif
#include "defines.h"
#include "opensprinkler_server.h"
#include "program.h"
#include "sensor_mqtt.h"
#include "utils.h"
#include "weather.h"
#include "osinfluxdb.h"
#ifdef ADS1115
#include "sensor_ospi_ads1115.h"
#endif
#ifdef PCF8591
#include "sensor_ospi_pcf8591.h"
#endif
#define MAX_RS485_DEVICES 4
unsigned char findKeyVal(const char *str, char *strbuf, uint16_t maxlen, const char *key,
bool key_in_pgm = false, uint8_t *keyfound = NULL);
// All sensors:
static Sensor_t *sensors = NULL;
static time_t last_save_time = 0;
static boolean apiInit = false;
static Sensor_t *current_sensor = NULL;
// Boards:
static uint16_t asb_detected_boards = 0; // bit 1=0x48+0x49 bit 2=0x4A+0x4B usw
// Sensor URLS:
static SensorUrl_t *sensorUrls = NULL;
// Program sensor data
static ProgSensorAdjust_t *progSensorAdjusts = NULL;
// Monitor data
static Monitor_t *monitors = NULL;
// modbus transaction id
static uint16_t modbusTcpId = 0;
#ifdef ESP8266
static uint i2c_rs485_allocated[MAX_RS485_DEVICES];
#else
static modbus_t * ttyDevices[MAX_RS485_DEVICES];
#endif
const char *sensor_unitNames[]{
"", "%", "°C", "°F", "V", "%", "in",
"mm", "mph", "kmh", "%", "DK"
// 0 1 2 3 4 5 6 7 8 9 10, 11
// 0=Nothing
// 1=Soil moisture
// 2=degree celsius temperature
// 3=degree fahrenheit temperature
// 4=Volt V
// 5=Humidity %
// 6=Rain inch
// 7=Rain mm
// 8=Wind mph
// 9=Wind kmh
// 10=Level %
// 11=DK
};
uint8_t logFileSwitch[3] = {0, 0, 0}; // 0=use smaller File, 1=LOG1, 2=LOG2
// Weather
time_t last_weather_time = 0;
bool current_weather_ok = false;
double current_temp = 0.0;
double current_humidity = 0.0;
double current_precip = 0.0;
double current_wind = 0.0;
uint16_t CRC16(unsigned char buf[], int len) {
uint16_t crc = 0xFFFF;
for (int pos = 0; pos < len; pos++) {
crc ^= (uint16_t)buf[pos]; // XOR byte into least sig. byte of crc
for (int i = 8; i != 0; i--) { // Loop over each bit
if ((crc & 0x0001) != 0) { // If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
} else // Else LSB is not set
crc >>= 1; // Just shift right
}
}
// Note, this number has low and high bytes swapped, so use it accordingly (or
// swap bytes)
return crc;
} // End: CRC16
/**
* @brief detect connected boards
*
*/
void detect_asb_board() {
// detect analog sensor board, 0x48+0x49=Board1, 0x4A+0x4B=Board2
#if defined(ESP8266)
if (detect_i2c(ASB_BOARD_ADDR1a) && detect_i2c(ASB_BOARD_ADDR1b))
asb_detected_boards |= ASB_BOARD1;
if (detect_i2c(ASB_BOARD_ADDR2a) && detect_i2c(ASB_BOARD_ADDR2b))
asb_detected_boards |= ASB_BOARD2;
if (detect_i2c(RS485_TRUEBNER1_ADDR)) asb_detected_boards |= RS485_TRUEBNER1;
if (detect_i2c(RS485_TRUEBNER2_ADDR)) asb_detected_boards |= RS485_TRUEBNER2;
if (detect_i2c(RS485_TRUEBNER3_ADDR)) asb_detected_boards |= RS485_TRUEBNER3;
if (detect_i2c(RS485_TRUEBNER4_ADDR)) asb_detected_boards |= RS485_TRUEBNER4;
#endif
// Old, pre OSPi 1.43 analog inputs:
#if defined(PCF8591)
asb_detected_boards |= OSPI_PCF8591;
#endif
// New OSPi 1.6 analog inputs:
#if defined(ADS1115)
asb_detected_boards |= OSPI_ADS1115;
#endif
DEBUG_PRINT("ASB DETECT=");
DEBUG_PRINTLN(asb_detected_boards);
for (int log = 0; log <= 2; log++) {
checkLogSwitch(log);
#if defined(ENABLE_DEBUG)
DEBUG_PRINT("log=");
DEBUG_PRINTLN(log);
const char *f1 = getlogfile(log);
DEBUG_PRINT("logfile1=");
DEBUG_PRINTLN(f1);
DEBUG_PRINT("size1=");
DEBUG_PRINTLN(file_size(f1));
const char *f2 = getlogfile2(log);
DEBUG_PRINT("logfile2=");
DEBUG_PRINTLN(f2);
DEBUG_PRINT("size2=");
DEBUG_PRINTLN(file_size(f2));
#endif
}
}
uint16_t get_asb_detected_boards() { return asb_detected_boards; }
/*
* init sensor api and load data
*/
void sensor_api_init(boolean detect_boards) {
apiInit = true;
if (detect_boards)
detect_asb_board();
sensor_load();
prog_adjust_load();
sensor_mqtt_init();
monitor_load();
#ifndef ESP8266
//Read rs485 file. Details see below
std::ifstream file;
file.open("rs485", std::ifstream::in);
if (!file.fail()) {
std::string tty;
int idx = 0;
int n = 0;
DEBUG_PRINTLN(F("Opening USB RS485 Adapters:"));
while (std::getline(file, tty)) {
modbus_t * ctx = modbus_new_rtu(tty.c_str(), 9600, 'E', 8, 1);
DEBUG_PRINT(idx);
DEBUG_PRINT(": ");
DEBUG_PRINTLN(tty.c_str());
//unavailable on Raspi? modbus_enable_quirks(ctx, MODBUS_QUIRK_MAX_SLAVE);
modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS485);
modbus_rtu_set_rts(ctx, MODBUS_RTU_RTS_NONE); // we use auto RTS function by the HAT
modbus_set_response_timeout(ctx, 1, 500000); // 1.5s
if (modbus_connect(ctx) == -1) {
modbus_free(ctx);
} else {
n++;
ttyDevices[idx] = ctx;
asb_detected_boards |= OSPI_USB_RS485;
#ifdef ENABLE_DEBUG
modbus_set_debug(ctx, TRUE);
DEBUG_PRINTLN(F("DEBUG ENABLED"));
#endif
}
idx++;
if (idx >= MAX_RS485_DEVICES)
break;
}
DEBUG_PRINT(F("Found "));
DEBUG_PRINT(n);
DEBUG_PRINTLN(F(" RS485 Adapters"));
}
#endif
}
void sensor_save_all() {
sensor_save();
prog_adjust_save();
SensorUrl_save();
monitor_save();
#ifndef ESP8266
for (int i = 0; i < MAX_RS485_DEVICES; i++) {
if (ttyDevices[i]) {
modbus_close(ttyDevices[i]);
modbus_free(ttyDevices[i]);
}
ttyDevices[i] = NULL;
}
#endif
}
/**
* @brief Unload sensorapi from memory, free everything. Be sure that you have save all before
*
*/
void sensor_api_free() {
apiInit = false;
os.mqtt.setCallback(2, NULL);
while (progSensorAdjusts) {
ProgSensorAdjust_t* next = progSensorAdjusts->next;
delete progSensorAdjusts;
progSensorAdjusts = next;
}
while (sensorUrls) {
SensorUrl_t* next = sensorUrls->next;
free(sensorUrls->urlstr);
delete sensorUrls;
sensorUrls = next;
}
while (monitors) {
Monitor_t* next = monitors->next;
delete monitors;
monitors = next;
}
while (sensors) {
Sensor_t* next = sensors->next;
delete sensors;
sensors = next;
}
modbusTcpId = 0;
#ifdef ESP8266
memset(i2c_rs485_allocated, 0, sizeof(i2c_rs485_allocated));
#endif
}
/*
* get list of all configured sensors
*/
Sensor_t *getSensors() { return sensors; }
/**
* @brief delete a sensor
*
* @param nr
*/
int sensor_delete(uint nr) {
Sensor_t *sensor = sensors;
Sensor_t *last = NULL;
while (sensor) {
if (sensor->nr == nr) {
if (last == NULL)
sensors = sensor->next;
else
last->next = sensor->next;
delete sensor;
sensor_save();
return HTTP_RQT_SUCCESS;
}
last = sensor;
sensor = sensor->next;
}
return HTTP_RQT_NOT_RECEIVED;
}
/**
* @brief define or insert a sensor
*
* @param nr > 0
* @param type > 0 add/modify, 0=delete
* @param group group assignment
* @param ip
* @param port
* @param id
*/
int sensor_define(uint nr, const char *name, uint type, uint group, uint32_t ip,
uint port, uint id, uint ri, int16_t factor, int16_t divider,
const char *userdef_unit, int16_t offset_mv, int16_t offset2,
SensorFlags_t flags, int16_t assigned_unitid) {
if (nr == 0 || type == 0) return HTTP_RQT_NOT_RECEIVED;
if (ri < 10) ri = 10;
DEBUG_PRINTLN(F("server_define"));
Sensor_t *sensor = sensors;
Sensor_t *last = NULL;
while (sensor) {
if (sensor->nr == nr) { // Modify existing
sensor->type = type;
sensor->group = group;
strncpy(sensor->name, name, sizeof(sensor->name) - 1);
sensor->ip = ip;
sensor->port = port;
sensor->id = id;
sensor->read_interval = ri;
sensor->factor = factor;
sensor->divider = divider;
sensor->offset_mv = offset_mv;
sensor->offset2 = offset2;
strncpy(sensor->userdef_unit, userdef_unit,
sizeof(sensor->userdef_unit) - 1);
sensor->flags = flags;
if (assigned_unitid >= 0) sensor->assigned_unitid = assigned_unitid;
else sensor->assigned_unitid = 0;
sensor_save();
return HTTP_RQT_SUCCESS;
}
if (sensor->nr > nr) break;
last = sensor;
sensor = sensor->next;
}
DEBUG_PRINTLN(F("server_define2"));
// Insert new
Sensor_t *new_sensor = new Sensor_t;
memset(new_sensor, 0, sizeof(Sensor_t));
new_sensor->nr = nr;
new_sensor->type = type;
new_sensor->group = group;
strncpy(new_sensor->name, name, sizeof(new_sensor->name) - 1);
new_sensor->ip = ip;
new_sensor->port = port;
new_sensor->id = id;
new_sensor->read_interval = ri;
new_sensor->factor = factor;
new_sensor->divider = divider;
new_sensor->offset_mv = offset_mv;
new_sensor->offset2 = offset2;
strncpy(new_sensor->userdef_unit, userdef_unit,
sizeof(new_sensor->userdef_unit) - 1);
new_sensor->flags = flags;
if (assigned_unitid >= 0) new_sensor->assigned_unitid = assigned_unitid;
else new_sensor->assigned_unitid = 0;
if (last) {
new_sensor->next = last->next;
last->next = new_sensor;
} else {
new_sensor->next = sensors;
sensors = new_sensor;
}
sensor_save();
return HTTP_RQT_SUCCESS;
}
int sensor_define_userdef(uint nr, int16_t factor, int16_t divider,
const char *userdef_unit, int16_t offset_mv,
int16_t offset2, int16_t assigned_unitid) {
Sensor_t *sensor = sensor_by_nr(nr);
if (!sensor) return HTTP_RQT_NOT_RECEIVED;
sensor->factor = factor;
sensor->divider = divider;
sensor->offset_mv = offset_mv;
sensor->offset2 = offset2;
sensor->assigned_unitid = assigned_unitid;
if (userdef_unit)
strncpy(sensor->userdef_unit, userdef_unit,
sizeof(sensor->userdef_unit) - 1);
else
memset(sensor->userdef_unit, 0, sizeof(sensor->userdef_unit));
return HTTP_RQT_SUCCESS;
}
/**
* @brief initial load stored sensor definitions
*
*/
void sensor_load() {
// DEBUG_PRINTLN(F("sensor_load"));
sensors = NULL;
current_sensor = NULL;
if (!file_exists(SENSOR_FILENAME)) return;
ulong pos = 0;
Sensor_t *last = NULL;
while (true) {
Sensor_t *sensor = new Sensor_t;
memset(sensor, 0, sizeof(Sensor_t));
file_read_block(SENSOR_FILENAME, sensor, pos, SENSOR_STORE_SIZE);
if (!sensor->nr || !sensor->type) {
delete sensor;
break;
}
if (!last)
sensors = sensor;
else
last->next = sensor;
last = sensor;
sensor->flags.data_ok = false;
sensor->next = NULL;
pos += SENSOR_STORE_SIZE;
}
SensorUrl_load();
last_save_time = os.now_tz();
}
/**
* @brief Store sensor data
*
*/
void sensor_save() {
if (!apiInit) return;
DEBUG_PRINTLN(F("sensor_save"));
if (file_exists(SENSOR_FILENAME_BAK)) remove_file(SENSOR_FILENAME_BAK);
if (file_exists(SENSOR_FILENAME))
rename_file(SENSOR_FILENAME, SENSOR_FILENAME_BAK);
ulong pos = 0;
Sensor_t *sensor = sensors;
while (sensor) {
file_write_block(SENSOR_FILENAME, sensor, pos, SENSOR_STORE_SIZE);
sensor = sensor->next;
pos += SENSOR_STORE_SIZE;
}
last_save_time = os.now_tz();
DEBUG_PRINTLN(F("sensor_save2"));
current_sensor = NULL;
}
uint sensor_count() {
// DEBUG_PRINTLN(F("sensor_count"));
Sensor_t *sensor = sensors;
uint count = 0;
while (sensor) {
count++;
sensor = sensor->next;
}
return count;
}
Sensor_t *sensor_by_nr(uint nr) {
// DEBUG_PRINTLN(F("sensor_by_nr"));
Sensor_t *sensor = sensors;
while (sensor) {
if (sensor->nr == nr) return sensor;
sensor = sensor->next;
}
return NULL;
}
Sensor_t *sensor_by_idx(uint idx) {
// DEBUG_PRINTLN(F("sensor_by_idx"));
Sensor_t *sensor = sensors;
uint count = 0;
while (sensor) {
if (count == idx) return sensor;
count++;
sensor = sensor->next;
}
return NULL;
}
// LOGGING METHODS:
/**
* @brief getlogfile name
*
* @param log
* @return const char*
*/
const char *getlogfile(uint8_t log) {
uint8_t sw = logFileSwitch[log];
switch (log) {
case LOG_STD:
return sw < 2 ? SENSORLOG_FILENAME1 : SENSORLOG_FILENAME2;
case LOG_WEEK:
return sw < 2 ? SENSORLOG_FILENAME_WEEK1 : SENSORLOG_FILENAME_WEEK2;
case LOG_MONTH:
return sw < 2 ? SENSORLOG_FILENAME_MONTH1 : SENSORLOG_FILENAME_MONTH2;
}
return "";
}
/**
* @brief getlogfile name2 (opposite file)
*
* @param log
* @return const char*
*/
const char *getlogfile2(uint8_t log) {
uint8_t sw = logFileSwitch[log];
switch (log) {
case 0:
return sw < 2 ? SENSORLOG_FILENAME2 : SENSORLOG_FILENAME1;
case 1:
return sw < 2 ? SENSORLOG_FILENAME_WEEK2 : SENSORLOG_FILENAME_WEEK1;
case 2:
return sw < 2 ? SENSORLOG_FILENAME_MONTH2 : SENSORLOG_FILENAME_MONTH1;
}
return "";
}
void checkLogSwitch(uint8_t log) {
if (logFileSwitch[log] == 0) { // Check file size, use smallest
ulong logFileSize1 = file_size(getlogfile(log));
ulong logFileSize2 = file_size(getlogfile2(log));
if (logFileSize1 < logFileSize2)
logFileSwitch[log] = 1;
else
logFileSwitch[log] = 2;
}
}
void checkLogSwitchAfterWrite(uint8_t log) {
ulong size = file_size(getlogfile(log));
if ((size / SENSORLOG_STORE_SIZE) >= MAX_LOG_SIZE) { // switch logs if max reached
if (logFileSwitch[log] == 1)
logFileSwitch[log] = 2;
else
logFileSwitch[log] = 1;
remove_file(getlogfile(log));
}
}
bool sensorlog_add(uint8_t log, SensorLog_t *sensorlog) {
#if defined(ESP8266)
if (checkDiskFree()) {
#endif
DEBUG_PRINT(F("sensorlog_add "));
DEBUG_PRINT(log);
checkLogSwitch(log);
file_append_block(getlogfile(log), sensorlog, SENSORLOG_STORE_SIZE);
checkLogSwitchAfterWrite(log);
DEBUG_PRINT(F("="));
DEBUG_PRINTLN(sensorlog_filesize(log));
return true;
#if defined(ESP8266)
}
return false;
#endif
}
bool sensorlog_add(uint8_t log, Sensor_t *sensor, ulong time) {
if (sensor->flags.data_ok && sensor->flags.log && time > 1000) {
if (log == LOG_STD)
add_influx_data(sensor);
// Write to log file only if necessary
if (time-sensor->last_logged_time > 86400 || abs(sensor->last_data - sensor->last_logged_data) > 0.00999) {
SensorLog_t sensorlog;
memset(&sensorlog, 0, sizeof(SensorLog_t));
sensorlog.nr = sensor->nr;
sensorlog.time = time;
sensorlog.native_data = sensor->last_native_data;
sensorlog.data = sensor->last_data;
sensor->last_logged_data = sensor->last_data;
sensor->last_logged_time = time;
if (!sensorlog_add(log, &sensorlog)) {
sensor->flags.log = 0;
return false;
}
}
return true;
}
return false;
}
ulong sensorlog_filesize(uint8_t log) {
// DEBUG_PRINT(F("sensorlog_filesize "));
checkLogSwitch(log);
ulong size = file_size(getlogfile(log)) + file_size(getlogfile2(log));
// DEBUG_PRINTLN(size);
return size;
}
ulong sensorlog_size(uint8_t log) {
// DEBUG_PRINT(F("sensorlog_size "));
ulong size = sensorlog_filesize(log) / SENSORLOG_STORE_SIZE;
// DEBUG_PRINTLN(size);
return size;
}
void sensorlog_clear_all() { sensorlog_clear(true, true, true); }
void sensorlog_clear(bool std, bool week, bool month) {
DEBUG_PRINTLN(F("sensorlog_clear "));
DEBUG_PRINT(std);
DEBUG_PRINT(week);
DEBUG_PRINT(month);
if (std) {
remove_file(SENSORLOG_FILENAME1);
remove_file(SENSORLOG_FILENAME2);
logFileSwitch[LOG_STD] = 1;
}
if (week) {
remove_file(SENSORLOG_FILENAME_WEEK1);
remove_file(SENSORLOG_FILENAME_WEEK2);
logFileSwitch[LOG_WEEK] = 1;
}
if (month) {
remove_file(SENSORLOG_FILENAME_MONTH1);
remove_file(SENSORLOG_FILENAME_MONTH2);
logFileSwitch[LOG_MONTH] = 1;
}
}
ulong sensorlog_clear_sensor(uint sensorNr, uint8_t log, bool use_under,
double under, bool use_over, double over, time_t before, time_t after) {
SensorLog_t sensorlog;
checkLogSwitch(log);
const char *flast = getlogfile2(log);
const char *fcur = getlogfile(log);
ulong size = file_size(flast) / SENSORLOG_STORE_SIZE;
ulong size2 = size + file_size(fcur) / SENSORLOG_STORE_SIZE;
const char *f;
ulong idxr = 0;
ulong n = 0;
DEBUG_PRINTLN(F("clearlog1"));
DEBUG_PRINTF("nr: %d log: %d under:%lf over: %lf before: %lld after: %lld size: %ld size2: %ld\n", sensorNr, log, under, over, before, after, size, size2);
while (idxr < size2) {
ulong idx = idxr;
if (idx >= size) {
idx -= size;
f = fcur;
} else {
f = flast;
}
ulong result = file_read_block(f, &sensorlog, idx * SENSORLOG_STORE_SIZE,
SENSORLOG_STORE_SIZE);
if (result == 0) break;
if (sensorlog.nr > 0 && (sensorlog.nr == sensorNr || sensorNr == 0)) {
DEBUG_PRINTF("clearlog2 idx=%ld idx2=%ld\n", idx, idxr);
boolean found = false;
if (use_under && sensorlog.data < under) found = true;
if (use_over && sensorlog.data > over) found = true;
if (before && sensorlog.time < before) found = true;
if (after && sensorlog.time > after) found = true;
if (sensorNr > 0 && sensorlog.nr != sensorNr) found = false;
if (sensorNr > 0 && sensorlog.nr == sensorNr && !use_under && !use_over && !before && !after) found = true;
if (found) {
sensorlog.nr = 0;
file_write_block(f, &sensorlog, idx * SENSORLOG_STORE_SIZE,
SENSORLOG_STORE_SIZE);
DEBUG_PRINTF("clearlog3 idx=%ld idxr=%ld\n", idx, idxr);
n++;
}
}
idxr++;
}
DEBUG_PRINTF("clearlog4 n=%ld\n", n);
return n;
}
SensorLog_t *sensorlog_load(uint8_t log, ulong idx) {
SensorLog_t *sensorlog = new SensorLog_t;
return sensorlog_load(log, idx, sensorlog);
}
SensorLog_t *sensorlog_load(uint8_t log, ulong idx, SensorLog_t *sensorlog) {
// DEBUG_PRINTLN(F("sensorlog_load"));
// Map lower idx to the other log file
checkLogSwitch(log);
const char *flast = getlogfile2(log);
const char *fcur = getlogfile(log);
ulong size = file_size(flast) / SENSORLOG_STORE_SIZE;
const char *f;
if (idx >= size) {
idx -= size;
f = fcur;
} else {
f = flast;
}
file_read_block(f, sensorlog, idx * SENSORLOG_STORE_SIZE,
SENSORLOG_STORE_SIZE);
return sensorlog;
}
int sensorlog_load2(uint8_t log, ulong idx, int count, SensorLog_t *sensorlog) {
// DEBUG_PRINTLN(F("sensorlog_load"));
// Map lower idx to the other log file
checkLogSwitch(log);
const char *flast = getlogfile2(log);
const char *fcur = getlogfile(log);
ulong size = file_size(flast) / SENSORLOG_STORE_SIZE;
const char *f;
if (idx >= size) {
idx -= size;
f = fcur;
size = file_size(f) / SENSORLOG_STORE_SIZE;
} else {
f = flast;
}
if (idx + count > size) count = size - idx;
if (count <= 0) return 0;
file_read_block(f, sensorlog, idx * SENSORLOG_STORE_SIZE,
count * SENSORLOG_STORE_SIZE);
return count;
}
ulong findLogPosition(uint8_t log, ulong after) {
ulong log_size = sensorlog_size(log);
ulong a = 0;
ulong b = log_size - 1;
ulong lastIdx = 0;
SensorLog_t sensorlog;
while (true) {
ulong idx = (b - a) / 2 + a;
sensorlog_load(log, idx, &sensorlog);
if (sensorlog.time < after) {
a = idx;
} else if (sensorlog.time > after) {
b = idx;
}
if (a >= b || idx == lastIdx) return idx;
lastIdx = idx;
}
return 0;
}
#if !defined(ARDUINO)
/**
* compatibility functions for OSPi:
**/
#define timeSet 0
int timeStatus() { return timeSet; }
void dtostrf(float value, int min_width, int precision, char *txt) {
printf(txt, "%*.*f", min_width, precision, value);
}
void dtostrf(double value, int min_width, int precision, char *txt) {
printf(txt, "%*.*d", min_width, precision, value);
}
#endif
// 1/4 of a day: 6*60*60
#define BLOCKSIZE 64
#define CALCRANGE_WEEK 21600
#define CALCRANGE_MONTH 172800
static ulong next_week_calc = 0;
static ulong next_month_calc = 0;
/**
Calculate week+month Data
We store only the average value of 6 hours utc
**/
void calc_sensorlogs() {
if (!sensors || timeStatus() != timeSet) return;
ulong log_size = sensorlog_size(LOG_STD);
if (log_size == 0) return;
SensorLog_t *sensorlog = NULL;
time_t time = os.now_tz();
time_t last_day = time;
if (time >= next_week_calc) {
DEBUG_PRINTLN(F("calc_sensorlogs WEEK start"));
sensorlog = (SensorLog_t *)malloc(sizeof(SensorLog_t) * BLOCKSIZE);
ulong size = sensorlog_size(LOG_WEEK);
if (size == 0) {
sensorlog_load(LOG_STD, 0, sensorlog);
last_day = sensorlog->time;
} else {
sensorlog_load(LOG_WEEK, size - 1, sensorlog); // last record
last_day = sensorlog->time + CALCRANGE_WEEK; // Skip last Range
}
time_t fromdate = (last_day / CALCRANGE_WEEK) * CALCRANGE_WEEK;
time_t todate = fromdate + CALCRANGE_WEEK;
// 4 blocks per day
while (todate < time) {
ulong startidx = findLogPosition(LOG_STD, fromdate);
Sensor_t *sensor = sensors;
while (sensor) {
if (sensor->flags.enable && sensor->flags.log) {
ulong idx = startidx;
double data = 0;
ulong n = 0;
bool done = false;
while (!done) {
int sn = sensorlog_load2(LOG_STD, idx, BLOCKSIZE, sensorlog);
if (sn <= 0) break;
for (int i = 0; i < sn; i++) {
idx++;
if (sensorlog[i].time >= todate) {
done = true;
break;
}
if (sensorlog[i].nr == sensor->nr) {
data += sensorlog[i].data;
n++;
}
}
}
if (n > 0) {
sensorlog->nr = sensor->nr;
sensorlog->time = fromdate;
sensorlog->data = data / (double)n;
sensorlog->native_data = 0;
sensorlog_add(LOG_WEEK, sensorlog);
}
}
sensor = sensor->next;
}
fromdate += CALCRANGE_WEEK;
todate += CALCRANGE_WEEK;
}
next_week_calc = todate;
DEBUG_PRINTLN(F("calc_sensorlogs WEEK end"));
}
if (time >= next_month_calc) {
log_size = sensorlog_size(LOG_WEEK);
if (log_size <= 0) {
if (sensorlog) free(sensorlog);
return;
}
if (!sensorlog)
sensorlog = (SensorLog_t *)malloc(sizeof(SensorLog_t) * BLOCKSIZE);
DEBUG_PRINTLN(F("calc_sensorlogs MONTH start"));
ulong size = sensorlog_size(LOG_MONTH);
if (size == 0) {
sensorlog_load(LOG_WEEK, 0, sensorlog);
last_day = sensorlog->time;
} else {
sensorlog_load(LOG_MONTH, size - 1, sensorlog); // last record
last_day = sensorlog->time + CALCRANGE_MONTH; // Skip last Range
}
time_t fromdate = (last_day / CALCRANGE_MONTH) * CALCRANGE_MONTH;
time_t todate = fromdate + CALCRANGE_MONTH;
// 4 blocks per day
while (todate < time) {
ulong startidx = findLogPosition(LOG_WEEK, fromdate);
Sensor_t *sensor = sensors;
while (sensor) {
if (sensor->flags.enable && sensor->flags.log) {
ulong idx = startidx;
double data = 0;
ulong n = 0;
bool done = false;
while (!done) {
int sn = sensorlog_load2(LOG_WEEK, idx, BLOCKSIZE, sensorlog);
if (sn <= 0) break;
for (int i = 0; i < sn; i++) {
idx++;
if (sensorlog[i].time >= todate) {
done = true;
break;
}
if (sensorlog[i].nr == sensor->nr) {
data += sensorlog[i].data;
n++;
}
}
}
if (n > 0) {
sensorlog->nr = sensor->nr;
sensorlog->time = fromdate;
sensorlog->data = data / (double)n;
sensorlog->native_data = 0;
sensorlog_add(LOG_MONTH, sensorlog);
}
}
sensor = sensor->next;
}
fromdate += CALCRANGE_MONTH;
todate += CALCRANGE_MONTH;
}
next_month_calc = todate;
DEBUG_PRINTLN(F("calc_sensorlogs MONTH end"));
}
if (sensorlog) free(sensorlog);
}
void sensor_remote_http_callback(char *) {
// unused
}
void push_message(Sensor_t *sensor) {
if (!sensor || !sensor->last_read) return;
static char topic[TMP_BUFFER_SIZE];
static char payload[TMP_BUFFER_SIZE];
char *postval = tmp_buffer;
if (os.mqtt.enabled()) {
DEBUG_PRINTLN("push mqtt1");
strncpy_P(topic, PSTR("analogsensor/"), sizeof(topic) - 1);
strncat(topic, sensor->name, sizeof(topic) - 1);
snprintf_P(payload, TMP_BUFFER_SIZE,
PSTR("{\"nr\":%u,\"type\":%u,\"data_ok\":%u,\"time\":%u,"
"\"value\":%d.%02d,\"unit\":\"%s\"}"),
sensor->nr, sensor->type, sensor->flags.data_ok,
sensor->last_read, (int)sensor->last_data,
abs((int)(sensor->last_data * 100) % 100), getSensorUnit(sensor));
if (!os.mqtt.connected()) os.mqtt.reconnect();
os.mqtt.publish(topic, payload);
DEBUG_PRINTLN("push mqtt2");
}
//ifttt is enabled, when the ifttt key is present!
os.sopt_load(SOPT_IFTTT_KEY, tmp_buffer);
bool ifttt_enabled = strlen(tmp_buffer)!=0;
if (ifttt_enabled) {
DEBUG_PRINTLN("push ifttt");
strcpy_P(postval, PSTR("{\"value1\":\"On site ["));
os.sopt_load(SOPT_DEVICE_NAME, postval + strlen(postval));
strcat_P(postval, PSTR("], "));
strcat_P(postval, PSTR("analogsensor "));
snprintf_P(postval + strlen(postval), TMP_BUFFER_SIZE - strlen(postval),
PSTR("nr: %u, type: %u, data_ok: %u, time: %u, value: %d.%02d, "
"unit: %s"),
sensor->nr, sensor->type, sensor->flags.data_ok,
sensor->last_read, (int)sensor->last_data,
abs((int)(sensor->last_data * 100) % 100), getSensorUnit(sensor));
strcat_P(postval, PSTR("\"}"));
// char postBuffer[1500];
BufferFiller bf = BufferFiller(ether_buffer, ETHER_BUFFER_SIZE*2);
bf.emit_p(PSTR("POST /trigger/sprinkler/with/key/$O HTTP/1.0\r\n"
"Host: $S\r\n"
"Accept: */*\r\n"
"Content-Length: $D\r\n"
"Content-Type: application/json\r\n\r\n$S"),
SOPT_IFTTT_KEY, DEFAULT_IFTTT_URL, strlen(postval), postval);
os.send_http_request(DEFAULT_IFTTT_URL, 80, ether_buffer, sensor_remote_http_callback);
DEBUG_PRINTLN("push ifttt2");
}
}
void read_all_sensors(boolean online) {
if (!sensors) return;
//DEBUG_PRINTLN(F("read_all_sensors"));
ulong time = os.now_tz();
#ifdef ENABLE_DEBUG
if (time < os.powerup_lasttime + 3)
#else
if (time < os.powerup_lasttime + 30)