matterbridge
Version:
Matterbridge plugin manager for Matter
425 lines • 19.4 kB
TypeScript
/**
* This file contains the class Matterbridge.
*
* @file matterbridge.ts
* @author Luca Liguori
* @date 2023-12-29
* @version 1.5.2
*
* Copyright 2023, 2024, 2025 Luca Liguori.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. *
*/
import EventEmitter from 'node:events';
import { AnsiLogger, LogLevel } from './logger/export.js';
import { NodeStorageManager, NodeStorage } from './storage/export.js';
import { MatterbridgeInformation, RegisteredPlugin, SanitizedExposedFabricInformation, SanitizedSessionInformation, SystemInformation } from './matterbridgeTypes.js';
import { PluginManager } from './pluginManager.js';
import { DeviceManager } from './deviceManager.js';
import { MatterbridgeEndpoint } from './matterbridgeEndpoint.js';
import { Frontend } from './frontend.js';
import { Endpoint as EndpointNode, LogLevel as MatterLogLevel, VendorId, StorageContext, StorageManager, StorageService, Environment, ServerNode } from '@matter/main';
import { AggregatorEndpoint } from '@matter/main/endpoints';
/**
* Represents the Matterbridge events.
*/
interface MatterbridgeEvent {
shutdown: [];
restart: [];
update: [];
startmemorycheck: [];
stopmemorycheck: [];
}
/**
* Represents the Matterbridge application.
*/
export declare class Matterbridge extends EventEmitter {
systemInformation: SystemInformation;
matterbridgeInformation: MatterbridgeInformation;
homeDirectory: string;
rootDirectory: string;
matterbridgeDirectory: string;
matterbridgePluginDirectory: string;
matterbridgeCertDirectory: string;
globalModulesDirectory: string;
matterbridgeVersion: string;
matterbridgeLatestVersion: string;
matterbridgeQrPairingCode: string | undefined;
matterbridgeManualPairingCode: string | undefined;
matterbridgeFabricInformations: SanitizedExposedFabricInformation[] | undefined;
matterbridgeSessionInformations: SanitizedSessionInformation[] | undefined;
matterbridgePaired: boolean | undefined;
bridgeMode: 'bridge' | 'childbridge' | 'controller' | '';
restartMode: 'service' | 'docker' | '';
profile: string | undefined;
shutdown: boolean;
edge: boolean;
private readonly failCountLimit;
log: AnsiLogger;
matterbrideLoggerFile: string;
matterLoggerFile: string;
plugins: PluginManager;
devices: DeviceManager;
frontend: Frontend;
nodeStorage: NodeStorageManager | undefined;
nodeContext: NodeStorage | undefined;
nodeStorageName: string;
private hasCleanupStarted;
private initialized;
private execRunningCount;
private startMatterInterval;
private checkUpdateInterval;
private checkUpdateTimeout;
private configureTimeout;
private reachabilityTimeout;
private sigintHandler;
private sigtermHandler;
private exceptionHandler;
private rejectionHandler;
environment: Environment;
matterStorageName: string;
matterStorageService: StorageService | undefined;
matterStorageManager: StorageManager | undefined;
matterbridgeContext: StorageContext | undefined;
mattercontrollerContext: StorageContext | undefined;
mdnsInterface: string | undefined;
ipv4address: string | undefined;
ipv6address: string | undefined;
port: number | undefined;
passcode: number | undefined;
discriminator: number | undefined;
serverNode: ServerNode<ServerNode.RootEndpoint> | undefined;
aggregatorNode: EndpointNode<AggregatorEndpoint> | undefined;
aggregatorVendorId: VendorId;
aggregatorVendorName: string;
aggregatorProductId: number;
aggregatorProductName: string;
protected static instance: Matterbridge | undefined;
protected constructor();
/**
* Emits an event of the specified type with the provided arguments.
*
* @template K - The type of the event.
* @param {K} eventName - The name of the event to emit.
* @param {...MatterbridgeEvent[K]} args - The arguments to pass to the event listeners.
* @returns {boolean} - Returns true if the event had listeners, false otherwise.
*/
emit<K extends keyof MatterbridgeEvent>(eventName: K, ...args: MatterbridgeEvent[K]): boolean;
/**
* Registers an event listener for the specified event type.
*
* @template K - The type of the event.
* @param {K} eventName - The name of the event to listen for.
* @param {(...args: MatterbridgeEvent[K]) => void} listener - The callback function to invoke when the event is emitted.
* @returns {this} - Returns the instance of the Matterbridge class.
*/
on<K extends keyof MatterbridgeEvent>(eventName: K, listener: (...args: MatterbridgeEvent[K]) => void): this;
/**
* Retrieves the list of Matterbridge devices.
* @returns {MatterbridgeEndpoint[]} An array of MatterbridgeDevice objects.
*/
getDevices(): MatterbridgeEndpoint[];
/**
* Retrieves the list of registered plugins.
* @returns {RegisteredPlugin[]} An array of RegisteredPlugin objects.
*/
getPlugins(): RegisteredPlugin[];
/**
* Set the logger logLevel for the Matterbridge classes.
* @param {LogLevel} logLevel The logger logLevel to set.
*/
setLogLevel(logLevel: LogLevel): Promise<void>;
/** ***********************************************************************************************************************************/
/** loadInstance() and cleanup() methods */
/** ***********************************************************************************************************************************/
/**
* Loads an instance of the Matterbridge class.
* If an instance already exists, return that instance.
*
* @param initialize - Whether to initialize the Matterbridge instance after loading.
* @returns The loaded Matterbridge instance.
*/
static loadInstance(initialize?: boolean): Promise<Matterbridge>;
/**
* Call cleanup().
* @deprecated This method is deprecated and is only used for jest tests.
*
*/
destroyInstance(): Promise<void>;
/**
* Initializes the Matterbridge application.
*
* @remarks
* This method performs the necessary setup and initialization steps for the Matterbridge application.
* It displays the help information if the 'help' parameter is provided, sets up the logger, checks the
* node version, registers signal handlers, initializes storage, and parses the command line.
*
* @returns A Promise that resolves when the initialization is complete.
*/
initialize(): Promise<void>;
/**
* Parses the command line arguments and performs the corresponding actions.
* @private
* @returns {Promise<void>} A promise that resolves when the command line arguments have been processed, or the process exits.
*/
private parseCommandLine;
/**
* Asynchronously loads and starts the registered plugins.
*
* This method is responsible for initializing and staarting all enabled plugins.
* It ensures that each plugin is properly loaded and started before the bridge starts.
*
* @returns {Promise<void>} A promise that resolves when all plugins have been loaded and started.
*/
private startPlugins;
/**
* Registers the process handlers for uncaughtException, unhandledRejection, SIGINT and SIGTERM.
* When either of these signals are received, the cleanup method is called with an appropriate message.
*/
private registerProcessHandlers;
/**
* Deregisters the process uncaughtException, unhandledRejection, SIGINT and SIGTERM signal handlers.
*/
private deregisterProcesslHandlers;
/**
* Logs the node and system information.
*/
private logNodeAndSystemInfo;
/**
* Creates a MatterLogger function to show the matter.js log messages in AnsiLogger (for the frontend).
*
* @returns {Function} The MatterLogger function.
*/
private createMatterLogger;
/**
* Creates a Matter File Logger.
*
* @param {string} filePath - The path to the log file.
* @param {boolean} [unlink=false] - Whether to unlink the log file before creating a new one.
* @returns {Function} - A function that logs formatted messages to the log file.
*/
createMatterFileLogger(filePath: string, unlink?: boolean): Promise<(_level: MatterLogLevel, formattedLog: string) => Promise<void>>;
/**
* Restarts the process by exiting the current instance and loading a new instance.
*/
restartProcess(): Promise<void>;
/**
* Shut down the process by exiting the current process.
*/
shutdownProcess(): Promise<void>;
/**
* Update matterbridge and and shut down the process.
*/
updateProcess(): Promise<void>;
/**
* Unregister all devices and shut down the process.
*/
unregisterAndShutdownProcess(): Promise<void>;
/**
* Reset commissioning and shut down the process.
*/
shutdownProcessAndReset(): Promise<void>;
/**
* Factory reset and shut down the process.
*/
shutdownProcessAndFactoryReset(): Promise<void>;
/**
* Cleans up the Matterbridge instance.
* @param message - The cleanup message.
* @param restart - Indicates whether to restart the instance after cleanup. Default is `false`.
* @returns A promise that resolves when the cleanup is completed.
*/
protected cleanup(message: string, restart?: boolean): Promise<void>;
/**
* Creates and configures the server node for an accessory plugin for a given device.
*
* @param {RegisteredPlugin} plugin - The plugin to configure.
* @param {MatterbridgeEndpoint} device - The device to associate with the plugin.
* @param {boolean} [start=false] - Whether to start the server node after adding the device.
* @returns {Promise<void>} A promise that resolves when the server node for the accessory plugin is created and configured.
*/
private createAccessoryPlugin;
/**
* Creates and configures the server node for a dynamic plugin.
*
* @param {RegisteredPlugin} plugin - The plugin to configure.
* @param {boolean} [start=false] - Whether to start the server node after adding the aggregator node.
* @returns {Promise<void>} A promise that resolves when the server node for the dynamic plugin is created and configured.
*/
private createDynamicPlugin;
/**
* Starts the Matterbridge in bridge mode.
* @private
* @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
*/
private startBridge;
/**
* Starts the Matterbridge in childbridge mode.
* @private
* @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
*/
private startChildbridge;
/**
* Starts the Matterbridge controller.
* @private
* @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
*/
protected startController(): Promise<void>;
/** ***********************************************************************************************************************************/
/** Matter.js methods */
/** ***********************************************************************************************************************************/
/**
* Starts the matter storage process with name Matterbridge.
* @returns {Promise<void>} - A promise that resolves when the storage process is started.
*/
private startMatterStorage;
/**
* Makes a backup copy of the specified matter storage directory.
*
* @param storageName - The name of the storage directory to be backed up.
* @param backupName - The name of the backup directory to be created.
* @returns {Promise<void>} A promise that resolves when the has been done.
*/
private backupMatterStorage;
/**
* Stops the matter storage.
* @returns {Promise<void>} A promise that resolves when the storage is stopped.
*/
private stopMatterStorage;
/**
* Creates a server node storage context.
*
* @param {string} pluginName - The name of the plugin.
* @param {string} deviceName - The name of the device.
* @param {DeviceTypeId} deviceType - The device type of the device.
* @param {number} vendorId - The vendor ID.
* @param {string} vendorName - The vendor name.
* @param {number} productId - The product ID.
* @param {string} productName - The product name.
* @param {string} [serialNumber] - The serial number of the device (optional).
* @returns {Promise<StorageContext>} The storage context for the commissioning server.
*/
private createServerNodeContext;
/**
* Creates a server node.
*
* @param {StorageContext} storageContext - The storage context for the server node.
* @param {number} [port=5540] - The port number for the server node. Defaults to 5540.
* @param {number} [passcode=20242025] - The passcode for the server node. Defaults to 20242025.
* @param {number} [discriminator=3850] - The discriminator for the server node. Defaults to 3850.
* @returns {Promise<ServerNode<ServerNode.RootEndpoint>>} A promise that resolves to the created server node.
*/
private createServerNode;
/**
* Starts the specified server node.
*
* @param {ServerNode} [matterServerNode] - The server node to start.
* @returns {Promise<void>} A promise that resolves when the server node has started.
*/
private startServerNode;
/**
* Stops the specified server node.
*
* @param {ServerNode} matterServerNode - The server node to stop.
* @returns {Promise<void>} A promise that resolves when the server node has stopped.
*/
private stopServerNode;
/**
* Advertises the specified server node.
*
* @param {ServerNode} [matterServerNode] - The server node to advertise.
* @returns {Promise<{ qrPairingCode: string, manualPairingCode: string } | undefined>} A promise that resolves to the pairing codes if the server node is advertised, or undefined if not.
*/
advertiseServerNode(matterServerNode?: ServerNode): Promise<{
qrPairingCode: string;
manualPairingCode: string;
} | undefined>;
/**
* Stop advertise the specified server node.
*
* @param {ServerNode} [matterServerNode] - The server node to advertise.
* @returns {Promise<void>} A promise that resolves when the server node has stopped advertising.
*/
stopAdvertiseServerNode(matterServerNode?: ServerNode): Promise<void>;
/**
* Creates an aggregator node with the specified storage context.
*
* @param {StorageContext} storageContext - The storage context for the aggregator node.
* @returns {Promise<EndpointNode<AggregatorEndpoint>>} A promise that resolves to the created aggregator node.
*/
private createAggregatorNode;
/**
* Adds a MatterbridgeEndpoint to the specified plugin.
*
* @param {string} pluginName - The name of the plugin.
* @param {MatterbridgeEndpoint} device - The device to add as a bridged endpoint.
* @returns {Promise<void>} A promise that resolves when the bridged endpoint has been added.
*/
addBridgedEndpoint(pluginName: string, device: MatterbridgeEndpoint): Promise<void>;
/**
* Removes a MatterbridgeEndpoint from the specified plugin.
*
* @param {string} pluginName - The name of the plugin.
* @param {MatterbridgeEndpoint} device - The device to remove as a bridged endpoint.
* @returns {Promise<void>} A promise that resolves when the bridged endpoint has been removed.
*/
removeBridgedEndpoint(pluginName: string, device: MatterbridgeEndpoint): Promise<void>;
/**
* Removes all bridged endpoints from the specified plugin.
*
* @param {string} pluginName - The name of the plugin.
* @param {number} [delay=0] - The delay in milliseconds between removing each bridged endpoint (default: 0).
* @returns {Promise<void>} A promise that resolves when all bridged endpoints have been removed.
*/
removeAllBridgedEndpoints(pluginName: string, delay?: number): Promise<void>;
/**
* Subscribes to the attribute change event for the given device and plugin.
* Specifically, it listens for changes in the 'reachable' attribute of the
* BridgedDeviceBasicInformationServer cluster server of the bridged device or BasicInformationServer cluster server of server node.
*
* @param {RegisteredPlugin} plugin - The plugin associated with the device.
* @param {MatterbridgeEndpoint} device - The device to subscribe to attribute changes for.
* @returns {Promise<void>} A promise that resolves when the subscription is set up.
*/
private subscribeAttributeChanged;
/**
* Sanitizes the fabric information by converting bigint properties to strings because `res.json` doesn't support bigint.
*
* @param {ExposedFabricInformation[]} fabricInfo - The array of exposed fabric information objects.
* @returns {SanitizedExposedFabricInformation[]} An array of sanitized exposed fabric information objects.
*/
private sanitizeFabricInformations;
/**
* Sanitizes the session information by converting bigint properties to strings because `res.json` doesn't support bigint.
*
* @param {SessionInformation[]} sessionInfo - The array of session information objects.
* @returns {SanitizedSessionInformation[]} An array of sanitized session information objects.
*/
private sanitizeSessionInformation;
/**
* Sets the reachability of the specified aggregator node bridged devices and trigger.
* @param {EndpointNode<AggregatorEndpoint>} aggregatorNode - The aggregator node to set the reachability for.
* @param {boolean} reachable - A boolean indicating the reachability status to set.
*/
private setAggregatorReachability;
private getVendorIdName;
/**
* Spawns a child process with the given command and arguments.
* @param {string} command - The command to execute.
* @param {string[]} args - The arguments to pass to the command (default: []).
* @returns {Promise<boolean>} A promise that resolves when the child process exits successfully, or rejects if there is an error.
*/
spawnCommand(command: string, args?: string[]): Promise<boolean>;
}
export {};
//# sourceMappingURL=matterbridge.d.ts.map