void relaisToggle(byte relaisnr) {
  if (relais_state[relaisnr]) {
    relaisOff(relaisnr);
  }
  else {
    relaisOn(relaisnr);
  }
}
void relaisOn(byte relaisnr) {
  switchRelais(relaisnr, true);
  //relais_setState[relaisnr] = true;
}
void relaisOff(byte relaisnr) {
  switchRelais(relaisnr, false);
  //relais_setState[relaisnr] = false;
}

//void handleRelaisSwitching() {
//  // this must be called from loop()
//  // switches relais to values set in relais_setState[relaisnr] if != relais_state[relaisnr]
//  // otherwise the operation with all the status and mqtt messages would take too long and block mqtt callback if it is the source for the switch command
//  for (int i=0; i < sizeof(relais_setState); i++) {
//    if( relais_setState[i] != relais_state[i] ) {
//      bool toState;
//      if (relais_setState[i] == 1) toState = true;
//      else toState = false;
//      switchRelais(i, toState);
//    }
//  }
//}

void switchRelais(byte relaisnr, bool onoff) {
  lastSwitchTime[relaisnr] = millis();
  bool toState;

  if ( onoff ) toState = RELAISONSTATE;
  else toState = !RELAISONSTATE;

  digitalWrite(relais_pins[relaisnr], toState);
  relais_state[relaisnr] = onoff;

  Serial.print("Relais ");
  Serial.print(relaisnr + 1);
  Serial.print(" ");

  char* stateName;
  if (onoff) stateName = "ON";
  else stateName = "OFF";

  Serial.println(stateName);

  char tmp_topic_out[50];
  sprintf(tmp_topic_out, "%s/%d", mqtt_topic_out, relaisnr + 1);

  mqttclient.publish(tmp_topic_out, stateName);

  if (updateDomoticz[relaisnr]) {
    int idx = domoticzIdx[relaisnr];
    byte nvalue;
    if ( onoff ) nvalue = 1;
    else nvalue = 0;

    char domoticzJson[40];
    sprintf(domoticzJson, "{\"idx\":%d,\"nvalue\":%d}", idx, nvalue);
    mqttclient.publish(DOMOTICZ_IN_TOPIC, domoticzJson);

    Serial.print("sent idx=");
    Serial.print(idx);
    Serial.print(", nvalue=");
    Serial.print(nvalue);
    Serial.print(" to ");
    Serial.println(DOMOTICZ_IN_TOPIC);
  }
}

void relais_handleImpulseTimeout() {
  for (int i = 0; i < RELAIS_COUNT; i++) {
    if (relais_impulse[i] > 0) {
      if (relais_state[i] == true && (millis() - lastSwitchTime[i]) > relais_impulse[i]) {
        Serial.print("Relais ");
        Serial.print(i + 1);
        Serial.println(" impulse timeout reached");
        relaisOff(i);
      }
    }
  }
}

