/*
 Rocrail - Model Railroad Software
 Copyright (c) 2002-2022 Robert Jan Versluis, Rocrail.net
 All rights reserved.
*/
#include "RCAN_dfs.h"
#include "trace.h"
#include <EEPROM.h>
#include "gen/revision.h"

// Disable to save a lot of memory!
static bool DEBUG = true;

#define MAXLEN 121

void setDebug(bool debug) {
  DEBUG=debug;
}

//---------- Global trace function.
void trace(const char* fmt, ...) {
  if( DEBUG ) {
    char msg[MAXLEN] = {'\0'};
    va_list args;
    va_start(args, fmt);
    vsnprintf(msg, MAXLEN-1, fmt, args);
    va_end(args);
    Serial.println(msg);
  }
}


void makeASCIIFrame(iCANFrame frame, char* sframe) {
  byte prio = 1;
  char sFrame[30] = {'\0'}; // Array to store serial string
  
  if( frame->ext ) {
    sprintf(sFrame, ":X%02X%02X%02X%02XN%02X%02X%02X%02X%02X%02X%02X%02X", (byte)((frame->id >> 24) &0x3F), (byte)((frame->id >> 16) & 0xFF), (byte)((frame->id >> 8) & 0xFF), (byte)((frame->id >> 0) & 0xFF),
    frame->data[0], frame->data[1], frame->data[2], frame->data[3], frame->data[4], frame->data[5], frame->data[6], frame->data[7]);
    sFrame[frame->dlc * 2 + 11] = ';';
    sFrame[frame->dlc * 2 + 12] = '\0';
  }
  else {
    sprintf(sFrame, ":S%02X%02XN%02X%02X%02X%02X%02X%02X%02X%02X", (byte)((0x80 + (prio << 5) + (frame->id >> 3)) &0xFF), (byte)((frame->id << 5) & 0xFF),
    frame->data[0], frame->data[1], frame->data[2], frame->data[3], frame->data[4], frame->data[5], frame->data[6], frame->data[7]);
    sFrame[frame->dlc * 2 + 7] = ';';
    sFrame[frame->dlc * 2 + 8] = '\0';
  }
  strcpy(sframe, sFrame);
}

//---------- Send the CAN frame in ASCII.
void sendASCIIFrame(iCANFrame frame) {
  byte prio = 1;
  char sFrame[30] = {'\0'}; // Array to store serial string
  
  makeASCIIFrame( frame, sFrame );
  Serial.println(sFrame);
}

int getRevision() {
  return revisionnr + 1; // The revision number is generated before the commit, so add one...
}


//---------- Dump the first 64 EEPROM bytes.
void dumpEEPROM(byte lines) {
  for( byte i = 0; i < lines; i++ ) {
    trace("E%02u %02X %02X %02X %02X %02X %02X %02X %02X", i*8,
      EEPROM.read(i*8+0), EEPROM.read(i*8+1), EEPROM.read(i*8+2), EEPROM.read(i*8+3), EEPROM.read(i*8+4), EEPROM.read(i*8+5), EEPROM.read(i*8+6), EEPROM.read(i*8+7) );
  }
}
