epicsadapter.c 15.2 KB
Newer Older
koennecke's avatar
koennecke committed
1
/**
2 3 4 5 6 7 8 9
 * This is a general purpose adapter between SICS and EPICS. It provides callbacks 
 * which allows Hipadaba nodes to be connected to EPICS PV's for both reading and 
 * writing. 
 *
 * copyright: see file COPYRIGHT
 *
 * Mark Koennecke, October - November  2014
 */
koennecke's avatar
koennecke committed
10 11 12
#include <assert.h>
#include <sics.h>
#include <sicshipadaba.h>
13
#undef INLINE /* already defined bz tcl.h, breaks EPICS includes */
koennecke's avatar
koennecke committed
14 15
#include <cadef.h>
#include <epicsMessageQueue.h>
16
#include <epicsThread.h>
koennecke's avatar
koennecke committed
17 18
#include <messagepipe.h>

19
/*
20 21
  One of those: alarmString.h cannot be doubly included into the 
  same application
22
*/
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
/*#include <alarmString.h> 
extern char *epicsAlarmConditionStrings[]; */

/* sometimes only this below works, for reasons I do not care to invest time to investigate */
const char * epicsAlarmConditionStrings[] = {
    "NO_ALARM",
    "READ",
    "WRITE",
    "HIHI",
    "HIGH",
    "LOLO",
    "LOW",
    "STATE",
    "COS",
    "COMM",
    "TIMEOUT",
    "HWLIMIT",
    "CALC",
    "SCAN",
    "LINK",
    "SOFT",
    "BAD_SUB",
    "UDF",
    "DISABLE",
    "SIMM",
    "READ_ACCESS",
    "WRITE_ACCESS"
};



54

koennecke's avatar
koennecke committed
55
/*
56 57
 * we have a SICS tasks which polls EPICS regularly.
 */
koennecke's avatar
koennecke committed
58 59 60 61 62 63
static long epicsTaskID = -1L;
static pMP readPipe = NULL;
static epicsMessageQueueId writeQueue;


typedef struct {
64 65 66 67 68
  char pvname[64];
  int connected;
  pHdb node;
  chid pvchid;
  chtype pvtype;
koennecke's avatar
koennecke committed
69 70 71
}EpicsPriv, *pEpicsPriv;

typedef struct {
72 73
  SConnection *pCon;
  char message[512];
koennecke's avatar
koennecke committed
74 75 76 77 78 79 80
} WriteMessage, *pWriteMessage;

/*======================================================================================
  Code for reading PV's
  ======================================================================================*/
static int EpicsTask(void *userData)
{
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
  pWriteMessage mes;

  /*
    drive the main EPICS loop for subscriptions
  */ 
  ca_poll();

  /*
    process possible messages from the writing threads
  */
  if(epicsMessageQueueTryReceive(writeQueue,&mes,sizeof(mes)) > 0){
    if(mes->pCon == NULL){
      traceIO("epics",mes->message);
    } else {
      SCWrite(mes->pCon,mes->message,eError);
      SCDeleteConnection(mes->pCon);
    }
    free(mes);
  }
  return 1;
koennecke's avatar
koennecke committed
101 102 103 104
}  
/*---------------------------------------------------------------------------------------*/
static int makeEPICSContext(void *message, void *userData)
{
105 106 107 108 109 110 111 112 113 114 115 116 117
  int status;
  pEpicsPriv priv = NULL;

  if(epicsTaskID < 0){
    status = ca_context_create(ca_disable_preemptive_callback);
    if(status != ECA_NORMAL){
      priv = (pEpicsPriv)message;
      SetHdbProperty(priv->node,"geterror", "Failed to create EPICS context");
      return MPSTOP;
    }
    epicsTaskID = TaskRegisterN(pServ->pTasker,
				"epics",
				EpicsTask,
118
				NULL,NULL,NULL,TASK_PRIO_LOW
119 120 121
				);
  }
  return MPCONTINUE;
koennecke's avatar
koennecke committed
122 123 124 125
}  
/*--------------------------------------------------------------------------------------*/
static int epicsConnectPV(void *message, void *userData)
{
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
  pEpicsPriv priv = NULL;
  int status;

  priv = (pEpicsPriv)message;

  status = ca_create_channel(priv->pvname,NULL,NULL,10,&priv->pvchid);
  if(status != ECA_NORMAL){
    SetHdbProperty(priv->node,"geterror", "Failed to connect to PV");
    return MPSTOP;
  }
  status = ca_pend_io(0.2);
  if(status != ECA_NORMAL){
    SetHdbProperty(priv->node,"geterror", "Timeout connecting to PV");
    return MPSTOP;
  }
  return MPCONTINUE;
koennecke's avatar
koennecke committed
142 143 144 145
}
/*--------------------------------------------------------------------------------------*/
static void epicsDataCallback(struct event_handler_args args)
{
146 147 148 149 150 151 152 153 154 155
  pEpicsPriv priv = NULL;
  hdbValue v;
  char error[256];

  priv = (pEpicsPriv)args.usr;

  if(args.status == ECA_NORMAL){
    switch(priv->node->value.dataType){
    case HIPTEXT:
      free(priv->node->value.v.text);
156 157 158 159 160
      if(args.type == DBR_STRING){
	priv->node->value.v.text = strdup((char *)args.dbr);
      } else if(args.type == DBR_CHAR) {
	priv->node->value.v.text = strndup((char *)args.dbr,args.count);
      }
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
      break;
    case HIPINT:
      priv->node->value.v.intValue = *(int *)args.dbr;
      break;
    case HIPFLOAT:
      priv->node->value.v.doubleValue = *(double *)args.dbr;
      break;
    case HIPINTAR:
    case HIPINTVARAR:
      v = MakeHdbIntArray(args.count,(int *)args.dbr);
      copyHdbValue(&v,&priv->node->value);
      break;
    case HIPFLOATAR:
    case HIPFLOATVARAR:
      v = MakeHdbFloatArray(args.count,(double *)args.dbr);
      copyHdbValue(&v,&priv->node->value);
      break;
    }
    SetHdbProperty(priv->node,"geterror",NULL);
    traceIO("epics","Received data for %s", priv->node->name);
    NotifyHipadabaPar(priv->node,NULL);
  } else {
    snprintf(error,sizeof(error),"ERROR: %s for node %s", ca_message(args.status), priv->node->name);
    traceIO("epics",error);
    SetHdbProperty(priv->node,"geterror",error);	
  }
koennecke's avatar
koennecke committed
187 188 189 190
}
/*--------------------------------------------------------------------------------------*/
static int epicsSubscribePV(void *message, void *userData)
{
191 192 193 194 195 196 197 198
  pEpicsPriv priv = NULL;
  int status;
  chtype subType = DBR_STRING;
  evid eid;

  priv = (pEpicsPriv)message;
  switch(priv->node->value.dataType){
  case HIPTEXT:
199 200 201 202 203
    if(ca_field_type(priv->pvchid) == DBR_CHAR){
      subType = DBR_CHAR;
    } else {
      subType = DBR_STRING;
    }
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    break;
  case HIPINT:
  case HIPINTAR:
  case HIPINTVARAR:
    subType = DBR_LONG;
    break;
  case HIPFLOAT:
  case HIPFLOATAR:
  case HIPFLOATVARAR:
    subType = DBR_DOUBLE;
    break;
  }

  status = ca_create_subscription(subType,0,priv->pvchid,
				  DBE_VALUE|DBE_ALARM,epicsDataCallback,priv,&eid);
  if(status != ECA_NORMAL){
    SetHdbProperty(priv->node,"geterror", "Failed to subscribe to PV");
    return MPSTOP;
  }


  return MPCONTINUE;
koennecke's avatar
koennecke committed
226 227 228 229
}
/*--------------------------------------------------------------------------------------*/  
static void createEPICSReadPipe()
{
230 231 232 233
  readPipe = MakeMP();
  AppendMPFilter(readPipe,makeEPICSContext,NULL,NULL);
  AppendMPFilter(readPipe,epicsConnectPV,NULL,NULL);
  AppendMPFilter(readPipe,epicsSubscribePV,NULL,NULL);
koennecke's avatar
koennecke committed
234 235 236 237
}
/*--------------------------------------------------------------------------------------*/
static void connectPV(pHdb node, pEpicsPriv priv)
{
238 239 240 241 242 243 244 245
  int status;

  SetHdbProperty(node,"geterror", NULL);
  priv->node = node;
  status = MPprocess(readPipe, priv);
  if(status == MPCONTINUE){
    priv->connected = 1;
  }
koennecke's avatar
koennecke committed
246 247 248 249
}
/*--------------------------------------------------------------------------------------
  This is the Hipadaba callback function
  --------------------------------------------------------------------------------------*/
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
static hdbCallbackReturn EPICSReadCallback(pHdb currentNode, 
					   void *userData,
					   pHdbMessage message)
{
  pEpicsPriv priv = (pEpicsPriv)userData;
  hdbDataMessage *mm = NULL;
  SConnection *con = NULL;
  char *geterror;
  char error[256];
  enum channel_state cs;

  assert(priv != NULL);

  mm = GetHdbGetMessage(message);
  if (mm != NULL) {
    con = mm->callData;

    if(priv->connected != 1){
      connectPV(currentNode, priv);
    }
    cs = ca_state(priv->pvchid);
    if(cs != cs_conn){
      SCWrite(con,"ERROR: epics disconnected", eError);
      return hdbAbort;
    }
    geterror = GetHdbProp(currentNode, "geterror");
    if (geterror != NULL) {
      snprintf(error,sizeof(error),"ERROR: %s", geterror); 
      SCWrite(con, error, eError);
      if (mm->v->dataType == HIPTEXT) {
	if (mm->v->v.text != NULL) {
	  free(mm->v->v.text);
koennecke's avatar
koennecke committed
282
	}
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
	mm->v->v.text = strdup(error);
      }
      return hdbAbort;
    }
    return hdbContinue;
  }

  return hdbContinue;
}
/*------------------------------------------------------------------------------------*/
static int EpicsConnectRead(pSICSOBJ ccmd, SConnection * con,
			    Hdb * cmdNode, Hdb * par[], int nPar)
{
  pHdb node = NULL;
  pEpicsPriv priv = NULL;

  if(nPar < 2){
    SCWrite(con,"ERROR: need node and PV-name arguments to connectread", eError);
    return 0;
  }

  node = FindHdbNode(NULL,par[0]->value.v.text,con);
  if(node == NULL){
    SCPrintf(con,eError,"ERROR: failed to locate node %s", par[0]->value.v.text);
    return 0;
  }

  priv = calloc(1,sizeof(EpicsPriv));
  priv->node = node;
  strncpy(priv->pvname,par[1]->value.v.text,sizeof(priv->pvname));
  SetHdbProperty(node,"readpv", par[1]->value.v.text);
  AppendHipadabaCallback(node,MakeHipadabaCallback(EPICSReadCallback, priv,free));
  connectPV(node,priv);

  SCSendOK(con);

  return 1;
}
koennecke's avatar
koennecke committed
321
/*==============================================================================================
322 323 324 325
  Writing Things. Writing can block, thus it has to run in its own thread. This raises the 
  question how to propagate error messages. The solution is a EPICS message queue to which 
  writing threads post. The epics task will read this queue and do the actual printing in the 
  SICS main thread. A convention: NULL means to print to trace.
326

327
  ================================================================================================*/
328
typedef struct {
329 330 331
  SConnection *pCon;
  hdbValue v;
  char pvName[64];
332 333 334 335
} WritePar, *pWritePar;	
/*----------------------------------------------------------------------------------------------*/
static void writeEpicsMessage(void *target, char *txt)
{
336 337 338 339 340 341 342 343 344 345
  pWriteMessage wm = NULL;

  wm = calloc(1,sizeof(WriteMessage));
  if(wm != NULL){
    if(target != NULL){
      wm->pCon = SCCopyConnection(target);
    }
    strncpy(wm->message,txt,sizeof(wm->message));
    epicsMessageQueueSend(writeQueue,&wm,sizeof(pWriteMessage));
  }
346
}
347 348 349
/*----------------------------------------------------------------------------------------------
  To my surprise this is never called. May be, when the thread terminates anyway, 
  epics does not know anymore that the callback existed or how to call it.
350
  ------------------------------------------------------------------------------------------------*/ 
351 352
static void epicsEndCallback(struct event_handler_args args)
{
353 354 355 356 357
  char message[512];
  snprintf(message,sizeof(message),"%s finished with %s", (char *)args.usr, 
	   ca_message(args.status));
  writeEpicsMessage(NULL,message);
  free(args.usr);
358 359 360 361
}
/*----------------------------------------------------------------------------------------------*/
static void EpicsWriteFunc(void *param)
{
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
  pWritePar wp = (pWritePar)param;
  pWriteMessage wm = NULL;
  int status;
  chid cid;
  char error[512];
  char *pv;

  status = ca_context_create(ca_disable_preemptive_callback);
  if(status != ECA_NORMAL){
    writeEpicsMessage(wp->pCon,"ERROR: failed to create EPICS context for write");
    goto cleanup;
  }
  status = ca_create_channel(wp->pvName,NULL,NULL,10,&cid);
  if(status != ECA_NORMAL){
    snprintf(error,sizeof(error),"ERROR: failed to create EPICS channel for %s", wp->pvName);
    writeEpicsMessage(wp->pCon,error);
    goto cleanup;
  }
  status = ca_pend_io(0.5);
  if(status != ECA_NORMAL){
    snprintf(error,sizeof(error),"ERROR: failed to connect EPICS channel for %s", wp->pvName);
    writeEpicsMessage(wp->pCon,error);
    goto cleanup;
  }

  pv = strdup(wp->pvName);
  switch(wp->v.dataType){
  case HIPINT:
    status = ca_put_callback(DBR_LONG,cid,&wp->v.v.intValue,epicsEndCallback,pv);
    break;
  case HIPFLOAT:
    status = ca_put_callback(DBR_DOUBLE,cid,&wp->v.v.doubleValue,epicsEndCallback,pv);
    break;
  case HIPTEXT:
    status = ca_put_callback(DBR_STRING,cid,wp->v.v.text,epicsEndCallback, pv);
    break;
  case HIPINTVARAR:
  case HIPINTAR:
    status = ca_array_put_callback(DBR_LONG,wp->v.arrayLength, 
				   cid, wp->v.v.intArray,epicsEndCallback,pv);
    break;
  case HIPFLOATVARAR:
  case HIPFLOATAR:
    status = ca_array_put_callback(DBR_DOUBLE,wp->v.arrayLength, 
				   cid, wp->v.v.floatArray,epicsEndCallback,pv);
    break;		
  }	
  if(status != ECA_NORMAL){
    snprintf(error,sizeof(error),"ERROR: failed to write to EPICS channel for %s with %d", wp->pvName, status);
    writeEpicsMessage(wp->pCon,error);
    goto cleanup;
  }
  writeEpicsMessage(wp->pCon,"OK");
  snprintf(error,sizeof(error),"Writing data for PV %s", wp->pvName);
  writeEpicsMessage(NULL,error);

  ca_pend_io(0);

  goto cleanup;
 cleanup:
422 423 424
  if(wp->pCon != NULL){
    SCDeleteConnection(wp->pCon);
  }
425 426 427 428 429
  ReleaseHdbValue(&wp->v);
  free(wp);
  free(pv);
  ca_clear_channel(cid);
  /* ca_context_destroy(); */
430 431 432
}
/*----------------------------------------------------------------------------------------------*/
static hdbCallbackReturn EPICSWriteCallback(pHdb currentNode, 
433 434
					    void *userData,
					    pHdbMessage message)
435
{
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
  hdbDataMessage *mm = NULL;
  pWritePar par = NULL;

  mm = GetHdbSetMessage(message);
  if(mm != NULL){
    par = calloc(1,sizeof(WritePar));
    if(par == NULL){
      SCWrite(mm->callData,"ERROR: out of memory in EPICSWriteCallback", eError);
      return hdbAbort;
    }
    if(mm->callData != NULL){
      par->pCon = SCCopyConnection(mm->callData);
    }
    cloneHdbValue(mm->v,&par->v);
    strncpy(par->pvName,(char *)userData,sizeof(par->pvName));
    epicsThreadCreate("Write", 
		      epicsThreadPriorityHigh,
		      epicsThreadStackMedium,
		      EpicsWriteFunc,
		      par);
  }

  return hdbContinue;
459 460
}
/*------------------------------------------------------------------------------------*/
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
static int EpicsConnectWrite(pSICSOBJ ccmd, SConnection * con,
			     Hdb * cmdNode, Hdb * par[], int nPar)
{
  pHdb node = NULL;
  pEpicsPriv priv = NULL;

  if(nPar < 2){
    SCWrite(con,"ERROR: need node and PV-name arguments to connectread", eError);
    return 0;
  }

  node = FindHdbNode(NULL,par[0]->value.v.text,con);
  if(node == NULL){
    SCPrintf(con,eError,"ERROR: failed to locate node %s", par[0]->value.v.text);
    return 0;
  }

  SetHdbProperty(node,"writepv", par[1]->value.v.text);
  RemoveSetUpdateCallback(node);
  AppendHipadabaCallback(node,MakeHipadabaCallback(EPICSWriteCallback, 
						   strdup(par[1]->value.v.text),free));

  SCSendOK(con);

  return 1;
}
koennecke's avatar
koennecke committed
487 488

/*==============================================================================================
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
  SICS Hydraulics
  ================================================================================================*/
static int EpicsConvertAlarm(pSICSOBJ ccmd, SConnection * con,
			     Hdb * cmdNode, Hdb * par[], int nPar)
{
  pHdb node = NULL;
  char value[256];

  if(nPar < 1){
    SCWrite(con,"ERROR: need alarm code to convert", eError);
    return 0;
  }

  snprintf(value,sizeof(value),"%s", epicsAlarmConditionStrings[par[0]->value.v.intValue]);
  SCWrite(con,value,eValue);
  return 1;
}
koennecke's avatar
koennecke committed
506

507 508

/*----------------------------------------------------------------------------------------------*/
koennecke's avatar
koennecke committed
509
int MakeEpicsAdapter(SConnection * con, SicsInterp * sics,
510
		     void *object, int argc, char *argv[])
koennecke's avatar
koennecke committed
511
{
512 513
  pSICSOBJ self = NULL;
  pHdb child, par;
koennecke's avatar
koennecke committed
514

515 516 517
  self = MakeSICSOBJv("epicsadapter", "EpicsAdapter", HIPNONE, usMugger);
  createEPICSReadPipe();
  writeQueue = epicsMessageQueueCreate(64,sizeof(pWriteMessage));
koennecke's avatar
koennecke committed
518

519 520 521 522
  child = AddSICSHdbPar(self->objectNode,
			"connectread", usMugger, MakeSICSFunc(EpicsConnectRead));
  AddSICSHdbPar(child, "node", usMugger, MakeHdbText(""));
  AddSICSHdbPar(child, "pvname", usMugger, MakeHdbText(""));
koennecke's avatar
koennecke committed
523

524 525 526 527
  child = AddSICSHdbPar(self->objectNode,
			"connectwrite", usMugger, MakeSICSFunc(EpicsConnectWrite));
  AddSICSHdbPar(child, "node", usMugger, MakeHdbText(""));
  AddSICSHdbPar(child, "pvname", usMugger, MakeHdbText(""));
528

529 530 531
  child = AddSICSHdbPar(self->objectNode,
			"convertalarm", usSpy, MakeSICSFunc(EpicsConvertAlarm));
  AddSICSHdbPar(child, "stat", usSpy, MakeHdbInt(1.));
532

533 534
  AddCommand(pServ->pSics, "epicsadapter", InterInvokeSICSOBJ, KillSICSOBJ, self);
  return 1;
koennecke's avatar
koennecke committed
535
}