diff --git a/examples/bfb.ts b/examples/bfb.ts new file mode 100644 index 0000000..42ee863 --- /dev/null +++ b/examples/bfb.ts @@ -0,0 +1,99 @@ +import { parseArgs } from 'node:util'; +import { BFB } from '../src/index.js'; +import { delay } from '../src/utils.js'; +import { openPort } from './utils.js'; + +const { values: argv } = parseArgs({ + options: { + port: { + type: 'string', + default: '/dev/ttyUSB0', + }, + help: { + type: 'boolean', + short: 'h', + default: false, + }, + usage: { + type: 'boolean', + default: false, + }, + }, +}); + +if (argv.help || argv.usage) { + console.log('USAGE: bfb.js --port /dev/ttyUSB0'); + process.exit(0); +} + +const port = await openPort(argv.port, 115200); +const bfb = new BFB(port); + +async function printValue(name: string, callback: () => Promise): Promise { + try { + console.log(name, await callback()); + } catch (error) { + console.error(name, error instanceof Error ? error.message : error); + } +} + +port.on('error', (error) => console.error('Port error', error)); +port.on('close', () => console.error('Port close')); + +try { + await port.open(); + console.log('Connecting...'); + await bfb.connect(); + await bfb.setBestBaudrate(0); + console.log('BFB connected at', port.baudRate); + await printValue('PING', () => bfb.ping()); + await printValue('DEBUGGER', () => bfb.getDebuggerName()); + await printValue('MODEL', () => bfb.getPhoneModel()); + await printValue('FW', () => bfb.getFirmwareVersion()); + await printValue('LANGUAGE', () => bfb.getLanguageGroup()); + await printValue('IMEI', () => bfb.getIMEI()); + await printValue('HWID', async () => (await bfb.getHardwareId()).toString(16).padStart(4, '0').toUpperCase()); + await printValue('ESN', async () => (await bfb.getFlashSerialNumber()).toString(16).padStart(8, '0').toUpperCase()); + await printValue('DISPLAY TYPE', () => bfb.getDisplayType()); + await printValue('DISPLAY BUFFER', async () => `0x${(await bfb.getDisplayBufferAddress()).toString(16).padStart(8, '0').toUpperCase()}`); + await printValue('GPRS BLER', () => bfb.getGprsBlerCounters()); + await printValue('AFC', () => bfb.readAfc()); + await printValue('MOBILE MODE', () => bfb.getMobileMode()); + await printValue('BATTERY', () => bfb.getBatteryVoltage()); + await printValue('DSP FW', () => bfb.getDspFirmwareVersion()); + await printValue('POWER ASIC', () => bfb.getPowerAsicProject()); + await printValue('FLAGS', () => bfb.getFlagStatus()); + await printValue('SECURITY MODE', () => bfb.getSecurityModeName()); + for (let selector = 0; selector <= 9; selector++) + await printValue(`HARDWARE INFO ${selector}`, () => bfb.getHardwareInfo(selector)); + await printValue('EELITE MAX BLOCK', () => bfb.getEepMaxBlockId('eelite')); + await printValue('EELITE SPACE', () => bfb.getEepSpaceInfo('eelite')); + await printValue('EELITE BLOCK 1', async () => { + const info = await bfb.getEepBlockInfo(1, 'eelite'); + const prefix = await bfb.readEepBlock(1, 0, Math.min(info.size, 16), 'eelite'); + return { ...info, bytesRead: prefix.length }; + }); + await printValue('EEFULL MAX BLOCK', () => bfb.getEepMaxBlockId('eefull')); + await printValue('EEFULL SPACE', () => bfb.getEepSpaceInfo('eefull')); + let displayRedirected = false; + let keypadRedirected = false; + try { + await bfb.redirectDisplay((event) => console.log('DISPLAY EVENT', event)); + displayRedirected = true; + await bfb.redirectKeypad((data) => console.log('KEYPAD EVENT', data.toString('hex'))); + keypadRedirected = true; + console.log('Waiting 5 seconds for display and keypad events...'); + await delay(5000); + } finally { + try { + if (keypadRedirected) + await bfb.redirectKeypad(); + } finally { + if (displayRedirected) + await bfb.redirectDisplay(); + } + } +} finally { + await bfb.disconnect(); + await port.close(); +} diff --git a/package.json b/package.json index f827cd6..8a4ff15 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,11 @@ "test": "vitest run", "test:watch": "vitest", "build": "tsc", - "watch": "tsc -w" + "watch": "tsc -w", + "docs:bfb-status": "node tools/generateBfbImplementationStatus.mjs", + "check:bfb-command-coverage": "node tools/checkBfbCommandCoverage.mjs", + "check:bfb-hardware-coverage": "node tools/checkBfbHardwareCoverage.mjs", + "test:bfb-hardware": "BFB_HARDWARE=1 vitest run src/BFB.test.ts" }, "author": "kirill.zhumarin@gmail.com", "license": "MIT", diff --git a/src/BFB.test.ts b/src/BFB.test.ts new file mode 100644 index 0000000..6d7deb1 --- /dev/null +++ b/src/BFB.test.ts @@ -0,0 +1,888 @@ +import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'; +import { openPort } from '../examples/utils.js'; +import { AsyncSerialPort } from './AsyncSerialPort.js'; +import { + BFB, + BFB_BAUD_RATES, + BFB_MAX_PAYLOAD_SIZE, + BfbChannel, + BfbCommandTimeoutError, + BfbCoreOpcode, + BfbHardwareOpcode, + BfbRemoteError, + BfbSecurityMode, + BfbUnsupportedCommandError, + encodeBfbFrame, +} from './BFB.js'; + +const PORT_PATH = process.env.BFB_PORT ?? '/dev/ttyUSB0'; +const RAM_START = 0x00000000; +const RAM_SIZE = 0x00200000; +const RAM_PAGE_SIZE = 0x00004000; +const TEST_PATTERN = Buffer.from('BFB RAM WRITE OK', 'ascii'); +const EXEC_CODE_TARGET_ADDRESS = 0x0000FFCA; +const EXEC_CODE_TARGET_MASK = 1 << 2; +const CPU_RESOURCE_LEVEL_ADDRESS = 0x00003D0A; +const DISPLAY_CONTRAST_BLOCK_ID = 0x138F; + +const describeHardware = process.env.BFB_HARDWARE == '1' ? describe.sequential : describe.skip; +const testUnsafeAction = (action: string) => process.env.BFB_UNSAFE_HARDWARE == action ? test : test.skip; +const testDestructiveAction = (action: string) => { + return process.env.BFB_DESTRUCTIVE_HARDWARE == action ? test : test.skip; +}; +const testSessionAction = (action: string) => process.env.BFB_SESSION_HARDWARE == action ? test : test.skip; + +test('enforces the DLL BFB payload bounds', () => { + expect(encodeBfbFrame(BfbChannel.CORE, Buffer.alloc(0))).toEqual(Buffer.from([BfbChannel.CORE, 0, BfbChannel.CORE])); + expect(encodeBfbFrame(BfbChannel.CORE, Buffer.alloc(BFB_MAX_PAYLOAD_SIZE))).toHaveLength(3 + BFB_MAX_PAYLOAD_SIZE); + expect(() => encodeBfbFrame(BfbChannel.CORE, Buffer.alloc(BFB_MAX_PAYLOAD_SIZE + 1))).toThrow('range 0..32'); +}); + +test('names unsupported commands by channel and opcode', () => { + const error = new BfbUnsupportedCommandError(BfbChannel.HARDWARE, BfbHardwareOpcode.GET_HARDWARE_DATA); + expect(error.message).toContain('GET_HARDWARE_DATA'); +}); + +describeHardware('BFB hardware', () => { + let port: AsyncSerialPort; + let bfb: BFB; + + beforeAll(async () => { + port = await openPort(PORT_PATH, 115200); + bfb = new BFB(port); + await port.open(); + await bfb.connect(); + }, 30000); + + afterAll(async () => { + await bfb?.disconnect(); + if (port?.isOpen) + await port.close(); + }); + + test('connects and responds to core commands', async () => { + expect(BFB_BAUD_RATES[port.baudRate]).toBeDefined(); + expect(await bfb.ping()).toBe(true); + expect(await bfb.getDebuggerName()).toMatch(/^SIEMENS Mobile Phones Debugger /); + expect(await bfb.exec(BfbChannel.CORE, [BfbCoreOpcode.PING])).toEqual(Buffer.from([BfbCoreOpcode.PING, 0xAA])); + }); + + test('sends a raw core frame', async () => { + await bfb.sendFrame(BfbChannel.CORE, [BfbCoreOpcode.PING]); + expect(await bfb.getDebuggerName()).toMatch(/^SIEMENS Mobile Phones Debugger /); + expect(await bfb.ping()).toBe(true); + }); + + test('switches baudrate and restores 115200', async () => { + try { + expect(await bfb.setPhoneBaudrate(57600)).toBe(true); + expect(port.baudRate).toBe(57600); + expect(await bfb.ping()).toBe(true); + expect(await bfb.setBestBaudrate(115200)).toBe(true); + } finally { + if (port.baudRate != 115200) + expect(await bfb.setPhoneBaudrate(115200)).toBe(true); + } + expect(port.baudRate).toBe(115200); + expect(await bfb.ping()).toBe(true); + }); + + test('switches host baudrate using DLL wire codes', async () => { + try { + for (const baudRate of [230400, 460800]) { + expect(await bfb.setPhoneBaudrate(baudRate)).toBe(true); + expect(port.baudRate).toBe(baudRate); + expect(await bfb.ping()).toBe(true); + } + } finally { + if (port.baudRate != 115200) + expect(await bfb.setPhoneBaudrate(115200)).toBe(true); + } + expect(await bfb.ping()).toBe(true); + }); + + test('reads phone information', async () => { + expect(await bfb.getPhoneModel()).toBe(process.env.BFB_MODEL ?? 'C60'); + expect(await bfb.getFirmwareVersion()).toBeGreaterThan(0); + expect(await bfb.getLanguageGroup()).not.toBe(''); + expect(await bfb.getIMEI()).toMatch(/^\d{15}$/); + expect(await bfb.getFlagStatus()).toBeGreaterThanOrEqual(0); + expect(await bfb.getHardwareId()).toBeGreaterThan(0); + expect(await bfb.getFlashSerialNumber()).toBeGreaterThan(0); + expect(await bfb.getDisplayType()).toBeGreaterThan(0); + expect(await bfb.getDisplayBufferAddress()).toBeGreaterThan(0); + expect(await bfb.getGprsBlerCounters()).toEqual({ counterA: expect.any(Number), counterB: expect.any(Number) }); + expect(await bfb.readAfc()).toBeGreaterThanOrEqual(0); + expect(await bfb.getMobileMode()).toBeGreaterThanOrEqual(0); + expect(await bfb.getDspFirmwareVersion()).toBeGreaterThanOrEqual(0); + expect(await bfb.getPowerAsicProject()).toBeGreaterThanOrEqual(0); + expect(await bfb.getBatteryVoltage()).toBeGreaterThan(0); + const securityMode = await bfb.getSecurityMode(); + expect(securityMode).toBeGreaterThanOrEqual(BfbSecurityMode.REPAIR); + expect(securityMode).toBeLessThanOrEqual(BfbSecurityMode.CUSTOMER); + expect(['REPAIR', 'DEVELOPER', 'FACTORY', 'CUSTOMER']).toContain(await bfb.getSecurityModeName()); + }); + + test('reads all hardware info selectors', async () => { + for (let selector = 0; selector <= 9; selector++) + expect(await bfb.getHardwareInfo(selector)).toBeGreaterThanOrEqual(0); + }); + + const optionalReaders: [string, () => Promise][] = [ + ['hardware data', () => bfb.getHardwareData(0)], + ['audio gain shadow', () => bfb.getAudioGainShadow()], + ['normal-mode RX level', () => bfb.getNormalModeRxLevel()], + ['B35 software version', () => bfb.getB35SoftwareVersion()], + ]; + test.each(optionalReaders)('reads optional %s or reports unsupported', async (_name, callback) => { + await expectSupportedOrUnsupported(callback); + }); + + const dllOptionalReaders: [string, () => Promise][] = [ + ['firmware information', () => bfb.getFirmwareInformation()], + ['IQ mean values', () => bfb.getIqMeanValues(1)], + ['IQ drift values', () => bfb.getIqDriftValues()], + ['information element list', () => bfb.getInformationElementList(0)], + ['single information element', async () => ({ value: await bfb.getSingleInformationElement(0) })], + ['boot PIN settings', () => bfb.requestBootPinSetting()], + ['Lumberg state', () => bfb.testLumberg()], + ]; + test.each(dllOptionalReaders)('reads DLL %s or reports unsupported/no response', async (_name, callback) => { + await expectSupportedOrNoResponse(callback); + expect(await bfb.ping()).toBe(true); + }, 10000); + + testUnsafeAction('power-values')('reads DLL power values', async () => { + expect((await bfb.getPowerValues(1)).length).toBeGreaterThanOrEqual(2); + expect(await bfb.ping()).toBe(true); + }, 10000); + + test('reads memory', async () => { + const result = await bfb.readMemory(0, 64); + expect(result.buffer).toHaveLength(64); + expect(result.canceled).toBe(false); + expect(result.errors).toBe(0); + + const buffer = Buffer.alloc(40, 0xA5); + await bfb.readMemoryChunk(0, 31, buffer, 4); + expect(buffer.subarray(0, 4)).toEqual(Buffer.alloc(4, 0xA5)); + expect(buffer.subarray(4, 35)).toEqual(result.buffer.subarray(0, 31)); + }); + + test('reads confirmed AMC modes 1-3 with zero selectors', async () => { + expect(await bfb.amcAdvanced(1, [0, 0])).toEqual(expect.any(Number)); + expect(await bfb.ping()).toBe(true); + expect(await bfb.amcAdvanced(2, [0, 0])).toEqual(expect.any(Number)); + expect(await bfb.ping()).toBe(true); + + const address = await bfb.amcAdvanced(3, [0, 0]); + if (address === undefined) + throw new Error('BFB AMC mode 3 returned no address.'); + const result = await bfb.readMemory(address, 16); + expect(result.buffer).toHaveLength(16); + expect(result.canceled).toBe(false); + expect(result.errors).toBe(0); + expect(await bfb.ping()).toBe(true); + }); + + test('reads EELITE and EEFULL', async () => { + const eeliteMaxBlockId = await bfb.getEepMaxBlockId('eelite'); + const eefullMaxBlockId = await bfb.getEepMaxBlockId('eefull'); + expect(eeliteMaxBlockId).toBeGreaterThan(0); + expect(eefullMaxBlockId).toBeGreaterThan(0); + + const eeliteSpace = await bfb.getEepSpaceInfo('eelite'); + expect(eeliteSpace.freeBlocks).toBeGreaterThan(0); + expect(eeliteSpace.freeAddressSpace).toBeGreaterThan(0); + expect(eeliteSpace.freeDataSpace).toBeGreaterThan(0); + const eefullSpace = await bfb.getEepSpaceInfo('eefull'); + expect(eefullSpace.freeBlocks).toBeGreaterThan(0); + expect(eefullSpace.freeAddressSpace).toBeGreaterThan(0); + expect(eefullSpace.freeDataSpace).toBeGreaterThan(0); + + const info = await bfb.getEepBlockInfo(1, 'eelite'); + const data = await bfb.readEepBlock(1, 0, Math.min(info.size, 16)); + expect(data).toHaveLength(Math.min(info.size, 16)); + + let chunkedBlockId: number | undefined; + let chunkedInfo; + for (let blockId = 5000; blockId <= eefullMaxBlockId; blockId++) { + try { + const info = await bfb.getEepBlockInfo(blockId, 'eefull'); + if (info.size > 30) { + chunkedBlockId = blockId; + chunkedInfo = info; + break; + } + } catch (error) { + if (!(error instanceof BfbRemoteError) || error.status != 0x32) + throw error; + } + } + expect(chunkedBlockId).toBeDefined(); + expect(chunkedInfo).toBeDefined(); + if (chunkedBlockId === undefined || chunkedInfo === undefined) + throw new Error('No readable EEFULL block larger than 30 bytes.'); + expect(chunkedInfo.size).toBeGreaterThan(30); + const chunkedLength = Math.min(chunkedInfo.size, 61); + const chunkedData = await bfb.readEepBlock(chunkedBlockId, 0, chunkedLength, 'eefull'); + expect(chunkedData).toHaveLength(chunkedLength); + expect(await bfb.readEepBlock(chunkedBlockId, 30, chunkedLength - 30, 'eefull')) + .toEqual(chunkedData.subarray(30)); + }, 60000); + + test('reads sensor data through the DLL command or reports no response', async () => { + await expectSupportedOrNoResponse(async () => { + const addresses = await bfb.getSensorAddresses(); + expect(addresses.raw).toBeGreaterThanOrEqual(0); + expect(addresses.calibrated).toBeGreaterThanOrEqual(0); + expect(await bfb.getRawSensorData()).toHaveLength(14); + const data = await bfb.getSensorData(); + expect(data.voltages).toHaveLength(3); + expect(data.temperatures).toHaveLength(3); + for (const value of [...data.voltages, ...data.temperatures]) + expect(Number.isFinite(value)).toBe(true); + return true; + }); + expect(await bfb.ping()).toBe(true); + }, 10000); + + test('creates, edits and deletes a free EEFULL block', async () => { + const maxBlockId = await bfb.getEepMaxBlockId('eefull'); + let blockId: number | undefined; + for (let candidate = maxBlockId; candidate >= 5000; candidate--) { + try { + await bfb.getEepBlockInfo(candidate, 'eefull'); + } catch (error) { + if (!(error instanceof BfbRemoteError) || error.status != 0x32) + throw error; + blockId = candidate; + break; + } + } + expect(blockId).toBeDefined(); + if (blockId === undefined) + throw new Error('No free EEFULL block id.'); + + const initial = Buffer.alloc(64); + for (let index = 0; index < initial.length; index++) + initial[index] = 0x40 + index; + const patch = Buffer.alloc(29); + for (let index = 0; index < patch.length; index++) + patch[index] = 0xE0 - index; + const expected = Buffer.from(initial); + patch.copy(expected, 17); + + try { + await expect(bfb.getEepBlockInfo(blockId, 'eefull')).rejects.toMatchObject({ status: 0x32 }); + await bfb.createEepBlock(blockId, initial.length, 0x5A, 'eefull'); + for (let offset = 0; offset < initial.length; offset += 26) + await bfb.writeEepBlockChunk(blockId, offset, initial.subarray(offset, offset + 26), 'eefull'); + await bfb.finishEepBlock(blockId, 'eefull'); + expect(await bfb.getEepBlockInfo(blockId, 'eefull')).toEqual({ + size: initial.length, + version: 0x5A, + storage: 'eefull', + }); + expect(await bfb.readEepBlock(blockId, 0, initial.length, 'eefull')).toEqual(initial); + expect(await bfb.readEepBlockChunk(blockId, 0, 30, 'eefull')).toEqual(initial.subarray(0, 30)); + + await bfb.writeEefullBlockRangeChunk(blockId, 17, patch.subarray(0, 26)); + await bfb.writeEepBlockRange(blockId, 43, patch.subarray(26)); + expect(await bfb.readEepBlock(blockId, 0, expected.length, 'eefull')).toEqual(expected); + } finally { + try { + await bfb.deleteEepBlock(blockId, 'eefull'); + } catch (error) { + if (!(error instanceof BfbRemoteError) || error.status != 0x32) + throw error; + } + } + + await expect(bfb.getEepBlockInfo(blockId, 'eefull')).rejects.toMatchObject({ status: 0x32 }); + }, 60000); + + test('creates, replaces and deletes a free EELITE block', async () => { + const maxBlockId = await bfb.getEepMaxBlockId('eelite'); + let blockId: number | undefined; + for (let candidate = maxBlockId; candidate > 0; candidate--) { + try { + await bfb.getEepBlockInfo(candidate, 'eelite'); + } catch (error) { + if (!(error instanceof BfbRemoteError) || error.status != 0x32) + throw error; + blockId = candidate; + break; + } + } + expect(blockId).toBeDefined(); + if (blockId === undefined) + throw new Error('No free EELITE block id.'); + + const initial = Buffer.from('BFB EELITE CREATE TEST', 'ascii'); + const replacement = Buffer.from('BFB EELITE REPLACE TEST', 'ascii'); + try { + await expect(bfb.getEepBlockInfo(blockId, 'eelite')).rejects.toMatchObject({ status: 0x32 }); + await bfb.writeEepBlock(blockId, initial, 1, 'eelite'); + expect(await bfb.readEepBlock(blockId, 0, initial.length, 'eelite')).toEqual(initial); + + await bfb.writeEepBlock(blockId, replacement, 2, 'eelite'); + expect(await bfb.getEepBlockInfo(blockId, 'eelite')).toEqual({ + size: replacement.length, + version: 2, + storage: 'eelite', + }); + expect(await bfb.readEepBlock(blockId, 0, replacement.length, 'eelite')).toEqual(replacement); + } finally { + try { + await bfb.deleteEepBlock(blockId, 'eelite'); + } catch (error) { + if (!(error instanceof BfbRemoteError) || error.status != 0x32) + throw error; + } + } + + await expect(bfb.getEepBlockInfo(blockId, 'eelite')).rejects.toMatchObject({ status: 0x32 }); + }, 60000); + + test('allocates and frees temporary GBS memory', async () => { + await expectSupportedOrUnsupported(async () => { + const address = await bfb.allocateGbsMemory(64); + expect(address).toBeGreaterThan(0); + try { + return address; + } finally { + await bfb.freeGbsMemory(address); + } + }); + }); + + test('executes a remote-control AT query', async () => { + await expectSupportedOrUnsupported(async () => { + const response = await bfb.sendRemoteControl('AT^SCID\r', 1000); + expect(response[0]).toBe(0xF0); + expect(response.subarray(1).toString('ascii')).toContain('^SCID:'); + return response; + }); + }); + + test('covers RAM write commands and restores the page', async () => { + const address = await findEmptyRamPage(bfb); + const original = (await bfb.readMemory(address, 0x50)).buffer; + expect(original.every((value) => value == 0)).toBe(true); + for (const length of [1, 31, 32, 64]) + expect((await bfb.readMemory(address, length)).buffer).toEqual(original.subarray(0, length)); + + let writeAttempted = false; + try { + writeAttempted = true; + await bfb.writeMemory(address, TEST_PATTERN); + let readback = (await bfb.readMemory(address, TEST_PATTERN.length)).buffer; + expect(readback).toEqual(TEST_PATTERN); + + const chunkPattern = Buffer.from('WRITE CHUNK', 'ascii'); + await bfb.writeMemoryChunk(address + 0x20, chunkPattern); + readback = (await bfb.readMemory(address + 0x20, chunkPattern.length)).buffer; + expect(readback).toEqual(chunkPattern); + + await bfb.writeMemoryByte(address + 0x40, 0xA5); + expect((await bfb.readMemory(address + 0x40, 1)).buffer[0]).toBe(0xA5); + + await bfb.writeMemoryWord(address + 0x42, 0x5AA5); + expect((await bfb.readMemory(address + 0x42, 2)).buffer.readUInt16LE(0)).toBe(0x5AA5); + + for (const length of [1, 25, 26, 80]) { + const pattern = Buffer.alloc(length, 0x40 + length); + await bfb.writeMemory(address, pattern); + expect((await bfb.readMemory(address, length)).buffer).toEqual(pattern); + } + } finally { + if (writeAttempted) { + await bfb.writeMemory(address, original); + const restored = (await bfb.readMemory(address, original.length)).buffer; + expect(restored).toEqual(original); + } + } + }, 60000); + + test('executes and reverses the DLL C166 bit-operation sample', async () => { + const original = (await bfb.readMemory(EXEC_CODE_TARGET_ADDRESS, 2)).buffer.readUInt16LE(0); + try { + await bfb.execCode(Buffer.from([0x2E, 0xE5, 0xDB, 0x00])); // bclr 0xFFCA.2; rets + const changed = (await bfb.readMemory(EXEC_CODE_TARGET_ADDRESS, 2)).buffer.readUInt16LE(0); + expect(changed & EXEC_CODE_TARGET_MASK).toBe(0); + } finally { + if (original & EXEC_CODE_TARGET_MASK) + await bfb.execCode(Buffer.from([0x2F, 0xE5, 0xDB, 0x00])); // bset 0xFFCA.2; rets + const restored = (await bfb.readMemory(EXEC_CODE_TARGET_ADDRESS, 2)).buffer.readUInt16LE(0); + expect(restored & EXEC_CODE_TARGET_MASK).toBe(original & EXEC_CODE_TARGET_MASK); + } + }); + + test('redirects, reads and restores the keypad around a key event', async () => { + let redirected = false; + let pressed = false; + const events: Buffer[] = []; + try { + await bfb.redirectKeypad((data) => events.push(data)); + redirected = true; + await bfb.pressKey(0x35); + pressed = true; + await vi.waitFor(() => expect(events.some((event) => event.includes(0x35))).toBe(true), { timeout: 1000 }); + await bfb.pressKey(0xB5); + pressed = false; + } finally { + if (pressed) + await bfb.pressKey(0xB5); + if (redirected) + await bfb.redirectKeypad(); + } + expect(await bfb.ping()).toBe(true); + }); + + test('redirects, updates and restores the display', async () => { + let redirected = false; + try { + await bfb.redirectDisplay(() => {}); + redirected = true; + await bfb.updateDisplay(0, 0, 101, 80); + } finally { + if (redirected) + await bfb.redirectDisplay(); + } + expect(await bfb.ping()).toBe(true); + }); + + test('writes and restores the display framebuffer', async () => { + const address = await bfb.getDisplayBufferAddress(); + let redirected = false; + let original: Buffer | undefined; + try { + await bfb.redirectDisplay(() => {}); + redirected = true; + original = (await bfb.readMemory(address, 32)).buffer; + const pattern = Buffer.from(original.map((value) => value ^ 0xFF)); + await bfb.writeMemory(address, pattern); + expect((await bfb.readMemory(address, pattern.length)).buffer).toEqual(pattern); + await bfb.updateDisplay(0, 0, 101, 80); + } finally { + if (original !== undefined) { + await bfb.writeMemory(address, original); + expect((await bfb.readMemory(address, original.length)).buffer).toEqual(original); + await bfb.updateDisplay(0, 0, 101, 80); + } + if (redirected) + await bfb.redirectDisplay(); + } + expect(await bfb.ping()).toBe(true); + }, 30000); + + test('sets and restores display contrast', async () => { + const original = (await bfb.readEepBlock(DISPLAY_CONTRAST_BLOCK_ID, 0, 2, 'eefull'))[0]; + const changed = original == 7 ? 6 : 7; + try { + await bfb.setDisplayContrast(changed); + await new Promise((resolve) => setTimeout(resolve, 100)); + } finally { + await bfb.setDisplayContrast(original); + } + expect(await bfb.ping()).toBe(true); + }); + + test('generates display patterns and restores normal content', async () => { + await bfb.generateDisplayPattern(0); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(await bfb.ping()).toBe(true); + await bfb.generateDisplayPattern(1); + await new Promise((resolve) => setTimeout(resolve, 100)); + await bfb.updateDisplay(0, 0, 101, 80); + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('switch-off-display')('switches off the display (crashes C60 FW27)', async () => { + await bfb.switchOffDisplay(); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('light-control')('controls a caller-selected light through the DLL payload form', async () => { + await bfb.controlLight( + readRequiredNumberEnv('BFB_LIGHT'), + readRequiredNumberEnv('BFB_LIGHT_VALUE'), + ); + expect(await bfb.ping()).toBe(true); + }); + + test('plays and stops a short tone', async () => { + try { + await bfb.playTone(800, 100); + await new Promise((resolve) => setTimeout(resolve, 150)); + } finally { + await bfb.stopTone(); + } + expect(await bfb.ping()).toBe(true); + }); + + test('starts and stops vibra', async () => { + try { + await bfb.setVibra(1); + await new Promise((resolve) => setTimeout(resolve, 100)); + } finally { + await bfb.setVibra(0); + } + expect(await bfb.ping()).toBe(true); + }); + + test('writes the current AFC value without changing it', async () => { + const value = await bfb.readAfc(); + await bfb.setAfc(value); + expect(await bfb.readAfc()).toBe(value); + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('power-saving')('configures power saving when the original mode is unknown', async () => { + const mode = 0; + try { + await bfb.configurePowerSaving(mode); + } catch (error) { + if (!(error instanceof BfbRemoteError) || error.status != 0x13) + throw error; + } + expect(await bfb.ping()).toBe(true); + }); + + testDestructiveAction('reset-gprs-bler')('resets GPRS BLER counters', async () => { + await bfb.resetGprsBlerCounters(); + expect(await bfb.getGprsBlerCounters()).toEqual({ counterA: 0, counterB: 0 }); + expect(await bfb.ping()).toBe(true); + }); + + test('simulates a chip card', async () => { + await bfb.simulateChipCard(); + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('boot-dsp')('boots DSP at a caller-provided address', async () => { + await bfb.bootDsp(readRequiredNumberEnv('BFB_DSP_ADDRESS')); + expect(await bfb.ping()).toBe(true); + }); + + test('sets the current environment temperature without changing it', async () => { + const before = await bfb.getSensorData(); + const temperature = before.temperatures[0]; + const rawTemperature = Math.round((temperature + 273) / 0.1); + try { + await bfb.setEnvironmentTemperature(rawTemperature); + const after = await bfb.getSensorData(); + expect(after.temperatures[0]).toBeCloseTo(temperature, 5); + } finally { + await bfb.setEnvironmentTemperature(rawTemperature); + } + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('nf-control')('changes NF control without a readable original state', async () => { + try { + await bfb.setNfControl(true); + expect(await bfb.ping()).toBe(true); + } finally { + await bfb.setNfControl(false); + } + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('nf-configure')('configures NF control with caller-provided values', async () => { + await bfb.configureNfControl( + readRequiredNumberEnv('BFB_NF_A'), + readRequiredNumberEnv('BFB_NF_B'), + readRequiredNumberEnv('BFB_NF_C'), + ); + expect(await bfb.ping()).toBe(true); + }); + + test('sets the current CPU speed without changing its resource level', async () => { + const resourceLevel = (await bfb.readMemory(CPU_RESOURCE_LEVEL_ADDRESS, 2)).buffer.readUInt16LE(0); + expect(resourceLevel).toBeGreaterThanOrEqual(2); + expect(resourceLevel).toBeLessThanOrEqual(5); + const speed = resourceLevel - 1; + try { + expect(await bfb.setCpuSpeed(speed)).toBe(1); + expect((await bfb.readMemory(CPU_RESOURCE_LEVEL_ADDRESS, 2)).buffer.readUInt16LE(0)).toBe(resourceLevel); + expect(await bfb.ping()).toBe(true); + } finally { + await bfb.setCpuSpeed(speed); + } + expect((await bfb.readMemory(CPU_RESOURCE_LEVEL_ADDRESS, 2)).buffer.readUInt16LE(0)).toBe(resourceLevel); + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('smi-normal')('switches SMI to normal mode', async () => { + await bfb.switchSmiToNormal(); + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('bluetooth-mapper')('changes Bluetooth mapper state without a readable original value', async () => { + try { + await bfb.activateBluetoothMapper(); + } finally { + await bfb.setBluetoothMapper(false); + } + expect(await bfb.ping()).toBe(true); + }); + + test('receives a display event while another command runs', async () => { + const address = await bfb.getDisplayBufferAddress(); + const original = (await bfb.readMemory(address, 1)).buffer; + const events: { left: number; top: number; right: number; bottom: number }[] = []; + let redirected = false; + let changed = false; + try { + await bfb.redirectDisplay((event) => events.push(event)); + redirected = true; + await bfb.writeMemory(address, Buffer.from([original[0] ^ 0xFF])); + changed = true; + await bfb.updateDisplay(0, 0, 1, 1); + await bfb.readMemory(address, 1); + await vi.waitFor(() => expect(events).toContainEqual({ left: 0, top: 0, right: 0, bottom: 0 }), { timeout: 5000 }); + } finally { + if (changed) { + await bfb.writeMemory(address, original); + await bfb.updateDisplay(0, 0, 1, 1); + } + if (redirected) + await bfb.redirectDisplay(); + } + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('amc')('runs a caller-selected AMC transaction', async () => { + const mode = readRequiredNumberEnv('BFB_AMC_MODE'); + const result = await bfb.amcAdvanced(mode, readRequiredNumberListEnv('BFB_AMC_DATA')); + if (mode == 8) + expect(result).toBeUndefined(); + else + expect(result).toEqual(expect.any(Number)); + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('dsp-command')('runs a caller-provided DSP command', async () => { + expect(await bfb.sendDspCommand(readRequiredNumberListEnv('BFB_DSP_WORDS'))).toBeInstanceOf(Buffer); + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('rf-channel')('sets caller-provided RF channels', async () => { + const arfcn = readRequiredNumberEnv('BFB_RF_ARFCN'); + const control = readRequiredNumberEnv('BFB_RF_CONTROL'); + const band = readRequiredNumberEnv('BFB_RF_BAND'); + const mode = readRequiredNumberEnv('BFB_RF_MODE'); + await bfb.setRxTxChannel(arfcn, control); + await bfb.setMonitorChannel(arfcn, control); + await bfb.setRxTxBandChannel(band, arfcn, control, mode); + await bfb.setMonitorBandChannel(band, arfcn, control, mode); + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('rf-calibration')('writes caller-provided RF calibration values', async () => { + await bfb.setPowerMode(readRequiredNumberEnv('BFB_POWER_MODE')); + await bfb.setTxPwm(readRequiredNumberEnv('BFB_TX_PWM')); + await bfb.setMc45PrechargeRampValue(readRequiredNumberEnv('BFB_MC45_PRECHARGE')); + await bfb.setPaCompensation(readRequiredNumberEnv('BFB_PA_COMPENSATION')); + await bfb.setNfScaling( + readRequiredNumberEnv('BFB_NF_SCALING_A'), + readRequiredNumberEnv('BFB_NF_SCALING_B'), + ); + await bfb.setTimingScenario(readRequiredNumberEnv('BFB_TIMING_SCENARIO')); + await bfb.setKeyValueRamp(readRequiredNumberEnv('BFB_KEY_VALUE_RAMP')); + expect(await bfb.ping()).toBe(true); + }); + + testUnsafeAction('audio-control')('runs caller-selected audio and vibra commands', async () => { + try { + await bfb.playToneOv( + readRequiredNumberEnv('BFB_TONE_OV_VALUE'), + readRequiredNumberEnv('BFB_TONE_OV_OPTION'), + ); + await bfb.setVibra(readRequiredNumberEnv('BFB_VIBRA_VALUE')); + await bfb.setPowerManagement( + readRequiredNumberEnv('BFB_POWER_MANAGEMENT_MODE'), + readRequiredNumberEnv('BFB_POWER_MANAGEMENT_VALUE'), + ); + await bfb.clickSchalkeKey( + readRequiredNumberEnv('BFB_SCHALKE_GROUP'), + readRequiredNumberEnv('BFB_SCHALKE_KEY'), + readRequiredNumberEnv('BFB_SCHALKE_OPTION'), + ); + await bfb.speechOff(); + } finally { + await bfb.setVibra(0); + await bfb.stopTone(); + } + expect(await bfb.ping()).toBe(true); + }); + + testDestructiveAction('ramp-bid')('writes a caller-provided ramp BID', async () => { + await bfb.setRampBid(readRequiredNumberEnv('BFB_RAMP_BID')); + await bfb.setU35RampBidTable( + readRequiredNumberEnv('BFB_U35_RAMP_MODE'), + readRequiredNumberEnv('BFB_U35_RAMP_START'), + readRequiredNumberEnv('BFB_U35_RAMP_COUNT'), + readRequiredNumberEnv('BFB_U35_RAMP_BID'), + readRequiredNumberEnv('BFB_U35_RAMP_ADDRESS'), + ); + await bfb.setU35RampBidValue( + readRequiredNumberEnv('BFB_U35_RAMP_INDEX'), + readRequiredNumberEnv('BFB_U35_RAMP_BID'), + ); + expect(await bfb.ping()).toBe(true); + }); + + testDestructiveAction('service-stream')('sends caller-provided raw service-stream forms', async () => { + const chunk = readRequiredHexEnv('BFB_SERVICE_STREAM_CHUNK'); + await bfb.sendServiceStream(chunk); + await bfb.sendServiceStreamTerminator(readRequiredHexEnv('BFB_SERVICE_STREAM_TERMINATOR')); + expect(await bfb.ping()).toBe(true); + }); + + testDestructiveAction('security-string')('sends a caller-provided security string', async () => { + const value = process.env.BFB_SECURITY_STRING; + if (value === undefined) + throw new Error('BFB_SECURITY_STRING is required.'); + expect(await bfb.sendSecurityString(value)).toBeInstanceOf(Buffer); + }); + + testDestructiveAction('security-delay')('collects security completion and delay frames', async () => { + const value = process.env.BFB_SECURITY_DELAY_STRING; + if (value === undefined) + throw new Error('BFB_SECURITY_DELAY_STRING is required.'); + const result = await bfb.sendSecurityStringWithDelayValue(value); + expect(result.response).toBeInstanceOf(Buffer); + expect(result.delay).toBeGreaterThanOrEqual(0); + expect(result.delay).toBeLessThanOrEqual(0xFF); + }); + + testDestructiveAction('security-key')('sends a caller-provided security key', async () => { + await bfb.sendSecurityKey(readRequiredNumberEnv('BFB_SECURITY_KEY')); + expect(await bfb.ping()).toBe(true); + }); + + testDestructiveAction('freeze-security')('freezes security data for a caller-provided IMEI', async () => { + const imei = process.env.BFB_FREEZE_IMEI; + if (imei === undefined) + throw new Error('BFB_FREEZE_IMEI is required.'); + expect(await bfb.freezeSecurityData(imei)).toEqual(expect.any(Number)); + }); + + testDestructiveAction('delete-eep-instance')('deletes a caller-selected EEPROM instance', async () => { + await bfb.deleteEepInstance(readRequiredNumberEnv('BFB_EEP_INSTANCE')); + }); + + testDestructiveAction('garbage-collect-eefull')('forces EEFULL garbage collection', async () => { + const maxBlockId = await bfb.getEepMaxBlockId('eefull'); + let blockId: number | undefined; + let info; + for (let candidate = 5000; candidate <= maxBlockId; candidate++) { + try { + info = await bfb.getEepBlockInfo(candidate, 'eefull'); + blockId = candidate; + break; + } catch (error) { + if (!(error instanceof BfbRemoteError) || error.status != 0x32) + throw error; + } + } + expect(blockId).toBeDefined(); + expect(info).toBeDefined(); + if (blockId === undefined || info === undefined) + throw new Error('No existing EEFULL block available for garbage-collection verification.'); + const data = await bfb.readEepBlock(blockId, 0, info.size, 'eefull'); + await bfb.garbageCollectEefull(); + expect(await bfb.getEepBlockInfo(blockId, 'eefull')).toEqual(info); + expect(await bfb.readEepBlock(blockId, 0, info.size, 'eefull')).toEqual(data); + expect(await bfb.ping()).toBe(true); + }, 60000); + + test('disconnects and reconnects without closing the port', async () => { + await bfb.disconnect(); + await bfb.connect(); + expect(BFB_BAUD_RATES[port.baudRate]).toBeDefined(); + expect(await bfb.ping()).toBe(true); + }, 30000); + + testSessionAction('power-off')('powers off the phone and ends the session', async () => { + await bfb.powerOff(); + expect(port.isOpen).toBe(true); + }); + + testSessionAction('software-update')('enters software-update mode and ends the session', async () => { + await bfb.enterSoftwareUpdate(readRequiredNumberEnv('BFB_SOFTWARE_UPDATE_BAUD_RATE')); + expect(port.isOpen).toBe(true); + }); + +}); + +async function findEmptyRamPage(bfb: BFB): Promise { + for (let address = RAM_START + RAM_SIZE - RAM_PAGE_SIZE; address >= RAM_START; address -= RAM_PAGE_SIZE) { + const sample = (await bfb.readMemory(address, 31)).buffer; + if (!sample.every((value) => value == 0)) + continue; + + const page = (await bfb.readMemory(address, RAM_PAGE_SIZE)).buffer; + if (page.every((value) => value == 0)) + return address; + } + + throw new Error('No empty 16-KiB RAM page found.'); +} + +async function expectSupportedOrUnsupported(callback: () => Promise): Promise { + try { + expect(await callback()).toBeDefined(); + } catch (error) { + if (error instanceof BfbUnsupportedCommandError) + return; + throw error; + } +} + +async function expectSupportedOrNoResponse(callback: () => Promise): Promise { + try { + await callback(); + } catch (error) { + if (error instanceof BfbUnsupportedCommandError || error instanceof BfbCommandTimeoutError) + return; + throw error; + } +} + +function readRequiredNumberEnv(name: string): number { + const value = process.env[name]; + if (value === undefined) + throw new Error(`${name} is required.`); + const number = Number(value); + if (!Number.isInteger(number)) + throw new Error(`${name} must be an integer.`); + return number; +} + +function readRequiredHexEnv(name: string): Buffer { + const value = process.env[name]; + if (value === undefined) + throw new Error(`${name} is required.`); + if (!value.match(/^(?:[0-9a-fA-F]{2})*$/)) + throw new Error(`${name} must contain an even-length hexadecimal string.`); + return Buffer.from(value, 'hex'); +} + +function readRequiredNumberListEnv(name: string): number[] { + const value = process.env[name]; + if (value === undefined) + throw new Error(`${name} is required.`); + if (value == '') + return []; + return value.split(',').map((item) => { + const number = Number(item); + if (!Number.isInteger(number)) + throw new Error(`${name} must contain comma-separated integers.`); + return number; + }); +} diff --git a/src/BFB.ts b/src/BFB.ts new file mode 100644 index 0000000..75e6107 --- /dev/null +++ b/src/BFB.ts @@ -0,0 +1,1898 @@ +import createDebug from 'debug'; +import { AtChannel } from './AtChannel.js'; +import { sprintf } from 'sprintf-js'; +import { ioReadMemory, IoReadResult, IoReadWriteOptions, ioWriteMemory, IoWriteResult } from './io.js'; +import { BaseSerialProtocol } from './BaseSerialProtocol.js'; +import { decodeCString, delay, usePromiseWithResolvers } from './utils.js'; + +const debug = createDebug('bfb'); +const debugTrx = createDebug('bfb:trx'); + +export const BFB_MAX_PAYLOAD_SIZE = 32; +export const BFB_MAX_MEMORY_READ_CHUNK = 31; +export const BFB_MAX_MEMORY_WRITE_CHUNK = 25; + +const BFB_EEP_READ_CHUNK = 30; +const BFB_EEP_WRITE_CHUNK = 20; +const BFB_EEP_MAX_WRITE_CHUNK = BFB_MAX_PAYLOAD_SIZE - 6; +const BFB_PING_ATTEMPTS = 10; + +export enum BfbChannel { + CONFIGURATION = 0x01, + CORE = 0x02, + HARDWARE = 0x05, + AT = 0x06, + GBS = 0x07, + SECURITY = 0x0B, + INFO = 0x0E, + EEPROM = 0x14, + SERVICE_STREAM = 0x16, +} + +export enum BfbCoreOpcode { + WRITE_MEMORY_BLOCK = 0x01, + READ_MEMORY = 0x02, + PING = 0x14, + WRITE_MEMORY_BYTE = 0x30, + WRITE_MEMORY_WORD = 0x31, + GET_DEBUGGER_NAME = 0x42, + EXEC_CODE = 0x75, +} + +export enum BfbConfigurationOpcode { + POWER_SAVING = 0x11, + POWER_SAVING_ACK = 0x12, + POWER_SAVING_REJECTED = 0x13, + SET_BAUD_RATE = 0xC0, + BAUD_RATE_ACK = 0xCC, + BAUD_RATE_REJECTED = 0xCF, +} + +export enum BfbHardwareOpcode { + PRESS_KEY = 0x06, + GET_DISPLAY_BUFFER_ADDRESS = 0x07, + UPDATE_DISPLAY = 0x08, + REDIRECT_KEYPAD = 0x0A, + RESTORE_KEYPAD = 0x0B, + KEYPAD_EVENT = 0x0C, + REDIRECT_DISPLAY = 0x0D, + RESTORE_DISPLAY = 0x0E, + DISPLAY_EVENT = 0x0F, + SET_DISPLAY_CONTRAST = 0x10, + PLAY_TONE = 0x11, + STOP_TONE = 0x12, + BOOT_DSP = 0x13, + GET_DISPLAY_TYPE = 0x14, + GET_SENSOR_ADDRESSES = 0x16, + SET_ENVIRONMENT_TEMPERATURE = 0x17, + ACTIVATE_NF_CONTROL = 0x18, + CONFIGURE_NF_CONTROL = 0x19, + DEACTIVATE_NF_CONTROL = 0x1A, + GET_HARDWARE_ID = 0x21, + GET_FLASH_SERIAL_NUMBER = 0x23, + GET_HARDWARE_INFO = 0x24, + GET_HARDWARE_DATA = 0x25, + SEND_DSP_COMMAND = 0x30, + SET_RX_TX_CHANNEL = 0x31, + SET_MONITOR_CHANNEL = 0x32, + SET_RAMP_BID = 0x33, + SET_POWER_MODE = 0x34, + GET_POWER_VALUES = 0x35, + SET_TX_PWM = 0x36, + SET_PA_COMPENSATION = 0x37, + SET_NF_SCALING = 0x38, + SIMULATE_CHIP_CARD = 0x39, + GET_AUDIO_GAIN_SHADOW = 0x3A, + GET_FIRMWARE_INFORMATION = 0x3B, + GET_NORMAL_MODE_RX_LEVEL = 0x3C, + SWITCH_SMI_TO_NORMAL = 0x3D, + SWITCH_SPEECH_OFF = 0x3E, + GET_MOBILE_MODE = 0x3F, + SWITCH_OFF_DISPLAY = 0x40, + PLAY_OV_TONE = 0x41, + SET_TIMING_SCENARIO = 0x42, + SET_KEY_VALUE_RAMP = 0x43, + CONTROL_LIGHT = 0x46, + GET_IQ_VALUES = 0x4A, + SET_VIBRA = 0x4B, + GET_POWER_ASIC_PROJECT = 0x4F, + SET_POWER_MANAGEMENT = 0x51, + CLICK_SCHALKE_KEY = 0x52, + GET_DSP_FIRMWARE_VERSION = 0x53, + TEST_LUMBERG = 0x55, + AUDIO_DIAGNOSTICS = 0x56, + SET_CPU_SPEED = 0x62, + RESET_GPRS_BLER_COUNTERS = 0x70, + GET_GPRS_BLER_COUNTERS = 0x71, + SET_BLUETOOTH_MAPPER = 0x72, + SET_RX_TX_BAND_CHANNEL = 0x73, + SET_MONITOR_BAND_CHANNEL = 0x74, + AFC = 0x77, + GENERATE_DISPLAY_PATTERN = 0x78, + AMC_ADVANCED = 0x81, +} + +export enum BfbInfoOpcode { + GET_BATTERY_VOLTAGE = 0x02, + GET_FIRMWARE_VERSION = 0x03, + POWER_OFF = 0x04, + GET_FLAG_STATUS = 0x05, + GET_MODEL_INFORMATION = 0x07, + GET_SOFTWARE_VERSION = 0x08, + GET_LANGUAGE_INFORMATION = 0x09, + GET_IMEI = 0x0A, + INFORMATION_ELEMENT = 0x0B, + BOOT_PIN_SETTINGS = 0x0C, + ENTER_SOFTWARE_UPDATE = 0x20, +} + +export enum BfbEepOpcode { + CREATE_EELITE_BLOCK = 0x01, + WRITE_EELITE_BLOCK = 0x02, + FINISH_EELITE_BLOCK = 0x03, + READ_EELITE_BLOCK = 0x04, + GET_EELITE_BLOCK_INFO = 0x05, + GET_EELITE_MAX_BLOCK_ID = 0x06, + DELETE_EELITE_BLOCK = 0x07, + GET_EELITE_SPACE_INFO = 0x08, + CREATE_EEFULL_BLOCK = 0x11, + WRITE_EEFULL_BLOCK = 0x12, + FINISH_EEFULL_BLOCK = 0x13, + READ_EEFULL_BLOCK = 0x14, + GET_EEFULL_BLOCK_INFO = 0x15, + GET_EEFULL_MAX_BLOCK_ID = 0x16, + DELETE_EEFULL_BLOCK = 0x17, + GET_EEFULL_SPACE_INFO = 0x18, + WRITE_EEFULL_RANGE = 0x1A, + GARBAGE_COLLECT_EEFULL = 0x1B, + DELETE_INSTANCE = 0x51, + FREEZE_SECURITY_DATA = 0x52, +} + +export enum BfbGbsOpcode { + ALLOCATE = 0x01, + FREE = 0x02, +} + +export enum BfbAtOpcode { + REMOTE_CONTROL = 0xF0, +} + +export enum BfbSecurityMode { + REPAIR = 0, + DEVELOPER = 1, + FACTORY = 2, + CUSTOMER = 3, +} + +export type BfbEepStorage = 'auto' | 'eelite' | 'eefull'; + +type BfbFrame = { + channel: number; + data: Buffer; +}; + +type BfbFrameReceiver = { + channel: number; + opcode: number; + resolve: (frame: BfbFrame) => void; + reject: (error: Error) => void; + timeoutId: NodeJS.Timeout; +}; + +type BfbEepExecOptions = { + timeout?: number; + allowWait?: boolean; + refreshTimeoutOnWait?: boolean; + responseLength?: number; +}; + +export type BfbApiExecOptions = { + timeout?: number; + expectedChannel?: number; + expectedOpcode?: number; + responseLength?: number; + minResponseLength?: number; +}; + +export type BfbEepBlockInfo = { + size: number; + version: number; + storage: Exclude; +}; + +export type BfbEepSpaceInfo = { + freeBlocks: number; + freeAddressSpace: number; + freeDataSpace: number; +}; + +export type BfbGprsBlerCounters = { + counterA: number; + counterB: number; +}; + +export type BfbDisplayEvent = { + left: number; + top: number; + right: number; + bottom: number; + bufferAddress?: number; + bytesPerPixel?: number; +}; + +export enum BfbDisplayRedirectMode { + RECT = 0x00, + RECT_WITH_ADDRESS = 0x01, + NO_CALLBACK = 0x02, + RAW_RECT = 0x10, + RAW_RECT_WITH_ADDRESS = 0x11, + RAW_NO_CALLBACK = 0x12, +} + +export enum BfbDisplayPattern { + SOLID = 0x00, + GRID = 0x01, + CHECKERBOARD = 0x02, + GRADIENT = 0x03, + COLOR_BARS = 0x04, + VALUE_GRID = 0x64, +} + +export type BfbDisplayState = { + x: number; + y: number; + width: number; + height: number; + bufferAddress: number; + bytesPerPixel: number; + data: Buffer; +}; + +export type BfbSensorData = { + voltages: [number, number, number]; + temperatures: [number, number, number]; +}; + +export type BfbSensorAddresses = { + raw: number; + calibrated: number; +}; + +export type BfbWordPair = [number, number]; + +export type BfbInformationElementList = { + count: number; + elements: number[]; +}; + +export type BfbSoftwareVersion = { + date: string; + time: string; +}; + +export type BfbSecurityStringResponse = { + response: Buffer; + delay: number; +}; + +enum BfbTransportMode { + NONE, + AT, + BFB, +} + +export const BFB_BAUD_RATES: Record = { + 57600: 57600, + 115200: 115200, + 230400: 230000, + 460800: 460000, +}; + +const BFB_RESPONSE_LENGTHS: Partial>> = { + [BfbChannel.HARDWARE]: { + [BfbHardwareOpcode.GET_DISPLAY_BUFFER_ADDRESS]: 5, + [BfbHardwareOpcode.DISPLAY_EVENT]: 11, + [BfbHardwareOpcode.GET_SENSOR_ADDRESSES]: 9, + [BfbHardwareOpcode.GET_HARDWARE_ID]: 3, + [BfbHardwareOpcode.GET_FLASH_SERIAL_NUMBER]: 5, + [BfbHardwareOpcode.GET_HARDWARE_INFO]: 3, + [BfbHardwareOpcode.GET_AUDIO_GAIN_SHADOW]: 3, + [BfbHardwareOpcode.GET_NORMAL_MODE_RX_LEVEL]: 3, + [BfbHardwareOpcode.GET_GPRS_BLER_COUNTERS]: 5, + }, + [BfbChannel.GBS]: { + [BfbGbsOpcode.ALLOCATE]: 5, + }, +}; + +const BFB_EEP_STATUS: Record = { + 0x30: 'EEPROM returned status OK without echoing the requested opcode.', + 0x31: 'EEPROM is not initialized.', + 0x32: 'EEPROM block does not exist.', + 0x33: 'EEPROM block id is not locked.', + 0x34: 'EEPROM response block id mismatch.', + 0x35: 'EEPROM has no free data space.', + 0x36: 'EEPROM block is too small.', + 0x37: 'EEPROM block is in use.', + 0x20: 'EEPROM transmission error.', +}; + +export class BfbRemoteError extends Error { + readonly status: number; + + constructor(status: number, message?: string) { + super(message ?? sprintf('BFB remote error: 0x%02X', status)); + this.name = 'BfbRemoteError'; + this.status = status; + } +} + +export class BfbUnsupportedCommandError extends Error { + readonly channel: number; + readonly opcode: number; + + constructor(channel: number, opcode: number) { + const command = getBfbOpcodeName(channel, opcode) ?? 'command'; + super(sprintf('BFB %s is unsupported in the current phone mode (%02X/%02X returned no data).', command, channel, opcode)); + this.name = 'BfbUnsupportedCommandError'; + this.channel = channel; + this.opcode = opcode; + } +} + +export class BfbCommandTimeoutError extends Error { + readonly channel: number; + readonly opcode: number; + + constructor(channel: number, opcode: number) { + super(sprintf('BFB command %02X/%02X timeout.', channel, opcode)); + this.name = 'BfbCommandTimeoutError'; + this.channel = channel; + this.opcode = opcode; + } +} + +export class BFB extends BaseSerialProtocol { + private mode = BfbTransportMode.NONE; + private buffer = Buffer.alloc(0); + private frames: BfbFrame[] = []; + private frameQueueChannel?: number; + private frameReceiver?: BfbFrameReceiver; + private keypadCallback?: (data: Buffer) => void; + private displayCallback?: (event: BfbDisplayEvent) => void; + private displayRedirectMode?: BfbDisplayRedirectMode; + private readonly handleSerialDataCallback = this.handleSerialData.bind(this); + private readonly handleSerialCloseCallback = this.handleSerialClose.bind(this); + private readonly atc = new AtChannel(this.port); + + private setTransportMode(mode: BfbTransportMode): void { + if (this.mode == mode) + return; + + this.mode = mode; + switch (mode) { + case BfbTransportMode.NONE: + debug('Mode: NONE'); + this.port.off('data', this.handleSerialDataCallback); + this.port.off('close', this.handleSerialCloseCallback); + this.atc.stop(); + this.buffer = Buffer.alloc(0); + this.frames = []; + this.frameQueueChannel = undefined; + this.keypadCallback = undefined; + this.displayCallback = undefined; + this.displayRedirectMode = undefined; + break; + + case BfbTransportMode.AT: + debug('Mode: AT'); + this.port.off('data', this.handleSerialDataCallback); + this.port.off('close', this.handleSerialCloseCallback); + this.atc.start(); + this.buffer = Buffer.alloc(0); + this.frames = []; + this.frameQueueChannel = undefined; + break; + + case BfbTransportMode.BFB: + debug('Mode: BFB'); + this.atc.stop(); + this.port.on('data', this.handleSerialDataCallback); + this.port.on('close', this.handleSerialCloseCallback); + break; + } + } + + private async findOpenedBfb(): Promise { + this.setTransportMode(BfbTransportMode.BFB); + for (const baudRate of Object.keys(BFB_BAUD_RATES).map(Number).sort((a, b) => b - a)) { + debug(`Probing BFB at baudrate: ${baudRate}`); + await this.port.update({ baudRate }); + if (await this.pingMobile(350)) { + debug(`Phone is already in BFB mode!`); + return baudRate; + } + } + this.setTransportMode(BfbTransportMode.NONE); + return 0; + } + + private async trySwitchFromAtToBfb(): Promise { + await this.port.update({ baudRate: 115200 }); + debug('Probing AT handshake at 115200...'); + this.setTransportMode(BfbTransportMode.AT); + + if (await this.atc.handshake()) { + debug('Phone in AT mode, switching from AT to BFB...'); + const response = await this.atc.sendCommandNumeric('AT^SQWE=1', 1000); + if (response.success) { + this.setTransportMode(BfbTransportMode.BFB); + await delay(300); // Wait for BFB is ready + await this.port.update({ baudRate: 57600 }); + if (!await this.pingMobile()) + throw new Error('Switching to BFB failed! (ping at 57600)'); + debug('Successfully switched to BFB mode!'); + return true; + } else { + this.setTransportMode(BfbTransportMode.NONE); + throw new Error('Switching to BFB failed! (AT^SQWE=1)'); + } + } else { + debug('AT handshake failed, maybe phone in BFB mode?'); + return false; + } + } + + async connect(): Promise { + if (this.mode == BfbTransportMode.BFB) + throw new Error('BFB already connected.'); + if (!this.port.isOpen) + throw new Error('Serial port closed.'); + await this.port.setSignals({ dtr: true }); + + try { + if (await this.trySwitchFromAtToBfb()) + return; + + if (await this.findOpenedBfb()) + return; + } catch (error) { + this.setTransportMode(BfbTransportMode.NONE); + throw error; + } + + this.setTransportMode(BfbTransportMode.NONE); + throw new Error('Phone not found.'); + } + + async disconnect(): Promise { + if (this.mode != BfbTransportMode.BFB) + return; + this.handleSerialClose(); + } + + private handleSerialClose(): void { + if (this.frameReceiver) { + const receiver = this.frameReceiver; + this.frameReceiver = undefined; + clearTimeout(receiver.timeoutId); + receiver.reject(new Error('BFB connection closed.')); + } + this.setTransportMode(BfbTransportMode.NONE); + } + + private handleSerialData(data: Buffer): void { + this.buffer = Buffer.concat([this.buffer, data]); + while (this.buffer.length >= 3) { + const channel = this.buffer[0]; + const length = this.buffer[1]; + if (this.buffer[2] != (channel ^ length) || length > BFB_MAX_PAYLOAD_SIZE) { + this.buffer = this.buffer.subarray(1); + continue; + } + if (this.buffer.length < 3 + length) + break; + const frame = { channel, data: Buffer.from(this.buffer.subarray(3, 3 + length)) }; + this.buffer = this.buffer.subarray(3 + length); + try { + this.handleBfbFrame(frame); + } catch (error) { + debug('BFB event callback failed: %O', error); + } + } + } + + private handleBfbFrame(frame: BfbFrame): void { + if (debugTrx.enabled) + debugTrx(sprintf('RX CH=%02X %s', frame.channel, frame.data.toString('hex'))); + + const receiver = this.frameReceiver; + if (receiver && this.frameMatches(frame, receiver.channel, receiver.opcode)) { + this.frameReceiver = undefined; + clearTimeout(receiver.timeoutId); + receiver.resolve(frame); + return; + } + if (frame.channel == this.frameQueueChannel) { + this.frames.push(frame); + return; + } + if (frame.channel == BfbChannel.HARDWARE && frame.data[0] == BfbHardwareOpcode.KEYPAD_EVENT) { + if (this.keypadCallback) + this.keypadCallback(Buffer.from(frame.data.subarray(1))); + else + debug(`Ignored BFB keypad event: ${frame.data.toString('hex')}`); + return; + } + if (frame.channel == BfbChannel.HARDWARE && frame.data[0] == BfbHardwareOpcode.DISPLAY_EVENT) { + if (this.displayCallback && (frame.data.length == 5 || frame.data.length == 11)) { + const left = frame.data[1]; + const top = frame.data[2]; + let right = frame.data[3]; + let bottom = frame.data[4]; + if (this.displayRedirectMode == BfbDisplayRedirectMode.RAW_RECT || this.displayRedirectMode == BfbDisplayRedirectMode.RAW_RECT_WITH_ADDRESS) { + right = left + right - 1; + bottom = top + bottom - 1; + } + const event: BfbDisplayEvent = { left, top, right, bottom }; + if (frame.data.length == 11) { + event.bufferAddress = frame.data.readUInt32LE(5); + event.bytesPerPixel = frame.data.readUInt16LE(9); + } + this.displayCallback(event); + } else { + debug(`Ignored BFB display event: ${frame.data.toString('hex')}`); + } + return; + } + debug(sprintf('Ignored BFB frame CH=%02X %s', frame.channel, frame.data.toString('hex'))); + } + + private frameMatches(frame: BfbFrame, channel: number, opcode: number): boolean { + return (channel == 0 || frame.channel == channel) && (opcode == 0 || frame.data[0] == opcode); + } + + private async receiveBfbFrame(channel: number, opcode: number, deadline: number, send?: () => Promise): Promise { + const index = this.frames.findIndex((frame) => this.frameMatches(frame, channel, opcode)); + if (index >= 0) + return this.frames.splice(index, 1)[0]; + + const timeout = deadline - Date.now(); + if (timeout <= 0) + throw new BfbCommandTimeoutError(channel, opcode); + + const { promise, resolve, reject } = usePromiseWithResolvers(); + const receiver: BfbFrameReceiver = { + channel, + opcode, + resolve, + reject, + timeoutId: setTimeout(() => { + this.frameReceiver = undefined; + reject(new BfbCommandTimeoutError(channel, opcode)); + }, timeout), + }; + this.frameReceiver = receiver; + if (!send) + return promise; + try { + const [frame] = await Promise.all([promise, send()]); + return frame; + } catch (error) { + if (this.frameReceiver == receiver) { + this.frameReceiver = undefined; + clearTimeout(receiver.timeoutId); + } + throw error; + } + } + + private async withFrameQueue(channel: number, action: () => Promise): Promise { + this.frameQueueChannel = channel; + this.frames = []; + try { + return await action(); + } finally { + this.frameQueueChannel = undefined; + for (const frame of this.frames) + debug(sprintf('Ignored BFB frame CH=%02X %s', frame.channel, frame.data.toString('hex'))); + this.frames = []; + } + } + + async exec( + channel: number, + payload: Buffer | number[], + options: BfbApiExecOptions = {}, + ): Promise { + if (this.mode != BfbTransportMode.BFB) + throw new Error('BFB is not connected.'); + + const data = Buffer.isBuffer(payload) ? payload : Buffer.from(payload); + const validOptions = { + timeout: 5000, + expectedChannel: channel, + expectedOpcode: data[0] ?? 0, + ...options, + }; + const frame = await this.receiveBfbFrame( + validOptions.expectedChannel, + validOptions.expectedOpcode, + Date.now() + validOptions.timeout, + () => this.sendFrame(channel, data), + ); + const expectedLength = validOptions.responseLength ?? BFB_RESPONSE_LENGTHS[channel]?.[data[0] ?? 0]; + const requiredLength = Math.max(expectedLength ?? 0, validOptions.minResponseLength ?? 0); + if (requiredLength > 1 && frame.data.length == 1 && frame.data[0] == data[0]) + throw new BfbUnsupportedCommandError(channel, data[0]); + if (expectedLength !== undefined && frame.data.length != expectedLength) + throw new Error(`Invalid BFB response length: ${frame.data.length}, expected ${expectedLength}.`); + if (validOptions.minResponseLength !== undefined && frame.data.length < validOptions.minResponseLength) + throw new Error(`Invalid BFB response length: ${frame.data.length}, expected at least ${validOptions.minResponseLength}.`); + return frame.data; + } + + private async pingMobile(timeout = 1000): Promise { + for (let attempt = 0; attempt < BFB_PING_ATTEMPTS; attempt++) { + if (await this.ping(timeout)) + return true; + } + return false; + } + + async sendFrame(channel: number, payload: Buffer | number[]): Promise { + if (this.mode != BfbTransportMode.BFB) + throw new Error('BFB is not connected.'); + + const frame = encodeBfbFrame(channel, payload); + if (debugTrx.enabled) { + const data = frame.subarray(3); + debugTrx(sprintf('TX CH=%02X %s', channel, data.toString('hex'))); + } + await this.port.write(frame); + } + + // ---------------------------------------------------------------------------------- + // BFB API + // ---------------------------------------------------------------------------------- + + async ping(timeout = 1000): Promise { + try { + const response = await this.exec(BfbChannel.CORE, [BfbCoreOpcode.PING], { timeout }); + return response.length == 2 && response[0] == BfbCoreOpcode.PING && response[1] == 0xAA; + } catch (error) { + return false; + } + } + + async getDebuggerName(): Promise { + return this.withFrameQueue(BfbChannel.CORE, async () => { + await this.sendFrame(BfbChannel.CORE, [BfbCoreOpcode.GET_DEBUGGER_NAME]); + const deadline = Date.now() + 5000; + const chunks: Buffer[] = []; + let expectedOpcode: number = BfbCoreOpcode.GET_DEBUGGER_NAME; + while (true) { + const frame = await this.receiveBfbFrame(BfbChannel.CORE, expectedOpcode, deadline); + if (expectedOpcode && frame.data.length < 2) + throw new Error('Invalid BFB debugger name response.'); + chunks.push(expectedOpcode ? frame.data.subarray(1) : frame.data); + expectedOpcode = 0; + if (frame.data.length < BFB_MAX_PAYLOAD_SIZE) + return decodeCString(Buffer.concat(chunks)); + } + }); + } + + async setPhoneBaudrate(baudRate: number): Promise { + const previousBaudRate = this.port.baudRate; + const bfbBaudrateCode = BFB_BAUD_RATES[baudRate]; + if (bfbBaudrateCode === undefined) + throw new Error(`Unsupported BFB baudrate: ${baudRate}.`); + + if (baudRate == previousBaudRate) + return true; + + let acknowledged = false; + try { + const payload = Buffer.concat([ + Buffer.from([BfbConfigurationOpcode.SET_BAUD_RATE]), + Buffer.from(bfbBaudrateCode.toString(), 'ascii'), + ]); + const request = Buffer.concat([payload, computeBfbBaudCrc(payload)]); + const response = await this.exec(BfbChannel.CONFIGURATION, request, { + expectedOpcode: 0, + }); + if (response[0] == BfbConfigurationOpcode.BAUD_RATE_ACK) { + acknowledged = response.subarray(1).equals(request.subarray(1)); + if (!acknowledged) + debug(`Invalid baudrate acknowledgement: ${response.toString('hex')}`); + } else if (response[0] != BfbConfigurationOpcode.BAUD_RATE_REJECTED) { + throw new Error(sprintf('Unexpected baud response opcode: 0x%02X', response[0] ?? 0)); + } + } catch (error) { + debug(`Baudrate acknowledgement failed: ${error}`); + } + + if (acknowledged) { + await this.port.update({ baudRate }); + await delay(75); + if (await this.ping()) + return true; + } + + await this.port.update({ baudRate: previousBaudRate }); + await delay(75); + if (await this.ping()) + return false; + + await this.port.update({ baudRate }); + await delay(75); + if (await this.ping()) + return true; + + await this.port.update({ baudRate: previousBaudRate }); + return false; + } + + async setBestBaudrate(limitBaudrate = 0): Promise { + const baudRates = Object.keys(BFB_BAUD_RATES).map(Number) + .filter((baudRate) => !limitBaudrate || baudRate <= limitBaudrate) + .sort((a, b) => b - a); + for (const baudRate of baudRates) { + debug(`Probing new baudrate: ${baudRate}`); + if (await this.setPhoneBaudrate(baudRate)) { + debug(`New baudrate: ${baudRate}`); + return true; + } + if (!await this.ping()) { + debug(`Phone connection lost!!!`); + return false; + } + } + return false; + } + + async configurePowerSaving(mode: number): Promise { + const response = await this.exec(BfbChannel.CONFIGURATION, [BfbConfigurationOpcode.POWER_SAVING, mode], { expectedOpcode: 0 }); + if (response[0] == BfbConfigurationOpcode.POWER_SAVING_REJECTED) + throw new BfbRemoteError(response[0], 'BFB power-saving configuration was rejected.'); + if (response.length != 2) + throw new Error(`Invalid BFB power-saving response length: ${response.length}.`); + if (response[0] != BfbConfigurationOpcode.POWER_SAVING_ACK || response[1] != mode) { + throw new Error( + `Invalid BFB power-saving response: ${response.toString('hex')}, expected 12${mode.toString(16).padStart(2, '0')}.`, + ); + } + } + + async readMemory(address: number, length: number, options: IoReadWriteOptions = {}): Promise { + return ioReadMemory({ + pageSize: BFB_MAX_MEMORY_READ_CHUNK, + align: 1, + debug, + maxRetries: 3, + read: this.readMemoryChunk.bind(this), + }, address, length, options); + } + + async readMemoryChunk(address: number, length: number, buffer: Buffer, bufferOffset = 0): Promise { + if (!Number.isInteger(length) || length < 1 || length > BFB_MAX_MEMORY_READ_CHUNK) + throw new Error(`BFB memory read length must be in range 1..${BFB_MAX_MEMORY_READ_CHUNK}.`); + if (!Number.isInteger(bufferOffset) || bufferOffset < 0 || bufferOffset + length > buffer.length) + throw new Error('Target buffer is too small for the BFB memory read.'); + + const request = Buffer.alloc(7); + request.writeUInt8(BfbCoreOpcode.READ_MEMORY, 0); + request.writeUInt32LE(address, 1); + request.writeUInt16LE(length, 5); + const response = await this.exec(BfbChannel.CORE, request, { responseLength: length + 1 }); + response.copy(buffer, bufferOffset, 1); + } + + async writeMemory(address: number, buffer: Buffer, options: IoReadWriteOptions = {}): Promise { + return ioWriteMemory({ + pageSize: BFB_MAX_MEMORY_WRITE_CHUNK, + align: 1, + debug, + maxRetries: 3, + write: this.writeMemoryChunk.bind(this), + }, address, buffer, options); + } + + async writeMemoryChunk(address: number, buffer: Buffer): Promise { + if (!buffer.length || buffer.length > BFB_MAX_MEMORY_WRITE_CHUNK) + throw new Error(`BFB memory write length must be in range 1..${BFB_MAX_MEMORY_WRITE_CHUNK}.`); + + const request = Buffer.alloc(7 + buffer.length); + request.writeUInt8(BfbCoreOpcode.WRITE_MEMORY_BLOCK, 0); + request.writeUInt32LE(address, 1); + request.writeUInt16LE(buffer.length, 5); + buffer.copy(request, 7); + await this.execAck(BfbChannel.CORE, request); + } + + async writeMemoryByte(address: number, value: number): Promise { + const request = Buffer.alloc(6); + request.writeUInt8(BfbCoreOpcode.WRITE_MEMORY_BYTE, 0); + request.writeUInt32LE(address, 1); + request.writeUInt8(value, 5); + await this.execAck(BfbChannel.CORE, request); + } + + async writeMemoryWord(address: number, value: number): Promise { + const request = Buffer.alloc(7); + request.writeUInt8(BfbCoreOpcode.WRITE_MEMORY_WORD, 0); + request.writeUInt32LE(address, 1); + request.writeUInt16LE(value, 5); + await this.execAck(BfbChannel.CORE, request); + } + + async execCode(code: Buffer): Promise { + if (!code.length || code.length >= BFB_MAX_PAYLOAD_SIZE) + throw new Error(`BFB executable code length must be in range 1..${BFB_MAX_PAYLOAD_SIZE - 1}.`); + const response = await this.exec(BfbChannel.CORE, Buffer.concat([ + Buffer.from([BfbCoreOpcode.EXEC_CODE]), + code, + ])); + return response.subarray(1); + } + + async getHardwareId(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_HARDWARE_ID]); + return response.readUInt16LE(1); + } + + async getFlashSerialNumber(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_FLASH_SERIAL_NUMBER]); + return response.readUInt32LE(1); + } + + async getDisplayType(): Promise { + return this.readUInt8Command(BfbChannel.HARDWARE, BfbHardwareOpcode.GET_DISPLAY_TYPE); + } + + async getDisplayBufferAddress(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_DISPLAY_BUFFER_ADDRESS]); + return response.readUInt32LE(1); + } + + async getDisplayState(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.DISPLAY_EVENT]); + return { + x: response[1], + y: response[2], + width: response[3], + height: response[4], + bufferAddress: response.readUInt32LE(5), + bytesPerPixel: response.readUInt16LE(9), + data: Buffer.from(response.subarray(1)), + }; + } + + async getGprsBlerCounters(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_GPRS_BLER_COUNTERS]); + return { + counterA: response.readUInt16LE(1), + counterB: response.readUInt16LE(3), + }; + } + + async getHardwareData(selector: number): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_HARDWARE_DATA, selector], { minResponseLength: 2 }); + if (response.length >= BFB_MAX_PAYLOAD_SIZE) + throw new Error(`Invalid BFB hardware data response length: ${response.length}.`); + if (response[1] != selector) + throw new Error(`BFB hardware data selector mismatch: ${response[1]} != ${selector}.`); + if (response.length == 2) + throw new BfbUnsupportedCommandError(BfbChannel.HARDWARE, BfbHardwareOpcode.GET_HARDWARE_DATA); + return Buffer.from(response.subarray(2)); + } + + async getPowerValues(count: number): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_POWER_VALUES, count, 0x01], { + timeout: (count + 0x32) * 5, + minResponseLength: 3, + }); + return Buffer.from(response.subarray(1)); + } + + async getFirmwareInformation(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_FIRMWARE_INFORMATION], { minResponseLength: 5 }); + return Buffer.from(response.subarray(1)); + } + + async getIqMeanValues(count: number): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_IQ_VALUES, 0, count], { responseLength: 5 }); + return [response.readUInt16LE(1), response.readUInt16LE(3)]; + } + + async getIqDriftValues(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_IQ_VALUES, 1], { responseLength: 17 }); + return Array.from({ length: 8 }, (_value, index) => response.readUInt16LE(1 + index * 2)); + } + + async amcAdvanced(mode: number, data: number[] = []): Promise { + const request = Buffer.from([BfbHardwareOpcode.AMC_ADVANCED, mode, ...data]); + const extended = mode == 3 || mode == 7; + let responseLength = 3; + if (extended) + responseLength = 5; + else if (mode == 8) + responseLength = 1; + const response = await this.exec(BfbChannel.HARDWARE, request, { responseLength }); + if (mode == 8) + return undefined; + const low = response.readUInt16LE(1); + return extended ? low + response.readUInt16LE(3) * 0x4000 : low; + } + + async getAudioGainShadow(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_AUDIO_GAIN_SHADOW]); + return response.readUInt16LE(1); + } + + async getNormalModeRxLevel(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_NORMAL_MODE_RX_LEVEL]); + const level = response.readInt16LE(1); + if (level == -1) + throw new BfbRemoteError(0xFF, 'BFB normal-mode RX level is unavailable.'); + return level; + } + + async readAfc(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.AFC, 0x02], { responseLength: 3 }); + return response.readUInt16LE(1); + } + + async getMobileMode(): Promise { + return this.readUInt16Command(BfbChannel.HARDWARE, BfbHardwareOpcode.GET_MOBILE_MODE); + } + + async getDspFirmwareVersion(): Promise { + return this.readUInt16Command(BfbChannel.HARDWARE, BfbHardwareOpcode.GET_DSP_FIRMWARE_VERSION); + } + + async getPowerAsicProject(): Promise { + return this.readUInt8Command(BfbChannel.HARDWARE, BfbHardwareOpcode.GET_POWER_ASIC_PROJECT); + } + + async getHardwareInfo(selector: number): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_HARDWARE_INFO, selector]); + if (response[1] != selector) + throw new Error(`BFB hardware info selector mismatch: ${response[1]} != ${selector}.`); + return response[2]; + } + + async getPhoneModel(): Promise { + return this.readStringCommand(BfbChannel.INFO, BfbInfoOpcode.GET_MODEL_INFORMATION); + } + + async getFirmwareVersion(): Promise { + const response = await this.exec(BfbChannel.INFO, [BfbInfoOpcode.GET_FIRMWARE_VERSION], { minResponseLength: 2 }); + return response[1]; + } + + async getLanguageGroup(): Promise { + return this.readStringCommand(BfbChannel.INFO, BfbInfoOpcode.GET_LANGUAGE_INFORMATION); + } + + async getIMEI(): Promise { + const response = await this.exec(BfbChannel.INFO, [BfbInfoOpcode.GET_IMEI], { minResponseLength: 17 }); + return response.subarray(2, 17).toString('ascii'); + } + + async getFlagStatus(): Promise { + return this.readUInt8Command(BfbChannel.INFO, BfbInfoOpcode.GET_FLAG_STATUS); + } + + async getSecurityMode(): Promise { + const response = await this.exec(BfbChannel.INFO, [BfbInfoOpcode.BOOT_PIN_SETTINGS, 0], { responseLength: 2 }); + const mode = response[1]; + switch (mode) { + case BfbSecurityMode.REPAIR: + case BfbSecurityMode.DEVELOPER: + case BfbSecurityMode.FACTORY: + case BfbSecurityMode.CUSTOMER: + return mode; + default: + throw new Error(`Invalid BFB security mode: ${mode}.`); + } + } + + async getSecurityModeName(): Promise { + const mode = await this.getSecurityMode(); + return BfbSecurityMode[mode] ?? 'UNKNOWN'; + } + + async getBatteryVoltage(): Promise { + return this.readUInt16Command(BfbChannel.INFO, BfbInfoOpcode.GET_BATTERY_VOLTAGE); + } + + async getB35SoftwareVersion(): Promise { + const response = await this.exec(BfbChannel.INFO, [BfbInfoOpcode.GET_SOFTWARE_VERSION], { minResponseLength: 17 }); + return { + date: decodeCString(response.subarray(1, 9)), + time: decodeCString(response.subarray(9, 17)), + }; + } + + async getInformationElementList(id: number): Promise { + const response = await this.exec(BfbChannel.INFO, createInformationElementRequest(0x0F, id), { minResponseLength: 2 }); + const count = response[1]; + if (response.length != 2 + count * 2) { + throw new Error( + `Invalid BFB information element list response length: ${response.length}, expected ${2 + count * 2}.`, + ); + } + return { + count, + elements: Array.from( + { length: count }, + (_value, index) => response.readUInt16LE(2 + index * 2), + ), + }; + } + + async getSingleInformationElement(id: number): Promise { + const response = await this.exec(BfbChannel.INFO, createInformationElementRequest(0, id), { minResponseLength: 2 }); + if (response[1] == 0) + return undefined; + if (response.length < 4) + throw new Error(`Invalid BFB information element response length: ${response.length}.`); + return response.readUInt16LE(2); + } + + async requestBootPinSetting(): Promise { + const response = await this.exec(BfbChannel.INFO, [BfbInfoOpcode.BOOT_PIN_SETTINGS, 0], { minResponseLength: 2 }); + return response[1]; + } + + async sendRemoteControl(command: string, timeout = 5000): Promise { + const payload = encodeRemoteControlCommand(command); + return this.withFrameQueue(BfbChannel.AT, async () => { + await this.sendFrame(BfbChannel.AT, payload); + const deadline = Date.now() + timeout; + const chunks: Buffer[] = []; + while (true) { + try { + const frame = await this.receiveBfbFrame(BfbChannel.AT, 0, deadline); + chunks.push(frame.data); + const response = Buffer.concat(chunks); + if (isTerminalAtResponse(response)) + return response; + } catch (error) { + if (!(error instanceof BfbCommandTimeoutError)) + throw error; + if (chunks.length) + return Buffer.concat(chunks); + throw new BfbUnsupportedCommandError(BfbChannel.AT, BfbAtOpcode.REMOTE_CONTROL); + } + } + }); + } + + async sendSecurityString(value: string, timeout = 5000): Promise { + const payload = encodeSecurityString(value); + return this.exec(BfbChannel.SECURITY, payload, { expectedOpcode: 0, timeout }); + } + + async sendSecurityStringWithDelayValue(value: string, timeout = 5000): Promise { + const payload = encodeSecurityString(value); + return this.withFrameQueue(BfbChannel.SECURITY, async () => { + await this.sendFrame(BfbChannel.SECURITY, payload); + const deadline = Date.now() + timeout; + const first = await this.receiveBfbFrame(BfbChannel.SECURITY, 0, deadline); + const second = await this.receiveBfbFrame(BfbChannel.SECURITY, 0, deadline); + if (first.data.length == 2 && first.data[0] == 0x57) { + return { + response: Buffer.from(second.data), + delay: first.data[1], + }; + } + if (second.data.length == 2 && second.data[0] == 0x57) { + return { + response: Buffer.from(first.data), + delay: second.data[1], + }; + } + throw new Error('BFB security delay response is missing.'); + }); + } + + async sendSecurityKey(key: number): Promise { + const value = `X${key.toString().padStart(8, '0')}`; + if (value.length != 9) + throw new Error('Security key must fit into eight decimal digits.'); + await this.sendSecurityString(value); + } + + async freezeSecurityData(imei: string): Promise { + if (!imei.match(/^\d{15}$/)) + throw new Error('IMEI must contain exactly 15 decimal digits.'); + const response = await this.execEep(Buffer.concat([ + Buffer.from([BfbEepOpcode.FREEZE_SECURITY_DATA]), + Buffer.from(imei, 'ascii'), + ]), { responseLength: 3 }); + return response.readUInt16LE(1); + } + + async simulateChipCard(): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.SIMULATE_CHIP_CARD]); + } + + async pressKey(keyCode: number): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.PRESS_KEY, keyCode]); + } + + async updateDisplay(x: number, y: number, width: number, height: number): Promise { + const request = Buffer.alloc(9); + request.writeUInt8(BfbHardwareOpcode.UPDATE_DISPLAY, 0); + request.writeUInt16LE(x, 1); + request.writeUInt16LE(y, 3); + request.writeUInt16LE(width, 5); + request.writeUInt16LE(height, 7); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async redirectKeypad(callback?: (data: Buffer) => void): Promise { + const previousCallback = this.keypadCallback; + this.keypadCallback = callback; + try { + await this.execAck(BfbChannel.HARDWARE, [callback ? BfbHardwareOpcode.REDIRECT_KEYPAD : BfbHardwareOpcode.RESTORE_KEYPAD]); + } catch (error) { + if (this.mode == BfbTransportMode.BFB) + this.keypadCallback = previousCallback; + throw error; + } + } + + async redirectDisplay(callback?: (event: BfbDisplayEvent) => void, mode?: BfbDisplayRedirectMode): Promise { + const previousCallback = this.displayCallback; + const previousMode = this.displayRedirectMode; + const enabled = callback !== undefined || mode !== undefined; + this.displayCallback = callback; + this.displayRedirectMode = enabled ? mode ?? BfbDisplayRedirectMode.RECT : undefined; + try { + let request: number[]; + if (!enabled) { + request = [BfbHardwareOpcode.RESTORE_DISPLAY]; + } else if (mode === undefined) { + request = [BfbHardwareOpcode.REDIRECT_DISPLAY]; + } else { + request = [BfbHardwareOpcode.REDIRECT_DISPLAY, mode]; + } + const response = await this.exec(BfbChannel.HARDWARE, request); + if (response.length == 1) + await this.exec(BfbChannel.HARDWARE, request); + } catch (error) { + if (this.mode == BfbTransportMode.BFB) { + this.displayCallback = previousCallback; + this.displayRedirectMode = previousMode; + } + throw error; + } + } + + async playTone(frequency: number, duration: number, option = 0): Promise { + const request = Buffer.alloc(6); + request.writeUInt8(BfbHardwareOpcode.PLAY_TONE, 0); + request.writeUInt16LE(frequency, 1); + request.writeUInt16LE(duration, 3); + request.writeUInt8(option, 5); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async stopTone(): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.STOP_TONE]); + } + + async bootDsp(address: number): Promise { + const request = Buffer.alloc(5); + request.writeUInt8(BfbHardwareOpcode.BOOT_DSP, 0); + request.writeUInt32LE(address, 1); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async sendDspCommand(words: number[]): Promise { + if (words.length > 14) + throw new Error('BFB DSP command must contain at most 14 words.'); + const request = Buffer.alloc(3 + words.length * 2); + request.writeUInt8(BfbHardwareOpcode.SEND_DSP_COMMAND, 0); + request.writeUInt16LE(words.length, 1); + for (let index = 0; index < words.length; index++) { + request.writeUInt16LE(words[index], 3 + index * 2); + } + const response = await this.exec(BfbChannel.HARDWARE, request); + return Buffer.from(response.subarray(1)); + } + + async setRxTxChannel(arfcn: number, control: number): Promise { + await this.setRfChannel(BfbHardwareOpcode.SET_RX_TX_CHANNEL, arfcn, control); + } + + async setMonitorChannel(arfcn: number, control: number): Promise { + await this.setRfChannel(BfbHardwareOpcode.SET_MONITOR_CHANNEL, arfcn, control); + } + + async setRampBid(value: number): Promise { + const request = Buffer.alloc(6); + request.writeUInt8(BfbHardwareOpcode.SET_RAMP_BID, 0); + request.writeUInt32LE(value, 1); + request.writeUInt8(1, 5); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async setU35RampBidTable(mode: number, start: number, count: number, bid: number, address: number): Promise { + const request = Buffer.alloc(11); + request.writeUInt8(BfbHardwareOpcode.SET_RAMP_BID, 0); + request.writeUInt8(mode, 1); + request.writeUInt8(start, 2); + request.writeUInt8(count, 3); + request.writeUInt16LE(bid, 4); + request.writeUInt32LE(address, 6); + request.writeUInt8(1, 10); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async setU35RampBidValue(index: number, bid: number): Promise { + const request = Buffer.alloc(6); + request.writeUInt8(BfbHardwareOpcode.SET_RAMP_BID, 0); + request.writeUInt8(2, 1); + request.writeUInt8(index, 2); + request.writeUInt16LE(bid, 3); + request.writeUInt8(1, 5); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async setPowerMode(mode: number): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.SET_POWER_MODE, mode, 0x01]); + } + + async setTxPwm(value: number): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.SET_TX_PWM, value]); + } + + async setMc45PrechargeRampValue(value: number): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.SET_TX_PWM, value, 0]); + } + + async setPaCompensation(value: number): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.SET_PA_COMPENSATION, value]); + } + + async setNfScaling(a: number, b: number): Promise { + const request = Buffer.alloc(5); + request.writeUInt8(BfbHardwareOpcode.SET_NF_SCALING, 0); + request.writeUInt16LE(a, 1); + request.writeUInt16LE(b, 3); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async setEnvironmentTemperature(temperature: number): Promise { + const request = Buffer.alloc(3); + request.writeUInt8(BfbHardwareOpcode.SET_ENVIRONMENT_TEMPERATURE, 0); + request.writeUInt16LE(temperature, 1); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async setNfControl(enabled: boolean): Promise { + await this.execAck(BfbChannel.HARDWARE, [enabled ? BfbHardwareOpcode.ACTIVATE_NF_CONTROL : BfbHardwareOpcode.DEACTIVATE_NF_CONTROL]); + } + + async configureNfControl(a: number, b: number, c: number): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.CONFIGURE_NF_CONTROL, a, b, c]); + } + + async setDisplayContrast(contrast: number): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.SET_DISPLAY_CONTRAST, contrast]); + } + + async controlLight(channel: number, brightness: number, duration = 0): Promise { + const request = Buffer.alloc(6); + request.writeUInt8(BfbHardwareOpcode.CONTROL_LIGHT, 0); + request.writeUInt8(0, 1); + request.writeUInt8(channel, 2); + request.writeUInt8(brightness, 3); + request.writeUInt16LE(duration, 4); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async getSensorAddresses(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GET_SENSOR_ADDRESSES]); + return { + raw: response.readUInt32LE(1), + calibrated: response.readUInt32LE(5), + }; + } + + async getRawSensorData(): Promise { + const addresses = await this.getSensorAddresses(); + return (await this.readMemory(addresses.raw, 14)).buffer; + } + + async getSensorData(): Promise { + const addresses = await this.getSensorAddresses(); + const buffer = (await this.readMemory(addresses.calibrated, 12)).buffer; + const values = Array.from({ length: 6 }, (_value, index) => buffer.readUInt16LE(index * 2)); + return { + voltages: [values[0] * 0.001, values[1] * 0.001, values[2] * 0.001], + temperatures: [values[3] * 0.1 - 273, values[4] * 0.1 - 273, values[5] * 0.1 - 273], + }; + } + + async switchOffDisplay(): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.SWITCH_OFF_DISPLAY]); + } + + async speechOff(): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.SWITCH_SPEECH_OFF]); + } + + async playToneOv(value: number, option: number): Promise { + const request = Buffer.alloc(4); + request.writeUInt8(BfbHardwareOpcode.PLAY_OV_TONE, 0); + request.writeUInt16LE(value, 1); + request.writeUInt8(option, 3); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async setTimingScenario(scenario: number): Promise { + const request = Buffer.alloc(5); + request.writeUInt8(BfbHardwareOpcode.SET_TIMING_SCENARIO, 0); + request.writeUInt32LE(scenario, 1); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async setKeyValueRamp(value: number): Promise { + const request = Buffer.alloc(4); + request.writeUInt8(BfbHardwareOpcode.SET_KEY_VALUE_RAMP, 0); + request.writeUInt16LE(value, 1); + request.writeUInt8(1, 3); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async setVibra(value: number): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.SET_VIBRA, value]); + } + + async setPowerManagement(mode: number, value: number): Promise { + const request = Buffer.alloc(4); + request.writeUInt8(BfbHardwareOpcode.SET_POWER_MANAGEMENT, 0); + request.writeUInt8(mode, 1); + request.writeUInt16LE(value, 2); + await this.execAck(BfbChannel.HARDWARE, request); + } + + async clickSchalkeKey(group: number, key: number, option: number): Promise { + if (!Number.isInteger(group) || group < 0 || group > 3) + throw new Error('Schalke key group must be in range 0..3.'); + if (!Number.isInteger(key) || key < 0 || key > 0x1F) + throw new Error('Schalke key must be in range 0..31.'); + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.CLICK_SCHALKE_KEY, group << 5 | key, option]); + } + + async testLumberg(): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.TEST_LUMBERG], { minResponseLength: 2 }); + return response[1]; + } + + async setCpuSpeed(speed: number): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.SET_CPU_SPEED, speed], { responseLength: 2 }); + return response[1]; + } + + async switchSmiToNormal(): Promise { + await this.sendFrame(BfbChannel.HARDWARE, [BfbHardwareOpcode.SWITCH_SMI_TO_NORMAL]); + } + + async resetGprsBlerCounters(): Promise { + await this.execAck(BfbChannel.HARDWARE, [BfbHardwareOpcode.RESET_GPRS_BLER_COUNTERS]); + } + + async activateBluetoothMapper(): Promise { + await this.setBluetoothMapper(true); + } + + async setBluetoothMapper(enabled: boolean): Promise { + await this.sendFrame(BfbChannel.HARDWARE, [BfbHardwareOpcode.SET_BLUETOOTH_MAPPER, enabled ? 0x01 : 0x02]); + } + + async setRxTxBandChannel(band: number, arfcn: number, control: number, mode: number): Promise { + await this.setRfBandChannel(BfbHardwareOpcode.SET_RX_TX_BAND_CHANNEL, band, arfcn, control, mode); + } + + async setMonitorBandChannel(band: number, arfcn: number, control: number, mode: number): Promise { + await this.setRfBandChannel(BfbHardwareOpcode.SET_MONITOR_BAND_CHANNEL, band, arfcn, control, mode); + } + + async setAfc(value: number): Promise { + const request = Buffer.alloc(4); + request.writeUInt8(BfbHardwareOpcode.AFC, 0); + request.writeUInt8(0, 1); + request.writeUInt16LE(value, 2); + const response = await this.exec(BfbChannel.HARDWARE, request, { responseLength: 2 }); + if (response[1] != 0) + throw new BfbRemoteError(response[1], sprintf('BFB set AFC failed: 0x%02X', response[1])); + } + + async generateDisplayPattern(pattern: number): Promise { + const response = await this.exec(BfbChannel.HARDWARE, [BfbHardwareOpcode.GENERATE_DISPLAY_PATTERN, pattern], { responseLength: 2 }); + if (response[1] != pattern) + throw new Error(`BFB display pattern echo mismatch: ${response[1]} != ${pattern}.`); + } + + async allocateGbsMemory(size: number): Promise { + const request = Buffer.alloc(3); + request.writeUInt8(BfbGbsOpcode.ALLOCATE, 0); + request.writeUInt16LE(size, 1); + const response = await this.exec(BfbChannel.GBS, request); + return response.readUInt32LE(1); + } + + async freeGbsMemory(address: number): Promise { + const request = Buffer.alloc(5); + request.writeUInt8(BfbGbsOpcode.FREE, 0); + request.writeUInt32LE(address, 1); + await this.execAck(BfbChannel.GBS, request); + } + + async powerOff(): Promise { + await this.execSessionEndingCommand(BfbChannel.INFO, [BfbInfoOpcode.POWER_OFF]); + } + + async enterSoftwareUpdate(baudRate: number): Promise { + const request = Buffer.alloc(6); + request.writeUInt8(BfbInfoOpcode.ENTER_SOFTWARE_UPDATE, 0); + request.writeUInt8(0, 1); + request.writeUInt32LE(baudRate, 2); + await this.sendFrame(BfbChannel.INFO, request); + await this.disconnect(); + } + + async sendServiceStream(data: Buffer): Promise { + if (!data.length) + await this.sendFrame(BfbChannel.SERVICE_STREAM, data); + for (let offset = 0; offset < data.length; offset += BFB_MAX_PAYLOAD_SIZE) + await this.sendFrame(BfbChannel.SERVICE_STREAM, data.subarray(offset, offset + BFB_MAX_PAYLOAD_SIZE)); + } + + async sendServiceStreamTerminator(terminator: Buffer): Promise { + if (terminator.length != 2) + throw new Error('BFB service-stream terminator must contain exactly two bytes.'); + await this.sendFrame(BfbChannel.SERVICE_STREAM, terminator); + } + + async getEepBlockInfo(blockId: number, storage: BfbEepStorage = 'auto'): Promise { + const resolvedStorage = resolveEepStorage(blockId, storage); + const opcode = resolvedStorage == 'eefull' ? BfbEepOpcode.GET_EEFULL_BLOCK_INFO : BfbEepOpcode.GET_EELITE_BLOCK_INFO; + const request = Buffer.alloc(3); + request.writeUInt8(opcode, 0); + request.writeUInt16LE(blockId, 1); + const response = await this.execEep(request, { responseLength: 4 }); + return { + size: response.readUInt16LE(1), + version: response[3], + storage: resolvedStorage, + }; + } + + async createEepBlock( + blockId: number, + size: number, + version: number, + storage: Exclude, + ): Promise { + const request = Buffer.alloc(6); + request.writeUInt8(storage == 'eefull' ? BfbEepOpcode.CREATE_EEFULL_BLOCK : BfbEepOpcode.CREATE_EELITE_BLOCK, 0); + request.writeUInt16LE(blockId, 1); + request.writeUInt16LE(size, 3); + request.writeUInt8(version, 5); + await this.execEepAck(request, { + allowWait: true, + refreshTimeoutOnWait: true, + }); + } + + async writeEepBlockChunk( + blockId: number, + offset: number, + data: Buffer, + storage: Exclude, + ): Promise { + if (data.length > BFB_EEP_MAX_WRITE_CHUNK) { + throw new Error( + `BFB EEPROM write chunk is too large: ${data.length} > ${BFB_EEP_MAX_WRITE_CHUNK}.`, + ); + } + const request = Buffer.alloc(5 + data.length); + request.writeUInt8(storage == 'eefull' ? BfbEepOpcode.WRITE_EEFULL_BLOCK : BfbEepOpcode.WRITE_EELITE_BLOCK, 0); + request.writeUInt16LE(blockId, 1); + request.writeUInt16LE(offset, 3); + data.copy(request, 5); + await this.execEepAck(request, { + allowWait: true, + refreshTimeoutOnWait: true, + }); + } + + async finishEepBlock(blockId: number, storage: Exclude): Promise { + const request = Buffer.alloc(3); + request.writeUInt8(storage == 'eefull' ? BfbEepOpcode.FINISH_EEFULL_BLOCK : BfbEepOpcode.FINISH_EELITE_BLOCK, 0); + request.writeUInt16LE(blockId, 1); + await this.execEepAck(request); + } + + async readEepBlockChunk( + blockId: number, + offset: number, + length: number, + storage: Exclude, + ): Promise { + if (!Number.isInteger(length) || length < 0 || length > BFB_EEP_READ_CHUNK) + throw new Error(`BFB EEPROM read chunk length must be in range 0..${BFB_EEP_READ_CHUNK}.`); + const request = Buffer.alloc(7); + request.writeUInt8(storage == 'eefull' ? BfbEepOpcode.READ_EEFULL_BLOCK : BfbEepOpcode.READ_EELITE_BLOCK, 0); + request.writeUInt16LE(blockId, 1); + request.writeUInt16LE(offset, 3); + request.writeUInt16LE(length, 5); + const response = await this.execEep(request, { responseLength: length + 1 }); + return Buffer.from(response.subarray(1)); + } + + async readEepBlock(blockId: number, offset = 0, length?: number, storage: BfbEepStorage = 'auto'): Promise { + const info = await this.getEepBlockInfo(blockId, storage); + if (!Number.isInteger(offset) || offset < 0 || offset > info.size) + throw new Error(`Invalid EEPROM block offset: ${offset}.`); + length ??= info.size - offset; + if (!Number.isInteger(length) || length < 0 || offset + length > info.size) + throw new Error(`Invalid EEPROM block range: offset=${offset}, length=${length}, size=${info.size}.`); + + const result = Buffer.alloc(length); + for (let cursor = 0; cursor < length; cursor += BFB_EEP_READ_CHUNK) { + const chunkSize = Math.min(length - cursor, BFB_EEP_READ_CHUNK); + const chunk = await this.readEepBlockChunk(blockId, offset + cursor, chunkSize, info.storage); + chunk.copy(result, cursor); + } + return result; + } + + async writeEepBlock(blockId: number, data: Buffer, version = 0, storage: BfbEepStorage = 'auto'): Promise { + const resolvedStorage = resolveEepStorage(blockId, storage); + await this.createEepBlock(blockId, data.length, version, resolvedStorage); + + if (!data.length) + await this.writeEepBlockChunk(blockId, 0, data, resolvedStorage); + for (let offset = 0; offset < data.length; offset += BFB_EEP_WRITE_CHUNK) + await this.writeEepBlockChunk(blockId, offset, data.subarray(offset, offset + BFB_EEP_WRITE_CHUNK), resolvedStorage); + + await this.finishEepBlock(blockId, resolvedStorage); + } + + async writeEefullBlockRangeChunk(blockId: number, offset: number, data: Buffer): Promise { + if (data.length > BFB_EEP_MAX_WRITE_CHUNK) { + throw new Error( + `BFB EEFULL range-write chunk is too large: ${data.length} > ${BFB_EEP_MAX_WRITE_CHUNK}.`, + ); + } + const request = Buffer.alloc(5 + data.length); + request.writeUInt8(BfbEepOpcode.WRITE_EEFULL_RANGE, 0); + request.writeUInt16LE(blockId, 1); + request.writeUInt16LE(offset, 3); + data.copy(request, 5); + await this.execEepAck(request, { + allowWait: true, + refreshTimeoutOnWait: true, + }); + } + + async writeEepBlockRange(blockId: number, offset: number, data: Buffer): Promise { + + const info = await this.getEepBlockInfo(blockId, 'eefull'); + if (offset + data.length > info.size) + throw new Error(`Invalid EEPROM block range: offset=${offset}, length=${data.length}, size=${info.size}.`); + + if (!data.length) + await this.writeEefullBlockRangeChunk(blockId, offset, data); + for (let cursor = 0; cursor < data.length; cursor += BFB_EEP_WRITE_CHUNK) + await this.writeEefullBlockRangeChunk(blockId, offset + cursor, data.subarray(cursor, cursor + BFB_EEP_WRITE_CHUNK)); + } + + async deleteEepBlock(blockId: number, storage: BfbEepStorage = 'auto'): Promise { + const resolvedStorage = resolveEepStorage(blockId, storage); + const request = Buffer.alloc(3); + request.writeUInt8(resolvedStorage == 'eefull' ? BfbEepOpcode.DELETE_EEFULL_BLOCK : BfbEepOpcode.DELETE_EELITE_BLOCK, 0); + request.writeUInt16LE(blockId, 1); + await this.execEepAck(request); + } + + async deleteEepInstance(instance: number): Promise { + const response = await this.execEep(Buffer.from([BfbEepOpcode.DELETE_INSTANCE, instance]), { responseLength: 2 }); + if (response[1] != instance) + throw new Error(`BFB EEPROM instance mismatch: ${response[1]} != ${instance}.`); + } + + async getEepMaxBlockId(storage: Exclude): Promise { + const opcode = storage == 'eefull' ? BfbEepOpcode.GET_EEFULL_MAX_BLOCK_ID : BfbEepOpcode.GET_EELITE_MAX_BLOCK_ID; + const response = await this.execEep(Buffer.from([opcode]), { responseLength: 3 }); + return response.readUInt16LE(1); + } + + async getEepSpaceInfo(storage: Exclude): Promise { + const opcode = storage == 'eefull' ? BfbEepOpcode.GET_EEFULL_SPACE_INFO : BfbEepOpcode.GET_EELITE_SPACE_INFO; + const response = await this.execEep(Buffer.from([opcode]), { responseLength: 13 }); + return { + freeBlocks: response.readUInt32LE(1), + freeAddressSpace: response.readUInt32LE(5), + freeDataSpace: response.readUInt32LE(9), + }; + } + + async garbageCollectEefull(): Promise { + await this.execEepAck(Buffer.from([BfbEepOpcode.GARBAGE_COLLECT_EEFULL]), { + timeout: 6000, + allowWait: true, + refreshTimeoutOnWait: true, + }); + } + + private async execSessionEndingCommand(channel: number, payload: Buffer | number[]): Promise { + const data = Buffer.isBuffer(payload) ? payload : Buffer.from(payload); + await this.withFrameQueue(channel, async () => { + await this.sendFrame(channel, data); + try { + await this.receiveBfbFrame(channel, data[0] ?? 0, Date.now() + 1000); + } catch (error) { + if (!(error instanceof BfbCommandTimeoutError) && this.mode == BfbTransportMode.BFB) + throw error; + } finally { + this.handleSerialClose(); + } + }); + } + + private async receiveCommandData( + channel: number, + opcode: number, + timeout: number, + ): Promise { + const frame = await this.receiveBfbFrame(channel, opcode, Date.now() + timeout); + if (frame.data.length == 1) + throw new BfbUnsupportedCommandError(channel, opcode); + return Buffer.from(frame.data.subarray(1)); + } + + private async setRfChannel(opcode: number, arfcn: number, control: number): Promise { + const request = Buffer.alloc(5); + request.writeUInt8(opcode, 0); + request.writeUInt16LE(arfcn, 1); + request.writeUInt8(control, 3); + request.writeUInt8(1, 4); + await this.execAck(BfbChannel.HARDWARE, request); + } + + private async setRfBandChannel( + opcode: number, + band: number, + arfcn: number, + control: number, + mode: number, + ): Promise { + const request = Buffer.alloc(7); + request.writeUInt8(opcode, 0); + request.writeUInt8(band, 1); + request.writeUInt16LE(arfcn, 2); + request.writeUInt8(control, 4); + request.writeUInt8(mode, 5); + request.writeUInt8(1, 6); + await this.execAck(BfbChannel.HARDWARE, request); + } + + private async execEep(request: Buffer, options: BfbEepExecOptions = {}): Promise { + const opcode = request[0]; + const validOptions = { + timeout: 5000, + allowWait: false, + refreshTimeoutOnWait: false, + ...options, + }; + return this.withFrameQueue(BfbChannel.EEPROM, async () => { + await this.sendFrame(BfbChannel.EEPROM, appendBfbPayloadXor(request)); + let deadline = Date.now() + validOptions.timeout; + while (true) { + const frame = await this.receiveBfbFrame(BfbChannel.EEPROM, 0, deadline); + if (!checkBfbPayloadXor(frame.data)) + throw new Error('Invalid BFB EEPROM payload checksum.'); + + const response = frame.data.subarray(0, frame.data.length - 1); + if (validOptions.allowWait && response.length == 1 && response[0] == 0x50) { + if (validOptions.refreshTimeoutOnWait) + deadline = Date.now() + validOptions.timeout; + continue; + } + if (response[0] != opcode) { + const status = response[0] ?? 0; + throw new BfbRemoteError(status, BFB_EEP_STATUS[status]); + } + if (validOptions.responseLength !== undefined && validOptions.responseLength > 1 && response.length == 1) + throw new BfbUnsupportedCommandError(BfbChannel.EEPROM, opcode); + if (validOptions.responseLength !== undefined && response.length != validOptions.responseLength) + throw new Error(`Invalid BFB EEPROM response length: ${response.length}, expected ${validOptions.responseLength}.`); + return response; + } + }); + } + + private async execEepAck( + request: Buffer, + options: BfbEepExecOptions = {}, + ): Promise { + await this.execEep(request, { ...options, responseLength: 1 }); + } + + private async execStatusZero( + channel: number, + request: Buffer, + exactResponseLength = true, + ): Promise { + const response = await this.exec(channel, request, exactResponseLength ? { responseLength: 2 } : { minResponseLength: 2 }); + if (response[1] != 0) { + const command = getBfbOpcodeName(channel, request[0]) ?? 'command'; + throw new BfbRemoteError(response[1], sprintf('BFB %s failed: 0x%02X', command, response[1])); + } + } + + private async execAck(channel: number, request: Buffer | number[]): Promise { + await this.exec(channel, request); + } + + private async readUInt8Command(channel: number, opcode: number): Promise { + const response = await this.exec(channel, [opcode], { responseLength: 2 }); + return response[1]; + } + + private async readUInt16Command(channel: number, opcode: number): Promise { + const response = await this.exec(channel, [opcode], { responseLength: 3 }); + return response.readUInt16LE(1); + } + + private async readStringCommand(channel: number, opcode: number): Promise { + const response = await this.exec(channel, [opcode], { minResponseLength: 2 }); + const data = response.subarray(1); + const zero = data.indexOf(0); + return data.subarray(0, zero < 0 ? data.length : zero).toString('ascii'); + } + + private async readCommandData(channel: number, request: Buffer | number[]): Promise { + const response = await this.exec(channel, request, { minResponseLength: 2 }); + return Buffer.from(response.subarray(1)); + } +} + +export function encodeBfbFrame(channel: number, payload: Buffer | number[]): Buffer { + if (!Number.isInteger(channel) || channel < 0 || channel > 0xFF) + throw new Error(`Invalid BFB channel: ${channel}`); + + const data = Buffer.isBuffer(payload) ? payload : Buffer.from(payload); + if (data.length > BFB_MAX_PAYLOAD_SIZE) + throw new Error(`BFB payload length must be in range 0..${BFB_MAX_PAYLOAD_SIZE}.`); + + return Buffer.concat([ + Buffer.from([channel, data.length, channel ^ data.length]), + data, + ]); +} + +export function appendBfbPayloadXor(payload: Buffer | number[]): Buffer { + const data = Buffer.isBuffer(payload) ? payload : Buffer.from(payload); + let checksum = 0; + for (const byte of data) + checksum ^= byte; + return Buffer.concat([data, Buffer.from([checksum])]); +} + +export function checkBfbPayloadXor(payload: Buffer): boolean { + if (!payload.length) + return false; + let checksum = 0; + for (const byte of payload) + checksum ^= byte; + return checksum == 0; +} + +function getBfbOpcodeName(channel: number, opcode: number): string | undefined { + switch (channel) { + case BfbChannel.CONFIGURATION: return BfbConfigurationOpcode[opcode]; + case BfbChannel.CORE: return BfbCoreOpcode[opcode]; + case BfbChannel.HARDWARE: return BfbHardwareOpcode[opcode]; + case BfbChannel.AT: return BfbAtOpcode[opcode]; + case BfbChannel.GBS: return BfbGbsOpcode[opcode]; + case BfbChannel.INFO: return BfbInfoOpcode[opcode]; + case BfbChannel.EEPROM: return BfbEepOpcode[opcode]; + } +} + +function resolveEepStorage(blockId: number, storage: BfbEepStorage): Exclude { + if (storage == 'auto') + return blockId >= 5000 ? 'eefull' : 'eelite'; + return storage; +} + +function createInformationElementRequest(mode: number, id: number): Buffer { + const request = Buffer.alloc(4); + request.writeUInt8(BfbInfoOpcode.INFORMATION_ELEMENT, 0); + request.writeUInt8(mode, 1); + request.writeUInt16LE(id, 2); + return request; +} + +function encodeSecurityString(value: string): Buffer { + const payload = Buffer.from(value, 'ascii'); + if (payload.includes(0)) + throw new Error('BFB security string must not contain a NUL byte.'); + if (payload.length > BFB_MAX_PAYLOAD_SIZE - 1) + throw new Error(`BFB security string is too long: ${payload.length} > ${BFB_MAX_PAYLOAD_SIZE - 1}.`); + return payload; +} + +function encodeRemoteControlCommand(command: string): Buffer { + const data = Buffer.from(command, 'ascii'); + if (data.includes(0)) + throw new Error('BFB remote-control command must not contain a NUL byte.'); + if (data.length > BFB_MAX_PAYLOAD_SIZE - 2) { + throw new Error( + `BFB remote-control command is too long: ${data.length} > ${BFB_MAX_PAYLOAD_SIZE - 2}.`, + ); + } + return Buffer.concat([Buffer.from([BfbAtOpcode.REMOTE_CONTROL]), data, Buffer.from([0])]); +} + +function isTerminalAtResponse(response: Buffer): boolean { + return /\r\n(OK|ERROR|\+CMS ERROR|\+CME ERROR)[^\r\n]*\r\n$/s.test(response.toString('ascii')); +} + +function computeBfbBaudCrc(payload: Buffer): Buffer { + const packed = Buffer.alloc(Math.ceil(payload.length / 2)); + let mergePackedByte = payload.length % 2 != 0; + let packedOffset = 0; + for (const byte of payload) { + if (mergePackedByte) { + packed[packedOffset] |= byte; + packedOffset++; + } else { + packed[packedOffset] = byte << 4; + } + mergePackedByte = !mergePackedByte; + } + + const crc = Buffer.alloc(3); + for (let index = 0; index < crc.length; index++) + crc[index] = ~packed[index]; + + for (let index = crc.length; index < packed.length; index++) { + const tableValue = getBfbBaudCrcTableValue(crc[0]); + crc[0] = (tableValue >> 16) ^ crc[1]; + crc[1] = (tableValue >> 8) ^ crc[2]; + crc[2] = tableValue ^ packed[index]; + } + return crc; +} + +function getBfbBaudCrcTableValue(index: number): number { + const table = [ + 0x76A7D6, + 0x5745F6, + 0x1581B7, + 0x910934, + 0x221368, + 0x4426D0, + 0x3347FB, + 0xDD85AD, + ]; + let value = 0; + for (let bit = 0; bit < table.length; bit++) { + if (index & (1 << bit)) + value ^= table[bit]; + } + return value; +} diff --git a/src/index.ts b/src/index.ts index 88c0b2f..ea2c65a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,6 @@ export * from './AtChannel.js'; export * from './BFC.js'; +export * from './BFB.js'; export * from './CGSN.js'; export * from './BSL.js'; export * from './DWD.js';