107 lines
No EOL
2.6 KiB
TypeScript
107 lines
No EOL
2.6 KiB
TypeScript
import { EventEmitter } from 'events';
|
|
import { IBedHardware, PinState, PinChange, BedHardwareConfig } from '../types/bedhardware';
|
|
import { BedHardwareMQTT } from './BedHardwareMQTT';
|
|
|
|
/**
|
|
* BedHardware - MQTT-based bed hardware implementation
|
|
*
|
|
* Usage:
|
|
* MQTT (connects to broker.hivemq.com with base topic /Jtkcp2N/pressurebed/)
|
|
* const hardware = BedHardware.createSimpleMQTT();
|
|
*
|
|
* With custom topics
|
|
* const hardware = BedHardware.createMQTT({
|
|
* topics: {
|
|
* pinState: '/custom/pin/state',
|
|
* pinChange: '/custom/pin/change',
|
|
* initialization: '/custom/init'
|
|
* }
|
|
* });
|
|
*/
|
|
export class BedHardware extends EventEmitter implements IBedHardware {
|
|
private implementation: IBedHardware;
|
|
constructor(config: BedHardwareConfig) {
|
|
super();
|
|
|
|
if (config.type === 'mqtt') {
|
|
this.implementation = new BedHardwareMQTT({
|
|
topics: config.mqtt?.topics
|
|
});
|
|
} else {
|
|
throw new Error(`Unsupported hardware type: ${config.type}`);
|
|
}
|
|
|
|
// Forward all events from the implementation
|
|
this.forwardEvents();
|
|
}
|
|
|
|
private forwardEvents(): void {
|
|
const events = [
|
|
'connected',
|
|
'disconnected',
|
|
'error',
|
|
'initialized',
|
|
'pinInitialized',
|
|
'pinChanged'
|
|
];
|
|
|
|
events.forEach(event => {
|
|
this.implementation.on(event, (...args: unknown[]) => {
|
|
this.emit(event, ...args);
|
|
});
|
|
});
|
|
|
|
// Forward dynamic pin events (pin{number}Changed)
|
|
this.implementation.on('pinChanged', (pinChange: PinChange) => {
|
|
this.emit(`pin${pinChange.pin}Changed`, pinChange);
|
|
});
|
|
}
|
|
|
|
async connect(): Promise<void> {
|
|
return this.implementation.connect();
|
|
}
|
|
|
|
async disconnect(): Promise<void> {
|
|
return this.implementation.disconnect();
|
|
}
|
|
|
|
getPinState(pin: number): PinState | undefined {
|
|
return this.implementation.getPinState(pin);
|
|
}
|
|
|
|
getAllPinStates(): PinState[] {
|
|
return this.implementation.getAllPinStates();
|
|
}
|
|
|
|
isConnected(): boolean {
|
|
return this.implementation.isConnected();
|
|
}
|
|
// Static factory methods for convenience
|
|
static createMQTT(config?: {
|
|
topics?: {
|
|
pinState: string;
|
|
pinChange: string;
|
|
initialization: string;
|
|
};
|
|
}): BedHardware {
|
|
return new BedHardware({
|
|
type: 'mqtt',
|
|
mqtt: config
|
|
});
|
|
}
|
|
|
|
static createSimpleMQTT(): BedHardware {
|
|
return new BedHardware({
|
|
type: 'mqtt',
|
|
mqtt: {}
|
|
});
|
|
}
|
|
}
|
|
|
|
// Create and export a default MQTT instance
|
|
export const bedHardwareInstance = new BedHardware({
|
|
type: 'mqtt',
|
|
mqtt: {}
|
|
});
|
|
|
|
export * from '../types/bedhardware'; |