pacer2influxdb/pacer2influxdb.py

84 lines
3.4 KiB
Python
Executable File

#!/usr/bin/env python3
"""Export Pacer data to InfluxDB"""
import datetime
import time
import sqlite3 as lite
import argparse
from influxdb import InfluxDBClient
def main(args):
"""Instantiate the connection to the InfluxDB client."""
influx_db = InfluxDBClient(args.host, args.port, args.user, args.password, args.dbname)
measurements = influx_db.get_list_measurements()
time_stamp = 0
lastdate = 0
laststeps = 0
if measurements != []:
lastentry = influx_db.query('SELECT LAST("steps") FROM "steps"')
points = lastentry.get_points('steps')
lastdate = list(points)[0]['time']
time_stamp = time.mktime(datetime.datetime.strptime(lastdate, '%Y-%m-%dT%H:%M:%SZ')
.timetuple())
if time_stamp == datetime.datetime.now().timestamp() // 86400 * 86400 + time.timezone:
points = lastentry.get_points('steps')
laststeps = list(points)[0]['last']
if args.verbose:
print(f'last entry is {lastdate}, timestamp is {time_stamp}, \
number of steps is {laststeps}\n')
con = lite.connect(args.dbfile)
with con:
cur = con.cursor()
cur.execute(f'SELECT recordedForDate,steps,distanceInMeters,activeTimeInSeconds,calories \
FROM dailyActivityLog \
WHERE recordedForDate >= {time_stamp} AND steps > {laststeps}')
while True:
row = cur.fetchone()
if row is None:
break
mytime = datetime.datetime.fromtimestamp(row[0]).strftime('%Y-%m-%dT%H:%M:%SZ')
data = [{"measurement":"steps",
"time":mytime,
"fields": {
"steps":row[1],
"distanceInMeters":row[2],
"activeTimeInSeconds":row[3],
"calories":row[4]
}
}]
if args.verbose:
print(f'writing data for {mytime}')
influx_db.write_points(data)
influx_db.close()
def parse_args():
"""Parse the args from main."""
parser = argparse.ArgumentParser(
description='Export Pacer data to InfluxDB')
parser.add_argument('-v', '--verbose', required=False,
action="store_true",
help='verbose output')
parser.add_argument('-H', '--host', type=str, required=False,
default='localhost',
help='hostname of InfluxDB http API')
parser.add_argument('-u', '--user', type=str, required=False,
default='root',
help='username for InfluxDB http API')
parser.add_argument('-p', '--password', type=str, required=False,
default='root',
help='passworid for InfluxDB http API')
parser.add_argument('-P', '--port', type=int, required=False, default=8086,
help='port of InfluxDB http API')
parser.add_argument('-n', '--dbname', type=str, required=True, default='demo',
help='InfluxDB database name')
parser.add_argument('-f', '--dbfile', type=str, required=True, default='demo.db',
help='sqlite (pacer) database name')
return parser.parse_args()
if __name__ == '__main__':
main(parse_args())