|
| 1 | +import { ReplaySubject } from 'rxjs'; |
| 2 | +import UnitModule, { |
| 3 | + type UnitModuleObservables, |
| 4 | + type UnitModuleOptions, |
| 5 | + type UnitModuleSetupContext, |
| 6 | + type UnitModuleState |
| 7 | +} from '../UnitModule'; |
| 8 | +import type Unit from '../Unit'; |
| 9 | + |
| 10 | +interface Obervables extends UnitModuleObservables { |
| 11 | + active$: ReplaySubject<boolean>; |
| 12 | +} |
| 13 | + |
| 14 | +interface Options extends UnitModuleOptions { |
| 15 | + onTime?: number; // 0 → Mitternacht, 0.25 → 6 Uhr, 0.5 → Mittag, 0.75 → 18 Uhr, 1 → Mitternacht wieder |
| 16 | + offTime?: number; // 0 → Mitternacht, 0.25 → 6 Uhr, 0.5 → Mittag, 0.75 → 18 Uhr, 1 → Mitternacht wieder |
| 17 | +} |
| 18 | + |
| 19 | +interface State extends UnitModuleState { |
| 20 | + active?: boolean; |
| 21 | +} |
| 22 | +export default class LightUnitModule extends UnitModule< |
| 23 | + Options, |
| 24 | + State, |
| 25 | + Obervables |
| 26 | +> { |
| 27 | + static override TYPE = 'light'; |
| 28 | + |
| 29 | + private active: boolean = false; |
| 30 | + |
| 31 | + constructor(unit: Unit, options: Options, state: State, debug: boolean) { |
| 32 | + super(unit, options, state, debug); |
| 33 | + //#region observables |
| 34 | + this.observables.active$ = new ReplaySubject<boolean>(); |
| 35 | + this.observables.active$.next(this.active); |
| 36 | + //#endregion |
| 37 | + } |
| 38 | + |
| 39 | + override async setup(context: UnitModuleSetupContext) { |
| 40 | + this.subscription.add( |
| 41 | + context.room?.app.modules.time.observables.dayTime$.subscribe( |
| 42 | + (dayTime: number) => { |
| 43 | + const isOn = |
| 44 | + dayTime >= (this.options.onTime ?? 0.7) || |
| 45 | + dayTime <= (this.options.offTime ?? 0.25); |
| 46 | + if (isOn !== this.isOn()) { |
| 47 | + this.active = isOn; |
| 48 | + if (isOn) { |
| 49 | + this.on(); |
| 50 | + } else { |
| 51 | + this.off(); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + ) |
| 56 | + ); |
| 57 | + |
| 58 | + return context.mesh; |
| 59 | + } |
| 60 | + |
| 61 | + isOn() { |
| 62 | + return this.state.active ?? this.active; |
| 63 | + } |
| 64 | + |
| 65 | + on() { |
| 66 | + this.observables.active$.next(true); |
| 67 | + } |
| 68 | + |
| 69 | + off() { |
| 70 | + this.observables.active$.next(false); |
| 71 | + } |
| 72 | +} |
0 commit comments