#include "avrIOhelper/io-helper.h"
#include "modbus-master.h"

#define IO_SLAVE_ADDR 0x04

volatile uint8_t modbus_io_inStates[4];
volatile uint8_t modbus_io_inStatesBothEdges[4];
volatile uint8_t modbus_io_inStatesRisingEdge[4];
volatile uint8_t modbus_io_inStatesFallingEdge[4];

void modbus_io_read(){
    readInputReg(IO_SLAVE_ADDR, 0, 2);
    wait_receive(2, (void*)modbus_io_inStates, 100);

    readInputReg(IO_SLAVE_ADDR, 100, 2);
    wait_receive(2, (void*)modbus_io_inStatesBothEdges, 100);

    readInputReg(IO_SLAVE_ADDR, 200, 2);
    wait_receive(2, (void*)modbus_io_inStatesFallingEdge, 100);

    readInputReg(IO_SLAVE_ADDR, 300, 2);
    wait_receive(2, (void*)modbus_io_inStatesRisingEdge, 100);
}

void modbus_io_set_Output(uint8_t slave_adr, uint8_t nr, uint8_t state) {
  switch (state) {
    case BLINK:
        writeCoil(slave_adr,100+nr,1);
        wait_write(10);
        break;
    //case TOGGLE:
    //  ioHelperSetBit(outStatesBlinking,  nr,  OFF);
    //  if (ioHelperReadBit(outStates, nr)) {
    //    ioHelperSetBit(outStates,  nr,  OFF);
    //  } else {
    //    ioHelperSetBit(outStates,  nr,  ON);
    //  }
    //  break;
    case ON:
        writeCoil(slave_adr,nr,1);
        wait_write(10);
      break;
    case OFF:
        writeCoil(slave_adr,nr,0);
        wait_write(10);
      break;
  }
}

uint8_t modbus_io_read_Input(uint8_t nr, uint8_t type) {
  uint8_t state = 0;
  switch (type) {
    case LEVEL:
      state = ioHelperReadBit(modbus_io_inStates, nr);
      break;
    case EDGE:
      state = ioHelperReadBit(modbus_io_inStatesBothEdges, nr);
      break;
    case RISING:
      state = ioHelperReadBit(modbus_io_inStatesFallingEdge, nr);
      break;
    case FALLING:
      state = ioHelperReadBit(modbus_io_inStatesRisingEdge, nr);
      break;
  }
  return state;
}
