Download this file
#include "protocol.h"
#include "heater_controller_slave.h"

Protocol::Protocol(Speaker* speaker):
  speaker(speaker)
  { }

void Protocol::handle(uint8_t * buffer, uint8_t buffer_len) {
  switch(buffer[0]) {
    case 0x00:
      status();
      break;
    case 0x01:
      relay.close();
      break;
    case 0x02:
      relay.open();
      break;
    default:
      error(buffer[0]);
      break;
  }
}

void Protocol::status() {
  uint8_t* buf = speaker->get_buffer();
  temperature.start_reading();
  uint16_t cur = current.get_value();
  uint16_t temp = temperature.get_value();
  uint8_t i = 0;
  buf[i++] = 0x80; // status reply
  buf[i++] = 4; // this value is the lenth of the data below
  buf[i++] = (relay.get_state() << 7) | ((temp & 0x0100) >> 8); // take only bit 8, since all bits >= 8 have the same value
  buf[i++] = temp & 0xFF;
  buf[i++] = (cur >> 8);
  buf[i++] = cur & 0xFF;
  speaker->send(i, true);
}

void Protocol::error(uint8_t faulty_command) {
  uint8_t* buf = speaker->get_buffer();
  uint8_t i = 0;
  buf[i++] = 0xFF; // error reply
  buf[i++] = 1;
  buf[i++] = faulty_command;
  speaker->send(i, true);
}

void Protocol::got_ack() {
  speaker->got_ack();
}


// vim:ft=arduino