matterbridge-dyson-robot
Version:
A Matterbridge plugin that connects Dyson robot vacuums and air treatment devices to the Matter smart home ecosystem via their local or cloud MQTT APIs.
62 lines • 2.33 kB
JavaScript
// Matterbridge plugin for Dyson robot vacuum and air treatment devices
// Copyright © 2025 Alexander Thoukydides
import { isDeepStrictEqual } from 'util';
import { formatList } from './utils.js';
export class Changed {
log;
// The previous values
prevValues = new Map();
// Construct a new value change tracker
constructor(log) {
this.log = log;
}
// Check if the value has changed
isChanged(key, newValue) {
const oldValue = this.prevValues.get(key);
const changed = !isDeepStrictEqual(oldValue, newValue);
if (changed) {
this.log.debug(`${String(key)} changed: ${diffChanged(oldValue, newValue)}`);
this.setLast(key, newValue);
}
return changed;
}
// Set the last value
setLast(key, value) {
this.prevValues.set(key, structuredClone(value));
}
// Flush previous values, so anything new is considered a change
flush(key) {
if (key)
this.prevValues.delete(key);
else
this.prevValues.clear();
}
}
// Decorator to only invoke method if the parameter value has changed
export function ifValueChanged(originalMethod, context) {
function replacementMethod(value) {
if (this.changed.isChanged(context.name, value)) {
return originalMethod.call(this, value);
}
// Must return a Promise in async context, but also safe when R is void
return Promise.resolve();
}
return replacementMethod;
}
// Diff two values (that are not equal)
function diffChanged(oldValue, newValue) {
const isObject = (value) => typeof value === 'object' && value !== null;
const stringify = (value) => JSON.stringify(value);
// Handle non-object comparisons
if (!isObject(oldValue) || !isObject(newValue)) {
return `${stringify(oldValue)} → ${stringify(newValue)}`;
}
// Compare the individual properties of objects
const oldObj = oldValue;
const newObj = newValue;
const diffs = [...new Set([...Object.keys(oldObj), ...Object.keys(newObj)])]
.filter(key => !isDeepStrictEqual(oldObj[key], newObj[key]))
.map(key => `${key}: ${stringify(oldObj[key])} → ${stringify(newObj[key])}`);
return formatList(diffs);
}
//# sourceMappingURL=decorator-changed.js.map