Download this file
#include "speaker.h"
#include "protocol.h"
#include "heater_controller_master.h"

Speaker::Speaker():
  buffer_len(0),
  with_ack(false),
  retry_count(0),
  next_retry_millis(0)
  {}

void Speaker::set_protocol(Protocol* _protocol) {
  protocol = _protocol;
}

bool Speaker::canRun(uint32_t now) {
  if (buffer_len > 0 && retry_count > 0 && millis() > next_retry_millis)
    return rf12_canSend();
  return false;
}

void Speaker::run(uint32_t now) {
  if (with_ack && retry_count == 1) {
    buffer_len = 0;
    protocol->got_nack();
  }
  uint8_t header = (with_ack ? RF12_HDR_ACK : 0) | RF12_HDR_DST | SLAVE_ID;
  //SHOW_BUFFER("SEND: ", header, buffer, buffer_len);
  rf12_sendStart(header, buffer, buffer_len);
  rf12_sendWait(0);
  if (with_ack) {
    //Serial.println("with_ack");
    retry_count --;
    next_retry_millis = millis() + SEND_RETRY_TIMEOUT;
  }
  else {
    //Serial.println("no_ack");
    buffer_len = 0;
  }
}

uint8_t* Speaker::get_buffer() {
  return buffer;
}

void Speaker::send(uint8_t len, bool ack) {
  with_ack = ack;
  buffer_len = len;
  retry_count = SEND_RETRY_COUNT + 1;
  next_retry_millis = millis();
}

void Speaker::got_ack() {
  //Serial.println("got_ack");
  buffer_len = 0;
}
// vim:ft=arduino