This repository has been archived by the owner on Nov 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcar.py
85 lines (63 loc) · 1.94 KB
/
car.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
import logging
import os
import typing
from collections import namedtuple
import obd
from obd.OBDResponse import Status, StatusTest, Monitor, MonitorTest
from stubs import ObdStub
logger = logging.getLogger(__name__)
USE_STUBS = int(os.environ.get('USE_STUBS', "0"))
ResponseStub = namedtuple("ResponseStub", ["value"])
def deserialize_value(name, test) -> str:
if isinstance(test, StatusTest):
if test.available:
if test.complete:
result = True
else:
result = False
return {name: result}
return {}
elif isinstance(test, MonitorTest):
return test.__dict__
else:
return {name: test}
def deserialize(cmd, response) -> typing.Optional[typing.Dict[str, str]]:
value = response.value
if value is None:
return None
name = cmd.name.lower()
if isinstance(value, Status) or isinstance(value, Monitor):
result = {}
for key, test_value in value.__dict__.items():
if not key or key.startswith('_'):
continue
data = deserialize_value(key, test_value)
for test, test_result_value in data.items():
if test_result_value is not None:
result[f"{name}_{test}"] = str(test_result_value)
return result
else:
return {name: str(value)}
class Car:
def __init__(self, device: str):
self._device = device
self._obd_con = None
while self._obd_con is None or not self._obd_con.is_connected():
self._obd_con = self._get_obd_connection()
def _get_obd_connection(self) -> obd.OBD:
logger.info("Connecting OBD...")
obd_con = ObdStub(self._device) if USE_STUBS else obd.OBD(self._device)
if obd_con.is_connected():
logger.info("OBD connected")
else:
logger.info("OBD not connected")
return obd_con
def obd_read(self) -> typing.Dict[str, str]:
data = {}
for cmd in self._obd_con.supported_commands:
response = self._obd_con.query(cmd)
values = deserialize(cmd, response)
if values is not None:
data.update(**values)
logger.info("%d records read: %s", len(data), data)
return data