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

const uint32_t HELP_PACKAGE_CAN_ID = 0xFFFF;
const uint32_t SWITCH_TRIGGERED_CAN_ID = 0x050;
const uint32_t TRIGGER_SWITCH_CAN_ID = 0x055;
const uint32_t  HELP_PACKAGE_ID = 0xFFFF;


byte MeyCircularShift(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;
}




byte DeviceId[1];


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

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

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

typedef struct
{
  uint32_t sourceDevId;
  byte sourceMeyPinId;
  byte targetMeyPinId;
  bool trigger;

  void InitSimple(uint32_t sourceDevId, byte sourceMeyPinId, byte targetMeyPinId)
  {
    this->sourceDevId = sourceDevId;
    this->sourceMeyPinId = sourceMeyPinId;
    this->targetMeyPinId = targetMeyPinId;
    trigger = false;
  }

  void InitTrigger(uint32_t sourceDevId, byte sourceMeyPinId, byte targetMeyPinId)
  {
    this->sourceDevId = sourceDevId;
    this->sourceMeyPinId = sourceMeyPinId;
    this->targetMeyPinId = targetMeyPinId;
    trigger = true;
  }
} Rule;


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;


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

void InitMeyCan()
{
  DeviceId[0] = GetDeviceIdLow();
  DeviceId[1] = GetDeviceIdHigh();
}