Skip to content

Commit

Permalink
refactor: use Uint8Array in more locations
Browse files Browse the repository at this point in the history
  • Loading branch information
AlCalzone committed Oct 29, 2024
1 parent a7c122b commit 2808040
Show file tree
Hide file tree
Showing 21 changed files with 81 additions and 71 deletions.
2 changes: 1 addition & 1 deletion packages/cc/src/cc/EntryControlCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ export class EntryControlCCNotification extends EntryControlCC {
public readonly sequenceNumber: number;
public readonly dataType: EntryControlDataTypes;
public readonly eventType: EntryControlEventTypes;
public readonly eventData?: Bytes | string;
public readonly eventData?: Uint8Array | string;

public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {
const message: MessageRecord = {
Expand Down
2 changes: 1 addition & 1 deletion packages/cc/src/cc/IndicatorCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1338,7 +1338,7 @@ export class IndicatorCCSupportedReport extends IndicatorCC {
public serialize(ctx: CCEncodingContext): Bytes {
const bitmask = this.supportedProperties.length > 0
? encodeBitMask(this.supportedProperties, undefined, 0)
: Bytes.from([]);
: new Bytes();
this.payload = Bytes.concat([
Bytes.from([
this.indicatorId,
Expand Down
8 changes: 4 additions & 4 deletions packages/cc/src/cc/ManufacturerProprietaryCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,28 +65,28 @@ export class ManufacturerProprietaryCCAPI extends CCAPI {
@validateArgs()
public async sendData(
manufacturerId: number,
data?: Bytes,
data?: Uint8Array,
): Promise<void> {
const cc = new ManufacturerProprietaryCC({
nodeId: this.endpoint.nodeId,
endpointIndex: this.endpoint.index,
manufacturerId,
});
cc.payload = data ?? new Bytes();
cc.payload = data ? Bytes.view(data) : new Bytes();

await this.host.sendCommand(cc, this.commandOptions);
}

@validateArgs()
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
public async sendAndReceiveData(manufacturerId: number, data?: Bytes) {
public async sendAndReceiveData(manufacturerId: number, data?: Uint8Array) {
const cc = new ManufacturerProprietaryCC({
nodeId: this.endpoint.nodeId,
endpointIndex: this.endpoint.index,
manufacturerId,
unspecifiedExpectsResponse: true,
});
cc.payload = data ?? new Bytes();
cc.payload = data ? Bytes.view(data) : new Bytes();

const response = await this.host.sendCommand<
ManufacturerProprietaryCC
Expand Down
4 changes: 2 additions & 2 deletions packages/cc/src/cc/MeterCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ function getValueLabel(
return ret;
}

function parseMeterValueAndInfo(data: Bytes, offset: number): {
function parseMeterValueAndInfo(data: Uint8Array, offset: number): {
type: number;
rateType: RateType;
scale1: number;
Expand Down Expand Up @@ -260,7 +260,7 @@ function encodeMeterValueAndInfo(

function parseScale(
scale1: number,
data: Bytes,
data: Uint8Array,
scale2Offset: number,
): number {
if (scale1 === 7) {
Expand Down
2 changes: 1 addition & 1 deletion packages/cc/src/cc/MultiChannelAssociationCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ function serializeMultiChannelAssociationDestination(
return payload;
}

function deserializeMultiChannelAssociationDestination(data: Bytes): {
function deserializeMultiChannelAssociationDestination(data: Uint8Array): {
nodeIds: number[];
endpoints: EndpointAddress[];
} {
Expand Down
2 changes: 1 addition & 1 deletion packages/cc/src/cc/NotificationCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1034,7 +1034,7 @@ export class NotificationCCReport extends NotificationCC {

const containsSeqNum = !!(raw.payload[6] & 0b1000_0000);
const numEventParams = raw.payload[6] & 0b11111;
let eventParameters: Bytes | undefined;
let eventParameters: Uint8Array | undefined;
if (numEventParams > 0) {
validatePayload(raw.payload.length >= 7 + numEventParams);
eventParameters = raw.payload.subarray(7, 7 + numEventParams);
Expand Down
2 changes: 1 addition & 1 deletion packages/cc/src/cc/Security2CC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1842,7 +1842,7 @@ export class Security2CCMessageEncapsulation extends Security2CC {
),
]);
const serializedCC = this.encapsulated?.serialize(ctx)
?? Bytes.from([]);
?? new Bytes();
const plaintextPayload = Bytes.concat([
...encryptedExtensions.map((e, index) =>
e.serialize(index < encryptedExtensions.length - 1)
Expand Down
14 changes: 7 additions & 7 deletions packages/cc/src/cc/ThermostatModeCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,13 @@ export class ThermostatModeCCAPI extends CCAPI {
): Promise<SupervisionResult | undefined>;
public async set(
mode: (typeof ThermostatMode)["Manufacturer specific"],
manufacturerData: Bytes | string,
manufacturerData: Uint8Array | string,
): Promise<SupervisionResult | undefined>;

@validateArgs({ strictEnums: true })
public async set(
mode: ThermostatMode,
manufacturerData?: Bytes | string,
manufacturerData?: Uint8Array | string,
): Promise<SupervisionResult | undefined> {
this.assertSupportsCommand(
ThermostatModeCommand,
Expand Down Expand Up @@ -318,7 +318,7 @@ export type ThermostatModeCCSetOptions =
}
| {
mode: (typeof ThermostatMode)["Manufacturer specific"];
manufacturerData: Bytes;
manufacturerData: Uint8Array;
};

@CCCommand(ThermostatModeCommand.Set)
Expand Down Expand Up @@ -361,14 +361,14 @@ export class ThermostatModeCCSet extends ThermostatModeCC {
}

public mode: ThermostatMode;
public manufacturerData?: Bytes;
public manufacturerData?: Uint8Array;

public serialize(ctx: CCEncodingContext): Bytes {
const manufacturerData =
this.mode === ThermostatMode["Manufacturer specific"]
&& this.manufacturerData
? this.manufacturerData
: Bytes.from([]);
: new Uint8Array();
const manufacturerDataLength = manufacturerData.length;
this.payload = Bytes.concat([
Bytes.from([
Expand Down Expand Up @@ -404,7 +404,7 @@ export type ThermostatModeCCReportOptions =
}
| {
mode: (typeof ThermostatMode)["Manufacturer specific"];
manufacturerData?: Bytes;
manufacturerData?: Uint8Array;
};

@CCCommand(ThermostatModeCommand.Report)
Expand Down Expand Up @@ -486,7 +486,7 @@ export class ThermostatModeCCReport extends ThermostatModeCC {
public readonly mode: ThermostatMode;

@ccValue(ThermostatModeCCValues.manufacturerData)
public readonly manufacturerData: Bytes | undefined;
public readonly manufacturerData: Uint8Array | undefined;

public serialize(ctx: CCEncodingContext): Bytes {
const manufacturerDataLength =
Expand Down
7 changes: 5 additions & 2 deletions packages/cc/src/cc/TransportServiceCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,17 @@ export class TransportServiceCCFirstSegment extends TransportServiceCC {

// If there is a header extension, read it
const hasHeaderExtension = !!(raw.payload[2] & 0b1000);
let headerExtension: Bytes | undefined;
let headerExtension: Uint8Array | undefined;

if (hasHeaderExtension) {
const extLength = raw.payload[3];
headerExtension = raw.payload.subarray(4, 4 + extLength);
payloadOffset += 1 + extLength;
}
const partialDatagram: Bytes = raw.payload.subarray(payloadOffset, -2);
const partialDatagram: Uint8Array = raw.payload.subarray(
payloadOffset,
-2,
);

// A node supporting the Transport Service Command Class, version 2
// MUST NOT send Transport Service segments with the Payload field longer than 39 bytes.
Expand Down
2 changes: 1 addition & 1 deletion packages/cc/src/cc/VersionCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ export const VersionCCValues = Object.freeze({
}),
});

function parseVersion(buffer: Bytes): string {
function parseVersion(buffer: Uint8Array): string {
if (buffer[0] === 0 && buffer[1] === 0 && buffer[2] === 0) return "unused";
return `${buffer[0]}.${buffer[1]}.${buffer[2]}`;
}
Expand Down
6 changes: 3 additions & 3 deletions packages/cc/src/cc/ZWaveProtocolCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1396,7 +1396,7 @@ export class ZWaveProtocolCCAssignSUCReturnRoutePriority

// @publicAPI
export interface ZWaveProtocolCCSmartStartIncludedNodeInformationOptions {
nwiHomeId: Bytes;
nwiHomeId: Uint8Array;
}

@CCCommand(ZWaveProtocolCommand.SmartStartIncludedNodeInformation)
Expand All @@ -1423,15 +1423,15 @@ export class ZWaveProtocolCCSmartStartIncludedNodeInformation
ctx: CCParsingContext,
): ZWaveProtocolCCSmartStartIncludedNodeInformation {
validatePayload(raw.payload.length >= 4);
const nwiHomeId: Bytes = raw.payload.subarray(0, 4);
const nwiHomeId = raw.payload.subarray(0, 4);

return new ZWaveProtocolCCSmartStartIncludedNodeInformation({
nodeId: ctx.sourceNodeId,
nwiHomeId,
});
}

public nwiHomeId: Bytes;
public nwiHomeId: Uint8Array;

public serialize(ctx: CCEncodingContext): Bytes {
this.payload = Bytes.from(this.nwiHomeId);
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/capabilities/NodeInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export interface ApplicationNodeInformation {
}

export function parseApplicationNodeInformation(
nif: Bytes,
nif: Uint8Array,
): ApplicationNodeInformation {
validatePayload(nif.length >= 2);
return {
Expand All @@ -38,7 +38,7 @@ export interface NodeUpdatePayload extends ApplicationNodeInformation {
}

export function parseNodeUpdatePayload(
nif: Bytes,
nif: Uint8Array,
nodeIdType: NodeIDType = NodeIDType.Short,
): NodeUpdatePayload {
let offset = 0;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/security/crypto.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ test("computeMAC() -> should work correctly (part 2)", (t) => {
test("computeCMAC() -> should work correctly (part 1)", (t) => {
// Test vector taken from https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/AES_CMAC.pdf
const key = Bytes.from("2B7E151628AED2A6ABF7158809CF4F3C", "hex");
const plaintext = Bytes.from([]);
const plaintext = new Bytes();
const expected = Bytes.from("BB1D6929E95937287FA37D129B756746", "hex");

t.deepEqual(computeCMAC(plaintext, key), expected);
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/util/crc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { CRC16_CCITT } from "./crc";
// Test cases based on http://srecord.sourceforge.net/crc16-ccitt.html

test("CRC16_CCITT() works correctly -> input: (empty)", (t) => {
t.is(CRC16_CCITT(Bytes.from([])), 0x1d0f);
t.is(CRC16_CCITT(new Bytes()), 0x1d0f);
});

test("CRC16_CCITT() works correctly -> input: A", (t) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/util/firmware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ function extractFirmwareHEX(dataHEX: Uint8Array | string): Firmware {
}
const memMap: Map<number, Uint8Array> = MemoryMap.fromHex(dataHEX);
// A memory map can be sparse - we'll have to fill the gaps with 0xFF
let data: Bytes = Bytes.from([]);
let data: Bytes = new Bytes();
for (const [offset, chunk] of memMap.entries()) {
data = Bytes.concat([
data,
Expand Down
4 changes: 2 additions & 2 deletions packages/nvmedit/src/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ export function nvmObjectsToJSON(
const controller: NVMJSONController = {
protocolVersion,
applicationVersion,
homeId: `0x${controllerInfoFile.homeId.toString("hex")}`,
homeId: buffer2hex(controllerInfoFile.homeId),
...pick(controllerInfoFile, controllerProps),
...pick(applicationTypeFile, [
"isListening",
Expand Down Expand Up @@ -906,7 +906,7 @@ export async function nvmToJSON(
const controller: NVMJSONController = {
protocolVersion,
applicationVersion,
homeId: `0x${controllerInfoFile.homeId.toString("hex")}`,
homeId: buffer2hex(controllerInfoFile.homeId),
...pick(controllerInfoFile, [
"nodeId",
"lastNodeId",
Expand Down
13 changes: 7 additions & 6 deletions packages/nvmedit/src/lib/NVM3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -773,10 +773,11 @@ async function readPageHeader(
}

function tryGetVersionAndEraseCount(
header: Bytes,
header: Uint8Array,
): { version: number; eraseCount: number } {
const version = header.readUInt16LE(0);
const magic = header.readUInt16LE(2);
const buffer = Bytes.view(header);
const version = buffer.readUInt16LE(0);
const magic = buffer.readUInt16LE(2);
if (magic !== NVM3_PAGE_MAGIC) {
throw new ZWaveError(
"Not a valid NVM3 page!",
Expand All @@ -791,12 +792,12 @@ function tryGetVersionAndEraseCount(
}

// The erase counter is saved twice, once normally, once inverted
let eraseCount = header.readUInt32LE(4);
let eraseCount = buffer.readUInt32LE(4);
const eraseCountCode = eraseCount >>> NVM3_PAGE_COUNTER_SIZE;
eraseCount &= NVM3_PAGE_COUNTER_MASK;
validateBergerCode(eraseCount, eraseCountCode, NVM3_PAGE_COUNTER_SIZE);

let eraseCountInv = header.readUInt32LE(8);
let eraseCountInv = buffer.readUInt32LE(8);
const eraseCountInvCode = eraseCountInv >>> NVM3_PAGE_COUNTER_SIZE;
eraseCountInv &= NVM3_PAGE_COUNTER_MASK;
validateBergerCode(
Expand Down Expand Up @@ -826,7 +827,7 @@ async function isValidPageHeaderAtOffset(
const { buffer } = await io.read(offset, NVM3_PAGE_HEADER_SIZE);

try {
tryGetVersionAndEraseCount(Bytes.view(buffer));
tryGetVersionAndEraseCount(buffer);
return true;
} catch {
return false;
Expand Down
4 changes: 2 additions & 2 deletions packages/nvmedit/src/lib/NVM500.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,12 @@ export class NVM500 implements NVM<NVMEntryName, NVMData[]> {
if (entry.type === NVMEntryType.NVMDescriptor) {
const entryData = await this.readRawEntry(resolvedEntry);
// NVMDescriptor is always a single entry
nvmDescriptor = parseNVMDescriptor(Bytes.view(entryData[0]));
nvmDescriptor = parseNVMDescriptor(entryData[0]);
} else if (entry.type === NVMEntryType.NVMModuleDescriptor) {
const entryData = await this.readRawEntry(resolvedEntry);
// NVMModuleDescriptor is always a single entry
const descriptor = parseNVMModuleDescriptor(
Bytes.view(entryData[0]),
entryData[0],
);
if (descriptor.size !== moduleSize) {
throw new ZWaveError(
Expand Down
2 changes: 1 addition & 1 deletion packages/nvmedit/src/lib/nvm3/files/ControllerInfoFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export class ControllerInfoFile extends NVMFile {
}
}

public homeId: Bytes;
public homeId: Uint8Array;
public nodeId: number;
public lastNodeId: number;
public staticControllerNodeId: number;
Expand Down
6 changes: 4 additions & 2 deletions packages/nvmedit/src/lib/nvm500/EntryParsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ export interface NVMDescriptor {
}

export function parseNVMDescriptor(
buffer: Bytes,
data: Uint8Array,
offset: number = 0,
): NVMDescriptor {
const buffer = Bytes.view(data);
return {
manufacturerID: buffer.readUInt16BE(offset),
firmwareID: buffer.readUInt16BE(offset + 2),
Expand Down Expand Up @@ -63,9 +64,10 @@ export interface NVMModuleDescriptor {
}

export function parseNVMModuleDescriptor(
buffer: Bytes,
data: Uint8Array,
offset: number = 0,
): NVMModuleDescriptor {
const buffer = Bytes.view(data);
return {
size: buffer.readUInt16BE(offset),
type: buffer[offset + 2],
Expand Down
Loading

0 comments on commit 2808040

Please sign in to comment.