esp-web-tools
Version:
Web tools for ESP devices
52 lines (51 loc) • 2.66 kB
JavaScript
/**
* Building blocks shared by all USB-UART bridge drivers.
*
* A driver knows how to talk to one family of chips over WebUSB: which
* interface to claim, how to initialise the chip, how to program baud rate and
* modem lines. The generic `UsbSerialPort` (port.ts) turns any driver into the
* Web Serial API surface that esptool-js, the Improv SDK and the console use.
*/
const matchesFilter = (device, filter) => {
if (filter.vendorId !== undefined && filter.vendorId !== device.vendorId) {
return false;
}
if (filter.productId !== undefined && filter.productId !== device.productId) {
return false;
}
if (filter.classCode === undefined) {
return true;
}
if (device.deviceClass === filter.classCode) {
return true;
}
return device.configurations.some((config) => config.interfaces.some((iface) => iface.alternates.some((alt) => alt.interfaceClass === filter.classCode)));
};
export const matchesDefinition = (device, definition) => definition.filters.some((f) => matchesFilter(device, f));
/** Find the first interface (alternate 0) of the active configuration. */
export const findInterface = (device, classCode) => { var _a; return (_a = device.configuration) === null || _a === void 0 ? void 0 : _a.interfaces.find((iface) => { var _a; return ((_a = iface.alternates[0]) === null || _a === void 0 ? void 0 : _a.interfaceClass) === classCode; }); };
/** Find the bulk IN and OUT endpoints of an interface (alternate 0). */
export const findBulkEndpoints = (iface) => {
const endpoints = iface.alternates[0].endpoints.filter((ep) => ep.type === "bulk");
const inEp = endpoints.find((ep) => ep.direction === "in");
const outEp = endpoints.find((ep) => ep.direction === "out");
if (!inEp || !outEp) {
throw new Error(`Interface ${iface.interfaceNumber} has no bulk IN and OUT endpoints`);
}
return { in: inEp, out: outEp };
};
/** controlTransferOut that throws when the device does not ACK. */
export const controlOut = async (device, setup, data) => {
const result = await device.controlTransferOut(setup, data);
if (result.status !== "ok") {
throw new Error(`USB control request 0x${setup.request.toString(16)} failed: ${result.status}`);
}
};
/** controlTransferIn that throws when the device does not ACK. */
export const controlIn = async (device, setup, length) => {
const result = await device.controlTransferIn(setup, length);
if (result.status !== "ok" || !result.data) {
throw new Error(`USB control request 0x${setup.request.toString(16)} failed: ${result.status}`);
}
return result.data;
};