From 838723c9b6ec80308e9b45bf27ce522da8594c5f Mon Sep 17 00:00:00 2001 From: Dominic Griesel Date: Wed, 16 Oct 2024 14:25:14 +0200 Subject: [PATCH] refactor: rename getNodeUnsafe to tryGetNode --- docs/api/endpoint.md | 4 +-- packages/cc/src/lib/API.ts | 2 +- packages/cc/src/lib/CommandClass.ts | 2 +- packages/serial/src/message/Message.test.ts | 36 ++++++++++--------- packages/serial/src/message/Message.ts | 8 ++--- packages/zwave-js/src/lib/driver/Driver.ts | 28 +++++++-------- .../src/lib/driver/MessageGenerators.ts | 2 +- .../zwave-js/src/lib/driver/Transaction.ts | 8 ++--- packages/zwave-js/src/lib/log/Driver.ts | 2 +- .../src/lib/node/MultiCCAPIWrapper.ts | 6 ++-- packages/zwave-js/src/lib/test/messages.ts | 2 +- packages/zwave-js/src/lib/test/mocks.ts | 2 +- 12 files changed, 53 insertions(+), 49 deletions(-) diff --git a/docs/api/endpoint.md b/docs/api/endpoint.md index 27876ce8d137..100479635005 100644 --- a/docs/api/endpoint.md +++ b/docs/api/endpoint.md @@ -56,10 +56,10 @@ createCCInstanceUnsafe(cc: CommandClasses): T | undefined Like [`createCCInstance`](#createCCInstance) but returns `undefined` instead of throwing when a CC is not supported. -### `getNodeUnsafe` +### `tryGetNode` ```ts -getNodeUnsafe(): ZWaveNode | undefined +tryGetNode(): ZWaveNode | undefined ``` Returns the node this endpoint belongs to (or undefined if the node doesn't exist). diff --git a/packages/cc/src/lib/API.ts b/packages/cc/src/lib/API.ts index 0797477b29e1..29bde3de01aa 100644 --- a/packages/cc/src/lib/API.ts +++ b/packages/cc/src/lib/API.ts @@ -888,7 +888,7 @@ export type APIMethodsOf = Omit< OnlyMethods>, | "ccId" | "getNode" - | "getNodeUnsafe" + | "tryGetNode" | "isSetValueOptimistic" | "isSupported" | "pollValue" diff --git a/packages/cc/src/lib/CommandClass.ts b/packages/cc/src/lib/CommandClass.ts index be394d8ebfff..69c049b994e4 100644 --- a/packages/cc/src/lib/CommandClass.ts +++ b/packages/cc/src/lib/CommandClass.ts @@ -618,7 +618,7 @@ export class CommandClass implements CCId { * @internal * Returns the node this CC is linked to (or undefined if the node doesn't exist) */ - public getNodeUnsafe( + public tryGetNode( ctx: GetNode, ): T | undefined { try { diff --git a/packages/serial/src/message/Message.test.ts b/packages/serial/src/message/Message.test.ts index 664245187419..a052fcc78983 100644 --- a/packages/serial/src/message/Message.test.ts +++ b/packages/serial/src/message/Message.test.ts @@ -40,8 +40,8 @@ test("should deserialize and serialize correctly", (t) => { ]), ]; for (const original of okayMessages) { - const parsed = new Message({ data: original }); - t.deepEqual(parsed.serialize(), original); + const parsed = new Message({ data: original, ctx: {} as any }); + t.deepEqual(parsed.serialize({} as any), original); } }); @@ -53,7 +53,7 @@ test("should serialize correctly when the payload is null", (t) => { type: MessageType.Request, functionType: 0xff as any, }); - t.deepEqual(message.serialize(), expected); + t.deepEqual(message.serialize({} as any), expected); }); test("should throw the correct error when parsing a faulty message", (t) => { @@ -92,10 +92,14 @@ test("should throw the correct error when parsing a faulty message", (t) => { ], ]; for (const [message, msg, code] of brokenMessages) { - assertZWaveError(t, () => new Message({ data: message }), { - messageMatches: msg, - errorCode: code, - }); + assertZWaveError( + t, + () => new Message({ data: message, ctx: {} as any }), + { + messageMatches: msg, + errorCode: code, + }, + ); } }); @@ -321,7 +325,7 @@ test(`the constructor should throw when no message type is specified`, (t) => { @messageTypes(undefined as any, 0xff as any) class FakeMessageWithoutMessageType extends Message {} - assertZWaveError(t, () => new FakeMessageWithoutMessageType(host), { + assertZWaveError(t, () => new FakeMessageWithoutMessageType(), { errorCode: ZWaveErrorCodes.Argument_Invalid, messageMatches: /message type/i, }); @@ -341,31 +345,31 @@ test(`the constructor should throw when no function type is specified`, (t) => { @messageTypes(MessageType.Request, undefined as any) class FakeMessageWithoutFunctionType extends Message {} - assertZWaveError(t, () => new FakeMessageWithoutFunctionType(host), { + assertZWaveError(t, () => new FakeMessageWithoutFunctionType(), { errorCode: ZWaveErrorCodes.Argument_Invalid, messageMatches: /function type/i, }); }); -test("getNodeUnsafe() returns undefined when the controller is not initialized yet", (t) => { +test("tryGetNode() returns undefined when the controller is not initialized yet", (t) => { const host = createTestingHost(); const msg = new Message({ type: MessageType.Request, functionType: 0xff as any, }); - t.is(msg.getNodeUnsafe(host), undefined); + t.is(msg.tryGetNode(host), undefined); }); -test("getNodeUnsafe() returns undefined when the message is no node query", (t) => { +test("tryGetNode() returns undefined when the message is no node query", (t) => { const host = createTestingHost(); const msg = new Message({ type: MessageType.Request, functionType: 0xff as any, }); - t.is(msg.getNodeUnsafe(host), undefined); + t.is(msg.tryGetNode(host), undefined); }); -test("getNodeUnsafe() returns the associated node otherwise", (t) => { +test("tryGetNode() returns the associated node otherwise", (t) => { const host = createTestingHost(); host.setNode(1, {} as any); @@ -376,9 +380,9 @@ test("getNodeUnsafe() returns the associated node otherwise", (t) => { // This node exists (msg as any as INodeQuery).nodeId = 1; - t.is(msg.getNodeUnsafe(host), host.getNode(1)); + t.is(msg.tryGetNode(host), host.getNode(1)); // This one does (msg as any as INodeQuery).nodeId = 2; - t.is(msg.getNodeUnsafe(host), undefined); + t.is(msg.tryGetNode(host), undefined); }); diff --git a/packages/serial/src/message/Message.ts b/packages/serial/src/message/Message.ts index 18c5a8d062f4..4bf25cbafcd7 100644 --- a/packages/serial/src/message/Message.ts +++ b/packages/serial/src/message/Message.ts @@ -14,9 +14,9 @@ import { } from "@zwave-js/core"; import type { GetDeviceConfig, + GetNode, GetSupportedCCVersion, HostIDs, - ZWaveApplicationHost, } from "@zwave-js/host"; import type { JSONObject, TypedClassDecorator } from "@zwave-js/shared/safe"; import { num2hex, staticExtends } from "@zwave-js/shared/safe"; @@ -453,11 +453,11 @@ export class Message { /** * Returns the node this message is linked to or undefined */ - public getNodeUnsafe( - applHost: ZWaveApplicationHost, + public tryGetNode( + ctx: GetNode, ): T | undefined { const nodeId = this.getNodeId(); - if (nodeId != undefined) return applHost.getNode(nodeId); + if (nodeId != undefined) return ctx.getNode(nodeId); } private _transmissionTimestamp: number | undefined; diff --git a/packages/zwave-js/src/lib/driver/Driver.ts b/packages/zwave-js/src/lib/driver/Driver.ts index 2b777909a584..2bab99cfc38c 100644 --- a/packages/zwave-js/src/lib/driver/Driver.ts +++ b/packages/zwave-js/src/lib/driver/Driver.ts @@ -1007,7 +1007,7 @@ export class Driver extends TypedEventEmitter return [...this.controller.nodes.values()]; } - public getNodeUnsafe(msg: Message): ZWaveNode | undefined { + public tryGetNode(msg: Message): ZWaveNode | undefined { const nodeId = msg.getNodeId(); if (nodeId != undefined) return this.controller.nodes.get(nodeId); } @@ -3501,7 +3501,7 @@ export class Driver extends TypedEventEmitter }, this._requestContext); if (isCommandClassContainer(msg)) { // Whether successful or not, a message from a node should update last seen - const node = this.getNodeUnsafe(msg); + const node = this.tryGetNode(msg); if (node) node.lastSeen = new Date(); // Ensure there are no errors @@ -3510,7 +3510,7 @@ export class Driver extends TypedEventEmitter // And update statistics if (!!this._controller) { if (isCommandClassContainer(msg)) { - this.getNodeUnsafe(msg)?.incrementStatistics("commandsRX"); + this.tryGetNode(msg)?.incrementStatistics("commandsRX"); } else { this._controller.incrementStatistics("messagesRX"); } @@ -3526,7 +3526,7 @@ export class Driver extends TypedEventEmitter if (response) await this.writeHeader(response); if (!!this._controller) { if (isCommandClassContainer(msg)) { - this.getNodeUnsafe(msg)?.incrementStatistics( + this.tryGetNode(msg)?.incrementStatistics( "commandsDroppedRX", ); @@ -3538,7 +3538,7 @@ export class Driver extends TypedEventEmitter && msg.command instanceof InvalidCC ) { // If it was, we need to notify the sender that we couldn't decode the command - const node = this.getNodeUnsafe(msg); + const node = this.tryGetNode(msg); if (node) { const endpoint = node.getEndpoint( msg.command.endpointIndex, @@ -3606,7 +3606,7 @@ export class Driver extends TypedEventEmitter msg.command instanceof SecurityCCCommandEncapsulationNonceGet ) { - void this.getNodeUnsafe(msg)?.handleSecurityNonceGet(); + void this.tryGetNode(msg)?.handleSecurityNonceGet(); } // Transport Service commands must be handled before assembling partial CCs @@ -3822,7 +3822,7 @@ export class Driver extends TypedEventEmitter if (!encapS2) return false; // With the MGRP extension present - const node = this.getNodeUnsafe(msg); + const node = this.tryGetNode(msg); if (!node) return false; const groupId = encapS2.getMulticastGroupId(); if (groupId == undefined) return false; @@ -4007,7 +4007,7 @@ export class Driver extends TypedEventEmitter }, error: ZWaveError, ): boolean { - const node = this.getNodeUnsafe(transaction.message); + const node = this.tryGetNode(transaction.message); if (!node) return false; // This should never happen, but whatever const messagePart1 = isSendData(transaction.message) @@ -4172,7 +4172,7 @@ export class Driver extends TypedEventEmitter || this._recoveryPhase === ControllerRecoveryPhase.CallbackTimeoutAfterReset ) { - const node = this.getNodeUnsafe(transaction.message); + const node = this.tryGetNode(transaction.message); if (!node) return false; // This should never happen, but whatever // The controller is still timing out transmitting after a soft reset, don't try again. @@ -4980,7 +4980,7 @@ ${handlers.length} left`, let handlers: RequestHandlerEntry[] | undefined; if (isNodeQuery(msg) || isCommandClassContainer(msg)) { - const node = this.getNodeUnsafe(msg); + const node = this.tryGetNode(msg); if (node) { // We have received an unsolicited message from a dead node, bring it back to life if (node.status === NodeStatus.Dead) { @@ -5427,7 +5427,7 @@ ${handlers.length} left`, result: Message | undefined, ): void { // Update statistics - const node = this.getNodeUnsafe(msg); + const node = this.tryGetNode(msg); let success = true; if (isSendData(msg) || isNodeQuery(msg)) { // This shouldn't happen, but just in case @@ -5528,7 +5528,7 @@ ${handlers.length} left`, } const message = transaction.message; - const targetNode = message.getNodeUnsafe(this); + const targetNode = message.tryGetNode(this); // Messages to the controller may always be sent... if (!targetNode) return true; @@ -5949,7 +5949,7 @@ ${handlers.length} left`, let node: ZWaveNode | undefined; if (isNodeQuery(msg) || isCommandClassContainer(msg)) { - node = this.getNodeUnsafe(msg); + node = this.tryGetNode(msg); } if (options.priority == undefined) { @@ -7073,7 +7073,7 @@ ${handlers.length} left`, /** Determines time in milliseconds to wait for a report from a node */ public getReportTimeout(msg: Message): number { - const node = this.getNodeUnsafe(msg); + const node = this.tryGetNode(msg); return ( // If there's a message-specific timeout, use that diff --git a/packages/zwave-js/src/lib/driver/MessageGenerators.ts b/packages/zwave-js/src/lib/driver/MessageGenerators.ts index 15b8ee124bde..aafa8eceab71 100644 --- a/packages/zwave-js/src/lib/driver/MessageGenerators.ts +++ b/packages/zwave-js/src/lib/driver/MessageGenerators.ts @@ -230,7 +230,7 @@ export const maybeTransportServiceGenerator: MessageGeneratorImplementation = ); } - const node = msg.getNodeUnsafe(driver); + const node = msg.tryGetNode(driver); const mayUseTransportService = node?.supportsCC(CommandClasses["Transport Service"]) && node.getCCVersion(CommandClasses["Transport Service"]) >= 2; diff --git a/packages/zwave-js/src/lib/driver/Transaction.ts b/packages/zwave-js/src/lib/driver/Transaction.ts index 46c7cd8bcceb..a2064e7ecc2d 100644 --- a/packages/zwave-js/src/lib/driver/Transaction.ts +++ b/packages/zwave-js/src/lib/driver/Transaction.ts @@ -194,8 +194,8 @@ export class Transaction implements Comparable { _this: Transaction, _other: Transaction, ): CompareResult | undefined => { - const thisNode = _this.message.getNodeUnsafe(this.driver); - const otherNode = _other.message.getNodeUnsafe(this.driver); + const thisNode = _this.message.tryGetNode(this.driver); + const otherNode = _other.message.tryGetNode(this.driver); // We don't require existence of the node object // If any transaction is not for a node, it targets the controller @@ -222,8 +222,8 @@ export class Transaction implements Comparable { _this: Transaction, _other: Transaction, ): CompareResult | undefined => { - const thisNode = _this.message.getNodeUnsafe(this.driver); - const otherNode = _other.message.getNodeUnsafe(this.driver); + const thisNode = _this.message.tryGetNode(this.driver); + const otherNode = _other.message.tryGetNode(this.driver); if (thisNode && otherNode) { // Both nodes exist const thisListening = thisNode.isListening diff --git a/packages/zwave-js/src/lib/log/Driver.ts b/packages/zwave-js/src/lib/log/Driver.ts index 2be109c6dfe6..332e381f60ad 100644 --- a/packages/zwave-js/src/lib/log/Driver.ts +++ b/packages/zwave-js/src/lib/log/Driver.ts @@ -197,7 +197,7 @@ export class DriverLogger extends ZWaveLoggerBase { if (queue.length > 0) { for (const trns of queue.transactions) { // TODO: This formatting should be shared with the other logging methods - const node = trns.message.getNodeUnsafe(this.driver); + const node = trns.message.tryGetNode(this.driver); const prefix = trns.message.type === MessageType.Request ? "[REQ]" : "[RES]"; diff --git a/packages/zwave-js/src/lib/node/MultiCCAPIWrapper.ts b/packages/zwave-js/src/lib/node/MultiCCAPIWrapper.ts index 9bdeda6d99a1..c6993ccc2bc5 100644 --- a/packages/zwave-js/src/lib/node/MultiCCAPIWrapper.ts +++ b/packages/zwave-js/src/lib/node/MultiCCAPIWrapper.ts @@ -57,7 +57,7 @@ export function createMultiCCAPIWrapper(apiInstances: T[]): T { // This wrapper is by definition for multiple nodes, so we cannot return one const getNode = () => undefined; - const getNodeUnsafe = () => undefined; + const tryGetNode = () => undefined; return new Proxy({} as T, { get(target, prop) { @@ -81,8 +81,8 @@ export function createMultiCCAPIWrapper(apiInstances: T[]): T { return isSupported; case "getNode": return getNode; - case "getNodeUnsafe": - return getNodeUnsafe; + case "tryGetNode": + return tryGetNode; case "isSetValueOptimistic": return isSetValueOptimistic; case "supportsCommand": diff --git a/packages/zwave-js/src/lib/test/messages.ts b/packages/zwave-js/src/lib/test/messages.ts index 48ed82c9b7e7..d37819af6ce2 100644 --- a/packages/zwave-js/src/lib/test/messages.ts +++ b/packages/zwave-js/src/lib/test/messages.ts @@ -3,7 +3,7 @@ import { MessageType } from "@zwave-js/serial"; const defaultImplementations = { serialize: () => Buffer.from([1, 2, 3]), - getNodeUnsafe: () => undefined, + tryGetNode: () => undefined, getNodeId: () => undefined, toLogEntry: () => ({ tags: [] }), needsCallbackId: () => true, diff --git a/packages/zwave-js/src/lib/test/mocks.ts b/packages/zwave-js/src/lib/test/mocks.ts index 9e15f4923e3c..e43c06b0e68a 100644 --- a/packages/zwave-js/src/lib/test/mocks.ts +++ b/packages/zwave-js/src/lib/test/mocks.ts @@ -389,7 +389,7 @@ export function createTestEndpoint( > { throw new Error("Function not implemented."); }, - getNodeUnsafe: function(): IZWaveNode | undefined { + tryGetNode: function(): IZWaveNode | undefined { return host.nodes.get(options.nodeId); }, };