#include <SPI.h>;
#include <mcp2515.h>;


struct can_frame _frame;
MCP2515 mcp2515(PIN_PA3);
const byte SoftwareVersionHigh = 1;
const byte SoftwareVersionLow = 0;
const byte HardwareVersionHigh = 2;
const byte HardwareVersionLow = 0;

typedef struct
{
  int pin_id;
  bool pin_state;
  bool is_input;
  byte meyPinId;

  PinState() {}
  void Init(int pin_id, byte meyPinId)
  {
    this->pin_id = pin_id;
    this->pin_state = true;
    this->is_input = true;
    this->meyPinId = meyPinId;
  }
} PinState;

int PinCount = 8;
PinState PinPD2[8];
byte DeviceId[2];

void setup() {
  SPI.begin();


  PinPD2[0] = PinState();
  PinPD2[0].Init(PIN_PC7, (byte) 1);

  PinPD2[1] = PinState();
  PinPD2[1].Init(PIN_PD0, (byte) 2);

  PinPD2[2] = PinState();
  PinPD2[2].Init(PIN_PD1, (byte) 3);

  PinPD2[3] = PinState();
  PinPD2[3].Init(PIN_PD2, (byte) 4);

  PinPD2[4] = PinState();
  PinPD2[4].Init(PIN_PD6, (byte) 5);

  PinPD2[5] = PinState();
  PinPD2[5].Init(PIN_PD5, (byte) 6);

  PinPD2[6] = PinState();
  PinPD2[6].Init(PIN_PD4, (byte) 7);

  PinPD2[7] = PinState();
  PinPD2[7].Init(PIN_PD3, (byte) 8);



  _PROTECTED_WRITE(CLKCTRL.MCLKCTRLA,  CLKCTRL.MCLKCTRLA | 1 << 7);
  mcp2515.reset();
  mcp2515.setBitrate(CAN_500KBPS, MCP_8MHZ); //Sets CAN at speed 500KBPS and Clock 8MHz
  mcp2515.setNormalMode();

  for (int i = 0; i <= PinCount - 1; i++)
  {
    pinMode(PinPD2[i].pin_id, INPUT_PULLUP);
    PinPD2[i].pin_state = ReadPin(&PinPD2[i]);
  }


  DeviceId[0] = GetDeviceIdLow();
  DeviceId[1] = GetDeviceIdHigh();

  SendSerialPackage();
}


void loop()
{
  for (int i = 0; i <= PinCount - 1; i++)
  {
    if (CheckPinStatus(&PinPD2[i]))
      SendSwitchedTriggeredCanPackage(PinPD2[i].meyPinId, PinPD2[i].pin_state);
  }

  if (mcp2515.readMessage(&_frame) == MCP2515::ERROR_OK)
  {

    if (GetDeviceId(_frame.can_id) == GetMyDeviceId())
    {
      
      int meyPinId = _frame.data[0];
      bool state = _frame.data[1] > 0;

      PinState *adressedPin;
      for (int i = 0; i <= PinCount - 1; i++)
        if (PinPD2[i].meyPinId == meyPinId)
        {
          adressedPin = &PinPD2[i];
          break;
        }

      if (adressedPin != NULL)
      {
        if (adressedPin->is_input == true)
        {
          pinMode(adressedPin->pin_id, OUTPUT);
          adressedPin->is_input = false;
        }
        adressedPin->pin_state = state;
        digitalWrite(adressedPin->pin_id, state);
      }

    }
  }
  delay(20);
}


void SendSerialPackage()
{
  _frame.can_id = CreateCanId(0xFFFF);
  _frame.can_dlc = 4;

  _frame.data[0] = SoftwareVersionHigh;
  _frame.data[1] = SoftwareVersionLow;
  _frame.data[2] = HardwareVersionHigh;
  _frame.data[3] = HardwareVersionLow;
  mcp2515.sendMessage(MCP2515::TXB1, &_frame);
}


void SendSwitchedTriggeredCanPackage(byte pinId, int state)
{
  _frame.can_id = CreateCanId(0x050);
  _frame.can_dlc = 2;
  _frame.data[0] = pinId;
  _frame.data[1] = state;
  mcp2515.sendMessage(MCP2515::TXB1, &_frame);
}


void SendDoTriggerSwitchCanPackage(uint32_t targetCanId, byte pinId, byte state)
{
  _frame.can_id = CreateCanId(0x050);
  _frame.can_dlc = 4;
  _frame.data[0] = targetCanId & 0xFF;
  _frame.data[1] = (targetCanId & 0xFF00) >> 8;
  _frame.data[2] = pinId;
  _frame.data[3] = state;
  mcp2515.sendMessage(MCP2515::TXB1, &_frame);
}

bool ReadPin(PinState * state)
{
  if (state->pin_id == PIN_PD2)
    return digitalReadFast(PIN_PD2);
  else if (state->pin_id == PIN_PC7)
    return digitalReadFast(PIN_PC7);
  else if (state->pin_id == PIN_PD1)
    return digitalReadFast(PIN_PD1);
  else if (state->pin_id == PIN_PD0)
    return digitalReadFast(PIN_PD0);
  else if (state->pin_id == PIN_PD6)
    return digitalReadFast(PIN_PD6);
  else if (state->pin_id == PIN_PD5)
    return digitalReadFast(PIN_PD5);
  else if (state->pin_id == PIN_PD4)
    return digitalReadFast(PIN_PD4);
  else if (state->pin_id == PIN_PD3)
    return digitalReadFast(PIN_PD3);
  else
    return digitalRead(state->pin_id);
}


byte CircularShift(byte b)
{
  return (b << 1) | (b >> 7 & 1);
}

uint32_t GetDeviceId(uint32_t canFrameId)
{
  return canFrameId & 0xFFFF;
}

uint32_t GetPackageType(uint32_t canFrameId)
{
  return (canFrameId / 0x10000) & 0xFFF;
}

uint32_t CreateCanId(uint32_t commandId)
{
  return ((commandId & 0xFFF) * 0x10000) | ( DeviceId[0] << 8) | (DeviceId[1]) | CAN_EFF_FLAG;
}

uint32_t GetMyDeviceId()
{
  return ( DeviceId[0] << 8) | (DeviceId[1]);
}

byte GetDeviceIdLow() {
  return (SIGROW.SERNUM0 ^
          CircularShift(SIGROW.SERNUM2) << 1 ^
          CircularShift( CircularShift(SIGROW.SERNUM4)) ^
          CircularShift( CircularShift( CircularShift(SIGROW.SERNUM6))) ^
          CircularShift( CircularShift( CircularShift( CircularShift(SIGROW.SERNUM8)))));
}

byte GetDeviceIdHigh() {
  return (SIGROW.SERNUM1 ^
          CircularShift(SIGROW.SERNUM3) << 1 ^
          CircularShift( CircularShift(SIGROW.SERNUM5)) ^
          CircularShift( CircularShift( CircularShift(SIGROW.SERNUM7))) ^
          CircularShift( CircularShift( CircularShift( CircularShift(SIGROW.SERNUM9)))));
}

bool CheckPinStatus(PinState * state)
{
  if (!state->is_input)
    return false;

  bool newValue = ReadPin(state);


  if (newValue != state->pin_state)
  {
    delay(10);
    newValue = ReadPin(state);
    if (newValue != state->pin_state)
    {
      state->pin_state = newValue;
      return true;
    }
  }
  return false;

}
