Skip to content

Commit

Permalink
✨ Implement debounce for brightness updates
Browse files Browse the repository at this point in the history
Add debounce mechanism to StateManager for brightness updates

- Introduce _pendingBrightnessUpdate property to track update state
- Modify setBrightness method to cancel pending updates
- Update UI state immediately for responsive feedback
- Defer Home Assistant service call to reduce API requests
- Remove unnecessary comment at the file start

This change improves performance and user experience by reducing
the frequency of API calls while maintaining UI responsiveness.
  • Loading branch information
hyperb1iss committed Sep 12, 2024
1 parent c5fe30f commit b4bc953
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/state-manager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// src/state-manager.ts
import { State } from './state';
import { ColorManager } from './color-manager';
import {
Expand All @@ -15,6 +14,7 @@ export class StateManager {
private _config: Config;
private _state: State;
private _colorManager: ColorManager;
private _pendingBrightnessUpdate: Promise<void> | null = null;

constructor(config: Config, state: State) {
this._config = config;
Expand Down Expand Up @@ -115,13 +115,19 @@ export class StateManager {
}
}

async setBrightness(brightness: number) {
setBrightness(brightness: number) {
// Update the UI state immediately
this._state.brightness = brightness;
log.debug('StateManager: Brightness updated:', this._state.brightness);

// Cancel any previous pending brightness update
if (this._pendingBrightnessUpdate) {
this._pendingBrightnessUpdate = null;
}

if (this._hass && this._config) {
const haBrightness = convertCardBrightnessToHA(brightness);
await this._hass.callService('light', 'turn_on', {
this._pendingBrightnessUpdate = this._hass.callService('light', 'turn_on', {
entity_id: this._config.entity,
brightness: haBrightness,
});
Expand All @@ -146,4 +152,4 @@ export class StateManager {
});
}
}
}
}

0 comments on commit b4bc953

Please sign in to comment.