//
// Copyright (c) 1999-2004 Darius Rad
//
// This file is part of the OpenOtto project.
//
// OpenOtto is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//

/// \file
/// \brief ISO 9141 data link layer protocol.
///
/// \todo keep alive?
/// \todo maintain list of open devices?
/// \todo keep timestamp of last rx?


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/types.h>
#include <assert.h>
#include <termios.h>
#include <linux/serial.h>
#include <sys/ioctl.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

#include <otto/otto.h>
#include <otto/packet.h>
#include <otto/device.h>
#include <otto/control.h>


static const char _ID_[] __attribute__ ((unused)) =
"$Id: uart_serial.c,v 1.9 2004/07/07 22:07:11 alpha Exp $";


static const int UART_SERIAL_DEFAULT_RATE = 10400;


/// \brief Driver specific private data for open driver
///
/// Dynamically allocated/freed via open/close
struct uart_serial_priv
{
  int fd;  ///< File descriptor for serial device
  char *file;  ///< Device file
  int rate;  ///< Device data rate
  int flags;  ///< Device flags
  struct
  {
    struct termios tio;  ///< TTY settings
    struct serial_struct ser;  ///< Linux specific bits
  }
  state_cur,  ///< Current device state
  state_old;  ///< Old device state, for restoring on close
  union otto_packet partial;  ///< Partial packet
};


/// \todo save read data in case match is wrong
/// \todo drain read buffer before writing
static int
uart_serial_write_half_duplex(
  int fd,
  const void *buf,
  size_t count
)
{
  ssize_t wcnt;
  ssize_t rcnt;
  unsigned char rbuf[1];


  // write data
  wcnt = write( fd, buf, count );
  if( wcnt <= 0 )
  {
    perror("write");
    return(wcnt);
  }

  int i;
  for( i = 0; i < wcnt; i++ )
  {
    // read back data
    rcnt = read( fd, rbuf, 1 );
    if( rcnt < 0 )
    {
      perror("read");
      return(-1);
    }
    else if( rcnt == 0 )
    {
      // didn't read byte
      perror("read");
      return(-1);
    }

    if( rbuf[0] != ((char*)buf)[i] )
    {
      // read didn't match
      return(-1);
    }
  }

  return(wcnt);
}


static int
uart_serial_read_flush(
  struct otto_device *dev
)
{
  assert( dev != NULL );

  struct uart_serial_priv *priv = dev->priv;

  fd_set fds;
  struct timeval tv;
  int ret;

  FD_ZERO(&fds);
  FD_SET( priv->fd, &fds );

  tv.tv_sec = 0;
  tv.tv_usec = 0;

  do
  {
    // select to see if data available
    ret = select( 1, &fds, NULL, NULL, &tv );
    if( ret == -1 )
    {
      perror("select");
      return(ret);
    }
    else if( ret > 0 )
    {
      unsigned char buf;

      // data available
      ret = read( priv->fd, &buf, sizeof(buf) );
      if( ret == -1 )
      {
	perror("read");
	return(ret);
      }
      else if( ret > 0 )
      {
	priv->partial.raw.data[priv->partial.raw.length++] = buf;
      }
    }
  }
  while( (ret > 0) && (priv->partial.raw.length < OTTO_PACKET_LENGTH_MAX) );

  return(0);
}


static int
uart_serial_init_fast(
  struct otto_device *dev
)
{
  struct uart_serial_priv *priv = dev->priv;
  struct timespec ts;
  ssize_t cnt;
  unsigned char buf[1];


  // prepare baud rate for 0x00 hack to assert bus
  // 25ms is 8 bits at 320 baud ( 1 / (.025/8) )
  // consider start/stop bits? (25ms is 10 bits at 400 baud)
  priv->state_cur.ser.custom_divisor = priv->state_cur.ser.baud_base / 320;
  if( ioctl( priv->fd, TIOCSSERIAL, &priv->state_cur.ser ) != 0 )
  {
    perror("ioctl(,TIOCSSERIAL,)");
    return(-1);
  }

  // wait 300, 55, or 0 ms
  ts.tv_sec = 0;
  ts.tv_nsec = 300 * 1000;
  if( nanosleep( &ts, NULL ) != 0 )
  {
    perror("nanosleep");
    return(-1);
  }

  // send 0x00 to assert bus for 25ms
  buf[0] = 0x00;
  cnt = uart_serial_write_half_duplex( priv->fd, buf, 1 );
  if( cnt < 0 )
  {
    // error
    return(-1);
  }
  else if( cnt != 1 )
  {
    // didn't write byte
    return(-1);
  }

  // set back proper rate
  priv->state_cur.ser.custom_divisor = priv->state_cur.ser.baud_base / priv->rate;
  if( ioctl( priv->fd, TIOCSSERIAL, &priv->state_cur.ser ) != 0 )
  {
    perror("ioctl(,TIOCSSERIAL,)");
    return(-1);
  }

  // wait 25ms +/- 1ms, so specify 24 since OS will wait at least that long
  //   plus, consider stop bit on 0x00 sent at 5 baud
  ts.tv_sec = 0;
  ts.tv_nsec = 24 * 1000;
  nanosleep( &ts, NULL );

  // (then ok to send start comm)

  return(0);
}


static int
uart_serial_init_slow(
  struct otto_device *dev,
  unsigned char adr
)
{
  struct uart_serial_priv *priv = dev->priv;
  struct timespec ts;
  ssize_t cnt;


  // setup for 5 baud transmit
  priv->state_cur.ser.custom_divisor = priv->state_cur.ser.baud_base / 5;
  if( ioctl( priv->fd, TIOCSSERIAL, &priv->state_cur.ser ) != 0 )
  {
    return(-1);
  }

  // wait 300 ms (maybe 55 or 0ms?)
  ts.tv_sec = 0;
  ts.tv_nsec = 300 * 1000;
  nanosleep( &ts, NULL );

  // send address at 5 baud
  cnt = uart_serial_write_half_duplex( priv->fd, &adr, 1 );
  if( cnt < 0 )
  {
    return(-1);
  }
  else if( cnt != 1 )
  {
    // didn't write expected amount
    return(-1);
  }

  // set back proper rate
  priv->state_cur.ser.custom_divisor = priv->state_cur.ser.baud_base / priv->rate;
  if( ioctl( priv->fd, TIOCSSERIAL, &priv->state_cur.ser ) != 0 )
  {
    return(-1);
  }

  // read response, baud rate detect
  // response expected within 300ms

  // (ok to send start comm)

  return(0);
}


static int
uart_serial_control_sbusrate(
  struct otto_device *dev,
  int rate
)
{
  struct uart_serial_priv *priv = dev->priv;

  if( dev->busses[0].rate == rate )
  {
    return(0);
  }

  dev->rate = rate;  // device and bus run at same rate
  dev->busses[0].rate = rate;

  // set baud to "magic" 38400 so custom baud rate below will work
  priv->state_cur.tio.c_cflag &= ~(CBAUD | CBAUDEX);
  priv->state_cur.tio.c_cflag |= B38400; 

  if( tcsetattr( priv->fd, TCSANOW, &priv->state_cur.tio ) != 0 )
  {
    perror("tcsetattr");
    return(-1);
  }

  priv->state_cur.ser.custom_divisor = priv->state_cur.ser.baud_base / rate;
  priv->state_cur.ser.flags &= ~ASYNC_SPD_MASK;
  priv->state_cur.ser.flags |= ASYNC_SPD_CUST;  // use ASYNC_LOW_LATENCY??

  if( ioctl( priv->fd, TIOCSSERIAL, &priv->state_cur.ser ) != 0 )
  {
    perror("ioctl(,TIOCSSERIAL,)");
    return(-1);
  }


  return(0);
}


static struct otto_device *
uart_serial_open(
  const char *fname
)
{
  assert( fname != NULL );

  struct otto_device *dev = NULL;
  struct uart_serial_priv *priv;

  dev = malloc(sizeof(struct otto_device));
  if( dev == NULL )
  {
    perror("malloc");
    return(NULL);
  }

  priv = malloc(sizeof(struct uart_serial_priv));
  if( priv == NULL )
  {
    perror("malloc");
    return(NULL);
  }

  dev->priv = priv;

  memset( priv, 0, sizeof(struct uart_serial_priv) );

  priv->rate = UART_SERIAL_DEFAULT_RATE;

  // open device
  priv->fd = open( dev->file, O_RDWR | O_NOCTTY );
  if( priv->fd < 0 )
  {
    perror("open");
    return(NULL);
  }

  // save setting for restore on close
  if( tcgetattr( priv->fd, &priv->state_old.tio ) != 0 )
  {
    perror("tcgetattr");
    return(NULL);
  }

  if( ioctl( priv->fd, TIOCGSERIAL, &priv->state_old.ser ) != 0 )
  {
    perror("ioctl(,TIOCGSERIAL,)");
    return(NULL);
  }

  // configure device

  // copy current settings to 'current' set, for mangling
  memcpy(
    &priv->state_cur,
    &priv->state_old,
    sizeof(priv->state_cur)
  );

  // set to current rate (or 0, since that won't accomplish much)
  dev->rate = 0;

  dev->nbus = 1;
  dev->busses = malloc( sizeof(struct otto_bus) * dev->nbus );
  if( dev->busses == NULL )
  {
    perror("malloc");
    return(NULL);
  }

  /// initialize busses (only 1)
  dev->busses[0].type = OTTO_LINK_TYPE_ISO;
  dev->busses[0].priv = NULL;

  int ret;

  ret = uart_serial_control_sbusrate( dev, UART_SERIAL_DEFAULT_RATE );
  if( ret != 0 )
  {
    return(NULL);
  }

  return(dev);
}


static int
uart_serial_close(
  struct otto_device *dev
)
{
  struct uart_serial_priv *priv = dev->priv;
  int ret = 0;

  // restore tio, ser settings
  if( ioctl( priv->fd, TIOCSSERIAL, &priv->state_old.ser ) != 0 )
  {
    ret = -1;
  }

  if( tcsetattr( priv->fd, TCSANOW, &priv->state_old.tio ) != 0 )
  {
    ret = -1;
  }

  // close device
  if( close( priv->fd ) != 0 )
  {
    ret = -1;
  }

  free( dev->busses );
  free( dev->priv );
  free( dev );

  return(ret);
}


static int
uart_serial_read(
  struct otto_device *dev,
  int bus,
  union otto_packet *pkt
)
{
  assert( dev != NULL );
  assert( pkt != NULL );

  struct uart_serial_priv *priv = dev->priv;
  int ret;
  int start;
  int len;

  // flush all data to driver buffer
  uart_serial_read_flush(dev);

  // if have full packet, return it
  ret = otto_findpacket( &priv->partial, &start, &len );
  if( ret > 0 )
  {
    // return packet
    memcpy( pkt->raw.data, &(priv->partial.raw.data[start]), len );

    priv->partial.raw.length -= (start + len);
    memmove( &priv->partial.raw.data, &(priv->partial.raw.data[start+len]), priv->partial.raw.length );
  }
  else
  {
    // no packet found, at least one garbage byte, so drop it
    priv->partial.raw.length--;
    memmove( &priv->partial.raw.data, &(priv->partial.raw.data[1]), priv->partial.raw.length );

    // return no packets yet
    ret = 0;
  }

  return(ret);
}


static int
uart_serial_write(
  struct otto_device *dev,
  int bus,
  union otto_packet *pkt
)
{
  assert( dev != NULL );
  assert( pkt != NULL );

  assert( pkt->raw.length > 0 );
  assert( pkt->raw.length <= OTTO_PACKET_LENGTH_MAX );

  struct uart_serial_priv *priv = dev->priv;

  // flush receive data
  uart_serial_read_flush(dev);

  /// \todo if partial packet, abort write? (how to handle many garbage characters? timeout as well?)

  return( uart_serial_write_half_duplex( priv->fd, pkt->raw.data, pkt->raw.length ) );
}


static int
uart_serial_control(
  struct otto_device *dev,
  int bus,
  void *data,
  int cmd
)
{
  assert( dev != NULL );

  union otto_control_data *idat = data;
  int ret = 0;

  switch(cmd)
  {
    case OTTO_IOCBUSINIT:

      if( idat->init.type == OTTO_INIT_SLOW )
      {
	ret = uart_serial_init_slow( dev, idat->init.addr );
      }
      else
      {
	ret = uart_serial_init_fast(dev);
      }
      break;

    case OTTO_IOCSDATARATE:
      ret = uart_serial_control_sbusrate( dev, idat->rate );
      break;

    case OTTO_IOCGDATARATE:
      idat->rate = dev->rate;
      ret = 0;
      break;

    case OTTO_IOCGSELECTFD:
      idat->fd = ((struct uart_serial_priv *)(dev->priv))->fd;
      ret = 0;
      break;

    case OTTO_IOCSBUSADR:
    case OTTO_IOCGBUSADR:
    default:
      ret = -1;
  }

  return(ret);
}


static struct otto_driver uart_serial_drv =
{
  .name = "uart_serial",
  .desc = "Device driver for a ISO 9141 bus over a serial port",
  .author = "Darius Rad <alpha@area49.net>",
  .license = "GPL",
  .open = uart_serial_open,
  .close = uart_serial_close,
  .write = uart_serial_write,
  .read = uart_serial_read,
  .control = uart_serial_control,
};


static void __attribute((constructor))
uart_serial_constructor(void)
{
  otto_register(&uart_serial_drv);
}
