diff --git a/src/protocols/bootloader.ts b/src/protocols/bootloader.ts index 700f4ea9..413dc613 100644 --- a/src/protocols/bootloader.ts +++ b/src/protocols/bootloader.ts @@ -3,7 +3,7 @@ // Ref: https://lego.github.io/lego-ble-wireless-protocol-docs/index.html#lego-hub-boot-loader-service -import { assert } from '../utils'; +import { assert, hex } from '../utils'; /** * LEGO Powered Up Bootloader Service UUID. @@ -207,19 +207,13 @@ export function parseErrorResponse(msg: DataView): Command { // Error responses are ordered differently compared to command responses. if (msg.getUint8(2) !== ErrorBytecode) { throw new ProtocolError( - `expecting error bytecode 0x05 but got 0x${msg - .getUint8(2) - .toString(16) - .padStart(2, '0')}`, + `expecting error bytecode 0x05 but got ${hex(msg.getUint8(2), 2)}`, msg, ); } if (msg.getUint8(4) !== ErrorCode.UnknownCommand) { // "command not recognized" is only possible error code - throw new ProtocolError( - `unknown error code: 0x${msg.getUint8(4).toString(16).padStart(2, '0')}`, - msg, - ); + throw new ProtocolError(`unknown error code: ${hex(msg.getUint8(4), 2)}`, msg); } const command = msg.getUint8(3); return command; diff --git a/src/sagas/bootloader.ts b/src/sagas/bootloader.ts index a9cbd1cc..a6861e47 100644 --- a/src/sagas/bootloader.ts +++ b/src/sagas/bootloader.ts @@ -84,6 +84,7 @@ import { parseInitLoaderResponse, parseProgramFlashResponse, } from '../protocols/bootloader'; +import { hex } from '../utils'; import { fmod, sumComplement32 } from '../utils/math'; const firmwareZipMap = new Map([ @@ -187,9 +188,7 @@ function* decodeResponse(action: BootloaderConnectionDidReceiveAction): Generato break; default: throw new ProtocolError( - `unknown bootloader response type: 0x${responseType - .toString(16) - .padStart(2, '0')}`, + `unknown bootloader response type: ${hex(responseType, 2)}`, action.data, ); } diff --git a/src/utils/index.ts b/src/utils/index.ts index ce6f40ab..7c336e75 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -13,3 +13,12 @@ export function assert(condition: boolean, message: string): void { throw Error(message); } } + +/** + * Formats a number as hex (0x00...) + * @param n The number to format + * @param pad The total number of digits padded with leading 0s + */ +export function hex(n: number, pad: number): string { + return `0x${n.toString(16).padStart(pad, '0')}`; +}