forked from brendan-w/python-OBD
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
189 lines (148 loc) · 5.89 KB
/
utils.py
File metadata and controls
189 lines (148 loc) · 5.89 KB
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
185
186
187
188
189
# -*- coding: utf-8 -*-
########################################################################
# #
# python-OBD: A python OBD-II serial module derived from pyobd #
# #
# Copyright 2004 Donour Sizemore (donour@uchicago.edu) #
# Copyright 2009 Secons Ltd. (www.obdtester.com) #
# Copyright 2009 Peter J. Creath #
# Copyright 2015 Brendan Whitfield (bcw7044@rit.edu) #
# #
########################################################################
# #
# utils.py #
# #
# This file is part of python-OBD (a derivative of pyOBD) #
# #
# python-OBD is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 2 of the License, or #
# (at your option) any later version. #
# #
# python-OBD is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with python-OBD. If not, see <http://www.gnu.org/licenses/>. #
# #
########################################################################
import serial
import errno
import string
import glob
import sys
import logging
logger = logging.getLogger(__name__)
class OBDStatus:
""" Values for the connection status flags """
NOT_CONNECTED = "Not Connected"
ELM_CONNECTED = "ELM Connected"
CAR_CONNECTED = "Car Connected"
class bitarray:
"""
Class for representing bitarrays (inefficiently)
There's a nice C-optimized lib for this: https://github.com/ilanschnell/bitarray
but python-OBD doesn't use it enough to be worth adding the dependency.
But, if this class starts getting used too much, we should switch to that lib.
"""
def __init__(self, _bytearray):
self.bits = ""
for b in _bytearray:
v = bin(b)[2:]
self.bits += ("0" * (8 - len(v))) + v # pad it with zeros
def __getitem__(self, key):
if isinstance(key, int):
if key >= 0 and key < len(self.bits):
return self.bits[key] == "1"
else:
return False
elif isinstance(key, slice):
bits = self.bits[key]
if bits:
return [ b == "1" for b in bits ]
else:
return []
def num_set(self):
return self.bits.count("1")
def num_cleared(self):
return self.bits.count("0")
def value(self, start, stop):
bits = self.bits[start:stop]
if bits:
return int(bits, 2)
else:
return 0
def __len__(self):
return len(self.bits)
def __str__(self):
return self.bits
def __iter__(self):
return [ b == "1" for b in self.bits ].__iter__()
def bytes_to_int(bs):
""" converts a big-endian byte array into a single integer """
v = 0
p = 0
for b in reversed(bs):
v += b * (2**p)
p += 8
return v
def bytes_to_hex(bs):
h = ""
for b in bs:
bh = hex(b)[2:]
h += ("0" * (2 - len(bh))) + bh
return h
def twos_comp(val, num_bits):
"""compute the 2's compliment of int value val"""
if( (val&(1<<(num_bits-1))) != 0 ):
val = val - (1<<num_bits)
return val
def isHex(_hex):
return all([c in string.hexdigits for c in _hex])
def contiguous(l, start, end):
""" checks that a list of integers are consequtive """
if not l:
return False
if l[0] != start:
return False
if l[-1] != end:
return False
# for consequtiveness, look at the integers in pairs
pairs = zip(l, l[1:])
if not all([p[0]+1 == p[1] for p in pairs]):
return False
return True
def try_port(portStr):
"""returns boolean for port availability"""
try:
s = serial.Serial(portStr)
s.close() # explicit close 'cause of delayed GC in java
return True
except serial.SerialException:
pass
except OSError as e:
if e.errno != errno.ENOENT: # permit "no such file or directory" errors
raise e
return False
def scan_serial():
"""scan for available ports. return a list of serial names"""
available = []
possible_ports = []
if sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
possible_ports += glob.glob("/dev/rfcomm[0-9]*")
possible_ports += glob.glob("/dev/ttyUSB[0-9]*")
elif sys.platform.startswith('win'):
possible_ports += ["\\.\COM%d" % i for i in range(256)]
elif sys.platform.startswith('darwin'):
exclude = [
'/dev/tty.Bluetooth-Incoming-Port',
'/dev/tty.Bluetooth-Modem'
]
possible_ports += [port for port in glob.glob('/dev/tty.*') if port not in exclude]
# possible_ports += glob.glob('/dev/pts/[0-9]*') # for obdsim
for port in possible_ports:
if try_port(port):
available.append(port)
return available