//
// 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 Device interface routes
///
/// \todo allocate/free otto_device/otto_bus structures dynamically in this lib


#include <linux/types.h>
#include <assert.h>
#include <string.h>

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


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


/// List of drivers
static struct otto_driver *g_drv_first = NULL;


void
otto_register(
  struct otto_driver *drv
)
{
  assert( drv != NULL );

  drv->next = NULL;

  if( g_drv_first == NULL )
  {
    g_drv_first = drv;
  }
  else
  {
    struct otto_driver *p = g_drv_first;

    while( p->next != NULL )
    {
      p = p->next;
    }

    p->next = drv;
  }
}


struct otto_device *
otto_open(
  const char *name,
  const char *fname
)
{
  assert( name != NULL );
  assert( fname != NULL );

  struct otto_driver *p = g_drv_first;

  // if no drivers, return error
  for( p = g_drv_first; p != NULL; p = p->next )
  {
    if( strcmp( name, p->name ) == 0 )
      break;
  }


  // driver not found, return error
  if( p == NULL )
    return(NULL);

  /// \todo add dev to dev->drv->dev_first list

  assert( p->open != NULL );

  return( p->open(fname) );
}


int
otto_close(
  struct otto_device *dev
)
{
  assert( dev != NULL );
  assert( dev->drv != NULL );
  assert( dev->drv->close != NULL );

  /// \todo remove dev from dev->drv->dev_first list

  return( dev->drv->close(dev) );
}


int
otto_write(
  struct otto_device *dev,
  int bus,
  union otto_packet *packet,
  size_t size
)
{
  assert( dev != NULL );
  assert( dev->drv != NULL );
  assert( dev->drv->write != NULL );
  assert( packet != NULL );
  assert( size == sizeof(union otto_packet) );

  return( dev->drv->write( dev, bus, packet ) );
}


int
otto_read(
  struct otto_device *dev,
  int bus,
  union otto_packet *packet,
  size_t size
)
{
  assert( dev != NULL );
  assert( dev->drv != NULL );
  assert( dev->drv->read != NULL );
  assert( packet != NULL );
  assert( size == sizeof(union otto_packet) );

  return( dev->drv->read( dev, bus, packet ) );
}


int
otto_control(
  struct otto_device *dev,
  int bus,
  void *data,
  int cmd
)
{
  assert( dev != NULL );
  assert( dev->drv != NULL );
  assert( dev->drv->control != NULL );

  return( dev->drv->control( dev, bus, data, cmd ) );
}


int
otto_getselectfd(
  struct otto_device *dev
)
{
  union otto_control_data data;

  otto_control( dev, 0, &data, OTTO_IOCGSELECTFD );

  return( data.fd );
}


