1 # Copyright (C) - Robin Krens - 2024
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 import serial.threaded
38 def find_device(vendor_id, product_id):
39 dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)
41 raise ValueError(f"Device {vendor_id}:{product_id} not found\n Are you sure it is connected?")
45 if usb.util.find_descriptor(config, custom_match=lambda d: (d.bInterfaceClass == 0x02 or d.bInterfaceClass == 0xFF)):
46 print(f"Found serial device with 0x02 | 0xFF")
48 if dev.is_kernel_driver_active(intf.bInterfaceNumber):
49 print(f"Found kernel driver, detaching ... ")
50 dev.detach_kernel_driver(intf.bInterfaceNumber)
52 if (ep.bmAttributes == 0x02):
53 if ep.bEndpointAddress == EP_IN:
56 elif ep.bEndpointAddress == EP_OUT:
59 return (dev, RxD, TxD)
61 raise ValueError("Device does not have a serial interface")
63 def establish_connection():
64 dev, rx_ep, tx_ep = find_device(0x1a86, 0x7523)
66 for i in range(MAX_TRIES):
68 tx_ep.write(b'\x00', 100)
69 ret = rx_ep.read(1, 100)
74 print(f"Timeout: retry #", i)
77 def confirm_connection():
78 dev, rx_ep, tx_ep = find_device(0x1a86, 0x7523)
80 for i in range(MAX_TRIES):
82 tx_ep.write(b'\x55', 100)
83 ret = rx_ep.read(1, 100)
88 print(f"Timeout: retry #", i)
91 if not establish_connection():
92 print("Cannot connect")
95 if not confirm_connection():
96 print("Failed to confirm boot code")