forked from ppetr/arduino-influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collect.py
247 lines (223 loc) · 9.7 KB
/
collect.py
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
#!/usr/bin/env python3
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Forwards data from a serial device to an InfluxDB database."""
import argparse
import importlib
import logging
import sys
import threading
import time
from typing import BinaryIO, Callable, FrozenSet, Generator, Optional
from retrying import retry
import serial
import influxdb
import persistent_queue
import serial_samples
import sched
import subprocess
import time
import os
def restart_script():
logging.info("Restarting script...")
os._exit(1) # Force immediate exit
def RetryOnIOError(exception):
"""Returns True if 'exception' is an IOError."""
return isinstance(exception, IOError)
@retry(wait_exponential_multiplier=1000,
wait_exponential_max=60000,
retry_on_exception=RetryOnIOError)
def ReadLoop(args, queue: persistent_queue.Queue):
"""Reads samples and stores them in a queue. Retries on IO errors."""
serial_fn: Optional[Callable[[BinaryIO], Generator[bytes, None,
None]]] = None
if args.serial_function:
module, fn_name = args.serial_function.rsplit(".", 1)
serial_fn = getattr(importlib.import_module(module), fn_name)
try:
logging.debug("Read loop started")
with serial.serial_for_url(args.device,
baudrate=args.baud_rate,
timeout=args.read_timeout) as handle:
if serial_fn:
lines = serial_fn(handle)
else:
lines = serial_samples.SerialLines(handle, args.max_line_length, 10.0)
start_time = time.time()
for line in lines:
# If line does not start with start string
if not line.startswith(b'FTX'):
continue
try:
line = str(line, encoding="UTF-8")
except TypeError:
pass
# Parse 'line', either with or without timestamp.
words = line.strip().split(" ")
if len(words) == 2:
(tags, values) = words
timestamp = int(time.time() * 1000000000)
elif len(words) == 3:
(tags, values, timestamp) = words
float(timestamp)
else:
raise ValueError("Unable to parse line {0!r}".format(line))
tags: str = ",".join(t for t in (tags, args.tags) if t)
queue.put("{0} {1} {2:d}".format(tags, values, timestamp))
except:
logging.exception("Error, retrying with backoff")
raise
@retry(wait_exponential_multiplier=1000,
wait_exponential_max=60000,
retry_on_exception=RetryOnIOError)
def WriteLoop(args, queue: persistent_queue.Queue):
"""Reads samples and stores them in a queue. Retries on IO errors."""
logging.debug("Write loop started")
warn_on_status: FrozenSet[int] = frozenset(
int(status) for status in args.warn_on_status)
try:
influxdb_line: str
for influxdb_line in queue.get_blocking(tick=60):
influxdb.PostLines(args.database,
args.host,
[influxdb_line.encode(encoding='UTF-8')],
warn_on_status=warn_on_status)
except:
logging.exception("Error, retrying with backoff")
raise
def RunAndDie(fun, *args):
"""Runs 'fn' on 'args'. If 'fn' exists, exit the whole program."""
try:
fun(*args)
finally:
sys.exit(1)
def main():
"""Parses the command line arguments and invokes the main loop."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="""
Collects values from a serial port and sends them to InfluxDB.
Note that the first received line is discarded to prevent recording
incomplete data.
Make sure to set READ_TIMEOUT higher than the longest expected
period of inactivity of your device. For example, if your device
sends data every 60 seconds, set --read-timeout=70 (or any similar
value >60s).
""",
epilog="""See
https://pyserial.readthedocs.io/en/latest/url_handlers.html#urls
for URL types accepted by -d/--device.
Run `python -m serial.tools.list_ports` to list of all available
COM ports.
""")
parser.add_argument('-d',
'--device',
required=True,
help='serial device to read from, or a URL accepted '
'by serial_for_url()')
parser.add_argument('-r',
'--baud-rate',
type=int,
default=9600,
help='baud rate of the serial device')
parser.add_argument('-t',
'--read-timeout',
type=int,
required=True,
help='read timeout on the serial device; this should '
'be longer that the longest expected period of '
'inactivity of the serial device')
parser.add_argument('--max-line-length',
type=int,
default=1024,
help='maximum line length')
parser.add_argument('--serial-function',
help='custom function that reads from a serial device '
'passed as its argument and yields InfluxDB '
'lines; specified as module.functionname')
parser.add_argument('-H',
'--host',
default='localhost:8086',
help='host and port with InfluxDB to send data to')
parser.add_argument('-D',
'--database',
required=True,
help='database to save data to')
parser.add_argument('-T',
'--tags',
default='',
help='additional static tags for measurements'
' separated by comma, for example foo=x,bar=y')
parser.add_argument('--warn_on_status',
nargs='*',
default=[400],
help='when one of these HTTP statuses is received from'
' InfluxDB, a warning is printed and the'
' datapoint is skipped; allows to continue on'
' invalid datapoints')
parser.add_argument('-q',
'--queue',
default=':memory:',
help='path for a persistent queue database file; this '
'file will be automatically created and managed '
'by the program; it ensures that no datapoints '
'are ever lost, even if the database is '
'temporarily unreachable; NOTE that at the '
'moment old lines are not garbage collected '
'from the file, so it grows forever!')
parser.add_argument('-w',
'--wal_autocheckpoint',
type=int,
default=10,
help='switches the queue SQLite database to use the '
'WAL mode and sets this parameter in the database')
parser.add_argument('--debug',
action='store_true',
help='enable debug level')
args = parser.parse_args()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
# Create a scheduler and schedule the script to restart in 24 hours
scheduler = sched.scheduler(time.time, time.sleep)
restart_delay = 24 * 60 * 60 # 24 hours in seconds
scheduler.enter(restart_delay, 1, restart_script)
# Start the scheduler in a separate thread
scheduler_thread = threading.Thread(target=scheduler.run)
scheduler_thread.start()
while True:
try:
with persistent_queue.Queue(
args.queue, wal_autocheckpoint=args.wal_autocheckpoint) as queue:
reader = threading.Thread(name="read",
target=ReadLoop,
args=(args, queue))
writer = threading.Thread(name="write",
target=WriteLoop,
args=(args, queue))
reader.start()
writer.start()
reader.join()
writer.join()
except Exception:
logging.exception("Unhandled exception occurred, restarting script...")
time.sleep(5) # Wait a bit before restarting
continue
break # Exit the loop if no exceptions occurred
if __name__ == "__main__":
while True:
try:
main()
except Exception:
logging.exception("Unhandled exception occurred in main(), restarting script...")
time.sleep(5) # Wait a bit before restarting