-
Notifications
You must be signed in to change notification settings - Fork 1
/
currentcost.py
executable file
·59 lines (40 loc) · 1.22 KB
/
currentcost.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
#!/usr/bin/env python
import datetime
import serial
from xml.etree.cElementTree import fromstring
import time
import csv
import signal
import sys
class UTC(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(0)
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return datetime.timedelta(0)
def utc_now_string():
return datetime.datetime.now(UTC()).strftime('%Y-%m-%dT%H:%M:%SZ')
serial = serial.Serial('/dev/ttyUSB0', 57600)
with open('/srv/currentcost/currentcost.csv', 'a') as csvfile:
writer = csv.writer(csvfile)
def signal_term_handler(signal, frame):
csvfile.flush()
sys.exit(0)
signal.signal(signal.SIGTERM, signal_term_handler)
try:
while True:
msg = serial.readline()
if not msg:
raise ValueError('Time out')
xml = fromstring(msg)
if xml.tag != 'msg':
continue
if xml.find('hist'):
continue
watts = int(xml.find('ch1').find('watts').text)
timestamp = utc_now_string()
row = [timestamp, watts]
writer.writerow(row)
except KeyboardInterrupt:
csvfile.flush()