//
// 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 Test application for OpenOtto/libobd2
///
/// \todo use readline
/// \todo init device, loop allowing input of arbitrary packet as hex bytes


#include <linux/types.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: ottotest.c,v 1.3 2004/07/07 22:07:11 alpha Exp $";


int
main( int argc, char **argv )
{
  struct otto_device *dev;
  union otto_packet pkt;
  union otto_control_data ctl;

  int ret = -1;

  dev = otto_open( "uart_serial", "/dev/ttyUSB0" );
  if( dev == NULL )
  {
    perror("otto_open failed");
    return(ret);
  }

  ctl.init.type = OTTO_INIT_FAST;
  ret = otto_control( dev, 1, &ctl, OTTO_IOCBUSINIT );
  if( ret != 0 )
  {
    perror("otto_control failed");
    return(ret);
  }

  //pkt.raw.data[0] = 0x68;  // prio/type
  pkt.consol3.first.z = 0x0;  // message type
  pkt.consol3.first.y = OTTO_PKTHDR_FUNCTIONAL;
  pkt.consol3.first.k = OTTO_PKTHDR_IFRDISALLOWED;
  pkt.consol3.first.h = OTTO_PKTHDR_THREEBYTE;
  pkt.consol3.first.p = 0x3;  // priority

  //pkt.raw.data[1] = 0x6a;  // target
  //pkt.consol3.func.target = 0x6a
  pkt.consol3.func.target.w = OTTO_FUNCADR_TGTADR_COMMAND;
  pkt.consol3.func.target.id = (0x6a >> 1);

  //pkt.raw.data[2] = 0xf1;  // source
  pkt.consol3.func.source = 0xf1;

  pkt.consol3.func.data.fmt4.mode = 0x01;  // diag mode 1 (req powertrain diag data)
  pkt.consol3.func.data.fmt4.data[0] = 0x00;  // pid 0 (PIDs supported)

  pkt.raw.length = 4;

  otto_crc_calc( &pkt );

  ret = otto_write( dev, 1, &pkt, sizeof(pkt) );
  if( ret != 0 )
  {
    perror("otto_write failed");
    return(ret);
  }

  /*
  ret = otto_read( dev, 1, &pkt, sizeof(pkt) );
  if( ret != 0 )
  {
    return(ret);
  }
  */

  otto_close(dev);

  return(0);
}
