/*---------------------------------------------------------------------------
                      T E C S D R I V . C

  This is the implementation for TECS object derived from an more general
  environment controller. At present, TECS is used for driving the
  LakeShore 340 Temperature Controller.
  
  Markus Zolliker, March 2000
  
       Copyright:

       Labor fuer Neutronenstreuung
       Paul Scherrer Institut
       CH-5423 Villigen-PSI


      The authors hereby grant permission to use, copy, modify, distribute,
      and license this software and its documentation for any purpose, provided
      that existing copyright notices are retained in all copies and that this
      notice is included verbatim in any distributions. No written agreement,
      license, or royalty fee is required for any of the authorized uses.
      Modifications to this software may be copyrighted by their authors
      and need not follow the licensing terms described here, provided that
      the new terms are clearly indicated on the first page of each file where
      they apply.

      IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
      FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
      ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
      DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
      POSSIBILITY OF SUCH DAMAGE.

      THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
      INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
      FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
      IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
      NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
      MODIFICATIONS.
----------------------------------------------------------------------------*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/time.h>
#include <tcl.h>
#include <fortify.h>
#include <sics.h>
#include <splitter.h>
#include <obpar.h>
#include <devexec.h>
#include <nserver.h>
#include <interrupt.h>
#include <emon.h>
#include <evcontroller.h>
#include <evcontroller.i>
#include "tecsdriv.h"
#include <servlog.h>
#include <sicsvar.h>
#include "tecs/coc_util.h"
#include "tecs/tecs_cli.h"
#include "tecs/myc_str.h"
#include "tecs/myc_err.h"
#include <evdriver.i>
#include "statistics.h"

/*-----------------------------------------------------------------------*/
typedef struct {
  void *pData;
  char *lastError;
  time_t lastGet, lastGetX;
  float lastValue, lastPos, lastDelta;
  int iLastError, port;
  int (*EVLimits) (void *, float, char *, int);
  char server[256];
} TecsDriv, *pTecsDriv;

typedef struct {
  char *buffer;
  int size;
} Buffer;

void outFunc(char *str, void *arg)
{
  Buffer *buffer = arg;
  str_ncat(buffer->buffer, str, buffer->size);
  str_ncat(buffer->buffer, "\n", buffer->size);
}

/*-------------------------------------------------------------------------*/

int TecsWrapper(SConnection * pCon, SicsInterp * pSics, void *pData,
                int argc, char *argv[])
{
  pEVControl self = NULL;
  char pBueffel[1024], result[1024], *res;
  int iRet = -1;
  pEVDriver pD;
  pTecsDriv pMe;
  float fVal;
  Buffer buffer;
  ObPar *pPar;

  self = (pEVControl) pData;
  assert(self);
  assert(pCon);
  assert(pSics);

  if (argc < 2) {
    return EVControlWrapper(pCon, pSics, pData, argc, argv);
  }

  pD = self->pDriv;
  assert(pD);
  pMe = pD->pPrivate;
  assert(pMe);
  snprintf(pBueffel, sizeof pBueffel, " %s ", argv[1]);
  strtolower(pBueffel);
  if (0 == strcmp(pBueffel, " targetvalue ")) {
    if (argc == 2) {
      iRet = CocGet(pMe->pData, "set", result); /* get parameter */
      if (iRet < 0)
        goto Error;
      self->fTarget = atof(result);
    }
    return EVControlWrapper(pCon, pSics, pData, argc, argv);
  } else if (0 == strcmp(pBueffel, " get ")) {
    buffer.buffer = result;
    buffer.size = sizeof result;
    result[0] = '\0';
    iRet = TeccGetMult(pMe->pData, argc - 2, argv + 2, outFunc, &buffer);
    if (iRet < 0)
      goto Error;
    SCWrite(pCon, result, eValue);
    return 1;
  } else if (0 == strcmp(pBueffel, " list ")) {
    iRet = CocGet(pMe->pData, "set", result);   /* get parameter */
    if (iRet < 0)
      goto Error;
    self->fTarget = atof(result);
    iRet = CocGet(pMe->pData, "tlimit", result);        /* get parameter */
    if (iRet < 0)
      goto Error;
    iRet = EVCGetPar(self, "upperlimit", &fVal);
    if (abs(fVal - atof(result)) > 1.0e-4 * abs(fVal)) {
      fVal = atof(result);
      pPar = ObParFind(self->pParam, "upperlimit");
      if (pPar != NULL) {
        pPar->fVal = fVal;
      }
    }
    iRet = EVControlWrapper(pCon, pSics, pData, argc, argv);
    if (iRet != 0) {
      iRet = CocGet(pMe->pData, "status", result);      /* show status */
      if (iRet < 0)
        goto Error;
      SCWrite(pCon, result, eValue);
    }
    return iRet;
  } else if (0 == strcmp(pBueffel, " upperlimit ")) {
    if (argc == 3) {
      iRet = CocSetGet(pMe->pData, "tLimit", argv[2], result);  /* set and get parameter */
      res = strchr(result, '=');
      if (res != NULL) {
        str_copy(result, res + 1);
      }
    } else if (argc == 2) {
      iRet = CocGet(pMe->pData, "tLimit", result);      /* get parameter */
    }
    if (iRet < 0)
      goto Error;
    fVal = atof(result);
    if (argc == 3 && atof(argv[2]) > fVal) {
      snprintf(pBueffel, sizeof pBueffel,
              "WARNING: upper limit reduced to maximal allowed value: %g",
              fVal);
      SCWrite(pCon, pBueffel, eWarning);
    }
    if (argc == 3) {
      iRet = EVCSetPar(self, "upperlimit", fVal, pCon);
    } else {
      pPar = ObParFind(self->pParam, "upperlimit");
      if (pPar != NULL) {
        pPar->fVal = fVal;
      }
      iRet = 1;
    }
    if (iRet) {
      snprintf(pBueffel, sizeof pBueffel,
               "%s.%s = %s\n", self->pName, argv[1], result);
      SCWrite(pCon, pBueffel, eValue);
    }
    return iRet;
  } else if (0 == strcmp(pBueffel, " lowerlimit ")) {
    if (argc > 2) {
      if (atof(argv[2]) > ObVal(self->pParam, UPLIMIT)) {
        SCWrite(pCon,
                "ERROR: lower limit must not be higher than upperlimit",
                eError);
        return 0;
      }
    }
    return EVControlWrapper(pCon, pSics, pData, argc, argv);
  } else if (NULL !=
             strstr
             (" log send tolerance access errorhandler interrupt interest uninterest safevalue currentvalue maxwait settle errorscript runscript driver ",
              pBueffel)) {
    /* forward to standard handler */
    return EVControlWrapper(pCon, pSics, pData, argc, argv);
  }
  if (argc > 2) {               /* set case */
    iRet = CocSet(pMe->pData, argv[1], argv[2]);
    if (iRet < 0)
      goto Error;
    return 1;
  } else {                      /* get case (or command without parameter) */
    if (0 == strcasecmp(argv[1], "kill")) {
      iRet = CocSet(pMe->pData, "quit", "1");   /* send quit flag */
      strcpy(result, "1");
    } else {
      iRet = CocGet(pMe->pData, argv[1], result);       /* get parameter */
    }
    if (iRet < 0)
      goto Error;
    snprintf(pBueffel, sizeof pBueffel,
             "%s.%s = %s\n", self->pName, argv[1], result);
    SCWrite(pCon, pBueffel, eValue);
    return 1;
  }
  /* not reached */
Error:
  sprintf(pBueffel, "ERROR in TECS: %s", ErrMessage);
  SCWrite(pCon, pBueffel, eError);
  return 0;
}

/*----------------------------------------------------------------------------*/

static int TecsGet(pEVDriver self, float *fPos)
{
  pTecsDriv pMe = NULL;
  int iRet;
  time_t now;
  static Statistics *stat = NULL;
  Statistics *old;

  assert(self);
  pMe = (pTecsDriv) self->pPrivate;
  assert(pMe);

  time(&now);
  if (now != pMe->lastGet) {    /* TecsGet was not yet called within this second */
    pMe->lastGet = now;
  } else {                      /* do not call tecs again, as we have already quite recent values */
    *fPos = pMe->lastValue;
    pMe->iLastError = 0;
    return 1;
  }

  if (stat == NULL)
    stat = StatisticsNew("TecsGet");
  old = StatisticsBegin(stat);

  /* get temperature */
  iRet = TeccGet(pMe->pData, fPos);
  StatisticsEnd(old);

  pMe->lastValue = *fPos;
  if (iRet < 0) {
    pMe->lastError = ErrMessage;
    pMe->iLastError = 1;        /* severe */
    return 0;
  }
  pMe->iLastError = 0;
  return 1;
}

/*----------------------------------------------------------------------------*/

static int TecsGetX(pEVDriver self, float *fTarget, float *fPos,
                    float *fDelta)
{
  pTecsDriv pMe = NULL;
  int iRet;
  time_t now;
  static Statistics *stat = NULL;
  Statistics *old;

  assert(self);
  pMe = (pTecsDriv) self->pPrivate;
  assert(pMe);

  time(&now);
  if (now != pMe->lastGetX) {   /* TecsGetX was not yet called within this second */
    pMe->lastGetX = now;
  } else {                      /* do not call tecs again, as we have already quite recent values */
    *fPos = pMe->lastPos;
    *fDelta = pMe->lastDelta;
    pMe->iLastError = 0;
    return 1;
  }

  if (stat == NULL)
    stat = StatisticsNew("TecsGetX");
  old = StatisticsBegin(stat);

  /* get temperatures */
  iRet = TeccGetX(pMe->pData, fTarget, fPos, fDelta);
  StatisticsEnd(old);

  pMe->lastPos = *fPos;
  pMe->lastDelta = *fDelta;
  if (iRet < 0) {
    pMe->lastError = ErrMessage;
    pMe->iLastError = 1;        /* severe */
    return 0;
  }
  pMe->iLastError = 0;
  return 1;
}

/*----------------------------------------------------------------------------*/
static int TecsRun(pEVDriver self, float fVal)
{
  pTecsDriv pMe = NULL;
  int iRet;

  assert(self);
  pMe = (pTecsDriv) self->pPrivate;
  assert(pMe);

  /* set temperature */
  iRet = TeccSet(pMe->pData, fVal);
  if (iRet < 0) {
    pMe->iLastError = 1;        /* severe */
    pMe->lastError = ErrMessage;
    return 0;
  }
  return 1;
}

/*--------------------------------------------------------------------------*/
int TecsError(pEVDriver self, int *iCode, char *error, int iErrLen)
{
  pTecsDriv pMe = NULL;

  assert(self);
  pMe = (pTecsDriv) self->pPrivate;
  assert(pMe);

  *iCode = pMe->iLastError;
  if (pMe->lastError == NULL) {
    str_ncpy(error, "undefined error", iErrLen);
  } else {
    str_ncpy(error, pMe->lastError, iErrLen);
    str_ncat(error, " (TECS)", iErrLen);
  }
  return 1;
}

/*---------------------------------------------------------------------------*/
static int TecsFix(pEVDriver self, int iError)
{
  pTecsDriv pMe = NULL;
  int iRet;

  assert(self);
  pMe = (pTecsDriv) self->pPrivate;
  assert(pMe);
  if (pMe->iLastError == 1) {   /* for Tecs, iLastError means severity level */
    return (DEVFAULT);          /* 1: severe */
  } else {
    return (DEVREDO);           /* 2: try again, good luck! */
  }
}

/*--------------------------------------------------------------------------*/
static int TecsSend(pEVDriver self, char *pCommand, char *pReply, int iLen)
{
  pTecsDriv pMe = NULL;
  int iRet;

  assert(self);
  pMe = (pTecsDriv) self->pPrivate;
  assert(pMe);

  iRet = TeccSend(pMe->pData, pCommand, pReply, iLen);
  if (iRet < 0) {
    pMe->lastError = ErrMessage;
    return 0;
  }
  return 1;

}

/*--------------------------------------------------------------------------*/
static int TecsInit(pEVDriver self)
{
  pTecsDriv pMe = NULL;
  int iRet;

  assert(self);
  pMe = (pTecsDriv) self->pPrivate;
  assert(pMe);

  pMe->pData = TeccInit(pMe->server, pMe->port);
  if (pMe->pData == NULL) {
    pMe->iLastError = 1;        /* severe */
    pMe->lastError = ErrMessage;
    return -1;                  /* fatal */
  }
  return 1;
}

/*--------------------------------------------------------------------------*/
static int TecsClose(pEVDriver self)
{
  pTecsDriv pMe = NULL;
  int iRet;

  assert(self);
  pMe = (pTecsDriv) self->pPrivate;
  assert(pMe);

  TeccClose(pMe->pData);
  pMe->pData = NULL;
  return 1;
}

/*--------------------------------------------------------------------------*/
static int TecsHalt(pEVDriver * self)
{
  assert(self);

  return 1;
}

/*------------------------------------------------------------------------*/
void TecsKill(void *pData)
{
  pTecsDriv pMe = NULL;

  pMe = (pTecsDriv) pData;
  assert(pMe);
  free(pMe);
}

/*------------------------------------------------------------------------*/
pEVDriver CreateTecsDriver(int argc, char *argv[])
{
  pEVDriver pNew = NULL;
  pTecsDriv pMe = NULL;
  pSicsVariable pInst = NULL;
  char *pPort = NULL, *pPath = NULL;
  FILE *fil;
  char buf[256];

  pNew = CreateEVDriver(argc, argv);
  pMe = (pTecsDriv) malloc(sizeof(TecsDriv));
  memset(pMe, 0, sizeof(TecsDriv));
  if (!pNew || !pMe) {
    return NULL;
  }
  pNew->pPrivate = pMe;
  pNew->KillPrivate = TecsKill;

  /* initalise pTecsDriver */
  pMe->lastError = NULL;

  pMe->port = 0;
  pMe->server[0] = '\0';

  pPath = IFindOption(pSICSOptions, "TecsInit");
  if (pPath != NULL) {
    fil = fopen(pPath, "r");
    if (fil != NULL) {
      pPort = fgets(buf, sizeof(buf), fil);
      if (pPort != NULL) {
        pMe->port = atoi(pPort);
      }
      fgets(buf, sizeof(buf), fil);
      fgets(pMe->server, sizeof(pMe->server), fil);
    }
  }

  if (pMe->port == 0) {
    /* get the port number for tecs */
    pPort = IFindOption(pSICSOptions, "TecsPort");
    if (pPort != NULL) {
      pMe->port = atoi(pPort);
    }
    if (pMe->port == 0) {
      pMe->port = 9753;
    }
  }

  /* initialise function pointers */
  pNew->SetValue = TecsRun;
  pNew->GetValue = TecsGet;
  pNew->Send = TecsSend;
  pNew->GetError = TecsError;
  pNew->TryFixIt = TecsFix;
  pNew->Init = TecsInit;
  pNew->Close = TecsClose;
  pNew->GetValues = TecsGetX;

  return pNew;
}

/*------------------------------------------------------------------------*/
static int TecsLimits(void *pData, float fVal, char *pError, int iErrLen)
{
  /* wrapper for EVILimits */
  pEVControl pEvc;
  pTecsDriv pMe;
  int iRet;
  float f;
  char result[64];

  pEvc = (pEVControl) pData;
  assert(pEvc);
  pMe = pEvc->pDriv->pPrivate;
  assert(pMe);
  iRet = CocGet(pMe->pData, "tLimit", result);  /* get parameter */
  if (iRet >= 0) {
    f = 0.0;
    f = atof(result);
    if (f > 0.0)
      pEvc->pParam[UPLIMIT].fVal = f;
  }
  return pMe->EVLimits(pData, fVal, pError, iErrLen);
}

/*------------------------------------------------------------------------*/
void TecsCustomize(SConnection * pCon, pEVControl pEvc)
{
  /* customize tecs driver */
  pTecsDriv pMe;

  pMe = pEvc->pDriv->pPrivate;
  assert(pMe);
  assert(pMe->EVLimits != pEvc->pDrivInt->CheckLimits);
  pMe->EVLimits = pEvc->pDrivInt->CheckLimits;  /* save original CheckLimits function */
  pEvc->pDrivInt->CheckLimits = TecsLimits;
  EVCSetPar(pEvc, "upperlimit", 1800.0, pCon);
  EVCSetPar(pEvc, "lowerlimit", 0.0, pCon);
}
