forked from EVNotify/EVNotiPi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evnotipi.py
executable file
·185 lines (151 loc) · 5.83 KB
/
evnotipi.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
#!/usr/bin/env python3
from gpspoller import GpsPoller
from subprocess import check_call
from time import sleep,time
import evnotifyapi
import io
import json
import os
import re
import string
import sys
import signal
LOOP_DELAY = 5
EVN_SETTINGS_DELAY = 300
ABORT_NOTIFICATION_DELAY = 60
# load config
with open('config.json', encoding='utf-8') as config_file:
config = json.loads(config_file.read())
# load api lib
EVNotify = evnotifyapi.EVNotify(config['akey'], config['token'])
settings = None
if 'cartype' in config:
cartype = config['cartype']
else:
# get settings from backend
while settings == None:
try:
settings = EVNotify.getSettings()
except EVNotify.CommunicationError as e:
print("Waiting for network connectivity")
sleep(3)
cartype = settings['car']
# Load OBD2 interface module
if not "{}.py".format(config['dongle']['type']) in os.listdir('dongles'):
raise Exception('Unknown dongle {}'.format(config['dongle']['type']))
# Init ODB2 adapter
sys.path.insert(0, 'dongles')
exec("from {0} import {0} as DONGLE".format(config['dongle']['type']))
sys.path.remove('dongles')
# Only accept a few characters, do not trust stuff from the Internet
if re.match('^[a-zA-Z0-9_-]+$',cartype) == None:
raise Exception('Invalid characters in cartype')
if not "{}.py".format(cartype) in os.listdir('cars'):
raise Exception('Unknown car {}'.format(cartype))
sys.path.insert(0, 'cars')
exec("from {0} import {0} as CAR".format(cartype))
sys.path.remove('cars')
dongle = DONGLE(config['dongle'])
car = CAR(dongle)
# Init GPS interface
gps = GpsPoller()
gps.start()
# Init some variables
main_running = True
# Init SOC notifications
chargingStartSOC = 0
socThreshold = int(config['socThreshold']) if 'socThreshold' in config else 0
notificationSent = False
abortNotificationSent = False
last_charging = time()
last_evn_settings_poll = time()
print("Notification threshold: {}".format(socThreshold))
# Set up signal handling
def exit_gracefully(signum, frame):
sys.exit(0)
signal.signal(signal.SIGTERM, exit_gracefully)
try:
while main_running:
now = time()
try:
data = car.getData()
fix = gps.fix()
except DONGLE.CAN_ERROR as e:
print(e)
except DONGLE.NO_DATA as e:
print(e)
except CAR.LOW_VOLTAGE as e:
print('Low Voltage ({})'.format(e))
except CAR.NULL_BLOCK as e:
print(e)
except:
raise
else:
print(data)
try:
if 'SOC_DISPLAY' in data and 'SOC_BMS' in data:
EVNotify.setSOC(data['SOC_DISPLAY'], data['SOC_BMS'])
currentSOC = data['SOC_DISPLAY'] or data['SOC_BMS']
if 'EXTENDED' in data:
EVNotify.setExtended(data['EXTENDED'])
is_charging = True if 'charging' in data['EXTENDED'] and \
data['EXTENDED']['charging'] == 1 else False
# TODO: check if really connected, once connection detection is working in KONA module
is_connected = True
if is_charging:
last_charging = now
if is_charging and 'socThreshold' not in config and \
now - last_evn_settings_poll > EVN_SETTINGS_DELAY:
try:
s = EVNotify.getSettings()
# following only happens if getSettings is successful, else jumps into exception handler
settings = s
last_evn_settings_poll = now
if s['soc'] and s['soc'] != socThreshold:
socThreshold = int(s['soc'])
print("New notification threshold: {}".format(socThreshold))
except EVNotify.CommunicationError:
pass
# track charging started
if is_charging and chargingStartSOC == 0:
chargingStartSOC = currentSOC or 0
# check if notification threshold reached
elif is_charging and chargingStartSOC < socThreshold and \
currentSOC >= socThreshold and not notificationSent:
print("Notification threshold reached")
EVNotify.sendNotification()
notificationSent = True
elif not is_charging: # Rearm notification
chargingStartSOC = 0
notificationSent = False
if fix and fix.mode > 1: # mode: GPS-fix quality
g ={
'latitude': fix.latitude,
'longitude': fix.longitude,
'speed': fix.speed,
}
print(g)
EVNotify.setLocation({'location': g})
except EVNotify.CommunicationError as e:
print(e)
except:
raise
finally:
try:
if not abortNotificationSent and \
now - last_charging > ABORT_NOTIFICATION_DELAY and chargingStartSOC > 0:
print("No response detected, send abort notification")
EVNotify.sendNotification(True)
abortNotificationSent = True
except EVNotify.CommunicationError as e:
print("Sending of notificatin failed! {}".format(e))
sys.stdout.flush()
if main_running: sleep(LOOP_DELAY)
except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
main_running = False
except:
raise
finally:
print("Exiting ...")
gps.stop()
print("Bye.")