HAP-python icon indicating copy to clipboard operation
HAP-python copied to clipboard

Make AccessoryEncoder easier to subclass.

Open schinckel opened this issue 6 years ago • 3 comments

Currently, it's really not possible to extend the encoder: you need to copy-paste the method body, and then add your extra stuff you want to store in the state before you dump it to json.

I think each operation should be split into two, so it's possible to add/change the data that will be persisted (and handle that extra data on the way in), but also more easily switch the encoding method (for instance, to be able to use a non-JSON encoder).

class Encoder(object):
    def prepare_state(self, accessory):
        return { ... }

    def persist(self, fp, accessory):
        json.dump(self.prepare_state(accessory), fp)

    def restore_state(self, accessory, state):
        ...

    def load_into(self, fp, accessory):
        self.restore_state(accessory, json.load(fp))

I'm not sure if those are the best names, but hopefully get the idea.

schinckel avatar Apr 07 '18 11:04 schinckel

In my case, I wanted to store/restore the associated accessories that were added to a bridge dynamically, and needed to rewrite the entire class - there was not even a simple way to use the existing AccessoryEncoder class.

schinckel avatar Apr 07 '18 11:04 schinckel

Thanks for the feedback, I will try to think of something in the weekend and get back to you

ikalchev avatar Apr 13 '18 06:04 ikalchev

It would be nice to allow accessories to expose their state and provide notifications on when this state changes so it can be persisted. I see that Accessory class implements getstate method, but I do not see it being used anywhere (directly or indirectly - can find any pickling or similar).

My use case is TV accessory providing "ConfiguredName" characteristics which is a way to assign custom names to your TV and input sources, and they are supposed to be persisted across restarts.

maximkulkin avatar Aug 17 '19 22:08 maximkulkin