comparison vanlogger.py @ 30:a9df202d14b7

Use logging infra. Handle errors during startup nicely.
author Daniel O'Connor <darius@dons.net.au>
date Mon, 13 Dec 2021 18:16:11 +1030
parents e86e839febca
children 5b03de9fb20b
comparison
equal deleted inserted replaced
29:e86e839febca 30:a9df202d14b7
1 #!/usr/bin/env python 1 #!/usr/bin/env python
2 2
3 import sys 3 import sys
4 4
5 import datetime 5 import datetime
6 import dbus
6 import json 7 import json
8 import logging
7 import serial 9 import serial
8 import sqlite3 10 import sqlite3
9 import subprocess 11 import subprocess
10 import sys 12 import sys
13 import time
11 import victron 14 import victron
15
16 logger = logging.getLogger('vanlogger')
17 logger.setLevel(logging.INFO)
18
19 formatter = logging.Formatter('%(message)s')
20
21 ch = logging.StreamHandler()
22 ch.setLevel(logging.INFO)
23 ch.setFormatter(formatter)
24 logger.addHandler(ch)
12 25
13 # Actual epro logging moved to eprodbus.py 26 # Actual epro logging moved to eprodbus.py
14 def create(cur): 27 def create(cur):
15 cur.execute(''' 28 cur.execute('''
16 CREATE TABLE IF NOT EXISTS eprolog( 29 CREATE TABLE IF NOT EXISTS eprolog(
64 data = [int(datetime.datetime.now().strftime('%s')), ] 77 data = [int(datetime.datetime.now().strftime('%s')), ]
65 data.extend(v.get_data()) 78 data.extend(v.get_data())
66 cur.execute('INSERT INTO victron (tstamp, ACIn_L1_volts, ACIn_L1_freq, ACIn_L1_current, ACIn_active, ACOut_L1_volts, ACOut_L1_freq, ACOut_L1_current, Battery_Voltage, Battery_Current) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', data) 79 cur.execute('INSERT INTO victron (tstamp, ACIn_L1_volts, ACIn_L1_freq, ACIn_L1_current, ACIn_active, ACOut_L1_volts, ACOut_L1_freq, ACOut_L1_current, Battery_Voltage, Battery_Current) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', data)
67 80
68 def main(): 81 def main():
69 print 'Started' 82 logger.error('Started')
70 dbh = sqlite3.connect('/home/root/vanlogger/log.db') 83 dbh = sqlite3.connect('/home/root/vanlogger/log.db')
71 cur = dbh.cursor() 84 cur = dbh.cursor()
72 create(cur) 85 create(cur)
73 86
74 v = victron.Victron('com.victronenergy.vebus.ttyUSB1') 87 v = victron.Victron('com.victronenergy.vebus.ttyUSB1')
78 dolog = False 91 dolog = False
79 if then == None or datetime.datetime.now() - then > datetime.timedelta(seconds = 60): 92 if then == None or datetime.datetime.now() - then > datetime.timedelta(seconds = 60):
80 dolog = True 93 dolog = True
81 then = datetime.datetime.now() 94 then = datetime.datetime.now()
82 if dolog: 95 if dolog:
83 log_victron(v, cur) 96 try:
84 dbh.commit() 97 log_victron(v, cur)
98 except (AttributeError, dbus.exceptions.DBusException) as e:
99 # We get various errors during startup so just log and keep going
100 logger.error('Error getting data: %s', str(e))
85 101
102 dbh.commit()
103 time.sleep(30)
86 if __name__ == '__main__': 104 if __name__ == '__main__':
87 main() 105 main()