m2-inno-bedpressure/services/mqttService.ts
Siwat Sirichai 4ae5196ef1 feat: Add Swagger documentation support and restructure routes
- Added @elysiajs/swagger dependency to package.json for API documentation.
- Removed the old bed router and replaced it with a new history router.
- Created a new state router to manage WebSocket connections and state updates.
- Implemented a comprehensive state management system with the StateManager service.
- Introduced AlarmManagement and BedService services for handling alarms and sensor readings.
- Established a new MQTT service for managing MQTT connections and subscriptions.
- Created an AlarmStateStore to manage volatile alerts and their states.
- Defined FrontendState types for structured state management and WebSocket messaging.
2025-06-21 18:56:34 +07:00

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;