#include "dsmrhandler.h"
/* -------------------------------------------------*/
/* https://github.com/matthijskooijman/arduino-dsmr */
/* -------------------------------------------------*/

SoftwareSerial DMSRSerial;

P1Reader reader(&DMSRSerial, DSMR_REQ);

unsigned long last;
DSMRData data;
unsigned long msgCount;

void dsmrParser(void)
{
  msgCount = 1322;
  ParseResult<void> res = P1Parser::parse(&data, testData, lengthof(testData), true);
  if (res.err)
  {
    // Parsing error, show it
    Serial.println(res.fullError(testData, testData + lengthof(testData)));
  }
  else
  {
    // Parsed succesfully, print all values
    data.applyEach(Printer());
  }
}

void dsmrReader(void)
{
  //process msg
  reader.loop();
  unsigned long now = millis();
  if (now - last > 60000)
  {
    reader.enable(true);
    last = now;
  }
  if (reader.available())
  {
    msgCount++;
    String err;
    if (reader.parse(&data, &err))
    {
      // Parse succesful, print result
      data.applyEach(Printer());
    }
    else
    {
      // Parser error, print error
      Serial.println(err);
    }
  }
}

void initDSMR(void)
{
  //init soft serial
  DMSRSerial.begin(115200, SWSERIAL_8N1, -1, DSMR_DATA);
  reader.enable(true);
  last = millis();
#ifdef TEST
  dsmrParser();
#endif
}

void handleDSMR(void)
{
  dsmrReader();
}

String getElecDelivered(void)
{
  String tmpstr("Cons: ");
  tmpstr += data.power_delivered.int_val();
  tmpstr += " kwh";
  return tmpstr;
}

String getElecReturned(void)
{
  String tmpstr("Prod: ");
  tmpstr += data.power_returned.int_val();
  tmpstr += " kwh";
  return tmpstr;
}

String getGasDelivered(void)
{
  String tmpstr("Cons: ");
  tmpstr += data.gas_delivered.int_val();
  tmpstr += " m3";
  return tmpstr;
}

String getMsgCount(void)
{
  String tmpstr("#Msg: ");
  tmpstr += msgCount;
  return tmpstr;
}