hestia/src/custom_modules/HestiaClasses.js

41 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-08-15 12:40:20 +00:00
export class State {
constructor(config) {
config.mqtt.subscriptions.forEach(subscription => {
this[subscription.name] = {
on: false,
topic: subscription.topic,
publisher: 'back',
power: (communicator) => {
2024-08-15 12:40:20 +00:00
// 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));
2024-08-15 12:40:20 +00:00
}
};
});
};
};
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) {
2024-08-15 12:40:20 +00:00
// 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);
}
});
}
}