hap-fluent / initializeAccessory
Function: initializeAccessory()
ts
function initializeAccessory<TContext, Services>(accessory, initialState): FluentAccessory<TContext, Services>;Defined in: packages/hap-fluent/src/AccessoryHandler.ts:353
Initialize a PlatformAccessory with fluent service wrappers and apply initial characteristic values in a single call.
Type Parameters
| Type Parameter |
|---|
TContext extends UnknownContext |
Services extends Interfaces[] |
Parameters
| Parameter | Type | Description |
|---|---|---|
accessory | PlatformAccessory<TContext> | The Homebridge PlatformAccessory to augment. |
initialState | InternalServicesStateObject<Services> | Partial characteristic values keyed by camelCase service name (e.g., { lightbulb: { on: true, brightness: 100 } }). |
Returns
FluentAccessory<TContext, Services>
The same accessory reference typed as FluentAccessory.
Remarks
This is the recommended entry-point for the functional pattern. It:
- Calls
createServicesObject()on the existingaccessory.services. - Calls
applyInitialState()to set characteristic values frominitialState. - Merges the resulting services onto
accessoryviaObject.assign.
The returned value is the same reference as the input accessory — no new PlatformAccessory is created. You can therefore pass the returned value to api.registerPlatformAccessories() unchanged.
Services not listed in initialState are still wrapped and accessible via property access; they just won't have values set on their characteristics.
Use When
- Initializing an accessory in
configureAccessory()or your plugin constructor, especially when you want to set initial states at the same time. - You prefer the functional style (no class inheritance required).
Avoid When
- You need to add services dynamically after initialization — use getOrAddService for post-initialization service additions.
- You need to track accessory lifecycle beyond initialization — use AccessoryHandler for a stateful class-based approach.
Pitfalls
- NEVER call
initializeAccessory()more than once on the same accessory instance — the second call will overwrite the service wrappers created by the first call, and anyonGet/onSethandlers registered between calls will be lost. - NEVER pass characteristic keys that don't exist on the service in
initialState— they are silently ignored (no error is thrown), which can mask typos in characteristic names.
Example
typescript
import { initializeAccessory } from 'hap-fluent';
class MyLightAccessory {
constructor(
private readonly api: API,
private readonly platformAccessory: PlatformAccessory
) {
const accessory = initializeAccessory(platformAccessory, {
lightbulb: { on: false, brightness: 100 },
accessoryInformation: {
manufacturer: 'ACME',
model: 'Smart Light',
serialNumber: 'SN-001',
firmwareRevision: '1.0.0'
}
});
accessory.lightbulb.onGet('on', async () => this.getState());
accessory.lightbulb.onSet('on', async (v) => this.setState(v));
}
}