apple / HomeKitADK

Apache License 2.0
2.56k stars 232 forks source link

Characteristic value notifications via Subscription #78

Open lerebel103 opened 3 years ago

lerebel103 commented 3 years ago

Hi folks,

I am looking for clarifications on how a device should push new values for a characteristic when it changes at the node, so Homekit reflects the current state of the device. That is, if I have a switch that is physically flicked on or off, how do I push this change out to Homekit?

I can see how subscriptions callbacks are wired to handleSubscribe and handleUnsubscribe, for example:

const HAPBoolCharacteristic switchOnCharacteristic = {
    .format = kHAPCharacteristicFormat_Bool,
    .iid = kIID_SwitchOn,
    ...
    ...
    ...
    .callbacks = { .handleRead = HandleSwitchOnRead, .handleWrite = HandleSwitchOnWrite,
                   .handleSubscribe=HandleSwitchOnSubscribe, .handleUnsubscribe=HandleSwitchOnUnsubscribe,}
};

I can receive subscriptions/un-subscriptions requests fine and assume this is the mechanism by which change notifications can be pushed from the device's end. The subscription callback receives a HAPBoolCharacteristicSubscriptionRequest pointer, but how can I update the actual value of the characteristic later?

I am most certainly missing something obvious, thanks for any pointers.

izmmisha commented 3 years ago

Hi, after updating characteristic value you should use HAPAccessoryServerRaiseEvent to notify that it changed. Don't forget that it should be called from run loop, otherwise it will not work properly. You can use HAPPlatformRunLoopScheduleCallback from other threads for that.

lerebel103 commented 3 years ago

Hi @izmmisha, I see, I take this will trigger a read for a given characteristic via the assigned .handleRead callback and cause an update to go out. Thanks for the clarifications and advice on threading.