/* $Id: sp03.c,v 1.1 2010/10/19 05:18:47 bsd Exp $ */

#include <util/twi.h>


#include "i2c.h"
#include "sp03.h"

static uint8_t sp03_init1[] = { 0x00, 0x00 };
static uint8_t sp03_init2[] = { 0x00, 0x00 };
static uint8_t sp03_init3[] = { 0x00, 0x40 };
uint8_t sp03_vol=0, sp03_speed=3, sp03_pitch=5;

/*
 * speak - direct the SP03 to speak the specified text string
 *
 * Return 0 on success, < 0 if an I2C error occured
 */
int8_t speak(char * s)
{
  uint8_t i;

  /* start condition */
  if (i2c_start(0x08, 1))
    return -1;

  /* address slave device, write */
  if (i2c_sla_rw(0x62, 0, TW_MT_SLA_ACK, 1))
    return -2;

  for (i=0; i<sizeof(sp03_init1); i++) {
    if (i2c_data_tx(sp03_init1[i], TW_MT_DATA_ACK, 1))
      return -3;
  }

  if (i2c_data_tx(sp03_vol, TW_MT_DATA_ACK, 1))
    return -4;

  if (i2c_data_tx(sp03_pitch, TW_MT_DATA_ACK, 1))
    return -5;

  if (i2c_data_tx(sp03_speed, TW_MT_DATA_ACK, 1))
    return -6;

  if (i2c_stop())
    return -7;

  /* start condition */
  if (i2c_start(0x08, 1))
    return -8;

  /* address slave device, write */
  if (i2c_sla_rw(0x62, 0, TW_MT_SLA_ACK, 1))
    return -9;

  for (i=0; i<sizeof(sp03_init2); i++) {
    if (i2c_data_tx(sp03_init2[i], TW_MT_DATA_ACK, 1))
      return -10;
  }

  while (*s) {
    if (i2c_data_tx(*s, TW_MT_DATA_ACK, 1))
      return -11;
    s++;
  }

  if (i2c_data_tx(*s, TW_MT_DATA_ACK, 1))
    return -12;

  if (i2c_stop())
    return -13;

  /* start condition */
  if (i2c_start(0x08, 1))
    return -14;

  /* address slave device, write */
  if (i2c_sla_rw(0x62, 0, TW_MT_SLA_ACK, 1))
    return -15;

  for (i=0; i<sizeof(sp03_init3); i++) {
    if (i2c_data_tx(sp03_init3[i], TW_MT_DATA_ACK, 1))
      return -16;
  }

  if (i2c_stop())
    return -17;

  return 0;
}


/*
 * wait4shutup - wait for the SP03 module to stop talking
 *
 * Return 0 on success, < 0 if an I2C error occured
 */
int8_t wait4shutup(void)
{
  uint8_t cmd = 0xff;

  while (cmd) {
    /* start condition */
    if (i2c_start(0x08, 1))
      return -1;

    /* address slave device, write */
    if (i2c_sla_rw(0x62, 0, TW_MT_SLA_ACK, 1))
      return -2;

    /* send command buffer address */
    if (i2c_data_tx(0x00, TW_MT_DATA_ACK, 1))
      return -3;

    /* repeated start condition */
    if (i2c_start(0x10, 1))
      return -4;

    /* address slave device, read */
    if (i2c_sla_rw(0x62, 1, TW_MR_SLA_ACK, 1))
      return -5;

    /* read command register */
    if (i2c_data_rx(&cmd, I2C_NACK, TW_MR_DATA_NACK, 1))
      return -6;

    if (i2c_stop())
      return -7;
  }

  return 0;
}



