#include <RH_ASK.h>
//#include <DHTStable.h>
#include <dhtnew.h>

#define SENSORID 102
#define PIN_SEND 15
#define PIN_RECEIVE 2
#define PIN_DHT 14

#define DELAYSEND 60000UL

#define Log(l) Serial.print(l)
#define LogLn(l) Serial.println(l)

RH_ASK driver(2000, PIN_RECEIVE, PIN_SEND, 12, false);
//DHTStable DHT;
DHTNEW DHT(PIN_DHT);

//uint8_t rh_payload[4];
uint8_t rh_payload[5];

uint16_t lastsendrh = 0;

void setSensorType(uint8_t stype)
{
  uint8_t payload0; 
  payload0 = stype << 4;
  rh_payload[0] &= 0b00001111;
  rh_payload[0] += payload0;
}

bool setTH()
{
  int errno;
  //if(DHT.read22(PIN_DHT) == DHTLIB_OK)
  errno = DHT.read();
  rh_payload[1] = (uint8_t) (errno*-1);
  if(errno == 0) {
    int16_t tempC = (int16_t) roundf(DHT.getTemperature()*100);
    uint8_t humidity = (uint8_t) roundf(DHT.getHumidity());
    Log("Send ");
    Log("Temperature: ");
    Log(tempC);
    //LogF(DHT.temperature);
    Log(" Humidity: ");
    LogLn(humidity);
    //LogF(DHT.humidity);
    //rh_payload[1] = tempC >> 8;
    //rh_payload[2] = tempC;
    //rh_payload[3] = humidity;
    rh_payload[2] = tempC >> 8;
    rh_payload[3] = tempC;
    rh_payload[4] = humidity;
    return true;
  } else {
    rh_payload[2] = 0;
    rh_payload[3] = 0;
    rh_payload[4] = 0;
    Log("DHT Error ");
    LogLn(errno);
    //return false;
    return true;
  }
}

void setup()
{
  Serial.begin(9600);	  // Debugging only
  delay(5000);
  LogLn("Startup");

  if (!driver.init()) { LogLn("RH init failed"); }
  driver.setHeaderId(SENSORID);

  DHT.setType(22);
  //DHT.setDisableIRQ(true);
  TIMSK1 &= ~_BV(OCIE1A);

  // Temperature initial (-100)
  //rh_payload[1] = 0xff;
  //rh_payload[2] = 0x9c;
  rh_payload[2] = 0xff;
  rh_payload[3] = 0x9c;

  setSensorType(2);

  sendTH();
  //driver.setModeRx();

}

void sendTH()
{
  //Serial.println("Send");
  if(setTH()==true) {
    TIMSK1 |= _BV(OCIE1A);
    //driver.setModeTx();
    for(uint8_t i=0;i<4;i++)
    {
      driver.send(rh_payload, 5);
      driver.waitPacketSent();
      delay(100);
    }
    TIMSK1 &= ~_BV(OCIE1A);
  }
}

void loop()
{
  //uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
  //uint8_t buflen = sizeof(buf);

  delay(60000+random(5000));
  //delay(15000);
  sendTH();
  /*if(millis() < lastsendrh || millis() > lastsendrh+DELAYSEND)
  {
    lastsendrh=millis();
    sendTH();
    //driver.setModeRx();
  }
  if (driver.recv(buf, &buflen)) {
    driver.printBuffer("Got:", buf, buflen);
  }*/
}
