From 6f9fc769883e9df599f38e02dc4fc27d8c253246 Mon Sep 17 00:00:00 2001 From: Jatus Date: Fri, 26 Jan 2024 23:19:14 +0100 Subject: [PATCH] add ha addon support --- .devcontainer/devcontainer.json | 36 +++++++ .vscode/tasks.json | 20 ++++ .yamlint | 0 README.md | 21 ++-- .../.eslintrc.json | 0 .gitignore => matter-bridge/.gitignore | 3 +- .nvmrc => matter-bridge/.nvmrc | 0 .prettierrc => matter-bridge/.prettierrc | 0 matter-bridge/Dockerfile | 35 ++++++ Makefile => matter-bridge/Makefile | 0 matter-bridge/config.yml | 17 +++ .../docker-compose.yml | 0 .../dockerfile.standalone | 0 matter-bridge/options.yml | 5 + .../package-lock.json | 2 +- package.json => matter-bridge/package.json | 7 +- matter-bridge/run.sh | 3 + matter-bridge/schema.yml | 5 + .../src/home-assistant}/HAmiddleware.ts | 10 +- .../src/home-assistant}/HAssTypes.ts | 0 matter-bridge/src/index.ts | 43 ++++++++ .../src/mapper}/Mapper.ts | 11 +- .../src/mapper/devices/MapperType.ts | 14 +++ .../devices/lights/DimmerableLightDevice.ts | 28 +++-- .../devices/lights/OnOffLightDevice.ts | 22 ++-- .../src/mapper}/devices/lights/index.ts | 2 +- .../src/matter}/Bridge.ts | 24 +++-- .../src/matter}/index.ts | 13 ++- {src => matter-bridge/src}/utils/utils.ts | 1 + matter-bridge/tsconfig.json | 13 +++ repository.yml | 1 + src/index.ts | 37 ------- src/matter/devices/MapperType.ts | 7 -- src/matter/index.ts | 3 - tsconfig.json | 102 ------------------ 35 files changed, 278 insertions(+), 207 deletions(-) create mode 100644 .devcontainer/devcontainer.json create mode 100644 .vscode/tasks.json create mode 100644 .yamlint rename .eslintrc.json => matter-bridge/.eslintrc.json (100%) rename .gitignore => matter-bridge/.gitignore (70%) rename .nvmrc => matter-bridge/.nvmrc (100%) rename .prettierrc => matter-bridge/.prettierrc (100%) create mode 100644 matter-bridge/Dockerfile rename Makefile => matter-bridge/Makefile (100%) create mode 100644 matter-bridge/config.yml rename docker-compose.yml => matter-bridge/docker-compose.yml (100%) rename dockerfile => matter-bridge/dockerfile.standalone (100%) create mode 100644 matter-bridge/options.yml rename package-lock.json => matter-bridge/package-lock.json (99%) rename package.json => matter-bridge/package.json (87%) create mode 100644 matter-bridge/run.sh create mode 100644 matter-bridge/schema.yml rename {src/HA => matter-bridge/src/home-assistant}/HAmiddleware.ts (89%) rename {src/HA => matter-bridge/src/home-assistant}/HAssTypes.ts (100%) create mode 100644 matter-bridge/src/index.ts rename {src/matter => matter-bridge/src/mapper}/Mapper.ts (86%) create mode 100644 matter-bridge/src/mapper/devices/MapperType.ts rename {src/matter => matter-bridge/src/mapper}/devices/lights/DimmerableLightDevice.ts (72%) rename {src/matter => matter-bridge/src/mapper}/devices/lights/OnOffLightDevice.ts (69%) rename {src/matter => matter-bridge/src/mapper}/devices/lights/index.ts (53%) rename {src/matter/server => matter-bridge/src/matter}/Bridge.ts (85%) rename {src/matter/server => matter-bridge/src/matter}/index.ts (71%) rename {src => matter-bridge/src}/utils/utils.ts (97%) create mode 100644 matter-bridge/tsconfig.json create mode 100644 repository.yml delete mode 100644 src/index.ts delete mode 100644 src/matter/devices/MapperType.ts delete mode 100644 src/matter/index.ts delete mode 100644 tsconfig.json diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..c37cf5a --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,36 @@ +{ + "name": "devcontainer for add-on repositories", + "image": "ghcr.io/home-assistant/devcontainer:addons", + "appPort": [ + "7123:8123", + "7357:4357" + ], + "postStartCommand": "bash devcontainer_bootstrap", + "runArgs": [ + "-e", + "GIT_EDITOR=code --wait", + "--privileged" + ], + "containerEnv": { + "WORKSPACE_DIRECTORY": "${containerWorkspaceFolder}" + }, + "extensions": [ + "timonwong.shellcheck", + "esbenp.prettier-vscode" + ], + "mounts": [ + "type=volume,target=/var/lib/docker" + ], + "settings": { + "terminal.integrated.profiles.linux": { + "zsh": { + "path": "/usr/bin/zsh" + } + }, + "terminal.integrated.defaultProfile.linux": "zsh", + "editor.formatOnPaste": false, + "editor.formatOnSave": true, + "editor.formatOnType": true, + "files.trimTrailingWhitespace": true + } +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..36e373a --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,20 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Start Home Assistant", + "type": "shell", + "command": "supervisor_run", + "group": { + "kind": "test", + "isDefault": true + }, + "presentation": { + "reveal": "always", + "panel": "new" + }, + "problemMatcher": [] + } + ] + } + \ No newline at end of file diff --git a/.yamlint b/.yamlint new file mode 100644 index 0000000..e69de29 diff --git a/README.md b/README.md index 1d43c87..ccde059 100644 --- a/README.md +++ b/README.md @@ -8,30 +8,25 @@ This project serves as a proof of concept to connect HomeAssistant devices to Vo ### Prerequisites -- Docker installed -- Docker Compose installed -- Clone this repository +- Add this repository to your home assistant install ### Configuration -Inside the repository, create a `.env` file with the following variables set: - -- `HA_HOST`: HomeAssistant network address -- `HA_PORT`: HomeAssistant port -- `HA_ACCESS_TOKEN`: HomeAssistant access token - -Once the `.env` file is configured, run the project with `docker-compose up` for the initial setup. You'll need to scan the QR code in the terminal. +1. Start this addon, should autmatically get all your devices +2. Watch the logs for the QR code that is needed to pair it with your assistant +3. Pair it with your assistant with the matter procedure +4. Enjoy ## Key Features -- Supports two types of elements: lights and dimmable lights. +- Supports two types of elements: lights and dimmable lights. ## How to Contribute 1. Help organize the project and dependencies. 2. Add integrations for other devices. -3. Add some tests +3. Add some tests ## Known Issues and Limitations -- Currently, only lights (including dimmable lights) are working, and the system may be unstable. +- Currently, only lights (including dimmable lights) are working, and the system may be unstable. diff --git a/.eslintrc.json b/matter-bridge/.eslintrc.json similarity index 100% rename from .eslintrc.json rename to matter-bridge/.eslintrc.json diff --git a/.gitignore b/matter-bridge/.gitignore similarity index 70% rename from .gitignore rename to matter-bridge/.gitignore index bc52dc0..012de65 100644 --- a/.gitignore +++ b/matter-bridge/.gitignore @@ -1,3 +1,4 @@ node_modules deviceData -.env \ No newline at end of file +.env +build \ No newline at end of file diff --git a/.nvmrc b/matter-bridge/.nvmrc similarity index 100% rename from .nvmrc rename to matter-bridge/.nvmrc diff --git a/.prettierrc b/matter-bridge/.prettierrc similarity index 100% rename from .prettierrc rename to matter-bridge/.prettierrc diff --git a/matter-bridge/Dockerfile b/matter-bridge/Dockerfile new file mode 100644 index 0000000..24d8272 --- /dev/null +++ b/matter-bridge/Dockerfile @@ -0,0 +1,35 @@ +ARG BUILD_FROM=ghcr.io/hassio-addons/base:15.0.3 + +FROM node:18.19.0-alpine as buildbase + +COPY ./package.json ./ +COPY ./package-lock.json ./ +COPY ./src ./src +COPY ./tsconfig.json ./ +RUN npm install +RUN npm run build + +FROM node:18.19.0-alpine as deps + +COPY ./package.json ./ +COPY ./package-lock.json ./ +COPY ./src ./src +COPY ./tsconfig.json ./ +RUN npm install --production + + +FROM ${BUILD_FROM} as runenv + +COPY --from=buildbase /usr/lib /usr/lib +COPY --from=buildbase /usr/local/lib /usr/local/lib +COPY --from=buildbase /usr/local/include /usr/local/include +COPY --from=buildbase /usr/local/bin /usr/local/bin +COPY --from=buildbase ./build ./build +COPY --from=deps ./node_modules ./node_modules +COPY --from=deps ./package.json ./package.json + + +COPY run.sh / +RUN chmod a+x /run.sh + +CMD [ "/run.sh" ] \ No newline at end of file diff --git a/Makefile b/matter-bridge/Makefile similarity index 100% rename from Makefile rename to matter-bridge/Makefile diff --git a/matter-bridge/config.yml b/matter-bridge/config.yml new file mode 100644 index 0000000..93c4eed --- /dev/null +++ b/matter-bridge/config.yml @@ -0,0 +1,17 @@ +--- +name: 'HA Matter Bridge' +version: '1.0.0' +slug: ha-matter-bridge +description: This project serves as a proof of concept to connect HomeAssistant devices to Voice Assistants through the Matter Protocol. +init: false +arch: + - amd64 +ports: + 5540/tcp: 5540 + +hassio_role: homeassistant +hassio_api: true +homeassistant_api: true +auth_api: true +map: + - addon_config:rw \ No newline at end of file diff --git a/docker-compose.yml b/matter-bridge/docker-compose.yml similarity index 100% rename from docker-compose.yml rename to matter-bridge/docker-compose.yml diff --git a/dockerfile b/matter-bridge/dockerfile.standalone similarity index 100% rename from dockerfile rename to matter-bridge/dockerfile.standalone diff --git a/matter-bridge/options.yml b/matter-bridge/options.yml new file mode 100644 index 0000000..9aaa603 --- /dev/null +++ b/matter-bridge/options.yml @@ -0,0 +1,5 @@ +message: "settings" + settings: + - HA_HOST: localhost + HA_PORT: 8123 + HA_ACCESS_TOKEN: "your acces token" \ No newline at end of file diff --git a/package-lock.json b/matter-bridge/package-lock.json similarity index 99% rename from package-lock.json rename to matter-bridge/package-lock.json index 67eb23f..9709d75 100644 --- a/package-lock.json +++ b/matter-bridge/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "ha-matter-bridge", "version": "1.0.0", - "license": "ISC", + "license": "GPL-3.0", "dependencies": { "@project-chip/matter-node.js": "^0.7.4", "@project-chip/matter.js-tools": "^0.7.4", diff --git a/package.json b/matter-bridge/package.json similarity index 87% rename from package.json rename to matter-bridge/package.json index 4ccd19d..c64bcac 100644 --- a/package.json +++ b/matter-bridge/package.json @@ -4,10 +4,11 @@ "description": "", "main": "index.js", "scripts": { - "start": "ts-node ./src/index.ts" + "build": "tsc", + "start": "node ./build/index.js" }, "author": "", - "license": "ISC", + "license": "GPL-3.0", "dependencies": { "@project-chip/matter-node.js": "^0.7.4", "@project-chip/matter.js-tools": "^0.7.4", @@ -24,4 +25,4 @@ "eslint": "^8.56.0", "typescript": "^5.3.3" } -} +} \ No newline at end of file diff --git a/matter-bridge/run.sh b/matter-bridge/run.sh new file mode 100644 index 0000000..b6f3dbf --- /dev/null +++ b/matter-bridge/run.sh @@ -0,0 +1,3 @@ +#!/usr/bin/with-contenv bashio + +npm run start \ No newline at end of file diff --git a/matter-bridge/schema.yml b/matter-bridge/schema.yml new file mode 100644 index 0000000..92c2322 --- /dev/null +++ b/matter-bridge/schema.yml @@ -0,0 +1,5 @@ +message: str +settings: + - HA_HOST: str + HA_PORT: int + HA_ACCESS_TOKEN: str diff --git a/src/HA/HAmiddleware.ts b/matter-bridge/src/home-assistant/HAmiddleware.ts similarity index 89% rename from src/HA/HAmiddleware.ts rename to matter-bridge/src/home-assistant/HAmiddleware.ts index 68255d3..eb42dce 100644 --- a/src/HA/HAmiddleware.ts +++ b/matter-bridge/src/home-assistant/HAmiddleware.ts @@ -8,7 +8,6 @@ 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: { @@ -36,8 +35,7 @@ export class HAMiddleware { subscribe() { this.hassClient.on('state_changed', (event) => { this.logger.debug(event); - const toDo = - this.functionsToCallOnChange[event.data.entity_id]; + const toDo = this.functionsToCallOnChange[event.data.entity_id]; if (toDo) { toDo(event.data); } @@ -97,12 +95,6 @@ export class 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; } diff --git a/src/HA/HAssTypes.ts b/matter-bridge/src/home-assistant/HAssTypes.ts similarity index 100% rename from src/HA/HAssTypes.ts rename to matter-bridge/src/home-assistant/HAssTypes.ts diff --git a/matter-bridge/src/index.ts b/matter-bridge/src/index.ts new file mode 100644 index 0000000..ac99202 --- /dev/null +++ b/matter-bridge/src/index.ts @@ -0,0 +1,43 @@ +import { getParameter } from './utils/utils'; +import { Bridge, getBridge } from './matter'; +import { Logger } from '@project-chip/matter-node.js/log'; +import { HAMiddleware } from './home-assistant/HAmiddleware'; +import { addAllDevicesToBridge } from './mapper/Mapper'; + +const LOGGER = new Logger('Main'); +let HA_MIDDLEWARE: HAMiddleware; +let BRIDGE: Bridge; + +async function run() { + LOGGER.info('Startup ...'); + const token = getParameter('SUPERVISOR_TOKEN'); + if (!token) { + throw new Error('Missing auth token cannot run without it'); + } + HA_MIDDLEWARE = await HAMiddleware.getInstance({ + host: 'supervisor', + port: 80, + path: '/core/websocket', + token, + }); + LOGGER.info('Connected to home assistant'); + BRIDGE = getBridge(); + LOGGER.info('Creating the bridge'); + await addAllDevicesToBridge(HA_MIDDLEWARE, BRIDGE); + LOGGER.info('all devices added'); + BRIDGE.start(); +} + +run() + .then() + .catch((error) => { + console.error(error); + LOGGER.error(JSON.stringify(error)); + }); + +process.on('SIGINT', () => { + HA_MIDDLEWARE.stop(); + BRIDGE.stop() + .then(() => process.exit(0)) + .catch((err) => LOGGER.error(err)); +}); diff --git a/src/matter/Mapper.ts b/matter-bridge/src/mapper/Mapper.ts similarity index 86% rename from src/matter/Mapper.ts rename to matter-bridge/src/mapper/Mapper.ts index 61d338b..38fc88e 100644 --- a/src/matter/Mapper.ts +++ b/matter-bridge/src/mapper/Mapper.ts @@ -1,12 +1,15 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { addDimmerableLightDevice, addOnOffLightDevice } from './devices/lights'; -import { HassEntity } from '../HA/HAssTypes'; -import { Bridge, HAMiddleware } from '.'; +import { + addDimmerableLightDevice, + addOnOffLightDevice, +} from './devices/lights'; +import { HassEntity } from '../home-assistant/HAssTypes'; +import { Bridge } from '../matter'; import { Logger } from '@project-chip/matter-node.js/log'; +import { HAMiddleware } from '../home-assistant/HAmiddleware'; const LOGGER = new Logger('Mapper'); - const lightsMap: Map< string, (haEntity: HassEntity, haMiddleware: HAMiddleware, bridge: Bridge) => void diff --git a/matter-bridge/src/mapper/devices/MapperType.ts b/matter-bridge/src/mapper/devices/MapperType.ts new file mode 100644 index 0000000..3713751 --- /dev/null +++ b/matter-bridge/src/mapper/devices/MapperType.ts @@ -0,0 +1,14 @@ +import { Device } from '@project-chip/matter-node.js/device'; +import { HassEntity } from '../../home-assistant/HAssTypes'; + +import { HAMiddleware } from '../../home-assistant/HAmiddleware'; +import { Bridge } from '../../matter'; + +export type AddHaDeviceToBridge = ( + haEntity: HassEntity, + haMiddleware: HAMiddleware, + bridge: Bridge +) => Device; + +export { HAMiddleware } from '../../home-assistant/HAmiddleware'; +export { Bridge } from '../../matter'; diff --git a/src/matter/devices/lights/DimmerableLightDevice.ts b/matter-bridge/src/mapper/devices/lights/DimmerableLightDevice.ts similarity index 72% rename from src/matter/devices/lights/DimmerableLightDevice.ts rename to matter-bridge/src/mapper/devices/lights/DimmerableLightDevice.ts index 0be6c79..d77b97c 100644 --- a/src/matter/devices/lights/DimmerableLightDevice.ts +++ b/matter-bridge/src/mapper/devices/lights/DimmerableLightDevice.ts @@ -1,12 +1,21 @@ -import { Device, DimmableLightDevice } from "@project-chip/matter-node.js/device"; -import { MD5 } from "crypto-js"; -import { HAMiddleware, Bridge } from "../.."; -import { HassEntity, StateChangedEvent } from "../../../HA/HAssTypes"; -import { AddHaDeviceToBridge } from "../MapperType"; -import { Logger } from "@project-chip/matter-node.js/log"; +import { + Device, + DimmableLightDevice, +} from '@project-chip/matter-node.js/device'; +import { MD5 } from 'crypto-js'; +import { + HassEntity, + StateChangedEvent, +} from '../../../home-assistant/HAssTypes'; +import { AddHaDeviceToBridge, Bridge, HAMiddleware } from '../MapperType'; +import { Logger } from '@project-chip/matter-node.js/log'; const LOGGER = new Logger('DimmableLight'); -export const addDimmerableLightDevice: AddHaDeviceToBridge = (haEntity: HassEntity, haMiddleware: HAMiddleware, bridge: Bridge): Device => { +export const addDimmerableLightDevice: AddHaDeviceToBridge = ( + haEntity: HassEntity, + haMiddleware: HAMiddleware, + bridge: Bridge +): Device => { const device = new DimmableLightDevice(); const serialFromId = MD5(haEntity.entity_id).toString(); device.addOnOffListener((value, oldValue) => { @@ -36,7 +45,8 @@ export const addDimmerableLightDevice: AddHaDeviceToBridge = (haEntity: HassEnti (event: StateChangedEvent) => { device.setOnOff(event.data.new_state?.state === 'on'); device.setCurrentLevel( - (event.data.new_state?.attributes as never)['brightness']); + (event.data.new_state?.attributes as never)['brightness'] + ); } ); @@ -46,4 +56,4 @@ export const addDimmerableLightDevice: AddHaDeviceToBridge = (haEntity: HassEnti serialNumber: serialFromId, }); return device; -} \ No newline at end of file +}; diff --git a/src/matter/devices/lights/OnOffLightDevice.ts b/matter-bridge/src/mapper/devices/lights/OnOffLightDevice.ts similarity index 69% rename from src/matter/devices/lights/OnOffLightDevice.ts rename to matter-bridge/src/mapper/devices/lights/OnOffLightDevice.ts index 953fabb..5805ceb 100644 --- a/src/matter/devices/lights/OnOffLightDevice.ts +++ b/matter-bridge/src/mapper/devices/lights/OnOffLightDevice.ts @@ -1,13 +1,19 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { Device, OnOffLightDevice } from "@project-chip/matter-node.js/device"; -import { MD5 } from "crypto-js"; -import { HAMiddleware, Bridge } from "../.."; -import { HassEntity, StateChangedEvent } from "../../../HA/HAssTypes"; -import { AddHaDeviceToBridge } from "../MapperType"; -import { Logger } from "@project-chip/matter-node.js/log"; +import { Device, OnOffLightDevice } from '@project-chip/matter-node.js/device'; +import { MD5 } from 'crypto-js'; +import { + HassEntity, + StateChangedEvent, +} from '../../../home-assistant/HAssTypes'; +import { AddHaDeviceToBridge, Bridge, HAMiddleware } from '../MapperType'; +import { Logger } from '@project-chip/matter-node.js/log'; const LOGGER = new Logger('OnOfflIght'); -export const addOnOffLightDevice: AddHaDeviceToBridge = (haEntity: HassEntity, haMiddleware: HAMiddleware, bridge: Bridge): Device => { +export const addOnOffLightDevice: AddHaDeviceToBridge = ( + haEntity: HassEntity, + haMiddleware: HAMiddleware, + bridge: Bridge +): Device => { const device = new OnOffLightDevice(); const serialFromId = MD5(haEntity.entity_id).toString(); device.addOnOffListener((value, oldValue) => { @@ -36,4 +42,4 @@ export const addOnOffLightDevice: AddHaDeviceToBridge = (haEntity: HassEntity, h serialNumber: serialFromId, }); return device; -} \ No newline at end of file +}; diff --git a/src/matter/devices/lights/index.ts b/matter-bridge/src/mapper/devices/lights/index.ts similarity index 53% rename from src/matter/devices/lights/index.ts rename to matter-bridge/src/mapper/devices/lights/index.ts index 9aade4f..39c83c6 100644 --- a/src/matter/devices/lights/index.ts +++ b/matter-bridge/src/mapper/devices/lights/index.ts @@ -1,2 +1,2 @@ export * from './DimmerableLightDevice'; -export * from './OnOffLightDevice'; \ No newline at end of file +export * from './OnOffLightDevice'; diff --git a/src/matter/server/Bridge.ts b/matter-bridge/src/matter/Bridge.ts similarity index 85% rename from src/matter/server/Bridge.ts rename to matter-bridge/src/matter/Bridge.ts index 0bc2f0a..f14e1b6 100644 --- a/src/matter/server/Bridge.ts +++ b/matter-bridge/src/matter/Bridge.ts @@ -10,7 +10,7 @@ import { } 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 { 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'; @@ -24,14 +24,16 @@ export class Bridge { 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 productName = 'HomeAssistant'; private static readonly port = getIntParameter('port') ?? 5540; + private ready = false; private matterServer: MatterServer; private static instace: Bridge; private logger = new Logger('bridge'); private storageManager: StorageManager; private aggregator: Aggregator; + private commissioningServer: CommissioningServer | undefined; private constructor( matterServer: MatterServer, @@ -106,20 +108,22 @@ export class Bridge { typeof BridgedDeviceBasicInformationCluster.attributes > ) { - // const id = getIntParameter('uniqueid'); + if (!this.commissioningServer?.isCommissioned()) { + this.logger.warn('System not initialized, may cause crashes'); + } this.aggregator.addBridgedDevice(device, bridgedBasicInformation); } async start() { this.logger.info('Starting...'); - const commissioningServer = + this.commissioningServer = await this.setupContextAndCommissioningServer(); - commissioningServer.addDevice(this.aggregator); - this.matterServer.addCommissioningServer(commissioningServer); + this.commissioningServer.addDevice(this.aggregator); + this.matterServer.addCommissioningServer(this.commissioningServer); await this.matterServer.start(); this.logger.info('Listening'); - if (!commissioningServer.isCommissioned()) { - const pairingData = commissioningServer.getPairingCode(); + if (!this.commissioningServer.isCommissioned()) { + const pairingData = this.commissioningServer.getPairingCode(); const { qrPairingCode, manualPairingCode } = pairingData; console.log(QrCode.get(qrPairingCode)); @@ -136,5 +140,9 @@ export class Bridge { async stop() { this.matterServer.close(); + this.storageManager + .close() + .then(() => process.exit(0)) + .catch((err) => this.logger.error(err)); } } diff --git a/src/matter/server/index.ts b/matter-bridge/src/matter/index.ts similarity index 71% rename from src/matter/server/index.ts rename to matter-bridge/src/matter/index.ts index 83f32d2..d580965 100644 --- a/src/matter/server/index.ts +++ b/matter-bridge/src/matter/index.ts @@ -4,6 +4,8 @@ import { StorageManager, } from '@project-chip/matter-node.js/storage'; import { getParameter, hasParameter } from '@project-chip/matter-node.js/util'; +export { Bridge } from './Bridge'; +import { Bridge } from './Bridge'; let MATTER_SERVER: MatterServer; let STORAGE: StorageBackendDisk; @@ -14,7 +16,7 @@ export function serverSetup(): { storageManager: StorageManager; } { if (!(MATTER_SERVER && STORAGE && STORAGE_MANAGER)) { - const storageLocation = getParameter('store') || './deviceData'; + const storageLocation = getParameter('store') || '/config/deviceData'; STORAGE = new StorageBackendDisk( storageLocation, @@ -27,3 +29,12 @@ export function serverSetup(): { } return { matterServer: MATTER_SERVER, storageManager: STORAGE_MANAGER }; } + +export function getBridge(): Bridge { + const serverData = serverSetup(); + const bridge = Bridge.getInstance( + serverData.matterServer, + serverData.storageManager + ); + return bridge; +} diff --git a/src/utils/utils.ts b/matter-bridge/src/utils/utils.ts similarity index 97% rename from src/utils/utils.ts rename to matter-bridge/src/utils/utils.ts index b4fafcf..3590073 100644 --- a/src/utils/utils.ts +++ b/matter-bridge/src/utils/utils.ts @@ -2,6 +2,7 @@ import { ValidationError } from '@project-chip/matter.js/common'; import { execSync } from 'child_process'; const envVar = process.env; +console.debug({ envVar }); export function getParameter(name: string) { return envVar[name]; diff --git a/matter-bridge/tsconfig.json b/matter-bridge/tsconfig.json new file mode 100644 index 0000000..52bd7ad --- /dev/null +++ b/matter-bridge/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, + "module": "Node16" /* Specify what module code is generated. */, + "rootDir": "./src", + "outDir": "./build", /* Specify the root folder within your source files. */ + "moduleResolution": "node16" /* Specify how TypeScript looks up a file from a given module specifier. */, + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, + "strict": true /* Enable all strict type-checking options. */, + "skipLibCheck": true /* Skip type checking all .d.ts files. */, + }, +} diff --git a/repository.yml b/repository.yml new file mode 100644 index 0000000..7cf72e7 --- /dev/null +++ b/repository.yml @@ -0,0 +1 @@ +name: ha-matter-bridge diff --git a/src/index.ts b/src/index.ts deleted file mode 100644 index b955a4b..0000000 --- a/src/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Bridge, HAMiddleware, addAllDevicesToBridge } from './matter'; -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)); -}); diff --git a/src/matter/devices/MapperType.ts b/src/matter/devices/MapperType.ts deleted file mode 100644 index 729a1f7..0000000 --- a/src/matter/devices/MapperType.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { Device } from "@project-chip/matter-node.js/device"; -import { HAMiddleware, Bridge } from ".."; -import { HassEntity } from "../../HA/HAssTypes"; - -export type AddHaDeviceToBridge = (haEntity: HassEntity, - haMiddleware: HAMiddleware, - bridge: Bridge) => Device diff --git a/src/matter/index.ts b/src/matter/index.ts deleted file mode 100644 index 9f222ee..0000000 --- a/src/matter/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './server/Bridge'; -export * from '../HA/HAmiddleware'; -export * from './Mapper'; diff --git a/tsconfig.json b/tsconfig.json deleted file mode 100644 index 06f6852..0000000 --- a/tsconfig.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig to read more about this file */ - /* Projects */ - // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - /* Language and Environment */ - "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ - // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ - /* Modules */ - // "module": "commonjs", /* Specify what module code is generated. */ - "module": "Node16" /* Specify what module code is generated. */, - // // "rootDir": "./", /* Specify the root folder within your source files. */ - "moduleResolution": "node16" /* Specify how TypeScript looks up a file from a given module specifier. */, - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ - // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ - // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ - // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ - // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ - // "resolveJsonModule": true, /* Enable importing .json files. */ - // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ - // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ - // "outDir": "./", /* Specify an output folder for all emitted files. */ - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, - /* Type Checking */ - "strict": true /* Enable all strict type-checking options. */, - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ - // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */, - }, -}