Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
GermanBluefox committed Oct 26, 2023
1 parent be6b68d commit a078325
Show file tree
Hide file tree
Showing 14 changed files with 57 additions and 64 deletions.
1 change: 1 addition & 0 deletions io-package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
],
"enabled": true,
"compact": true,
"singleton": true,
"extIcon": "https://raw.githubusercontent.com/ioBroker/ioBroker.matter/master/admin/matter.png",
"type": "iot-systems",
"messagebox": true,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
},
"dependencies": {
"@iobroker/adapter-core": "^3.0.4",
"@project-chip/matter.js": "0.6.1-alpha.0-20231022-4bd17ea",
"@project-chip/matter-node.js": "0.6.1-alpha.0-20231022-4bd17ea",
"@iobroker/type-detector": "^3.0.5",
"axios": "^1.5.1",
Expand All @@ -30,10 +29,11 @@
"@alcalzone/release-script": "^3.6.0",
"@alcalzone/release-script-plugin-iobroker": "^3.6.0",
"@alcalzone/release-script-plugin-license": "^3.5.9",
"@iobroker/legacy-testing": "^1.0.1",
"@iobroker/legacy-testing": "^1.0.2",
"@types/iobroker": "^5.0.6",
"@types/jsonwebtoken": "^9.0.4",
"@types/node": "^20.8.8",
"colorette": "^2.0.20",
"puppeteer": "^21.4.1",
"@typescript-eslint/eslint-plugin": "^6.9.0",
"chai": "^4.3.10",
Expand Down
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ export class MatterAdapter extends utils.Adapter {
* The storage manager is then also used by the Matter server, so this code block in general is required,
* but you can choose a different storage backend as long as it implements the required API.
*/
this.storage = new StorageIoBroker(this, 'matter.0');
this.storage = new StorageIoBroker(this);
this.storageManager = new StorageManager(this.storage);
await this.storageManager.initialize();

Expand Down
12 changes: 6 additions & 6 deletions src/matter/BridgedDevicesNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Aggregator, DeviceTypes } from '@project-chip/matter-node.js/device';
import { GenericDevice } from '../lib';
import { BridgeDeviceDescription } from '../ioBrokerStorageTypes';

import matterDeviceFabric from './matterFabric';
import matterDeviceFactory from './matterFactory';
import VENDOR_IDS from './vendorIds';

export interface BridgeCreateOptions {
Expand Down Expand Up @@ -59,9 +59,9 @@ class BridgedDevices {
}

async init(): Promise<void> {
const commissionedObj = await this.adapter.getForeignObjectAsync(`matter.0.bridges.${this.parameters.uuid}.commissioned`);
const commissionedObj = await this.adapter.getObjectAsync(`bridges.${this.parameters.uuid}.commissioned`);
if (!commissionedObj) {
await this.adapter.setForeignObjectAsync(`matter.0.bridges.${this.parameters.uuid}.commissioned`, {
await this.adapter.setObjectAsync(`bridges.${this.parameters.uuid}.commissioned`, {
type: 'state',
common: {
name: 'commissioned',
Expand Down Expand Up @@ -144,7 +144,7 @@ class BridgedDevices {

for (let i = 1; i <= this.devices.length; i++) {
const ioBrokerDevice = this.devices[i - 1] as GenericDevice;
const mappingDevice = await matterDeviceFabric(ioBrokerDevice, this.devicesOptions[i - 1].name, this.devicesOptions[i - 1].uuid);
const mappingDevice = await matterDeviceFactory(ioBrokerDevice, this.devicesOptions[i - 1].name, this.devicesOptions[i - 1].uuid);
if (mappingDevice) {
const name = mappingDevice.getName();// `OnOff Socket ${i}`;
aggregator.addBridgedDevice(mappingDevice.getMatterDevice(), {
Expand Down Expand Up @@ -192,7 +192,7 @@ class BridgedDevices {
if (!this.commissioningServer.isCommissioned()) {
if (this.commissioned !== false) {
this.commissioned = false;
await this.adapter.setForeignStateAsync(`matter.0.bridges.${this.parameters.uuid}.commissioned`, this.commissioned, true);
await this.adapter.setStateAsync(`bridges.${this.parameters.uuid}.commissioned`, this.commissioned, true);
}
const pairingData = this.commissioningServer.getPairingCode();
// const { qrPairingCode, manualPairingCode } = pairingData;
Expand All @@ -209,7 +209,7 @@ class BridgedDevices {
} else {
if (this.commissioned !== true) {
this.commissioned = true;
await this.adapter.setForeignStateAsync(`matter.0.bridges.${this.parameters.uuid}.commissioned`, this.commissioned, true);
await this.adapter.setStateAsync(`bridges.${this.parameters.uuid}.commissioned`, this.commissioned, true);
}

const activeSession = this.commissioningServer.getActiveSessionInformation();
Expand Down
10 changes: 5 additions & 5 deletions src/matter/ControllerNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { DeviceTypes } from '@project-chip/matter-node.js/device';
import { GenericDevice } from '../lib';
import { DeviceDescription } from '../ioBrokerStorageTypes';

import matterDeviceFabric from './matterFabric';
import matterDeviceFactory from './matterFactory';
import VENDOR_IDS from './vendorIds';
import { NodeStateResponse, NodeStates } from './BridgedDevicesNode';

Expand Down Expand Up @@ -57,9 +57,9 @@ class Controller {
}

async init(): Promise<void> {
const commissionedObj = await this.adapter.getForeignObjectAsync(`matter.0.devices.${this.parameters.uuid}.commissioned`);
const commissionedObj = await this.adapter.getObjectAsync(`devices.${this.parameters.uuid}.commissioned`);
if (!commissionedObj) {
await this.adapter.setForeignObjectAsync(`matter.0.devices.${this.parameters.uuid}.commissioned`, {
await this.adapter.setObjectAsync(`devices.${this.parameters.uuid}.commissioned`, {
type: 'state',
common: {
name: 'commissioned',
Expand Down Expand Up @@ -125,7 +125,7 @@ class Controller {
if (!this.commissioningServer.isCommissioned()) {
if (this.commissioned !== false) {
this.commissioned = false;
await this.adapter.setForeignStateAsync(`matter.0.devices.${this.parameters.uuid}.commissioned`, this.commissioned, true);
await this.adapter.setStateAsync(`devices.${this.parameters.uuid}.commissioned`, this.commissioned, true);
}
const pairingData = this.commissioningServer.getPairingCode();
// const { qrPairingCode, manualPairingCode } = pairingData;
Expand All @@ -142,7 +142,7 @@ class Controller {
} else {
if (this.commissioned !== true) {
this.commissioned = true;
await this.adapter.setForeignStateAsync(`matter.0.devices.${this.parameters.uuid}.commissioned`, this.commissioned, true);
await this.adapter.setStateAsync(`devices.${this.parameters.uuid}.commissioned`, this.commissioned, true);
}

const activeSession = this.commissioningServer.getActiveSessionInformation();
Expand Down
17 changes: 7 additions & 10 deletions src/matter/DeviceNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { DeviceTypes } from '@project-chip/matter-node.js/device';
import { GenericDevice } from '../lib';
import { DeviceDescription } from '../ioBrokerStorageTypes';

import matterDeviceFabric from './matterFabric';
import matterDeviceFactory from './matterFactory';
import VENDOR_IDS from './vendorIds';
import { NodeStateResponse, NodeStates } from './BridgedDevicesNode';

Expand Down Expand Up @@ -46,9 +46,9 @@ class Device {
}

async init(): Promise<void> {
const commissionedObj = await this.adapter.getForeignObjectAsync(`matter.0.devices.${this.parameters.uuid}.commissioned`);
const commissionedObj = await this.adapter.getObjectAsync(`devices.${this.parameters.uuid}.commissioned`);
if (!commissionedObj) {
await this.adapter.setForeignObjectAsync(`matter.0.devices.${this.parameters.uuid}.commissioned`, {
await this.adapter.setObjectAsync(`devices.${this.parameters.uuid}.commissioned`, {
type: 'state',
common: {
name: 'commissioned',
Expand Down Expand Up @@ -82,8 +82,6 @@ class Device {
const productName = `ioBroker OnOff-Bridge`;
const productId = this.parameters.productid; // 0x8000;

const port = 5540;

const uniqueId = this.parameters.uuid.replace(/-/g, '').split('.').pop() || '0000000000000000';

/**
Expand All @@ -99,7 +97,6 @@ class Device {
* are called.
*/
this.commissioningServer = new CommissioningServer({
port,
deviceName,
deviceType,
passcode,
Expand All @@ -121,14 +118,14 @@ class Device {
* Create an instance of the matter device class you want to use.
* This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.
* To execute the on/off scripts defined as parameters, a listener for the onOff attribute is registered via the
* device specific API.
* device-specific API.
*
* The below logic also adds command handlers for commands of clusters that normally are handled device internally
* like identify that can be implemented with the logic when these commands are called.
*/

const ioBrokerDevice = this.device;
const mappingDevice = await matterDeviceFabric(ioBrokerDevice, this.deviceOptions.name, this.parameters.uuid);
const mappingDevice = await matterDeviceFactory(ioBrokerDevice, this.deviceOptions.name, this.parameters.uuid);
if (mappingDevice) {
this.commissioningServer.addDevice(mappingDevice.getMatterDevice());
} else {
Expand Down Expand Up @@ -156,7 +153,7 @@ class Device {
if (!this.commissioningServer.isCommissioned()) {
if (this.commissioned !== false) {
this.commissioned = false;
await this.adapter.setForeignStateAsync(`matter.0.devices.${this.parameters.uuid}.commissioned`, this.commissioned, true);
await this.adapter.setStateAsync(`devices.${this.parameters.uuid}.commissioned`, this.commissioned, true);
}
const pairingData = this.commissioningServer.getPairingCode();
// const { qrPairingCode, manualPairingCode } = pairingData;
Expand All @@ -173,7 +170,7 @@ class Device {
} else {
if (this.commissioned !== true) {
this.commissioned = true;
await this.adapter.setForeignStateAsync(`matter.0.devices.${this.parameters.uuid}.commissioned`, this.commissioned, true);
await this.adapter.setStateAsync(`devices.${this.parameters.uuid}.commissioned`, this.commissioned, true);
}

const activeSession = this.commissioningServer.getActiveSessionInformation();
Expand Down
29 changes: 12 additions & 17 deletions src/matter/StorageIoBroker.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,35 @@
import { fromJson, Storage, StorageError, SupportedStorageTypes, toJson } from '@project-chip/matter.js/storage';
import { fromJson, Storage, StorageError, SupportedStorageTypes, toJson } from '@project-chip/matter-node.js/storage';

export class StorageIoBroker implements Storage {
private readonly adapter: ioBroker.Adapter;
private readonly oid: string;
private data: Record<string, any> = {};
private clear: boolean = false;
private savingNumber: number = 1;
private readonly savingPromises: Record<string, Promise<void>> = {};
private readonly createdKeys: Record<string, boolean>;

constructor(adapter: ioBroker.Adapter, uuid: string, clear = false) {
constructor(adapter: ioBroker.Adapter, clear = false) {
this.adapter = adapter;
this.oid = `${uuid}.storage`;
this.clear = clear;
this.createdKeys = {};
}

async initialize(): Promise<void> {
let object;
try {
object = await this.adapter.getForeignObjectAsync(this.oid);
object = await this.adapter.getObjectAsync('storage');
} catch (error) {
// create object
object = {
_id: this.oid,
_id: 'storage',
type: 'folder',
common: {
expert: true,
name: 'Matter storage',
},
native: {}
};
await this.adapter.setForeignObjectAsync(this.oid, object as ioBroker.Object);
await this.adapter.setObjectAsync('storage', object as ioBroker.Object);
}

if (this.clear) {
Expand All @@ -40,19 +38,16 @@ export class StorageIoBroker implements Storage {
}

// read all keys
const states = await this.adapter.getForeignStatesAsync(`${this.oid}.*`);
const len = this.oid.length + 1;
const states = await this.adapter.getStatesAsync('storage.*');
const len = 'storage'.length + 1;
for (const key in states) {
this.createdKeys[key] = true;
this.data[key.substring(len)] = fromJson(states[key].val as string);
}
}

async clearAll(): Promise<void> {
const rows = await this.adapter.getObjectViewAsync('system', 'state', { startkey: `${this.oid}.`, endkey: `${this.oid}.\u9999` });
for (const row of rows.rows) {
await this.adapter.delForeignObjectAsync(row.id);
}
await this.adapter.delObjectAsync('storage', { recursive: true });
this.clear = false;
this.data = {};
}
Expand Down Expand Up @@ -94,15 +89,15 @@ export class StorageIoBroker implements Storage {
this.savingNumber = 1;
}
if (this.createdKeys[oid]) {
this.savingPromises[index] = this.adapter.setForeignStateAsync(`${this.oid}.${oid}`, value, true)
this.savingPromises[index] = this.adapter.setStateAsync(`storage.${oid}`, value, true)
.catch(error => this.adapter.log.error(`[STORAGE] Cannot save state: ${error}`))
.then(() => {
delete this.savingPromises[index];
});

} else {
this.savingPromises[index] =
this.adapter.setForeignObjectAsync(`${this.oid}.${oid}`, {
this.adapter.setObjectAsync(`storage.${oid}`, {
type: 'state',
common: {
name: 'key',
Expand All @@ -114,7 +109,7 @@ export class StorageIoBroker implements Storage {
},
native: {}
})
.then(() => this.adapter.setForeignStateAsync(`${this.oid}.${oid}`, value, true)
.then(() => this.adapter.setStateAsync(`storage.${oid}`, value, true)
.catch(error => this.adapter.log.error(`[STORAGE] Cannot save state: ${error}`))
.then(() => {
this.createdKeys[oid] = true;
Expand All @@ -129,7 +124,7 @@ export class StorageIoBroker implements Storage {
if (this.savingNumber >= 0xFFFFFFFF) {
this.savingNumber = 1;
}
this.savingPromises[index] = this.adapter.delForeignObjectAsync(`${this.oid}.${oid}`)
this.savingPromises[index] = this.adapter.delObjectAsync(`storage.${oid}`)
.catch(error => this.adapter.log.error(`[STORAGE] Cannot save state: ${error}`))
.then(() => {
delete this.createdKeys[oid];
Expand Down
2 changes: 1 addition & 1 deletion src/matter/devices/MappingDimmer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DimmableLightDevice, Device } from '@project-chip/matter.js/device';
import { DimmableLightDevice, Device } from '@project-chip/matter-node.js/device';

import { GenericDevice } from '../../lib';
import { PropertyType } from '../../lib/devices/GenericDevice';
Expand Down
2 changes: 1 addition & 1 deletion src/matter/devices/MappingLight.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { OnOffLightDevice, Device } from '@project-chip/matter.js/device';
import { OnOffLightDevice, Device } from '@project-chip/matter-node.js/device';

import { GenericDevice } from '../../lib';
import { PropertyType } from '../../lib/devices/GenericDevice';
Expand Down
2 changes: 1 addition & 1 deletion src/matter/devices/MappingSocket.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { OnOffPluginUnitDevice, Device } from '@project-chip/matter.js/device';
import { OnOffPluginUnitDevice, Device } from '@project-chip/matter-node.js/device';

import { GenericDevice } from '../../lib';
import { PropertyType } from '../../lib/devices/GenericDevice';
Expand Down
File renamed without changes.
30 changes: 15 additions & 15 deletions test/engineHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function deleteFoldersRecursive(path) {
}
}

function startIoBroker(adapterName, options) {
function startIoBrokerAdmin(options) {
options = options || {};
if (options.rootDir) {
rootDir = options.rootDir;
Expand All @@ -35,19 +35,19 @@ function startIoBroker(adapterName, options) {
// delete the old project
deleteFoldersRecursive(`${rootDir}tmp/screenshots`);

await setup.setOfflineState(`system.adapter.${adapterName}.0.alive`, { val: false });
await setup.setOfflineState(`system.adapter.admin.0.alive`, { val: false });

setup.setupController(null, async systemConfig => {
setup.setupController(['admin'], async systemConfig => {
// disable statistics and set license accepted
systemConfig.common.licenseConfirmed = true;
systemConfig.common.diag = 'none';
await setup.setObject('system.config', systemConfig);

// lets the web adapter start on port 18080
const config = await setup.getAdapterConfig(0, adapterName);
if (config && config.common) {
config.common.enabled = true;
await setup.setAdapterConfig(config.common, config.native, 0, adapterName);
// start admin
const adminConfig = await setup.getAdapterConfig(0, 'admin');
if (adminConfig && adminConfig.common) {
adminConfig.common.enabled = true;
await setup.setAdapterConfig(adminConfig.common, adminConfig.native, 0, 'admin');
}

setup.startController(
Expand All @@ -57,16 +57,16 @@ function startIoBroker(adapterName, options) {
async (_objects, _states) => {
objects = _objects;
states = _states;
setup.startCustomAdapter(adapterName, 0);
await checkIsWelcomeStartedAsync(states);
setup.startCustomAdapter('admin', 0);
await checkIsWelcomeStartedAsync('admin', states);
resolve({ objects, states });
});
});
});
}

async function stopIoBroker(adapterName) {
await setup.stopCustomAdapter(adapterName, 0);
async function stopIoBrokerAdmin() {
await setup.stopCustomAdapter('admin', 0);

await new Promise(resolve =>
setup.stopController(normalTerminated => {
Expand All @@ -88,7 +88,7 @@ function checkIsWelcomeStarted(adapterName, states, cb, counter) {
cb && cb();
} else {
setTimeout(() =>
checkIsWelcomeStarted(states, cb, counter - 1), 500);
checkIsWelcomeStarted(adapterName, states, cb, counter - 1), 500);
}
});
}
Expand All @@ -98,7 +98,7 @@ function checkIsWelcomeStartedAsync(adapterName, states, counter) {
}

module.exports = {
startIoBroker,
stopIoBroker,
startIoBrokerAdmin,
stopIoBrokerAdmin,
setOnStateChanged: cb => onStateChanged = cb
};
Loading

0 comments on commit a078325

Please sign in to comment.