How to use controlTransferIn method in wpt

Best JavaScript code snippet using wpt

interface.ts

Source:interface.ts Github

copy

Full Screen

...286 if (this.usbApiVersion < version)287 throw new HackrfError(ErrorCode.USB_API_VERSION)288 }289 // CONTROL TRANSFERS290 private controlTransferIn(bRequest: VendorRequest, wValue: number, wIndex: number, length: number): Promise<Buffer> {291 return promisify(cb => this.handle.controlTransfer(292 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,293 bRequest, wValue, wIndex, length, cb))() as Promise<Buffer>294 }295 private controlTransferOut(bRequest: VendorRequest, wValue: number, wIndex: number, data: Buffer = Buffer.alloc(0)): Promise<void> {296 return promisify(cb => this.handle.controlTransfer(297 LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,298 bRequest, wValue, wIndex, data, cb))() as Promise<void>299 }300 protected async setTransceiverMode(value: TransceiverMode) {301 await this.controlTransferOut(VendorRequest.SET_TRANSCEIVER_MODE, value, 0)302 }303 /**304 * Query the firmware version305 *306 * @category Device info307 */308 async getVersionString() {309 const buf = await this.controlTransferIn(VendorRequest.VERSION_STRING_READ, 0, 0, 255)310 return buf.toString('utf-8')311 }312 /**313 * @category Device info314 */315 async getBoardId() {316 const buf = await this.controlTransferIn(VendorRequest.BOARD_ID_READ, 0, 0, 1)317 return checkInLength(buf, 1).readUInt8() as BoardId318 }319 /**320 * @category Device info321 */322 async getBoardPartIdSerialNo() {323 const buf = await this.controlTransferIn(VendorRequest.BOARD_PARTID_SERIALNO_READ, 0, 0, 24)324 checkInLength(buf, 24)325 const u32 = [0,1,2,3,4,5].map(x => buf.readUInt32LE(x * 4))326 return {327 partId: u32.slice(0, 2) as [ number, number ],328 serialNo: u32.slice(2, 6) as [ number, number, number, number ],329 }330 }331 /**332 * @category IC333 */334 async max2837_read(register: number) {335 const buf = await this.controlTransferIn(VendorRequest.MAX2837_READ,336 0, checkMax2837Reg(register), 2)337 return checkInLength(buf, 2).readUInt16LE()338 }339 /**340 * @category IC341 */342 async max2837_write(register: number, value: number) {343 await this.controlTransferOut(VendorRequest.MAX2837_WRITE,344 checkMax2837Value(value), checkMax2837Reg(register))345 }346 /**347 * @category IC348 */349 async si5351c_read(register: number) {350 const buf = await this.controlTransferIn(VendorRequest.SI5351C_READ,351 0, checkSi5351cReg(register), 1)352 return checkInLength(buf, 1).readUInt8()353 }354 /**355 * @category IC356 */357 async si5351c_write(register: number, value: number) {358 await this.controlTransferOut(VendorRequest.SI5351C_WRITE,359 checkSi5351cValue(value), checkSi5351cReg(register))360 }361 /**362 * @category IC363 */364 async rffc5071_read(register: number) {365 const buf = await this.controlTransferIn(VendorRequest.RFFC5071_READ,366 0, checkRffc5071Reg(register), 2)367 return checkInLength(buf, 2).readUInt16LE()368 }369 /**370 * @category IC371 */372 async rffc5071_write(register: number, value: number) {373 await this.controlTransferOut(VendorRequest.RFFC5071_WRITE,374 checkRffc5071Value(value), checkRffc5071Reg(register))375 }376 /**377 * @category Flash & CPLD378 */379 async spiflash_erase() {380 await this.controlTransferOut(VendorRequest.SPIFLASH_ERASE, 0, 0)381 }382 /**383 * @category Flash & CPLD384 */385 async spiflash_write(address: number, data: Buffer) {386 checkSpiflashAddress(address)387 await this.controlTransferOut(VendorRequest.SPIFLASH_WRITE,388 address >>> 16, address & 0xFFFF, data)389 }390 /**391 * @category Flash & CPLD392 */393 async spiflash_read(address: number, length: number) {394 checkSpiflashAddress(address)395 const buf = await this.controlTransferIn(VendorRequest.SPIFLASH_READ,396 address >>> 16, address & 0xFFFF, length)397 return checkInLength(buf, length)398 }399 /**400 * TODO401 *402 * Requires USB API 1.3.403 *404 * @category Flash & CPLD405 */406 async spiflash_getStatus() {407 this.usbApiRequired(0x0103)408 const buf = await this.controlTransferIn(VendorRequest.SPIFLASH_STATUS, 0, 0, 2)409 return checkInLength(buf, 1) // FIXME410 }411 /**412 * TODO413 *414 * Requires USB API 1.3.415 *416 * @category Flash & CPLD417 */418 async spiflash_clearStatus() {419 this.usbApiRequired(0x0103)420 await this.controlTransferOut(VendorRequest.SPIFLASH_CLEAR_STATUS, 0, 0)421 }422 /**423 * Set baseband filter bandwidth in Hz424 *425 * Possible values: 1.75/2.5/3.5/5/5.5/6/7/8/9/10/12/14/15/20/24/28MHz426 *427 * @category Radio control428 */429 async setBasebandFilterBandwidth(freqHz: number) {430 checkBasebandFilterBw(checkU32(freqHz))431 await this.controlTransferOut(VendorRequest.BASEBAND_FILTER_BANDWIDTH_SET,432 freqHz & 0xffff, freqHz >>> 16)433 }434 /**435 * Set the tuning frequency436 *437 * @category Radio control438 */439 async setFrequency(freqHz: number) {440 checkFreq(freqHz)441 // convert Freq Hz 64bits to Freq MHz (32bits) & Freq Hz (32bits)442 const FREQ_ONE_MHZ = 1000*1000443 const data = Buffer.alloc(8)444 data.writeUInt32LE(freqHz / FREQ_ONE_MHZ, 0)445 data.writeUInt32LE(freqHz % FREQ_ONE_MHZ, 4)446 await this.controlTransferOut(VendorRequest.SET_FREQ, 0, 0, data)447 }448 /**449 * Set the tuning frequency (raw version)450 *451 * @param iFreqHz intermediate frequency452 * @param loFreqHz front-end local oscillator frequency453 * @param path image rejection filter path454 * @category Radio control455 */456 async setFrequencyExplicit(iFreqHz: number, loFreqHz: number, path: RfPathFilter) {457 checkIFreq(iFreqHz)458 if (path !== RfPathFilter.BYPASS)459 checkLoFreq(loFreqHz)460 if (checkU32(path) > 2)461 throw new HackrfError(ErrorCode.INVALID_PARAM)462 const data = Buffer.alloc(8 + 8 + 1)463 data.writeBigUInt64LE(BigInt(iFreqHz), 0)464 data.writeBigUInt64LE(BigInt(loFreqHz), 8)465 data.writeUInt8(path, 16)466 await this.controlTransferOut(VendorRequest.SET_FREQ_EXPLICIT, 0, 0, data)467 }468 /**469 * Set the sample rate (raw version)470 *471 * You should probably use [[setSampleRate]] instead of this472 * function.473 *474 * For anti-aliasing, the baseband filter bandwidth is automatically set to the475 * widest available setting that is no more than 75% of the sample rate. This476 * happens every time the sample rate is set. If you want to override the477 * baseband filter selection, you must do so after setting the sample rate.478 *479 * 2-20Mhz - as a fraction, i.e. freq 20000000 divider 2 -> 10Mhz480 *481 * @category Radio control482 */483 async setSampleRateManual(freqHz: number, divider: number) {484 const data = Buffer.alloc(8)485 data.writeUInt32LE(freqHz, 0)486 data.writeUInt32LE(divider, 4)487 await this.controlTransferOut(VendorRequest.SAMPLE_RATE_SET, 0, 0, data)488 }489 /**490 * Set the sample rate491 *492 * For anti-aliasing, the baseband filter bandwidth is automatically set to the493 * widest available setting that is no more than 75% of the sample rate. This494 * happens every time the sample rate is set. If you want to override the495 * baseband filter selection, you must do so after setting the sample rate.496 *497 * @param freqHz frequency in Hz, 2-20MHz (double)498 *499 * @category Radio control500 */501 async setSampleRate(freqHz: number) {502 return this.setSampleRateManual(...calcSampleRate(freqHz))503 }504 /**505 * Enable / disable RX/TX RF external amplifier506 *507 * @category Radio control508 */509 async setAmpEnable(value: boolean) {510 await this.controlTransferOut(VendorRequest.AMP_ENABLE, Number(value), 0)511 }512 /**513 * Set RX LNA (IF) gain, 0-40dB in 8dB steps514 *515 * @category Radio control516 */517 async setLnaGain(gainDb: number) {518 if (checkU32(gainDb) > 40 || gainDb % 8)519 throw new HackrfError(ErrorCode.INVALID_PARAM)520 const buf = await this.controlTransferIn(VendorRequest.SET_LNA_GAIN, 0, gainDb, 1)521 if (buf.length != 1 || !buf.readUInt8())522 throw new HackrfError(ErrorCode.INVALID_PARAM)523 }524 /**525 * Set RX VGA (baseband) gain, 0-62dB in 2dB steps526 *527 * @category Radio control528 */529 async setVgaGain(gainDb: number) {530 if (checkU32(gainDb) > 62 || gainDb % 2)531 throw new HackrfError(ErrorCode.INVALID_PARAM)532 const buf = await this.controlTransferIn(VendorRequest.SET_VGA_GAIN, 0, gainDb, 1)533 if (buf.length != 1 || !buf.readUInt8())534 throw new HackrfError(ErrorCode.INVALID_PARAM)535 }536 /**537 * Set TX VGA (IF) gain, 0-47dB in 1dB steps538 *539 * @category Radio control540 */541 async setTxVgaGain(gainDb: number) {542 if (checkU32(gainDb) > 47)543 throw new HackrfError(ErrorCode.INVALID_PARAM)544 const buf = await this.controlTransferIn(VendorRequest.SET_TXVGA_GAIN, 0, gainDb, 1)545 if (buf.length != 1 || !buf.readUInt8())546 throw new HackrfError(ErrorCode.INVALID_PARAM)547 }548 /**549 * Antenna port power control550 *551 * @category Radio control552 */553 async setAntennaEnable(value: boolean) {554 await this.controlTransferOut(VendorRequest.ANTENNA_ENABLE, Number(value), 0)555 }556 /**557 * Enable / disable hardware sync558 *559 * Multiple boards can be made to syncronize560 * their USB transfers through a GPIO connection561 * between them.562 *563 * Requires USB API 1.2.564 *565 * @category Radio control566 */567 async setHwSyncMode(value: boolean) {568 this.usbApiRequired(0x0102)569 await this.controlTransferOut(VendorRequest.SET_HW_SYNC_MODE, Number(value), 0)570 }571 /**572 * Reset the device573 *574 * Requires USB API 1.2.575 *576 * @category Main577 */578 async reset() {579 this.usbApiRequired(0x0102)580 await this.controlTransferOut(VendorRequest.RESET, 0, 0)581 }582 /**583 * Initialize sweep mode584 *585 * Requires USB API 1.2.586 *587 * @param ranges is a list of `[start, stop]` pairs of frequencies in MHz,588 * no more than [[MAX_SWEEP_RANGES]] entries.589 * @param numBytes the number of sample bytes to capture after each tuning.590 * @param stepWidth the width in Hz of the tuning step.591 * @param offset number of Hz added to every tuning frequency.592 * Use to select center frequency based on the expected usable bandwidth.593 * @category Radio control594 */595 async initSweep(596 ranges: [number, number][], numBytes: number,597 stepWidth: number, offset: number, style: SweepStyle598 ) {599 this.usbApiRequired(0x0102)600 if (!( ranges.length >= 1 && ranges.length <= MAX_SWEEP_RANGES ))601 throw new HackrfError(ErrorCode.INVALID_PARAM)602 if(numBytes % BYTES_PER_BLOCK || numBytes < BYTES_PER_BLOCK)603 throw new HackrfError(ErrorCode.INVALID_PARAM)604 if(stepWidth < 1)605 throw new HackrfError(ErrorCode.INVALID_PARAM)606 if(checkU32(style) > 1)607 throw new HackrfError(ErrorCode.INVALID_PARAM)608 const data = Buffer.alloc(9 + ranges.length * 4)609 data.writeUInt32LE(checkU32(stepWidth), 0)610 data.writeUInt32LE(checkU32(offset), 4)611 data.writeUInt8(style, 8)612 ranges.forEach(([start, stop], i) => {613 data.writeUInt16LE(checkU16(start), 9 + i*4)614 data.writeUInt16LE(checkU16(stop), 9 + i*4 + 2)615 })616 checkU32(numBytes)617 await this.controlTransferOut(VendorRequest.INIT_SWEEP,618 numBytes & 0xffff, (numBytes >>> 16) & 0xffff, data)619 }620 /**621 * Retrieve list of Opera Cake board addresses (uint8, terminated by 0)622 *623 * Requires USB API 1.2.624 *625 * @category Opera Cake626 */627 async getOperacakeBoards() {628 this.usbApiRequired(0x0102)629 const buf = await this.controlTransferIn(VendorRequest.OPERACAKE_GET_BOARDS, 0, 0, 8)630 return Array.from(checkInLength(buf, 8))631 }632 /**633 * Set Opera Cake ports634 *635 * Requires USB API 1.2.636 *637 * @category Opera Cake638 */639 async setOperacakePorts(address: number, portA: OperacakePorts, portB: OperacakePorts) {640 this.usbApiRequired(0x0102)641 if(checkU32(portA) > OperacakePorts.PB4 || checkU32(portB) > OperacakePorts.PB4)642 throw new HackrfError(ErrorCode.INVALID_PARAM)643 // Check which side PA and PB are on644 if ((portA <= OperacakePorts.PA4 && portB <= OperacakePorts.PA4) ||645 (portA > OperacakePorts.PA4 && portB > OperacakePorts.PA4))646 throw new HackrfError(ErrorCode.INVALID_PARAM)647 await this.controlTransferOut(VendorRequest.OPERACAKE_SET_PORTS,648 checkU8(address), portA | (portB << 8))649 }650 /**651 * Set Opera Cake [frequency-antenna ranges](https://github.com/mossmann/hackrf/wiki/Opera-Cake#opera-glasses)652 *653 * Requires USB API 1.3.654 *655 * @category Opera Cake656 */657 async setOperacakeRanges(ranges: Buffer) {658 this.usbApiRequired(0x0103)659 await this.controlTransferOut(VendorRequest.OPERACAKE_SET_RANGES, 0, 0, ranges)660 }661 /**662 * Test GPIO functionality of an Opera Cake663 *664 * Returns test result (uint16)665 *666 * Requires USB API 1.3.667 *668 * @category Opera Cake669 */670 async operacakeGpioTest(address: number) {671 this.usbApiRequired(0x0103)672 const buf = await this.controlTransferIn(VendorRequest.OPERACAKE_GPIO_TEST, address, 0, 2)673 return checkInLength(buf, 1) // FIXME674 }675 /**676 * Enable / disable clock output through CLKOUT677 *678 * Requires USB API 1.3.679 *680 * @category Radio control681 */682 async setClkoutEnable(value: boolean) {683 this.usbApiRequired(0x0103)684 await this.controlTransferOut(VendorRequest.CLKOUT_ENABLE, Number(value), 0)685 }686 // Disabled for now, see https://github.com/mossmann/hackrf/issues/609687 // /**688 // * Returns crc32 (uint32)689 // *690 // * Requires USB API 1.3.691 // *692 // * @category Flash & CPLD693 // */694 // async cpld_checksum() {695 // this.usbApiRequired(0x0103)696 // const buf = await this.controlTransferIn(VendorRequest.CPLD_CHECKSUM, 0, 0, 4)697 // return checkInLength(buf, 4).readUInt32LE()698 // }699 /**700 * Enable / disable PortaPack display701 *702 * Requires USB API 1.4.703 *704 * @category Radio control705 */706 async setUiEnable(value: boolean) {707 this.usbApiRequired(0x0104)708 await this.controlTransferOut(VendorRequest.UI_ENABLE, Number(value), 0)709 }710 // DATA TRANSFERS...

Full Screen

Full Screen

dfu.ts

Source:dfu.ts Github

copy

Full Screen

...62 private progress(task: string, current: number, total: number) {63 if (this.progressCallback) this.progressCallback({ task, current, total });64 }65 private async getString(index: number) {66 const result = await this.device.controlTransferIn(67 {68 recipient: "device",69 requestType: "standard",70 request: 6,71 value: 0x300 | index,72 index: 0, // specifies language73 },74 25575 );76 if (result?.status != "ok") {77 throw new Error(result.status);78 }79 const view = result.data!;80 const length = view.getUint8(0);81 let descriptor = "";82 for (let i = 2; i < length; i += 2) {83 const charCode = view.getUint16(i, true);84 descriptor += String.fromCharCode(charCode);85 }86 return descriptor;87 }88 private async getInterfaceDescriptor(iface: number) {89 const result = await this.device.controlTransferIn(90 {91 recipient: "device",92 requestType: "standard",93 request: 6,94 value: 0x200,95 index: 0,96 },97 18 + iface * 998 );99 if (result?.status != "ok") {100 throw new Error(result.status);101 }102 const buf = new Uint8Array(result.data!.buffer, 9 + iface * 9);103 return {104 bLength: buf[0],105 bDescriptorType: buf[1],106 bInterfaceNumber: buf[2],107 bAlternateSetting: buf[3],108 bNumEndpoints: buf[4],109 bInterfaceClass: buf[5],110 bInterfaceSubclass: buf[6],111 bInterfaceProtocol: buf[7],112 iInterface: buf[8],113 };114 }115 private async getFunctionalDescriptor() {116 const result = await this.device.controlTransferIn(117 {118 recipient: "interface",119 requestType: "standard",120 request: 6,121 value: 0x2100,122 index: 0,123 },124 255125 );126 if (result?.status != "ok") {127 throw new Error(result.status);128 }129 const buf = new Uint8Array(result.data!.buffer);130 return {131 bLength: buf[0],132 bDescriptorType: buf[1],133 bmAttributes: buf[2],134 wDetachTimeOut: (buf[4] << 8) | buf[3],135 wTransferSize: (buf[6] << 8) | buf[5],136 bcdDFUVersion: buf[7],137 };138 }139 private async getInterfaceDescriptors(interfaceNum: number) {140 const descStrings: string[] = [];141 const config = this.device.configuration!;142 for (const iface of config.interfaces) {143 for (let i = 0; i < iface.alternates.length; i++) {144 const desc = await this.getInterfaceDescriptor(145 iface.interfaceNumber + i146 );147 if (desc.bInterfaceNumber != interfaceNum) {148 continue;149 }150 const str = await this.getString(desc.iInterface);151 descStrings.push(str);152 }153 }154 return descStrings;155 }156 private async controlTransferIn(157 request: number,158 value: number,159 iface: number,160 length: number161 ) {162 // data is ignored163 const result = await this.device.controlTransferIn(164 {165 recipient: "interface",166 requestType: "class",167 request: request,168 value: value,169 index: iface,170 },171 length172 );173 if (result?.status != "ok") {174 throw new Error(result.status);175 }176 return new Uint8Array(result.data!.buffer);177 }178 private async controlTransferOut(179 request: number,180 value: number,181 iface: number,182 data?: number[]183 ) {184 // length is ignored185 let arrayBuf = new ArrayBuffer(0);186 if (data) {187 arrayBuf = new ArrayBuffer(data.length);188 const arrayBufView = new Uint8Array(arrayBuf);189 arrayBufView.set(data);190 }191 const result = await this.device.controlTransferOut(192 {193 recipient: "interface",194 requestType: "class",195 request: request,196 value: value,197 index: iface,198 },199 arrayBuf200 );201 if (result?.status != "ok") {202 throw new Error(result.status);203 }204 return result;205 }206 private clearStatus() {207 const check_status = async (): Promise<Uint8Array> => {208 const data = await this.controlTransferIn(DFURequest.GETSTATUS, 0, 0, 6);209 if (data[4] == DFUState.dfuIDLE) {210 return data;211 }212 const delay = data[1] | (data[2] << 8) | (data[3] << 16);213 await asyncDelay(delay);214 return clear_status();215 };216 const clear_status = async () => {217 await this.controlTransferOut(DFURequest.CLRSTATUS, 0, 0);218 return check_status();219 };220 return check_status();221 }222 private async getChipInfo() {223 const parseDescriptor = (str: string) => {224 // F303: "@Internal Flash /0x08000000/128*0002Kg"225 // F40x: "@Internal Flash /0x08000000/04*016Kg,01*064Kg,07*128Kg"226 // F72x: "@Internal Flash /0x08000000/04*016Kg,01*64Kg,03*128Kg"227 // F74x: "@Internal Flash /0x08000000/04*032Kg,01*128Kg,03*256Kg"228 // H750 SPRacing H7 EXST: "@External Flash /0x90000000/998*128Kg,1*128Kg,4*128Kg,21*128Ka"229 // H750 SPRacing H7 EXST: "@External Flash /0x90000000/1001*128Kg,3*128Kg,20*128Ka" - Early BL firmware with incorrect string, treat as above.230 // H750 Partitions: Flash, Config, Firmware, 1x BB Management block + x BB Replacement blocks)231 if (str == "@External Flash /0x90000000/1001*128Kg,3*128Kg,20*128Ka") {232 str = "@External Flash /0x90000000/998*128Kg,1*128Kg,4*128Kg,21*128Ka";233 }234 // split main into [location, start_addr, sectors]235 const tmp0 = str.replace(/[^\x20-\x7E]+/g, "");236 const tmp1 = tmp0.split("/");237 // G474 (and may be other G4 variants) returns238 // "@Option Bytes /0x1FFF7800/01*048 e/0x1FFFF800/01*048 e"239 // for two banks of options bytes which may be fine in terms of descriptor syntax,240 // but as this splits into an array of size 5 instead of 3, it induces an length error.241 // Here, we blindly trim the array length to 3. While doing so may fail to242 // capture errornous patterns, but it is good to avoid this known and immediate243 // error.244 // May need to preserve the second bank if the configurator starts to really245 // support option bytes.246 if (tmp1.length > 3) {247 Log.info(248 "flash",249 'parseDescriptor: shrinking long descriptor "' + str + '"'250 );251 tmp1.length = 3;252 }253 if (!tmp1[0].startsWith("@")) {254 return null;255 }256 const type = tmp1[0].trim().replace("@", "");257 const start_address = parseInt(tmp1[1]);258 // split sectors into array259 const sectors: any[] = [];260 let total_size = 0;261 const tmp2 = tmp1[2].split(",");262 if (tmp2.length < 1) {263 return null;264 }265 for (let i = 0; i < tmp2.length; i++) {266 // split into [num_pages, page_size]267 const tmp3 = tmp2[i].split("*");268 if (tmp3.length != 2) {269 return null;270 }271 const num_pages = parseInt(tmp3[0]);272 let page_size = parseInt(tmp3[1]);273 if (!page_size) {274 return null;275 }276 const unit = tmp3[1].slice(-2, -1);277 switch (unit) {278 case "M":279 page_size *= 1024; // fall through to K as well280 case "K":281 page_size *= 1024;282 break;283 }284 sectors.push({285 num_pages: num_pages,286 start_address: start_address + total_size,287 page_size: page_size,288 total_size: num_pages * page_size,289 });290 total_size += num_pages * page_size;291 }292 const memory = {293 type: type,294 start_address: start_address,295 sectors: sectors,296 total_size: total_size,297 };298 return memory;299 };300 const descriptors = await this.getInterfaceDescriptors(0);301 return descriptors.map(parseDescriptor).reduce(function (o: any, v, i) {302 o[v!.type.toLowerCase().replace(" ", "_")] = v;303 return o;304 }, {});305 }306 private async loadAddress(address: number, abort = true) {307 const payload = [308 0x21,309 address & 0xff,310 (address >> 8) & 0xff,311 (address >> 16) & 0xff,312 (address >> 24) & 0xff,313 ];314 await this.controlTransferOut(DFURequest.DNLOAD, 0, 0, payload);315 const busyCheck = await this.controlTransferIn(316 DFURequest.GETSTATUS,317 0,318 0,319 6320 );321 if (busyCheck[4] != DFUState.dfuDNBUSY) {322 throw new Error("Failed to request address load");323 }324 const delay = busyCheck[1] | (busyCheck[2] << 8) | (busyCheck[3] << 16);325 await asyncDelay(delay);326 const data = await this.controlTransferIn(DFURequest.GETSTATUS, 0, 0, 6);327 if (data[4] != DFUState.dfuDNLOAD_IDLE && abort) {328 throw new Error("Failed to request address load");329 }330 return data;331 }332 private async unlockOptionBytes(start_address: number, total_size: number) {333 const unprotect = async () => {334 Log.info("flash", "Initiate read unprotect");335 // 0x92 initiates read unprotect336 await this.controlTransferOut(DFURequest.DNLOAD, 0, 0, [0x92]);337 const status = await this.controlTransferIn(338 DFURequest.GETSTATUS,339 0,340 0,341 6342 );343 if (status[4] != DFUState.dfuDNBUSY) {344 throw new Error("Failed to initiate unprotect memory command");345 }346 const delay = status[1] | (status[2] << 8) | (status[3] << 16);347 const total_delay = delay + 20000; // wait at least 20 seconds to make sure the user does not disconnect the board while erasing the memory348 await asyncDelay(total_delay);349 try {350 const data = await this.controlTransferIn(351 DFURequest.GETSTATUS,352 0,353 0,354 6355 );356 // unprotecting the flight controller did not work. It did not reboot.357 Log.info("flash", "Failed to execute unprotect memory command");358 Log.info("flash", data);359 throw new Error("Failed to execute unprotect memory command");360 } catch (e) {361 // we encounter an error, but this is expected. should be a stall.362 Log.info(363 "flash",364 "Unprotect memory command ran successfully. Unplug flight controller. Connect again in DFU mode and try flashing again."365 );366 }367 };368 const tryReadOB = async () => {369 // the following should fail if read protection is active370 const ob_data = await this.controlTransferIn(371 DFURequest.UPLOAD,372 2,373 0,374 total_size375 );376 const data = await this.controlTransferIn(DFURequest.GETSTATUS, 0, 0, 6);377 if (data[4] == DFUState.dfuUPLOAD_IDLE && ob_data.length == total_size) {378 Log.info("flash", "Option bytes read successfully");379 Log.info("flash", "Chip does not appear read protected");380 return this.clearStatus();381 } else {382 Log.info(383 "flash",384 "Option bytes could not be read. Quite possibly read protected."385 );386 await this.clearStatus();387 return unprotect();388 }389 };390 await this.clearStatus();391 const loadAddressResponse = await this.loadAddress(start_address, false);392 // contrary to what is in the docs. Address load should in theory work even if read protection is active393 // if address load fails with this specific error though, it is very likely bc of read protection394 if (395 loadAddressResponse[4] == DFUState.dfuERROR &&396 loadAddressResponse[0] == DFUStatus.errVENDOR397 ) {398 // read protected399 await this.clearStatus();400 return unprotect();401 } else if (loadAddressResponse[4] == DFUState.dfuDNLOAD_IDLE) {402 Log.info("flash", "Address load for option bytes sector succeeded.");403 await this.clearStatus();404 return tryReadOB();405 } else {406 throw new Error("Address load failed");407 }408 }409 private async erasePages(flash_layout: any) {410 const erase_pages: any[] = [];411 for (let i = 0; i < flash_layout.sectors.length; i++) {412 for (let j = 0; j < flash_layout.sectors[i].num_pages; j++) {413 erase_pages.push({ sector: i, page: j });414 }415 }416 if (erase_pages.length === 0) {417 Log.info("flash", "Aborting, No flash pages to erase");418 throw new Error("No flash pages to erase");419 }420 Log.info("flash", "Executing local chip erase", erase_pages);421 let erase_progress = 0;422 for (const erase_page of erase_pages) {423 erase_progress++;424 this.progress("erase", erase_progress, erase_pages.length);425 const page_addr =426 erase_page.page * flash_layout.sectors[erase_page.sector].page_size +427 flash_layout.sectors[erase_page.sector].start_address;428 const cmd = [429 0x41,430 page_addr & 0xff,431 (page_addr >> 8) & 0xff,432 (page_addr >> 16) & 0xff,433 (page_addr >> 24) & 0xff,434 ];435 Log.info(436 "flash",437 "Erasing. sector " +438 erase_page.sector +439 ", page " +440 erase_page.page +441 " @ 0x" +442 page_addr.toString(16)443 );444 await this.controlTransferOut(DFURequest.DNLOAD, 0, 0, cmd);445 const status = await this.controlTransferIn(446 DFURequest.GETSTATUS,447 0,448 0,449 6450 );451 if (status[4] != DFUState.dfuDNBUSY) {452 throw new Error(453 "Failed to initiate page erase, page 0x" + page_addr.toString(16)454 );455 }456 const delay = status[1] | (status[2] << 8) | (status[3] << 16);457 await asyncDelay(delay);458 const data = await this.controlTransferIn(DFURequest.GETSTATUS, 0, 0, 6);459 if (data[4] == DFUState.dfuDNLOAD_IDLE) {460 continue;461 } else if (data[4] == DFUState.dfuDNBUSY) {462 //463 // H743 Rev.V (probably other H7 Rev.Vs also) remains in dfuDNBUSY state after the specified delay time.464 // STM32CubeProgrammer deals with behavior with an undocumented procedure as follows.465 // 1. Issue DFU_CLRSTATUS, which ends up with (14,10) = (errUNKNOWN, dfuERROR)466 // 2. Issue another DFU_CLRSTATUS which delivers (0,2) = (OK, dfuIDLE)467 // 3. Treat the current erase successfully finished.468 // Here, we call clarStatus to get to the dfuIDLE state.469 //470 Log.info("flash", "erase_page: dfuDNBUSY after timeout, clearing");471 await this.clearStatus();472 const clearStatus = await this.controlTransferIn(473 DFURequest.GETSTATUS,474 0,475 0,476 6477 );478 if (clearStatus[4] != DFUState.dfuIDLE) {479 throw new Error(480 "Failed to erase page 0x" +481 page_addr.toString(16) +482 " (did not reach dfuIDLE after clearing"483 );484 }485 } else {486 throw new Error("Failed to erase page 0x" + page_addr.toString(16));487 }488 }489 }490 private async upload(hex: IntelHEX, transferSize: number) {491 Log.info("flash", "Writing data ...");492 const bytes_total = hex.segment_bytes_total;493 let bytes_flashed_total = 0;494 for (const segment of hex.segments) {495 let address = segment.address;496 let wBlockNum = 2;497 let bytes_flashed = 0;498 await this.loadAddress(address);499 while (bytes_flashed < segment.data.length) {500 let bytes_to_write = transferSize;501 if (bytes_flashed + bytes_to_write > segment.data.length) {502 bytes_to_write = segment.data.length - bytes_flashed;503 }504 const data_to_flash = segment.data.slice(505 bytes_flashed,506 bytes_flashed + bytes_to_write507 );508 address += bytes_to_write;509 bytes_flashed += bytes_to_write;510 bytes_flashed_total += bytes_to_write;511 this.progress("write", bytes_flashed_total, bytes_total);512 this.controlTransferOut(DFURequest.DNLOAD, wBlockNum++, 0, [513 ...data_to_flash,514 ]);515 const status = await this.controlTransferIn(516 DFURequest.GETSTATUS,517 0,518 0,519 6520 );521 if (status[4] != DFUState.dfuDNBUSY) {522 throw new Error(523 "Failed to initiate write " +524 bytes_to_write +525 "bytes to 0x" +526 address.toString(16)527 );528 }529 const delay = status[1] | (status[2] << 8) | (status[3] << 16);530 await asyncDelay(delay);531 const data = await this.controlTransferIn(532 DFURequest.GETSTATUS,533 0,534 0,535 6536 );537 if (data[4] != DFUState.dfuDNLOAD_IDLE) {538 throw new Error(539 "Failed to write " +540 bytes_to_write +541 "bytes to 0x" +542 address.toString(16)543 );544 }545 }546 }547 }548 private async verify(hex: IntelHEX, transferSize: number) {549 Log.info("flash", "Verifying data ...");550 const bytes_total = hex.segment_bytes_total;551 let bytes_verified_total = 0;552 for (const segment of hex.segments) {553 let address = segment.address;554 let wBlockNum = 2;555 let bytes_verified = 0;556 await this.clearStatus();557 await this.loadAddress(address);558 await this.clearStatus();559 while (bytes_verified < segment.data.length) {560 let bytes_to_read = transferSize;561 if (bytes_verified + bytes_to_read > segment.data.length) {562 bytes_to_read = segment.data.length - bytes_verified;563 }564 const data = await this.controlTransferIn(565 DFURequest.UPLOAD,566 wBlockNum++,567 0,568 bytes_to_read569 );570 for (let i = 0; i < bytes_to_read; i++) {571 if (data[i] != segment.data[bytes_verified + i]) {572 throw new Error("verify failed");573 }574 }575 address += bytes_to_read;576 bytes_verified += bytes_to_read;577 bytes_verified_total += bytes_to_read;578 this.progress("verify", bytes_verified_total, bytes_total);579 }580 }581 }582 private async leave(hex?: IntelHEX) {583 const address = hex?.segments[0]?.address || 0x08000000;584 await this.clearStatus();585 await this.loadAddress(address);586 // 'downloading' 0 bytes to the program start address followed by a GETSTATUS is used to trigger DFU exit on STM32587 await this.controlTransferOut(DFURequest.DNLOAD, 0, 0);588 await this.controlTransferIn(DFURequest.GETSTATUS, 0, 0, 6);589 }590 async flash(hex: IntelHEX) {591 const info = await this.getChipInfo();592 const flash_layout = info.internal_flash || info.external_flash;593 let available_flash_size = 0;594 if (info.internal_flash) {595 available_flash_size =596 flash_layout.total_size -597 (hex.start_linear_address - flash_layout.start_address);598 } else if (info.external_flash) {599 const firmware_partition_index = 2;600 const firmware_sectors = flash_layout.sectors[firmware_partition_index];601 const firmware_partition_size = firmware_sectors.total_size;602 available_flash_size = firmware_partition_size;...

Full Screen

Full Screen

index.ts

Source:index.ts Github

copy

Full Screen

1import { I2CAddressedBus } from '@johntalton/and-other-delights'2import { sendRecvCommand } from './transfer.js'3export class FT232HCommon {4 static async usbReset(device: USBDevice) {5 await device.controlTransferIn({6 requestType: 'vendor',7 recipient: 'device',8 request: 0,9 value: 0,10 index: 011 })12 }13 static async tciFlush(device: USBDevice) {14 await device.controlTransferIn({15 requestType: 'vendor',16 recipient: 'device',17 request: 0,18 value: 2,19 index: 020 })21 }22 static async tcoFlush(device: USBDevice) {23 await device.controlTransferIn({24 requestType: 'vendor',25 recipient: 'device',26 request: 0,27 value: 1,28 index: 029 })30 }31 static async setBaudrate(device: USBDevice, value: number) {32 await device.controlTransferIn({33 requestType: 'vendor',34 recipient: 'device',35 request: 3,36 value,37 index: 038 })39 }40 static async setLineProperty() {}41 static async writeData(device: USBDevice, bufferSource: BufferSource) {42 await device.transferOut(ep, bufferSource)43 }44 static async readData(device: USBDevice) {45 await device.transferIn(ep, length)46 }47 static async setBitmode(device: USBDevice, value: number) {48 await device.controlTransferIn({49 requestType: 'vendor',50 recipient: 'device',51 request: 0x0b,52 value,53 index: 054 })55 }56 static async disableBitbang() {57 throw new Error('no impl')58 }59 static async readPins() {60 throw new Error('no impl')61 }62 static async setLatencyTimer() {63 throw new Error('no impl')64 }65 static async getLatencyTimer() {66 throw new Error('no impl')67 }68 static async pollModemStatus(device: USBDevice) {69 const SIO_POLL_MODEM_STATUS_REQUEST = 0x0570 const length = 6471 const result = await device.controlTransferIn({72 requestType: 'vendor',73 recipient: 'device',74 request: SIO_POLL_MODEM_STATUS_REQUEST,75 value: 0,76 index: 077 }, length)78 if(result.status !== 'ok') { }79 console.log(result)80 const usb_val0 = result.data.getUint8(0)81 const usb_val1 = result.data.getUint8(1)82 const status = {83 CTS: isBitSet(usb_val0, 4),84 DTS: isBitSet(usb_val0, 5),85 RI: isBitSet(usb_val0, 6),...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webusb-polyfill');2var wpt = new wpt();3wpt.controlTransferIn({4}, 2).then(function(result) {5 console.log(result.data);6});7 at Object.<anonymous> (C:\Users\user\Documents\GitHub\test.js:5:5)8 at Module._compile (module.js:652:30)9 at Object.Module._extensions..js (module.js:663:10)10 at Module.load (module.js:565:32)11 at tryModuleLoad (module.js:505:12)12 at Function.Module._load (module.js:497:3)13 at Function.Module.runMain (module.js:693:10)14 at startup (bootstrap_node.js:188:16)

Full Screen

Using AI Code Generation

copy

Full Screen

1wpt.controlTransferIn(0x01, 0x01, 0x02, 0x02, 0x02, function(data){2 console.log(data);3});4wpt.controlTransferOut(0x01, 0x01, 0x02, 0x02, 0x02, function(data){5 console.log(data);6});7wpt.interruptTransferIn(0x01, 0x02, function(data){8 console.log(data);9});10wpt.interruptTransferOut(0x01, 0x02, function(data){11 console.log(data);12});13wpt.bulkTransferIn(0x01, 0x02, function(data){14 console.log(data);15});16wpt.bulkTransferOut(0x01, 0x02, function(data){17 console.log(data);18});19wpt.isochronousTransferIn(0x01, 0x02, function(data){20 console.log(data);21});22wpt.isochronousTransferOut(0x01, 0x02, function(data){23 console.log(data);24});25wpt.reset(function(data){26 console.log(data);27});28wpt.clearHalt(0x01, function(data){29 console.log(data);30});31wpt.claimInterface(0x01, function(data){32 console.log(data);33});34wpt.releaseInterface(0x01, function(data){35 console.log(data);36});37wpt.selectConfiguration(0x01, function(data){38 console.log(data);39});40wpt.selectAlternateInterface(0x01, 0x02, function(data){41 console.log(data);42});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webusb-polyfill');2var button = document.querySelector('button');3button.addEventListener('click', function() {4 wpt.requestDevice({ filters: [{ vendorId: 0x04b4, productId: 0x00f1 }] })5 .then(device => {6 console.log(device);7 })8 .then(() => {9 console.log('Connection established');10 return device.controlTransferIn({11 }, 64);12 })13 .then(result => {14 console.log(result);15 })16 .catch(error => {17 console.log(error);18 });19});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var wpt = new wpt('your api key');3wpt.controlTransferIn('test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', function (err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10{ response: 'OK' }

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('node-wpt').wpt;2var wptDriver = new wpt({3});4wptDriver.connect().then(function() {5 return wptDriver.controlTransferIn({6 }, 18);7}).then(function(result) {8 console.log(result);9 wptDriver.disconnect();10}).catch(function(error) {11 console.log(error);12});13{ data: <Buffer 12 01 00 02 00 00 00 40 3f 00 00 00 01 01 02 03 01 00>, status: 'ok' }

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = new WebUSBPort();2wpt.onconnect = function() {3 console.log("Connected to WPT");4 wpt.controlTransferIn(0x80, 0x01, 0x0000, 0x0000, 0x0002, function(data) {5 console.log(data);6 });7}8wpt.connect();9var wpt = new WebUSBPort();10connect()11disconnect()12controlTransferIn()13controlTransferOut()14read()15write()

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful