/*---------------------------------------------------------------------------
                      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 Temperutre 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 <stdlib.h>
#include <assert.h>
#include <sys/time.h>
#include <tcl.h>
#include "fortify.h"
#include "conman.h"
#include "splitter.h"
#include "obdes.h"
#include "interface.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/str_util.h"
#include "tecs/err_handling.h"
  extern pServer pServ;

#include "evdriver.i"  

/*-----------------------------------------------------------------------*/
  typedef struct {
                   void *pData;
                   char *lastError;
                   time_t lastGet;
                   int iLastError, port;
                   char server[256];
                 } TecsDriv, *pTecsDriv;


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

  int TecsWrapper(SConnection *pCon, SicsInterp *pSics, void *pData,
                  int argc, char *argv[])
  {
    pEVControl self = NULL;
    char pBueffel[256], result[256];
    int iRet;
    pEVDriver pD;
    pTecsDriv pMe;
    double fNum;
    float fVal;
    
    self = (pEVControl)pData;
    assert(self);
    assert(pCon);
    assert(pSics);
    
    if(argc < 2)
    {
      return EVControlWrapper(pCon,pSics,pData,argc,argv);
    }
    
    strcpy(pBueffel, " ");
    strcat(pBueffel, argv[1]);
    strcat(pBueffel, " ");
    strtolower(pBueffel);
    if (   NULL==strstr(" log send list tolerance access errorhandler interrupt interest ", pBueffel)
        && NULL==strstr(" upperlimit lowerlimit safevalue currentvalue targetvalue ", pBueffel)
      ) {

      pD=self->pDriv; assert(pD);
      pMe=pD->pPrivate; assert(pMe);
      if(argc > 2) { /* set case */
        iRet=CocSet(pMe->pData,argv[1],argv[2]);
        if (iRet<0) {
          sprintf(pBueffel,"ERROR: %s",ErrMessage);
          SCWrite(pCon,pBueffel,eError);
          return 0;
        }
        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) {
          sprintf(pBueffel,"ERROR: %s",ErrMessage);
          SCWrite(pCon,pBueffel,eError);
          return 0;
        }
        sprintf(pBueffel,"%s.%s = %s\n",self->pName,
                 argv[1],result);
        SCWrite(pCon,pBueffel,eValue);
        return 1;
      }
    } else {
      return EVControlWrapper(pCon,pSics,pData,argc,argv);
    }
    /* not reached */
    return 0; 
  }  

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

  static int TecsGet(pEVDriver  self, float *fPos)
  {
     pTecsDriv pMe = NULL;
     int iRet;
     time_t now;
     static int configuring;
     
     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 {
       CocDelay(200); /* wait 0.2 sec. (seems that SICS has nothing else to do then reading temperatures) */
     }

     /* get temperature */
     iRet = TeccGet(pMe->pData, fPos);
     if (iRet > 0) {
       if (configuring) {
         iRet = TeccWait(pMe->pData);
         iRet = TeccGet(pMe->pData, fPos);
       } else {         
         pMe->lastError = ": controller busy (configuring)";
         pMe->iLastError=2; /* fixable */
         configuring=1;
         return 0;
       }
     }
     configuring=0;
     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);
     }
     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 != 1)
     {
       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;

     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->server[0]='\0';

     /* get the port number for tecs */
     pMe->port=0;
     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;
     
     return pNew; 
  }	
