Add util funciton to format as hex

This commit is contained in:
David Lechner
2020-05-26 21:20:08 -05:00
committed by David Lechner
parent 7a7eba407f
commit 6713afe198
3 changed files with 14 additions and 12 deletions
+3 -9
View File
@@ -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;
+2 -3
View File
@@ -84,6 +84,7 @@ import {
parseInitLoaderResponse,
parseProgramFlashResponse,
} from '../protocols/bootloader';
import { hex } from '../utils';
import { fmod, sumComplement32 } from '../utils/math';
const firmwareZipMap = new Map<HubType, string>([
@@ -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,
);
}
+9
View File
@@ -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')}`;
}