Skip to content

Commit

Permalink
iss #47: [wip]
Browse files Browse the repository at this point in the history
  • Loading branch information
maizy committed Feb 16, 2019
1 parent 2ec25f9 commit 2229be6
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
4 changes: 2 additions & 2 deletions ambient7-arduino/serial2influxdb/config.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ baud=9600
server=localhost
port=8086
username=influxdb
passwork=pa$$word
password=pa$$word
database=ambient7

[metrics]
prefix="ambient7_"
prefix=ambient7_
47 changes: 45 additions & 2 deletions ambient7-arduino/serial2influxdb/serial2influxdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
import configparser
import logging
import time
import re
import datetime

import serial
import influxdb


SERIAL_RETRY_DELAY = 5.0
Expand All @@ -31,7 +34,8 @@ def open_serial(config):
return serial.Serial(
port=config['serial']['tty'],
baudrate=int(config['serial']['baud']),
timeout=1
timeout=1,
exclusive=True
)
except serial.SerialException as e:
logger.warning('unable to open pyserial connection: {}'.format(e))
Expand Down Expand Up @@ -60,17 +64,56 @@ def resilient_line_generator(config):
pass


def collect_data(key, value, measurement_prefix):
data = {
'time': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),
'measurement': measurement_prefix + key
}
if key == 'uptime':
data['fields'] = {'value': int(value.rstrip('s'))}
else:
return None
return [data]


def build_influxdb_client(config):
opts = {
'host': config['influxdb']['server'],
'port': int(config['influxdb']['port']),
'database': config['influxdb']['database']
}
if 'username' in config['influxdb']:
opts['username'] = config['influxdb']['username']
opts['password'] = config['influxdb']['password']
return influxdb.InfluxDBClient(**opts)


def main(args):
cli_args, config = parse_args_and_config(args)

influxdb_client = build_influxdb_client(config)

logging.basicConfig(
level=logging.DEBUG if cli_args.verbose else logging.INFO,
stream=sys.stderr,
format='%(asctime)s %(levelname).1s %(message)s'
)

for line in resilient_line_generator(config):
logger.debug(line)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("receive line: %r", line)
data_match = re.match(r'DATA: (?P<key>[a-z0-9_]+)=(?P<value>.+)', line, re.IGNORECASE)
if data_match is not None:
key = data_match.group('key')
raw_value = data_match.group('value')
logging.debug('Key=%s Value=%s', key, raw_value)

data = collect_data(key, raw_value, measurement_prefix=config['metrics']['prefix'])
logger.info(data)

if data is not None:
influxdb_client.write_points(data)


return 0

Expand Down

0 comments on commit 2229be6

Please sign in to comment.