matterbridge-roborock-vacuum-plugin
Version:
Matterbridge Roborock Vacuum Plugin
149 lines (148 loc) • 7.76 kB
JavaScript
import { MatterbridgeDynamicPlatform } from 'matterbridge';
import * as axios from 'axios';
import { debugStringify } from 'matterbridge/logger';
import RoborockService from './roborockService.js';
import { PLUGIN_NAME } from './settings.js';
import ClientManager from './clientManager.js';
import { isSupportedDevice } from './helper.js';
import { PlatformRunner } from './platformRunner.js';
import { RoborockVacuumCleaner } from './rvc.js';
import { configurateBehavior } from './behaviorFactory.js';
import { RoborockAuthenticateApi, RoborockIoTApi } from './roborockCommunication/index.js';
import { getSupportedAreas, getSupportedScenes } from './initialData/index.js';
import NodePersist from 'node-persist';
import Path from 'node:path';
export class RoborockMatterbridgePlatform extends MatterbridgeDynamicPlatform {
robot;
rvcInterval;
roborockService;
clientManager;
platformRunner;
devices;
serialNumber;
cleanModeSettings;
enableExperimentalFeature;
persist;
constructor(matterbridge, log, config) {
super(matterbridge, log, config);
if (this.verifyMatterbridgeVersion === undefined || typeof this.verifyMatterbridgeVersion !== 'function' || !this.verifyMatterbridgeVersion('3.0.5')) {
throw new Error(`This plugin requires Matterbridge version >= "3.0.5". Please update Matterbridge from ${this.matterbridge.matterbridgeVersion} to the latest version in the frontend.`);
}
this.log.info('Initializing platform:', this.config.name);
if (config.whiteList === undefined)
config.whiteList = [];
if (config.blackList === undefined)
config.blackList = [];
if (config.enableExperimentalFeature === undefined)
config.enableExperimentalFeature = false;
const persistDir = Path.join(this.matterbridge.matterbridgePluginDirectory, PLUGIN_NAME, 'persist');
this.persist = NodePersist.create({ dir: persistDir });
this.clientManager = new ClientManager(this.log);
this.devices = new Map();
}
async onStart(reason) {
this.log.notice('onStart called with reason:', reason ?? 'none');
await this.ready;
await this.clearSelect();
await this.persist.init();
if (this.config.username === undefined || this.config.password === undefined) {
this.log.error('"username" and "password" are required in the config');
return;
}
const axiosInstance = axios.default ?? axios;
this.enableExperimentalFeature = this.config.enableExperimental;
if (this.enableExperimentalFeature?.enableExperimentalFeature && this.enableExperimentalFeature?.cleanModeSettings?.enableCleanModeMapping) {
this.cleanModeSettings = this.enableExperimentalFeature.cleanModeSettings;
this.log.notice(`Experimental Feature has been enable`);
this.log.notice(`cleanModeSettings ${debugStringify(this.cleanModeSettings)}`);
}
this.platformRunner = new PlatformRunner(this);
this.roborockService = new RoborockService(() => new RoborockAuthenticateApi(this.log, axiosInstance), (logger, ud) => new RoborockIoTApi(ud, logger), this.config.refreshInterval ?? 60, this.clientManager, this.log);
const username = this.config.username;
const password = this.config.password;
const userData = await this.roborockService.loginWithPassword(username, password);
this.log.debug('Initializing - userData:', debugStringify(userData));
const devices = await this.roborockService.listDevices(username);
this.log.notice('Initializing - devices: ', debugStringify(devices));
let vacuum = undefined;
if (this.config.whiteList.length > 0) {
const firstDUID = this.config.whiteList[0];
const duid = firstDUID.split('-')[1];
vacuum = devices.find((d) => d.duid == duid);
}
else {
vacuum = devices.find((d) => isSupportedDevice(d.data.model));
}
if (!vacuum) {
this.log.error('Initializing: No device found');
return;
}
await this.roborockService.initializeMessageClient(username, vacuum, userData);
this.devices.set(vacuum.serialNumber, vacuum);
this.serialNumber = vacuum.serialNumber;
await this.onConfigurateDevice();
this.log.notice('onStart finished');
}
async onConfigure() {
await super.onConfigure();
const self = this;
this.rvcInterval = setInterval(async () => {
self.platformRunner?.requestHomeData();
}, (this.config.refreshInterval ?? 60) * 1000 + 100);
}
async onConfigurateDevice() {
this.log.info('onConfigurateDevice start');
if (this.platformRunner === undefined || this.roborockService === undefined) {
this.log.error('Initializing: PlatformRunner or RoborockService is undefined');
return;
}
const vacuum = this.devices.get(this.serialNumber);
const username = this.config.username;
if (!vacuum || !username) {
this.log.error('Initializing: No supported devices found');
return;
}
const self = this;
await this.roborockService.initializeMessageClientForLocal(vacuum);
const roomMap = await this.platformRunner.getRoomMapFromDevice(vacuum);
this.log.debug('Initializing - roomMap: ', debugStringify(roomMap));
const behaviorHandler = configurateBehavior(vacuum.data.model, vacuum.duid, this.roborockService, this.cleanModeSettings, this.enableExperimentalFeature?.advancedFeature?.forceRunAtDefault ?? false, this.log);
this.roborockService.setSupportedAreas(vacuum.duid, getSupportedAreas(vacuum.rooms, roomMap, this.log));
let routineAsRoom = [];
if (this.enableExperimentalFeature?.enableExperimentalFeature && this.enableExperimentalFeature.advancedFeature?.showRoutinesAsRoom) {
routineAsRoom = getSupportedScenes(vacuum.scenes, this.log);
this.roborockService.setSupportedScenes(vacuum.duid, routineAsRoom);
}
this.robot = new RoborockVacuumCleaner(username, vacuum, roomMap, routineAsRoom, this.enableExperimentalFeature, this.log);
this.robot.configurateHandler(behaviorHandler);
this.log.info('vacuum:', debugStringify(vacuum));
this.setSelectDevice(this.robot.serialNumber ?? '', this.robot.deviceName ?? '', undefined, 'hub');
if (this.validateDevice(this.robot.deviceName ?? '')) {
await this.registerDevice(this.robot);
}
this.roborockService.setDeviceNotify(async function (messageSource, homeData) {
await self.platformRunner?.updateRobot(messageSource, homeData);
});
await this.roborockService.activateDeviceNotify(this.robot.device);
await self.platformRunner?.requestHomeData();
this.log.info('onConfigurateDevice finished');
}
async onShutdown(reason) {
await super.onShutdown(reason);
this.log.notice('onShutdown called with reason:', reason ?? 'none');
if (this.rvcInterval)
clearInterval(this.rvcInterval);
if (this.roborockService)
this.roborockService.stopService();
if (this.config.unregisterOnShutdown === true)
await this.unregisterAllDevices(500);
}
async onChangeLoggerLevel(logLevel) {
this.log.notice(`Change ${PLUGIN_NAME} log level: ${logLevel} (was ${this.log.logLevel})`);
this.log.logLevel = logLevel;
return Promise.resolve();
}
sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}