first commit

This commit is contained in:
2024-01-23 23:39:46 +01:00
committed by Gianmarco Pettinato
commit 30187250c2
19 changed files with 6626 additions and 0 deletions

37
src/index.ts Normal file
View File

@@ -0,0 +1,37 @@
import { Bridge, HAMiddleware, addAllDevicesToBridge } from './matter/devices';
import { serverSetup } from './matter/server';
import { Logger } from '@project-chip/matter-node.js/log';
let LOGGER = new Logger('Main');
let BRIDGE: Bridge;
let HA_MIDDLEWARE: HAMiddleware;
const SERVER_DATA = serverSetup();
async function run() {
HA_MIDDLEWARE = await HAMiddleware.getInstance({
host: process.env.HA_HOST,
port: Number(process.env.HA_PORT),
token: process.env.HA_ACCESS_TOKEN,
});
BRIDGE = Bridge.getInstance(
SERVER_DATA.matterServer,
SERVER_DATA.storageManager
);
await addAllDevicesToBridge(HA_MIDDLEWARE, BRIDGE);
BRIDGE.start();
}
run().then().catch(LOGGER.error);
process.on('SIGINT', () => {
HA_MIDDLEWARE.stop();
BRIDGE.stop()
.then(() => {
// Pragmatic way to make sure the storage is correctly closed before the process ends.
SERVER_DATA.storageManager
.close()
.then(() => process.exit(0))
.catch((err) => LOGGER.error(err));
})
.catch((err) => LOGGER.error(err));
});

View File

@@ -0,0 +1,140 @@
import {
CommissioningServer,
MatterServer,
} from '@project-chip/matter-node.js';
import {
Aggregator,
ComposedDevice,
Device,
DeviceTypes,
} from '@project-chip/matter-node.js/device';
import { Logger } from '@project-chip/matter-node.js/log';
import { StorageManager } from '@project-chip/matter-node.js/storage';
import { getIntParameter, getParameter } from '../../utils/utils';
import { Time } from '@project-chip/matter-node.js/time';
import { VendorId } from '@project-chip/matter-node.js/datatype';
import { QrCode } from '@project-chip/matter-node.js/schema';
import {
AttributeInitialValues,
BridgedDeviceBasicInformationCluster,
} from '@project-chip/matter-node.js/cluster';
export class Bridge {
private static readonly deviceName =
getParameter('name') || 'Matter Bridge';
private static readonly deviceType = DeviceTypes.AGGREGATOR.code;
private static readonly vendorName = getParameter('vendor') || 'Jatus';
private static readonly productName = 'node-matter OnOff-Bridge';
private static readonly port = getIntParameter('port') ?? 5540;
private matterServer: MatterServer;
private static instace: Bridge;
private logger = new Logger('bridge');
private storageManager: StorageManager;
private aggregator: Aggregator;
private constructor(
matterServer: MatterServer,
storageManager: StorageManager
) {
this.matterServer = matterServer;
this.storageManager = storageManager;
this.aggregator = new Aggregator();
}
public static getInstance(
matterServer: MatterServer,
storageManager: StorageManager
): Bridge {
if (!Bridge.instace) {
this.instace = new Bridge(matterServer, storageManager);
}
return Bridge.instace;
}
private async setupContextAndCommissioningServer(): Promise<CommissioningServer> {
this.logger.info('setting up context');
await this.storageManager.initialize();
const deviceContextStorage =
this.storageManager.createContext('Bridge-Device');
const passcode =
getIntParameter('passcode') ??
deviceContextStorage.get('passcode', 20202021);
const discriminator =
getIntParameter('discriminator') ??
deviceContextStorage.get('discriminator', 3840);
const vendorId =
getIntParameter('vendorid') ??
deviceContextStorage.get('vendorid', 0xfff1);
const productId =
getIntParameter('productid') ??
deviceContextStorage.get('productid', 0x8000);
const uniqueId =
getIntParameter('uniqueid') ??
deviceContextStorage.get('uniqueid', Time.nowMs());
deviceContextStorage.set('passcode', passcode);
deviceContextStorage.set('discriminator', discriminator);
deviceContextStorage.set('vendorid', vendorId);
deviceContextStorage.set('productid', productId);
deviceContextStorage.set('uniqueid', uniqueId);
const commissioningServer = new CommissioningServer({
port: Bridge.port,
deviceName: Bridge.deviceName,
deviceType: Bridge.deviceType,
passcode,
discriminator,
basicInformation: {
vendorName: Bridge.vendorName,
vendorId: VendorId(vendorId),
nodeLabel: Bridge.productName,
productName: Bridge.productName,
productLabel: Bridge.productName,
productId,
serialNumber: `node-matter-${uniqueId}`,
},
});
return commissioningServer;
}
addDevice(
device: Device | ComposedDevice,
bridgedBasicInformation?: AttributeInitialValues<
typeof BridgedDeviceBasicInformationCluster.attributes
>
) {
// const id = getIntParameter('uniqueid');
this.aggregator.addBridgedDevice(device, bridgedBasicInformation);
}
async start() {
this.logger.info('Starting...');
const commissioningServer =
await this.setupContextAndCommissioningServer();
commissioningServer.addDevice(this.aggregator);
this.matterServer.addCommissioningServer(commissioningServer);
await this.matterServer.start();
this.logger.info('Listening');
if (!commissioningServer.isCommissioned()) {
const pairingData = commissioningServer.getPairingCode();
const { qrPairingCode, manualPairingCode } = pairingData;
console.log(QrCode.get(qrPairingCode));
this.logger.info(
`QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`
);
this.logger.info(`Manual pairing code: ${manualPairingCode}`);
} else {
this.logger.info(
'Device is already commissioned. Waiting for controllers to connect ...'
);
}
}
async stop() {
this.matterServer.close();
}
}

View File

@@ -0,0 +1,109 @@
import { Logger } from '@project-chip/matter-node.js/log';
import { HassEntity, HassEvent } from './HAssTypes';
import hass, { HassApi, HassWsOptions } from 'homeassistant-ws';
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export class HAMiddleware {
private logger = new Logger('HAMiddleware');
private hassClient: HassApi;
private static instance: HAMiddleware;
private connectionOpen: boolean = false;
private requestFulfilled: boolean = true;
private entities: { [k: string]: HassEntity } = {};
private functionsToCallOnChange: {
[k: string]: ((data: HassEvent['data']) => void) | undefined;
} = {};
async waitCompletition(): Promise<void> {
let waited = 0;
const timeOut = 5000;
while (!this.requestFulfilled && waited < timeOut) {
await sleep(1000);
waited += 1000;
}
}
stop(): void {
this.hassClient.rawClient.ws.close();
}
async callAService(domain: string, service: string, extraArgs?: unknown) {
this.requestFulfilled = false;
this.hassClient.callService(domain, service, extraArgs);
}
subscribe() {
this.hassClient.on('state_changed', (stateChangedEvent) => {
this.logger.debug(stateChangedEvent.data);
const toDo =
this.functionsToCallOnChange[stateChangedEvent.data.entity_id];
if (toDo) {
toDo(stateChangedEvent.data);
}
});
}
subscrieToDevice(deviceId: string, fn: (data: HassEvent['data']) => void) {
this.functionsToCallOnChange[deviceId] = fn;
this.logger.debug(this.functionsToCallOnChange);
}
async getStates(): Promise<{ [k: string]: HassEntity }> {
this.requestFulfilled = false;
const states = await this.hassClient.getStates();
const sorted = states.reduceRight<{ [k: string]: HassEntity }>(
(last, current) => {
last[current['entity_id']] = current;
return last;
},
{}
);
this.logger.debug({ getStates: sorted });
this.entities = sorted;
return this.entities;
}
async getStatesPartitionedByType(): Promise<{ [k: string]: HassEntity[] }> {
const states = await this.getStates();
const toReturn = Object.keys(states).reduceRight<{
[k: string]: HassEntity[];
}>((prev, current) => {
const key = current.split('.')[0];
if (!prev[key] && !Array.isArray(prev[key])) {
prev[key] = new Array<HassEntity>();
}
prev[key].push(states[current]);
return prev;
}, {});
this.logger.debug({ getStatesPartitionedByType: toReturn });
return toReturn;
}
async getServices() {
this.requestFulfilled = false;
const states = await this.hassClient.getServices();
return states;
}
private constructor(client: HassApi) {
this.hassClient = client;
}
public static async getInstance(
callerOptions?: Partial<HassWsOptions> | undefined
): Promise<HAMiddleware> {
if (!HAMiddleware.instance) {
const client = await hass(callerOptions);
HAMiddleware.instance = new HAMiddleware(client);
let waited = 0;
const timeOut = 5000;
while (!HAMiddleware.instance.connectionOpen && waited < timeOut) {
await sleep(1000);
waited += 1000;
}
}
return HAMiddleware.instance;
}
}

View File

@@ -0,0 +1,133 @@
// This file has no imports on purpose
// So it can easily be consumed by other TS projects
export type Error = 1 | 2 | 3 | 4;
export type UnsubscribeFunc = () => void;
export type MessageBase = {
id?: number;
type: string;
[key: string]: unknown;
};
export type Context = {
id: string;
user_id: string | null;
parent_id: string | null;
};
export type HassEventBase = {
origin: string;
time_fired: string;
context: Context;
};
export type HassEvent = HassEventBase & {
event_type: string;
data: { [key: string]: unknown };
};
export type StateChangedEvent = HassEventBase & {
event_type: 'state_changed';
data: {
entity_id: string;
new_state: HassEntity | null;
old_state: HassEntity | null;
};
};
export type HassConfig = {
latitude: number;
longitude: number;
elevation: number;
unit_system: {
length: string;
mass: string;
volume: string;
temperature: string;
pressure: string;
wind_speed: string;
accumulated_precipitation: string;
};
location_name: string;
time_zone: string;
components: string[];
config_dir: string;
allowlist_external_dirs: string[];
allowlist_external_urls: string[];
version: string;
config_source: string;
recovery_mode: boolean;
safe_mode: boolean;
state: 'NOT_RUNNING' | 'STARTING' | 'RUNNING' | 'STOPPING' | 'FINAL_WRITE';
external_url: string | null;
internal_url: string | null;
currency: string;
country: string | null;
language: string;
};
export type HassEntityBase = {
entity_id: string;
state: string;
last_changed: string;
last_updated: string;
attributes: HassEntityAttributeBase;
context: Context;
};
export type HassEntityAttributeBase = {
friendly_name?: string;
unit_of_measurement?: string;
icon?: string;
entity_picture?: string;
supported_features?: number;
hidden?: boolean;
assumed_state?: boolean;
device_class?: string;
state_class?: string;
restored?: boolean;
};
export type HassEntity = HassEntityBase & {
attributes: { [key: string]: unknown };
};
export type HassEntities = { [entity_id: string]: HassEntity };
export type HassService = {
name?: string;
description: string;
target?: object | null;
fields: {
[field_name: string]: {
name?: string;
description: string;
example: string | boolean | number;
selector?: object;
};
};
response?: { optional: boolean };
};
export type HassDomainServices = {
[service_name: string]: HassService;
};
export type HassServices = {
[domain: string]: HassDomainServices;
};
export type HassUser = {
id: string;
is_admin: boolean;
is_owner: boolean;
name: string;
};
export type HassServiceTarget = {
entity_id?: string | string[];
device_id?: string | string[];
area_id?: string | string[];
};

View File

@@ -0,0 +1,179 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
Device,
DimmableLightDevice,
OnOffLightDevice,
} from '@project-chip/matter.js/device';
import { HassEntity, HassEvent } from './HAssTypes';
import { Bridge, HAMiddleware } from '.';
import { MD5 } from 'crypto-js';
import { Logger } from '@project-chip/matter-node.js/log';
const DEVICE_ENTITY_MAP: {
[k: string]: { haEntity: HassEntity; device: Device };
} = {};
const LOGGER = new Logger('Mapper');
function addRGBLightDeviceToMap(
haEntity: HassEntity,
haMiddleware: HAMiddleware,
bridge: Bridge
): void {
const device = new DimmableLightDevice();
const serialFromId = MD5(haEntity.entity_id).toString();
device.addOnOffListener((value, oldValue) => {
if (value !== oldValue) {
haMiddleware.callAService('light', value ? 'turn_on' : 'turn_off', {
entity_id: haEntity.entity_id,
});
}
});
device.addCurrentLevelListener((value) => {
haMiddleware.callAService(
'light',
Number(value) > 0 ? 'turn_on' : 'turn_off',
{ entity_id: haEntity.entity_id, brightness: Number(value) }
);
});
bridge.addDevice(device, {
nodeLabel: haEntity.attributes['friendly_name'],
reachable: true,
serialNumber: serialFromId,
});
DEVICE_ENTITY_MAP[haEntity.entity_id] = { haEntity, device };
}
function addimmerableLightDeviceToMap(
haEntity: HassEntity,
haMiddleware: HAMiddleware,
bridge: Bridge
): void {
const device = new DimmableLightDevice();
const serialFromId = MD5(haEntity.entity_id).toString();
device.addOnOffListener((value, oldValue) => {
if (value !== oldValue) {
haMiddleware.callAService('light', value ? 'turn_on' : 'turn_off', {
entity_id: haEntity.entity_id,
});
}
});
device.addCommandHandler(
'identify',
async ({ request: { identifyTime } }) =>
LOGGER.info(
`Identify called for OnOffDevice ${haEntity.attributes['friendly_name']} with id: ${serialFromId} and identifyTime: ${identifyTime}`
)
);
device.addCurrentLevelListener((value) => {
haMiddleware.callAService(
'light',
Number(value) > 0 ? 'turn_on' : 'turn_off',
{ entity_id: haEntity.entity_id, brightness: Number(value) }
);
});
haMiddleware.subscrieToDevice(
haEntity.entity_id,
(data: HassEvent['data']) => {
device.setOnOff((data.new_state as any).state === 'on');
device.setCurrentLevel(
(data.new_state as any)['attributes']['brightness']
);
}
);
bridge.addDevice(device, {
nodeLabel: haEntity.attributes['friendly_name'],
reachable: true,
serialNumber: serialFromId,
});
DEVICE_ENTITY_MAP[haEntity.entity_id] = { haEntity, device };
}
function addOnOffLightDeviceToMap(
haEntity: HassEntity,
haMiddleware: HAMiddleware,
bridge: Bridge
) {
const device = new OnOffLightDevice();
const serialFromId = MD5(haEntity.entity_id).toString();
device.addOnOffListener((value, oldValue) => {
if (value !== oldValue) {
haMiddleware.callAService('light', value ? 'turn_on' : 'turn_off', {
entity_id: haEntity.entity_id,
});
}
});
device.addCommandHandler(
'identify',
async ({ request: { identifyTime } }) =>
LOGGER.info(
`Identify called for OnOffDevice ${haEntity.attributes['friendly_name']} with id: ${serialFromId} and identifyTime: ${identifyTime}`
)
);
haMiddleware.subscrieToDevice(
haEntity.entity_id,
(data: HassEvent['data']) => {
device.setOnOff((data.new_state as any).state === 'on');
}
);
bridge.addDevice(device, {
nodeLabel: haEntity.attributes['friendly_name'],
reachable: true,
serialNumber: serialFromId,
});
DEVICE_ENTITY_MAP[haEntity.entity_id] = { haEntity, device };
}
const lightsMap: Map<
string,
(haEntity: HassEntity, haMiddleware: HAMiddleware, bridge: Bridge) => void
> = new Map<
string,
(haEntity: HassEntity, haMiddleware: HAMiddleware, bridge: Bridge) => void
>([
['onoff', addOnOffLightDeviceToMap],
['rgb', addRGBLightDeviceToMap],
['brightness', addimmerableLightDeviceToMap],
]);
function setLights(
lights: HassEntity[],
haMiddleware: HAMiddleware,
bridge: Bridge
) {
lights.forEach((entity) => {
LOGGER.info({ colormodes: entity.attributes['supported_color_modes'] });
const key = (entity.attributes['supported_color_modes'] as string[])[0];
LOGGER.info({ key });
const lightBuildFunction = lightsMap.get(key);
if (!lightBuildFunction) {
throw new Error('Missing ' + key);
}
return lightBuildFunction(entity, haMiddleware, bridge);
});
}
async function setHasEnties(
haMiddleware: HAMiddleware,
bridge: Bridge
): Promise<void> {
const entities = await haMiddleware.getStatesPartitionedByType();
LOGGER.info({ entities });
if (entities['light']) {
LOGGER.info('adding ', entities['light'].length, 'light devices');
setLights(entities['light'], haMiddleware, bridge);
}
}
export async function addAllDevicesToBridge(
haMiddleware: HAMiddleware,
bridge: Bridge
): Promise<void> {
await setHasEnties(haMiddleware, bridge);
haMiddleware.subscribe();
}

View File

@@ -0,0 +1,3 @@
export * from './Bridge';
export * from './HAmiddleware';
export * from './Mapper';

View File

@@ -0,0 +1,29 @@
import { MatterServer } from '@project-chip/matter-node.js';
import {
StorageBackendDisk,
StorageManager,
} from '@project-chip/matter-node.js/storage';
import { getParameter, hasParameter } from '@project-chip/matter-node.js/util';
let MATTER_SERVER: MatterServer;
let STORAGE: StorageBackendDisk;
let STORAGE_MANAGER: StorageManager;
export function serverSetup(): {
matterServer: MatterServer;
storageManager: StorageManager;
} {
if (!(MATTER_SERVER && STORAGE && STORAGE_MANAGER)) {
const storageLocation = getParameter('store') || './deviceData';
STORAGE = new StorageBackendDisk(
storageLocation,
hasParameter('clearstorage')
);
STORAGE_MANAGER = new StorageManager(STORAGE);
MATTER_SERVER = new MatterServer(STORAGE_MANAGER, {
mdnsInterface: getParameter('netinterface'),
});
}
return { matterServer: MATTER_SERVER, storageManager: STORAGE_MANAGER };
}

32
src/utils/utils.ts Normal file
View File

@@ -0,0 +1,32 @@
import { ValidationError } from '@project-chip/matter.js/common';
import { execSync } from 'child_process';
const envVar = process.env;
export function getParameter(name: string) {
return envVar[name];
}
export function hasParameter(name: string) {
return getIntParameter(name) !== undefined;
}
export function getIntParameter(name: string) {
const value = getParameter(name);
if (value === undefined) return undefined;
const intValue = parseInt(value, 10);
if (isNaN(intValue))
throw new ValidationError(
`Invalid value for parameter ${name}: ${value} is not a number`
);
return intValue;
}
export function commandExecutor(scriptParamName: string) {
const script = getParameter(scriptParamName);
if (script === undefined) return undefined;
return () =>
console.log(
`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`
);
}