
//sample domoticz/out payload switch:
//{
//   "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



//sample domoticz/out payload thermostat:
//{
//  "command": "udevice",
//  "idx": 219,
//  "nvalue": 0,
//  "svalue": "24.00"
//}
//
//
//domoticz/out:
//{
//   "Battery" : 255,
//   "RSSI" : 12,
//   "description" : "",
//   "dtype" : "Thermostat",
//   "id" : "001412B",
//   "idx" : 219,
//   "meterType" : "Energy",
//   "name" : "Raumthermostat Wohnzimmer",
//   "nvalue" : 0,
//   "stype" : "SetPoint",
//   "svalue1" : "22.00",
//   "unit" : 1
//} -> we need idx and svalue

//sample domoticz/out payload selector switch:
//{
//   "Battery" : 255,
//   "LevelActions" : "||",
//   "LevelNames" : "Off|Normal|Nachtabsenkung",
//   "LevelOffHidden" : "false",
//   "RSSI" : 12,
//   "SelectorStyle" : "0",
//   "description" : "",
//   "dtype" : "Light/Switch",
//   "id" : "0001415C",
//   "idx" : 268,
//   "name" : "Heizung Betriebsart",
//   "nvalue" : 2,
//   "stype" : "Selector Switch",
//   "svalue1" : "10",
//   "switchType" : "Selector",
//   "unit" : 1
//}
// -> we need idx and svalue ("0"="Off", "10"="Normal", "20"="Nachtabsenkung"


// counter for automatic domoticz update used in function updateDomoticzDevices()
// initially set to domoticzUpdateInterval, to ensure soon update after boot
int count_sendToDomoticz_thermostat = domoticzUpdateInterval;
int count_sendToDomoticz_heatingMode = domoticzUpdateInterval;


void parseDomoticzOut() {
  domoticzOutParseData = false;
  domoticzOutParserBusy = true;
  unsigned long idx = 0;
  int16_t nvalue;
  char svalue[21];
  int16_t found = 0;

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

  yield();

  if (idx == domoticzIdx_Thermostat || idx == domoticzIdx_ThermostatMode) {
    nvalue = domoticz["nvalue"];
    strlcpy(svalue, domoticz["svalue1"] | "", 21);

    if ( idx == domoticzIdx_Thermostat ) {
      if ((millis() - lastUpdate_setTemp) > dismissUpdateFromDomoticzTimeout) {
        Serial.print(domoticz_out_topic);
        Serial.print(" received: ");
        Serial.print(" idx=");
        Serial.print(idx);
        Serial.print(", nvalue=");
        Serial.print(nvalue);
        Serial.print(", svalue=");
        Serial.println(svalue);

        yield();

        float valueFloat = round(atof(svalue) * 2.0) / 2.0;
        setTempTo(valueFloat);
        lastValueChange = 0; // force saving of values without delay
        checkValuesChanged();
      }
    }
    else if ( idx == domoticzIdx_ThermostatMode ) {
      if ((millis() - lastUpdate_heatingMode) > dismissUpdateFromDomoticzTimeout) {
        Serial.print(domoticz_out_topic);
        Serial.print(" received: ");
        Serial.print(" idx=");
        Serial.print(idx);
        Serial.print(", nvalue=");
        Serial.print(nvalue);
        Serial.print(", svalue=");
        Serial.println(svalue);

        yield();

        if (strcmp(svalue, "0") == 0) {
          setHeatingmodeTo(0);
          lastValueChange = 0; // force saving of values without delay
          checkValuesChanged();
        }
        else if (strcmp(svalue, "10") == 0) {
          setHeatingmodeTo(1);
          lastValueChange = 0; // force saving of values without delay
          checkValuesChanged();
        }
        else if (strcmp(svalue, "20") == 0) {
          setHeatingmodeTo(2);
          lastValueChange = 0; // force saving of values without delay
          checkValuesChanged();
        }
      }
    }
  }
  domoticzOutParserBusy = false;
}


void sendToDomoticz_thermostat() {
  if (domoticzIdx_Thermostat > 0) {
    //{"idx": 219,"nvalue":0,"svalue":"24.00"}
    char domSetTempTo[6];
    dtostrf(setTemp, 1, 1, domSetTempTo);

    char buf[101];
    sprintf(buf, "{\"idx\":%d,\"nvalue\":0,\"svalue\":\"%s\"}", domoticzIdx_Thermostat, domSetTempTo);
    mqttclient.publish(DOMOTICZ_IN_TOPIC, buf);
    count_sendToDomoticz_thermostat = 0;
  }
}


void sendToDomoticz_heatingMode() {
  //if (!skipNextDomoticzUpdate_ThermostatMode) {
  if (domoticzIdx_ThermostatMode > 0) {
    //skipNextDomoticzUpdate_ThermostatMode = false;
    //{"command": "switchlight", "idx": 2450, "switchcmd": "Set Level", "level": 100 }
    if (heatingMode == 0 || heatingMode == 1 || heatingMode == 2) {
      int domLevel;
      domLevel = heatingMode * 10;
      // 0 = Off, 10 = Normal, 20 = Reduction
      char buf[101];
      sprintf(buf, "{\"command\":\"switchlight\",\"idx\":%d,\"switchcmd\":\"Set Level\",\"level\":%d}", domoticzIdx_ThermostatMode, domLevel);
      mqttclient.publish(DOMOTICZ_IN_TOPIC, buf);
      count_sendToDomoticz_heatingMode = 0;
    }
  }
}

void sendToDomoticz_TempHum() {
  if (domoticzIdx_TempHumSensor > 0) {
    if ( lastTempUpdate != 0 && (millis() - lastTempUpdate) < 120000 ) {
      //{"idx":idx,"nvalue":0,"svalue":"TEMP;HUM;0"}
      char buf[101];
      char buftemp[10];
      dtostrf(temperature, 1, 1, buftemp );
      sprintf(buf, "{\"idx\":%d,\"nvalue\":0,\"svalue\":\"%s;%d;0\"}", domoticzIdx_TempHumSensor, buftemp, humidity);
      mqttclient.publish(DOMOTICZ_IN_TOPIC, buf);
    }
  }
}

void checkUseDomoticz() {
  if (domoticzIdx_Thermostat != 0 || domoticzIdx_ThermostatMode != 0) {
    useDomoticz = true;
  }
  else {
    useDomoticz = false;
  }
}


void updateDomoticzDevices() {
  // sends updates to domoticz, is called every minute by misc/everyMinute()

  // update TempHum-Sensor device every minute
  sendToDomoticz_TempHum();

  if (count_sendToDomoticz_thermostat >= domoticzUpdateInterval) {
    sendToDomoticz_thermostat();
    count_sendToDomoticz_thermostat = 0;
  }
  else count_sendToDomoticz_thermostat++;

  if (count_sendToDomoticz_heatingMode >= domoticzUpdateInterval) {
    sendToDomoticz_heatingMode();
    count_sendToDomoticz_heatingMode = 0;
  }
  else count_sendToDomoticz_heatingMode++;


}

