- Added MQTT support to BedHardware, allowing for connection to MQTT brokers. - Created BedHardwareMQTT and BedHardwareSerial classes to handle respective connections. - Introduced a unified BedHardwareConfig interface for configuration management. - Implemented event forwarding from the underlying implementations to the BedHardware class. - Added MQTT adapter for handling MQTT connections and message subscriptions. - Updated package.json to include the mqtt library as a dependency. - Created a singleton MQTTService for managing MQTT client instances. - Enhanced error handling and logging throughout the BedHardware and MQTT classes.
72 lines
No EOL
1.8 KiB
TypeScript
72 lines
No EOL
1.8 KiB
TypeScript
import MQTT, { MQTTConfig } from '../adapter/mqtt';
|
|
|
|
// Default MQTT configuration for HiveMQ broker
|
|
const defaultConfig: MQTTConfig = {
|
|
host: 'broker.hivemq.com',
|
|
port: 1883,
|
|
username: undefined,
|
|
password: undefined
|
|
};
|
|
|
|
export const BASE_TOPIC = '/Jtkcp2N/pressurebed/';
|
|
|
|
// Singleton MQTT client instance
|
|
let mqttInstance: MQTT | null = null;
|
|
|
|
export class MQTTService {
|
|
private static instance: MQTT | null = null;
|
|
|
|
static async initialize(config?: Partial<MQTTConfig>): Promise<MQTT> {
|
|
if (!MQTTService.instance) {
|
|
const finalConfig = { ...defaultConfig, ...config };
|
|
MQTTService.instance = new MQTT();
|
|
await MQTTService.instance.initialize(finalConfig);
|
|
}
|
|
return MQTTService.instance;
|
|
}
|
|
|
|
static getInstance(): MQTT | null {
|
|
return MQTTService.instance;
|
|
}
|
|
|
|
static async disconnect(): Promise<void> {
|
|
if (MQTTService.instance) {
|
|
await MQTTService.instance.disconnect();
|
|
MQTTService.instance = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Factory function to get or create MQTT client
|
|
export async function getMQTTClient(config?: Partial<MQTTConfig>): Promise<MQTT> {
|
|
if (!mqttInstance) {
|
|
mqttInstance = new MQTT();
|
|
const finalConfig = { ...defaultConfig, ...config };
|
|
await mqttInstance.initialize(finalConfig);
|
|
}
|
|
return mqttInstance;
|
|
}
|
|
|
|
// Export the singleton instance getter
|
|
export function getMQTTInstance(): MQTT | null {
|
|
return mqttInstance;
|
|
}
|
|
|
|
// Cleanup function
|
|
export async function disconnectMQTT(): Promise<void> {
|
|
if (mqttInstance) {
|
|
await mqttInstance.disconnect();
|
|
mqttInstance = null;
|
|
}
|
|
}
|
|
|
|
// Export default configured client (lazy initialization)
|
|
const mqttService = {
|
|
async getClient(config?: Partial<MQTTConfig>): Promise<MQTT> {
|
|
return getMQTTClient(config);
|
|
},
|
|
getInstance: getMQTTInstance,
|
|
disconnect: disconnectMQTT
|
|
};
|
|
|
|
export default mqttService; |