/* i2cLEDhandle.c -- i2c SAA1064 LED functions */

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h> 
#include <exec/types.h>
#include <proto/exec.h>
#include <proto/dos.h>

#include <proto/i2c.h>
#include <libraries/i2c.h>

#include "LED.h"

#include "i2cLEDhandle.h"

#define SAA1064 0x70    /* may be jumpered as 0x72, 0x74, 0x76, too */

struct Library *I2C_Base;

/*
void LibClose( struct Library **ppLib )
{
  if( *ppLib )
  {
    CloseLibrary( *ppLib );
    *ppLib = NULL;
  }
}

void CleanUp()
{                                                   do NOT use: crashes the system!!!
  SendLed( "    " );
  LibClose( &I2C_Base );
  LibClose( (struct Library **)&DOSBase );
}
*/


void CleanUp()
{
  SendLed( "    " );
  CloseLibrary( I2C_Base );
  CloseLibrary( (struct Library *) DOSBase );
}




struct Library* LibOpen( STRPTR strName, LONG lVersion )
{
    struct Library* pLib;

    pLib = OpenLibrary( strName, lVersion );
    if( !pLib )
    {
        printf( "Can't open %s", strName );
        printf( lVersion ? " V%ld+\n" : "\n", lVersion );
        return(NULL);
    }
    else return pLib;
}


BOOL setup_i2cLED(void)
{
    LONG lResult;

    DOSBase  = NULL;
    I2C_Base = NULL;

    if ((I2C_Base = LibOpen( "i2c.library", 39 ) ) == NULL)
    {
#ifdef DEBUG
        printf("i2cLEDhandle.c: Couldn't open i2c.library !\n");
#endif
        return(FALSE);
    }

    if ( (DOSBase  = (struct DosLibrary *)LibOpen( "dos.library", 0 )) == NULL)
    {
#ifdef DEBUG
        printf("i2cLEDhandle.c: Couldn't open dos.library !\n");
#endif
        CloseLibrary( I2C_Base );
        return(FALSE);
    }

    lResult = SendLed("    ");
    if( lResult )
    {
        printf( "I²C bus: error 0x%06lx, %s\n", lResult, I2CErrText( lResult ) );
        return FALSE;
    }

    return(TRUE);
}


void cleanup_i2cLED(void)
{
    CleanUp();
}


BOOL LED_echo(char * msg)
{
    LONG lResult;

    if (msg == NULL) return TRUE;

    lResult = SendLed( msg );
    if( lResult )
    {
        printf( "I²C bus: error 0x%06lx, %s\n", lResult, I2CErrText( lResult ) );
        return FALSE;
    }

    return TRUE;
}

