Skip to content

Commit 2dc2437

Browse files
author
Brendan Whitfield
committed
converted DTC decoders to work with messages
1 parent 445a086 commit 2dc2437

2 files changed

Lines changed: 35 additions & 19 deletions

File tree

‎obd/decoders.py‎

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -330,38 +330,47 @@ def fuel_type(_hex):
330330
return (v, Unit.NONE)
331331

332332

333-
# converts 2 bytes of hex into a DTC code
334-
def single_dtc(_hex):
333+
def single_dtc(_bytes):
334+
""" converts 2 bytes into a DTC code """
335335

336-
if len(_hex) != 4:
336+
# check validity (also ignores padding that the ELM returns)
337+
if (len(_bytes) != 2) or (_bytes == (0,0)):
337338
return None
338339

339-
if _hex == "0000":
340-
return None
341-
342-
bits = bitstring(_hex[0], 4)
340+
# BYTES: (16, 35 )
341+
# HEX: 4 1 2 3
342+
# BIN: 01000001 00100011
343+
# [][][ in hex ]
344+
# | / /
345+
# DTC: C0123
343346

344-
dtc = ""
345-
dtc += ['P', 'C', 'B', 'U'][unbin(bits[0:2])]
346-
dtc += str(unbin(bits[2:4]))
347-
dtc += _hex[1:4]
347+
dtc = ['P', 'C', 'B', 'U'][ _bytes[0] >> 6 ] # the last 2 bits of the first byte
348+
dtc += str( (_bytes[0] >> 4) & 0b0011 ) # the next pair of 2 bits. Mask off the bits we read above
349+
dtc += bytes_to_hex(_bytes)[1:4]
348350

349351
return dtc
350352

351-
# converts a frame of 2-byte DTCs into a list of DTCs
352-
# example input = "010480034123"
353-
# [ ][ ][ ]
354-
def dtc(_hex):
353+
def dtc(messages):
354+
""" converts a frame of 2-byte DTCs into a list of DTCs """
355355
codes = []
356-
for n in range(0, len(_hex), 4):
357-
dtc = single_dtc(_hex[n:n+4])
356+
d = []
357+
for message in messages:
358+
d += message.data
358359

359-
if dtc is not None:
360+
print(bytes_to_hex(d))
360361

362+
# look at data in pairs of bytes
363+
for n in range(0, len(d), 2):
364+
365+
# parse the code
366+
dtc = single_dtc( (d[n], d[n+1]) )
367+
368+
if dtc is not None:
361369
# pull a description if we have one
362-
desc = "Unknown error code"
363370
if dtc in DTC:
364371
desc = DTC[dtc]
372+
else:
373+
desc = "Unknown error code"
365374

366375
codes.append( (dtc, desc) )
367376

‎obd/utils.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,13 @@ def bytes_to_bits(bs):
7979
bits += ("0" * (8 - len(v))) + v # pad it with zeros
8080
return bits
8181

82+
def bytes_to_hex(bs):
83+
h = ""
84+
for b in bs:
85+
bh = hex(b)[2:]
86+
h += ("0" * (2 - len(bh))) + bh
87+
return h
88+
8289
def ascii_to_bytes(a):
8390
""" converts a string of hex to an array of integer byte values """
8491
return [ unhex(a[i:i+2]) for i in range(0, len(a), 2) ]

0 commit comments

Comments
 (0)