diff --git a/src/adapter/adapter.ts b/src/adapter/adapter.ts index 255344499d..ded1e2c1ec 100644 --- a/src/adapter/adapter.ts +++ b/src/adapter/adapter.ts @@ -1,4 +1,4 @@ -import events from 'events'; +import events from 'node:events'; import * as Models from '../models'; import {BroadcastAddress} from '../zspec/enums'; @@ -17,7 +17,14 @@ interface AdapterEventMap { deviceLeave: [payload: AdapterEvents.DeviceLeavePayload]; } -abstract class Adapter extends events.EventEmitter { +type AdapterConstructor = new ( + networkOptions: TsType.NetworkOptions, + serialPortOptions: TsType.SerialPortOptions, + backupPath: string, + adapterOptions: TsType.AdapterOptions, +) => Adapter; + +export abstract class Adapter extends events.EventEmitter { public hasZdoMessageOverhead: boolean; public manufacturerID: Zcl.ManufacturerCode; protected networkOptions: TsType.NetworkOptions; @@ -50,28 +57,25 @@ abstract class Adapter extends events.EventEmitter { backupPath: string, adapterOptions: TsType.AdapterOptions, ): Promise { - const {ZStackAdapter} = await import('./z-stack/adapter'); - const {DeconzAdapter} = await import('./deconz/adapter'); - const {ZiGateAdapter} = await import('./zigate/adapter'); - const {EZSPAdapter} = await import('./ezsp/adapter'); - const {EmberAdapter} = await import('./ember/adapter'); - const {ZBOSSAdapter} = await import('./zboss/adapter'); const adapterLookup = { - zstack: ZStackAdapter, - deconz: DeconzAdapter, - zigate: ZiGateAdapter, - ezsp: EZSPAdapter, - ember: EmberAdapter, - zboss: ZBOSSAdapter, + deconz: ['./deconz/adapter/deconzAdapter', 'DeconzAdapter'], + ember: ['./ember/adapter/emberAdapter', 'EmberAdapter'], + ezsp: ['./ezsp/adapter/ezspAdapter', 'EZSPAdapter'], + zstack: ['./z-stack/adapter/zStackAdapter', 'ZStackAdapter'], + zboss: ['./zboss/adapter/zbossAdapter', 'ZBOSSAdapter'], + zigate: ['./zigate/adapter/zigateAdapter', 'ZiGateAdapter'], }; - const [adapter, path] = await discoverAdapter(serialPortOptions.adapter, serialPortOptions.path); + const detectedAdapter = adapterLookup[adapter]; - if (adapterLookup[adapter]) { + if (detectedAdapter) { serialPortOptions.adapter = adapter; serialPortOptions.path = path; - return new adapterLookup[adapter](networkOptions, serialPortOptions, backupPath, adapterOptions); + const adapterModule = await import(detectedAdapter[0]); + const AdapterCtor = adapterModule[detectedAdapter[1]] as AdapterConstructor; + + return new AdapterCtor(networkOptions, serialPortOptions, backupPath, adapterOptions); } else { throw new Error(`Adapter '${adapter}' does not exists, possible options: ${Object.keys(adapterLookup).join(', ')}`); } diff --git a/src/adapter/adapterDiscovery.ts b/src/adapter/adapterDiscovery.ts index 2c1a618a80..73d49c9eb8 100644 --- a/src/adapter/adapterDiscovery.ts +++ b/src/adapter/adapterDiscovery.ts @@ -1,5 +1,5 @@ -import assert from 'assert'; -import {platform} from 'os'; +import assert from 'node:assert'; +import {platform} from 'node:os'; import {PortInfo} from '@serialport/bindings-cpp'; import {Bonjour, Service} from 'bonjour-service'; diff --git a/src/adapter/deconz/adapter/deconzAdapter.ts b/src/adapter/deconz/adapter/deconzAdapter.ts index d97881eab0..6165b930e2 100644 --- a/src/adapter/deconz/adapter/deconzAdapter.ts +++ b/src/adapter/deconz/adapter/deconzAdapter.ts @@ -2,7 +2,7 @@ import Device from '../../../controller/model/device'; import * as Models from '../../../models'; -import {Wait, Waitress} from '../../../utils'; +import {wait, Waitress} from '../../../utils'; import {logger} from '../../../utils/logger'; import * as ZSpec from '../../../zspec'; import {BroadcastAddress} from '../../../zspec/enums'; @@ -28,7 +28,7 @@ interface WaitressMatcher { direction: number; } -class DeconzAdapter extends Adapter { +export class DeconzAdapter extends Adapter { private driver: Driver; private openRequestsQueue: WaitForDataRequest[]; private transactionID: number; @@ -156,7 +156,7 @@ class DeconzAdapter extends Adapter { try { await this.driver.writeParameterRequest(PARAM.PARAM.Network.CHANNEL_MASK, setChannelMask); - await Wait(500); + await wait(500); changed = true; } catch (error) { logger.debug('Could not set channel: ' + error, NS); @@ -172,7 +172,7 @@ class DeconzAdapter extends Adapter { try { await this.driver.writeParameterRequest(PARAM.PARAM.Network.PAN_ID, this.networkOptions.panID); - await Wait(500); + await wait(500); changed = true; } catch (error) { logger.debug('Could not set panid: ' + error, NS); @@ -192,7 +192,7 @@ class DeconzAdapter extends Adapter { try { await this.driver.writeParameterRequest(PARAM.PARAM.Network.APS_EXT_PAN_ID, this.networkOptions.extendedPanID!); - await Wait(500); + await wait(500); changed = true; } catch (error) { logger.debug('Could not set extended panid: ' + error, NS); @@ -208,7 +208,7 @@ class DeconzAdapter extends Adapter { try { await this.driver.writeParameterRequest(PARAM.PARAM.Network.NETWORK_KEY, this.networkOptions.networkKey!); - await Wait(500); + await wait(500); changed = true; } catch (error) { logger.debug('Could not set network key: ' + error, NS); @@ -217,9 +217,9 @@ class DeconzAdapter extends Adapter { if (changed) { await this.driver.changeNetworkStateRequest(PARAM.PARAM.Network.NET_OFFLINE); - await Wait(2000); + await wait(2000); await this.driver.changeNetworkStateRequest(PARAM.PARAM.Network.NET_CONNECTED); - await Wait(2000); + await wait(2000); } // write endpoints @@ -754,5 +754,3 @@ class DeconzAdapter extends Adapter { ); } } - -export default DeconzAdapter; diff --git a/src/adapter/deconz/adapter/index.ts b/src/adapter/deconz/adapter/index.ts deleted file mode 100644 index 898d8299af..0000000000 --- a/src/adapter/deconz/adapter/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import DeconzAdapter from './deconzAdapter'; - -export {DeconzAdapter}; diff --git a/src/adapter/deconz/driver/driver.ts b/src/adapter/deconz/driver/driver.ts index 365678b6b6..40726bb113 100644 --- a/src/adapter/deconz/driver/driver.ts +++ b/src/adapter/deconz/driver/driver.ts @@ -1,7 +1,7 @@ /* istanbul ignore file */ -import events from 'events'; -import net from 'net'; +import events from 'node:events'; +import net from 'node:net'; import slip from 'slip'; diff --git a/src/adapter/deconz/driver/frameParser.ts b/src/adapter/deconz/driver/frameParser.ts index ce9522653a..6cd8c254ec 100644 --- a/src/adapter/deconz/driver/frameParser.ts +++ b/src/adapter/deconz/driver/frameParser.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import {EventEmitter} from 'stream'; +import {EventEmitter} from 'node:events'; import {logger} from '../../../utils/logger'; import * as Zdo from '../../../zspec/zdo'; diff --git a/src/adapter/deconz/driver/parser.ts b/src/adapter/deconz/driver/parser.ts index 0f5fd28949..b1f9a436b5 100644 --- a/src/adapter/deconz/driver/parser.ts +++ b/src/adapter/deconz/driver/parser.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import {Transform, TransformCallback} from 'stream'; +import {Transform, TransformCallback} from 'node:stream'; import slip from 'slip'; @@ -34,7 +34,7 @@ class Parser extends Transform { logger.debug(`<-- error '${error}'`, NS); } - public _transform(chunk: Buffer, _: string, cb: TransformCallback): void { + public override _transform(chunk: Buffer, _: string, cb: TransformCallback): void { //logger.debug(`<-- [${[...chunk]}]`, NS); this.decoder.decode(chunk); //logger.debug(`<-- [${[...chunk]}]`, NS); diff --git a/src/adapter/deconz/driver/writer.ts b/src/adapter/deconz/driver/writer.ts index a7ba21f1c9..730324494d 100644 --- a/src/adapter/deconz/driver/writer.ts +++ b/src/adapter/deconz/driver/writer.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import * as stream from 'stream'; +import * as stream from 'node:stream'; import slip from 'slip'; @@ -16,7 +16,7 @@ class Writer extends stream.Readable { this.push(buffer); } - public _read(): void {} + public override _read(): void {} } export default Writer; diff --git a/src/adapter/ember/adapter/emberAdapter.ts b/src/adapter/ember/adapter/emberAdapter.ts index 2ec69871b3..fc71539338 100644 --- a/src/adapter/ember/adapter/emberAdapter.ts +++ b/src/adapter/ember/adapter/emberAdapter.ts @@ -1,12 +1,12 @@ -import {randomBytes} from 'crypto'; -import {existsSync, readFileSync, renameSync} from 'fs'; -import path from 'path'; +import {randomBytes} from 'node:crypto'; +import {existsSync, readFileSync, renameSync} from 'node:fs'; +import path from 'node:path'; import equals from 'fast-deep-equal/es6'; import {Adapter, TsType} from '../..'; import {Backup, UnifiedBackupStorage} from '../../../models'; -import {BackupUtils, Queue, Wait} from '../../../utils'; +import {BackupUtils, Queue, wait} from '../../../utils'; import {logger} from '../../../utils/logger'; import * as ZSpec from '../../../zspec'; import {EUI64, ExtendedPanId, NodeId, PanId} from '../../../zspec/tstypes'; @@ -921,7 +921,7 @@ export class EmberAdapter extends Adapter { '[INIT TC] Leave network', ); - await Wait(200); // settle down + await wait(200); // settle down action = NetworkInitAction.LEFT; } @@ -1271,7 +1271,7 @@ export class EmberAdapter extends Adapter { // XXX: this will block other requests for a while, but should ensure the key propagates without interference? // could also stop dispatching entirely and do this outside the queue if necessary/better - await Wait(BROADCAST_NETWORK_KEY_SWITCH_WAIT_TIME); + await wait(BROADCAST_NETWORK_KEY_SWITCH_WAIT_TIME); status = await this.ezsp.ezspBroadcastNetworkKeySwitch(); @@ -2009,9 +2009,9 @@ export class EmberAdapter extends Adapter { `~x~> [ZCL to=${ieeeAddr}:${networkAddress} apsFrame=${JSON.stringify(apsFrame)}] Failed to send request with status=${SLStatus[status]}.`, ); } else if (status === SLStatus.ZIGBEE_MAX_MESSAGE_LIMIT_REACHED || status === SLStatus.BUSY) { - await Wait(QUEUE_BUSY_DEFER_MSEC); + await wait(QUEUE_BUSY_DEFER_MSEC); } else if (status === SLStatus.NETWORK_DOWN) { - await Wait(QUEUE_NETWORK_DOWN_DEFER_MSEC); + await wait(QUEUE_NETWORK_DOWN_DEFER_MSEC); } else { throw new Error( `~x~> [ZCL to=${ieeeAddr}:${networkAddress} apsFrame=${JSON.stringify(apsFrame)}] Failed to send request with status=${SLStatus[status]}.`, @@ -2075,7 +2075,7 @@ export class EmberAdapter extends Adapter { } // NOTE: since ezspMessageSentHandler could take a while here, we don't block, it'll just be logged if the delivery failed - await Wait(QUEUE_BUSY_DEFER_MSEC); + await wait(QUEUE_BUSY_DEFER_MSEC); }); } @@ -2117,7 +2117,7 @@ export class EmberAdapter extends Adapter { } // NOTE: since ezspMessageSentHandler could take a while here, we don't block, it'll just be logged if the delivery failed - await Wait(QUEUE_BUSY_DEFER_MSEC); + await wait(QUEUE_BUSY_DEFER_MSEC); }); } @@ -2246,7 +2246,7 @@ export class EmberAdapter extends Adapter { } // let adapter settle down - await Wait(QUEUE_NETWORK_DOWN_DEFER_MSEC); + await wait(QUEUE_NETWORK_DOWN_DEFER_MSEC); this.interpanLock = false; }); diff --git a/src/adapter/ember/adapter/index.ts b/src/adapter/ember/adapter/index.ts deleted file mode 100644 index 581b5bed29..0000000000 --- a/src/adapter/ember/adapter/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import {EmberAdapter} from './emberAdapter'; - -export {EmberAdapter}; diff --git a/src/adapter/ember/ezsp/ezsp.ts b/src/adapter/ember/ezsp/ezsp.ts index 640c0ae527..689e6b74f4 100644 --- a/src/adapter/ember/ezsp/ezsp.ts +++ b/src/adapter/ember/ezsp/ezsp.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import EventEmitter from 'events'; +import EventEmitter from 'node:events'; import {Queue} from '../../../utils'; import {logger} from '../../../utils/logger'; diff --git a/src/adapter/ember/uart/ash.ts b/src/adapter/ember/uart/ash.ts index c18cb32587..7135644162 100644 --- a/src/adapter/ember/uart/ash.ts +++ b/src/adapter/ember/uart/ash.ts @@ -1,9 +1,9 @@ /* istanbul ignore file */ -import {Socket} from 'net'; -import {EventEmitter} from 'stream'; +import {EventEmitter} from 'node:events'; +import {Socket} from 'node:net'; -import {Wait} from '../../../utils'; +import {wait} from '../../../utils'; import {logger} from '../../../utils/logger'; import {SerialPort} from '../../serialPort'; import SocketPortUtils from '../../socketPortUtils'; @@ -640,7 +640,7 @@ export class UartAsh extends EventEmitter { } logger.debug(`Waiting for RSTACK... ${i}/${CONFIG_TIME_RST}`, NS); - await Wait(CONFIG_TIME_RST_CHECK); + await wait(CONFIG_TIME_RST_CHECK); } return EzspStatus.HOST_FATAL_ERROR; diff --git a/src/adapter/ember/uart/parser.ts b/src/adapter/ember/uart/parser.ts index 86599beae4..af54bfa406 100644 --- a/src/adapter/ember/uart/parser.ts +++ b/src/adapter/ember/uart/parser.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import {Transform, TransformCallback, TransformOptions} from 'stream'; +import {Transform, TransformCallback, TransformOptions} from 'node:stream'; // import {logger} from '../../../utils/logger'; import {AshReservedByte} from './enums'; @@ -16,7 +16,7 @@ export class AshParser extends Transform { this.buffer = Buffer.alloc(0); } - _transform(chunk: Buffer, encoding: BufferEncoding, cb: TransformCallback): void { + override _transform(chunk: Buffer, encoding: BufferEncoding, cb: TransformCallback): void { let data = Buffer.concat([this.buffer, chunk]); let position: number; @@ -37,7 +37,7 @@ export class AshParser extends Transform { cb(); } - _flush(cb: TransformCallback): void { + override _flush(cb: TransformCallback): void { this.push(this.buffer); this.buffer = Buffer.alloc(0); diff --git a/src/adapter/ember/uart/writer.ts b/src/adapter/ember/uart/writer.ts index a891fd480f..1e545fe64b 100644 --- a/src/adapter/ember/uart/writer.ts +++ b/src/adapter/ember/uart/writer.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import {Readable, ReadableOptions} from 'stream'; +import {Readable, ReadableOptions} from 'node:stream'; // import {logger} from '../../../utils/logger'; @@ -49,5 +49,5 @@ export class AshWriter extends Readable { } } - public _read(): void {} + public override _read(): void {} } diff --git a/src/adapter/events.ts b/src/adapter/events.ts index 10eb3763d9..7b4bfe77da 100644 --- a/src/adapter/events.ts +++ b/src/adapter/events.ts @@ -1,13 +1,13 @@ import {Header as ZclHeader} from '../zspec/zcl'; -type DeviceJoinedPayload = { +export type DeviceJoinedPayload = { networkAddress: number; ieeeAddr: string; }; -type DeviceLeavePayload = {networkAddress?: number; ieeeAddr: string} | {networkAddress: number; ieeeAddr?: string}; +export type DeviceLeavePayload = {networkAddress?: number; ieeeAddr: string} | {networkAddress: number; ieeeAddr?: string}; -interface ZclPayload { +export interface ZclPayload { clusterID: number; address: number | string; header: ZclHeader | undefined; @@ -19,5 +19,3 @@ interface ZclPayload { wasBroadcast: boolean; destinationEndpoint: number; } - -export {DeviceJoinedPayload, ZclPayload, DeviceLeavePayload}; diff --git a/src/adapter/ezsp/adapter/backup.ts b/src/adapter/ezsp/adapter/backup.ts index f66eb23034..6ec4919083 100644 --- a/src/adapter/ezsp/adapter/backup.ts +++ b/src/adapter/ezsp/adapter/backup.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import * as fs from 'fs'; +import * as fs from 'node:fs'; import * as Models from '../../../models'; import {BackupUtils} from '../../../utils'; diff --git a/src/adapter/ezsp/adapter/ezspAdapter.ts b/src/adapter/ezsp/adapter/ezspAdapter.ts index 1c0bc3965d..753d99977b 100644 --- a/src/adapter/ezsp/adapter/ezspAdapter.ts +++ b/src/adapter/ezsp/adapter/ezspAdapter.ts @@ -1,9 +1,9 @@ /* istanbul ignore file */ -import assert from 'assert'; +import assert from 'node:assert'; import * as Models from '../../../models'; -import {Queue, Wait, Waitress} from '../../../utils'; +import {Queue, wait, Waitress} from '../../../utils'; import {logger} from '../../../utils/logger'; import * as ZSpec from '../../../zspec'; import * as Zcl from '../../../zspec/zcl'; @@ -25,7 +25,7 @@ interface WaitressMatcher { commandIdentifier: number; } -class EZSPAdapter extends Adapter { +export class EZSPAdapter extends Adapter { private driver: Driver; private waitress: Waitress; private interpanLock: boolean; @@ -427,7 +427,7 @@ class EZSPAdapter extends Adapter { * (contrary to network address requests) we will give the * command some time to 'settle' in the network. */ - await Wait(200); + await wait(200); }); } @@ -454,7 +454,7 @@ class EZSPAdapter extends Adapter { * (contrary to network address requests) we will give the * command some time to 'settle' in the network. */ - await Wait(200); + await wait(200); }); } @@ -480,7 +480,7 @@ class EZSPAdapter extends Adapter { const channel = (await this.getNetworkParameters()).channel; await this.driver.setChannel(channel); // Give adapter some time to restore, otherwise stuff crashes - await Wait(3000); + await wait(3000); this.interpanLock = false; }); } @@ -605,5 +605,3 @@ class EZSPAdapter extends Adapter { ); } } - -export default EZSPAdapter; diff --git a/src/adapter/ezsp/adapter/index.ts b/src/adapter/ezsp/adapter/index.ts deleted file mode 100644 index 3f6cb8e2a0..0000000000 --- a/src/adapter/ezsp/adapter/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import EZSPAdapter from './ezspAdapter'; - -export {EZSPAdapter}; diff --git a/src/adapter/ezsp/driver/driver.ts b/src/adapter/ezsp/driver/driver.ts index f1bd4899a4..70d3f19c2d 100644 --- a/src/adapter/ezsp/driver/driver.ts +++ b/src/adapter/ezsp/driver/driver.ts @@ -1,10 +1,10 @@ /* istanbul ignore file */ -import {EventEmitter} from 'events'; +import {EventEmitter} from 'node:events'; import equals from 'fast-deep-equal/es6'; -import {Wait, Waitress} from '../../../utils'; +import {wait, Waitress} from '../../../utils'; import {logger} from '../../../utils/logger'; import * as ZSpec from '../../../zspec'; import {Clusters} from '../../../zspec/zcl/definition/cluster'; @@ -142,7 +142,7 @@ export class Driver extends EventEmitter { logger.debug(`Stop error ${err}`, NS); } try { - await Wait(1000); + await wait(1000); logger.debug(`Startup again.`, NS); await this.startup(); } catch (err) { @@ -293,7 +293,7 @@ export class Driver extends EventEmitter { const netResult = await this.getKey(EmberKeyType.CURRENT_NETWORK_KEY); logger.debug(`CURRENT_NETWORK_KEY: ${JSON.stringify(netResult)}`, NS); - await Wait(1000); + await wait(1000); await this.ezsp.execCommand('setManufacturerCode', {code: DEFAULT_MFG_ID}); this.multicast = new Multicast(this); @@ -607,7 +607,7 @@ export class Driver extends EventEmitter { private async resetMfgId(mfgId: number): Promise { await this.ezsp.execCommand('setManufacturerCode', {code: mfgId}); // 60 sec for waiting - await Wait(60000); + await wait(60000); await this.ezsp.execCommand('setManufacturerCode', {code: DEFAULT_MFG_ID}); } @@ -683,7 +683,7 @@ export class Driver extends EventEmitter { // need to repeat after pause logger.error(`Request send status ${sendResult.status}. Attempt to repeat the request`, NS); - await Wait(delay); + await wait(delay); } else { result = sendResult.status == EmberStatus.SUCCESS; break; diff --git a/src/adapter/ezsp/driver/ezsp.ts b/src/adapter/ezsp/driver/ezsp.ts index cb5e0adea1..6db85fe23a 100644 --- a/src/adapter/ezsp/driver/ezsp.ts +++ b/src/adapter/ezsp/driver/ezsp.ts @@ -1,8 +1,8 @@ /* istanbul ignore file */ -import {EventEmitter} from 'events'; +import {EventEmitter} from 'node:events'; -import {Queue, Wait, Waitress} from '../../../utils'; +import {Queue, wait, Waitress} from '../../../utils'; import {logger} from '../../../utils/logger'; import {SerialPortOptions} from '../../tstype'; import { @@ -350,7 +350,7 @@ export class Ezsp extends EventEmitter { logger.error(`Connection attempt ${i} error: ${error}`, NS); if (i < MAX_SERIAL_CONNECT_ATTEMPTS) { - await Wait(SERIAL_CONNECT_NEW_ATTEMPT_MIN_DELAY * i); + await wait(SERIAL_CONNECT_NEW_ATTEMPT_MIN_DELAY * i); logger.debug(`Next attempt ${i + 1}`, NS); } diff --git a/src/adapter/ezsp/driver/parser.ts b/src/adapter/ezsp/driver/parser.ts index 64e5137986..a87da0943b 100644 --- a/src/adapter/ezsp/driver/parser.ts +++ b/src/adapter/ezsp/driver/parser.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import * as stream from 'stream'; +import * as stream from 'node:stream'; import {logger} from '../../../utils/logger'; import * as consts from './consts'; @@ -17,7 +17,7 @@ export class Parser extends stream.Transform { this.tail = []; } - public _transform(chunk: Buffer, _: string, cb: () => void): void { + public override _transform(chunk: Buffer, _: string, cb: () => void): void { if (chunk.indexOf(consts.CANCEL) >= 0) { this.reset(); chunk = chunk.subarray(chunk.lastIndexOf(consts.CANCEL) + 1); diff --git a/src/adapter/ezsp/driver/types/basic.ts b/src/adapter/ezsp/driver/types/basic.ts index 24bb1f3e85..4e28364628 100644 --- a/src/adapter/ezsp/driver/types/basic.ts +++ b/src/adapter/ezsp/driver/types/basic.ts @@ -62,7 +62,7 @@ export class int64s extends int_t { } export class uint_t extends int_t { - static _signed = false; + static override _signed = false; } export class uint8_t extends uint_t { @@ -126,14 +126,14 @@ export abstract class List { class _LVList extends List { /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ - static serialize(cls: any, value: any[]): Buffer { + static override serialize(cls: any, value: any[]): Buffer { const head = [cls.length]; const data = super.serialize(cls, value); return Buffer.from(head.concat(data)); } /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ - static deserialize(cls: any, data: Buffer): any[] { + static override deserialize(cls: any, data: Buffer): any[] { let item, length; /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ const r: any[] = []; @@ -166,7 +166,7 @@ export function LVList(itemtype: any): List { export class WordList extends List { /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ - static serialize(cls: any, value: any[]): Buffer { + static override serialize(cls: any, value: any[]): Buffer { const data = value.map((i) => Buffer.from(uint16_t.serialize(uint16_t, i))); return Buffer.concat(data); } @@ -174,13 +174,13 @@ export class WordList extends List { class _FixedList extends List { /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ - static serialize(cls: any, value: any[]): Buffer { + static override serialize(cls: any, value: any[]): Buffer { const data = value.map((i) => cls.itemtype.serialize(cls.itemtype, i)[0]); return Buffer.from(data); } /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ - static deserialize(cls: any, data: Buffer): any[] { + static override deserialize(cls: any, data: Buffer): any[] { let item; /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ const r: any[] = []; diff --git a/src/adapter/ezsp/driver/types/named.ts b/src/adapter/ezsp/driver/types/named.ts index 87b9d7862a..303932c1ed 100644 --- a/src/adapter/ezsp/driver/types/named.ts +++ b/src/adapter/ezsp/driver/types/named.ts @@ -48,7 +48,7 @@ export class EmberEUI64 extends fixed_list(8, basic.uint8_t) { } /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ - static deserialize(cls: any, data: Buffer): any[] { + static override deserialize(cls: any, data: Buffer): any[] { const arr = super.deserialize(cls, data); const r = arr[0]; data = arr[1] as Buffer; diff --git a/src/adapter/ezsp/driver/types/struct.ts b/src/adapter/ezsp/driver/types/struct.ts index cf4095be5e..95552f9156 100644 --- a/src/adapter/ezsp/driver/types/struct.ts +++ b/src/adapter/ezsp/driver/types/struct.ts @@ -671,7 +671,7 @@ export class EmberMultiAddress extends EzspStruct { ['nwk', named.EmberNodeId], ]; /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ - static serialize(cls: any, obj: any): Buffer { + static override serialize(cls: any, obj: any): Buffer { const addrmode = obj['addrmode']; const fields = addrmode == 3 ? cls.fields3 : cls.fields1; diff --git a/src/adapter/ezsp/driver/uart.ts b/src/adapter/ezsp/driver/uart.ts index ad3663a317..ce947c2c9a 100644 --- a/src/adapter/ezsp/driver/uart.ts +++ b/src/adapter/ezsp/driver/uart.ts @@ -1,11 +1,10 @@ /* istanbul ignore file */ -import {EventEmitter} from 'events'; -import net from 'net'; +import {EventEmitter} from 'node:events'; +import net from 'node:net'; -import {Queue, Wait, Waitress} from '../../../utils'; +import {Queue, wait, Waitress} from '../../../utils'; import {logger} from '../../../utils/logger'; -import wait from '../../../utils/wait'; import {SerialPort} from '../../serialPort'; import SocketPortUtils from '../../socketPortUtils'; import {SerialPortOptions} from '../../tstype'; @@ -416,7 +415,7 @@ export class SerialDriver extends EventEmitter { logger.error(`Can't send DATA frame (${seq},${ackSeq},0): ${data.toString('hex')}`, NS); try { - await Wait(500); + await wait(500); const waiter = this.waitFor(nextSeq); logger.debug(`->> DATA (${seq},${ackSeq},1): ${data.toString('hex')}`, NS); this.writer.sendData(randData, seq, 1, ackSeq); diff --git a/src/adapter/ezsp/driver/utils/crc16ccitt.ts b/src/adapter/ezsp/driver/utils/crc16ccitt.ts index 2f153da521..ca91b4c36a 100644 --- a/src/adapter/ezsp/driver/utils/crc16ccitt.ts +++ b/src/adapter/ezsp/driver/utils/crc16ccitt.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import {Buffer} from 'buffer'; +import {Buffer} from 'node:buffer'; type calcFn = (buf: Buffer | number[], previous: number) => number; diff --git a/src/adapter/ezsp/driver/utils/index.ts b/src/adapter/ezsp/driver/utils/index.ts index 35ecbe1b19..ee615cc511 100644 --- a/src/adapter/ezsp/driver/utils/index.ts +++ b/src/adapter/ezsp/driver/utils/index.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import {randomBytes} from 'crypto'; +import {randomBytes} from 'node:crypto'; import {EmberEUI64, EmberInitialSecurityBitmask} from '../types/named'; import {EmberInitialSecurityState, EmberKeyData} from '../types/struct'; diff --git a/src/adapter/ezsp/driver/writer.ts b/src/adapter/ezsp/driver/writer.ts index 90f7ed1cdf..42fda6e086 100644 --- a/src/adapter/ezsp/driver/writer.ts +++ b/src/adapter/ezsp/driver/writer.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import * as stream from 'stream'; +import * as stream from 'node:stream'; import {logger} from '../../../utils/logger'; import * as consts from './consts'; @@ -14,7 +14,7 @@ export class Writer extends stream.Readable { this.push(buffer); } - public _read(): void {} + public override _read(): void {} public sendACK(ackNum: number): void { /* Construct a acknowledgement frame */ diff --git a/src/adapter/index.ts b/src/adapter/index.ts index 95c4bf39b8..f5be94a51f 100644 --- a/src/adapter/index.ts +++ b/src/adapter/index.ts @@ -1,5 +1,3 @@ -import Adapter from './adapter'; -import * as Events from './events'; -import * as TsType from './tstype'; - -export {TsType, Adapter, Events}; +export {Adapter} from './adapter'; +export * as Events from './events'; +export * as TsType from './tstype'; diff --git a/src/adapter/z-stack/adapter/adapter-backup.ts b/src/adapter/z-stack/adapter/adapter-backup.ts index 1d3f431ddb..70278ee48a 100644 --- a/src/adapter/z-stack/adapter/adapter-backup.ts +++ b/src/adapter/z-stack/adapter/adapter-backup.ts @@ -1,5 +1,5 @@ -import assert from 'assert'; -import * as fs from 'fs'; +import assert from 'node:assert'; +import * as fs from 'node:fs'; import * as Models from '../../../models'; import {BackupUtils} from '../../../utils'; diff --git a/src/adapter/z-stack/adapter/adapter-nv-memory.ts b/src/adapter/z-stack/adapter/adapter-nv-memory.ts index 0117de09f7..6e0f6c0a41 100644 --- a/src/adapter/z-stack/adapter/adapter-nv-memory.ts +++ b/src/adapter/z-stack/adapter/adapter-nv-memory.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {NvItemsIds, NvSystemIds, ZnpCommandStatus} from '../constants/common'; import * as Structs from '../structs'; diff --git a/src/adapter/z-stack/adapter/index.ts b/src/adapter/z-stack/adapter/index.ts deleted file mode 100644 index 9be97f1a94..0000000000 --- a/src/adapter/z-stack/adapter/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import ZStackAdapter from './zStackAdapter'; - -export {ZStackAdapter}; diff --git a/src/adapter/z-stack/adapter/manager.ts b/src/adapter/z-stack/adapter/manager.ts index fdad9b1816..6a6e27854d 100644 --- a/src/adapter/z-stack/adapter/manager.ts +++ b/src/adapter/z-stack/adapter/manager.ts @@ -1,8 +1,8 @@ -import * as crypto from 'crypto'; +import * as crypto from 'node:crypto'; import {TsType} from '../../'; import * as Models from '../../../models'; -import {Wait} from '../../../utils'; +import {wait} from '../../../utils'; import {logger} from '../../../utils/logger'; import * as ZSpec from '../../../zspec'; import * as Zdo from '../../../zspec/zdo'; @@ -18,7 +18,7 @@ import {AdapterBackup} from './adapter-backup'; import {AdapterNvMemory} from './adapter-nv-memory'; import {Endpoints} from './endpoints'; import {ZnpVersion} from './tstype'; -import ZStackAdapter from './zStackAdapter'; +import {ZStackAdapter} from './zStackAdapter'; const NS = 'zh:adapter:zstack:manager'; @@ -328,7 +328,7 @@ export class ZnpAdapterManager { /* settle & reset adapter */ logger.debug('giving adapter some time to settle', NS); - await Wait(1000); + await wait(1000); await this.resetAdapter(); /* startup with restored adapter */ @@ -383,7 +383,7 @@ export class ZnpAdapterManager { let reads = 0; let nib: ReturnType; do { - await Wait(3000); + await wait(3000); nib = await this.nv.readItem(NvItemsIds.NIB, 0, Structs.nib); reads++; } while ((!nib || nib.nwkPanId === 65535 || nib.nwkLogicalChannel === 0) && reads < 10); diff --git a/src/adapter/z-stack/adapter/zStackAdapter.ts b/src/adapter/z-stack/adapter/zStackAdapter.ts index f174ce2882..0fac8013e0 100644 --- a/src/adapter/z-stack/adapter/zStackAdapter.ts +++ b/src/adapter/z-stack/adapter/zStackAdapter.ts @@ -1,9 +1,9 @@ -import assert from 'assert'; +import assert from 'node:assert'; import debounce from 'debounce'; import * as Models from '../../../models'; -import {Queue, Wait, Waitress} from '../../../utils'; +import {Queue, wait, Waitress} from '../../../utils'; import {logger} from '../../../utils/logger'; import * as ZSpec from '../../../zspec'; import {BroadcastAddress} from '../../../zspec/enums'; @@ -57,7 +57,7 @@ class DataConfirmError extends Error { } } -class ZStackAdapter extends Adapter { +export class ZStackAdapter extends Adapter { private deviceAnnounceRouteDiscoveryDebouncers: Map void>; private znp: Znp; // @ts-expect-error initialized in `start` @@ -147,7 +147,7 @@ class ZStackAdapter extends Adapter { if (this.adapterOptions.disableLED) { // Wait a bit for adapter to startup, otherwise led doesn't disable (tested with CC2531) - await Wait(200); + await wait(200); await this.setLED('disable'); } @@ -269,13 +269,13 @@ class ZStackAdapter extends Adapter { return this.version.product === ZnpVersion.zStack3x0 && parseInt(this.version.revision) >= 20201026; } - private async discoverRoute(networkAddress: number, wait = true): Promise { + private async discoverRoute(networkAddress: number, waitSettled = true): Promise { logger.debug(`Discovering route to ${networkAddress}`, NS); const payload = {dstAddr: networkAddress, options: 0, radius: Constants.AF.DEFAULT_RADIUS}; await this.znp.request(Subsystem.ZDO, 'extRouteDisc', payload); - if (wait) { - await Wait(3000); + if (waitSettled) { + await wait(3000); } } @@ -558,7 +558,7 @@ class ZStackAdapter extends Adapter { * MAC_NO_RESOURCES: Operation could not be completed because no memory resources are available, * wait some time and retry. */ - await Wait(2000); + await wait(2000); return await this.sendZclFrameToEndpointInternal( ieeeAddr, networkAddress, @@ -633,7 +633,7 @@ class ZStackAdapter extends Adapter { } } else { logger.debug('Wait 2000ms', NS); - await Wait(2000); + await wait(2000); } return await this.sendZclFrameToEndpointInternal( @@ -733,7 +733,7 @@ class ZStackAdapter extends Adapter { * (contrary to network address requests) we will give the * command some time to 'settle' in the network. */ - await Wait(200); + await wait(200); }); } @@ -759,7 +759,7 @@ class ZStackAdapter extends Adapter { * (contrary to network address requests) we will give the * command some time to 'settle' in the network. */ - await Wait(200); + await wait(200); }); } @@ -976,7 +976,7 @@ class ZStackAdapter extends Adapter { return await this.queue.execute(async () => { await this.znp.request(Subsystem.AF, 'interPanCtl', {cmd: 0, data: []}); // Give adapter some time to restore, otherwise stuff crashes - await Wait(3000); + await wait(3000); this.interpanLock = false; }); } @@ -1123,7 +1123,7 @@ class ZStackAdapter extends Adapter { * error. This is because there is too much traffic on the network. * Retry this command once after a cooling down period. */ - await Wait(2000); + await wait(2000); return await this.dataRequestExtended( addressMode, destinationAddressOrGroupID, @@ -1187,5 +1187,3 @@ class ZStackAdapter extends Adapter { } } } - -export default ZStackAdapter; diff --git a/src/adapter/z-stack/structs/entries/address-manager-table.ts b/src/adapter/z-stack/structs/entries/address-manager-table.ts index 5c48c2532f..1f1380a714 100644 --- a/src/adapter/z-stack/structs/entries/address-manager-table.ts +++ b/src/adapter/z-stack/structs/entries/address-manager-table.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {StructMemoryAlignment} from '../struct'; import {Table} from '../table'; diff --git a/src/adapter/z-stack/structs/entries/aps-link-key-data-table.ts b/src/adapter/z-stack/structs/entries/aps-link-key-data-table.ts index 55285e3b1a..daa375f1de 100644 --- a/src/adapter/z-stack/structs/entries/aps-link-key-data-table.ts +++ b/src/adapter/z-stack/structs/entries/aps-link-key-data-table.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {StructMemoryAlignment} from '../struct'; /* eslint-disable @typescript-eslint/explicit-function-return-type */ diff --git a/src/adapter/z-stack/structs/entries/aps-tc-link-key-table.ts b/src/adapter/z-stack/structs/entries/aps-tc-link-key-table.ts index b9341db669..580393df42 100644 --- a/src/adapter/z-stack/structs/entries/aps-tc-link-key-table.ts +++ b/src/adapter/z-stack/structs/entries/aps-tc-link-key-table.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {StructMemoryAlignment} from '../struct'; /* eslint-disable @typescript-eslint/explicit-function-return-type */ diff --git a/src/adapter/z-stack/structs/entries/has-configured.ts b/src/adapter/z-stack/structs/entries/has-configured.ts index 5363c0b140..bff4db33d0 100644 --- a/src/adapter/z-stack/structs/entries/has-configured.ts +++ b/src/adapter/z-stack/structs/entries/has-configured.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/explicit-function-return-type */ -import assert from 'assert'; +import assert from 'node:assert'; import {Struct} from '../struct'; diff --git a/src/adapter/z-stack/structs/entries/nib.ts b/src/adapter/z-stack/structs/entries/nib.ts index e6c9aea0e3..0d5bae498f 100644 --- a/src/adapter/z-stack/structs/entries/nib.ts +++ b/src/adapter/z-stack/structs/entries/nib.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/explicit-function-return-type */ -import assert from 'assert'; +import assert from 'node:assert'; import {Struct} from '../struct'; import {nwkKeyDescriptor} from './nwk-key-descriptor'; diff --git a/src/adapter/z-stack/structs/entries/nwk-key-descriptor.ts b/src/adapter/z-stack/structs/entries/nwk-key-descriptor.ts index ac3f7ab1d9..584ae57d6c 100644 --- a/src/adapter/z-stack/structs/entries/nwk-key-descriptor.ts +++ b/src/adapter/z-stack/structs/entries/nwk-key-descriptor.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/explicit-function-return-type */ -import assert from 'assert'; +import assert from 'node:assert'; import {Struct} from '../struct'; diff --git a/src/adapter/z-stack/structs/entries/nwk-key.ts b/src/adapter/z-stack/structs/entries/nwk-key.ts index 4132af31e2..2cb0875dc4 100644 --- a/src/adapter/z-stack/structs/entries/nwk-key.ts +++ b/src/adapter/z-stack/structs/entries/nwk-key.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/explicit-function-return-type */ -import assert from 'assert'; +import assert from 'node:assert'; import {Struct} from '../struct'; diff --git a/src/adapter/z-stack/structs/entries/nwk-sec-material-descriptor-table.ts b/src/adapter/z-stack/structs/entries/nwk-sec-material-descriptor-table.ts index 960e5af6f3..30f2016603 100644 --- a/src/adapter/z-stack/structs/entries/nwk-sec-material-descriptor-table.ts +++ b/src/adapter/z-stack/structs/entries/nwk-sec-material-descriptor-table.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {StructMemoryAlignment} from '../struct'; /* eslint-disable @typescript-eslint/explicit-function-return-type */ diff --git a/src/adapter/z-stack/structs/entries/security-manager-table.ts b/src/adapter/z-stack/structs/entries/security-manager-table.ts index 9f59676b7f..28427ac72e 100644 --- a/src/adapter/z-stack/structs/entries/security-manager-table.ts +++ b/src/adapter/z-stack/structs/entries/security-manager-table.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {StructMemoryAlignment} from '../struct'; /* eslint-disable @typescript-eslint/explicit-function-return-type */ diff --git a/src/adapter/z-stack/structs/struct.ts b/src/adapter/z-stack/structs/struct.ts index c021a6261d..3f5cf96477 100644 --- a/src/adapter/z-stack/structs/struct.ts +++ b/src/adapter/z-stack/structs/struct.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {SerializableMemoryObject} from './serializable-memory-object'; diff --git a/src/adapter/z-stack/structs/table.ts b/src/adapter/z-stack/structs/table.ts index f806abb351..07fb27bb1e 100644 --- a/src/adapter/z-stack/structs/table.ts +++ b/src/adapter/z-stack/structs/table.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {SerializableMemoryObject} from './serializable-memory-object'; import {BuiltStruct, StructFactorySignature, StructMemoryAlignment} from './struct'; diff --git a/src/adapter/z-stack/unpi/frame.ts b/src/adapter/z-stack/unpi/frame.ts index e89d9bc87f..b6f88dc3f5 100644 --- a/src/adapter/z-stack/unpi/frame.ts +++ b/src/adapter/z-stack/unpi/frame.ts @@ -1,6 +1,6 @@ import {DataStart, PositionCmd0, PositionCmd1, SOF, Subsystem, Type} from './constants'; -class Frame { +export class Frame { public readonly type: Type; public readonly subsystem: Subsystem; public readonly commandID: number; @@ -60,5 +60,3 @@ class Frame { return `${this.length} - ${this.type} - ${this.subsystem} - ${this.commandID} - [${[...this.data]}] - ${this.fcs}`; } } - -export default Frame; diff --git a/src/adapter/z-stack/unpi/index.ts b/src/adapter/z-stack/unpi/index.ts index d830db975d..94ae381837 100644 --- a/src/adapter/z-stack/unpi/index.ts +++ b/src/adapter/z-stack/unpi/index.ts @@ -1,6 +1,4 @@ -import * as Constants from './constants'; -import Frame from './frame'; -import Parser from './parser'; -import Writer from './writer'; - -export {Writer, Frame, Parser, Constants}; +export * as Constants from './constants'; +export {Frame} from './frame'; +export {Parser} from './parser'; +export {Writer} from './writer'; diff --git a/src/adapter/z-stack/unpi/parser.ts b/src/adapter/z-stack/unpi/parser.ts index f96b7d1889..c4c8222164 100644 --- a/src/adapter/z-stack/unpi/parser.ts +++ b/src/adapter/z-stack/unpi/parser.ts @@ -1,12 +1,12 @@ -import * as stream from 'stream'; +import * as stream from 'node:stream'; import {logger} from '../../../utils/logger'; import {DataStart, MinMessageLength, PositionDataLength, SOF} from './constants'; -import Frame from './frame'; +import {Frame} from './frame'; const NS = 'zh:zstack:unpi:parser'; -class Parser extends stream.Transform { +export class Parser extends stream.Transform { private buffer: Buffer; public constructor() { @@ -14,7 +14,7 @@ class Parser extends stream.Transform { this.buffer = Buffer.from([]); } - public _transform(chunk: Buffer, _: string, cb: () => void): void { + public override _transform(chunk: Buffer, _: string, cb: () => void): void { logger.debug(`<-- [${[...chunk]}]`, NS); this.buffer = Buffer.concat([this.buffer, chunk]); this.parseNext(); @@ -54,5 +54,3 @@ class Parser extends stream.Transform { } } } - -export default Parser; diff --git a/src/adapter/z-stack/unpi/writer.ts b/src/adapter/z-stack/unpi/writer.ts index f6cc31c34a..3eb66c01f5 100644 --- a/src/adapter/z-stack/unpi/writer.ts +++ b/src/adapter/z-stack/unpi/writer.ts @@ -1,11 +1,11 @@ -import * as stream from 'stream'; +import * as stream from 'node:stream'; import {logger} from '../../../utils/logger'; -import Frame from './frame'; +import {Frame} from './frame'; const NS = 'zh:zstack:unpi:writer'; -class Writer extends stream.Readable { +export class Writer extends stream.Readable { public writeFrame(frame: Frame): void { const buffer = frame.toBuffer(); logger.debug(`--> frame [${[...buffer]}]`, NS); @@ -17,7 +17,5 @@ class Writer extends stream.Readable { this.push(buffer); } - public _read(): void {} + public override _read(): void {} } - -export default Writer; diff --git a/src/adapter/z-stack/znp/index.ts b/src/adapter/z-stack/znp/index.ts index 781184f750..f1a7e2f84d 100644 --- a/src/adapter/z-stack/znp/index.ts +++ b/src/adapter/z-stack/znp/index.ts @@ -1,4 +1,2 @@ -import Znp from './znp'; -import ZpiObject from './zpiObject'; - -export {Znp, ZpiObject}; +export {Znp} from './znp'; +export {ZpiObject} from './zpiObject'; diff --git a/src/adapter/z-stack/znp/znp.ts b/src/adapter/z-stack/znp/znp.ts index 0327a1c3bc..9ca519c2a3 100755 --- a/src/adapter/z-stack/znp/znp.ts +++ b/src/adapter/z-stack/znp/znp.ts @@ -1,8 +1,8 @@ -import assert from 'assert'; -import events from 'events'; -import net from 'net'; +import assert from 'node:assert'; +import events from 'node:events'; +import net from 'node:net'; -import {Queue, Wait, Waitress} from '../../../utils'; +import {Queue, wait, Waitress} from '../../../utils'; import {logger} from '../../../utils/logger'; import {ClusterId as ZdoClusterId} from '../../../zspec/zdo'; import {SerialPort} from '../../serialPort'; @@ -13,7 +13,7 @@ import {Subsystem, Type} from '../unpi/constants'; import Definition from './definition'; import {ZpiObjectPayload} from './tstype'; import {isMtCmdSreqZdo} from './utils'; -import ZpiObject from './zpiObject'; +import {ZpiObject} from './zpiObject'; const { COMMON: {ZnpCommandStatus}, @@ -37,7 +37,7 @@ interface WaitressMatcher { state?: number; } -class Znp extends events.EventEmitter { +export class Znp extends events.EventEmitter { private path: string; private baudRate: number; private rtscts: boolean; @@ -173,18 +173,18 @@ class Znp extends events.EventEmitter { try { logger.info('Writing CC2530/CC2531 skip bootloader payload', NS); this.unpiWriter.writeBuffer(Buffer.from([0xef])); - await Wait(1000); + await wait(1000); await this.request(Subsystem.SYS, 'ping', {capabilities: 1}, undefined, 250); } catch { // Skip bootloader on some CC2652 devices (e.g. zzh-p) logger.info('Skip bootloader for CC2652/CC1352', NS); if (this.serialPort) { await this.serialPort.asyncSet({dtr: false, rts: false}); - await Wait(150); + await wait(150); await this.serialPort.asyncSet({dtr: false, rts: true}); - await Wait(150); + await wait(150); await this.serialPort.asyncSet({dtr: false, rts: false}); - await Wait(150); + await wait(150); } } } @@ -333,5 +333,3 @@ class Znp extends events.EventEmitter { ); } } - -export default Znp; diff --git a/src/adapter/z-stack/znp/zpiObject.ts b/src/adapter/z-stack/znp/zpiObject.ts index f3faecc88f..27acaaad75 100755 --- a/src/adapter/z-stack/znp/zpiObject.ts +++ b/src/adapter/z-stack/znp/zpiObject.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {ClusterId as ZdoClusterId} from '../../../zspec/zdo'; import {BuffaloZdo} from '../../../zspec/zdo/buffaloZdo'; @@ -25,7 +25,7 @@ const BufferAndListTypes = [ type ZpiObjectType = 'Request' | 'Response'; -class ZpiObject { +export class ZpiObject { public readonly type: Type; public readonly subsystem: Subsystem; public readonly command: MtCmd; @@ -147,5 +147,3 @@ class ZpiObject { return includePayload ? baseStr + ` - ${JSON.stringify(this.payload)}` : baseStr; } } - -export default ZpiObject; diff --git a/src/adapter/zboss/adapter/index.ts b/src/adapter/zboss/adapter/index.ts deleted file mode 100644 index c61df0e2e7..0000000000 --- a/src/adapter/zboss/adapter/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import {ZBOSSAdapter} from './zbossAdapter'; - -export {ZBOSSAdapter}; diff --git a/src/adapter/zboss/adapter/zbossAdapter.ts b/src/adapter/zboss/adapter/zbossAdapter.ts index 664cd67b64..ac4df65b50 100644 --- a/src/adapter/zboss/adapter/zbossAdapter.ts +++ b/src/adapter/zboss/adapter/zbossAdapter.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import assert from 'assert'; +import assert from 'node:assert'; import {Adapter, TsType} from '../..'; import {Backup} from '../../../models'; diff --git a/src/adapter/zboss/driver.ts b/src/adapter/zboss/driver.ts index 727a030ed8..79999b55ca 100644 --- a/src/adapter/zboss/driver.ts +++ b/src/adapter/zboss/driver.ts @@ -1,7 +1,7 @@ /* istanbul ignore file */ -import assert from 'assert'; -import EventEmitter from 'events'; +import assert from 'node:assert'; +import EventEmitter from 'node:events'; import equals from 'fast-deep-equal/es6'; diff --git a/src/adapter/zboss/frame.ts b/src/adapter/zboss/frame.ts index aafc154993..683862c77c 100644 --- a/src/adapter/zboss/frame.ts +++ b/src/adapter/zboss/frame.ts @@ -13,7 +13,7 @@ import {BuffaloZBOSSDataType, CommandId} from './enums'; export class ZBOSSBuffaloZcl extends BuffaloZcl { // eslint-disable-next-line @typescript-eslint/no-explicit-any - public write(type: DataType | BuffaloZclDataType | BuffaloZBOSSDataType, value: any, options: BuffaloZclOptions): void { + public override write(type: DataType | BuffaloZclDataType | BuffaloZBOSSDataType, value: any, options: BuffaloZclOptions): void { switch (type) { case BuffaloZBOSSDataType.EXTENDED_PAN_ID: { return this.writeBuffer(value, 8); @@ -25,7 +25,7 @@ export class ZBOSSBuffaloZcl extends BuffaloZcl { } // eslint-disable-next-line @typescript-eslint/no-explicit-any - public read(type: DataType | BuffaloZclDataType | BuffaloZBOSSDataType, options: BuffaloZclOptions): any { + public override read(type: DataType | BuffaloZclDataType | BuffaloZBOSSDataType, options: BuffaloZclOptions): any { switch (type) { case BuffaloZBOSSDataType.EXTENDED_PAN_ID: { return this.readBuffer(8); diff --git a/src/adapter/zboss/reader.ts b/src/adapter/zboss/reader.ts index 58900f8d6e..5050d7f4b5 100644 --- a/src/adapter/zboss/reader.ts +++ b/src/adapter/zboss/reader.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import {Transform, TransformCallback, TransformOptions} from 'stream'; +import {Transform, TransformCallback, TransformOptions} from 'node:stream'; import {logger} from '../../utils/logger'; import {SIGNATURE} from './consts'; @@ -16,7 +16,7 @@ export class ZBOSSReader extends Transform { this.buffer = Buffer.alloc(0); } - _transform(chunk: Buffer, encoding: BufferEncoding, cb: TransformCallback): void { + override _transform(chunk: Buffer, encoding: BufferEncoding, cb: TransformCallback): void { let data = Buffer.concat([this.buffer, chunk]); let position: number; @@ -54,7 +54,7 @@ export class ZBOSSReader extends Transform { cb(); } - _flush(cb: TransformCallback): void { + override _flush(cb: TransformCallback): void { this.push(this.buffer); this.buffer = Buffer.alloc(0); diff --git a/src/adapter/zboss/uart.ts b/src/adapter/zboss/uart.ts index 5d3859a5ce..16c52688db 100644 --- a/src/adapter/zboss/uart.ts +++ b/src/adapter/zboss/uart.ts @@ -1,11 +1,10 @@ /* istanbul ignore file */ -import {Socket} from 'net'; -import EventEmitter from 'stream'; +import EventEmitter from 'node:events'; +import {Socket} from 'node:net'; -import {Queue, Waitress} from '../../utils'; +import {Queue, wait, Waitress} from '../../utils'; import {logger} from '../../utils/logger'; -import wait from '../../utils/wait'; import {SerialPort} from '../serialPort'; import SocketPortUtils from '../socketPortUtils'; import {SerialPortOptions} from '../tstype'; diff --git a/src/adapter/zboss/writer.ts b/src/adapter/zboss/writer.ts index c3c20221e4..e773d5f034 100644 --- a/src/adapter/zboss/writer.ts +++ b/src/adapter/zboss/writer.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ -import {Readable, ReadableOptions} from 'stream'; +import {Readable, ReadableOptions} from 'node:stream'; export class ZBOSSWriter extends Readable { private bytesToWrite: number[]; @@ -45,5 +45,5 @@ export class ZBOSSWriter extends Readable { } } - public _read(): void {} + public override _read(): void {} } diff --git a/src/adapter/zigate/adapter/index.ts b/src/adapter/zigate/adapter/index.ts deleted file mode 100644 index 6d1ad6d68a..0000000000 --- a/src/adapter/zigate/adapter/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -/* istanbul ignore file */ - -import ZiGateAdapter from './zigateAdapter'; - -export {ZiGateAdapter}; diff --git a/src/adapter/zigate/adapter/patchZdoBuffaloBE.ts b/src/adapter/zigate/adapter/patchZdoBuffaloBE.ts index eacdedc7dc..3df072122c 100644 --- a/src/adapter/zigate/adapter/patchZdoBuffaloBE.ts +++ b/src/adapter/zigate/adapter/patchZdoBuffaloBE.ts @@ -1,17 +1,17 @@ import {BuffaloZdo} from '../../../zspec/zdo/buffaloZdo'; class ZiGateZdoBuffalo extends BuffaloZdo { - public writeUInt16(value: number): void { + public override writeUInt16(value: number): void { this.buffer.writeUInt16BE(value, this.position); this.position += 2; } - public writeUInt32(value: number): void { + public override writeUInt32(value: number): void { this.buffer.writeUInt32BE(value, this.position); this.position += 4; } - public writeIeeeAddr(value: string /*TODO: EUI64*/): void { + public override writeIeeeAddr(value: string /*TODO: EUI64*/): void { this.writeUInt32(parseInt(value.slice(2, 10), 16)); this.writeUInt32(parseInt(value.slice(10), 16)); } diff --git a/src/adapter/zigate/adapter/zigateAdapter.ts b/src/adapter/zigate/adapter/zigateAdapter.ts index 909632c51e..4a6b6689c5 100644 --- a/src/adapter/zigate/adapter/zigateAdapter.ts +++ b/src/adapter/zigate/adapter/zigateAdapter.ts @@ -1,7 +1,7 @@ /* istanbul ignore file */ import * as Models from '../../../models'; -import {Queue, Wait, Waitress} from '../../../utils'; +import {Queue, wait, Waitress} from '../../../utils'; import {logger} from '../../../utils/logger'; import * as ZSpec from '../../../zspec'; import {BroadcastAddress} from '../../../zspec/enums'; @@ -29,7 +29,7 @@ interface WaitressMatcher { direction: number; } -class ZiGateAdapter extends Adapter { +export class ZiGateAdapter extends Adapter { private driver: Driver; private joinPermitted: boolean; private waitress: Waitress; @@ -447,7 +447,7 @@ class ZiGateAdapter extends Adapter { logger.debug(() => `sendZclFrameToAll ${JSON.stringify(payload)}`, NS); await this.driver.sendCommand(ZiGateCommandCode.RawAPSDataRequest, payload, undefined, {}, true); - await Wait(200); + await wait(200); }); } @@ -468,7 +468,7 @@ class ZiGateAdapter extends Adapter { }; await this.driver.sendCommand(ZiGateCommandCode.RawAPSDataRequest, payload, undefined, {}, true); - await Wait(200); + await wait(200); }); } @@ -614,5 +614,3 @@ class ZiGateAdapter extends Adapter { } } } - -export default ZiGateAdapter; diff --git a/src/adapter/zigate/driver/zigate.ts b/src/adapter/zigate/driver/zigate.ts index d2d4179f59..dab172c95a 100644 --- a/src/adapter/zigate/driver/zigate.ts +++ b/src/adapter/zigate/driver/zigate.ts @@ -1,14 +1,14 @@ /* istanbul ignore file */ -import assert from 'assert'; -import {EventEmitter} from 'events'; -import net from 'net'; +import assert from 'node:assert'; +import {EventEmitter} from 'node:events'; +import net from 'node:net'; import {DelimiterParser} from '@serialport/parser-delimiter'; import {Queue} from '../../../utils'; import {logger} from '../../../utils/logger'; -import Waitress from '../../../utils/waitress'; +import {Waitress} from '../../../utils/waitress'; import * as ZSpec from '../../../zspec'; import * as Zdo from '../../../zspec/zdo'; import {EndDeviceAnnounce, GenericZdoResponse, ResponseMap as ZdoResponseMap} from '../../../zspec/zdo/definition/tstypes'; diff --git a/src/buffalo/buffalo.ts b/src/buffalo/buffalo.ts index cc59c98603..6a8ace8de5 100644 --- a/src/buffalo/buffalo.ts +++ b/src/buffalo/buffalo.ts @@ -2,7 +2,7 @@ import type {EUI64} from '../zspec/tstypes'; import {Utils as ZSpecUtils} from '../zspec'; -class Buffalo { +export class Buffalo { protected position: number; protected buffer: Buffer; diff --git a/src/buffalo/index.ts b/src/buffalo/index.ts index ab7cc09510..eab6ccc041 100644 --- a/src/buffalo/index.ts +++ b/src/buffalo/index.ts @@ -1,3 +1 @@ -import Buffalo from './buffalo'; - -export {Buffalo}; +export {Buffalo} from './buffalo'; diff --git a/src/controller/controller.ts b/src/controller/controller.ts index 1e8c0b4617..a74fa22756 100644 --- a/src/controller/controller.ts +++ b/src/controller/controller.ts @@ -1,11 +1,11 @@ -import assert from 'assert'; -import events from 'events'; -import fs from 'fs'; +import assert from 'node:assert'; +import events from 'node:events'; +import fs from 'node:fs'; import mixinDeep from 'mixin-deep'; import {Adapter, Events as AdapterEvents, TsType as AdapterTsType} from '../adapter'; -import {BackupUtils, Wait} from '../utils'; +import {BackupUtils, wait} from '../utils'; import {logger} from '../utils/logger'; import {isNumberArrayOfLength} from '../utils/utils'; import * as ZSpec from '../zspec'; @@ -67,7 +67,7 @@ export interface ControllerEventMap { /** * @noInheritDoc */ -class Controller extends events.EventEmitter { +export class Controller extends events.EventEmitter { private options: Options; // @ts-expect-error assigned and validated in start() private database: Database; @@ -509,7 +509,7 @@ class Controller extends events.EventEmitter { this.networkParametersCached = undefined; // invalidate cache // wait for the broadcast to propagate and the adapter to actually change // NOTE: observed to ~9sec on `ember` with actual stack event - await Wait(12000); + await wait(12000); } public async identifyUnknownDevice(nwkAddress: number): Promise { diff --git a/src/controller/database.ts b/src/controller/database.ts index 10dde8b258..c28c5500e8 100644 --- a/src/controller/database.ts +++ b/src/controller/database.ts @@ -1,11 +1,11 @@ -import fs from 'fs'; +import fs from 'node:fs'; import {logger} from '../utils/logger'; import {DatabaseEntry, EntityType} from './tstype'; const NS = 'zh:controller:database'; -class Database { +export class Database { private entries: {[id: number]: DatabaseEntry}; private path: string; private maxId: number; diff --git a/src/controller/events.ts b/src/controller/events.ts index 94404a52a8..30f2ae165d 100644 --- a/src/controller/events.ts +++ b/src/controller/events.ts @@ -2,40 +2,40 @@ import {FrameControl} from '../zspec/zcl/definition/tstype'; import {Device, Endpoint} from './model'; import {KeyValue} from './tstype'; -interface DeviceJoinedPayload { +export interface DeviceJoinedPayload { device: Device; } -interface DeviceInterviewPayload { +export interface DeviceInterviewPayload { status: 'started' | 'successful' | 'failed'; device: Device; } -interface DeviceNetworkAddressChangedPayload { +export interface DeviceNetworkAddressChangedPayload { device: Device; } -interface DeviceAnnouncePayload { +export interface DeviceAnnouncePayload { device: Device; } -interface DeviceLeavePayload { +export interface DeviceLeavePayload { ieeeAddr: string; } -interface PermitJoinChangedPayload { +export interface PermitJoinChangedPayload { permitted: boolean; time?: number; } -interface LastSeenChangedPayload { +export interface LastSeenChangedPayload { device: Device; reason: 'deviceAnnounce' | 'networkAddress' | 'deviceJoined' | 'messageEmitted' | 'messageNonEmitted'; } -type MessagePayloadType = 'attributeReport' | 'readResponse' | 'raw' | 'read' | 'write' | `command${string}`; +export type MessagePayloadType = 'attributeReport' | 'readResponse' | 'raw' | 'read' | 'write' | `command${string}`; -interface MessagePayload { +export interface MessagePayload { type: MessagePayloadType; device: Device; endpoint: Endpoint; @@ -49,15 +49,3 @@ interface MessagePayload { frameControl?: FrameControl; }; } - -export { - MessagePayload, - MessagePayloadType, - DeviceInterviewPayload, - DeviceAnnouncePayload, - DeviceLeavePayload, - DeviceJoinedPayload, - PermitJoinChangedPayload, - DeviceNetworkAddressChangedPayload, - LastSeenChangedPayload, -}; diff --git a/src/controller/greenPower.ts b/src/controller/greenPower.ts index 78113e5104..38aac985f0 100644 --- a/src/controller/greenPower.ts +++ b/src/controller/greenPower.ts @@ -1,6 +1,6 @@ -import assert from 'assert'; -import crypto from 'crypto'; -import events from 'events'; +import assert from 'node:assert'; +import crypto from 'node:crypto'; +import events from 'node:events'; import {Adapter, Events as AdapterEvents} from '../adapter'; import {logger} from '../utils/logger'; @@ -19,7 +19,7 @@ interface GreenPowerEventMap { deviceJoined: [payload: GreenPowerDeviceJoinedPayload]; } -class GreenPower extends events.EventEmitter { +export class GreenPower extends events.EventEmitter { private adapter: Adapter; public constructor(adapter: Adapter) { diff --git a/src/controller/helpers/index.ts b/src/controller/helpers/index.ts index c21a951fdb..0ee91ca406 100644 --- a/src/controller/helpers/index.ts +++ b/src/controller/helpers/index.ts @@ -1,3 +1 @@ -import * as ZclFrameConverter from './zclFrameConverter'; - -export {ZclFrameConverter}; +export * as ZclFrameConverter from './zclFrameConverter'; diff --git a/src/controller/helpers/request.ts b/src/controller/helpers/request.ts index df82a54af7..d9d57e9417 100644 --- a/src/controller/helpers/request.ts +++ b/src/controller/helpers/request.ts @@ -2,7 +2,7 @@ import * as Zcl from '../../zspec/zcl'; import {SendPolicy} from '../tstype'; /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ -class Request { +export class Request { static defaultSendPolicy: {[key: number]: SendPolicy} = { 0x00: 'keep-payload', // Read Attributes 0x01: 'immediate', // Read Attributes Response diff --git a/src/controller/helpers/requestQueue.ts b/src/controller/helpers/requestQueue.ts index 05a6ca739d..cf140a9c23 100755 --- a/src/controller/helpers/requestQueue.ts +++ b/src/controller/helpers/requestQueue.ts @@ -7,7 +7,7 @@ const NS = 'zh:controller:requestqueue'; type Mutable = {-readonly [P in keyof T]: T[P]}; -class RequestQueue extends Set { +export class RequestQueue extends Set { private sendInProgress: boolean; private ID: number; private deviceIeeeAddress: string; diff --git a/src/controller/helpers/zclTransactionSequenceNumber.ts b/src/controller/helpers/zclTransactionSequenceNumber.ts index ddf24434ec..2cc0d75f44 100644 --- a/src/controller/helpers/zclTransactionSequenceNumber.ts +++ b/src/controller/helpers/zclTransactionSequenceNumber.ts @@ -1,4 +1,4 @@ -class ZclTransactionSequenceNumber { +export class ZclTransactionSequenceNumber { private static number = 1; public static next(): number { diff --git a/src/controller/model/device.ts b/src/controller/model/device.ts index e4c01d5b40..17c0267e3a 100755 --- a/src/controller/model/device.ts +++ b/src/controller/model/device.ts @@ -1,8 +1,8 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {Events as AdapterEvents} from '../../adapter'; import {LQINeighbor, RoutingTableEntry} from '../../adapter/tstype'; -import {Wait} from '../../utils'; +import {wait} from '../../utils'; import {logger} from '../../utils/logger'; import * as ZSpec from '../../zspec'; import {BroadcastAddress} from '../../zspec/enums'; @@ -40,7 +40,7 @@ interface RoutingTable { type CustomReadResponse = (frame: Zcl.Frame, endpoint: Endpoint) => boolean; -class Device extends Entity { +export class Device extends Entity { private readonly ID: number; private _applicationVersion?: number; private _dateCode?: string; @@ -877,7 +877,7 @@ class Device extends Entity { // Give Tuya end device some time to pair. Otherwise they leave immediately. // https://github.com/Koenkk/zigbee2mqtt/issues/5814 logger.debug('Interview - Detected Tuya end device, waiting 10 seconds...', NS); - await Wait(10000); + await wait(10000); } else if (this.manufacturerID === 0 || this.manufacturerID === 4098) { // Potentially a Tuya device, some sleep fast so make sure to read the modelId and manufacturerName quickly. // In case the device responds, the endoint and modelID/manufacturerName are set @@ -942,7 +942,7 @@ class Device extends Entity { // The modelID and manufacturerName are crucial for device identification, so retry. if (item.key === 'modelID' || item.key === 'manufacturerName') { logger.debug(`Interview - first ${item.key} retrieval attempt failed, retrying after 10 seconds...`, NS); - await Wait(10000); + await wait(10000); result = await endpoint.read('genBasic', [key], {sendPolicy: 'immediate'}); } else { throw error; @@ -978,14 +978,14 @@ class Device extends Entity { // - Manual enroll: coordinator replies to enroll request with an enroll response. // this case in hanled in onZclData(). // https://github.com/Koenkk/zigbee2mqtt/issues/4569#issuecomment-706075676 - await Wait(500); + await wait(500); logger.debug(`IAS - '${this.ieeeAddr}' sending enroll response (auto enroll)`, NS); const payload = {enrollrspcode: 0, zoneid: 23}; await endpoint.command('ssIasZone', 'enrollRsp', payload, {disableDefaultResponse: true, sendPolicy: 'immediate'}); let enrolled = false; for (let attempt = 0; attempt < 20; attempt++) { - await Wait(500); + await wait(500); const stateAfter = await endpoint.read('ssIasZone', ['iasCieAddr', 'zoneState'], {sendPolicy: 'immediate'}); logger.debug(`Interview - IAS - after enrolling state (${attempt}): '${JSON.stringify(stateAfter)}'`, NS); if (stateAfter.zoneState === 1) { diff --git a/src/controller/model/endpoint.ts b/src/controller/model/endpoint.ts index 3c8ff776e2..a1e8451a38 100644 --- a/src/controller/model/endpoint.ts +++ b/src/controller/model/endpoint.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {Events as AdapterEvents} from '../../adapter'; import {logger} from '../../utils/logger'; @@ -86,7 +86,7 @@ interface ConfiguredReporting { reportableChange: number; } -class Endpoint extends Entity { +export class Endpoint extends Entity { public deviceID?: number; public inputClusters: number[]; public outputClusters: number[]; diff --git a/src/controller/model/entity.ts b/src/controller/model/entity.ts index fe04780f8e..38e9fdafa4 100644 --- a/src/controller/model/entity.ts +++ b/src/controller/model/entity.ts @@ -1,4 +1,4 @@ -import events from 'events'; +import events from 'node:events'; import {Adapter} from '../../adapter'; import Database from '../database'; @@ -7,7 +7,7 @@ import Database from '../database'; type EventMap = Record | DefaultEventMap; type DefaultEventMap = [never]; -abstract class Entity = DefaultEventMap> extends events.EventEmitter { +export abstract class Entity = DefaultEventMap> extends events.EventEmitter { protected static database?: Database; protected static adapter?: Adapter; diff --git a/src/controller/model/group.ts b/src/controller/model/group.ts index 82cc28daef..742a5e1550 100644 --- a/src/controller/model/group.ts +++ b/src/controller/model/group.ts @@ -1,4 +1,4 @@ -import assert from 'assert'; +import assert from 'node:assert'; import {logger} from '../../utils/logger'; import * as Zcl from '../../zspec/zcl'; @@ -23,7 +23,7 @@ interface OptionsWithDefaults extends Options { reservedBits: number; } -class Group extends Entity { +export class Group extends Entity { private databaseID: number; public readonly groupID: number; private readonly _members: Set; diff --git a/src/controller/model/index.ts b/src/controller/model/index.ts index 003241ea19..d755c79bff 100644 --- a/src/controller/model/index.ts +++ b/src/controller/model/index.ts @@ -1,6 +1,4 @@ -import Device from './device'; -import Endpoint from './endpoint'; -import Entity from './entity'; -import Group from './group'; - -export {Device, Endpoint, Entity, Group}; +export {Device} from './device'; +export {Endpoint} from './endpoint'; +export {Entity} from './entity'; +export {Group} from './group'; diff --git a/src/controller/touchlink.ts b/src/controller/touchlink.ts index ef48fe933b..c9f2a10586 100644 --- a/src/controller/touchlink.ts +++ b/src/controller/touchlink.ts @@ -1,5 +1,5 @@ import {Adapter} from '../adapter'; -import {Wait} from '../utils'; +import {wait} from '../utils'; import {logger} from '../utils/logger'; import {assertString} from '../utils/utils'; import * as Zcl from '../zspec/zcl'; @@ -7,7 +7,7 @@ import * as Zcl from '../zspec/zcl'; const NS = 'zh:controller:touchlink'; const scanChannels = [11, 15, 20, 25, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26]; -class Touchlink { +export class Touchlink { private adapter: Adapter; private locked: boolean; @@ -90,7 +90,7 @@ class Touchlink { logger.debug(`Identifying '${ieeeAddr}'`, NS); await this.adapter.sendZclFrameInterPANToIeeeAddr(this.createIdentifyRequestFrame(transaction), ieeeAddr); - await Wait(2000); + await wait(2000); logger.debug(`Reset to factory new '${ieeeAddr}'`, NS); await this.adapter.sendZclFrameInterPANToIeeeAddr(this.createResetFactoryNewRequestFrame(transaction), ieeeAddr); @@ -123,7 +123,7 @@ class Touchlink { // identify it (this will make e.g. the bulb flash) logger.debug(`Identifying`, NS); await this.adapter.sendZclFrameInterPANToIeeeAddr(this.createIdentifyRequestFrame(transaction), response.address); - await Wait(2000); + await wait(2000); logger.debug(`Reset to factory new`, NS); await this.adapter.sendZclFrameInterPANToIeeeAddr(this.createResetFactoryNewRequestFrame(transaction), response.address); diff --git a/src/controller/tstype.ts b/src/controller/tstype.ts index 8e07b9d921..897be55598 100644 --- a/src/controller/tstype.ts +++ b/src/controller/tstype.ts @@ -1,4 +1,4 @@ -interface KeyValue { +export interface KeyValue { // eslint-disable-next-line @typescript-eslint/no-explicit-any [s: string]: any; } @@ -19,22 +19,20 @@ interface KeyValue { If immediate delivery fails, only the latest undivided set of commands is sent for each unique set of command IDs. */ -type SendPolicy = 'bulk' | 'queue' | 'immediate' | 'keep-payload' | 'keep-command' | 'keep-cmd-undiv'; -type DeviceType = 'Coordinator' | 'Router' | 'EndDevice' | 'Unknown' | 'GreenPower'; +export type SendPolicy = 'bulk' | 'queue' | 'immediate' | 'keep-payload' | 'keep-command' | 'keep-cmd-undiv'; +export type DeviceType = 'Coordinator' | 'Router' | 'EndDevice' | 'Unknown' | 'GreenPower'; -type EntityType = DeviceType | 'Group'; +export type EntityType = DeviceType | 'Group'; -interface DatabaseEntry { +export interface DatabaseEntry { id: number; type: EntityType; // eslint-disable-next-line @typescript-eslint/no-explicit-any [s: string]: any; } -interface GreenPowerDeviceJoinedPayload { +export interface GreenPowerDeviceJoinedPayload { sourceID: number; deviceID: number; networkAddress: number; } - -export {KeyValue, DatabaseEntry, EntityType, DeviceType, GreenPowerDeviceJoinedPayload, SendPolicy}; diff --git a/src/index.ts b/src/index.ts index 6e81866239..b61592ee34 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,9 @@ -export {default as Controller} from './controller/controller'; +export {Controller} from './controller/controller'; +export type * as Events from './controller/events'; +export type * as Types from './controller/tstype'; +export type * as Models from './controller/model'; +export type * as AdapterEvents from './adapter/events'; +export type * as AdapterTypes from './adapter/tstype'; export * as Zcl from './zspec/zcl'; export * as Zdo from './zspec/zdo'; export * as ZSpec from './zspec'; diff --git a/src/utils/backup.ts b/src/utils/backup.ts index 5d93db5437..4f978762d6 100644 --- a/src/utils/backup.ts +++ b/src/utils/backup.ts @@ -1,5 +1,5 @@ -import * as fs from 'fs'; -import * as path from 'path'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; import * as ZStackStructs from '../adapter/z-stack/structs'; import * as ZStackUtils from '../adapter/z-stack/utils'; diff --git a/src/utils/index.ts b/src/utils/index.ts index 04973310bf..f2904d6ee1 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,8 +1,5 @@ -import * as BackupUtils from './backup'; -import Queue from './queue'; -import RealpathSync from './realpathSync'; -import * as Utils from './utils'; -import Wait from './wait'; -import Waitress from './waitress'; - -export {Wait, Queue, Waitress, RealpathSync, BackupUtils, Utils}; +export * as BackupUtils from './backup'; +export {Queue} from './queue'; +export * as Utils from './utils'; +export {wait} from './wait'; +export {Waitress} from './waitress'; diff --git a/src/utils/queue.ts b/src/utils/queue.ts index b10911bb28..892dfb1690 100644 --- a/src/utils/queue.ts +++ b/src/utils/queue.ts @@ -4,7 +4,7 @@ interface Job { start?: () => void; } -class Queue { +export class Queue { private jobs: Job[]; private readonly concurrent: number; @@ -73,5 +73,3 @@ class Queue { return this.jobs.length; } } - -export default Queue; diff --git a/src/utils/realpathSync.ts b/src/utils/realpathSync.ts deleted file mode 100644 index 3b2424b896..0000000000 --- a/src/utils/realpathSync.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* istanbul ignore file */ - -import fs from 'fs'; - -/* Only used for mocking purposes */ -function realpathSync(path: string): string { - return fs.realpathSync(path); -} - -export default realpathSync; diff --git a/src/utils/wait.ts b/src/utils/wait.ts index fd62ea0a79..f39b44f985 100644 --- a/src/utils/wait.ts +++ b/src/utils/wait.ts @@ -1,7 +1,5 @@ -function wait(milliseconds: number): Promise { +export function wait(milliseconds: number): Promise { return new Promise((resolve): void => { setTimeout((): void => resolve(), milliseconds); }); } - -export default wait; diff --git a/src/utils/waitress.ts b/src/utils/waitress.ts index edf3a52d85..57f201d4c4 100644 --- a/src/utils/waitress.ts +++ b/src/utils/waitress.ts @@ -11,7 +11,7 @@ interface Waiter { type Validator = (payload: TPayload, matcher: TMatcher) => boolean; type TimeoutFormatter = (matcher: TMatcher, timeout: number) => string; -class Waitress { +export class Waitress { private waiters: Map>; private readonly validator: Validator; private readonly timeoutFormatter: TimeoutFormatter; @@ -86,5 +86,3 @@ class Waitress { return foundMatching; } } - -export default Waitress; diff --git a/src/zspec/utils.ts b/src/zspec/utils.ts index 8b17f453b8..b83769b6d3 100644 --- a/src/zspec/utils.ts +++ b/src/zspec/utils.ts @@ -1,6 +1,6 @@ import type {EUI64} from './tstypes'; -import {createCipheriv} from 'crypto'; +import {createCipheriv} from 'node:crypto'; import {AES_MMO_128_BLOCK_SIZE, ALL_802_15_4_CHANNELS, INSTALL_CODE_CRC_SIZE, INSTALL_CODE_SIZES} from './consts'; import {BroadcastAddress} from './enums'; diff --git a/test/adapter/adapter.test.ts b/test/adapter/adapter.test.ts index 062cf041ce..7f74c44746 100644 --- a/test/adapter/adapter.test.ts +++ b/test/adapter/adapter.test.ts @@ -1,15 +1,15 @@ -import os from 'os'; +import os from 'node:os'; import {Bonjour, BrowserConfig} from 'bonjour-service'; -import {Adapter} from '../../src/adapter'; -import {DeconzAdapter} from '../../src/adapter/deconz/adapter'; -import {EmberAdapter} from '../../src/adapter/ember/adapter'; -import {EZSPAdapter} from '../../src/adapter/ezsp/adapter'; +import {Adapter, TsType} from '../../src/adapter'; +import {DeconzAdapter} from '../../src/adapter/deconz/adapter/deconzAdapter'; +import {EmberAdapter} from '../../src/adapter/ember/adapter/emberAdapter'; +import {EZSPAdapter} from '../../src/adapter/ezsp/adapter/ezspAdapter.ts'; import {SerialPort} from '../../src/adapter/serialPort'; -import {ZStackAdapter} from '../../src/adapter/z-stack/adapter'; -import {ZBOSSAdapter} from '../../src/adapter/zboss/adapter'; -import {ZiGateAdapter} from '../../src/adapter/zigate/adapter'; +import {ZStackAdapter} from '../../src/adapter/z-stack/adapter/zStackAdapter'; +import {ZBOSSAdapter} from '../../src/adapter/zboss/adapter/zbossAdapter'; +import {ZiGateAdapter} from '../../src/adapter/zigate/adapter/zigateAdapter'; import { DECONZ_CONBEE_II, EMBER_SKYCONNECT, @@ -51,6 +51,24 @@ describe('Adapter', () => { jest.useFakeTimers(); }); + it.each([ + ['deconz', DeconzAdapter], + ['ember', EmberAdapter], + ['ezsp', EZSPAdapter], + ['zstack', ZStackAdapter], + ['zboss', ZBOSSAdapter], + ['zigate', ZiGateAdapter], + ])('Calls adapter contructor for %s', async (name, cls) => { + const adapter = await Adapter.create( + {panID: 0x1a62, channelList: [11]}, + {path: '/dev/ttyUSB0', adapter: name as TsType.Adapter}, + 'test.db.backup', + {disableLED: false}, + ); + + expect(adapter).toBeInstanceOf(cls); + }); + describe('mDNS discovery', () => { beforeEach(() => { mockBonjourResult.mockClear(); @@ -640,7 +658,7 @@ describe('Adapter', () => { 'test.db.backup', {disableLED: false}, ); - }).rejects.toThrow(`Adapter 'invalid' does not exists, possible options: zstack, deconz, zigate, ezsp, ember, zboss`); + }).rejects.toThrow(`Adapter 'invalid' does not exists, possible options: deconz, ember, ezsp, zstack, zboss, zigate`); }); }); diff --git a/test/adapter/ember/ash.test.ts b/test/adapter/ember/ash.test.ts index 8bc916fe08..3f84b526a9 100644 --- a/test/adapter/ember/ash.test.ts +++ b/test/adapter/ember/ash.test.ts @@ -19,7 +19,7 @@ import {CONFIG_TX_K, UartAsh} from '../../../src/adapter/ember/uart/ash'; import {EZSP_HOST_RX_POOL_SIZE, TX_POOL_BUFFERS} from '../../../src/adapter/ember/uart/consts'; import {EzspBuffer} from '../../../src/adapter/ember/uart/queues'; import {lowByte} from '../../../src/adapter/ember/utils/math'; -import {Wait} from '../../../src/utils/'; +import {wait} from '../../../src/utils/'; import {adapterSONOFFDongleE, ASH_ACK_FIRST_BYTES, RECD_RSTACK_BYTES, SEND_ACK_FIRST_BYTES, SEND_RST_BYTES} from './consts'; const mockSerialPortCloseEvent = jest.fn(); @@ -206,7 +206,7 @@ describe('Ember UART ASH Protocol', () => { uartAsh.serialPort.port.emitData(badCrcRSTACK); const startResult = await uartAsh.start(); - await Wait(10); + await wait(10); expect(startResult).toStrictEqual(EzspStatus.HOST_FATAL_ERROR); expect(uartAsh.counters.txAllFrames).toStrictEqual(1); @@ -253,7 +253,7 @@ describe('Ember UART ASH Protocol', () => { uartAsh.send(sendBuf.length, sendBuf); - await Wait(10); + await wait(10); expect(uartAsh.counters.txDataFrames).toStrictEqual(1); //@ts-expect-error private @@ -282,12 +282,12 @@ describe('Ember UART ASH Protocol', () => { uartAsh.send(sendBuf.length, sendBuf); - await Wait(10); + await wait(10); //@ts-expect-error private uartAsh.serialPort.port.emitData(Buffer.from(SEND_ACK_FIRST_BYTES)); // just an ACK, doesn't matter what it is - await Wait(10); // force wait new frame + await wait(10); // force wait new frame expect(uartAsh.counters.txAckFrames).toStrictEqual(1); expect(uartAsh.counters.rxAckFrames).toStrictEqual(1); @@ -317,7 +317,7 @@ describe('Ember UART ASH Protocol', () => { uartAsh.send(sendBuf.length, sendBuf); } - await Wait(10); + await wait(10); expect(uartAsh.counters.txDataFrames).toStrictEqual(3); expect(uartAsh.txQueue.length).toStrictEqual(1); diff --git a/test/adapter/ember/emberAdapter.test.ts b/test/adapter/ember/emberAdapter.test.ts index 277e40376f..de351edd3e 100644 --- a/test/adapter/ember/emberAdapter.test.ts +++ b/test/adapter/ember/emberAdapter.test.ts @@ -1,10 +1,15 @@ -import {existsSync, mkdirSync, unlinkSync, writeFileSync} from 'fs'; -import path from 'path'; -import {EventEmitter} from 'stream'; +import {existsSync, mkdirSync, unlinkSync, writeFileSync} from 'node:fs'; +import path from 'node:path'; +import {EventEmitter} from 'node:stream'; import {TsType} from '../../../src/adapter'; -import {EmberAdapter} from '../../../src/adapter/ember/adapter'; -import {DEFAULT_APS_OPTIONS, DEFAULT_STACK_CONFIG, LinkKeyBackupData, NetworkCache} from '../../../src/adapter/ember/adapter/emberAdapter'; +import { + DEFAULT_APS_OPTIONS, + DEFAULT_STACK_CONFIG, + EmberAdapter, + LinkKeyBackupData, + NetworkCache, +} from '../../../src/adapter/ember/adapter/emberAdapter'; import {FIXED_ENDPOINTS} from '../../../src/adapter/ember/adapter/endpoints'; import {OneWaitressEvents} from '../../../src/adapter/ember/adapter/oneWaitress'; import {EMBER_LOW_RAM_CONCENTRATOR, INVALID_RADIO_CHANNEL, SECURITY_LEVEL_Z3} from '../../../src/adapter/ember/consts'; @@ -69,7 +74,7 @@ function reverseApsFrame(apsFrame: EmberApsFrame): EmberApsFrame { } function flushPromises(): Promise { - return new Promise(jest.requireActual('timers').setImmediate); + return new Promise(jest.requireActual('node:timers').setImmediate); } const TEMP_PATH = path.resolve('temp'); @@ -271,7 +276,7 @@ jest.mock('../../../src/adapter/ember/uart/ash'); jest.mock('../../../src/adapter/ember/ezsp/ezsp', () => ({ ...jest.requireActual('../../../src/adapter/ember/ezsp/ezsp'), - Ezsp: jest.fn().mockImplementation(() => ({ + Ezsp: jest.fn(() => ({ removeAllListeners: mockEzspRemoveAllListeners, on: mockEzspOn, once: mockEzspOnce, diff --git a/test/adapter/ezsp/uart.test.ts b/test/adapter/ezsp/uart.test.ts index 12657c0e45..65ea3f4ac0 100644 --- a/test/adapter/ezsp/uart.test.ts +++ b/test/adapter/ezsp/uart.test.ts @@ -22,31 +22,29 @@ const mockSerialPortSet = jest.fn().mockImplementation((opts, cb) => cb()); const mockSerialPortWrite = jest.fn((buffer, cb) => (cb ? cb() : null)); let mockSerialPortIsOpen = false; -jest.mock('../../../src/adapter/serialPort', () => { - return { - SerialPort: jest.fn().mockImplementation(() => { - return { - close: mockSerialPortClose, - constructor: mockSerialPortConstructor, - emit: () => {}, - on: () => {}, - once: mockSerialPortOnce, - open: mockSerialPortOpen, - pipe: mockSerialPortPipe, - set: mockSerialPortSet, - write: mockSerialPortWrite, - flush: mockSerialPortFlush, - isOpen: mockSerialPortIsOpen, - asyncOpen: mockSerialPortAsyncOpen, - asyncFlushAndClose: mockSerialPortAsyncFlushAndClose, - }; - }), - }; -}); - -jest.mock('../../../src/utils/wait', () => { - return () => {}; -}); +jest.mock('../../../src/adapter/serialPort', () => ({ + SerialPort: jest.fn(() => ({ + close: mockSerialPortClose, + constructor: mockSerialPortConstructor, + emit: () => {}, + on: () => {}, + once: mockSerialPortOnce, + open: mockSerialPortOpen, + pipe: mockSerialPortPipe, + set: mockSerialPortSet, + write: mockSerialPortWrite, + flush: mockSerialPortFlush, + isOpen: mockSerialPortIsOpen, + asyncOpen: mockSerialPortAsyncOpen, + asyncFlushAndClose: mockSerialPortAsyncFlushAndClose, + })), +})); + +jest.mock('../../../src/utils/wait', () => ({ + wait: jest.fn(() => { + return new Promise((resolve) => resolve()); + }), +})); let writeBufferSpy; diff --git a/test/adapter/z-stack/adapter.test.ts b/test/adapter/z-stack/adapter.test.ts index 6e98de4211..de48aa741f 100644 --- a/test/adapter/z-stack/adapter.test.ts +++ b/test/adapter/z-stack/adapter.test.ts @@ -1,13 +1,13 @@ import 'regenerator-runtime/runtime'; -import * as fs from 'fs'; -import * as path from 'path'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; import equals from 'fast-deep-equal/es6'; import {ZclPayload} from '../../../src/adapter/events'; -import {ZStackAdapter} from '../../../src/adapter/z-stack/adapter'; import {ZnpVersion} from '../../../src/adapter/z-stack/adapter/tstype'; +import {ZStackAdapter} from '../../../src/adapter/z-stack/adapter/zStackAdapter'; import * as Constants from '../../../src/adapter/z-stack/constants'; import {AddressMode, DevStates, NvItemsIds, NvSystemIds, ZnpCommandStatus} from '../../../src/adapter/z-stack/constants/common'; import * as Structs from '../../../src/adapter/z-stack/structs'; @@ -49,11 +49,18 @@ const mockLogger = { error: jest.fn(), }; const deepClone = (obj) => JSON.parse(JSON.stringify(obj)); -const mockSetTimeout = () => (setTimeout = jest.fn().mockImplementation((r) => r())); +const mockSetTimeout = () => { + return jest.spyOn(globalThis, 'setTimeout').mockImplementation( + // @ts-expect-error mock + (cb) => cb(), + ); +}; -jest.mock('../../../src/utils/wait', () => { - return jest.fn(); -}); +jest.mock('../../../src/utils/wait', () => ({ + wait: jest.fn(() => { + return new Promise((resolve) => resolve()); + }), +})); const waitForResult = (payloadOrPromise: Promise | ZpiObjectPayload, ID?: number) => { ID = ID || 1; @@ -1355,34 +1362,30 @@ let lastStartIndex = 0; let simpleDescriptorEndpoint = 0; let assocGetWithAddressNodeRelation; -jest.mock('../../../src/adapter/z-stack/znp/znp', () => { - return jest.fn().mockImplementation(() => { - return { - on: (event, handler) => { - if (event === 'received') { - znpReceived = handler; - } else if (event === 'close') { - znpClose = handler; - } - }, - open: mockZnpOpen, - request: mockZnpRequest, - requestZdo: mockZnpRequestZdo, - requestWithReply: mockZnpRequest, - waitFor: mockZnpWaitFor, - close: mockZnpClose, - }; - }); -}); - -jest.mock('../../../src/utils/queue', () => { - return jest.fn().mockImplementation(() => { - return { - execute: mockQueueExecute, - count: () => 1, - }; - }); -}); +jest.mock('../../../src/adapter/z-stack/znp/znp', () => ({ + Znp: jest.fn(() => ({ + on: (event, handler) => { + if (event === 'received') { + znpReceived = handler; + } else if (event === 'close') { + znpClose = handler; + } + }, + open: mockZnpOpen, + request: mockZnpRequest, + requestZdo: mockZnpRequestZdo, + requestWithReply: mockZnpRequest, + waitFor: mockZnpWaitFor, + close: mockZnpClose, + })), +})); + +jest.mock('../../../src/utils/queue', () => ({ + Queue: jest.fn(() => ({ + execute: mockQueueExecute, + count: () => 1, + })), +})); const mocksClear = [mockLogger.debug, mockLogger.info, mockLogger.warning, mockLogger.error]; @@ -3144,10 +3147,11 @@ describe('zstack-adapter', () => { }); let error; try { - mockSetTimeout(); + const spy = mockSetTimeout(); const response = adapter.sendZclFrameToEndpoint('0x02', 2, 20, frame, 1, false, false); znpReceived(objectMismatch); await response; + spy.mockRestore(); } catch (e) { error = e; } @@ -3202,10 +3206,11 @@ describe('zstack-adapter', () => { }); let error; try { - mockSetTimeout(); + const spy = mockSetTimeout(); const response = adapter.sendZclFrameToEndpoint('0x02', 2, 20, frame, 1, false, false); znpReceived(objectMismatch); await response; + spy.mockRestore(); } catch (e) { error = e; } diff --git a/test/adapter/z-stack/znp.test.ts b/test/adapter/z-stack/znp.test.ts index b8045912ef..c6d0c62283 100644 --- a/test/adapter/z-stack/znp.test.ts +++ b/test/adapter/z-stack/znp.test.ts @@ -30,95 +30,74 @@ const mockSerialPortAsyncSet = jest.fn(); const mockSerialPortWrite = jest.fn((buffer, cb) => cb()); let mockSerialPortIsOpen = false; -jest.mock('../../../src/utils/wait', () => { - return jest.fn(); -}); - -jest.mock('../../../src/adapter/serialPort', () => { - return { - SerialPort: jest.fn().mockImplementation(() => { - return { - close: mockSerialPortClose, - constructor: mockSerialPortConstructor, - emit: () => {}, - on: () => {}, - once: mockSerialPortOnce, - open: mockSerialPortOpen, - pipe: mockSerialPortPipe, - write: mockSerialPortWrite, - flush: mockSerialPortFlush, - isOpen: mockSerialPortIsOpen, - asyncOpen: mockSerialPortAsyncOpen, - asyncFlushAndClose: mockSerialPortAsyncFlushAndClose, - asyncSet: mockSerialPortAsyncSet, - }; - }), - }; -}); +jest.mock('../../../src/utils/wait', () => ({ + wait: jest.fn(() => { + return new Promise((resolve) => resolve()); + }), +})); + +jest.mock('../../../src/adapter/serialPort', () => ({ + SerialPort: jest.fn(() => ({ + close: mockSerialPortClose, + constructor: mockSerialPortConstructor, + emit: () => {}, + on: () => {}, + once: mockSerialPortOnce, + open: mockSerialPortOpen, + pipe: mockSerialPortPipe, + write: mockSerialPortWrite, + flush: mockSerialPortFlush, + isOpen: mockSerialPortIsOpen, + asyncOpen: mockSerialPortAsyncOpen, + asyncFlushAndClose: mockSerialPortAsyncFlushAndClose, + asyncSet: mockSerialPortAsyncSet, + })), +})); const mockSocketSetNoDelay = jest.fn(); const mockSocketSetKeepAlive = jest.fn(); const mockSocketPipe = jest.fn(); const mockSocketOnce = jest.fn(); const mockSocketCallbacks = {}; -const mockSocketConnect = jest.fn().mockImplementation(() => { +const mockSocketConnect = jest.fn(() => { mockSocketCallbacks['connect'](); mockSocketCallbacks['ready'](); }); const mockSocketDestroy = jest.fn(); let requestSpy; -jest.mock('net', () => { - return { - Socket: jest.fn().mockImplementation(() => { - return { - setNoDelay: mockSocketSetNoDelay, - pipe: mockSocketPipe, - connect: mockSocketConnect, - on: (event, cb) => (mockSocketCallbacks[event] = cb), - once: mockSocketOnce, - destroy: mockSocketDestroy, - setKeepAlive: mockSocketSetKeepAlive, - }; - }), - }; -}); - -// Mock realPathSync -let mockRealPathSyncError = false; -jest.mock('../../../src/utils/realpathSync', () => { - return jest.fn().mockImplementation((path) => { - if (mockRealPathSyncError) { - throw new Error('Not a valid path'); - } - return path; - }); -}); +jest.mock('node:net', () => ({ + Socket: jest.fn(() => ({ + setNoDelay: mockSocketSetNoDelay, + pipe: mockSocketPipe, + connect: mockSocketConnect, + on: (event, cb) => (mockSocketCallbacks[event] = cb), + once: mockSocketOnce, + destroy: mockSocketDestroy, + setKeepAlive: mockSocketSetKeepAlive, + })), +})); SerialPort.list = mockSerialPortList; const mockUnpiParserOn = jest.fn(); -jest.mock('../../../src/adapter/z-stack/unpi/parser', () => { - return jest.fn().mockImplementation(() => { - return { - on: mockUnpiParserOn, - }; - }); -}); +jest.mock('../../../src/adapter/z-stack/unpi/parser', () => ({ + Parser: jest.fn(() => ({ + on: mockUnpiParserOn, + })), +})); const mockUnpiWriterWriteFrame = jest.fn(); const mockUnpiWriterWriteBuffer = jest.fn(); -jest.mock('../../../src/adapter/z-stack/unpi/writer', () => { - return jest.fn().mockImplementation(() => { - return { - writeFrame: mockUnpiWriterWriteFrame, - writeBuffer: mockUnpiWriterWriteBuffer, - pipe: jest.fn(), - }; - }); -}); +jest.mock('../../../src/adapter/z-stack/unpi/writer', () => ({ + Writer: jest.fn(() => ({ + writeFrame: mockUnpiWriterWriteFrame, + writeBuffer: mockUnpiWriterWriteBuffer, + pipe: jest.fn(), + })), +})); const mocks = [ mockSerialPortClose, diff --git a/test/adapter/zigate/patchZdoBuffaloBE.test.ts b/test/adapter/zigate/patchZdoBuffaloBE.test.ts index 2d885cd7cf..8d619a7ba9 100644 --- a/test/adapter/zigate/patchZdoBuffaloBE.test.ts +++ b/test/adapter/zigate/patchZdoBuffaloBE.test.ts @@ -7,7 +7,7 @@ describe('ZiGate Patch BuffaloZdo to use BE variants when writing', () => { await jest.isolateModulesAsync(async () => { const buf = await import('../../../src/zspec/zdo/buffaloZdo'); BuffaloZdo = buf.BuffaloZdo; - const {ZiGateAdapter} = await import('../../../src/adapter/zigate/adapter'); + const {ZiGateAdapter} = await import('../../../src/adapter/zigate/adapter/zigateAdapter'); // @ts-expect-error bogus, just need to trigger constructor const adapter = new ZiGateAdapter({}, {}, '', {}); }); diff --git a/test/adapter/zigate/zdo.test.ts b/test/adapter/zigate/zdo.test.ts index d5bb17724c..7a9cf1a845 100644 --- a/test/adapter/zigate/zdo.test.ts +++ b/test/adapter/zigate/zdo.test.ts @@ -1,4 +1,4 @@ -import {ZiGateAdapter} from '../../../src/adapter/zigate/adapter'; +import {ZiGateAdapter} from '../../../src/adapter/zigate/adapter/zigateAdapter'; import {BLANK_EUI64} from '../../../src/zspec'; import * as Zdo from '../../../src/zspec/zdo'; diff --git a/test/controller.test.ts b/test/controller.test.ts index 515eb46612..2aa23da75f 100755 --- a/test/controller.test.ts +++ b/test/controller.test.ts @@ -1,15 +1,13 @@ import 'regenerator-runtime/runtime'; -import fs from 'fs'; -import path from 'path'; +import fs from 'node:fs'; +import path from 'node:path'; import Bonjour, {Browser, BrowserConfig, Service} from 'bonjour-service'; import equals from 'fast-deep-equal/es6'; import {Adapter} from '../src/adapter'; -import {DeconzAdapter} from '../src/adapter/deconz/adapter'; -import {ZStackAdapter} from '../src/adapter/z-stack/adapter'; -import {ZiGateAdapter} from '../src/adapter/zigate/adapter'; +import {ZStackAdapter} from '../src/adapter/z-stack/adapter/zStackAdapter'; import {Controller} from '../src/controller'; import * as Events from '../src/controller/events'; import Request from '../src/controller/helpers/request'; @@ -17,7 +15,7 @@ import zclTransactionSequenceNumber from '../src/controller/helpers/zclTransacti import ZclTransactionSequenceNumber from '../src/controller/helpers/zclTransactionSequenceNumber'; import {Device, Endpoint, Group} from '../src/controller/model'; import * as Models from '../src/models'; -import {Wait} from '../src/utils'; +import {wait} from '../src/utils'; import * as Utils from '../src/utils'; import {setLogger} from '../src/utils/logger'; import * as ZSpec from '../src/zspec'; @@ -40,7 +38,7 @@ const mockLogger = { }; let skipWait = true; -(Wait as ReturnType).mockImplementation((milliseconds) => { +(wait as ReturnType).mockImplementation((milliseconds) => { if (!skipWait) { return new Promise((resolve) => { setTimeout((): void => resolve(), milliseconds); @@ -313,18 +311,11 @@ const equalsPartial = (object, expected) => { return true; }; -// Mock realPathSync -jest.mock('../src/utils/realpathSync', () => { - return jest.fn().mockImplementation((path) => { - return path; - }); -}); - -jest.mock('../src/utils/wait', () => { - return jest.fn().mockImplementation(() => { - return new Promise((resolve, reject) => resolve()); - }); -}); +jest.mock('../src/utils/wait', () => ({ + wait: jest.fn(() => { + return new Promise((resolve) => resolve()); + }), +})); const getCluster = (key) => { const cluster = Zcl.Utils.getCluster(key, undefined, {}); @@ -379,53 +370,39 @@ const mockDummyBackup: Models.Backup = { let dummyBackup; -jest.mock('../src/adapter/z-stack/adapter/zStackAdapter', () => { - return jest.fn().mockImplementation(() => { - return { - hasZdoMessageOverhead: false, - manufacturerID: 0x0007, - on: (event, handler) => (mockAdapterEvents[event] = handler), - removeAllListeners: (event) => delete mockAdapterEvents[event], - start: mockAdapterStart, - getCoordinatorIEEE: mockAdapterGetCoordinatorIEEE, - reset: mockAdapterReset, - supportsBackup: mockAdapterSupportsBackup, - backup: () => { - return mockDummyBackup; - }, - getCoordinatorVersion: () => { - return {type: 'zStack', meta: {version: 1}}; - }, - getNetworkParameters: mockAdapterGetNetworkParameters, - waitFor: mockAdapterWaitFor, - sendZclFrameToEndpoint: mocksendZclFrameToEndpoint, - sendZclFrameToGroup: mocksendZclFrameToGroup, - sendZclFrameToAll: mocksendZclFrameToAll, - addInstallCode: mockAddInstallCode, - permitJoin: mockAdapterPermitJoin, - supportsDiscoverRoute: mockAdapterSupportsDiscoverRoute, - discoverRoute: mockDiscoverRoute, - stop: mockAdapterStop, - setChannelInterPAN: mockSetChannelInterPAN, - sendZclFrameInterPANToIeeeAddr: mocksendZclFrameInterPANToIeeeAddr, - sendZclFrameInterPANBroadcast: mocksendZclFrameInterPANBroadcast, - restoreChannelInterPAN: mockRestoreChannelInterPAN, - sendZdo: mockAdapterSendZdo, - }; - }); -}); - -jest.mock('../src/adapter/deconz/adapter/deconzAdapter', () => { - return jest.fn().mockImplementation(() => { - return {}; - }); -}); - -jest.mock('../src/adapter/zigate/adapter/zigateAdapter', () => { - return jest.fn().mockImplementation(() => { - return {}; - }); -}); +jest.mock('../src/adapter/z-stack/adapter/zStackAdapter', () => ({ + ZStackAdapter: jest.fn(() => ({ + hasZdoMessageOverhead: false, + manufacturerID: 0x0007, + on: (event, handler) => (mockAdapterEvents[event] = handler), + removeAllListeners: (event) => delete mockAdapterEvents[event], + start: mockAdapterStart, + getCoordinatorIEEE: mockAdapterGetCoordinatorIEEE, + reset: mockAdapterReset, + supportsBackup: mockAdapterSupportsBackup, + backup: () => { + return mockDummyBackup; + }, + getCoordinatorVersion: () => { + return {type: 'zStack', meta: {version: 1}}; + }, + getNetworkParameters: mockAdapterGetNetworkParameters, + waitFor: mockAdapterWaitFor, + sendZclFrameToEndpoint: mocksendZclFrameToEndpoint, + sendZclFrameToGroup: mocksendZclFrameToGroup, + sendZclFrameToAll: mocksendZclFrameToAll, + addInstallCode: mockAddInstallCode, + permitJoin: mockAdapterPermitJoin, + supportsDiscoverRoute: mockAdapterSupportsDiscoverRoute, + discoverRoute: mockDiscoverRoute, + stop: mockAdapterStop, + setChannelInterPAN: mockSetChannelInterPAN, + sendZclFrameInterPANToIeeeAddr: mocksendZclFrameInterPANToIeeeAddr, + sendZclFrameInterPANBroadcast: mocksendZclFrameInterPANBroadcast, + restoreChannelInterPAN: mockRestoreChannelInterPAN, + sendZdo: mockAdapterSendZdo, + })), +})); const TEMP_PATH = path.resolve('temp'); diff --git a/test/utils.test.ts b/test/utils.test.ts index 7e2ce24226..907c7169c8 100644 --- a/test/utils.test.ts +++ b/test/utils.test.ts @@ -1,6 +1,6 @@ import 'regenerator-runtime/runtime'; -import {Queue, Utils, Wait, Waitress} from '../src/utils'; +import {Queue, Utils, wait, Waitress} from '../src/utils'; import {logger, setLogger} from '../src/utils/logger'; const mockLogger = { @@ -38,12 +38,14 @@ describe('Utils', () => { }); it('Test wait', async () => { - const originalSetTimeout = setTimeout; - setTimeout = jest.fn(); - Wait(1000).then(() => {}); + const setTimeoutSpy = jest.spyOn(globalThis, 'setTimeout').mockImplementationOnce( + // @ts-expect-error mocked + () => {}, + ); + wait(1000).then(() => {}); expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000); - setTimeout = originalSetTimeout; + setTimeoutSpy.mockRestore(); }); it('Test waitress', async () => { @@ -93,7 +95,7 @@ describe('Utils', () => { // reject test const wait1_ = waitress.waitFor(1, 5000).start(); let error1_; - Wait(1000).then(() => { + wait(1000).then(() => { waitress.reject('one', 'drop'); }); try {