#include "OT_Slave.h"

#ifndef _SIM_T_BOILER_
#define	_SIM_T_BOILER_	1
#endif
#ifndef _SIM_T_RET_
#define	_SIM_T_RET_	1
#endif

#define THERMOSTAT_IN	2
#define THERMOSTAT_OUT	4

uint32_t	OT_Action::OTD2uint32 (const OpenthermData& data)
{
	uint32_t val(data.type);
	val = ((val << 8) | data.id);
	val = ((val << 8) | data.valueHB);
	val = ((val << 8) | data.valueLB);
	return val;
}

OT_Action OT_Slave::action;

OT_Slave::OT_Slave ()
:
  cbAction(0),
  chEnable(false),
  chActive(false),
  chTemperature(0),
  dhwEnable(false),
  dhwActive(false),
  dhwTemperature(0),
  tBoiler(28.0),
  tReturn(28.0)
{
}

void  OT_Slave::begin (OT_Action_CB cb)
{
  pinMode(THERMOSTAT_IN, INPUT);
  digitalWrite(THERMOSTAT_OUT, HIGH);
  pinMode(THERMOSTAT_OUT, OUTPUT);	// low output = high current, high output = low current
  cbAction = cb;
}

/**
 * Loop will act as boiler (slave) connected to Opentherm thermostat.
 * It will wait for requests from thermostat and response with unknown data id as a fake response.
 */
void  OT_Slave::maintain ()
{
  if (OPENTHERM::getMessage(action.request)) {
    HandleRequest(action);
  } else if (OPENTHERM::isSent() || OPENTHERM::isIdle() || OPENTHERM::isError()) { // wait for request from thermostat
    OPENTHERM::listen(THERMOSTAT_IN, -1);
  }
}

void  OT_Slave::HandleRequest (OT_Action& action) 
{
  if (Serial) {
    Serial.print("-> ");
    OPENTHERM::printToSerial(action.request);
    Serial.println();
  }
  delay(100); // Opentherm defines delay between request and response
  action.response = action.request;
  switch (action.request.id) {
    case OT_MSGID_STATUS: // 0  (Master and slave status flags) [M:ReadAck] 
      StatusReq(action);
      break; 
    case OT_MSGID_CH_SETPOINT:  // 1  (Control setpoint ie CH water temp. setpoint) [M:WriteAck]
      action.response.type = OT_MSGTYPE_WRITE_ACK;
      CH_Temperature(action.request.f88());
      break;
    case OT_MSGID_SLAVE_CONFIG: // 3  (Slave configuration flags) [M:ReadAck] 
      ConfigReq(action);
      break; 
    case OT_MSGID_FAULT_FLAGS:  // 5  (Application-specific fault flags / OEM fault code)
      FaultReq(action);
      break; 
    case 14:  // 14 (Maximum relative modulation level setting) [M:WriteAck]  
      action.response.type = OT_MSGTYPE_WRITE_ACK;
      break;
    case OT_MSGID_MODULATION_LEVEL: // 17 (Relative modulation level)  [M:ReadAck|DataInvalid] 
      action.response.type = OT_MSGTYPE_DATA_INVALID;
      break;
    case OT_MSGID_FEED_TEMP:  // 25 (Boiler water temperature)  [M:ReadAck|DataInvalid]
#if _SIM_T_BOILER_
      action.response.type = OT_MSGTYPE_READ_ACK;
      action.response.f88(GetBoilerTemperature());
#else
      action.response.type = OT_MSGTYPE_DATA_INVALID;
#endif
      break;
#if _SIM_T_RET_
    case OT_MSGID_RETURN_WATER_TEMP: // 28 (Return water temperature)
      action.response.type = OT_MSGTYPE_READ_ACK;
      action.response.f88(GetReturnTemperature());
      break;
#endif
    case OT_MSGID_DHW_SETPOINT: // 56 (DHW setpoint)
      if (action.request.type == OT_MSGTYPE_READ_DATA) {
        action.response.type = OT_MSGTYPE_READ_ACK;
        action.response.f88(dhwTemperature);
        break;
      } else if (action.request.type == OT_MSGTYPE_WRITE_DATA) {
        action.response.type = OT_MSGTYPE_WRITE_ACK;
        DHW_Temperature(action.request.f88());
      } else {
        action.response.type = OT_MSGTYPE_UNKNOWN_DATAID; // construct fake response
      }
      break; 
    case OT_MSGID_VERSION_SLAVE:  // 127  (Slave product version number and type)
      action.response.type = OT_MSGTYPE_READ_ACK;
      action.response.valueHB = 0;  //  product type 
      action.response.valueLB = 0;  //  product version
      break; 
    default:
      action.response.type = OT_MSGTYPE_UNKNOWN_DATAID; // construct fake response
      action.response.valueHB = 0;
      action.response.valueLB = 0;
  }
  if (cbAction) {
    (*cbAction)(action);
  }
  OPENTHERM::send(THERMOSTAT_OUT, action.response, OT_Slave::ListenAfterResponse); // send some response and wait for antoher request from thermostat set by callback
}

void  OT_Slave::ConfigReq (OT_Action& action)
{
  action.response.type = OT_MSGTYPE_READ_ACK;
  action.response.valueHB = 0; // 0x11;  //  slave configuration:
  action.response.valueLB = 0;  //  Slave MemberID code
}

void  OT_Slave::StatusReq (OT_Action& action)
{
  action.response.type = OT_MSGTYPE_READ_ACK;
  CH_Enable(action.request.valueHB & 0x01);
  DHW_Enable(action.request.valueHB & 0x02);
  action.response.valueLB = 0;  //  Slave status
  if (chActive) {
    action.response.valueLB |= 0x02;
  } else {
    action.response.valueLB &= ~0x02;
  }
  if (dhwActive) {
    action.response.valueLB |= 0x04;
  } else {
    action.response.valueLB &= ~0x04;
  }
}

void  OT_Slave::FaultReq (OT_Action& action)
{
  action.response.type = OT_MSGTYPE_READ_ACK;
  action.response.valueHB = 0;  //  Application-specific fault flags
  action.response.valueLB = 0;  //  OEM fault code 
}

bool  OT_Slave::CH_Enable (bool enable)
{
  chEnable = enable;
  chActive = enable;
  return chEnable;
}

bool  OT_Slave::CH_Disable ()
{
  chEnable = false;
  chActive = false;
  return chEnable;
}

void  OT_Slave::CH_Temperature (float temp)
{
  chTemperature = temp;
}

bool  OT_Slave::DHW_Enable (bool enable)
{
  dhwEnable = enable;
  dhwActive = enable;
  return dhwEnable;
}

bool  OT_Slave::DHW_Disable ()
{
  dhwEnable = false;
  dhwActive = false;
  return dhwEnable;
}

void  OT_Slave::DHW_Temperature (float temp)
{
  dhwTemperature = temp;
}

bool	OT_Slave::IsActive ()
{
	return (chActive || dhwActive);
}

float   OT_Slave::GetBoilerTemperature ()
{
	if (IsActive()) {
		// increase
		float tTarget = (chTemperature > dhwTemperature) ? chTemperature : dhwTemperature;
		if (tBoiler < tTarget) {
			tBoiler = (tBoiler + 2.0 * tTarget) / 3.0;
		}
	} else {
		// decrease
		if (tBoiler > tReturn) {
			tBoiler = (tBoiler + 2.0 * tReturn) / 3.0;
		}
	}
	return tBoiler;	// FAKE NEWS !!!
}

extern volatile long  loops;

float   OT_Slave::GetReturnTemperature ()
{
	float temp = 100.0 * (tReturn - 1);
	temp += float((loops >> 4) % 100);
	return temp / 100.0;
}

void  OT_Slave::ListenAfterResponse () 
{
  if (Serial) {
    Serial.print("<- ");
    OPENTHERM::printToSerial(action.response);
    Serial.println();
    Serial.println();
  }
  OPENTHERM::listen(THERMOSTAT_IN, -1);
}
