#include <Arduino.h>
#include <CAN.h>

#define TX_DELAY 3 // Delay between messages

byte sndStat; // Status of the sent message (global variable)

// Struct to hold CAN packet information
struct CanPacket {
    unsigned long id;
    char data[24];
};

// Array of CAN packets to be sent
const CanPacket packets[] PROGMEM = {
    {0x418, "30 07 00 03 28 28 F8 A0"},
    {0x46B, "01 00 A3 00 01 00 00 C0"},
    {0x47C, "64 7D 42 01 91 00 70 04"},
    {0x47D, "04 C1 77 95 60 01 20 C4"},
    {0x47F, "34 0C 96 00 EA 72 44 00"},
    {0x25B, "04 46 00 FF FF C0"},
    {0x69F, "75 01 33 6F"}, //Anti-Theft protection, VIN encoding unknown
};

// Function to send a CAN message
void sendCanMessage(unsigned long canId, const char* hexString) {
    int len = strlen(hexString) / 3 + 1; // Determine the length of the data in bytes
    byte data[len]; // Create an array to store the data bytes

    // Convert hex string to bytes
    for (int i = 0; i < len; i++) {
        unsigned int byteData;
        sscanf(&hexString[i * 3], "%x", &byteData);
        data[i] = (byte)byteData;
    }

    CAN.beginPacket(canId);
    CAN.write(data, len);
    CAN.endPacket();

    Serial.print("Message Sent: ID = ");
    Serial.print(canId, HEX);
    Serial.print(", Data = ");
    Serial.println(hexString);
}


void setup() {
    Serial.begin(115200);
    Serial.println("CAN_Waker starting up...");


    // start the CAN bus at 500 kbps
    if (!CAN.begin(500E3)) {
      Serial.println("Starting CAN failed!");
      while (1);
    }

    delay(2000);
}

void loop() {
    // Replay all the CAN packets
    for (unsigned int i = 0; i < sizeof(packets) / sizeof(packets[0]); i++) {
        CanPacket packet;
        memcpy_P(&packet, &packets[i], sizeof(CanPacket)); // Copy packet from PROGMEM to SRAM
        sendCanMessage(packet.id, packet.data); // packet.data is now a char array
        delay(TX_DELAY); // Wait for the specified delay between messages
    }
}
