Skip to content

Commit dad86e7

Browse files
committed
connections/PybricksHub: Read one checksum.
1 parent d4470d7 commit dad86e7

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

pybricksdev/connections.py

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -601,6 +601,9 @@ def __init__(self):
601601
self.output = []
602602
self.print_output = True
603603

604+
self.checksum_ready = asyncio.Event()
605+
self.expected_checksum = -1
606+
604607
def line_handler(self, line):
605608
self.output.append(line)
606609
if self.print_output:
@@ -609,8 +612,15 @@ def line_handler(self, line):
609612
def nus_handler(self, sender, data):
610613

611614
# If no program is running, read checksum bytes.
612-
if not self.program_running:
613-
print(data)
615+
if not self.program_running and self.expected_checksum >= 0:
616+
if data[0] == self.expected_checksum:
617+
self.checksum_ready.set()
618+
self.logger.debug("Correct checksum: {0}".format(data[0]))
619+
else:
620+
self.logger.warning("Expected checksum {0} but got {1}".format(
621+
self.expected_checksum,
622+
data[0]
623+
))
614624
return
615625

616626
# Store incoming data
@@ -658,15 +668,24 @@ async def disconnect(self):
658668
self.logger.info("Disconnecting...")
659669
await self.client.disconnect()
660670

661-
async def write(self, data, pause=0, with_response=False):
662-
await self.client.write_gatt_char(
663-
NUS_RX_UUID,
664-
bytearray(data),
665-
with_response
666-
)
667-
await asyncio.sleep(pause)
671+
def get_checksum(self, block):
672+
checksum = 0
673+
for b in block:
674+
checksum ^= b
675+
return checksum
676+
677+
async def send_block(self, data):
678+
self.checksum_ready.clear()
679+
self.expected_checksum = self.get_checksum(data)
680+
await self.client.write_gatt_char(NUS_RX_UUID, bytearray(data), False)
681+
try:
682+
await asyncio.wait_for(self.checksum_ready.wait(), timeout=0.5)
683+
except asyncio.TimeoutError:
684+
self.logger.warning("Error during program download.")
685+
return
686+
self.expected_checksum = 0
668687

669688
async def run(self, py_path, wait=True, print_output=True):
670689
await asyncio.sleep(4)
671-
await self.write(b" ")
690+
await self.send_block(b" ")
672691
await asyncio.sleep(4)

0 commit comments

Comments
 (0)