|
| 1 | +let device = null; |
| 2 | + |
| 3 | +class UsbError extends Error { |
| 4 | + constructor(message) { |
| 5 | + super(message); |
| 6 | + this.name = this.constructor.name; |
| 7 | + } |
| 8 | +} |
| 9 | + |
| 10 | +async function connectFastboot() { |
| 11 | + device = await navigator.usb.requestDevice({ |
| 12 | + filters: [ |
| 13 | + { vendorId: 0x18d1, productId: 0x4ee0 }, |
| 14 | + ], |
| 15 | + }); |
| 16 | + console.log('dev', device); |
| 17 | + |
| 18 | + // Validate device |
| 19 | + let interface = device.configurations[0].interfaces[0].alternates[0]; |
| 20 | + if (interface.endpoints.length != 2) { |
| 21 | + throw new UsbError('Interface has wrong number of endpoints'); |
| 22 | + } |
| 23 | + |
| 24 | + if (interface.interfaceClass != 255 || interface.interfaceProtocol != 3 || interface.interfaceSubclass != 66) { |
| 25 | + throw new UsbError('Interface has wrong class, subclass, or protocol'); |
| 26 | + } |
| 27 | + |
| 28 | + let epIn = null; |
| 29 | + let epOut = null; |
| 30 | + for (let endpoint of interface.endpoints) { |
| 31 | + console.log('check endpoint', endpoint) |
| 32 | + if (endpoint.type != 'bulk') { |
| 33 | + throw new UsbError('Interface endpoint is not bulk'); |
| 34 | + } |
| 35 | + |
| 36 | + if (endpoint.direction == 'in') { |
| 37 | + if (epIn == null) { |
| 38 | + epIn = endpoint.endpointNumber; |
| 39 | + } else { |
| 40 | + throw new UsbError('Interface has multiple IN endpoints'); |
| 41 | + } |
| 42 | + } else if (endpoint.direction == 'out') { |
| 43 | + if (epOut == null) { |
| 44 | + epOut = endpoint.endpointNumber; |
| 45 | + } else { |
| 46 | + throw new UsbError('Interface has multiple OUT endpoints'); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + console.log('eps: in', epIn, 'out', epOut); |
| 51 | + |
| 52 | + await device.open(); |
| 53 | + await device.reset(); |
| 54 | + await device.selectConfiguration(1); |
| 55 | + await device.claimInterface(0); // fastboot |
| 56 | +} |
| 57 | + |
| 58 | +async function sendCommand(device, command) { |
| 59 | + if (command.length > 64) { |
| 60 | + throw new RangeError(); |
| 61 | + } |
| 62 | + |
| 63 | + let cmdPacket = new TextEncoder('utf-8').encode(command); |
| 64 | + await device.transferOut(0x01, cmdPacket); |
| 65 | + |
| 66 | + let returnStr = '' |
| 67 | + let response; |
| 68 | + do { |
| 69 | + let respPacket = await device.transferIn(0x01, 64); |
| 70 | + console.log('resppacket', respPacket) |
| 71 | + response = new TextDecoder().decode(respPacket.data); |
| 72 | + console.log('resppacket', respPacket, 'resp', response); |
| 73 | + |
| 74 | + if (response.startsWith('OKAY')) { |
| 75 | + returnStr += response.substring(4); |
| 76 | + } else { |
| 77 | + returnStr += `[${response.substring(0, 4)}]: ${response.substring(4)}\n`; |
| 78 | + } |
| 79 | + } while (response.startsWith('INFO')); |
| 80 | + |
| 81 | + return returnStr; |
| 82 | +} |
0 commit comments