7 MAX_TRANSFER_SIZE = 2048 + 6 # include header and footer
10 def __init__(self, vendor_id, product_id):
11 self.vendor_id = vendor_id
12 self.product_id = product_id
21 self.sel_area = 0 # default to Area 0
24 status_conn = self.inquire_connection()
26 self.confirm_connection()
28 def find_device(self):
29 self.dev = usb.core.find(idVendor=self.vendor_id, idProduct=self.product_id)
31 raise ValueError(f"Device {self.vendor_id}:{self.product_id} not found\nAre you sure it is connected?")
33 for config in self.dev:
35 product_name = usb.util.get_string(self.dev, self.dev.iProduct)
36 print(f'Found {product_name} ({self.vendor_id}:{self.product_id})')
37 if self.dev.is_kernel_driver_active(intf.bInterfaceNumber):
38 print("Found kernel driver, detaching ... ")
39 self.dev.detach_kernel_driver(intf.bInterfaceNumber)
41 if (ep.bmAttributes == 0x02):
42 if ep.bEndpointAddress == self.ep_in:
44 elif ep.bEndpointAddress == self.ep_out:
48 raise ValueError("Device does not have a CDC interface")
51 def inquire_connection(self):
52 packed = pack_pkt(INQ_CMD, "")
53 self.send_data(packed)
54 info = self.recv_data(7)
55 if info == bytearray(b'\x00') or info == bytearray(b''):
57 msg = unpack_pkt(info)
58 #print("Connection already established")
61 def confirm_connection(self):
62 for i in range(self.max_tries):
64 self.tx_ep.write(bytes([0x55]), self.timeout_ms)
65 ret = self.rx_ep.read(1, self.timeout_ms)
67 print("Reply received (0xC3)")
69 except usb.core.USBError as e:
70 print(f"Timeout: retry #{i}", e)
73 def authenticate_connection(self):
74 raise Exception("Not implemented")
76 def set_chip_layout(self, cfg):
78 raise ValueError("Could net get chip layout")
79 self.chip_layout = cfg
81 def send_data(self, packed_data):
82 if (self.tx_ep == None):
85 self.tx_ep.write(packed_data, self.timeout_ms)
86 except usb.core.USBError as e:
87 print(f"Timeout: error", e)
91 def recv_data(self, exp_len, timeout=100):
93 if (exp_len > MAX_TRANSFER_SIZE):
94 raise ValueError(f"length package {exp_len} over max transfer size")
95 if (self.rx_ep == None):
99 while received != exp_len:
100 buf = self.rx_ep.read(exp_len, timeout)
103 if received == exp_len:
105 except usb.core.USBError as e:
106 print(f"Timeout: error", e)