/*
 * iface_fake.cpp
 *
 * (C) Copyright 2014 Ulrich Hecht
 *
 * This file is part of CASCADE.  CASCADE is almost free software; you can
 * redistribute it and/or modify it under the terms of the Cascade Public
 * License 1.0.  Read the file "LICENSE" for details.
 */

#include "iface_fake.h"
#include "debug.h"
#include "os.h"
#include "serial.h"
#include <stdlib.h>
#include <string.h>

IfaceFake::IfaceFake(Cpu *c, UI *ui) : Interface(ui)
{
  delay = c->getCycles();
  obd_ptr = can_ptr = 0;
  astate = FAKE_ASTATE_IDLE;
  in_buf_start = in_buf_end = 0;
  cpu = c;
  hyundai = true;
  ui->setPort("FAKE");
}

static int obd_replies[][2][200] = {
  /* Hyundai keep-alive */
  {{0x68, 0x6a, 0xf1, 0x01, 0x01, 0xc5, -1}, {0x48, 0x6b, 0x12, 0x41, 0x01, 0x01, 0x04, 0x00, 0x00, 0x0c, -1}},
  /* Honda keep-alive (not sure what the proper answer is, copied from above) */
  {{0x68, 0x6a, 0xf1, 0x01, 0x00, 0xc4, -1}, {0x48, 0x6b, 0x12, 0x41, 0x01, 0x01, 0x04, 0x00, 0x00, 0x0c, -1}},
  /* Hyundai DTC */
  {{0x68, 0x6a, 0xf1, 0x03, 0xc6, -1}, {0x48, 0x6b, 0x12, 0x43, 0x00, 0x33, 0x00, 0x00, 0x00, 0x00, 0x71, -1}},

  /* Toyota (transmissions from a benched Yaris 1SZ-FE ECU) */
  {{0x68, 0x6a, 0xf0, 0x01, 0xe1, 0xa4, -1}, {0x48, 0x6b, 0x10, 0x41, 0xe1, 0x07, 0x07, 0xf3, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xc1, 0x28, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xc1, 0x01, 0x00, 0x6a, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xc2, 0x29, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xc2, 0x00, 0x00, 0x6a, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xc4, 0x2b, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xc4, 0x63, 0x57, 0x26, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xc6, 0x2d, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xc6, 0x01, 0x45, 0xb4, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xc8, 0x2f, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xc8, 0x46, 0x01, 0xb7, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xca, 0x31, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xca, 0x00, 0x50, 0xc2, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xcc, 0x33, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xcc, 0x43, 0x53, 0x0a, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xcf, 0x36, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xcf, 0x40, 0x00, 0xb7, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xd2, 0x39, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xd2, 0x03, 0xe6, 0x63, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xd3, 0x3a, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xd3, 0xe6, 0x03, 0x64, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xd6, 0x3d, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xd6, 0x02, 0x12, 0x92, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xd7, 0x3e, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xd7, 0x12, 0x01, 0x92, -1}},
  {{0x68, 0x6a, 0xf0, 0xa4, 0x02, 0xff, 0xd8, 0x3f, -1}, {0x48, 0x6b, 0x10, 0xe4, 0x02, 0xff, 0xd8, 0x01, 0x00, 0x81, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0x00, 0xc3, -1}, {0x48, 0x6b, 0x10, 0x41, 0x00, 0xbe, 0x1f, 0xb8, 0x11, 0xaa, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0x20, 0xe3, -1}, {0x48, 0x6b, 0x10, 0x41, 0x20, 0x80, 0x00, 0x00, 0x00, 0xa4, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0xb0, 0x73, -1}, {0x48, 0x6b, 0x10, 0x41, 0xb0, 0x00, 0x01, 0xb5, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0xe0, 0xa3, -1}, {0x48, 0x6b, 0x10, 0x41, 0xe0, 0xd5, 0xb3, 0xe0, 0x00, 0x4c, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0xe1, 0xa4, -1}, {0x48, 0x6b, 0x10, 0x41, 0xe1, 0x07, 0x07, 0xf3, -1}},
  {{0x68, 0x6a, 0xf0, 0x30, 0x00, 0xf2, -1}, {0x48, 0x6b, 0x10, 0x70, 0x00, 0xdc, 0x82, 0x00, 0x00, 0x91, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0x01, 0xc4, -1}, {0x48, 0x6b, 0x10, 0x41, 0x01, 0x86, 0x07, 0x61, 0x61, 0x54, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0x03, 0xc6, -1}, {0x48, 0x6b, 0x10, 0x41, 0x03, 0x01, 0x00, 0x08, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0x04, 0xc7, -1}, {0x48, 0x6b, 0x10, 0x41, 0x04, 0x00, 0x08, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0x05, 0xc8, -1}, {0x48, 0x6b, 0x10, 0x41, 0x05, 0x00, 0x09, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0x06, 0xc9, -1}, {0x48, 0x6b, 0x10, 0x41, 0x06, 0x80, 0x8a, -1}},
  /* these are made up, added to make "current data" work */
  {{0x68, 0x6a, 0xf0, 0x01, 0x07, 0xca, -1}, {0x48, 0x6b, 0x10, 0x41, 0x07, 0x00, 0x0b, -1}},
  {{0x68, 0x6a, 0xf0, 0x01, 0x0c, 0xcf, -1}, {0x48, 0x6b, 0x10, 0x41, 0x0c, 0x00, 0x10, -1}},

  /* Honda Civic (benched ECU, extracted from log with log2fake.py) */
  {{ 0x20,0x05,0x00,0x10,0xCB, -1}, { 0x00,0x13,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x21,0x02,0x00,0x10,0x97, -1}},
  {{ 0x20,0x05,0x10,0x10,0xBB, -1}, { 0x00,0x13,0xFF,0xFF,0xFE,0x00,0x01,0xC2,0x00,0x95,0x00,0xE8,0x00,0x00,0xE8,0x00,0x00,0x00,0xC9, -1}},
  {{ 0x20,0x05,0x10,0x10,0xBB, -1}, { 0x00,0x13,0xFF,0xFF,0xFE,0x00,0x01,0xC2,0x00,0x96,0x00,0xE8,0x00,0x00,0xE8,0x00,0x00,0x00,0xC8, -1}},
  {{ 0x20,0x05,0x10,0x10,0xBB, -1}, { 0x00,0x13,0xFF,0xFF,0xFE,0x00,0x01,0xC2,0x00,0x97,0x00,0xE8,0x00,0x00,0xE8,0x00,0x00,0x00,0xC7, -1}},
  {{ 0x20,0x05,0x10,0x10,0xBB, -1}, { 0x00,0x13,0xFF,0xFF,0xFE,0x00,0x01,0xC2,0x00,0x98,0x00,0xE8,0x00,0x00,0xE8,0x00,0x00,0x00,0xC6, -1}},
  {{ 0x20,0x05,0x10,0x10,0xBB, -1}, { 0x00,0x13,0xFF,0xFF,0xFE,0x00,0x01,0xC2,0x00,0x99,0x00,0xE8,0x00,0x00,0xE8,0x00,0x00,0x00,0xC5, -1}},
  {{ 0x20,0x05,0x10,0x10,0xBB, -1}, { 0x00,0x13,0xFF,0xFF,0xFE,0x00,0x01,0xC3,0x00,0x95,0x00,0xE8,0x00,0x00,0xE8,0x00,0x00,0x00,0xC8, -1}},
  {{ 0x20,0x05,0x10,0x10,0xBB, -1}, { 0x00,0x13,0xFF,0xFF,0xFE,0x00,0x01,0xC3,0x00,0x96,0x00,0xE8,0x00,0x00,0xE8,0x00,0x00,0x00,0xC7, -1}},
  {{ 0x20,0x05,0x10,0x10,0xBB, -1}, { 0x00,0x13,0xFF,0xFF,0xFE,0x00,0x01,0xC3,0x00,0x97,0x00,0xE8,0x00,0x00,0xE8,0x00,0x00,0x00,0xC6, -1}},
  {{ 0x20,0x05,0x20,0x10,0xAB, -1}, { 0x00,0x13,0x80,0x00,0x80,0x00,0x00,0x00,0x2B,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x00,0x00,0xAF, -1}},
  {{ 0x20,0x05,0x30,0x10,0x9B, -1}, { 0x00,0x13,0x00,0x00,0x2D,0x37,0x00,0x2D,0x07,0x2D,0x19,0x19,0x19,0x00,0xFF,0x00,0x00,0x00,0xDE, -1}},
  {{ 0x20,0x05,0x76,0x0A,0x5B, -1}, { 0x00,0x0D,0x00,0x00,0x00,0x96,0x05,0x10,0x14,0x00,0x07,0x00,0x2D, -1}},
  {{ 0x20,0x05,0x90,0x10,0x3B, -1}, { 0x00,0x13,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x84,0xE1,0x01,0x00,0x00,0x00,0x00,0x00,0x87, -1}},
  {{ 0x20,0x05,0xA0,0x10,0x2B, -1}, { 0x00,0x13,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0xEC, -1}},
  {{ 0x20,0x05,0xB0,0x10,0x1B, -1}, { 0x00,0x13,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xED, -1}},
  {{ 0x20,0x05,0xF0,0x10,0xDB, -1}, { 0x00,0x13,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xED, -1}},

  {{-1}, {-1}},
};

static int *get_obd_reply(int *msg)
{
  int i, j;
  int count = 0;
  int *replies[10];
  static unsigned int reply_cycle = 0;
  for (i = 0; obd_replies[i][0][0] != -1; i++) {
    for (j = 0; obd_replies[i][0][j] != -1; j++) {
      if (obd_replies[i][0][j] != msg[j])
        break;
    }
    if (obd_replies[i][0][j] == -1) {
      DEBUG(IFACE, "IFACE fake OBD reply %d found!\n", count);
      replies[count++] = obd_replies[i][1];
      if (count == 10)
        break;
    }
  }
  if (count == 0) {
    DEBUG(IFACE, "IFACE no fake OBD reply found\n");
    return obd_replies[i][1];
  }
  int *reply;
  if (count > 1) {
    DEBUG(IFACE, "IFACE fake OBD reply %d chosen\n", reply_cycle % count);
    reply = replies[reply_cycle % count];
    reply_cycle++;
  }
  else
    reply = replies[0];
  return reply;
}

void IfaceFake::sendSlowInit(uint8_t target)
{
  DEBUG(IFACE, "IFACE sending slow init to %02X\n", target);
  astate = FAKE_ASTATE_SLOW_INIT_KW_SENT;
  delay = cpu->getCycles() + 
          100 * 10000 +	/* standard says 30 - 200 ms, we use 100 ms */
          200 * 10000;	/* we also have to take the time for the last bit of 
                           the slow init into account; yes, the CARB OBD-II
                           code _is_ that picky... */
  slow_init_target = target;
  if (target < 0x30)	/* sounds like VAG to me... */
    hyundai = false;
  else
    hyundai = true;
}

void IfaceFake::setBaudDivisor(int divisor)
{
  if (baud_divisor != divisor) {
    baud_divisor = divisor;
    serial->flushRxBuf();
  }
  /* no serial buffer flushing, it might contain our crafted response */
  ui->setBaudrate(10400, cpu->serDivToBaud(divisor));
}

void IfaceFake::sendByte(uint8_t byte)
{
  if (astate == FAKE_ASTATE_IDLE &&
      (baud_divisor == 0x77 || baud_divisor == 0x76 || baud_divisor == 0x81)
     ) {
    DEBUG(IFACE, "IFACE starting OBD message\n");
    astate = FAKE_ASTATE_OBD_COMPOSING;
    obd_ptr = 0;
    obd_message[obd_ptr++] = byte;
    /* don't change state until no byte has been written for some time */
    delay = cpu->getCycles() + 8 * baud_divisor * 10 * 2;
  }
  else if (astate == FAKE_ASTATE_OBD_COMPOSING) {
    obd_message[obd_ptr++] = byte;
    /* don't change state until no byte has been written for some time */
    delay = cpu->getCycles() + 8 * baud_divisor * 10 * 2;
  }
  else if (astate == FAKE_ASTATE_SLOW_INIT_WAIT_FOR_CHECK_BYTE) {
    if (byte == slow_init_check_byte) {
      DEBUG(IFACE, "IFACE slow init: got expected byte %02X\n", byte);
    }
    else {
      DEBUG(IFACE, "IFACE slow init: unexpected byte %02X\n", byte);
    }
    astate = FAKE_ASTATE_SLOW_INIT_CHECK_BYTE_RECEIVED;
    delay = cpu->getCycles() + 1000;
  }
  else if (astate == FAKE_ASTATE_IDLE && byte == 0xf1) {
    astate = FAKE_ASTATE_CAN_START;
    can_ptr = 0;
    serial->flushRxBuf();
  }
  else if (astate == FAKE_ASTATE_CAN_START) {
    can_mode = byte;
    astate = FAKE_ASTATE_CAN_LENGTH;
  }
  else if (astate == FAKE_ASTATE_CAN_LENGTH) {
    can_length = byte;
    if (!can_length)
      astate = FAKE_ASTATE_CAN_ANSWERING;
    else
      astate = FAKE_ASTATE_CAN_COMPOSING;
  }
  else if (astate == FAKE_ASTATE_CAN_COMPOSING) {
    can_message[can_ptr++] = byte;
    if (can_ptr == can_length)
      astate = FAKE_ASTATE_CAN_ANSWERING;
  }
}

void IfaceFake::checkInput()
{
  if (cpu->getCycles() < delay)
    return;

  if (astate == FAKE_ASTATE_OBD_COMPOSING) {
    DEBUG(IFACE, "IFACE OBD message complete, %d bytes: ", obd_ptr);
    int i;
    for (i = 0; i < obd_ptr; i++)
      DEBUG(IFACE, "%02X ", obd_message[i]);
    DEBUG(IFACE, "\n");
    
    astate = FAKE_ASTATE_OBD_ANSWERING;
    delay = cpu->getCycles() + 3000;
    obd_message[obd_ptr] = -1;
    DEBUG(IFACE, "IFACE transmitting OBD message\n");
    obd_request = obd_message;
  }
  else if (astate == FAKE_ASTATE_OBD_ANSWERING) {
    obd_reply = get_obd_reply(obd_request);
    serial->addRxData(obd_reply);
    astate = FAKE_ASTATE_IDLE;
  }
  else if (astate == FAKE_ASTATE_SLOW_INIT_KW_SENT) {
    DEBUG(IFACE, "IFACE adding slow init msg\n");
    serial->addRxData(0x55);
    astate = FAKE_ASTATE_SLOW_INIT_PAUSE_AFTER_55;
    delay = cpu->getCycles() + 6 * 10000;	/* standard says wait 5 ms - 20 ms */
  }
  else if (astate == FAKE_ASTATE_SLOW_INIT_PAUSE_AFTER_55) {
    if (hyundai) {
      static const int slow_init_msg[] = {0x08, 0x08, -1};
      serial->addRxData(slow_init_msg);
      slow_init_check_byte = (~slow_init_msg[2]) & 0xff;
    }
    else {
      static const int slow_init_msg[] = {0x01, 0x8a, -1};
      serial->addRxData(slow_init_msg);
      slow_init_check_byte = (~slow_init_msg[2]) & 0xff;
    }
    astate = FAKE_ASTATE_SLOW_INIT_WAIT_FOR_CHECK_BYTE;
  }
  else if (astate == FAKE_ASTATE_SLOW_INIT_CHECK_BYTE_RECEIVED) {
    if (hyundai) {
      /* it seems that even S-System - which never expects any echo anywhere -
         wants the check byte to be echoed...
         fortunately, at this point, auto-echo is made sure to be on, so we
         don't have to care */
      int slow_init_epilog[] = {0xcc, -1};
      slow_init_epilog[0] = (~slow_init_target) & 0xff;
      serial->addRxData(slow_init_epilog);
    }
    else {
      /* AUDI simulation */
      /* XXX: this is massively broken because we have to inline the echos
         of the confirmation bytes sent by the tester into the epilog,
         but of course the serial port will add the echos once more to
         the end of its input buffer... */
      int slow_init_epilog[] = {0x0f, 0xf0, 0x01, 0xfe, 0xf6, 0x09, 0x30, 0xcf,
                                0x33, 0xcc, 0x30, 0xcf, 0x39, 0xc6, 0x30, 0xcf,
                                0x36, 0xc9, 0x30, 0xcf, 0x33, 0xcc, 0x32, 0xcd,
                                0x45, 0xba, 0x20, 0xdf, 0x20, 0xdf, 0x03, -1};
      serial->addRxData(slow_init_epilog);
    }
    astate = FAKE_ASTATE_IDLE;
  }
  else if (astate == FAKE_ASTATE_CAN_ANSWERING) {
    DEBUG(IFACE, "IFACE CAN message complete, mode %02X, %d bytes: ", can_mode, can_ptr);
    int i;
    for (i = 0; i < can_ptr; i++)
      DEBUG(IFACE, "%02X ", can_message[i]);
    DEBUG(IFACE, "\n");
    static int can_reply[100];
    memset((void *)can_reply, 0, 100 * sizeof(int));
    can_reply[0] = 0x42;
    can_reply[1] = 0xf2;
    can_reply[2] = 0xff;
    can_reply[3] = 0;
    can_reply[4] = -1;
    switch (can_mode) {
      case 0xfa:
        can_reply[2] = 0xf6;
        can_reply[3] = 0;
        can_reply[4] = -1;
        break;
      case 0xfb:
        can_reply[2] = 0xfc;
        can_reply[3] = 10;
        can_reply[4] = 0xfc;
        can_reply[5] = 0xe0;
        can_reply[6] = 0x70;
        can_reply[7] = 1;
        can_reply[14] = -1;
        //can_reply[12] = 0xf2;
        //can_reply[13] = 0xfd;
        //can_reply[14] = 0;
        //can_reply[15] = -1;
        break;
      case 0xfc:
        can_reply[2] = 0xfc;
        can_reply[3] = 10;
        can_reply[4] = 0xfc;
        can_reply[5] = 0xe0;
        can_reply[6] = 0x60;
        can_reply[7] = 1;
        can_reply[8] = 0x50;
        can_reply[14] = -1;
        break;
    };
    serial->addRxData(can_reply);
    //serial->addRxData(can_reply + 1);
    astate = FAKE_ASTATE_IDLE;
  }
}

bool IfaceFake::isInInputBuffer(uint8_t byte)
{
  int i = 0;
  for (i = in_buf_start; i != in_buf_end; i = (i + 1) % in_buf_size)
    if (in_buf[i] == byte)
      return true;
  return false;
}

char *IfaceFake::getInputBuffer()
{
  int current_buf_size = in_buf_end - in_buf_start;
  if (current_buf_size < 0)
    current_buf_size += in_buf_size;
  char *buf = (char *)malloc(current_buf_size + 1);
  char *ret = buf;
  for (; in_buf_start != in_buf_end; in_buf_start = (in_buf_start + 1) % in_buf_size)
    *buf++ = in_buf[in_buf_start];
  *buf = 0;
  return ret;
}

void IfaceFake::slowInitImminent()
{
}
