/*
 *  zwickroll.c
 *
 *  This is a variation of the standard AsonHandler which does not 
 *  clear the garbage away before writing. This lead to lost data with 
 * the zwickroll machine.
 *
 * This is actually a fix rather then a solution. The Zwickroll test rig
 * sends unsolicited messages. A better way to deal with this is to store them all 
 * in a queue which clients can inspect and consume from. Or use a callback system
 * for processing incoming messages.   
 *
 *  Created on: December, 4, 2013
 *      Author: koennecke
 */
#include <errno.h>
#include <ascon.h>
#include <ascon.i>

/*-----------------------------------------------------------
 * I am abusing the echo field as a flag if we are reading
 * an echo char or not
-----------------------------------------------------------*/
static int ZwickrollHandler(Ascon *a)
{
  int ret, l;

  switch(a->state){
  case AsconWriting:
    l = GetDynStringLength(a->wrBuffer) - a->wrPos;
    ret = AsconWriteChars(a->fd, GetCharArray(a->wrBuffer) + a->wrPos, l);
    if (ret < 0) {
      AsconError(a, "ASC4", errno); /* sets state to AsconFailed */ 
    } else {
      a->wrPos += ret;
      if (a->wrPos >= GetDynStringLength(a->wrBuffer)) {
        a->state = AsconWriteDone;
      }
    }
    break;
  case AsconReading:
  default:
    return AsconStdHandler(a);
  }
  return 1;
}
/*------------------------------------------------------------------------*/
void AddZwickrollProtocoll()
{
  AsconProtocol *prot = NULL;

  prot = calloc(sizeof(AsconProtocol), 1);
  prot->name = strdup("zwickroll");
  prot->init = AsconStdInit;
  prot->handler = ZwickrollHandler;
  AsconInsertProtocol(prot);
}
