hestia/src/custom_modules/HestiaClasses.js

41 lines
1.4 KiB
JavaScript

export class State {
constructor(config) {
config.mqtt.subscriptions.forEach(subscription => {
this[subscription.name] = {
on: false,
topic: subscription.topic,
publisher: 'back',
power: (communicator) => {
// This *should* toggle the state, asks if state is true, if it is set it false, otherwise set it true
this[subscription.name].on ? this[subscription.name].on = false : this[subscription.name].on = true;
communicator.send(subscription.name, JSON.stringify(this));
}
};
});
};
};
export class Communicator {
constructor(state) {
// Connect to the MQTT Broker
this.client = mqtt.connect(config.mqtt.address);
// Subscribe to status topics
config.mqtt.subscriptions.forEach(subscription => {
this.client.subscribe(subscription.topic);
state[subscription.name].topic = subscription.topic;
});
}
// Publish a message to the MQTT Broker
send(topic, message) {
// Publish with retain flag set to true
this.client.publish(topic, message, { retain: true }, (err) => {
if (err) {
console.error('Failed to publish message:', err);
} else {
console.log('Message published and retained on topic:', topic);
}
});
}
}