6 MAX_TRANSFER_SIZE = 2048 + 6 # include header and footer
9 def __init__(self, vendor_id, product_id):
10 self.vendor_id = vendor_id
11 self.product_id = product_id
23 print(f'Device not connected')
26 def find_device(self):
27 self.dev = usb.core.find(idVendor=self.vendor_id, idProduct=self.product_id)
29 raise ValueError(f"Device {self.vendor_id}:{self.product_id} not found\nAre you sure it is connected?")
31 for config in self.dev:
36 #if usb.util.find_descriptor(config, custom_match=lambda d: (d.bInterfaceClass == 0xa or d.bInterfaceClass == 0xBB)):
37 print("Found serial device with 0x0a | 0xFF")
38 if self.dev.is_kernel_driver_active(intf.bInterfaceNumber):
39 print("Found kernel driver, detaching ... ")
40 self.dev.detach_kernel_driver(intf.bInterfaceNumber)
44 if (ep.bmAttributes == 0x02):
45 if ep.bEndpointAddress == self.ep_in:
48 elif ep.bEndpointAddress == self.ep_out:
53 raise ValueError("Device does not have a serial interface")
55 def establish_connection(self):
56 for i in range(self.max_tries):
58 self.tx_ep.write(bytes([0x00]), self.timeout_ms)
59 ret = self.rx_ep.read(1, self.timeout_ms)
61 print("Reply ACK received (0x00)")
63 except usb.core.USBError as e:
64 print(f"Timeout: retry #{i}", e)
67 def confirm_connection(self):
68 for i in range(self.max_tries):
70 self.tx_ep.write(bytes([0x55]), self.timeout_ms)
71 ret = self.rx_ep.read(1, self.timeout_ms)
73 print("Reply received (0xC3)")
75 except usb.core.USBError as e:
76 print(f"Timeout: retry #{i}", e)
79 def authenticate_connection(self):
80 raise Exception("Not implemented")
82 def send_data(self, packed_data):
83 if (self.tx_ep == None):
86 self.tx_ep.write(packed_data, self.timeout_ms)
87 except usb.core.USBError as e:
88 print(f"Timeout: error", e)
92 # packets are length 7, except for a read package
93 def recv_data(self, exp_len):
95 if (exp_len > MAX_TRANSFER_SIZE):
96 raise ValueError(f"length package {exp_len} over max transfer size")
97 if (self.rx_ep == None):
101 while received != exp_len:
102 buf = self.rx_ep.read(exp_len, self.timeout_ms)
104 #print(buf, len(buf))
106 if received == exp_len:
108 except usb.core.USBError as e:
109 print(f"Timeout: error", e)
114 #communicator = RAConnect(vendor_id=0x1a86, product_id=0x7523)
116 #communicator.send_data(b'\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA')
117 #communicator.recv_data(7)
119 #if not communicator.establish_connection():
120 # print("Cannot connect")
123 #if not communicator.confirm_connection():
124 # print("Failed to confirm boot code")