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,
|
2024-08-15 13:30:36 +00:00
|
|
|
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;
|
2024-08-15 13:30:36 +00:00
|
|
|
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;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2024-08-15 13:30:36 +00:00
|
|
|
// 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);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|