maximkulkin / esp-homekit

Apple HomeKit accessory server library for ESP-OPEN-RTOS
MIT License
1.1k stars 168 forks source link

Doubt on default starting value #156

Closed beckmx closed 4 years ago

beckmx commented 4 years ago

Hello everyone, I have been trying to report if the device is on/off depending on last saved state, however, for some reason, maybe because I am changing the incorrect value, the HomeKit_characteristic is always starting with the value defined in the beginning, the code looks like this:

homekit_characteristic_t initial_state = HOMEKIT_CHARACTERISTIC_(ON, false, .getter=led_on_get, .setter=led_on_set);

homekit_accessory_t *accessories[] = {
    HOMEKIT_ACCESSORY(.id=1, .category=homekit_accessory_category_lightbulb, .services=(homekit_service_t*[]){        
HOMEKIT_SERVICE(LIGHTBULB, .primary=true, .characteristics=(homekit_characteristic_t*[]){
            HOMEKIT_CHARACTERISTIC(NAME, "bulb"),
            &initial_state,
            NULL
        }),
        NULL
    }),
    NULL
};

void ir_codes_init(){
  int this_state = NULL;
  if(sysparam_get_int8("last_state", (int *)&this_state) == SYSPARAM_NOTFOUND){
    sysparam_set_int8("last_state", 0);
  } else if(sysparam_get_int8("last_state", (int *)&this_state) == SYSPARAM_OK){
    if (this_state == 1)
    {
      // modify the last state to boot from
      initial_state.value = HOMEKIT_BOOL(true);
    }
  }
}
maximkulkin commented 4 years ago

I think you can simplify this to this:

int this_state = 0;
sysparam_get_int8("last_state", &this_state);
initial_state.value = HOMEKIT_BOOL(this_state);

If sysparam_get_int8 fails, it will not modify output value and your initial value (0, not NULL) will be your default value. Regardless if values is not there or it is invalid, you can rely on default behavior (and default value) and you will fix sysparam with the next time you store it.

So, in your code if the value is not there, it is left as 0 (thus false).