Added address claim code

This commit is contained in:
Thomas Hooge 2025-11-09 11:09:15 +01:00
parent a2289a8621
commit 1c78f24505
1 changed files with 59 additions and 0 deletions

View File

@ -3,6 +3,9 @@ NMEA2000-Gerät
- auf dem Bus erkannte Geräte
- für das eigene Gerät steht initUid() zur Verfügung
TODO
- logging
"""
import time
@ -74,6 +77,62 @@ class Device():
self.NAME = struct.unpack_from('<Q', data, 0)[0]
return data
def send_address_claim(self, bus):
data = self.getNAME()
print("sending address claim for '{}' with name {} ...".format(self.address, data))
priority = 6
pgn = 60928
msg = can.Message(
arbitration_id = (((priority << 18) + pgn) << 8) + self.address,
data = data,
is_extended_id = True
);
try:
bus.send(msg)
print(f"Address claim sent to bus {bus.channel_info}")
except can.CanError:
print("Address claim NOT sent")
def claim_address(self, bus):
self.send_address_claim(bus)
pgn = None
claim_ok = False
t0 = time.monotonic()
while not time.monotonic() - t0 > 0.25:
# recv ist blocking. if timeout reached msg should be None
msg = bus.recv(0.25)
if msg:
baseid = (msg.arbitration_id & 0x3ffff00) >> 8
pgn = baseid & 0xffff00
if not pgn == 60928:
continue
dest = baseid & 0x0000ff
if dest == 0xff:
print("Claim detected for 0xff (broadcast)")
if self.NAME > struct.unpack_from('<Q', msg.data, 0)[0]:
# collision we have a lower priority:
# start over with new address
print("Address is in use, trying next one")
t0 = time.monotonic()
owndevice.address += 1
send_address_claim(bus)
else:
print("Ignore collision because of our lower NAME")
else:
print(f"Answer: DEST={dest}")
print(msg.data)
if dest == self.address:
print("We are addressed: WIP!")
else:
print("Frame ist not for us.")
else:
# timeout without answer
print("Timeout after claim. Keep selected address")
claim_ok = True
if not claim_ok and (time.monotonic() - t0 > 0.25):
print("claim seems ok after 250ms")
return claim_ok
def __str__(self):
out = f"Device: {self.address} : '{self.product}'\n"
out += " NAME: {} ({})\n".format(self.getNAME(), self.NAME)