bei einer seriellen Abfrage muss ich ein paar Bytes konvertieren und eine CRC-Summe prüfen,
es funktioniert soweit, allerdings habe ich einen komischen Fehler entdeckt, was die Abfrage verfälscht
(ein Byte mit Hex-Wert "bf" verschwindet).
Es sollen nur die Bytes:
"fe00" zu "fe", "fe12" zu "11" ...
Ändere ich die Reihenfolge im Tupel, kommt kein Fehler mehr.
Kann mir es jemand erklären?
Code-Ausschnitt mit vorgegebenem String:
Code: Alles auswählen
#!/usr/bin/env python
import binascii, struct
def READ_SERIAL(x):
c = 0; r = ""; r1 = ""; l = 5; m = 0; i = 0; r2 = "";
j = 0
while True:
#b = ser1.read(1);
b = x[j]; j += 1
c += 1; i = 0; r2 += b
if r1 == "fe" and h(b) == "00": r += a("fe"); l += 1; m += 1; i = 1
if r1 == "fe" and h(b) == "12": r += a("11"); l += 1; m += 1; i = 1
if r1 == "fe" and h(b) == "14": r += a("13"); l += 1; m += 1; i = 1
if r1 == "02" and h(b) == "00": r += a("02"); l += 1; m += 1; i = 1
if r1 == "2b" and h(b) == "00": r += a("2b"); l += 1; m += 1; i = 1
r1 = ""
#if c >= 2 and c != l and h(b) in "fe" "02" "2b" : r1 = h(b) # nutzt man diese Reihenfolge, ist alles ok
if c >= 2 and c != l and h(b) in "2b" "fe" "02" : r1 = h(b) # hier eben nicht
else:
if i == 0: r += b
if c == 5:
try:
l += struct.unpack('>H', (r[2:4]))[0]
except:
print "LAENGE NICHT FESTGELEGT"
if c == l and (h(b) == "fe" or h(b) == "02" or h(b) == "2b"): l += 1
if c == l: return r2,l,r
def a(wert):
a = binascii.a2b_hex(wert)
return a
def h(wert):
h = binascii.b2a_hex(wert)
return h
def crc(s,a):
c = 0; crc = 0
while c < (len(s) - a):
crc = crc ^ (ord(s[c]) ^ ((ord(s[c]) * 2 & 255)))
c += 1
return chr(crc)
def READ_AUSGABE(read):
tel = read[0]; i = read[1] - 1
telc = read[2]
print "RECV<", h(tel),
if h(tel[i]) == h(crc(tel,1)): print "CRC OK"
else: print "NO CRC"
print "RECV<", h(telc),
if h(tel[i]) == h(crc(telc,1)): print "CRC OK"
else: print "NO CRC"
return telc
b = a("02fd000c420100bf3cdcffffffffffff31")
read = READ_SERIAL(b)
telc = READ_AUSGABE(read)
Die Ausgabe ist:
Code: Alles auswählen
RECV< 02fd000c420100bf3cdcffffffffffff31 CRC OK
RECV< 02fd000c4201003cdcffffffffffff31 NO CRC
Code: Alles auswählen
RECV< 02fd000c420100bf3cdcffffffffffff31 CRC OK
RECV< 02fd000c420100bf3cdcffffffffffff31 CRC OK