forked from EVNotify/EVNotiPi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabrp.py
159 lines (132 loc) · 5.62 KB
/
abrp.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
""" Direct submission of data to ABRP. """
from time import monotonic, sleep
from threading import Thread, Condition
import json
import logging
import requests
PID_MAP = {
'SOC_DISPLAY': ['soc', 1], # %
'dcBatteryPower': ['power', 2], # kW
'speed': ['speed', 1], # km/h
'latitude': ['lat', 9], # °
'longitude': ['lon', 9], # °
'charging': ['is_charging', 0], # bool 1/0
'rapidChargePort': ['is_dcfc', 0], # bool 1/0
'isParked': ['is_parked', 0], # bool 1/0
'cumulativeEnergyCharged': ['kwh_charged', 2], # kWh
'soh': ['soh', 1], # %
'heading': ['heading', 2], # °
'altitude': ['elevation', 1], # m
'externalTemperature': ['ext_temp', 1], # °C
'batteryAvgTemperature': ['batt_temp', 1], # °C
'dcBatteryVoltage': ['voltage', 2], # V
'dcBatteryCurrent': ['current', 2], # A
'odo': ['odometer', 2], # km
}
API_URL = "https://api.iternio.com/1/tlm"
class SubmitError(Exception):
""" Problem while submitting data. """
class ABRP:
""" The ABRP class """
def __init__(self, config, car):
self._log = logging.getLogger("EVNotiPi/ABRP")
self._log.info("Initializing ABRP")
self._car = car
self._config = config
self._api_key = config['api_key']
self._token = config['token']
self._poll_interval = config['interval']
self._running = False
self._thread = None
self._data_queue = []
self._data_queue_lock = Condition()
def start(self):
""" Start the submission thread """
self._running = True
self._thread = Thread(target=self.submit_data, name="EVNotiPi/ABRP")
self._thread.start()
self._car.register_data(self.data_callback)
def stop(self):
""" Stop the submission thread """
self._car.unregister_data(self.data_callback)
self._running = False
with self._data_queue_lock:
self._data_queue_lock.notify()
self._thread.join()
def data_callback(self, data):
""" Callback to get new data from "car" """
self._log.debug("Enqeue...")
with self._data_queue_lock:
if data['SOC_DISPLAY'] is not None:
self._data_queue.append(data)
self._data_queue_lock.notify()
def submit_data(self):
""" Data submission thread """
session = requests.Session()
while self._running:
now = monotonic()
avgs = {
'dcBatteryCurrent': [],
'dcBatteryPower': [],
'dcBatteryVoltage': [],
'speed': [],
'latitude': [],
'longitude': [],
'heading': [],
'altitude': [],
}
with self._data_queue_lock:
self._log.debug('Waiting...')
self._data_queue_lock.wait()
if len(self._data_queue) == 0:
continue
new_data = self._data_queue.copy()
self._data_queue.clear()
for data in new_data:
for key, values in avgs.items():
if key in data and data[key] is not None:
values.append(data[key])
data = new_data[-1]
if not 'timestamp' in data or data['timestamp'] is None:
continue
payload = {
'utc': int(data['timestamp']),
'power': 0,
'current': 0,
}
payload.update({v[0]: round(data[k], v[1]) for k, v in PID_MAP.items()
if k in data and data[k] is not None})
# Apply averages
payload.update({PID_MAP[k][0]: round(
sum(v)/len(v), PID_MAP[k][1]) for k, v in avgs.items() if len(v) > 0})
if 'speed' in payload:
payload['speed'] *= 3.6 # convert from m/s to km/h
else:
# Skip iteration, ABRP does not accept payload without speed field
self._log.debug("speed missing, skip... %s", payload)
continue
self._log.debug("Transmit...")
try:
self._log.debug("Send payload %s", payload)
payload_str = json.dumps(payload)
ret = session.post(API_URL + "/send",
data={'api_key': self._api_key,
'token': self._token,
'tlm': payload_str})
if ret.status_code != requests.codes.ok or ret.json()['status'] != "ok":
self._log.error("Submit error: %s %s %s",
payload_str, str(ret), ret.text)
else:
self._log.debug("Post result: %i %s",
ret.status_code, ret.text)
except requests.exceptions.ConnectionError as err:
self._log.error("ConnectionError: %s", err)
except SubmitError as err:
self._log.error("SubmitError: %s", err)
# Prime next loop iteration
if self._running:
interval = self._poll_interval - (monotonic() - now)
sleep(max(0, interval))
def check_thread(self):
""" Return the status of the thread """
return self._thread.is_alive()