-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsensorpushd.py
More file actions
executable file
·1694 lines (1495 loc) · 66.2 KB
/
sensorpushd.py
File metadata and controls
executable file
·1694 lines (1495 loc) · 66.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------
# sensorpushd.py, Copyright Bjoern Olausson
# -----------------------------------------------------------------------------
# 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 2 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.
#
# To view the license visit
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# or write to
# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
# -----------------------------------------------------------------------------
#
# Unified SensorPush daemon - queries the SensorPush API and stores
# temperature, humidity, and other sensor readings in InfluxDB 2,
# InfluxDB 3, and/or VictoriaMetrics. Multiple backends can be
# active simultaneously.
#
# Can run as a one-shot command (backward compatible with cron) or as a
# continuous daemon managed by systemd.
#
import os
import sys
import json
import time
import math
import signal
import socket
import logging
import threading
import requests
import datetime
import argparse
import configparser
from abc import ABC, abstractmethod
from pathlib import Path
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# Suppress SSL warnings globally
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
def sd_notify(state):
"""Send a notification to the systemd watchdog (if available).
Uses the NOTIFY_SOCKET environment variable set by systemd for
Type=notify or WatchdogSec services. Silently does nothing when
the socket is not available (e.g. running outside systemd).
"""
sock_path = os.environ.get('NOTIFY_SOCKET')
if not sock_path:
return
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
if sock_path.startswith('@'):
sock_path = '\0' + sock_path[1:]
sock.sendto(state.encode(), sock_path)
sock.close()
except Exception:
pass
logger = logging.getLogger('sensorpushd')
# -----------------------------------------------------------------------------
# Constants
# -----------------------------------------------------------------------------
VERIFY_SSL = False
RETRYWAIT = 60
MAXRETRY = 3
RETRY_DELAYS = [10, 30, 60, 120, 300]
# Stop feeding the systemd watchdog if the main loop makes no progress for
# this many seconds. Must be larger than any single legitimate blocking
# step (an API call + its retries) but small enough to catch a real hang.
WATCHDOG_HANG_THRESHOLD = 900
API_URL_BASE = 'https://api.sensorpush.com/api/v1'
API_URL_OA_AUTH = f'{API_URL_BASE}/oauth/authorize'
API_URL_OA_ATOK = f'{API_URL_BASE}/oauth/accesstoken'
API_URL_GW = f'{API_URL_BASE}/devices/gateways'
API_URL_SE = f'{API_URL_BASE}/devices/sensors'
API_URL_SPL = f'{API_URL_BASE}/samples'
API_URL_RPL = f'{API_URL_BASE}/reports/list'
API_URL_RPDL = f'{API_URL_BASE}/reports/download'
HTTP_OA_HEAD = {'accept': 'application/json',
'Content-Type': 'application/json'}
MEASURES = ["altitude", "barometric_pressure", "dewpoint", "humidity",
"temperature", "vpd", "distance"]
# -----------------------------------------------------------------------------
# Logging setup
# -----------------------------------------------------------------------------
def setup_logging(level='INFO', log_file=None):
fmt = '%(asctime)s %(name)s %(levelname)s %(message)s'
datefmt = '%Y-%m-%d %H:%M:%S'
handlers = []
if log_file:
handlers.append(logging.FileHandler(log_file))
else:
handlers.append(logging.StreamHandler(sys.stderr))
logging.basicConfig(level=getattr(logging, level),
format=fmt, datefmt=datefmt,
handlers=handlers)
logging.getLogger('urllib3').setLevel(logging.WARNING)
# -----------------------------------------------------------------------------
# Configuration
# -----------------------------------------------------------------------------
def load_config(config_path):
"""Load config from file. Auto-detects legacy formats."""
config = configparser.ConfigParser()
if not Path(config_path).is_file():
create_default_config(config_path)
print(f'Created config file template at {config_path}')
print('Please edit the config file with your settings and run again.')
sys.exit(0)
config.read(config_path)
# Detect legacy InfluxDB 2 format (~/.sensorpush.conf)
if 'INFLUXDBCONF' in config:
return _load_legacy_influxdb2(config)
# Detect legacy VictoriaMetrics format (~/.sensorpush_vm.conf)
if 'VICTORIAMETRICSCONF' in config:
return _load_legacy_vm(config)
# New unified format (~/.sensorpushd.conf)
return _load_unified(config)
def _load_legacy_influxdb2(config):
"""Load legacy ~/.sensorpush.conf format."""
# Note: original config uses 'SONSORPUSHAPI' (typo preserved for compat)
section = 'SONSORPUSHAPI' if 'SONSORPUSHAPI' in config else 'SENSORPUSHAPI'
# Legacy config has separate IFDB_URL and IFDB_PORT — combine into one URL
url = config['INFLUXDBCONF']['IFDB_URL']
port = config['INFLUXDBCONF']['IFDB_PORT']
host_part = url.split('://', 1)[-1]
if ':' not in host_part:
url = f'{url}:{port}'
return {
'login': config[section]['LOGIN'],
'password': config[section]['PASSWD'],
'backend': 'influxdb2',
'my_altitude': float(config['MISC'].get('MY_ALTITUDE', '0')),
'force_ipv4': config['MISC'].get('FORCE_IPv4', 'False').lower() in ('true', '1', 'yes'),
'influxdb2': {
'measurement_name': config['INFLUXDBCONF'].get('MEASUREMENT_NAME', 'SensorPush'),
'url': url,
'token': config['INFLUXDBCONF']['IFDB_TOKEN'],
'org': config['INFLUXDBCONF']['IFDB_ORG'],
'bucket': config['INFLUXDBCONF']['IFDB_BUCKET'],
'verify_ssl': config['INFLUXDBCONF'].get('IFDB_VERIFY_SSL', 'False').lower() in ('true', '1', 'yes'),
},
'influxdb3': None,
'victoriametrics': None,
'daemon': {
'interval': 300,
'poll_backlog': '10m',
'max_backfill': '0',
'deep_scan_interval': '1h',
},
}
def _load_legacy_vm(config):
"""Load legacy ~/.sensorpush_vm.conf format."""
section = 'SONSORPUSHAPI' if 'SONSORPUSHAPI' in config else 'SENSORPUSHAPI'
return {
'login': config[section]['LOGIN'],
'password': config[section]['PASSWD'],
'backend': 'victoriametrics',
'my_altitude': float(config['MISC'].get('MY_ALTITUDE', '0')),
'force_ipv4': config['MISC'].getboolean('FORCE_IPv4', False),
'influxdb2': None,
'influxdb3': None,
'victoriametrics': {
'measurement_name': config['VICTORIAMETRICSCONF'].get('MEASUREMENT_NAME', 'SensorPush'),
'url': config['VICTORIAMETRICSCONF'].get('VM_URL', 'http://localhost:8428'),
'verify_ssl': config['VICTORIAMETRICSCONF'].getboolean('VM_VERIFY_SSL', False),
},
'daemon': {
'interval': 300,
'poll_backlog': '10m',
'max_backfill': '0',
'deep_scan_interval': '1h',
},
}
def _load_unified(config):
"""Load new unified ~/.sensorpushd.conf format."""
section = 'SONSORPUSHAPI' if 'SONSORPUSHAPI' in config else 'SENSORPUSHAPI'
# Accept both 'PASSWD' (legacy) and 'PASSWORD' (new) key names
if config.has_option(section, 'PASSWD'):
password = config[section]['PASSWD']
else:
password = config[section]['PASSWORD']
cfg = {
'login': config.get(section, 'LOGIN', fallback=config.get(section, 'EMAIL', fallback='')),
'password': password,
'backend': config.get('BACKEND', 'TYPE', fallback='victoriametrics'),
'my_altitude': config.getfloat('MISC', 'MY_ALTITUDE', fallback=0.0),
'force_ipv4': config.getboolean('MISC', 'FORCE_IPv4', fallback=False),
'influxdb2': None,
'influxdb3': None,
'victoriametrics': None,
'daemon': {
'interval': config.getint('DAEMON', 'INTERVAL', fallback=300),
'poll_backlog': config.get('DAEMON', 'POLL_BACKLOG', fallback='10m'),
'max_backfill': config.get('DAEMON', 'MAX_BACKFILL', fallback='0'),
'deep_scan_interval': config.get('DAEMON', 'DEEP_SCAN_INTERVAL', fallback='1h'),
},
}
if 'INFLUXDB2' in config:
url = config.get('INFLUXDB2', 'URL', fallback='http://localhost:8086')
# Legacy compat: if PORT is set and URL doesn't already contain a port
if config.has_option('INFLUXDB2', 'PORT'):
port = config.get('INFLUXDB2', 'PORT')
host_part = url.split('://', 1)[-1]
if ':' not in host_part:
url = f'{url}:{port}'
cfg['influxdb2'] = {
'measurement_name': config.get('INFLUXDB2', 'MEASUREMENT_NAME', fallback='SensorPush'),
'url': url,
'token': config.get('INFLUXDB2', 'TOKEN', fallback=''),
'org': config.get('INFLUXDB2', 'ORG', fallback=''),
'bucket': config.get('INFLUXDB2', 'BUCKET', fallback='sensorpush'),
'verify_ssl': config.getboolean('INFLUXDB2', 'VERIFY_SSL', fallback=False),
}
if 'INFLUXDB3' in config:
# Read URL (new) or HOST (legacy) for backward compat
if config.has_option('INFLUXDB3', 'URL'):
url = config.get('INFLUXDB3', 'URL')
else:
url = config.get('INFLUXDB3', 'HOST', fallback='http://localhost:8181')
cfg['influxdb3'] = {
'measurement_name': config.get('INFLUXDB3', 'MEASUREMENT_NAME', fallback='SensorPush'),
'url': url,
'database': config.get('INFLUXDB3', 'DATABASE', fallback='sensorpush'),
'token': config.get('INFLUXDB3', 'TOKEN', fallback=''),
'verify_ssl': config.getboolean('INFLUXDB3', 'VERIFY_SSL', fallback=False),
}
if 'VICTORIAMETRICS' in config:
cfg['victoriametrics'] = {
'measurement_name': config.get('VICTORIAMETRICS', 'MEASUREMENT_NAME', fallback='SensorPush'),
'url': config.get('VICTORIAMETRICS', 'URL', fallback='http://localhost:8428'),
'verify_ssl': config.getboolean('VICTORIAMETRICS', 'VERIFY_SSL', fallback=False),
}
return cfg
def create_default_config(path):
"""Write a default config template."""
config = configparser.ConfigParser()
config['SENSORPUSHAPI'] = {
'LOGIN': 'SensorPush login (email)',
'PASSWORD': 'SensorPush password',
}
config['BACKEND'] = {
'TYPE': 'victoriametrics',
}
config['INFLUXDB2'] = {
'MEASUREMENT_NAME': 'SensorPush',
'URL': 'http://localhost:8086',
'TOKEN': 'your_influxdb2_token',
'ORG': 'your_org',
'BUCKET': 'sensorpush',
'VERIFY_SSL': 'False',
}
config['INFLUXDB3'] = {
'MEASUREMENT_NAME': 'SensorPush',
'URL': 'http://localhost:8181',
'DATABASE': 'sensorpush',
'TOKEN': 'your_influxdb3_token',
'VERIFY_SSL': 'False',
}
config['VICTORIAMETRICS'] = {
'MEASUREMENT_NAME': 'SensorPush',
'URL': 'http://localhost:8428',
'VERIFY_SSL': 'False',
}
config['DAEMON'] = {
'INTERVAL': '300',
'POLL_BACKLOG': '10m',
}
config['MISC'] = {
'MY_ALTITUDE': '0.0',
'FORCE_IPv4': 'False',
}
with open(path, 'w') as f:
config.write(f)
# -----------------------------------------------------------------------------
# CLI argument parsing
# -----------------------------------------------------------------------------
def parse_args():
parser = argparse.ArgumentParser(
description='Unified SensorPush daemon - queries the SensorPush API and '
'stores readings in InfluxDB 2, InfluxDB 3, and/or VictoriaMetrics')
parser.add_argument(
'-s', '--start', dest='starttime', default='', type=str,
help='Start query at time (e.g. "2019-07-25T00:10:41+0200")')
parser.add_argument(
'-p', '--stop', dest='stoptime', default='', type=str,
help='Stop query at time (e.g. "2019-07-26T00:10:41+0200")')
parser.add_argument(
'-b', '--backlog', dest='backlog', default='1d', type=str,
help='Historical data to fetch (default 1d) - format: <number>[m|h|d|w|M|Y]')
parser.add_argument(
'-t', '--timestep', dest='timestep', default=720, type=int,
help='Time slice per query in minutes (default 720 = 12h)')
parser.add_argument(
'-q', '--querylimit', dest='qlimit', default=0, type=int,
help='Max samples per sensor (0 = unlimited, default 0)')
parser.add_argument(
'-d', '--delay', dest='delay', default=60, type=int,
help='Delay in seconds between queries (default 60)')
parser.add_argument(
'-l', '--listsensors', dest='listsensors', action='store_true',
help='Show a list of sensors and exit')
parser.add_argument(
'-g', '--listgateways', dest='listgateways', action='store_true',
help='Show a list of gateways and exit')
parser.add_argument(
'-i', '--sensorlist', dest='sensorlist', nargs='+', type=str,
help='List of sensor IDs to query')
parser.add_argument(
'-n', '--noconvert', dest='noconvert', action='store_true',
help='Do not convert F to C, inHG to mBar, kPa to mBar and feet to meters')
parser.add_argument(
'-x', '--dryrun', dest='dryrun', action='store_true',
help='Do not write anything to the database, just print what would have been written')
parser.add_argument(
'-v', '--verbose', dest='verbose', action='store_true',
help='Show full output in dryrun mode (do not truncate)')
# New arguments
parser.add_argument(
'--backend', dest='backend',
nargs='+',
choices=['influxdb2', 'influxdb3', 'victoriametrics'],
default=None,
help='Database backend(s) (overrides config file). '
'Specify multiple to write to all simultaneously')
parser.add_argument(
'--daemon', dest='daemon', action='store_true', default=False,
help='Run as a continuous daemon (default: one-shot mode)')
parser.add_argument(
'--interval', dest='interval', default=None, type=int,
help='Polling interval in seconds for daemon mode (default: from config or 300)')
parser.add_argument(
'-c', '--config', dest='config', default=None, type=str,
help='Path to config file (default: ~/.sensorpushd.conf)')
parser.add_argument(
'--log-level', dest='loglevel',
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
default='INFO',
help='Logging verbosity (default: INFO)')
parser.add_argument(
'--log-file', dest='logfile', default=None, type=str,
help='Log to file instead of stderr')
parser.add_argument(
'--generate-config', dest='generate_config', nargs='?',
const='', default=None, metavar='PATH',
help='Generate a default config file and exit. '
'Optionally specify output path (default: ~/.sensorpushd.conf)')
return parser.parse_args()
# -----------------------------------------------------------------------------
# Utility functions
# -----------------------------------------------------------------------------
def local_time_offset(t=None):
"""Return offset of local zone from GMT, either at present or at time t."""
if t is None:
t = time.time()
if time.localtime(t).tm_isdst and time.daylight:
return -time.altzone / 3600
else:
return -time.timezone / 3600
def F_to_C(F, noconvert=False):
if noconvert:
return float(F)
try:
return float(round((F - 32) * 5.0 / 9.0, 2))
except TypeError:
return 0.0
def ft_to_m(ft, noconvert=False):
if noconvert:
return float(ft)
return float(round(ft * 0.3048, 2))
def inHg_to_mBar(inHg, noconvert=False):
if noconvert:
return float(inHg)
return float(round(inHg * 33.8639, 2))
def kPa_to_mBar(kPa, noconvert=False):
if noconvert:
return float(kPa)
return float(round(kPa * 10, 2))
def parse_backlog(backlogstring):
"""Convert backlog string like '1d', '10m', '1M' to minutes."""
minutes_per_unit = {
"m": 1, "h": 60, "d": 60 * 24, "w": 60 * 24 * 7,
"M": 60 * 24 * 30.417, "Y": 60 * 24 * 365
}
return int(int(backlogstring[:-1]) * minutes_per_unit[backlogstring[-1]])
def build_timelist(starttime, stoptime, timesteps):
"""Build list of [start, stop] time windows with 30-min overlaps."""
timelist = []
newstartt = None
while starttime <= stoptime:
start = datetime.date.strftime(starttime, '%Y-%m-%dT%X%z')
if newstartt is not None:
nextstop = newstartt + datetime.timedelta(minutes=int(timesteps))
else:
nextstop = starttime + datetime.timedelta(minutes=int(timesteps))
stop = datetime.date.strftime(nextstop, '%Y-%m-%dT%X%z')
starttime = nextstop - datetime.timedelta(minutes=30)
newstartt = nextstop
timelist.append([start, stop])
return timelist
def parse_timestamp_to_ms(timestamp):
"""Convert timestamp string to milliseconds for VictoriaMetrics."""
if isinstance(timestamp, str):
try:
dt = datetime.datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
except (ValueError, AttributeError):
dt = datetime.datetime.strptime(timestamp.split('.')[0], '%Y-%m-%dT%H:%M:%S')
return int(dt.timestamp() * 1000)
return int(timestamp * 1000)
# -----------------------------------------------------------------------------
# Backend Writers
# -----------------------------------------------------------------------------
class BaseWriter(ABC):
"""Abstract base class for database backend writers."""
def __init__(self):
self._connected = False
self._consecutive_failures = 0
@property
def connected(self):
return self._connected
@abstractmethod
def connect(self):
"""Establish connection to the backend."""
pass
@abstractmethod
def write(self, records):
"""Write a list of measurement dicts to the backend.
Each record is: {'measurement': str, 'tags': dict, 'fields': dict, 'time': str}
"""
pass
@abstractmethod
def get_last_timestamp(self, measurement_name, sensor_id=None):
"""Query the backend for the most recent data point timestamp.
If sensor_id is given, returns the last timestamp for that
specific sensor (using the temperature metric as reference).
Returns a datetime object or None if no data exists.
"""
pass
@abstractmethod
def close(self):
"""Close the backend connection."""
pass
def reconnect(self):
"""Tear down and re-establish the connection."""
try:
self.close()
except Exception:
pass
self._connected = False
self.connect()
class InfluxDB2Writer(BaseWriter):
"""InfluxDB 2.x backend writer."""
def __init__(self, config):
super().__init__()
self.url = config['url']
self.token = config['token']
self.org = config['org']
self.bucket = config['bucket']
self.verify_ssl = config['verify_ssl']
self.measurement_name = config['measurement_name']
self.client = None
self.write_api = None
self.query_api = None
def connect(self):
try:
from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS
except ImportError:
raise ImportError(
"InfluxDB 2 backend requires the 'influxdb-client' package. "
"Install with: pip install influxdb-client"
)
self.client = InfluxDBClient(
url=self.url,
token=self.token,
org=self.org,
verify_ssl=self.verify_ssl
)
self.write_api = self.client.write_api(write_options=SYNCHRONOUS)
self.query_api = self.client.query_api()
self._connected = True
logger.info("Connected to InfluxDB 2 at %s", self.url)
def write(self, records):
if not records:
return
self.write_api.write(bucket=self.bucket, org=self.org, record=records)
def get_last_timestamp(self, measurement_name, sensor_id=None):
try:
sensor_filter = ''
if sensor_id is not None:
sensor_filter = (
f' |> filter(fn: (r) => r.sensor_id == "{sensor_id}")'
)
query = (
f'from(bucket: "{self.bucket}")'
f' |> range(start: -30d)'
f' |> filter(fn: (r) => r._measurement == "{measurement_name}"'
f' and r._field == "temperature")'
f'{sensor_filter}'
f' |> last()'
)
tables = self.query_api.query(query, org=self.org)
for table in tables:
for record in table.records:
return record.get_time()
except Exception as e:
logger.warning("Failed to query last timestamp from InfluxDB 2: %s", e)
return None
def close(self):
if self.client:
self.client.close()
self.client = None
self.write_api = None
self.query_api = None
self._connected = False
logger.info("InfluxDB 2 connection closed")
class InfluxDB3Writer(BaseWriter):
"""InfluxDB 3.x backend writer."""
def __init__(self, config):
super().__init__()
self.url = config['url']
self.database = config['database']
self.token = config['token']
self.verify_ssl = config.get('verify_ssl', False)
self.measurement_name = config['measurement_name']
self.client = None
def connect(self):
try:
from influxdb_client_3 import InfluxDBClient3, write_client_options, SYNCHRONOUS
except ImportError:
raise ImportError(
"InfluxDB 3 backend requires the 'influxdb3-python' package. "
"Install with: pip install influxdb3-python"
)
wco = write_client_options(write_options=SYNCHRONOUS)
self.client = InfluxDBClient3(
host=self.url,
database=self.database,
token=self.token,
write_client_options=wco
)
self._connected = True
logger.info("Connected to InfluxDB 3 at %s", self.url)
def write(self, records):
if not records:
return
self.client.write(record=records)
def get_last_timestamp(self, measurement_name, sensor_id=None):
try:
sensor_filter = ''
if sensor_id is not None:
sensor_filter = f" AND sensor_id = '{sensor_id}'"
query = (
f'SELECT max(time) AS last_time FROM "{measurement_name}"'
f" WHERE time > now() - INTERVAL '30 days'"
f'{sensor_filter}'
)
result = self.client.query(query)
if result and len(result) > 0:
last_time = result.column('last_time')[0].as_py()
if last_time:
return last_time
except Exception as e:
logger.warning("Failed to query last timestamp from InfluxDB 3: %s", e)
return None
def close(self):
if self.client:
self.client.close()
self.client = None
self._connected = False
logger.info("InfluxDB 3 connection closed")
class VMWriter(BaseWriter):
"""VictoriaMetrics backend writer using native JSON import API."""
def __init__(self, config):
super().__init__()
self.url = config['url']
self.verify_ssl = config['verify_ssl']
self.measurement_name = config['measurement_name']
self.session = None
def connect(self):
self.session = requests.Session()
self._connected = True
logger.info("VictoriaMetrics writer ready for %s", self.url)
def write(self, records):
if not records:
return
lines = []
for record in records:
lines.extend(self._to_json_lines(
record['measurement'], record['tags'],
record['fields'], record['time']
))
if not lines:
return
data = '\n'.join(lines)
url = f'{self.url}/api/v1/import'
response = self.session.post(
url,
data=data.encode('utf-8'),
headers={'Content-Type': 'application/json'},
verify=self.verify_ssl,
timeout=15
)
response.raise_for_status()
def _to_json_lines(self, measurement_name, tags, fields, timestamp):
"""Convert to VictoriaMetrics native JSON format."""
timestamp_ms = parse_timestamp_to_ms(timestamp)
lines = []
for field_name, field_value in fields.items():
metric = {'__name__': f'{measurement_name}_{field_name}'}
for tag_key, tag_value in tags.items():
metric[tag_key] = str(tag_value)
json_obj = {
'metric': metric,
'values': [float(field_value)],
'timestamps': [timestamp_ms]
}
lines.append(json.dumps(json_obj, ensure_ascii=False))
return lines
def get_last_timestamp(self, measurement_name, sensor_id=None):
try:
# Use last_over_time() which is standard MetricsQL. The response
# timestamp in the [value] array tells us when the last point was.
sensor_filter = ''
if sensor_id is not None:
sensor_filter = f'sensor_id="{sensor_id}"'
url = f'{self.url}/api/v1/query'
metric = f'{measurement_name}_temperature'
query_str = f'last_over_time({metric}{{{sensor_filter}}}[30d])'
response = self.session.get(
url,
params={'query': query_str},
verify=self.verify_ssl,
timeout=30
)
response.raise_for_status()
data = response.json()
results = data.get('data', {}).get('result', [])
if results:
# [0] = unix timestamp, [1] = value
ts = float(results[0]['value'][0])
return datetime.datetime.fromtimestamp(
ts, tz=datetime.timezone.utc)
return None
except Exception as e:
logger.warning("Failed to query last timestamp from VictoriaMetrics: %s", e)
return None
def close(self):
if self.session:
self.session.close()
self.session = None
self._connected = False
logger.info("VictoriaMetrics session closed")
def create_writer(backend_name, config):
"""Factory: create the appropriate backend writer."""
if backend_name == 'influxdb2':
if not config.get('influxdb2'):
raise ValueError(
"InfluxDB 2 backend selected but [INFLUXDB2] config section is missing")
return InfluxDB2Writer(config['influxdb2'])
elif backend_name == 'influxdb3':
if not config.get('influxdb3'):
raise ValueError(
"InfluxDB 3 backend selected but [INFLUXDB3] config section is missing")
return InfluxDB3Writer(config['influxdb3'])
elif backend_name == 'victoriametrics':
if not config.get('victoriametrics'):
raise ValueError(
"VictoriaMetrics backend selected but [VICTORIAMETRICS] config section is missing")
return VMWriter(config['victoriametrics'])
else:
raise ValueError(f"Unknown backend: {backend_name}")
def create_writers(backend_names, config):
"""Create writer instances for all specified backends."""
writers = []
for name in backend_names:
writers.append(create_writer(name, config))
return writers
# -----------------------------------------------------------------------------
# SensorPush API
# -----------------------------------------------------------------------------
class SensorPushAPI:
"""Client for the SensorPush cloud API."""
def __init__(self, login, password, verify_ssl=False, force_ipv4=False):
self.login = login
self.password = password
self.verify_ssl = verify_ssl
if force_ipv4:
import urllib3.util.connection
urllib3.util.connection.HAS_IPV6 = False
self.session = requests.Session()
self.session.mount(API_URL_BASE, HTTPAdapter(max_retries=0))
self.access_token = None
self._token_time = None
self._auth_header = None
def authenticate(self):
"""Perform OAuth authentication flow with retry."""
http_data = json.dumps({'email': self.login, 'password': self.password})
# Step 1: Get authorization string
auth = None
for attempt in range(1, MAXRETRY + 1):
logger.info("Fetching API oauth authorization string - try %d/%d",
attempt, MAXRETRY)
try:
r = self.session.post(API_URL_OA_AUTH, headers=HTTP_OA_HEAD,
data=http_data, verify=self.verify_ssl,
timeout=30)
if r.status_code == 200:
auth = r.content.decode('utf-8')
break
else:
logger.error("Auth request failed with status %d", r.status_code)
except (requests.exceptions.ConnectionError,
requests.exceptions.Timeout) as e:
logger.warning("Connection error during auth: %s", e)
if attempt >= MAXRETRY:
raise ConnectionError(
f"Failed to fetch API oauth authorization after {MAXRETRY} attempts")
time.sleep(20)
# Step 2: Get access token
logger.info("Fetching API oauth access token")
r = self.session.post(API_URL_OA_ATOK, headers=HTTP_OA_HEAD,
data=auth, verify=self.verify_ssl,
timeout=30)
if r.status_code == 200:
self.access_token = json.loads(r.content.decode('utf-8'))['accesstoken']
self._token_time = time.time()
self._auth_header = {
'accept': 'application/json',
'Authorization': self.access_token
}
logger.info("Authentication successful")
else:
raise ConnectionError(
f"Access token request failed with status {r.status_code}")
def _ensure_auth(self):
"""Re-authenticate if token is likely expired (>55 min)."""
if (self._token_time is None or
time.time() - self._token_time > 3300):
self.authenticate()
def _post(self, url, data=None):
"""Make an authenticated POST request."""
self._ensure_auth()
http_data = json.dumps(data or {})
r = self.session.post(url, headers=self._auth_header,
data=http_data, verify=self.verify_ssl,
timeout=60)
if r.status_code == 200:
return json.loads(r.content.decode('utf-8'))
raise ValueError(
f"API request to {url} failed with status {r.status_code}: "
f"{r.content.decode('utf-8')}")
def get_gateways(self):
logger.info("Fetching the list of gateways")
return self._post(API_URL_GW)
def get_sensors(self):
logger.info("Fetching the list of sensors")
return self._post(API_URL_SE)
def get_reports(self):
logger.info("Fetching the list of bulk reports")
return self._post(API_URL_RPL)
def get_samples(self, start, stop, measures=None, limit=0, sensors=None):
query = {'startTime': start, 'stopTime': stop,
'measures': measures or MEASURES}
if limit != 0:
query['limit'] = limit
if sensors:
query['sensors'] = sensors
return self._post(API_URL_SPL, query)
# -----------------------------------------------------------------------------
# Data processing
# -----------------------------------------------------------------------------
def build_voltage_records(sensors, measurement_name, querytime):
"""Build voltage/RSSI measurement records for all sensors."""
records = []
measurement_v_name = f'{measurement_name}_V'
for sid in sensors.keys():
try:
bat_volt = float(sensors[sid]["battery_voltage"])
except (KeyError, TypeError):
bat_volt = 0.0
try:
rssi = float(sensors[sid]["rssi"])
except (KeyError, TypeError):
rssi = 0.0
records.append({
'measurement': str(measurement_v_name),
'tags': {
'sensor_id': float(sensors[sid]["id"]),
'sensor_name': str(sensors[sid]["name"]),
},
'fields': {
'voltage': float(bat_volt),
'rssi': float(rssi),
},
'time': datetime.date.strftime(querytime, '%Y-%m-%dT%X%z')
})
return records
def process_samples(samples, sensors, measurement_name, my_altitude, noconvert):
"""Process API sample response into measurement records."""
records = []
for key in samples['sensors'].keys():
for item in samples['sensors'][key]:
observed = str(item['observed'])
sensor_name = str(sensors[key]['name'])
m = {
'measurement': str(measurement_name),
'tags': {
'sensor_id': float(key),
'sensor_name': str(sensor_name),
},
'fields': {},
'time': str(observed)
}
try:
humidity = float(item['humidity'])
except KeyError:
pass
else:
m['fields']['humidity'] = float(humidity)
try:
temperature = F_to_C(item['temperature'], noconvert)
except KeyError:
pass
else:
m['fields']['temperature'] = float(temperature)
try:
pressure = inHg_to_mBar(item['barometric_pressure'], noconvert)
except KeyError:
# Absolute humidity (g/m3) - simplified formula without pressure
# https://carnotcycle.wordpress.com/2012/08/04/how-to-convert-relative-humidity-to-absolute-humidity/
abs_humidity = float(round(
(6.112 * math.e**((17.67 * temperature) / (temperature + 243.5))
* humidity * 2.1674) / (273.15 + temperature), 2))
m['fields']['abs_humidity'] = float(abs_humidity)
else:
m['fields']['pressure'] = float(pressure)
# Absolute humidity (g/m3) - accurate formula with pressure
# https://www.loxwiki.eu/display/LOX/Absolute+Luftfeuchtigkeit+berechnen
abs_humidity = float(round(
0.622 * humidity / 100 * (
1.01325 * 10.0**(5.426651 - 2005.1 / (temperature + 273.15)
+ 0.00013869 * ((temperature + 273.15) * (temperature + 273.15) - 293700.0)
/ (temperature + 273.15) * (10.0**(0.000000000011965
* ((temperature + 273.15) * (temperature + 273.15) - 293700.0)
* ((temperature + 273.15) * (temperature + 273.15) - 293700.0)) - 1.0)
- 0.0044 * 10.0**((-0.0057148 * (374.11 - temperature)**1.25)))
+ (((temperature + 273.15) / 647.3) - 0.422)
* (0.577 - ((temperature + 273.15) / 647.3))
* math.exp(0.000000000011965
* ((temperature + 273.15) * (temperature + 273.15) - 293700.0)
* ((temperature + 273.15) * (temperature + 273.15) - 293700.0))
* 0.00980665)
/ (pressure / 1000.0 - humidity / 100.0 * (
1.01325 * 10.0**(5.426651 - 2005.1 / (temperature + 273.15)
+ 0.00013869 * ((temperature + 273.15) * (temperature + 273.15) - 293700.0)
/ (temperature + 273.15) * (10.0**(0.000000000011965
* ((temperature + 273.15) * (temperature + 273.15) - 293700.0)
* ((temperature + 273.15) * (temperature + 273.15) - 293700.0)) - 1.0)
- 0.0044 * 10.0**((-0.0057148 * (374.11 - temperature)**1.25)))
+ (((temperature + 273.15) / 647.3) - 0.422)
* (0.577 - ((temperature + 273.15) / 647.3))
* math.exp(0.000000000011965
* ((temperature + 273.15) * (temperature + 273.15) - 293700.0)
* ((temperature + 273.15) * (temperature + 273.15) - 293700.0))
* 0.00980665))
* pressure / 1000.0 * 100000000.0
/ ((temperature + 273.15) * 287.1), 2))
m['fields']['abs_humidity'] = float(abs_humidity)
try:
altitude = ft_to_m(item['altitude'], noconvert)
except KeyError:
altitude = float(my_altitude)
finally:
if altitude == 0:
altitude = float(my_altitude)
m['fields']['altitude'] = float(altitude)
try: