
//sample domoticz/out payload:
//{
//   "Battery" : 255,
//   "RSSI" : 12,
//   "description" : "Deckenleuchte Arbeitszimmer\nSonoff-Touch-01",
//   "dtype" : "Light/Switch",
//   "id" : "00014121",
//   "idx" : 209,
//   "name" : "Arbeitszimmer Licht",
//   "nvalue" : 1,
//   "stype" : "Switch",
//   "switchType" : "On/Off",
//   "unit" : 1
//}
// -> we need idx and nvalue

void parseDomoticzOut() {
  domoticzOutParseData = false;
  domoticzOutParserBusy = true;
  unsigned long idx = 0;
  int16_t nvalue;
  int16_t found = 0;

  StaticJsonBuffer<450> jsonBuf;
  JsonObject& domoticz = jsonBuf.parseObject(domoticzOutPayload);
  idx = domoticz["idx"];
  nvalue = domoticz["nvalue"];

  for (int i = 0; i < sizeof(domoticzIdx); i++) {
    if ( idx == domoticzIdx[i] && idx != 0 ) {
      if ( dismissUpdateFromDomoticzTimeout == 0 || (lastSwitchSource[i] == 3 || (lastSwitchSource[i] < 3 && (millis() - lastSwitchTime[i]) > dismissUpdateFromDomoticzTimeout)) ) {
        // -> only perform operation if last switch command came from domoticz (lastSwitchSource==3) or is older than dismissUpdateFromDomoticzTimeout
        // disable this filtering if dismissUpdateFromDomoticzTimeout is set to 0
        Serial.print(domoticz_out_topic);
        Serial.print(" received: ");
        Serial.print(" idx=");
        Serial.print(idx);
        Serial.print(", nvalue=");
        Serial.println(nvalue);
        if (nvalue == 1) {
          updateDomoticz[i] = false; // prevent loop - when update came from domoticz, do not update domoticz state
          lastSwitchSource[i] = 3;
          relaisOn(i);
          updateDomoticz[i] = true; // enable domoticz updates again
        }
        else if (nvalue == 0) {
          updateDomoticz[i] = false; // prevent loop - when update came from domoticz, do not update domoticz state
          lastSwitchSource[i] = 3;
          relaisOff(i);
          updateDomoticz[i] = true; // enable domoticz updates again
        }
      }
    }
  }
  domoticzOutParserBusy = false;
}

void checkUseDomoticz() {
  if (domoticzIdx[0] != 0 || domoticzIdx[1] != 0 || domoticzIdx[2] != 0) {
    useDomoticz = true;
  }
  else {
    useDomoticz = false;
  }
}
