-
Notifications
You must be signed in to change notification settings - Fork 26
/
goveebttemplogger.cpp
3687 lines (3633 loc) · 176 KB
/
goveebttemplogger.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
/////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 William C Bonner
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// GoveeBTTempLogger is designed as a project to run on a Raspberry Pi with
// Bluetooth Low Energy support. It listens for advertisments from Govee
// https://www.govee.com/product/thermometers-hygrometers/indoor-thermometers-hygrometers
// Currently the H5074, GVH5075, and GVH5177 are decoded and logged.
// Each unit has its data logged to it's own file, with a new file created daily.
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
//
// Links I've found useful in learning about Bluetooth Low Energy (BLE) or Govee
// https://github.com/Thrilleratplay/GoveeWatcher
// https://github.com/neilsheps/GoveeTemperatureAndHumidity
// https://github.com/carsonmcdonald/bluez-experiments/blob/master/experiments/scantest.c
// https://people.csail.mit.edu/albert/bluez-intro/index.html
// https://reelyactive.github.io/ble-identifier-reference.html
// https://ukbaz.github.io/howto/beacon_scan_cmd_line.html
// https://github.com/ukBaz/ukBaz.github.io/blob/master/howto/beacon_scan_cmd_line.html
// http://kktechkaizen.blogspot.com/2014/10/bluetooth-technology-overview.html
// https://github.com/microsoftarchive/msdn-code-gallery-microsoft/tree/master/Official%20Windows%20Platform%20Sample/Bluetooth%20LE%20Explorer%20sample
// https://docs.microsoft.com/en-us/windows/win32/bluetooth/bluetooth-programming-with-windows-sockets
// https://www.reddit.com/r/Govee/comments/f1dfcd/home_assistant_component_for_h5074_and_h5075/fi7hnic/
// https://unix.stackexchange.com/questions/96106/bluetooth-le-scan-as-non-root
// https://docs.microsoft.com/en-us/cpp/linux/configure-a-linux-project?view=vs-2017
// https://reelyactive.github.io/diy/best-practices-ble-identifiers/
// https://github.com/pauloborges/bluez/blob/master/doc/mgmt-api.txt
// https://gist.github.com/mironovdm/cb7f47e8d898e9a3977fc888d990e8a9
// https://www.argenox.com/library/bluetooth-low-energy/using-raspberry-pi-ble/
//
#include <algorithm>
#include <arpa/inet.h>
#include <bluetooth/bluetooth.h> // apt install libbluetooth-dev
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <bluetooth/l2cap.h>
#include <cfloat>
#include <climits>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <getopt.h>
#include <iomanip>
#include <iostream>
#include <locale>
#include <map>
#include <netdb.h>
#include <netinet/in.h>
#include <queue>
#include <random>
#include <regex>
#include <set>
#include <sstream>
#include <string>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h> // For close()
#include <utime.h>
#include <vector>
#include "wimiso8601.h"
#include "att-types.h"
#include "uuid.h"
/////////////////////////////////////////////////////////////////////////////
#if __has_include("goveebttemplogger-version.h")
#include "goveebttemplogger-version.h"
#endif
#ifndef GoveeBTTempLogger_VERSION
#define GoveeBTTempLogger_VERSION "(non-CMake)"
#endif // !GoveeBTTempLogger_VERSION
/////////////////////////////////////////////////////////////////////////////
static const std::string ProgramVersionString("GoveeBTTempLogger Version " GoveeBTTempLogger_VERSION " Built on: " __DATE__ " at " __TIME__);
/////////////////////////////////////////////////////////////////////////////
#ifndef BT_HCI_CMD_LE_SET_EXT_SCAN_PARAMS
#define BT_HCI_CMD_LE_SET_EXT_SCAN_PARAMS 0x2041
int hci_le_set_ext_scan_parameters(int dd, uint8_t type, uint16_t interval, uint16_t window, uint8_t own_type, uint8_t filter, int to)
{
struct bt_hci_cmd_le_set_ext_scan_params {
uint8_t own_addr_type;
uint8_t filter_policy;
uint8_t num_phys;
uint8_t type;
uint16_t interval;
uint16_t window;
} __attribute__((packed)) param_cp;
memset(¶m_cp, 0, sizeof(param_cp));
param_cp.type = type;
param_cp.interval = interval;
param_cp.window = window;
param_cp.own_addr_type = own_type;
param_cp.filter_policy = filter;
param_cp.num_phys = 1;
uint8_t status;
struct hci_request rq;
memset(&rq, 0, sizeof(rq));
rq.ogf = OGF_LE_CTL;
rq.ocf = BT_HCI_CMD_LE_SET_EXT_SCAN_PARAMS;
rq.cparam = ¶m_cp;
rq.clen = sizeof(bt_hci_cmd_le_set_ext_scan_params);
rq.rparam = &status;
rq.rlen = 1;
if (hci_send_req(dd, &rq, to) < 0)
return -1;
if (status) {
errno = EIO;
return -1;
}
return 0;
}
#endif // !BT_HCI_CMD_LE_SET_EXT_SCAN_PARAMS
#ifndef BT_HCI_CMD_LE_SET_EXT_SCAN_ENABLE
#define BT_HCI_CMD_LE_SET_EXT_SCAN_ENABLE 0x2042
int hci_le_set_ext_scan_enable(int dd, uint8_t enable, uint8_t filter_dup, int to)
{
struct bt_hci_cmd_le_set_ext_scan_enable {
uint8_t enable;
uint8_t filter_dup;
uint16_t duration;
uint16_t period;
} __attribute__((packed)) scan_cp;
memset(&scan_cp, 0, sizeof(scan_cp));
scan_cp.enable = enable;
scan_cp.filter_dup = filter_dup;
uint8_t status;
struct hci_request rq;
memset(&rq, 0, sizeof(rq));
rq.ogf = OGF_LE_CTL;
rq.ocf = BT_HCI_CMD_LE_SET_EXT_SCAN_ENABLE;
rq.cparam = &scan_cp;
rq.clen = sizeof(scan_cp);
rq.rparam = &status;
rq.rlen = 1;
if (hci_send_req(dd, &rq, to) < 0)
return -1;
if (status) {
errno = EIO;
return -1;
}
return 0;
}
#endif // !BT_HCI_CMD_LE_SET_EXT_SCAN_ENABLE
#ifndef BT_HCI_CMD_LE_SET_RANDOM_ADDRESS
// 2023-11-29 Added this function to fix problem with Raspberry Pi Zero 2 W Issue https://github.com/wcbonner/GoveeBTTempLogger/issues/50
int hci_le_set_random_address(int dd, int to)
{
le_set_random_address_cp scan_cp{ 0 };
std::default_random_engine generator(std::chrono::system_clock::now().time_since_epoch().count()); // 2023-12-01 switch to c++ std library <random>
for (auto & b : scan_cp.bdaddr.b)
b = generator() % 256;
uint8_t status;
struct hci_request rq;
memset(&rq, 0, sizeof(rq));
rq.ogf = OGF_LE_CTL;
rq.ocf = OCF_LE_SET_RANDOM_ADDRESS;
rq.cparam = &scan_cp;
rq.clen = sizeof(scan_cp);
rq.rparam = &status;
rq.rlen = 1;
if (hci_send_req(dd, &rq, to) < 0)
return -1;
if (status) {
errno = EIO;
return -1;
}
return 0;
}
#endif // BT_HCI_CMD_LE_SET_RANDOM_ADDRESS
/////////////////////////////////////////////////////////////////////////////
int ConsoleVerbosity(1);
bool UseBluetooth(true);
std::filesystem::path LogDirectory; // If this remains empty, log Files are not created.
std::filesystem::path CacheDirectory; // If this remains empty, cache Files are not used. Cache Files should greatly speed up startup of the program if logged data runs multiple years over many devices.
std::filesystem::path SVGDirectory; // If this remains empty, SVG Files are not created. If it's specified, _day, _week, _month, and _year.svg files are created for each bluetooth address seen.
int SVGBattery(0); // 0x01 = Draw Battery line on daily, 0x02 = Draw Battery line on weekly, 0x04 = Draw Battery line on monthly, 0x08 = Draw Battery line on yearly
int SVGMinMax(0); // 0x01 = Draw Temperature and Humiditiy Minimum and Maximum line on daily, 0x02 = on weekly, 0x04 = on monthly, 0x08 = on yearly
bool SVGFahrenheit(true);
std::filesystem::path SVGTitleMapFilename;
std::filesystem::path SVGIndexFilename;
// The following details were taken from https://github.com/oetiker/mrtg
const size_t DAY_COUNT(600); /* 400 samples is 33.33 hours */
const size_t WEEK_COUNT(600); /* 400 samples is 8.33 days */
const size_t MONTH_COUNT(600); /* 400 samples is 33.33 days */
const size_t YEAR_COUNT(2 * 366); /* 1 sample / day, 366 days, 2 years */
const size_t DAY_SAMPLE(5 * 60); /* Sample every 5 minutes */
const size_t WEEK_SAMPLE(30 * 60); /* Sample every 30 minutes */
const size_t MONTH_SAMPLE(2 * 60 * 60); /* Sample every 2 hours */
const size_t YEAR_SAMPLE(24 * 60 * 60); /* Sample every 24 hours */
/////////////////////////////////////////////////////////////////////////////
// Class I'm using for storing raw data from the Govee thermometers
enum class ThermometerType
{
Unknown = 0,
H5074 = 5074,
H5075 = 5075,
H5100 = 5100,
H5101 = 5101,
H5104 = 5104,
H5105 = 5105,
H5174 = 5174,
H5177 = 5177,
H5179 = 5179,
H5183 = 5183,
H5182 = 5182,
H5181 = 5181,
};
class Govee_Temp {
public:
time_t Time;
std::string WriteTXT(const char seperator = '\t') const;
std::string WriteCache(void) const;
bool ReadCache(const std::string& data);
bool ReadMSG(const uint8_t * const data);
Govee_Temp() : Time(0), Temperature{ 0, 0, 0, 0 }, TemperatureMin{ DBL_MAX, DBL_MAX, DBL_MAX, DBL_MAX }, TemperatureMax{ -DBL_MAX, -DBL_MAX, -DBL_MAX, -DBL_MAX }, Humidity(0), HumidityMin(DBL_MAX), HumidityMax(-DBL_MAX), Battery(INT_MAX), Averages(0), Model(ThermometerType::Unknown) { };
Govee_Temp(const time_t tim, const double tem, const double hum, const int bat)
{
Time = tim;
Temperature[0] = tem;
TemperatureMin[0] = tem;
TemperatureMax[0] = tem;
Humidity = hum;
HumidityMin = hum;
HumidityMax = hum;
Battery = bat;
Averages = 1;
};
Govee_Temp(const std::string & data);
double GetTemperature(const bool Fahrenheit = false, const int index = 0) const { if (Fahrenheit) return((Temperature[index] * 9.0 / 5.0) + 32.0); return(Temperature[index]); };
double GetTemperatureMin(const bool Fahrenheit = false, const int index = 0) const { if (Fahrenheit) return(std::min(((Temperature[index] * 9.0 / 5.0) + 32.0), ((TemperatureMin[index] * 9.0 / 5.0) + 32.0))); return(std::min(Temperature[index], TemperatureMin[index])); };
double GetTemperatureMax(const bool Fahrenheit = false, const int index = 0) const { if (Fahrenheit) return(std::max(((Temperature[index] * 9.0 / 5.0) + 32.0), ((TemperatureMax[index] * 9.0 / 5.0) + 32.0))); return(std::max(Temperature[index], TemperatureMax[index])); };
void SetMinMax(const Govee_Temp & a);
double GetHumidity(void) const { return(Humidity); };
double GetHumidityMin(void) const { return(std::min(Humidity, HumidityMin)); };
double GetHumidityMax(void) const { return(std::max(Humidity, HumidityMax)); };
int GetBattery(void) const { return(Battery); };
ThermometerType GetModel(void) const { return(Model); };
ThermometerType SetModel(const std::string& Name);
ThermometerType SetModel(const unsigned short* UUID);
enum granularity {day, week, month, year};
void NormalizeTime(granularity type);
granularity GetTimeGranularity(void) const;
bool IsValid(void) const { return(Averages > 0); };
Govee_Temp& operator +=(const Govee_Temp& b);
protected:
double Temperature[4];
double TemperatureMin[4];
double TemperatureMax[4];
double Humidity;
double HumidityMin;
double HumidityMax;
int Battery;
int Averages;
ThermometerType Model;
};
Govee_Temp::Govee_Temp(const std::string & data)
{
std::istringstream TheLine(data);
// erase any nulls from the data. these are occasionally in the log file when the platform crashed during a write to the logfile.
while (TheLine.peek() == '\000')
TheLine.get();
std::string theDay;
TheLine >> theDay;
std::string theHour;
TheLine >> theHour;
std::string theDate(theDay + " " + theHour);
Time = ISO8601totime(theDate);
TheLine >> Temperature[0];
TemperatureMin[0] = TemperatureMax[0] = Temperature[0];
TheLine >> Humidity;
HumidityMin = HumidityMax = Humidity;
TheLine >> Battery;
if (!TheLine.eof())
{
int theModel(0);
TheLine >> theModel;
switch (theModel)
{
case 5181:
Model = ThermometerType::H5181;
break;
case 5182:
Model = ThermometerType::H5182;
break;
case 5183:
Model = ThermometerType::H5183;
break;
default:
Model = ThermometerType::Unknown;
}
auto index = 1;
while ((!TheLine.eof()) && (index < (sizeof(Temperature) / sizeof(Temperature[0]))))
{
TheLine >> Temperature[index];
TemperatureMin[index] = TemperatureMax[index] = Temperature[index];
index++;
}
}
time_t timeNow(0);
time(&timeNow);
if (Time <= timeNow) // Only validate data from the past.
Averages = 1;
// h5074, h5075, h5100, h5179 Temperature Range = -20C to 60C
// h5103 Temperature Range = 0C to 50C
if (Temperature[0] < -20)
Averages = 0; // invalidate the data
}
std::string Govee_Temp::WriteTXT(const char seperator) const
{
std::ostringstream ssValue;
ssValue << timeToExcelDate(Time);
ssValue << seperator << Temperature[0];
ssValue << seperator << Humidity;
ssValue << seperator << Battery;
if (Model == ThermometerType::H5181)
{
ssValue << seperator << 5181;
ssValue << seperator << Temperature[1];
}
if (Model == ThermometerType::H5182)
{
ssValue << seperator << 5182;
ssValue << seperator << Temperature[1];
ssValue << seperator << Temperature[2];
ssValue << seperator << Temperature[3];
}
if (Model == ThermometerType::H5183)
{
ssValue << seperator << 5183;
ssValue << seperator << Temperature[1];
}
return(ssValue.str());
}
std::string Govee_Temp::WriteCache(void) const
{
std::ostringstream ssValue;
ssValue << Time;
for (auto a : Temperature)
ssValue << "\t" << a;
for (auto a : TemperatureMin)
ssValue << "\t" << a;
for (auto a : TemperatureMax)
ssValue << "\t" << a;
ssValue << "\t" << Humidity;
ssValue << "\t" << HumidityMin;
ssValue << "\t" << HumidityMax;
ssValue << "\t" << Battery;
ssValue << "\t" << Averages;
//TODO: Write Model
// ssValue << "\t" << Model;
return(ssValue.str());
}
bool Govee_Temp::ReadCache(const std::string& data)
{
bool rval = false;
std::istringstream ssValue(data);
ssValue >> Time;
for (auto & a : Temperature)
ssValue >> a;
for (auto & a : TemperatureMin)
ssValue >> a;
for (auto & a : TemperatureMax)
ssValue >> a;
ssValue >> Humidity;
ssValue >> HumidityMin;
ssValue >> HumidityMax;
ssValue >> Battery;
ssValue >> Averages;
// TODO: Read Model
return(rval);
}
ThermometerType Govee_Temp::SetModel(const std::string& Name)
{
ThermometerType rval = Model;
if (0 == Name.substr(0, 8).compare("GVH5177_"))
Model = ThermometerType::H5177;
else if (0 == Name.substr(0, 8).compare("GVH5100_"))
Model = ThermometerType::H5100;
else if (0 == Name.substr(0, 8).compare("GVH5101_"))
Model = ThermometerType::H5101;
else if (0 == Name.substr(0, 8).compare("GVH5104_"))
Model = ThermometerType::H5104;
else if (0 == Name.substr(0, 8).compare("GVH5105_"))
Model = ThermometerType::H5105;
else if (0 == Name.substr(0, 8).compare("GVH5174_"))
Model = ThermometerType::H5174;
else if (0 == Name.substr(0, 12).compare("Govee_H5179_"))
Model = ThermometerType::H5179;
else if (0 == Name.substr(0, 8).compare("GVH5075_"))
Model = ThermometerType::H5075;
else if (0 == Name.substr(0, 12).compare("Govee_H5074_"))
Model = ThermometerType::H5074;
return(rval);
}
ThermometerType Govee_Temp::SetModel(const unsigned short* UUID)
{
ThermometerType rval = Model;
// 88EC could be either GVH5075_ or GVH5174_
if (0x8151 == *UUID)
Model = ThermometerType::H5181;
else if (0x8251 == *UUID)
Model = ThermometerType::H5182;
else if (0x8351 == *UUID)
Model = ThermometerType::H5183;
return(rval);
}
bool Govee_Temp::ReadMSG(const uint8_t * const data)
{
bool rval = false;
const size_t data_len = data[0];
if (data[1] == 0xFF) // https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/ «Manufacturer Specific Data»
{
if ((data_len == 9) && (data[2] == 0x88) && (data[3] == 0xEC)) // GVH5075_xxxx
{
if (Model == ThermometerType::Unknown)
Model = ThermometerType::H5075;
// This data came from https://github.com/Thrilleratplay/GoveeWatcher
// 88ec00 03519e 64 00 Temp: 21.7502°C Temp: 71.1504°F Humidity: 50.2%
// 2 3 4 5 6 7 8
int iTemp = int(data[5]) << 16 | int(data[6]) << 8 | int(data[7]);
bool bNegative = iTemp & 0x800000; // check sign bit
iTemp = iTemp & 0x7ffff; // mask off sign bit
Temperature[0] = float(iTemp / 1000) / 10.0; // issue #49 fix.
// After converting the hexadecimal number into decimal the first three digits are the
// temperature and the last three digits are the humidity.So "03519e" converts to "217502"
// which means 21.7 °C and 50.2 % humidity without any rounding.
if (bNegative) // apply sign bit
Temperature[0] = -1.0 * Temperature[0];
Humidity = float(iTemp % 1000) / 10.0;
Battery = int(data[8]);
Averages = 1;
time(&Time);
TemperatureMin[0] = TemperatureMax[0] = Temperature[0]; //HACK: make sure that these values are set
rval = true;
}
else if ((data_len == 10) && (data[2] == 0x88) && (data[3] == 0xEC))// Govee_H5074_xxxx
{
if (Model == ThermometerType::Unknown)
Model = ThermometerType::H5074;
// This data came from https://github.com/neilsheps/GoveeTemperatureAndHumidity
// 88EC00 0902 CD15 64 02 (Temp) 41.378°F (Humidity) 55.81% (Battery) 100%
// 2 3 4 5 6 7 8 9
short iTemp = short(data[6]) << 8 | short(data[5]);
int iHumidity = int(data[8]) << 8 | int(data[7]);
Temperature[0] = float(iTemp) / 100.0;
Humidity = float(iHumidity) / 100.0;
Battery = int(data[9]);
Averages = 1;
time(&Time);
TemperatureMin[0] = TemperatureMax[0] = Temperature[0]; //HACK: make sure that these values are set
rval = true;
}
else if ((data_len == 12) && (data[2] == 0x01) && (data[3] == 0x88) && (data[4] == 0xEC)) // Govee_H5179
{
if (Model == ThermometerType::Unknown)
Model = ThermometerType::H5179;
// This is from data provided in https://github.com/wcbonner/GoveeBTTempLogger/issues/36
// 0188EC00 0101 0A0A B018 64 (Temp) 25.7°C (Humidity) 63.2% (Battery) 100% (GVH5179)
// 2 3 4 5 6 7 8 9 1011 12
short iTemp = short(data[9]) << 8 | short(data[8]);
int iHumidity = int(data[11]) << 8 | int(data[10]);
Temperature[0] = float(iTemp) / 100.0;
Humidity = float(iHumidity) / 100.0;
Battery = int(data[12]);
Averages = 1;
time(&Time);
TemperatureMin[0] = TemperatureMax[0] = Temperature[0]; //HACK: make sure that these values are set
rval = true;
}
else if ((data_len == 9) && (data[2] == 0x01) && (data[3] == 0x00)) // GVH5177_xxxx or GVH5174_xxxx or GVH5100_xxxx
{
// This is a guess based on the H5075 3 byte encoding
// 01000101 029D1B 64 (Temp) 62.8324°F (Humidity) 29.1% (Battery) 100%
// 2 3 4 5 6 7 8 9
// It appears that the H5174 uses the exact same data format as the H5177, with the difference being the broadcase name starting with GVH5174_
int iTemp = int(data[6]) << 16 | int(data[7]) << 8 | int(data[8]);
bool bNegative = iTemp & 0x800000; // check sign bit
iTemp = iTemp & 0x7ffff; // mask off sign bit
Temperature[0] = float(iTemp) / 10000.0;
Humidity = float(iTemp % 1000) / 10.0;
if (bNegative) // apply sign bit
Temperature[0] = -1.0 * Temperature[0];
Battery = int(data[9]);
Averages = 1;
time(&Time);
TemperatureMin[0] = TemperatureMax[0] = Temperature[0]; //HACK: make sure that these values are set
rval = true;
}
else if (data_len == 17 && (data[5] == 0x01) && (data[6] == 0x00) && (data[7] == 0x01) && (data[8] == 0x01)) // GVH5183 (UUID) 5183 B5183011
{
if (Model == ThermometerType::Unknown)
Model = ThermometerType::H5183;
// Govee Bluetooth Wireless Meat Thermometer, Digital Grill Thermometer with 1 Probe, 230ft Remote Temperature Monitor, Smart Kitchen Cooking Thermometer, Alert Notifications for BBQ, Oven, Smoker, Cakes
// https://www.amazon.com/gp/product/B092ZTD96V
// The probe measuring range is 0° to 300°C /32° to 572°F.
// 5DA1B4 01000101 E4 01 80 0708 13 24 00 00
// 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
// (Manu) 5DA1B4 01000101 81 0180 07D0 1324 0000 (Temp) 20°C (Temp) 49°C (Battery) 1% (Other: 00) (Other: 00) (Other: 00) (Other: 00) (Other: 00) (Other: BF)
// the first three bytes are the last three bytes of the bluetooth address.
// then next four bytes appear to be a signature for the device type.
// Model = ThermometerType::H5181;
// Govee Bluetooth Meat Thermometer, 230ft Range Wireless Grill Thermometer Remote Monitor with Temperature Probe Digital Grilling Thermometer with Smart Alerts for Smoker Cooking BBQ Kitchen Oven
// https://www.amazon.com/dp/B092ZTJW37/
short iTemp = short(data[12]) << 8 | short(data[13]);
Temperature[0] = float(iTemp) / 100.0;
iTemp = short(data[14]) << 8 | short(data[15]);
Temperature[1] = float(iTemp) / 100.0; // This appears to be the alarm temperature.
Humidity = 0;
Battery = int(data[9] & 0x7F);
Averages = 1;
time(&Time);
for (auto index = 0; index < (sizeof(Temperature) / sizeof(Temperature[0])); index++)
TemperatureMin[index] = TemperatureMax[index] = Temperature[index]; //HACK: make sure that these values are set
rval = true;
}
else if (data_len == 20 && (data[5] == 0x01) && (data[6] == 0x00) && (data[7] == 0x01) && (data[8] == 0x01)) // GVH5182 (UUID) 5182 (Manu) 30132701000101E4018606A413F78606A41318
{
if (Model == ThermometerType::Unknown)
Model = ThermometerType::H5182;
// Govee Bluetooth Meat Thermometer, 230ft Range Wireless Grill Thermometer Remote Monitor with Temperature Probe Digital Grilling Thermometer with Smart Alerts for Smoker , Cooking, BBQ, Kitchen, Oven
// https://www.amazon.com/gp/product/B094N2FX9P
// 301327 01000101 64 01 80 05DC 1324 86 06A4 FFFF
// 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
// (Manu) 301327 01000101 3A 01 86 076C FFFF 86 076C FFFF (Temp) 19°C (Temp) -0.01°C (Temp) 19°C (Temp) -0.01°C (Battery) 58%
// If the probe is not connected to the device, the temperature data is set to FFFF.
// If the alarm is not set for the probe, the data is set to FFFF.
short iTemp = short(data[12]) << 8 | short(data[13]); // Probe 1 Temperature
Temperature[0] = float(iTemp) / 100.0;
iTemp = short(data[14]) << 8 | short(data[15]); // Probe 1 Alarm Temperature
Temperature[1] = float(iTemp) / 100.0;
iTemp = short(data[17]) << 8 | short(data[18]); // Probe 2 Temperature
Temperature[2] = float(iTemp) / 100.0;
iTemp = short(data[19]) << 8 | short(data[20]); // Probe 2 Alarm Temperature
Temperature[3] = float(iTemp) / 100.0;
Humidity = 0;
Battery = int(data[9]);
Averages = 1;
time(&Time);
for (auto index = 0; index < (sizeof(Temperature) / sizeof(Temperature[0])); index++)
TemperatureMin[index] = TemperatureMax[index] = Temperature[index]; //HACK: make sure that these values are set
rval = true;
}
}
return(rval);
}
void Govee_Temp::SetMinMax(const Govee_Temp& a)
{
for (auto index = 0; index < (sizeof(Temperature) / sizeof(Temperature[0])); index++)
{
TemperatureMin[index] = TemperatureMin[index] < Temperature[index] ? TemperatureMin[index] : Temperature[index];
TemperatureMax[index] = TemperatureMax[index] > Temperature[index] ? TemperatureMax[index] : Temperature[index];
TemperatureMin[index] = TemperatureMin[index] < a.TemperatureMin[index] ? TemperatureMin[index] : a.TemperatureMin[index];
TemperatureMax[index] = TemperatureMax[index] > a.TemperatureMax[index] ? TemperatureMax[index] : a.TemperatureMax[index];
}
HumidityMin = HumidityMin < Humidity ? HumidityMin : Humidity;
HumidityMax = HumidityMax > Humidity ? HumidityMax : Humidity;
HumidityMin = HumidityMin < a.HumidityMin ? HumidityMin : a.HumidityMin;
HumidityMax = HumidityMax > a.HumidityMax ? HumidityMax : a.HumidityMax;
}
void Govee_Temp::NormalizeTime(granularity type)
{
if (type == day)
Time = (Time / DAY_SAMPLE) * DAY_SAMPLE;
else if (type == week)
Time = (Time / WEEK_SAMPLE) * WEEK_SAMPLE;
else if (type == month)
Time = (Time / MONTH_SAMPLE) * MONTH_SAMPLE;
else if (type == year)
{
struct tm UTC;
if (0 != localtime_r(&Time, &UTC))
{
UTC.tm_hour = 0;
UTC.tm_min = 0;
UTC.tm_sec = 0;
Time = mktime(&UTC);
}
}
}
Govee_Temp::granularity Govee_Temp::GetTimeGranularity(void) const
{
granularity rval = granularity::day;
struct tm UTC;
if (0 != localtime_r(&Time, &UTC))
{
//if (((UTC.tm_hour == 0) && (UTC.tm_min == 0)) || ((UTC.tm_hour == 23) && (UTC.tm_min == 0) && (UTC.tm_isdst == 1)))
if ((UTC.tm_hour == 0) && (UTC.tm_min == 0))
rval = granularity::year;
else if ((UTC.tm_hour % 2 == 0) && (UTC.tm_min == 0))
rval = granularity::month;
else if ((UTC.tm_min == 0) || (UTC.tm_min == 30))
rval = granularity::week;
}
return(rval);
}
Govee_Temp& Govee_Temp::operator +=(const Govee_Temp& b)
{
if (b.IsValid())
{
Time = std::max(Time, b.Time); // Use the maximum time (newest time)
for (auto index = 0; index < (sizeof(Temperature) / sizeof(Temperature[0])); index++)
{
Temperature[index] = ((Temperature[index] * Averages) + (b.Temperature[index] * b.Averages)) / (Averages + b.Averages);
TemperatureMin[index] = std::min(std::min(Temperature[index], TemperatureMin[index]), b.TemperatureMin[index]);
TemperatureMax[index] = std::max(std::max(Temperature[index], TemperatureMax[index]), b.TemperatureMax[index]);
}
Humidity = ((Humidity * Averages) + (b.Humidity * b.Averages)) / (Averages + b.Averages);
HumidityMin = std::min(std::min(Humidity, HumidityMin), b.HumidityMin);
HumidityMax = std::max(std::max(Humidity, HumidityMax), b.HumidityMax);
Battery = std::min(Battery, b.Battery);
Averages += b.Averages; // existing average + new average
}
return(*this);
}
/////////////////////////////////////////////////////////////////////////////
std::string iBeacon(const uint8_t * const data)
{
std::ostringstream ssValue;
const size_t data_len = data[0];
if (data[1] == 0xFF) // https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/ «Manufacturer Specific Data»
{
if ((data[2] == 0x4c) && (data[3] == 0x00))
{
ssValue << " (Apple)";
if ((data[4] == 0x02) && (data[5] == 0x15)) // SubType: 0x02 (iBeacon) && SubType Length: 0x15
{
ssValue << " (UUID) ";
for (auto index = 6; index < 22; index++)
ssValue << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << int(data[index]);
ssValue << " (Major) ";
ssValue << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << int(data[22]);
ssValue << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << int(data[23]);
ssValue << " (Minor) ";
ssValue << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << int(data[24]);
ssValue << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << int(data[25]);
ssValue << " (RSSI) ";
ssValue << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << int(data[26]);
// https://en.wikipedia.org/wiki/IBeacon
// https://scapy.readthedocs.io/en/latest/layers/bluetooth.html#apple-ibeacon-broadcast-frames
// https://atadiat.com/en/e-bluetooth-low-energy-ble-101-tutorial-intensive-introduction/
// https://deepai.org/publication/handoff-all-your-privacy-a-review-of-apple-s-bluetooth-low-energy-continuity-protocol
}
else
{
// 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// 4C00 02 15 494E54454C4C495F524F434B535F48 5750 740F 5CC2
// 4C00 02 15494E54454C4C495F524F434B535F48 5750 75F2 FFC2
ssValue << " ";
for (size_t index = 4; index < data_len; index++)
ssValue << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << int(data[index]);
// Apple Company Code: 0x004C
// UUID 16 bytes
// Major 2 bytes
// Minor 2 bytes
}
}
}
return(ssValue.str());
}
/////////////////////////////////////////////////////////////////////////////
// The following operator was required so I could use the std::map<> to use BlueTooth Addresses as the key
bool operator <(const bdaddr_t &a, const bdaddr_t &b)
{
unsigned long long A = a.b[5];
A = A << 8 | a.b[4];
A = A << 8 | a.b[3];
A = A << 8 | a.b[2];
A = A << 8 | a.b[1];
A = A << 8 | a.b[0];
unsigned long long B = b.b[5];
B = B << 8 | b.b[4];
B = B << 8 | b.b[3];
B = B << 8 | b.b[2];
B = B << 8 | b.b[1];
B = B << 8 | b.b[0];
return(A < B);
}
bool operator ==(const bdaddr_t& a, const bdaddr_t& b)
{
unsigned long long A = a.b[5];
A = A << 8 | a.b[4];
A = A << 8 | a.b[3];
A = A << 8 | a.b[2];
A = A << 8 | a.b[1];
A = A << 8 | a.b[0];
unsigned long long B = b.b[5];
B = B << 8 | b.b[4];
B = B << 8 | b.b[3];
B = B << 8 | b.b[2];
B = B << 8 | b.b[1];
B = B << 8 | b.b[0];
return(A == B);
}
/////////////////////////////////////////////////////////////////////////////
std::string ba2string(const bdaddr_t& a) { char addr_str[18]; ba2str(&a, addr_str); std::string rVal(addr_str); return(rVal); }
bdaddr_t string2ba(const std::string& a) { std::string ssBTAddress(a); if (ssBTAddress.length() == 12)for (auto index = ssBTAddress.length() - 2; index > 0; index -= 2)ssBTAddress.insert(index, ":"); bdaddr_t TheBlueToothAddress({ 0 }); if (ssBTAddress.length() == 17)str2ba(ssBTAddress.c_str(), &TheBlueToothAddress); return(TheBlueToothAddress); }
/////////////////////////////////////////////////////////////////////////////
std::map<bdaddr_t, std::queue<Govee_Temp>> GoveeTemperatures;
std::map<bdaddr_t, time_t> GoveeLastDownload;
const std::filesystem::path GVHLastDownloadFileName("gvh-lastdownload.txt");
/////////////////////////////////////////////////////////////////////////////
volatile bool bRun = true; // This is declared volatile so that the compiler won't optimized it out of loops later in the code
void SignalHandlerSIGINT(int signal)
{
bRun = false;
std::cerr << "***************** SIGINT: Caught Ctrl-C, finishing loop and quitting. *****************" << std::endl;
}
void SignalHandlerSIGHUP(int signal)
{
bRun = false;
std::cerr << "***************** SIGHUP: Caught HangUp, finishing loop and quitting. *****************" << std::endl;
}
void SignalHandlerSIGALRM(int signal)
{
if (ConsoleVerbosity > 0)
std::cout << "[" << getTimeISO8601() << "] ***************** SIGALRM: Caught Alarm. *****************" << std::endl;
}
/////////////////////////////////////////////////////////////////////////////
bool ValidateDirectory(const std::filesystem::path& DirectoryName)
{
bool rval = false;
// https://linux.die.net/man/2/stat
struct stat64 StatBuffer;
if (0 == stat64(DirectoryName.c_str(), &StatBuffer))
if (S_ISDIR(StatBuffer.st_mode))
{
// https://linux.die.net/man/2/access
if (0 == access(DirectoryName.c_str(), R_OK | W_OK))
rval = true;
else
{
switch (errno)
{
case EACCES:
std::cerr << DirectoryName << " (" << errno << ") The requested access would be denied to the file, or search permission is denied for one of the directories in the path prefix of pathname." << std::endl;
break;
case ELOOP:
std::cerr << DirectoryName << " (" << errno << ") Too many symbolic links were encountered in resolving pathname." << std::endl;
break;
case ENAMETOOLONG:
std::cerr << DirectoryName << " (" << errno << ") pathname is too long." << std::endl;
break;
case ENOENT:
std::cerr << DirectoryName << " (" << errno << ") A component of pathname does not exist or is a dangling symbolic link." << std::endl;
break;
case ENOTDIR:
std::cerr << DirectoryName << " (" << errno << ") A component used as a directory in pathname is not, in fact, a directory." << std::endl;
break;
case EROFS:
std::cerr << DirectoryName << " (" << errno << ") Write permission was requested for a file on a read-only file system." << std::endl;
break;
case EFAULT:
std::cerr << DirectoryName << " (" << errno << ") pathname points outside your accessible address space." << std::endl;
break;
case EINVAL:
std::cerr << DirectoryName << " (" << errno << ") mode was incorrectly specified." << std::endl;
break;
case EIO:
std::cerr << DirectoryName << " (" << errno << ") An I/O error occurred." << std::endl;
break;
case ENOMEM:
std::cerr << DirectoryName << " (" << errno << ") Insufficient kernel memory was available." << std::endl;
break;
case ETXTBSY:
std::cerr << DirectoryName << " (" << errno << ") Write access was requested to an executable which is being executed." << std::endl;
break;
default:
std::cerr << DirectoryName << " (" << errno << ") An unknown error." << std::endl;
}
}
}
return(rval);
}
// Create a standardized logfile name for this program based on a Bluetooth address and the global parameter of the log file directory.
std::filesystem::path GenerateLogFileName(const bdaddr_t &a, time_t timer = 0)
{
std::ostringstream OutputFilename;
// Original version of filename was formatted gvh507x_XXXX with only last two bytes of bluetooth address
// Second version of filename was formatted gvh507x_XXXXXXXXXXXX with all six bytes of the bluetooth address
// Third version of filename is formatted gvh-XXXXXXXXXXXX because I've been tired of the 507x for the past two years (2023-04-03)
//OutputFilename << "gvh507x_";
//OutputFilename << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << int(a.b[1]);
//OutputFilename << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << int(a.b[0]);
OutputFilename << "gvh507x_";
std::string btAddress(ba2string(a));
for (auto pos = btAddress.find(':'); pos != std::string::npos; pos = btAddress.find(':'))
btAddress.erase(pos, 1);
OutputFilename << btAddress;
if (timer == 0)
time(&timer);
struct tm UTC;
if (0 != gmtime_r(&timer, &UTC))
if (!((UTC.tm_year == 70) && (UTC.tm_mon == 0) && (UTC.tm_mday == 1)))
OutputFilename << "-" << std::dec << UTC.tm_year + 1900 << "-" << std::setw(2) << std::setfill('0') << UTC.tm_mon + 1;
OutputFilename << ".txt";
std::filesystem::path OldFormatFileName(LogDirectory / OutputFilename.str());
// The New Format Log File Name includes the entire Bluetooth Address, making it much easier to recognize and add to MRTG config files.
OutputFilename.str("");
OutputFilename << "gvh-";
OutputFilename << btAddress;
if (!((UTC.tm_year == 70) && (UTC.tm_mon == 0) && (UTC.tm_mday == 1)))
OutputFilename << "-" << std::dec << UTC.tm_year + 1900 << "-" << std::setw(2) << std::setfill('0') << UTC.tm_mon + 1;
OutputFilename << ".txt";
std::filesystem::path NewFormatFileName(LogDirectory / OutputFilename.str());
// This is a temporary hack to transparently change log file name formats
std::ifstream OldFile(OldFormatFileName);
if (OldFile.is_open())
{
OldFile.close();
try
{
std::filesystem::rename(OldFormatFileName, NewFormatFileName);
std::cerr << "[ ] Renamed " << OldFormatFileName << " to " << NewFormatFileName << std::endl;
}
catch (const std::filesystem::filesystem_error& ia)
{
std::cerr << "[ ] " << ia.what() << std::endl;
std::cerr << "[ ] Unable to Rename " << OldFormatFileName << " to " << NewFormatFileName << std::endl;
}
}
return(NewFormatFileName);
}
bool GenerateLogFile(std::map<bdaddr_t, std::queue<Govee_Temp>> &AddressTemperatureMap, std::map<bdaddr_t, time_t> &PersistenceData)
{
bool rval = false;
if (!LogDirectory.empty())
{
if (ConsoleVerbosity > 1)
std::cout << "[" << getTimeISO8601() << "] GenerateLogFile: " << LogDirectory << std::endl;
for (auto it = AddressTemperatureMap.begin(); it != AddressTemperatureMap.end(); ++it)
{
if (!it->second.empty()) // Only open the log file if there are entries to add
{
std::filesystem::path filename(GenerateLogFileName(it->first));
std::ofstream LogFile(filename, std::ios_base::out | std::ios_base::app | std::ios_base::ate);
if (LogFile.is_open())
{
time_t MostRecentData(0);
while (!it->second.empty())
{
LogFile << it->second.front().WriteTXT() << std::endl;
MostRecentData = std::max(it->second.front().Time, MostRecentData);
it->second.pop();
}
LogFile.close();
struct utimbuf Log_ut;
Log_ut.actime = MostRecentData;
Log_ut.modtime = MostRecentData;
utime(filename.c_str(), &Log_ut);
rval = true;
}
}
}
if (!PersistenceData.empty())
{
if (ConsoleVerbosity > 0)
for (auto & iter : PersistenceData)
std::cout << "[-------------------] [" << ba2string(iter.first) << "] " << timeToISO8601(iter.second) << std::endl;
// If PersistenceData has updated information, write new data to file
std::filesystem::path filename(LogDirectory / GVHLastDownloadFileName);
time_t MostRecentDownload(0);
for (auto & it : PersistenceData)
if (MostRecentDownload < it.second)
MostRecentDownload = it.second;
bool NewData(true);
struct stat64 StatBuffer;
StatBuffer.st_mtim.tv_sec = 0;
if (0 == stat64(filename.c_str(), &StatBuffer))
{
// compare the date of the file with the most recent data in the structure.
if (MostRecentDownload <= StatBuffer.st_mtim.tv_sec)
NewData = false;
}
if (NewData)
{
std::ofstream PersistenceFile(filename, std::ios_base::out | std::ios_base::trunc);
if (PersistenceFile.is_open())
{
for (auto & it : PersistenceData)
PersistenceFile << ba2string(it.first) << "\t" << timeToISO8601(it.second) << std::endl;
PersistenceFile.close();
struct utimbuf Persistut;
Persistut.actime = MostRecentDownload;
Persistut.modtime = MostRecentDownload;
utime(filename.c_str(), &Persistut);
}
}
}
}
else
{
// clear the queued data if LogDirectory not specified
for (auto it = AddressTemperatureMap.begin(); it != AddressTemperatureMap.end(); ++it)
{
while (!it->second.empty())
{
it->second.pop();
}
}
}
return(rval);
}
bool GetLogEntry(const bdaddr_t &InAddress, const int Minutes, Govee_Temp & OutValue)
{
// Returned value is now the average of whatever values were recorded over the previous 5 minutes
bool rval = false;
std::ifstream TheFile(GenerateLogFileName(InAddress));
if (TheFile.is_open())
{
time_t now = ISO8601totime(getTimeISO8601());
std::queue<Govee_Temp> LogValues;
TheFile.seekg(0, std::ios_base::end); //Start at end of file
do
{
char ch = ' '; //Init ch not equal to '\n'
while (ch != '\n')
{
TheFile.seekg(-2, std::ios_base::cur); //Two steps back, this means we will NOT check the last character
if ((int)TheFile.tellg() <= 0) //If passed the start of the file,
{
TheFile.seekg(0); //this is the start of the line
break;
}
TheFile.get(ch); //Check the next character
}
auto FileStreamPos = TheFile.tellg(); // Save Current Stream Position
std::string TheLine;
std::getline(TheFile, TheLine);
TheFile.seekg(FileStreamPos); // Move Stream position to where it was before reading TheLine
char buffer[256];
if (TheLine.size() < sizeof(buffer))
{
TheLine.copy(buffer, TheLine.size());
buffer[TheLine.size()] = '\0';
std::string theDate(strtok(buffer, "\t"));
std::string theTemp(strtok(NULL, "\t"));
std::string theHumidity(strtok(NULL, "\t"));
std::string theBattery(strtok(NULL, "\t"));
Govee_Temp TheValue(ISO8601totime(theDate), atof(theTemp.c_str()), atof(theHumidity.c_str()), atoi(theBattery.c_str()));
if ((Minutes == 0) && LogValues.empty()) // HACK: Special Case to always accept the last logged value
LogValues.push(TheValue);
if ((Minutes * 60.0) < difftime(now, TheValue.Time)) // If this entry is more than Minutes parameter from current time, it's time to stop reading log file.
break;
LogValues.push(TheValue);
}
} while (TheFile.tellg() > 0); // If we are at the beginning of the file, there's nothing more to do
TheFile.close();
if (!LogValues.empty())
OutValue = Govee_Temp();
while (!LogValues.empty())
{
OutValue += LogValues.front();
LogValues.pop();
rval = true; // I'm doing this multiple times, but it was easier than having an extra check
}
}
return(rval);
}
void GetMRTGOutput(const std::string &TextAddress, const int Minutes)
{
bdaddr_t TheAddress = { 0 };
str2ba(TextAddress.c_str(), &TheAddress);
Govee_Temp TheValue;