Mixiaoxiao / Arduino-HomeKit-ESP8266

Native Apple HomeKit accessory implementation for the ESP8266 Arduino core.
MIT License
1.51k stars 277 forks source link

Inconsistent switch states & sudden activations #119

Open Lennart-O opened 3 years ago

Lennart-O commented 3 years ago

I'm noticing quite a few issues with my ESP8266s which were flashed with essentially the Switch example code. Sometimes Homekit reports a switch to be on - while the actual relay connected to the ESP hasn't latched. Sometimes it's other way round - the relay has latched, but Homekit reports the switch to be off. Sometimes the relay is latched all of a sudden - without any user engagement or automation programmed.

What could cause or trigger this behaviour? Any ideas?

Could it be related to this line? Does it make any difference to switch LOW and HIGH around?

Line 58 digitalWrite(PIN_SWITCH, on ? LOW : HIGH);

Or does it make sense to use this part of the following example extract in order to report the relay state to Homekit? But with bool switch_is_on = digitalRead(PIN_SWITCH) instead of true/false?

//report the switch value to HomeKit if it is changed (e.g. by a physical button) bool switch_is_on = true/false; cha_switch_on.value.bool_value = switch_is_on; homekit_characteristic_notify(&cha_switch_on, cha_switch_on.value);

Thanks :-)

sircuri commented 3 years ago

I have my setup like this. It uses both the setter and getter of the homekit_characteristic:

extern "C" homekit_server_config_t config;
extern "C" homekit_characteristic_t cha_switch_on;

bool relayStatus = false;

#define PIN_BUTTON 0
#define PIN_LED 13
#define PIN_RELAY 12

void setRelayState(bool on) {
  cha_switch_on.value.bool_value = on;  //sync the value
  digitalWrite(PIN_RELAY, on ? HIGH : LOW);
  digitalWrite(PIN_LED, on ? LOW : HIGH);
  relayStatus = on;
}

homekit_value_t cha_switch_on_getter() {
  return HOMEKIT_BOOL_CPP(relayStatus);
}

void cha_switch_on_setter(const homekit_value_t value) {
  bool on = value.bool_value;
  setRelayState(on);
}

void toggleRelay() {
  setRelayState(!relayStatus);
  homekit_characteristic_notify(&cha_switch_on, cha_switch_on.value);
}

void my_homekit_setup() {
  pinMode(PIN_LED, OUTPUT);
  pinMode(PIN_RELAY, OUTPUT);
  pinMode(PIN_BUTTON, INPUT);
  digitalWrite(PIN_LED, LOW);
  digitalWrite(PIN_RELAY, HIGH);
  relayStatus = true;

  cha_switch_on.getter = cha_switch_on_getter;
  cha_switch_on.setter = cha_switch_on_setter;
  arduino_homekit_setup(&config);
}
madmacks59 commented 2 years ago

If you're not using pull-up resisters and you didn't define them with something like this "pinMode(S1, INPUT_PULLUP);" then the pins could be floating and you'll get random HIGH or LOW reading, which would cause "interesting" results in your code... Just a thought...