/*---------------------------------------------------------------------------
                      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/tecc.h"
#include "tecs/str_util.h"
#include "tecs/errhdl.h"
  extern pServer pServ;

#include "evdriver.i"  

/*------------------------- The Driver ------------------------------------*/

   pEVDriver CreateTecsDriver(int argc, char *argv[]);
      
      
/*-----------------------------------------------------------------------*/
  typedef struct {
                   void *pData;
                   char *lastError;
                   int iLastError, port;
                   char server[256];
                 } TecsDriv, *pTecsDriv;


  static time_t lastGet=0;

/*-------------------------------------------------------------------------*/
  int TecsWrapper(SConnection *pCon, SicsInterp *pSics, void *pData,
                  int argc, char *argv[])
  {
    pEVControl self = NULL;
    char pBueffel[256];
    int iRet;
    double fNum;
    float fVal;
    pEVDriver pD;
    pTecsDriv pMe;
    char *dev;
    
    self = (pEVControl)pData;
    assert(self);
    assert(pCon);
    assert(pSics);
    
    if(argc < 2)
    {
      return EVControlWrapper(pCon,pSics,pData,argc,argv);
    }
    
    strtolower(argv[1]);
    if (strcmp(argv[1],"device") == 0)
    {
       if(argc > 2) /* set case */
       {
         iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&fNum);
         if(iRet != TCL_OK)
         {
           sprintf(pBueffel,"ERROR: expected number, got %s",argv[2]);
           SCWrite(pCon,pBueffel,eError);
           return 0;
         }
         pD=self->pDriv; assert(pD);
         pMe=pD->pPrivate; assert(pMe);
         iRet=TeccSetDev(pMe->pData,argv[2]);
         if (iRet<0) {
           sprintf(pBueffel,"ERROR: %s",ErrMessage);
           SCWrite(pCon,pBueffel,eError);
           return 0;
         }
         return 1;
       }
       else /* get case */
       {
         pD=self->pDriv; assert(pD);
         pMe=pD->pPrivate; assert(pMe);
         dev=TeccGetDev(pMe->pData);
         if (dev==NULL) {
           sprintf(pBueffel,"ERROR: %s",ErrMessage);
           SCWrite(pCon,pBueffel,eError);
           return 0;
         }
         sprintf(pBueffel,"%s.%s = %s\n",self->pName,
                  argv[1],dev);
         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;
     
     assert(self);
     pMe = (pTecsDriv)self->pPrivate;
     assert(pMe);   

     time(&now);
     if (now>lastGet) {
       lastGet=now;
     } else {
       SicsWait(1); /* avoid extensive network traffic */
     }

     /* get temperature */
     iRet = TeccGet(pMe->pData, fPos);
     if(iRet < 0 )
     {
       pMe->lastError = ErrMessage;
       pMe->iLastError=1; /* severe */
       return 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;
 }
/*--------------------------------------------------------------------------*/
  static 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 0;
     }
     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 *pStart = NULL, *pBin=NULL, *pLog=NULL, *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;

     /* get the start server option */
     pStart = IFindOption(pSICSOptions, "TecsStartCmd");
     if (pStart==NULL) return(NULL);
     str_copy(pMe->server, pStart);

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

     /* get the instrument name */
     pInst = FindVariable(pServ->pSics,"instrument");
     if (pInst==NULL ||
         pInst->text==NULL ||
         strlen(pInst->text)>sizeof(pMe->server)-6) return NULL;
     str_append(pMe->server, " -n tecs_");
     str_append(pMe->server, pInst->text);

     /* add binDir option if present */
     pBin = IFindOption(pSICSOptions, "TecsBinDir");
     if (pBin!=NULL) {
       str_append(pMe->server, " -b ");
       str_append(pMe->server, pBin);
     }
     /* add logDir option if present */
     pLog = IFindOption(pSICSOptions, "TecsLogDir");
     if (pLog!=NULL) {
       str_append(pMe->server, " -d ");
       str_append(pMe->server, pLog);
     }
     str_append(pMe->server, " &");
     
     /* 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; 
  }	
