Files
cycafe/PyCafe.pyx
2017-11-14 09:26:02 +01:00

6182 lines
206 KiB
Cython

#distutils: language = c++
# file: PyCafe.pyx
cimport PyCafe as ccafe
import numpy as np
cimport numpy as cnp
from cpython cimport array
import array
from cython.view cimport array as cvarray
from libc.stdlib cimport malloc, free
from cython.operator cimport dereference as deref, preincrement as inc
from cython cimport view
import ctypes
import time
import timeit
import os
import cython
import inspect
import sys
#from libcpp.string cimport string
import Cython.Compiler.Options
Cython.Compiler.Options.annotate=True
include "PyCafeDefs.pxi"
cdef dict monDictGlobal={}
##################################################################################
cdef class CyCafe:
cdef:
ccafe.CAFE *_c_cafe
double valFloat #cython float64
string valStr
int valInt
#double * valFloatArray #cython float64
#int * valIntArray
#dbr_string_t * valStringArray
vector[string] vStr
vector[double] vFloat #cython float64
vector[dbr_long_t] vInt
HandleHelper hh
PolicyHelper ph
CAFEException_pv expv
CAFEException_open exopen
CAFEStatus cs
CAFEStatusSeverity css
####PyGILState_STATE gstate
tuple pythonVersion
bint haveExceptions
ChannelRegalia channelInfo
#list moncbList
#list monidList
#dict monDict
str exString
def __cinit__(self):
self._c_cafe = new ccafe.CAFE()
if self._c_cafe is NULL:
raise MemoryError()
self.cs =self._c_cafe.getCafeStatus()
##self.css=self._c_cafe_getCafeStatusSeverity()
self.pythonVersion=sys.version_info[0:4]
self.haveExceptions=True
self.exString="EXCEPTION RAISED IN PyCafe.pyx:"
#self.moncbList =[]
#self.monidList=[]
#self.monDict={}
#Required with gil for callbacks
#However seems to work without this call
####Py_Initialize()
####PyEval_InitThreads()
def __dealloc__(self):
del self._c_cafe
##################################################################################
def init(self):
return self._c_cafe.init()
##################################################################################
def withExceptions(self, bint exceptions=True):
self.haveExceptions=exceptions
return self.haveExceptions
#def getMonidList(self):
# return self.monidList
#def getMoncbList(self):
# return self.moncbList
#def getMonDict(self):
# return self.monDict
##################################################################################
def open(self, pv):
cdef str _METHOD_="open(pv)"
cdef vector[string] pvV
cdef vector[unsigned int] handleV
cdef bytes py_string
if isinstance(pv, (list)):
for i in range(0, len(pv)):
if isinstance(pv[i], unicode):
py_string = (<bytes>pv[i]).encode('UTF-8')
pvV.push_back( py_string )
elif isinstance(pv[i], bytes):
pvV.push_back( (<bytes>pv[i]).encode('utf8') )
else:
print ("Unknown type in {}".format(_METHOD_))
try:
status=self._c_cafe.openV(pvV, handleV)
except RuntimeError as e:
if isinstance (e.args, tuple):
if 'CAFEException' in (e.args[0]):
_cyCafeException = CyCafeException(_type='cafe', _source=_METHOD_, \
_ec=ECA_ALLOCMEM, _et=self.cs.code(ECA_ALLOCMEM), _ei=self.cs.info(ECA_ALLOCMEM))
raise Exception(_cyCafeException)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, e.what()))
return handleV
elif not isinstance(pv, (bytes,str)):
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"Input argument, pv, should be <type 'str'>"))
cdef unsigned int handle=0
try:
self._c_cafe.open(pv, handle)
except RuntimeError as e:
if isinstance (e.args, tuple):
if 'CAFEException' in (e.args[0]):
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, _handle=handle, _pv=pv, \
_ec=ECA_ALLOCMEM, _et=self.cs.code(ECA_ALLOCMEM), _ei=self.cs.info(ECA_ALLOCMEM))
raise Exception(_cyCafeException)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, e.what()))
#print ("******************** HANDLE *******", handle);
return handle
##################################################################################
def openNoWait(self):
#self._c_cafe.channelOpenPolicy.setFlushSendBufferKind(WITH_PEND_EVENT)
#self._c_cafe.channelOpenPolicy.setWhenToFlushSendBuffer(FLUSH_DESIGNATED_TO_CLIENT)
with nogil:
self._c_cafe.openNoWait()
return
def openPrepare(self):
#self._c_cafe.channelOpenPolicy.setFlushSendBufferKind(WITH_PEND_EVENT)
#self._c_cafe.channelOpenPolicy.setWhenToFlushSendBuffer(FLUSH_DESIGNATED_TO_CLIENT)
with nogil:
self._c_cafe.openPrepare()
return
def openGroupPrepare(self):
#self._c_cafe.channelOpenGroupPolicy.setFlushSendBufferKind(WITH_PEND_EVENT)
#self._c_cafe.channelOpenGroupPolicy.setWhenToFlushSendBuffer(FLUSH_DESIGNATED_TO_CLIENT)
with nogil:
self._c_cafe.openGroupPrepare()
return
def setOpenDefaultPendTime(self, double timeout):
return self._c_cafe.channelOpenPolicy.setDefaultTimeout(timeout)
def getOpenDefaultPendTime(self):
return self._c_cafe.channelOpenPolicy.getDefaultTimeout()
##################################################################################
def openNow(self):
#self._c_cafe.channelOpenPolicy.flushSendBufferNow()
#self._c_cafe.channelOpenPolicy.setWhenToFlushSendBuffer(FLUSH_NOW)
#self._c_cafe.channelOpenPolicy.setFlushSendBufferKind(WITH_PEND_EVENT)
with nogil:
self._c_cafe.openNow()
return
##################################################################################
def openNowAndWait(self, double timeout):
#self._c_cafe.channelOpenPolicy.setTimeout(timeout)
#self._c_cafe.channelOpenPolicy.flushSendBufferNow()
#reset
#self._c_cafe.channelOpenPolicy.setWhenToFlushSendBuffer(FLUSH_NOW)
#self._c_cafe.channelOpenPolicy.setFlushSendBufferKind(WITH_PEND_EVENT)
#self._c_cafe.channelOpenPolicy.setTimeoutToDefault()
with nogil:
self._c_cafe.openNowAndWait(timeout)
return
##################################################################################
##################################################################################
def openGroupNowAndWait(self, double timeout):
#self._c_cafe.channelOpenGroupPolicy.setTimeout(timeout)
#self._c_cafe.channelOpenGroupPolicy.flushSendBufferNow()
#reset
#self._c_cafe.channelOpenGroupPolicy.setWhenToFlushSendBuffer(FLUSH_NOW)
#self._c_cafe.channelOpenGroupPolicy.setFlushSendBufferKind(WITH_PEND_EVENT)
#self._c_cafe.channelOpenGroupPolicy.setTimeoutToDefault()
with nogil:
self._c_cafe.openGroupNowAndWait(timeout)
return
##################################################################################
##################################################################################
def openGroupNowAndWaitForInputGroups(self, double timeout, groupHandles):
cdef str _METHOD_="openGroupNowAndWaitForInputGroups"
cdef vector[unsigned int] hList
if isinstance(groupHandles, (list)) == 1:
for i in range (0, len(groupHandles)):
if isinstance(groupHandles[i], (int,long)) == 1:
hList.push_back(groupHandles[i])
elif isinstance(groupHandles[i], (str)) == 1:
hList.push_back(self.hh.getGroupHandleFromGroupName(groupHandles[i]))
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"List input arguments, should be <type 'int'> if group handle, else <type 'str'> if group name"))
elif isinstance(groupHandles, (int,long)) == 1:
hList.push_back(groupHandles)
elif isinstance(groupHandles, (str)) == 1:
hList.push_back(self.hh.getGroupHandleFromGroupName(groupHandles))
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"Second input argument (if not a list), should be <type 'int'> if group handle, else <type 'str'> if group name"))
#list to vector
with nogil:
self._c_cafe.groupOpenNowAndWait(timeout, hList)
return
##################################################################################
def openMonitorPrepare(self):
#self._c_cafe.channelMonitorPolicy.setFlushSendBufferKind(WITH_FLUSH_IO)
#self._c_cafe.channelMonitorPolicy.setWhenToFlushSendBuffer(FLUSH_DESIGNATED_TO_CLIENT)
with nogil:
self._c_cafe.openMonitorPrepare()
return
##################################################################################
def openMonitorNow(self):
#self._c_cafe.channelMonitorPolicy.flushSendBufferNow()
#reset
#self._c_cafe.channelMonitorPolicy.setWhenToFlushSendBuffer(FLUSH_NOW)
#self._c_cafe.channelMonitorPolicy.setFlushSendBufferKind(WITH_FLUSH_IO)
with nogil:
self._c_cafe.openMonitorNow()
time.sleep(0.1)
return
##################################################################################
##################################################################################
def getMonitorWhenToFlushSendBuffer(self):
return self._c_cafe.channelMonitorPolicy.getWhenToFlushSendBuffer()
##################################################################################
##################################################################################
def openMonitorNowAndWait(self, double timeout):
#self._c_cafe.channelMonitorPolicy.setTimeout(timeout)
#self._c_cafe.channelMonitorPolicy.flushSendBufferNow()
#time.sleep(timeout)
#reset
#self._c_cafe.channelMonitorPolicy.setWhenToFlushSendBuffer(FLUSH_NOW)
#self._c_cafe.channelMonitorPolicy.setFlushSendBufferKind(WITH_FLUSH_IO)
with nogil:
self._c_cafe.openMonitorNowAndWait(timeout)
return
##################################################################################
def ca_pend_event(self, double timeout):
self._c_cafe._ca_pend_event(timeout)
return
def ca_pend_io(self, double timeout):
self._c_cafe._ca_pend_io(timeout)
return
def ca_poll(self):
with nogil:
self._c_cafe._ca_poll()
return
def ca_flush_io(self):
with nogil:
self._c_cafe._ca_flush_io()
return
##################################################################################
def setChannelRequestPolicyGet(self, handlePV, ChannelWhenToFlushSendBufferPolicyKind when, \
ChannelWaitForResponsePolicyKind wait, ChannelRequestPolicyKind method, \
object cb=None):
cdef str _METHOD_="setChannelRequestPolicyGet"
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First Input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
global py_cb_handle_get
cdef ChannelRequestPolicy cp
self.ph.getChannelRequestPolicyGet(handlePV, cp)
if when:
cp.setWhenToFlushSendBuffer(when)
if wait:
cp.setWaitKind(wait)
if method:
cp.setMethodKind(method)
if cb:
py_cb_handle_get=cb
cp.setPyHandlerGet() #forces when=WITH_CALLBACK_USER_SUPPLIED
self.ph.setChannelRequestPolicyGet(handlePV, cp)
return
##################################################################################
##################################################################################
def setCallbackGet(self, handlePV, object cb=None):
cdef str _METHOD_="setCallbackGet"
cdef ChannelRequestPolicy cp
self.ph.getChannelRequestPolicyGet(handlePV, cp)
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
global py_cb_handle_get
if cb:
py_cb_handle_get=cb
cp.setPyHandlerGet() #forces when=WITH_CALLBACK_USER_SUPPLIED
else:
cp.setMethodKind(WITH_CALLBACK_DEFAULT)
self.ph.setChannelRequestPolicyGet(handlePV, cp)
return
##################################################################################
##################################################################################
def setCallbackPut(self, handlePV, object cb=None):
cdef str _METHOD_="setCallbackPut"
cdef ChannelRequestPolicy cp
self.ph.getChannelRequestPolicyPut(handlePV, cp)
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
global py_cb_handle_put
if cb:
py_cb_handle_put=cb
cp.setPyHandlerPut() #forces when=WITH_CALLBACK_USER_SUPPLIED
else:
cp.setMethodKind(WITH_CALLBACK_DEFAULT)
self.ph.setChannelRequestPolicyPut(handlePV, cp)
return
##################################################################################
##################################################################################
def setTimeout(self, timeout):
return self.ph.setTimeout(timeout)
##################################################################################
##################################################################################
def getTimeoutGet(self):
cdef double minValue,p,g
minValue=0
p=0
g=0
self.ph.getTimeoutMin(p,g)
minValue=g
self.ph.getTimeoutMax(p,g)
if (g < minValue):
minValue=g
return minValue
##################################################################################
##################################################################################
def getTimeoutPut(self):
cdef double minValue,p,g
minValue=0
p=0
g=0
self.ph.getTimeoutMin(p,g)
minValue=p
self.ph.getTimeoutMax(p,g)
if (p < minValue):
minValue=g
return minValue
##################################################################################
##################################################################################
def setSelfGoverningTimeout(self, bint b):
return self.ph.setSelfGoverningTimeout(b)
##################################################################################
##################################################################################
# Synchronous Groups
##################################################################################
def setSGTimeout(self, double timeout):
return self.ph.setSGTimeout(timeout)
##################################################################################
##################################################################################
def getSGTimeoutGet(self):
cdef double minValue,p,g
minValue=0
p=0
g=0
self.ph.getSGTimeoutMin(p,g)
minValue=g
self.ph.getSGTimeoutMax(p,g)
if (g < minValue):
minValue=g
return minValue
##################################################################################
##################################################################################
def getSGTimeoutPut(self):
cdef double minValue,p,g
minValue=0
p=0
g=0
self.ph.getSGTimeoutMin(p,g)
minValue=p
self.ph.getSGTimeoutMax(p,g)
if (p < minValue):
minValue=p
return minValue
##################################################################################
##################################################################################
def setSGSelfGoverningTimeout(self, bint b):
cdef PolicyHelper ph
return ph.setSGSelfGoverningTimeout(b)
##################################################################################
##################################################################################
def attachContext(self, handlePV):
cdef str _METHOD_="attachContext"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
return self._c_cafe.attachContextByHandle(handlePV)
elif isinstance(handlePV, (str)) == 1:
return self._c_cafe.attachContextByPVName(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
##################################################################################
##################################################################################
def loadCollectionsFromXML(self, const char * fileName):
with nogil:
self._c_cafe.loadCollectionsFromXML(fileName)
return
##################################################################################
##################################################################################
def loadGroupsFromXML(self, const char * fileName):
with nogil:
self._c_cafe.loadGroupsFromXML(fileName)
return
##################################################################################
def devicePositionMap(self, const char * collectionName):
p=[]
d=[]
cdef map[float, string] mmfs
cdef map[float, string].iterator it
self._c_cafe.devicePositionMap(collectionName, mmfs)
it= mmfs.begin()
tup=() #tuple
while it != mmfs.end():
tup=deref(it)
p.append(tup[0])
d.append(tup[1])
inc(it)
return d,p
def devicePositionV(self, const char * collectionName):
cdef str _METHOD_="devicePositionV(self, const char * collectionName)"
#p=[]
#d=[]
cdef vector[string] dev
cdef vector[float] pos
status=self._c_cafe.devicePositionV(collectionName, dev, pos)
if status != ICAFE_NORMAL:
raise Exception("{} {} {} {} {} {}".format(self.exString, _METHOD_, \
"status=", status, self.cs.code(status), self.cs.code(status) ))
#for i in range (0, dev.size()):
#d.append(dev[i])
#p.append(pos[i])
return dev, pos
##################################################################################
def groupList(self):
cdef vector[string] gList
#conservative guess
gList.reserve(36)
self._c_cafe.groupList(gList)
#Place in list to avoid this warning:
# warning: comparison between signed and unsigned integer expressions
#gl=[]
#for i in range (0, len(gList)):
# gl.append(gList[i])
return gList
##################################################################################
def getMonitorIDInCallback(self, handle):
return self.hh.getUsrArgsAsUInt(handle)
def getDataTypeInCallback(self, handle):
return <long>self.hh.getDataTypeCB(handle)
def getDbrDataTypeInCallback(self, handle):
return <long>self.hh.getDbrDataTypeCB(handle)
def getDbrBaseInCallback(self, handle):
return <unsigned int>self.hh.getCafeDbrTypeCB(handle)
##################################################################################
def getHandlesFromWithinGroup(self, gHandleName):
cdef str _METHOD_="getHandlesFromWithinGroup(gHandleName)"
cdef unsigned int groupHandle=0
if isinstance(gHandleName, (int,long)) == 1:
groupHandle=gHandleName
elif isinstance(gHandleName, (str)) == 1:
groupHandle=self.hh.getGroupHandleFromGroupName(gHandleName)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if group handle, else <type 'str'> if group name"))
cdef vector[unsigned int] hList
hList=self.hh.getHandlesFromWithinGroupV(groupHandle)
return hList
##################################################################################
##################################################################################
def close(self, handlePV):
cdef str _METHOD_="close"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef int stat
with nogil:
stat=self._c_cafe.close(handle)
return stat
##################################################################################
def closeChannels(self):
cdef int stat
with nogil:
stat=self._c_cafe.closeChannels()
return stat
##################################################################################
def closeHandles(self, list handleList):
cdef str _METHOD_="closeHandlesV"
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList, force=False)
elif not isinstance(handleList[0], (int, long)):
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be a 'list' of <type 'int'> if handles or <type 'str'> if PVs"))
#Do this only to avoid compiler warnings
cdef vector[unsigned int] v
for i in range(0, len(handleList)):
v.push_back(handleList[i])
cdef int stat
with nogil:
stat=self._c_cafe.closeHandlesV(v)
return stat
##################################################################################
def closeDisconnectedChannelsWithinGroup(self, ghandleName):
cdef str _METHOD_="closeDisconnectedChannelsWithinGroup"
cdef vector[unsigned int] hList
cdef vector[unsigned int] disHandles
if isinstance(ghandleName, (list)) == 1:
for i in range (0, len(ghandleName)):
if isinstance(ghandleName[i], (int,long)) == 1:
hList.push_back(ghandleName[i])
elif isinstance(ghandleName[i], (str)) == 1:
hList.push_back(self.checkForGroupHandle(ghandleName[i]))
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"List input arguments, should be <type 'int'> if group handle, else <type 'str'> if group name"))
elif isinstance(ghandleName, (int,long)) == 1:
hList.push_back(ghandleName)
elif isinstance(ghandleName, (str)) == 1:
hList.push_back(self.checkForGroupHandle(ghandleName))
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument (if not list), should be <type 'int'> if group handle, else <type 'str'> if group name"))
for i in range (0, len(hList)):
with nogil:
self._c_cafe.closeDisconnectedChannelsFromWithinGroupV(hList[i])
return
##################################################################################
def closeChannelKeepHandle(self, handlePV):
cdef str _METHOD_="closeChannelKeepHandle"
cdef vector[unsigned int] hList
cdef int statusClose
if isinstance(handlePV, (list)) == 1:
for i in range (0, len(handlePV)):
if isinstance(handlePV[i], (int,long)) == 1:
hList.push_back(handlePV[i])
elif isinstance(handlePV[i], (str)) == 1:
hList.push_back(self.checkForHandle(handlePV[i]))
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"List input arguments, should be <type 'int'> if group handle, else <type 'str'> if group name"))
elif isinstance(handlePV, (int,long)) == 1:
hList.push_back(handlePV)
elif isinstance(handlePV, (str)) == 1:
hList.push_back(self.checkForHandle(handlePV))
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument (if not list), should be <type 'int'> if handle, else <type 'str'> if PV"))
with nogil:
statusClose= self._c_cafe.closeChannelsKeepHandles(hList)
return statusClose
##################################################################################
def allConnected(self):
return <bint>self._c_cafe.allChannelsConnected()
##################################################################################
def isConnected(self, handlePV):
cdef str _METHOD_="isConnected"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
return <bint>self._c_cafe.isChannelConnected(handle)
##################################################################################
def printDisconnected(self):
return self._c_cafe.printDisconnectedHandles()
def printDisconnectedHandles(self):
return self._c_cafe.printDisconnectedHandles()
##################################################################################
def printHandles(self):
return self._c_cafe.printHandles()
##################################################################################
def printHandle(self, handlePV):
cdef str _METHOD_="printHandle"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
return self._c_cafe.printHandle(handle)
##################################################################################
##################################################################################
def printHandlesV(self, list handleList):
cdef str _METHOD_="printHandlesV"
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList)
elif not isinstance(handleList[0], (int, long)):
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be a 'list' of <type 'int'> if handles or <type 'str'> if PVs"))
#Do this only to avoid compiler warnings
cdef vector[unsigned int] v
for i in range(0, len(handleList)):
v.push_back(handleList[i])
return self.hh.printHandlesV(v)
##################################################################################
##################################################################################
def getDisconnectedHandles(self):
cdef vector[unsigned int] dhV
cdef vector[string] pvV
self.hh.getDisconnectedHandles(dhV,pvV)
return dhV,pvV
##################################################################################
##################################################################################
def getHandles(self):
cdef vector[unsigned int] dhV
cdef vector[string] pvV
self.hh.getHandles(dhV,pvV)
return dhV,pvV
##################################################################################
##################################################################################
def getHandleStates(self):
cdef vector[unsigned int] dhV
cdef vector[string] pvV
cdef vector[unsigned short] stateV
self.hh.getHandleStates(dhV,pvV, stateV)
return dhV,pvV,stateV
##################################################################################
##################################################################################
def getStatusSeverity(self, int statusCode):
return self._c_cafe.getCafeStatusSeverity().message(statusCode)
##################################################################################
def getStatusCodeAsText(self, int statusCode):
return self.cs.code(statusCode)
##################################################################################
def getStatusCodeAsString(self, int statusCode):
return self.cs.code(statusCode)
##################################################################################
def getStatusInfo(self, int statusCode):
return self.cs.info(statusCode)
##################################################################################
def getStatusMsg(self, int statusCode):
return self.cs.message(statusCode)
##################################################################################
def getStatus(self, handlePV):
cdef str _METHOD_="getStatus"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
return self.hh.getStatus(handle)
##################################################################################
def getAlarmStatusSeverity(self,handlePV):
cdef str _METHOD_="getAlarmStatusSeverity"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef short aStatSev[2]
status=self.hh.getAlarmStatusSeverity(handle,aStatSev)
return aStatSev[0], aStatSev[1]
##################################################################################
def getTimeStamp(self,handlePV):
cdef str _METHOD_="getTimeStamp"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef HandleHelper hh
hh._etsNorm=self.hh.getEpicsTimeStampAsUInt32(handle)
cpdef ll=[]
ll.append(hh._etsNorm.secPastEpoch)
ll.append(hh._etsNorm.nsec)
#print ("TimeStamp ", ll)
return ll
##################################################################################
def getTimeStampAsDate(self,handlePV):
cdef str _METHOD_="getimeStampAsDate"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef HandleHelper hh
cpdef ld=[]
hh._etsDate =self.hh.getEpicsTimeStampAsDate(handle)
ld.append(hh._etsDate.year )
ld.append(hh._etsDate.mon )
ld.append(hh._etsDate.day )
ld.append(hh._etsDate.hour )
ld.append(hh._etsDate.min )
ld.append(hh._etsDate.sec )
ld.append(hh._etsDate.nsec )
#print ("TimeStampAsDate ", ld)
return ld
##################################################################################
### Allow user to choose whether or not to open #####
cpdef checkForHandle(self, str pv, bint force=True):
cdef unsigned int _handle=0;
_handle=self.hh.getHandleFromPV(pv)
if _handle == 0:
if (force):
return self.open(pv)
else:
return 0
else:
return _handle
##################################################################################
##################################################################################
cpdef checkForHandleList(self, list pvList, bint force=True):
cdef unsigned int nToOpen=0
handleList=[]
cdef unsigned int _handle=0
for i in range(0, len(pvList)):
_handle=self.hh.getHandleFromPV(pvList[i])
if _handle == 0:
if (force):
nToOpen=nToOpen+1;
self.openNoWait()
_handle=self.open(pvList[i])
handleList.append(_handle)
else:
handleList.append(_handle)
if nToOpen > 0:
self.openNowAndWait(2.0+nToOpen*0.001)
return handleList
##################################################################################
##################################################################################
cpdef checkForGroupHandle(self, str gName, bint force=True):
cdef unsigned int _ghandle=0;
_ghandle=self.hh.getGroupHandleFromGroupName(gName)
if _ghandle == 0:
if (force):
return self.groupOpen(gName)
else:
return 0
else:
return _ghandle
##################################################################################
##################################################################################
def getPVNameFromHandle(self, int h):
return self._c_cafe.getPVFromHandle(h)
##################################################################################
##################################################################################
def getHandleFromPVName(self, str name):
#if type(name) is unicode:
# py_string = (<bytes>name).encode('UTF-8')
# return self._c_cafe.getHandleFromPV(py_string)
return self._c_cafe.getHandleFromPV(name)
##################################################################################
##################################################################################
def getChannelInfo(self, handlePV):
cdef str _METHOD_="getChannelInfo"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)):
handle=handlePV
elif isinstance(handlePV, (str)):
handle=self.checkForHandle(handlePV, force=True)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
if handle == 0:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(ECAFE_INVALID_HANDLE)
raise Exception("EXCEPTION RAISED in PyCafe def getChannelInfo")
cdef ChannelRegalia cr
status=self._c_cafe.getChannelInfo(handle,cr)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
raise Exception("EXCEPTION RAISED in PyCafe def getChannelInfo. Status = %d" %status)
#cdef channelInfo ci=channelRegaliaToStruct(cr)
#ci.channelID=self._c_cafe.getChannelIDAsString(cr.getChannelID())
#do hex(cr.getChannelID()) to get channelId in hex form
return channelRegaliaToStruct(cr)
##################################################################################
def getChannelList(self, list listStrings):
return self._c_cafe.getFromGlobalChannelList(listStrings)
##################################################################################
##################################################################################
def getWFAsString(self, handlePV, bint cache=False):
cdef str _METHOD_="getWFAsString"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef string strWF
if (cache == True):
status=self._c_cafe.getWFAsStringCache(handle, strWF)
else:
with nogil:
status=self._c_cafe.getWFAsString(handle, strWF)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
raise Exception("EXCEPTION RAISED in PyCafe def %s. Status = %d" %_METHOD_,status)
return strWF
##################################################################################
##################################################################################
def getWFAsStringCache(self, handlePV):
return self.getWFAsString(handlePV, cache=True)
##################################################################################
##################################################################################
def getEnumFromString(self, handlePV, str enumString):
cdef str _METHOD_="getEnumFromString"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
enumValue=self.hh.getEnumFromString(handle, enumString)
if enumValue == -1:
raise Exception("{} {} {} {} {}".format(self.exString, _METHOD_, \
": ENUM string value:", enumString, "not recognized! "))
return enumValue
##################################################################################
def getStringFromEnum(self, handlePV, int enumValue):
cdef str _METHOD_="getStringFromEnum"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
return self.hh.getStringFromEnum(handle, enumValue)
##################################################################################
def loadSFGroups(self):
cdef bytes py_string
py_string = (<bytes>'VA').encode('UTF-8')
#cdef vector[string] gnV
#gnV.push_back(py_string)
#return self._c_cafe.loadSFGroups(gnV[0])
return self._c_cafe.loadSFGroups(py_string)
def loadSFGroupsWithBase(self, str VA):
cdef bytes py_string
py_string = (<bytes>VA).encode('UTF-8')
return self._c_cafe.loadSFGroups(py_string)
#return self._c_cafe.loadSFGroups(VA)
##################################################################################
def setDbrBase(self, handlePV, DBR_TYPE dbrBase):
cdef str _METHOD_="setDbrBase"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
#Print Warning Message
if dbrBase > DBR_TIME:
print ("WARNING: PyCafe def setDbrBase(handle/PV, DBR_TYPE)")
print ("Allowed DBR_TYPEs are DBR_PLAIN (0), DBR_STS(1), DBR_TIME(2)")
print ("The value entered was", dbrBase, "hence assuming DBR_TIME" )
dbrBase=DBR_TIME
return self.hh.setCafeDbrType(handle, dbrBase)
##################################################################################
##################################################################################
def getDbrBase(self, handlePV):
cdef str _METHOD_="getDbrBase"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef DBR_TYPE _cafeDbrType=DBR_PLAIN
cdef int status=self.hh.getCafeDbrType(handle,_cafeDbrType)
return _cafeDbrType
##################################################################################
##################################################################################
def setGetCacheWaitPolicy(self, handlePV, ChannelGetCacheWaitPolicyKind wpk):
cdef str _METHOD_="setGetCacheWaitPolicy"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
#Print Warning Message
if wpk > GET_CACHE_WAIT:
print ("WARNING: PyCafe def setGetCacheWaitPolicy(handle/PV, ChannelGetCacheWaitPolicyKind)")
print ("Allowed ChannelGetCacheWaitPolicyKind are GET_CACHE_NO_CHECK (0), GET_CACHE_NO_WAIT (1), GET_CACHE_WAIT (2)")
print ("The value entered was", wpk, "hence assuming default value GET_CACHE_WAIT" )
wpk=GET_CACHE_WAIT
cdef ChannelGetCacheWaitPolicy channelGetCacheWaitPolicy
channelGetCacheWaitPolicy.setWaitKind(wpk)
return self.ph.setChannelGetCacheWaitPolicy(handle,channelGetCacheWaitPolicy)
##################################################################################
##################################################################################
def setGetCacheWaitPolicyAllHandles(self, ChannelGetCacheWaitPolicyKind wpk):
#Print Warning Message
if wpk > GET_CACHE_WAIT:
print ("WARNING: PyCafe def setGetCacheWaitPolicyAllHandles(ChannelGetCacheWaitPolicyKind)")
print ("Allowed ChannelGetCacheWaitPolicyKind are GET_CACHE_NO_CHECK (0), GET_CACHE_NO_WAIT (1), GET_CACHE_WAIT (2)")
print ("The value entered was", wpk, "hence assuming default value GET_CACHE_WAIT" )
wpk=GET_CACHE_WAIT
cdef ChannelGetCacheWaitPolicy channelGetCacheWaitPolicy
channelGetCacheWaitPolicy.setWaitKind(wpk)
return self.ph.setChannelGetCacheWaitPolicyAllHandles(channelGetCacheWaitPolicy)
##################################################################################
##################################################################################
def setGetActionWhenMonitorPolicy(self, handlePV, ChannelGetActionWhenMonitorPolicyKind wmpk):
cdef str _METHOD_="setGetActionWhenMonitorPolicy"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
#Print Warning Message
if wmpk > GET_FROM_IOC:
print ("WARNING: PyCafe def setGetActionWhenMonitorPolicy(handle/PV, ChannelGetActionWhenMonitorPolicyKind)")
print ("Allowed ChannelGetActionWhenMonitorPolicyKind are GET_FROM_CACHE (0), GET_FROM_IOC (1)")
print ("The value entered was", wmpk, "hence assuming default value GET_FROM_IOC" )
wmpk=GET_FROM_IOC
cdef ChannelGetActionWhenMonitorPolicy channelGetActionWhenMonitorPolicy
channelGetActionWhenMonitorPolicy.setActionKind(wmpk)
return self.ph.setChannelGetActionWhenMonitorPolicy(handle,channelGetActionWhenMonitorPolicy)
##################################################################################
##################################################################################
def setGetActionWhenMonitorPolicyAllHandles(self, ChannelGetActionWhenMonitorPolicyKind wmpk):
#Print Warning Message
if wmpk > GET_FROM_IOC:
print ("WARNING: PyCafe def setGetActionWhenMonitorPolicyAllHandles(ChannelGetActionWhenMonitorPolicyKind)")
print ("Allowed ChannelGetActionWhenMonitorPolicyKind are GET_FROM_CACHE (0), GET_FROM_IOC (1)")
print ("The value entered was", wmpk, "hence assuming default value GET_FROM_IOC" )
wmpk=GET_FROM_IOC
cdef ChannelGetActionWhenMonitorPolicy channelGetActionWhenMonitorPolicy
channelGetActionWhenMonitorPolicy.setActionKind(wmpk)
return self.ph.setChannelGetActionWhenMonitorPolicyAllHandles(channelGetActionWhenMonitorPolicy)
##################################################################################
##################################################################################
def getNonBlocking(self, handlePV):
##################################################################################
cdef str _METHOD_="getNonBlocking"
cdef unsigned int handle=0
cdef int status
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
with nogil:
status=self._c_cafe.getNonBlocking(handle)
if status != ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
raise Exception("EXCEPTION RAISED in PyCafe def getNonBlocking. Status = %d" %status)
return status
##################################################################################
##################################################################################
def getStr(self, handlePV, object cb=None):
return self.get(handlePV,dt='str')
##################################################################################
##################################################################################
def getInt(self, handlePV, object cb=None):
return self.get(handlePV, dt='int')
##################################################################################
##################################################################################
def getFloat(self, handlePV, object cb=None):
return self.get(handlePV, dt='float')
##################################################################################
##################################################################################
def get(self, handlePV, str dt='native'):
##################################################################################
cdef str _METHOD_ = "get"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef int status
cdef long dtr=0
status=self.hh.getDataTypeNative(handle, dtr)
if status != ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe', _source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return None
elif dtr in [CAFE_NO_ACCESS, CAFE_TYPENOTCONN]:
if self._c_cafe.isChannelConnected(handle) is False:
self._c_cafe.getChannelInfo(handle,self.channelInfo)
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatus(handle,self.channelInfo.getCafeConnectionState() )
if self.haveExceptions:
#raise Exception("EXCEPTION RAISED in PyCafe def get. \
#Channel Not Connected, status = %d" %self.channelInfo.getCafeConnectionState())
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=self.channelInfo.getCafeConnectionState(), \
_et=self.cs.code(self.channelInfo.getCafeConnectionState()), \
_ei=self.cs.info(self.channelInfo.getCafeConnectionState()))
raise Exception(_cyCafeException)
return None
#Likely to be superfluous
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatus(handle,ICAFE_TYPENOTCONN)
if self.haveExceptions:
_cyCafeException = CyCafeException(type='cafe', _source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=ICAFE_TYPENOTCONN, _et=self.cs.code(ICAFE_TYPENOTCONN), _ei=self.cs.info(ICAFE_TYPENOTCONN))
raise Exception(_cyCafeException)
return None
#global py_cb_handle_get
#if cb:
#py_cb_handle_get=cb
#self.setChannelRequestPolicyGet(handle, wait=WAIT, when=FLUSH_NOW, method=WITH_CALLBACK_USER_SUPPLIED, pcb=True)
cdef unsigned int dtcheck = dtr
dtcheck=getMatchedDataType(dt, dtr)
if dtcheck in [CAFE_STRING]:
with nogil:
status=self._c_cafe.getString(handle, self.valStr)
if status==ICAFE_NORMAL:
return self.valStr
elif dtcheck in [CAFE_SHORT, CAFE_CHAR, CAFE_LONG]:
with nogil:
status=self._c_cafe.getLong(handle, self.valInt)
if status==ICAFE_NORMAL:
return self.valInt
elif dtcheck in [CAFE_FLOAT, CAFE_DOUBLE]:
with nogil:
status=self._c_cafe.getDouble(handle, self.valFloat)
if status==ICAFE_NORMAL:
return self.valFloat
elif dtcheck==CAFE_ENUM:
#if enum, string taken as native
if self._c_cafe.isEnum(handle):
with nogil:
status=self._c_cafe.getString(handle, self.valStr)
if status==ICAFE_NORMAL:
return self.valStr
else:
with nogil:
status=self._c_cafe.getLong(handle, self.valInt)
if status ==ICAFE_NORMAL:
return self.valInt
else:
print ("This line in PyCafe def get should never appear!")
return None
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return None
##################################################################################
#END: def get(self, handlePV, dt)
##################################################################################
##################################################################################
def getIntList(self, handlePV):
return self.getList(handlePV, 'int')
##################################################################################
def getFloatList(self, handlePV):
return self.getList(handlePV, 'float')
##################################################################################
def getStrList(self, handlePV):
return self.getList(handlePV, 'str')
##################################################################################
def getList(self, handlePV, str dt='native'):
cdef str _METHOD_="getList(handlePV, str dt='native')"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef int status
cdef long dtr=0
status=self.hh.getDataTypeNative(handle, dtr)
if status != ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return [None]
elif dtr in [CAFE_NO_ACCESS, CAFE_TYPENOTCONN]:
if self._c_cafe.isChannelConnected(handle) is False:
self._c_cafe.getChannelInfo(handle,self.channelInfo)
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatus(handle,self.channelInfo.getCafeConnectionState() )
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=self.channelInfo.getCafeConnectionState(), _et=self.cs.code(self.channelInfo.getCafeConnectionState()),\
_ei=self.cs.info(self.channelInfo.getCafeConnectionState()))
raise Exception(_cyCafeException)
return [None]
#This paragraph should be superfluous
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatus(handle,ICAFE_TYPENOTCONN)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=ICAFE_TYPENOTCONN, _et=self.cs.code(ICAFE_TYPENOTCONN), _ei=self.cs.info(ICAFE_TYPENOTCONN))
raise Exception(_cyCafeException)
return [None]
cdef unsigned int dtcheck = dtr
dtcheck=getMatchedDataType(dt, dtr)
#print ("dtcheck", dtcheck)
cdef unsigned int nelemNative =self.hh.getNelemNative (handle)
cdef unsigned int nelemClient =self.hh.getNelemClient (handle)
cdef unsigned int nelemRequest=self.hh.getNelemRequest(handle)
cdef unsigned int nelemMethod = nelemClient
cdef dbr_string_t * valStringArray
cdef int * valIntArray
cdef double * valDoubleArray
if dtcheck in [CAFE_STRING]:
valStringArray = <char[40]*>malloc( nelemMethod * sizeof(dbr_string_t))
with nogil:
status=self._c_cafe.getDbrStringArray(handle, valStringArray)
ll=[]
for i in range(0,nelemMethod):
ll.append(valStringArray[i])
free(valStringArray)
if status == ICAFE_NORMAL:
return ll
elif dtcheck in [CAFE_SHORT, CAFE_CHAR, CAFE_LONG]:
valIntArray = <int *>malloc( nelemMethod * sizeof(int))
with nogil:
status=self._c_cafe.getLongArray(handle, valIntArray)
ll=[]
for i in range(0, nelemMethod):
ll.append(valIntArray[i])
free(valIntArray)
if status == ICAFE_NORMAL:
return ll
elif dtcheck in [CAFE_FLOAT, CAFE_DOUBLE]:
valDoubleArray = <double *>malloc( nelemMethod * sizeof(double))
with nogil:
status=self._c_cafe.getDoubleArray(handle, valDoubleArray)
ll=[]
for i in range(0, nelemMethod):
ll.append(valDoubleArray[i])
free(valDoubleArray)
if status == ICAFE_NORMAL:
return ll
elif dtcheck==CAFE_ENUM:
#if enum, string taken as native
if self._c_cafe.isEnum(handle):
valStringArray = <char[40]*>malloc( nelemMethod * sizeof(dbr_string_t))
with nogil:
status=self._c_cafe.getDbrStringArray(handle, valStringArray)
ll=[]
for i in range(0,nelemMethod):
ll.append(valStringArray[i])
free(valStringArray)
if status ==ICAFE_NORMAL:
return ll
else:
valIntArray = <int *>malloc( nelemMethod * sizeof(int))
with nogil:
status=self._c_cafe.getLongArray(handle, valIntArray)
ll=[]
for i in range(0,nelemMethod):
ll.append(valIntArray[i])
free(valIntArray)
if status ==ICAFE_NORMAL:
return ll
#Will not happen; already covered above
elif dtcheck in [CAFE_NO_ACCESS,CAFE_TYPENOTCONN]:
print ("Channel", self._c_cafe.getPVFromHandle(handle), " not connected")
return None
else:
print ("This line in PyCafe def getAsList should never appear!")
return None
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.withExceptions is False:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return None
##################################################################################
def getStrArray(self, handlePV, str art='memoryview'):
return self.getArray(handlePV, dt='str', art=art)
##################################################################################
##################################################################################
def getIntArray(self, handlePV, str art='memoryview' ):
return self.getArray(handlePV, dt='int', art=art)
##################################################################################
##################################################################################
def getFloatArray(self, handlePV, str art='memoryview'):
return self.getArray(handlePV, dt='float', art=art )
##################################################################################
##################################################################################
def getArray(self, handlePV, str dt='native', str art='memoryview'):
##################################################################################
#Typed Memoryviews from K.W. Smith
#Cython has a C-level type the typed memoryview, that conceptually overlaps
#with the Python memoryiew and expands on it. A typed memory view is used to
#view (share) data from a buffer-producing object.
#A typed memoryview has a memory-view like interface and is easier to use than
#working with C-level buffers directly. And because a typed memoryview is designed
#to work with the buffer protocol it supports any buffer-producing object efficiently
#allowing sharing of data buffers without copying
#If we declare a typed memoryview with a single colon in each dimension's slot,
#the typed mv can acquire a buffer from an object if the same dimensionality and with
#either strided or contiguous packing.
#Declaring a C-contiguous typed memoryview: all dimensions except the last is specified
#with two colons followed by a literal 1. The mnemonic is that the last dimension has
#a unitary stride, i.e., is contiguous in memory, hence C contiguous
cdef str _METHOD_="getArray"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef:
short * i16val
int * ival
double * dval
float * fval
dbr_string_t * sval
cnp.int16_t [::1] mvShort #C-contiguous
int [::1] mvInt #C-contiguous
double [::1] mvDouble #C-contiguous
float [::1] mvFloat #C-contiguous
#str [:,::1] mvStr
cnp.ndarray arr
long dtr=0
int status
#cvarray mvDoubleArray
unsigned int i
unsigned int ij
array.array a
cnp.uint8_t [::1] mvUInt8 #C-contiguous
cnp.int8_t [::1] mvInt8 #C-contiguous
cnp.uint16_t [::1] mvUInt16 #C-contiguous
cnp.int16_t [::1] mvInt16 #C-contiguous
cnp.uint32_t [::1] mvUInt32 #C-contiguous
cnp.int32_t [::1] mvInt32 #C-contiguous
cnp.uint64_t [::1] mvUInt64 #C-contiguous
cnp.int64_t [::1] mvInt64 #C-contiguous
#cnp.float16_t [::1] mvFloat16 #C-contiguous
cnp.float32_t [::1] mvFloat32 #C-contiguous
cnp.float64_t [::1] mvFloat64 #C-contiguous
#cdef PVDataHolder pvd
status=self.hh.getDataTypeNative(handle, dtr)
if status != ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return [None]
elif dtr in [CAFE_NO_ACCESS, CAFE_TYPENOTCONN]:
if self._c_cafe.isChannelConnected(handle) is False:
self._c_cafe.getChannelInfo(handle,self.channelInfo)
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatus(handle,self.channelInfo.getCafeConnectionState() )
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=self.channelInfo.getCafeConnectionState(), _et=self.cs.code(self.channelInfo.getCafeConnectionState()),\
_ei=self.cs.info(self.channelInfo.getCafeConnectionState()))
raise Exception(_cyCafeException)
return [None]
#Likely to be superfluous
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatus(handle,ICAFE_TYPENOTCONN)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=ICAFE_TYPENOTCONN, _et=self.cs.code(ICAFE_TYPENOTCONN), _ei=self.cs.info(ICAFE_TYPENOTCONN))
raise Exception(_cyCafeException)
return [None]
cdef unsigned int dtcheck = dtr
dtcheck=getMatchedDataType(dt, dtr)
cdef unsigned int nelemNative = self.hh.getNelemNative (handle)
cdef unsigned int nelemClient = self.hh.getNelemClient (handle)
cdef unsigned int nelemRequest = self.hh.getNelemRequest(handle)
cdef unsigned int nelemMethod = nelemClient
cdef unsigned int nelemMemory = nelemClient #previously nelemNative - has to be at least size of nelemClient
#print('native', self.hh.getNelemNative(handle))
#print('client', self.hh.getNelemClient(handle))
#print('request',self.hh.getNelemRequest(handle))
#print ('dtcheck', dtcheck)
#cdef double [::1] cyarr_view
#The element type of a typed memoryview may be a numeric scalar type (int, float)
#It may be a ctypedef alias, or it may be a structured type declared with e.g. cdef struct
if dtcheck in [CAFE_STRING, CAFE_ENUM]:
sval = <char[40]*>malloc( nelemMemory * sizeof(dbr_string_t))
with nogil:
status=self._c_cafe.getDbrStringArray(handle, sval)
#http://cython.readthedocs.org/en/latest/src/tutorial/numpy.html
#Some data types are not yet supported, like boolean arrays and string arrays.
locallist=[]
if status==ICAFE_NORMAL:
if art in ['numpy','ndarray','numpy.ndarray']:
###elif dt in ['np.string','np.str','np.unicode','np.string_','np.str_','np.unicode_']:
mvStr = np.empty(nelemMethod, dtype=(np.str_,40))
#mvStr=np.array(self.hh.getNelemRequest(handle), dtype='S40')
for i in range(0, nelemMethod):
#print sval[i].decode('utf8'), i
mvStr[i]=str(sval[i]) #.decode('utf8')
#locallist.append(sval[i])
free(sval)
return np.array(mvStr)
elif art in ['memoryview','mv','memoryviewslice']:
mvStr = np.empty(nelemMethod, dtype=(np.str_,40), order='C')
for ij in range(0, nelemMethod):
mvStr[ij]=str(sval[ij])
free(sval)
return memoryview(mvStr)
elif art in ['array','array.array']:
print ("PyCafe.pyx getArray, 'array' type does not support array of strings; returning list")
#RETURNING LIST - DOES NOT SUPPORT array of strings;
#arrayArray=array.array('u', 'hello \u2641')
arrayArray=[]
for ij in range(0, nelemMethod):
arrayArray.append(str(sval[ij]))
free(sval)
return arrayArray
elif art in ['ctypes', 'ctype']:
ctypesArray=(ctypes.c_char_p*nelemMethod)() #c_wchar_p is unicode!
for ij in range(0, nelemMethod):
ctypesArray[ij]=(sval[ij]).encode('utf-8')
free(sval)
return ctypesArray
else:
print("Unknown array type in user request for art='",art,"'. Possible types are:")
print("memoryview, numpy, array, ctypes")
print("Returning memoryview")
mvStr = np.empty(nelemMethod, dtype=(np.str_,40), order='C')
for ij in range(0, nelemMethod):
mvStr[ij]=<str>sval[ij]
free(sval)
return mvStr
elif dtcheck in [CAFE_SHORT, CAFE_CHAR]:
i16val = <short *>malloc(nelemMemory * sizeof(np.int16))
with nogil:
status=self._c_cafe.getShortArray(handle, i16val)
if status==ICAFE_NORMAL:
#np.empty preferred, else mvInt does not get correct value for first couple of array elements
if art in ['numpy','ndarray','numpy.ndarray']:
# ##mvInt=<int[:nelemMethod]>ival
# ##arr = np.ascontiguousarray(mvInt)
# ##set_base(arr, ival)
if dt in ['np.short','np.int16','short','int16']:
mvShort = np.empty(nelemMethod, dtype=np.int16, order='C')
for ij in range(0, nelemMethod):
mvShort[ij]=<cnp.int16_t>i16val[ij]
free(i16val)
return np.array(mvShort)
elif dt in ['np.int8','np.bool_','np.byte','bool','byte']:
mvInt8 = np.empty(nelemMethod, dtype=np.int8, order='C')
for ij in range(0, nelemMethod):
mvInt8[ij]=<cnp.int8_t>i16val[ij]
free(i16val)
return np.array(mvInt8)
elif dt in ['uchar','np.uint8']:
mvUInt8 = np.empty(nelemMethod, dtype=np.uint8, order='C')
for ij in range(0, nelemMethod):
mvUInt8[ij]=<cnp.uint8_t>i16val[ij]
free(i16val)
return np.array(mvUInt8)
else:
mvShort = np.empty(nelemMethod, dtype=np.int16, order='C')
#mvShortNP = np.ndarray(buffer=np.array(i16val), dtype=np.int16, order='C')
for ij in range(0, nelemMethod):
mvShort[ij]=<cnp.int16_t>i16val[ij]
#mvShortNP=cnp.asarray(i16val)
#aaa=np.full(nelemMethod,<mvShort, dtype=np.int16, order='C')
free(i16val)
return np.array(mvShort) #arr
elif art in ['memoryview','mv','memoryviewslice']:
mvShort = np.empty(nelemMethod, dtype=np.int16, order='C')
for ij in range(0, nelemMethod):
mvShort[ij]=<short>i16val[ij]
free(i16val)
return memoryview(mvShort)
elif art in ['array','array.array']:
a=array.array('h')
for ij in range(0, nelemMethod):
a.append(<short>i16val[ij])
free(i16val)
return a
elif art in ['ctypes', 'ctype']:
ctypesArray16=(ctypes.c_int16*nelemMethod)()
for ij in range(0, nelemMethod):
ctypesArray16[ij]=<short>i16val[ij]
free(i16val)
return ctypesArray16
else:
print("Unknow array type in user request for art='",art,"'. Possible types are:")
print("memoryview, numpy, array, ctypes")
print("Returning memoryview")
mvShort = np.empty(nelemMethod, dtype=np.int16, order='C')
for ij in range(0, nelemMethod):
mvShort[ij]=<short>i16val[ij]
free(i16val)
return mvShort
elif dtcheck in [CAFE_LONG]:
ival = <int *>malloc( nelemMemory * sizeof(np.int32))
with nogil:
status=self._c_cafe.getLongArray(handle, ival)
if status==ICAFE_NORMAL:
#np.empty preferred, else mvInt does not get correct value for first couple of array elements
#nelemMethod=self.hh.getnelemMethod(handle)
if art in ['numpy','ndarray','numpy.ndarray']:
##elif dt in ['np.intc','np.int_','np.long','np.ulong','np.ushort','np.int32','np.int64','np.uint32','np.uint64']:
if dt in ['np.int32','int32']:
mvInt32 = np.empty(nelemMethod, dtype=np.int32, order='C')
for ij in range(0, nelemMethod):
mvInt32[ij]=<cnp.int32_t>ival[ij]
free(ival)
return np.array(mvInt32) #
elif dt in ['np.uint32','uint32']:
mvUInt32 = np.empty(nelemMethod, dtype=np.uint32, order='C')
for ij in range(0, nelemMethod):
mvUInt32[ij]=<cnp.uint32_t>ival[ij]
free(ival)
return np.array(mvUInt32)
#elif dt in ['np.int64','int64']:
# mvInt64 = np.empty(nelemMethod, dtype=np.int64, order='C')
# for ij in range(0, nelemMethod):
# mvInt64[ij]=<cnp.int64_t>ival[ij]
# free(ival)
# return np.array(mvInt64) #
#elif dt in ['np.uint64','uint64']:
# mvUInt64 = np.empty(nelemMethod, dtype=np.uint64, order='C')
# for ij in range(0, nelemMethod):
# mvUInt64[ij]=<cnp.uint64_t>ival[ij]
# free(ival)
# return np.array(mvUInt64)
else:
mvInt = np.empty(nelemMethod, dtype=np.int32, order='C')
for ij in range(0, nelemMethod):
mvInt[ij]=<cnp.int32_t>ival[ij]
free(ival)
return np.array(mvInt) #arr
elif art in ['memoryview','mv','memoryviewslice']:
mvInt = np.empty(nelemMethod, dtype=np.int32, order='C')
for ij in range(0, nelemMethod):
mvInt[ij]=<int>ival[ij]
free(ival)
return memoryview(mvInt)
elif art in ['array','array.array']:
a=array.array('h')
for ij in range(0, nelemMethod):
a.append(<int>ival[ij])
free(ival)
return a
elif art in ['ctypes', 'ctype']:
ctypesArray=(ctypes.c_int32*nelemMethod)()
for ij in range(0, nelemMethod):
ctypesArray[ij]=<int>ival[ij]
free(ival)
return ctypesArray
else:
print("Unknow array type in user request for art='",art,"'. Possible types are:")
print("memoryview, numpy, array, ctypes")
print("Returning memoryview")
mvInt = np.empty(nelemMethod, dtype=np.int32, order='C')
for ij in range(0, nelemMethod):
mvInt[ij]=<int>ival[ij]
free(ival)
return mvInt
elif dtcheck in [CAFE_FLOAT]:
fval = <float *>malloc( nelemMemory * sizeof(float))
start=time.time()
with nogil:
status=self._c_cafe.getFloatArray(handle, fval)
# pvd.setNelem(self.hh.getnelemMethod(handle))
# with nogil:
# status=self._c_cafe.get(handle, pvd)
if status==ICAFE_NORMAL:
#nelemMethod=self.hh.getnelemMethod(handle)
if art in ['numpy','ndarray','numpy.ndarray']:
##elif dt in ['np.float16','np.float32']:
mvFloat = np.empty(nelemMethod, dtype=np.float32)
for ij in range(0, nelemMethod):
mvFloat[ij]=<float>fval[ij] # pvd.getAsFloat(ij)
#arr=np.asarray(mvFloat)
free(fval)
#arr = np.ascontiguousarray(mvDouble)
#set_base(arr, dval)
return np.array(mvFloat) #arr
elif art in ['memoryview','mv','memoryviewslice']:
#Method A to return memory view
mvFloat = np.empty(nelemMethod, dtype=np.float32)
for ij in range(0, nelemMethod):
mvFloat[ij]=<float>fval[ij]
free(fval)
#memoryview(mvFloat).tolist() #tolist() only supports byte views
return memoryview(mvFloat)
#Method B to return memory view
'''
mvDoubleArray=cvarray(shape=(nelemMethod,), itemsize=sizeof(double), format="d")
cyarr_view=mvDoubleArray
for i in range(0, nelemMethod):
#mvDoubleArray AVOID COPY TO mvDoubel Array!!
cyarr_view[i]=dval[i]
free(dval)
return cyarr_view
'''
elif art in ['array','array.array']:
a=array.array('f')
for ij in range(0, nelemMethod):
a.append(fval[ij])
free(fval)
return a
'''
arrayArray=array.array('f')
for ij in range(0, nelemMethod):
arrayArray.append(fval[ij])
free(fval)
return arrayArray
'''
'''
cvFloatArray=cvarray(shape=(nelemMethod,), itemsize=sizeof(float), format="f")
cyarr_view=cvFloatArray
for i in range(0, nelemMethod):
#mvDoubleArray AVOID COPY TO mvDoubel Array!!
cyarr_view[i]=fval[i]
free(fval)
return cyarr_view
'''
elif art in ['ctypes', 'ctype']:
ctypesArray=(ctypes.c_float*nelemMethod)()
for ij in range(0, nelemMethod):
ctypesArray[ij]=fval[ij]
free(fval)
return ctypesArray
else:
print("Unknow array type in user request for art='",art,"'. Possible types are:")
print("memoryview, numpy, array, ctypes")
print("Returning memoryview")
mvFloat = np.empty(nelemMethod, dtype=np.float32)
for ij in range(0, nelemMethod):
mvFloat[ij]=<float>fval[ij]
free(fval)
return mvFloat
elif dtcheck in [CAFE_DOUBLE]:
#start=time.time()
dval = <double *>malloc( nelemMemory * sizeof(double))
with nogil:
#for ij in range(0, 10000):
status=self._c_cafe.getDoubleArray(handle, dval)
if status==ICAFE_NORMAL:
#nelemMethod=self.hh.getnelemMethod(handle)
if art in ['numpy','ndarray','numpy.ndarray']:
#elif dt in ['double', 'np.float_','np.float64']:
#mvDouble=<double[:nelemMethod]>dval
mvDouble = np.empty(nelemMethod, dtype=np.float64)
for ij in range(0, nelemMethod):
mvDouble[ij]=<double>dval[ij]
#arr=np.asarray(mvDouble)
free(dval)
#end=time.time()
#print (end - start)
return np.array(mvDouble) #arr
elif art in ['memoryview','mv','memoryviewslice']:
#Method A to return memory view
mvDouble = np.empty(nelemMethod, dtype=np.float64)
for ij in range(0, nelemMethod):
mvDouble[ij]=<double>dval[ij]
free(dval)
#end=time.time()
#print (end - start)
return memoryview(mvDouble)
elif art in ['array','array.array']:
a=array.array('d')
for ij in range(0, nelemMethod):
a.append(dval[ij])
free(dval)
#end=time.time()
#print (end - start)
return a
elif art in ['ctypes', "ctype"]:
ctypesArray=(ctypes.c_double*nelemMethod)()
for ij in range(0, nelemMethod):
ctypesArray[ij]=dval[ij]
free(dval)
return ctypesArray
else:
print("Unknow array type in user request for art='",art,"'. Possible types are:")
print("memoryview, numpy, array, ctypes")
print("Returning memoryview")
mvDouble = np.empty(nelemMethod, dtype=np.float64)
for ij in range(0, nelemMethod):
mvDouble[ij]=<double>dval[ij]
free(dval)
return mvDouble
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return [None]
##################################################################################
#END: def getArray(self, handlePV, dt):
##################################################################################
##################################################################################
def getPVInt(self, handlePV):
return self.getPV(handlePV,'int')
##################################################################################
##################################################################################
def getPVFloat(self, handlePV):
return self.getPV(handlePV,'float')
##################################################################################
##################################################################################
def getPVStr(self, handlePV):
return self.getPV(handlePV,'str')
##################################################################################
##################################################################################
def getPV(self, handlePV, str dt='native'):
##################################################################################
cdef str _METHOD_="getPV"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef int status
cdef PVDataHolder pvd = PVDataHolder(self.hh.getNelemNative(handle))
with nogil:
status=self._c_cafe.get(handle, pvd)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
pvd_valnone=PVDataHolderToStruct(pvd, dt)
pvd_valnone.value[0]=None
return pvd_valnone
return PVDataHolderToStruct(pvd, dt)
##################################################################################
#END def getPV(self, handlePV):
##################################################################################
##################################################################################
def getPVStrList(self, handleList):
return self.getPVList(handleList, dt='str')
##################################################################################
##################################################################################
def getPVIntList(self, handleList):
return self.getPVList(handleList, dt='int')
##################################################################################
##################################################################################
def getPVFloatList(self, handleList):
return self.getPVList(handleList, dt='float')
##################################################################################
##################################################################################
def getPVList(self, handleList, str dt='native', cacheFlag=False):
##################################################################################
cdef str _METHOD_="getPVList"
if isinstance(handleList, (str,int,long)):
hl=[]
hl.append(handleList)
handleList=[]
handleList=hl
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList)
elif not isinstance(handleList[0], (int, long)):
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be a 'list' of <type 'int'> if handles, else <type 'str'> if PVs"))
#cdef unsigned int nelemTotal=0
#for i in range(0, len(handleList)):
# nelemTotal+=self.hh.getNelemNative(handleList[i])
# cdef int size_cdu = sizeof(CAFE_DATATYPE_UNION) #16 is size of boost_shared_ptr<CAFE_DATATYPE_UNION> (size 40)
# cdef PVDataHolder * pvd = \
# <PVDataHolder *>malloc( 100000000 + \
# len(handleList) * sizeof(PVDataHolder) + nelemTotal*size_cdu)
cdef vector[unsigned int] v
#do this to avoid compiler warning messages
for i in range(0, len(handleList)):
v.push_back(handleList[i])
cdef PVDataHolder * pvd = self._c_cafe.getPVData(v)
for i in range(0, len(handleList)):
pvd[i].setNelem(self.hh.getNelemNative(handleList[i]))
#print " ", pvd[i].getNelem(), self.hh.getNelemNative(handleList[i]), i
cdef int status
if(cacheFlag):
status=self._c_cafe.getCachePVArray(v, pvd)
else:
with nogil:
status=self._c_cafe.getPVArray(v, pvd)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
for i in range(0, len(handleList)):
if (pvd[i].getStatus() != ICAFE_NORMAL):
print ("Handle=", handleList[i], "PV=", self.hh.getPVFromHandle(handleList[i]) )
print ("with error status=", pvd[i].getStatus() )
self._c_cafe.printStatusMessage(status)
print ("")
#raise Exception("EXCEPTION RAISED in PyCafe def getPVList. Status = %d" %status)
cdef unsigned int dtn
cdef unsigned int dtcheck
pvdList=[]
cpdef pvdata p1
for i in range(0, len(handleList)):
dtn = pvd[i].getDataType();
dtcheck=getMatchedDataType(dt, dtn)
localList=[]
if pvd[i].getNelem() == 1:
if dtcheck==CAFE_STRING:
localList.append(pvd[i].getAsString())
elif dtcheck==CAFE_SHORT:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_FLOAT:
localList.append(pvd[i].getAsDouble())
elif dtcheck==CAFE_ENUM:
#if enum, string taken as native
if self._c_cafe.isEnum(handleList[i]):
localList.append(pvd[i].getAsString())
else:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_CHAR:
localList.append(pvd[i].getAsLong()) #(<unsigned char> pvd[i].getAsChar())
elif dtcheck==CAFE_LONG:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_DOUBLE:
localList.append(pvd[i].getAsDouble())
else:
localList.append(0) #no data
else:
localListInner=[]
if dtcheck==CAFE_STRING:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsString(j))
elif dtcheck==CAFE_SHORT:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_FLOAT:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsDouble(j))
elif dtcheck==CAFE_ENUM:
for j in range(0, pvd[i].getNelem()):
#if enum, string taken as native
if self._c_cafe.isEnum(handleList[i]):
localListInner.append(pvd[i].getAsString(j))
else:
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_CHAR:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j))#(<unsigned char> pvd[i].getAsChar(j))
elif dtcheck==CAFE_LONG:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_DOUBLE:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsDouble(j))
else:
for j in range(0, pvd[i].getNelem()):
localListInner.append(0) #no data
localList.append(localListInner)
p1 = pvdata()
p1.value=localList
p1.status=pvd[i].getStatus()
p1.nelem=pvd[i].getNelem()
p1.alarmStatus=pvd[i].getAlarmStatus()
p1.alarmSeverity=pvd[i].getAlarmSeverity()
pvd._etsNorm=pvd[i].getEpicsTimeStampAsUInt32()
ll=[]
ll.append((pvd[i]._etsNorm).secPastEpoch)
ll.append((pvd[i]._etsNorm).nsec)
p1.ts=ll
pvd._etsDate=pvd[i].getEpicsTimeStampAsDate()
ld=[]
ld.append( (pvd[i]._etsDate).year )
ld.append( (pvd[i]._etsDate).mon )
ld.append( (pvd[i]._etsDate).day )
ld.append( (pvd[i]._etsDate).hour )
ld.append( (pvd[i]._etsDate).min )
ld.append( (pvd[i]._etsDate).sec )
ld.append( (pvd[i]._etsDate).nsec )
p1.tsDate=ld
pvdList.append(p1)
#free(pvd)
return pvdList, status
##################################################################################
#END: def getPVList(self, handlePV, dt):
##################################################################################
##################################################################################
def printStatusIfError(self, handleList, statusList):
##################################################################################
cdef str _METHOD_="printStatusIfError"
if isinstance(handleList,(str,int,long)):
handleListB=[]
handleListB.append(handleList)
handleList=[]
handleList=handleListB
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList)
elif not isinstance(handleList[0], (int, long)):
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be a 'list' of <type 'int'> if handles or <type 'str'> if PVs"))
if isinstance(statusList, (int,long)):
statusListB=[]
statusListB.append(statusList)
statusList=[]
statusList=statusListB
if not isinstance(statusList, (list)):
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"Second input argument should be <type 'list'> of <type 'int'>"))
if not isinstance(statusList[0], (int, long, float)):
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"Second input argument should be a <type 'list'> of <type 'int'>"))
cdef vector[unsigned int] v
#do next step to avoid:
#warning: comparison between signed and unsigned integer expressions
for i in range(0, len(handleList)):
v.push_back(handleList[i]) #do this copy to avoid compiler warning messages
return self._c_cafe.printStatusIfError(v, statusList)
##################################################################################
##################################################################################
def getAsyn(self, handleList):
##################################################################################
cdef str _METHOD_="getAsyn"
if isinstance(handleList, (str,int,long)):
handleListB=[]
handleListB.append(handleList)
handleList=[]
handleList=handleListB
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList)
elif not isinstance(handleList[0], (int, long)):
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be a 'list' of <type 'int'> if handles or <type 'str'> if PVs"))
cdef vector[unsigned int] v
cdef vector[int] vStatus
v.reserve (len(handleList))
vStatus.reserve(len(handleList))
#do next step to avoid:
#warning: comparison between signed and unsigned integer expressions
for i in range(0, len(handleList)):
v.push_back(handleList[i]) #do this copy to avoid compiler warning messages
#Need to copy to a vector since
#Coercion from Python not allowed without the GIL
with nogil:
status=self._c_cafe.getV(v, vStatus)
if (status!=ICAFE_NORMAL):
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
print ("Error/Warning from def getAsyn: ")
self._c_cafe.printStatusMessage(status)
return status, vStatus
##################################################################################
#END: def getAsyn(self, handleList):
##################################################################################
##################################################################################
def waitForGetEvent(self,handlePV):
##################################################################################
cdef str _METHOD_="waitForGetEvent(handlePV)"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument, should be <type 'int'> if handle, else <type 'str'> if PV"))
with nogil:
status=self._c_cafe.waitForGetEvent(handle)
return status
##################################################################################
#END: def waitForGetEvent(self, handlePV)
##################################################################################
##################################################################################
def waitForBundledEvents(self, handleList):
##################################################################################
cdef str _METHOD_="waitForBundledEvents(self, handleList)"
if isinstance(handleList, (str,int,long)):
handleListB=[]
handleListB.append(handleList)
handleList=[]
handleList=handleListB
if not isinstance(handleList, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def waitForBundledEvents. \n\
First input argument, should be <type 'list'> of handles or PVs")
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList)
elif not isinstance(handleList[0], (int, long)):
raise Exception ("EXCEPTION RAISED IN PyCafe def waitForBundledEvents. \n\
First input argument, should be a 'list' of <type 'int'> if handles or <type 'str'> if PVs")
cdef vector[unsigned int] v
cdef vector[int] vRB
v.reserve (len(handleList))
vRB.reserve(len(handleList))
for i in range(0, len(handleList)):
v.push_back(handleList[i]) #do this copy to avoid compiler warning messages
#Wait for bundle
with nogil:
status=self._c_cafe.waitForBundledEvents(v, vRB)
if (status!=ICAFE_NORMAL):
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
print ("Error in def waitForBundledEvents: ")
self._c_cafe.printStatusMessage(status)
return status
return status, vRB
##################################################################################
#END: def waitForBundledEvents(self, handleList):
##################################################################################
##################################################################################
def getScalarArray(self, handleList, str dt='native', bint cacheFlag=False):
##################################################################################
cdef str _METHOD_="getScalarArray(handleList, str dt='native')"
#cdef float [::1] mvFloat #C-contiguous
if not isinstance(handleList, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def getScalarList. \n\
First input argument, should be <type 'list'> of handles or PVs")
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList)
elif not isinstance(handleList[0], (int, long)):
raise Exception ("EXCEPTION RAISED IN PyCafe def getScalarList. \n\
First input argument, should be a 'list' of <type 'int'> if handles or <type 'str'> if PVs")
nelemPrevious= []
for i in range(0, len(handleList)):
nelemPrevious.append(self._c_cafe.setNelemToOne(handleList[i]))
#pack into numpy
cdef vector[unsigned int] v
cdef vector[int] vStatus
v.reserve (len(handleList))
vStatus.reserve(len(handleList))
for i in range(0, len(handleList)):
v.push_back(handleList[i]) #do this copy to avoid compiler warning messages
cdef vector[int] vRB
status=ICAFE_NORMAL
if (cacheFlag == False):
#Need to copy to a vector since
#Coercion from Python not allowed without the GIL
with nogil:
status=self._c_cafe.getV(v, vStatus)
#Check for error code 704: ICAFE_WAITING_FOR_PREV_CALLBACK
#as this may mean we have a double handle instance.
#This is not a problem as such but if this is the case let's
#remove the error if the first getAsyn call for the handle in question was OK
#Functionality not yet moved to CAFE::
#Required for when dt='native'
if (status != ICAFE_NORMAL):
for i in range(0,len(vStatus)):
if (vStatus[i]==ICAFE_WAITING_FOR_PREV_CALLBACK):
#getHandle
for j in range(0,(i-1)):
if(v[j]==v[i]):
if (vStatus[j]==ICAFE_NORMAL):
vStatus[i]=vStatus[j]
#ca_poll() Not required as above will flush!
#Wait for bundle
with nogil:
statusBundle=self._c_cafe.waitForBundledEvents(v, vRB)
if (statusBundle!=ICAFE_NORMAL):
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
print ("Error in def getScalarList: ")
self._c_cafe.printStatusMessage(statusBundle)
cdef unsigned int dtcheck=CAFE_NOT_REQUESTED #native type not yet know
dtcheck=getMatchedDataType(dt, dtcheck)
#print ("dt=", dt, "dtcheck=", dtcheck)
if dtcheck in [CAFE_STRING]:
self.vStr.clear()
self.vStr.reserve(len(handleList))
with nogil:
status=self._c_cafe.getCacheVStr(v, self.vStr, vStatus)
for i in range(0, len(handleList)):
self._c_cafe.setNelemToPrevious(handleList[i],nelemPrevious[i])
##localList=[]
##statusList=[]
#for i in range(0, len(self.vStr)):
#localList.append( self.vStr[i])
return self.vStr, status, vStatus
elif dtcheck in [CAFE_SHORT, CAFE_CHAR, CAFE_LONG]:
self.vInt.clear()
self.vInt.reserve(len(handleList))
with nogil:
status=self._c_cafe.getCacheVLong(v, self.vInt, vStatus)
#for i in range(0, len(vStatus)):
#print ("status " , vStatus[i], " i", i, self._c_cafe.getPVFromHandle(handleList[i]))
for i in range(0, len(handleList)):
self._c_cafe.setNelemToPrevious(handleList[i],nelemPrevious[i])
##localList=[]
##statusList=[]
#for i in range(0, len(self.vInt)):
return self.vInt, status, vStatus
elif dtcheck in [CAFE_FLOAT, CAFE_DOUBLE]:
self.vFloat.clear()
self.vFloat.reserve(len(handleList))
with nogil:
status=self._c_cafe.getCacheVDouble(v, self.vFloat, vStatus)
for i in range(0, len(handleList)):
self._c_cafe.setNelemToPrevious(handleList[i],nelemPrevious[i])
#for i in range(0, len(vStatus)):
# print ("status/// " , vStatus[i], " i", i, self._c_cafe.getPVFromHandle(handleList[i]))
#print ("overall status", status)
##localList=[]
##statusList=[]
#Method A to return memory view
#mvFloat = np.empty(len(handleList), dtype=np.float32)
#for ij in range(0, len(handleList)):
# mvFloat[ij]=<float>self.vFloat[ij]
#return mvFloat, status, vStatus
#for i in range(0, len(self.vFloat)):
return self.vFloat, status, vStatus
#Native
#cdef unsigned int nelemTotal=0
# for i in range(0, len(handleList)):
# nelemTotal+=self.hh.getNelemNative(handleList[i])
#cdef int size_cdu = sizeof(CAFE_DATATYPE_UNION) #16 is size of boost_shared_ptr<CAFE_DATATYPE_UNION> (size 40)
#Create temporary group from handleList
#Does group exist?
cdef PVDataHolder * pvd = self._c_cafe.getPVData(v)
#for i in range (0, len(handleList)):
# print pvd[i].getPVName(), pvd[i].getAsString(), " [",i,"]"
# print ""
#print ("-----------------------------------------------------------------")
#cdef PVDataHolder * pvd = \
#<PVDataHolder *>malloc( 100000000 + \
# len(handleList) * sizeof(PVDataHolder) + nelemTotal*size_cdu)
#print "size_pvd=", sizeof(PVDataHolder)
#print "sizeoverall", len(handleList) * sizeof(PVDataHolder)*10000
#Required to allocate memory for shared pointer
for i in range(0, len(handleList)):
pvd[i].setNelem(1)
statusNoWait=self._c_cafe.getCachePVArrayNoWait(v, pvd)
for i in range(0, len(handleList)):
self._c_cafe.setNelemToPrevious(handleList[i],nelemPrevious[i])
statusList=[]
statusFlag=True
statusLocal=ICAFE_NORMAL
if (cacheFlag==True):
#if status !=ICAFE_NORMAL:
# if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
# self._c_cafe.printStatusMessage(status)
#status=ICAFE_NORMAL
for i in range(0, len(handleList)):
statusList.append(pvd[i].getStatus())
if pvd[i].getStatus() != ICAFE_NORMAL:
print ("Error in Element ", i, " from ", len(handleList), " in PyCafe def getScalarList")
print ("Handle= ", handleList[i], " PV=", self.hh.getPVFromHandle(handleList[i]))
print ("with error status=", pvd[i].getStatus())
self._c_cafe.printStatusMessage(pvd[i].getStatus())
if statusFlag:
statusLocal =pvd[i].getStatus()
statusFlag=False
#
#else:
# statusList.append(status)
#Wht not as a memoryView?
cdef unsigned int dtn
localList=[]
for i in range(0, len(handleList)):
dtn = pvd[i].getDataType();
dtcheck = getMatchedDataType(dt, dtn)
#print ("dt=", dt, "dtn=", dtn, "dtcheck=", dtcheck)
#print (pvd[i].getAsString())
#print (pvd[i].getAsDouble())
if dtcheck==CAFE_STRING:
localList.append(pvd[i].getAsString())
elif dtcheck==CAFE_SHORT:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_FLOAT:
localList.append(pvd[i].getAsDouble())
elif dtcheck==CAFE_ENUM:
#if enum, string taken as native
if self._c_cafe.isEnum(self.hh.getHandleFromPV(pvd[i].getPVName()))==1:
localList.append(pvd[i].getAsString())
else:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_CHAR:
localList.append( pvd[i].getAsLong()) #<unsigned char> pvd[i].getAsChar()
elif dtcheck==CAFE_LONG:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_DOUBLE:
localList.append(pvd[i].getAsDouble())
else:
localList.append(0)
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_HIGH:
print ("def getScalarList:")
print ("Entering 0 for element", i, "as channel is not connected!")
#print (" vstatus = ", vStatus[i] , " pvd[i].status ", pvd[i].getStatus() )
#free(pvd)
if (cacheFlag==True):
return localList, statusLocal, statusList
return localList, status, vStatus # use vstatus instead of statusList (as cache is NoWait)
##################################################################################
#END: def getScalarList(self, handleList, dt):
##################################################################################
##################################################################################
def getStrScalarList(self, handleList):
##################################################################################
return self.getScalarList(handleList, dt='str')
##################################################################################
def getIntScalarList(self, handleList):
##################################################################################
return self.getScalarList(handleList, dt='int')
##################################################################################
def getFloatScalarList(self, handleList):
##################################################################################
return self.getScalarList(handleList, dt='float')
##################################################################################
def getScalarList(self, handleList, str dt='native', bint cacheFlag=False):
##################################################################################
cdef str _METHOD_="getScalarList(handleList, str dt='native')"
#cdef float [::1] mvFloat #C-contiguous
if not isinstance(handleList, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def getScalarList. \n\
First input argument, should be <type 'list'> of handles or PVs")
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList)
elif not isinstance(handleList[0], (int, long)):
raise Exception ("EXCEPTION RAISED IN PyCafe def getScalarList. \n\
First input argument, should be a 'list' of <type 'int'> if handles or <type 'str'> if PVs")
nelemPrevious= []
for i in range(0, len(handleList)):
nelemPrevious.append(self._c_cafe.setNelemToOne(handleList[i]))
#c=self.hh.getNelemClient(handleList[i])
#n=self.hh.getNelemNative(handleList[i])
#r=self.hh.getNelemRequest(handleList[i])
#print "c,n,r", c,n,r, "[",i,"]"
#c=self.hh.getNelemToRetrieveFromCache(handleList[i])
#print "cache", c, "[",i,"]"
#pack into vectors
cdef vector[unsigned int] v
cdef vector[int] vStatus
v.reserve (len(handleList))
vStatus.reserve(len(handleList))
for i in range(0, len(handleList)):
v.push_back(handleList[i]) #do this copy to avoid compiler warning messages
cdef vector[int] vRB
status=ICAFE_NORMAL
if (cacheFlag == False):
#Need to copy to a vector since
#Coercion from Python not allowed without the GIL
with nogil:
status=self._c_cafe.getV(v, vStatus)
#Check for error code 704: ICAFE_WAITING_FOR_PREV_CALLBACK
#as this may mean we have a double handle instance.
#This is not a problem as such but if this is the case let's
#remove the error if the first getAsyn call for the handle in question was OK
#Functionality not yet moved to CAFE::
#Required for when dt='native'
if (status != ICAFE_NORMAL):
for i in range(0,len(vStatus)):
if (vStatus[i]==ICAFE_WAITING_FOR_PREV_CALLBACK):
#getHandle
for j in range(0,(i-1)):
if(v[j]==v[i]):
if (vStatus[j]==ICAFE_NORMAL):
vStatus[i]=vStatus[j]
#ca_poll() Not required as above will flush!
#Wait for bundle
with nogil:
statusBundle=self._c_cafe.waitForBundledEvents(v, vRB)
if (statusBundle!=ICAFE_NORMAL):
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
print ("Error in def getScalarList: ")
self._c_cafe.printStatusMessage(statusBundle)
cdef unsigned int dtcheck=CAFE_NOT_REQUESTED #native type not yet know
dtcheck=getMatchedDataType(dt, dtcheck)
#print ("dt=", dt, "dtcheck=", dtcheck)
if dtcheck in [CAFE_STRING]:
self.vStr.clear()
self.vStr.reserve(len(handleList))
with nogil:
status=self._c_cafe.getCacheVStr(v, self.vStr, vStatus)
for i in range(0, len(handleList)):
self._c_cafe.setNelemToPrevious(handleList[i],nelemPrevious[i])
##localList=[]
##statusList=[]
#for i in range(0, len(self.vStr)):
#localList.append( self.vStr[i])
return self.vStr, status, vStatus
elif dtcheck in [CAFE_SHORT, CAFE_CHAR, CAFE_LONG]:
self.vInt.clear()
self.vInt.reserve(len(handleList))
with nogil:
status=self._c_cafe.getCacheVLong(v, self.vInt, vStatus)
#for i in range(0, len(vStatus)):
#print ("status " , vStatus[i], " i", i, self._c_cafe.getPVFromHandle(handleList[i]))
for i in range(0, len(handleList)):
self._c_cafe.setNelemToPrevious(handleList[i],nelemPrevious[i])
##localList=[]
##statusList=[]
#for i in range(0, len(self.vInt)):
return self.vInt, status, vStatus
elif dtcheck in [CAFE_FLOAT, CAFE_DOUBLE]:
self.vFloat.clear()
self.vFloat.reserve(len(handleList))
with nogil:
status=self._c_cafe.getCacheVDouble(v, self.vFloat, vStatus)
for i in range(0, len(handleList)):
self._c_cafe.setNelemToPrevious(handleList[i],nelemPrevious[i])
#for i in range(0, len(vStatus)):
# print ("status/// " , vStatus[i], " i", i, self._c_cafe.getPVFromHandle(handleList[i]))
#print ("overall status", status)
##localList=[]
##statusList=[]
#Method A to return memory view
#mvFloat = np.empty(len(handleList), dtype=np.float32)
#for ij in range(0, len(handleList)):
# mvFloat[ij]=<float>self.vFloat[ij]
#return mvFloat, status, vStatus
#for i in range(0, len(self.vFloat)):
return self.vFloat, status, vStatus
#Native
#cdef unsigned int nelemTotal=0
# for i in range(0, len(handleList)):
# nelemTotal+=self.hh.getNelemNative(handleList[i])
#cdef int size_cdu = sizeof(CAFE_DATATYPE_UNION) #16 is size of boost_shared_ptr<CAFE_DATATYPE_UNION> (size 40)
#Create temporary group from handleList
#Does group exist?
cdef PVDataHolder * pvd = self._c_cafe.getPVData(v)
#for i in range (0, len(handleList)):
# print pvd[i].getPVName(), pvd[i].getAsString(), " [",i,"]"
# print ""
#print ("-----------------------------------------------------------------")
#cdef PVDataHolder * pvd = \
#<PVDataHolder *>malloc( 100000000 + \
# len(handleList) * sizeof(PVDataHolder) + nelemTotal*size_cdu)
#print "size_pvd=", sizeof(PVDataHolder)
#print "sizeoverall", len(handleList) * sizeof(PVDataHolder)*10000
#Required to allocate memory for shared pointer
for i in range(0, len(handleList)):
pvd[i].setNelem(1)
statusNoWait=self._c_cafe.getCachePVArrayNoWait(v, pvd)
for i in range(0, len(handleList)):
self._c_cafe.setNelemToPrevious(handleList[i],nelemPrevious[i])
statusList=[]
statusFlag=True
statusLocal=ICAFE_NORMAL
if (cacheFlag==True):
#if status !=ICAFE_NORMAL:
# if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
# self._c_cafe.printStatusMessage(status)
#status=ICAFE_NORMAL
for i in range(0, len(handleList)):
statusList.append(pvd[i].getStatus())
if pvd[i].getStatus() != ICAFE_NORMAL:
print ("Error in Element ", i, " from ", len(handleList), " in PyCafe def getScalarList")
print ("Handle= ", handleList[i], " PV=", self.hh.getPVFromHandle(handleList[i]))
print ("with error status=", pvd[i].getStatus())
self._c_cafe.printStatusMessage(pvd[i].getStatus())
if statusFlag:
statusLocal =pvd[i].getStatus()
statusFlag=False
#
#else:
# statusList.append(status)
#Wht not as a memoryView?
cdef unsigned int dtn
localList=[]
for i in range(0, len(handleList)):
dtn = pvd[i].getDataType();
dtcheck = getMatchedDataType(dt, dtn)
#print ("dt=", dt, "dtn=", dtn, "dtcheck=", dtcheck)
#print (pvd[i].getAsString())
#print (pvd[i].getAsDouble())
if dtcheck==CAFE_STRING:
localList.append(pvd[i].getAsString())
elif dtcheck==CAFE_SHORT:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_FLOAT:
localList.append(pvd[i].getAsDouble())
elif dtcheck==CAFE_ENUM:
#if enum, string taken as native
if self._c_cafe.isEnum(self.hh.getHandleFromPV(pvd[i].getPVName()))==1:
localList.append(pvd[i].getAsString())
else:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_CHAR:
localList.append( pvd[i].getAsLong()) #<unsigned char> pvd[i].getAsChar()
elif dtcheck==CAFE_LONG:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_DOUBLE:
localList.append(pvd[i].getAsDouble())
else:
localList.append(0)
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_HIGH:
print ("def getScalarList:")
print ("Entering 0 for element", i, "as channel is not connected!")
#print (" vstatus = ", vStatus[i] , " pvd[i].status ", pvd[i].getStatus() )
#free(pvd)
if (cacheFlag==True):
return localList, statusLocal, statusList
return localList, status, vStatus # use vstatus instead of statusList (as cache is NoWait)
##################################################################################
#END: def getScalarList(self, handleList, dt):
##################################################################################
### # int alarmStatus=None, int alarmSev=None):
##################################################################################
def getCompoundList(self, handleList, str dt='native', bint cacheFlag=False):
##################################################################################
cdef str _METHOD_="getCompoundList(handleList, str dt='native')"
if isinstance(handleList, (str)):
handleList=self.getHandlesFromWithinGroup(handleList)
else:
if not isinstance(handleList, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def getCompoundList. \n\
First input argument, should be <type 'list'> of handles or PVs")
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList)
elif not isinstance(handleList[0], (int, long)):
raise Exception ("EXCEPTION RAISED IN PyCafe def getCompoundList. \n\
First input argument, should be a 'list' of <type 'int'> if handles or <type 'str'> if PVs")
#pack into vectors
cdef vector[unsigned int] v
cdef vector[int] vStatus
cdef vector[int] vRB
v.reserve (len(handleList))
vStatus.reserve(len(handleList))
cdef bint flagCompound=False
cdef unsigned int nelemLocal=1
for i in range(0, len(handleList)):
v.push_back(handleList[i]) #do this copy to avoid compiler warning messages
if (nelemLocal==1):
nelemLocal=self.hh.getNelemNative(handleList[i])
if nelemLocal > 1:
flagCompound=True
if (cacheFlag == False):
#Need to copy to a vector since
#Coercion from Python not allowed without the GIL
with nogil:
status=self._c_cafe.getV(v, vStatus)
#ca_poll() Not required as above will flush!
#Wait for bundle
with nogil:
statusBundle=self._c_cafe.waitForBundledEvents(v, vRB)
if (statusBundle!=ICAFE_NORMAL):
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
print ("Error in def getCompoundList: ")
self._c_cafe.printStatusMessage(statusBundle)
cdef unsigned int dtcheck=CAFE_NOT_REQUESTED #native type not yet know
dtcheck=getMatchedDataType(dt, dtcheck)
#Use Scalar
if flagCompound == False:
if dtcheck in [CAFE_STRING]:
self.vStr.clear()
self.vStr.reserve(len(handleList))
with nogil:
status=self._c_cafe.getCacheVStr(v, self.vStr, vStatus)
#localList=[]
#statusList=[]
#for i in range(0, len(self.vStr)):
#localList.append( self.vStr[i])
return self.vStr, status, vStatus
elif dtcheck in [CAFE_SHORT, CAFE_CHAR, CAFE_LONG]:
self.vInt.clear()
self.vInt.reserve(len(handleList))
with nogil:
status=self._c_cafe.getCacheVLong(v, self.vInt, vStatus)
#localList=[]
#statusList=[]
return self.vInt, status, vStatus
elif dtcheck in [CAFE_FLOAT, CAFE_DOUBLE]:
self.vFloat.clear()
self.vFloat.reserve(len(handleList))
with nogil:
status=self._c_cafe.getCacheVDouble(v, self.vFloat, vStatus)
#localList=[]
#statusList=[]
return self.vFloat, status, vStatus
#continue Can be a compound or native
#Native
#Create temporary group from handleList
#Does group exist?
cdef PVDataHolder * pvd = self._c_cafe.getPVData(v)
#Required to allocate memory for shared pointer
for i in range(0, len(handleList)):
pvd[i].setNelem(self.hh.getNelemClient(handleList[i]))
statusNoWait=self._c_cafe.getCachePVArrayNoWait(v, pvd)
statusList=[]
statusFlag=True
statusLocal=ICAFE_NORMAL
if (cacheFlag==True):
for i in range(0, len(handleList)):
statusList.append(pvd[i].getStatus())
if pvd[i].getStatus() != ICAFE_NORMAL:
print ("Error in Element ", i, " from ", len(handleList), " in PyCafe def getCompundList")
print ("Handle= ", handleList[i], " PV=", self.hh.getPVFromHandle(handleList[i]))
print ("with error status=", pvd[i].getStatus())
self._c_cafe.printStatusMessage(pvd[i].getStatus())
if statusFlag:
statusLocal =pvd[i].getStatus()
statusFlag=False
cdef unsigned int dtn
localList=[]
for i in range(0, len(handleList)):
dtn = pvd[i].getDataType();
dtcheck = getMatchedDataType(dt, dtn)
if pvd[i].getNelem() == 1:
if dtcheck==CAFE_STRING:
localList.append(pvd[i].getAsString())
elif dtcheck==CAFE_SHORT:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_FLOAT:
localList.append(pvd[i].getAsDouble())
elif dtcheck==CAFE_ENUM:
#if enum, string taken as native
if self._c_cafe.isEnum(handleList[i])==1:
localList.append(pvd[i].getAsString())
else:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_CHAR:
localList.append(<unsigned char> pvd[i].getAsChar())
elif dtcheck==CAFE_LONG:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_DOUBLE:
localList.append(pvd[i].getAsDouble())
else:
localList.append(0) #no data
else:
localListInner=[]
if dtcheck==CAFE_STRING:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsString(j))
elif dtcheck==CAFE_SHORT:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_FLOAT:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsDouble(j))
elif dtcheck==CAFE_ENUM:
for j in range(0, pvd[i].getNelem()):
#if enum, string taken as native
if self._c_cafe.isEnum(handleList[i])==1:
localListInner.append(pvd[i].getAsString(j))
else:
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_CHAR:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j)) #<unsigned char> pvd[i].getAsChar(j))
elif dtcheck==CAFE_LONG:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_DOUBLE:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsDouble(j))
else:
for j in range(0, pvd[i].getNelem()):
localListInner.append(0) #no data
localList.append(localListInner)
#free(pvd)
if (cacheFlag==True):
return localList, statusLocal, statusList
return localList, status, vStatus # use vstatus instead of statusList (as cache is NoWait)
##################################################################################
#END: def getCompoundList(self, handleList, dt):
##################################################################################
##################################################################################
def getCompoundPVGroup(self, ghandleName, str dt='native'):
##################################################################################
cdef str _METHOD_="getCompoundPVGroup(ghandleName, str dt='native')"
cdef unsigned int ghandle=0
if isinstance(ghandleName, (int,long)) == 1:
ghandle=ghandleName
elif isinstance(ghandleName, (str)) == 1:
ghandle=self.checkForGroupHandle(ghandleName)
else:
raise Exception ("EXCEPTION RAISED IN PyCafe def getCompoundPVGroup. \n\
First input argument, should be <type 'int'> if group handle, else <type 'str'> if group name")
handleList=[]
handleList=self.getHandlesFromWithinGroup(ghandle)
localList=[]
statusList=[]
cdef vector[unsigned int] hV
for i in range(0, len(handleList)):
hV.push_back(handleList[i])
self.hh.setCafeDbrTypeV(hV, DBR_TIME)
localList, status, statusList=self.getCompoundList(handleList, dt)
cdef PVGroup pvg
with nogil:
self._c_cafe.groupAttach(ghandle, pvg)
cdef PVDataHolder * pvd
pvd=pvg.getPVData()
cdef pvdata p1
localListToStruct=[]
cdef int groupStatus=ICAFE_NORMAL
for i in range(0, pvg.getNPV()):
p1 = pvdata()
#pvd[i].setDouble(localList[i])
p1=PVDataHolderToStruct(pvd[i], dt)
if not isinstance(localList[i],(list)):
ll=[]
ll.append(localList[i])
p1.value=ll
else:
p1.value=localList[i] #put into List!
p1.status=statusList[i]
if groupStatus == ICAFE_NORMAL:
groupStatus=statusList[i]
aStatSev=[]
aStatSev=self.getAlarmStatusSeverity(handleList[i])
p1.alarmStatus=aStatSev[0]
p1.alarmSeverity=aStatSev[1]
p1.ts=self.getTimeStamp(handleList[i])
p1.tsDate=self.getTimeStampAsDate(handleList[i])
#p1.showMax(10)
localListToStruct.append(p1)
#for j in range (0, len(localListToStruct)):
#localListToStruct[j].showMax(10)
cpdef pvgroup pg
pg = pvgroup()
pg.pvdata=localListToStruct
#pg.pvdata[0].showMax(10)
pg.npv=pvg.getNPV()
pg.name=pvg.getNameAsString()
pg.groupStatus=groupStatus #pvg.getStatusGroup()
pg.groupHandle=pvg.getGroupHandle()
#pg.showMax(1)
return pg
##################################################################################
#END: def getCompoundPVGroup(self, handleList, dt):
##################################################################################
##################################################################################
def getStrCache(self, handlePV):
return self.getCache(handlePV,'str')
##################################################################################
##################################################################################
def getIntCache(self, handlePV):
return self.getCache(handlePV,'int')
##################################################################################
##################################################################################
def getFloatCache(self, handlePV):
return self.getCache(handlePV,'float')
##################################################################################
##################################################################################
def getCache(self, handlePV, str dt='native'):
cdef str _METHOD_="getCache(handlePV, str dt='native')"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception ("EXCEPTION RAISED IN PyCafe def getCache. \n\
First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
cdef long dtr=0
status=self.hh.getDataTypeNative(handle, dtr)
if status != ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
raise Exception("EXCEPTION RAISED in PyCafe def getCache. Status = %d" %status)
return None
elif dtr in [CAFE_NO_ACCESS, CAFE_TYPENOTCONN]:
if self._c_cafe.isChannelConnected(handle) is False:
self._c_cafe.getChannelInfo(handle,self.channelInfo)
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatus(handle,self.channelInfo.getCafeConnectionState() )
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=self.channelInfo.getCafeConnectionState(), _et=self.cs.code(self.channelInfo.getCafeConnectionState()),\
_ei=self.cs.info(self.channelInfo.getCafeConnectionState()))
raise Exception(_cyCafeException)
return [None]
#Likely to be superfluous
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatus(handle,ICAFE_TYPENOTCONN)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=ICAFE_TYPENOTCONN, _et=self.cs.code(ICAFE_TYPENOTCONN), _ei=self.cs.info(ICAFE_TYPENOTCONN))
raise Exception(_cyCafeException)
return [None]
cdef unsigned int dtcheck = dtr
dtcheck=getMatchedDataType(dt, dtr)
if dtcheck in [CAFE_STRING]:
status=self._c_cafe.getCacheString(handle, self.valStr)
if status==ICAFE_NORMAL:
return self.valStr
elif dtcheck in [CAFE_SHORT, CAFE_CHAR, CAFE_LONG]:
status=self._c_cafe.getCacheLong(handle, self.valInt)
if status==ICAFE_NORMAL:
return self.valInt
elif dtcheck in [CAFE_FLOAT, CAFE_DOUBLE]:
status=self._c_cafe.getCacheDouble(handle, self.valFloat)
if status==ICAFE_NORMAL:
return self.valFloat
elif dtcheck==CAFE_ENUM:
#if enum, string taken as native
if self._c_cafe.isEnum(handle):
status=self._c_cafe.getCacheString(handle, self.valStr)
if status==ICAFE_NORMAL:
return self.valStr
else:
status=self._c_cafe.getCacheLong(handle, self.valInt)
if status ==ICAFE_NORMAL:
return self.valInt
else:
status=self.hh.getStatus(handle)
if status == ICAFE_NORMAL:
print ("This line in PyCafe def getCache should never appear!")
print ("Datatype unknown, returning value 0")
return 0
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
##################################################################################
##################################################################################
def getStrArrayCache(self, handlePV, str art='memoryview'):
return self.getArrayCache(handlePV, dt='str', art=art)
##################################################################################
##################################################################################
def getIntArrayCache(self, handlePV, str art='memoryview'):
return self.getArrayCache(handlePV, dt='int', art=art)
##################################################################################
##################################################################################
def getFloatArrayCache(self, handlePV, str art='memoryview'):
return self.getArrayCache(handlePV, dt='float', art=art)
##################################################################################
##################################################################################
def getArrayCache(self, handlePV, str dt='native', str art='memoryview'):
##################################################################################
#Typed Memoryviews from K.W. Smith
#Cython has a C-level type the typed memoryview, that conceptually overlaps
#with the Python memoryiew and expands on it. A typed memory view is used to
#view (share) data from a buffer-producing object.
#A typed memoryview has a memory-view like interface and is easier to use than
#workingwith C-lvevel buffers directly. And because a typed memoryview is designed
#to work with the buffer protocol it supports any buffer-producing object efficiently
#allowing sharing of data buffers without copying
cdef str _METHOD_="getArrayCache"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception("{} {} {}".format(self.exString, _METHOD_, \
"First input argument should be <type 'int'> if handle, else <type 'str'> if PV"))
cdef:
short * i16val
int * ival
double * dval
float * fval
dbr_string_t * sval
cnp.int16_t [::1] mvShort #C-contiguous
int [::1] mvInt #C-contiguous
double [::1] mvDouble #C-contiguous
float [::1] mvFloat #C-contiguous
#str [:,::1] mvStr
cnp.ndarray arr
long dtr=0
int status
unsigned int i
unsigned int ij
status=self.hh.getDataTypeNative(handle, dtr)
if status != ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return [None]
elif dtr in [CAFE_NO_ACCESS, CAFE_TYPENOTCONN]:
if self._c_cafe.isChannelConnected(handle) is False:
self._c_cafe.getChannelInfo(handle,self.channelInfo)
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatus(handle,self.channelInfo.getCafeConnectionState() )
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=self.channelInfo.getCafeConnectionState(), _et=self.cs.code(self.channelInfo.getCafeConnectionState()),\
_ei=self.cs.info(self.channelInfo.getCafeConnectionState()))
raise Exception(_cyCafeException)
return [None]
#Likely to be superfluous
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatus(handle,ICAFE_TYPENOTCONN)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=ICAFE_TYPENOTCONN, _et=self.cs.code(ICAFE_TYPENOTCONN), _ei=self.cs.info(ICAFE_TYPENOTCONN))
raise Exception(_cyCafeException)
return [None]
cdef unsigned int nelemToRetrieveFromCache=self.hh.getNelemToRetrieveFromCache(handle)
cdef unsigned int dtcheck = dtr
dtcheck=getMatchedDataType(dt, dtr)
#The elemnt type of a typed memoryview may be a numeric scalar type (int, float)
#It may be a ctypedef alias, or it may be a structured type declared with e.g. cdef struct
if dtcheck in [CAFE_STRING, CAFE_ENUM]:
sval = <char[40]*>malloc( nelemToRetrieveFromCache * sizeof(dbr_string_t))
status=self._c_cafe.getCacheDbrStringArray(handle, sval)
locallist=[]
if status==ICAFE_NORMAL:
for i in range(0,nelemToRetrieveFromCache):
locallist.append(sval[i])
free(sval)
return locallist
if status==ICAFE_NORMAL:
if art in ['numpy','ndarray','numpy.ndarray']:
mvStr = np.empty(nelemToRetrieveFromCache, dtype=(np.str_,40))
for i in range(0, nelemToRetrieveFromCache):
mvStr[i]=str(sval[i])
free(sval)
return mvStr
elif art in ['memoryview','mv','memoryviewslice']:
mvStr = np.empty(nelemToRetrieveFromCache, dtype=(np.str_,40), order='C')
for ij in range(0, nelemToRetrieveFromCache):
mvStr[ij]=str(sval[ij])
free(sval)
return mvStr
elif art in ['array','array.array']:
print ("PyCafe.pyx getArray, 'array' type does not support array of strings; returning list")
#RETURNING LIST - DOES NOT SUPPORT array of strings;
arrayArray=[]
for ij in range(0, nelemToRetrieveFromCache):
arrayArray.append(str(sval[ij]))
free(sval)
return arrayArray
elif art in ['ctypes', 'ctype']:
ctypesArray=(ctypes.c_char_p*nelemToRetrieveFromCache)() #c_wchar_p is unicode!
for ij in range(0, nelemToRetrieveFromCache):
ctypesArray[ij]=(sval[ij]).encode('utf-8')
free(sval)
return ctypesArray
else:
print("Unknow array type in user request for art='",art,"'. Possible types are:")
print("memoryview, numpy, array, ctypes")
print("Returning memoryview")
mvStr = np.empty(nelemToRetrieveFromCache, dtype=(np.str_,40), order='C')
for ij in range(0, nelemToRetrieveFromCache):
mvStr[ij]=<str>sval[ij]
free(sval)
return mvStr
elif dtcheck in [CAFE_SHORT, CAFE_CHAR]:
i16val = <short *>malloc( nelemToRetrieveFromCache * sizeof(np.int16))
status=self._c_cafe.getCacheShortArray(handle, i16val)
if status==ICAFE_NORMAL:
#np.empty preferred, else mvInt does not get correct value for first couple of array elements
if art in ['numpy','ndarray','numpy.ndarray']:
mvShortNP = np.empty(nelemToRetrieveFromCache, dtype=np.int16, order='C')
for ij in range(0, nelemToRetrieveFromCache):
mvShortNP[ij]=<cnp.int16_t>i16val[ij]
#arr=np.asarray(mvShort)
free(i16val)
return mvShortNP #arr
elif art in ['memoryview','mv','memoryviewslice']:
mvShort = np.empty(nelemToRetrieveFromCache, dtype=np.int16, order='C')
for ij in range(0, nelemToRetrieveFromCache):
mvShort[ij]=<short>i16val[ij]
free(i16val)
return mvShort
elif art in ['array','array.array']:
arrayArray=array.array('h')
for ij in range(0, nelemToRetrieveFromCache):
arrayArray.append(<short>i16val[ij])
free(i16val)
return arrayArray
elif art in ['ctypes', 'ctype']:
ctypesArray=(ctypes.c_int16*nelemToRetrieveFromCache)()
for ij in range(0, nelemToRetrieveFromCache):
ctypesArray[ij]=<short>i16val[ij]
free(i16val)
return ctypesArray
else:
print("Unknow array type in user request for art='",art,"'. Possible types are:")
print("memoryview, numpy, array, ctypes")
print("Returning memoryview")
mvShort = np.empty(nelemToRetrieveFromCache, dtype=np.int16, order='C')
for ij in range(0, nelemToRetrieveFromCache):
mvShort[ij]=<short>i16val[ij]
free(i16val)
return mvShort
elif dtcheck in [CAFE_LONG]:
ival = <int *>malloc( nelemToRetrieveFromCache * sizeof(np.int32))
status=self._c_cafe.getCacheLongArray(handle, ival)
if status==ICAFE_NORMAL:
if art in ['numpy','ndarray','numpy.ndarray']:
mvIntNP = np.empty(nelemToRetrieveFromCache, dtype=np.int32, order='C')
for ij in range(0, nelemToRetrieveFromCache):
mvIntNP[ij]=<cnp.int32_t>ival[ij]
free(ival)
return mvIntNP #arr
elif art in ['memoryview','mv','memoryviewslice']:
mvInt = np.empty(nelemToRetrieveFromCache, dtype=np.int32, order='C')
for ij in range(0, nelemToRetrieveFromCache):
mvInt[ij]=<int>ival[ij]
free(ival)
return mvInt
elif art in ['array','array.array']:
arrayArray=array.array('h')
for ij in range(0, nelemToRetrieveFromCache):
arrayArray.append(<int>ival[ij])
free(ival)
return arrayArray
elif art in ['ctypes', 'ctype']:
ctypesArray=(ctypes.c_int32*nelemToRetrieveFromCache)()
for ij in range(0, nelemToRetrieveFromCache):
ctypesArray[ij]=<int>ival[ij]
free(ival)
return ctypesArray
else:
print("Unknow array type in user request for art='",art,"'. Possible types are:")
print("memoryview, numpy, array, ctypes")
print("Returning memoryview")
mvInt = np.empty(nelemToRetrieveFromCache, dtype=np.int32, order='C')
for ij in range(0, nelemToRetrieveFromCache):
mvInt[ij]=<int>ival[ij]
free(ival)
return mvInt
elif dtcheck in [CAFE_FLOAT]:
fval = <float *>malloc( nelemToRetrieveFromCache * sizeof(float))
status=self._c_cafe.getCacheFloatArray(handle, fval)
if status==ICAFE_NORMAL:
if art in ['numpy','ndarray','numpy.ndarray']:
mvFloatNP = np.empty(nelemToRetrieveFromCache, dtype=np.float32)
for ij in range(0, nelemToRetrieveFromCache):
mvFloatNP[ij]=<float>fval[ij] # pvd.getAsFloat(ij)
free(fval)
return mvFloatNP #arr
elif art in ['memoryview','mv','memoryviewslice']:
#Method A to return memory view
mvFloat = np.empty(nelemToRetrieveFromCache, dtype=np.float32)
for ij in range(0, nelemToRetrieveFromCache):
mvFloat[ij]=<float>fval[ij]
free(fval)
return mvFloat
#Method B to return memory view
'''
mvDoubleArray=cvarray(shape=(nelemToRetrieveFromCache,), itemsize=sizeof(double), format="d")
cyarr_view=mvDoubleArray
for i in range(0, nelemToRetrieveFromCache):
#mvDoubleArray AVOID COPY TO mvDoubel Array!!
cyarr_view[i]=dval[i]
free(dval)
return cyarr_view
'''
elif art in ['array','array.array']:
arrayArray=array.array('f')
for ij in range(0, nelemToRetrieveFromCache):
arrayArray.append(fval[ij])
free(fval)
return arrayArray
elif art in ['ctypes', "ctype"]:
ctypesArray=(ctypes.c_float*nelemToRetrieveFromCache)()
for ij in range(0, nelemToRetrieveFromCache):
ctypesArray[ij]=fval[ij]
free(fval)
return ctypesArray
else:
print("Unknow array type in user request for art='",art,"'. Possible types are:")
print("memoryview, numpy, array, ctypes")
print("Returning memoryview")
mvFloat = np.empty(nelemToRetrieveFromCache, dtype=np.float32)
for ij in range(0, nelemToRetrieveFromCache):
mvFloat[ij]=<float>fval[ij]
free(fval)
return mvFloat
elif dtcheck in [CAFE_DOUBLE]:
dval = <double *>malloc( nelemToRetrieveFromCache * sizeof(double))
status=self._c_cafe.getDoubleArray(handle, dval)
if status==ICAFE_NORMAL:
if art in ['numpy','ndarray','numpy.ndarray']:
mvDoubleNP = np.empty(nelemToRetrieveFromCache, dtype=np.float64)
for ij in range(0, nelemToRetrieveFromCache):
mvDoubleNP[ij]=<double>dval[ij]
free(dval)
return mvDoubleNP #arr
elif art in ['memoryview','mv','memoryviewslice']:
#Method A to return memory view
mvDouble = np.empty(nelemToRetrieveFromCache, dtype=np.float64)
for ij in range(0, nelemToRetrieveFromCache):
mvDouble[ij]=<double>dval[ij]
free(dval)
return mvDouble
elif art in ['array','array.array']:
arrayArray=array.array('d')
for ij in range(0, nelemToRetrieveFromCache):
arrayArray.append(dval[ij])
free(dval)
return arrayArray
elif art in ['ctypes', "ctype"]:
ctypesArray=(ctypes.c_double*nelemToRetrieveFromCache)()
for ij in range(0, nelemToRetrieveFromCache):
ctypesArray[ij]=dval[ij]
free(dval)
return ctypesArray
else:
print("Unknow array type in user request for art='",art,"'. Possible types are:")
print("memoryview, numpy, array, ctypes")
print("Returning memoryview")
mvDouble = np.empty(nelemToRetrieveFromCache, dtype=np.float64)
for ij in range(0, nelemToRetrieveFromCache):
mvDouble[ij]=<double>dval[ij]
free(dval)
return mvDouble
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return [None]
##################################################################################
#END: def getArrayCache(self, handlePV, dt):
##################################################################################
##################################################################################
def getPVStrCache(self, handlePV):
return self.getPVCache(handlePV,'str')
##################################################################################
##################################################################################
def getPVIntCache(self, handlePV):
return self.getPVCache(handlePV,'int')
##################################################################################
##################################################################################
def getPVFloatCache(self, handlePV):
return self.getPVCache(handlePV,'float')
##################################################################################
##################################################################################
def getPVCache(self, handlePV, str dt='native'):
##################################################################################
cdef str _METHOD_="getPVCache(handlePV, str dt='native'"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception ("EXCEPTION RAISED IN PyCafe def getPVCache. \n \
First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
cdef PVDataHolder pvd
pvd.setNelem(self.hh.getNelemToRetrieveFromCache(handle))
status=self._c_cafe.getCache(handle, pvd)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
pvd_valnone=PVDataHolderToStruct(pvd, dt)
pvd_valnone.value[0]=None
return pvd_valnone
return PVDataHolderToStruct(pvd, dt)
##################################################################################
#END def getPVCache(self, handlePV):
##################################################################################
##################################################################################
def getCtrl(self, handlePV, str dt='native'):
##################################################################################
cdef str _METHOD_="getCtrl(handlePV, str dt='native')"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception ("EXCEPTION RAISED IN PyCafe def getCtrl. \n\
First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
cdef PVCtrlHolder pvc
pvc.setNelem(self.hh.getNelemClientCtrl(handle)) #do this dynamically
cdef int status
with nogil:
status=self._c_cafe.getCtrl(handle, pvc)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
pvc_valnone=PVCtrlHolderToStruct(pvc, dt)
pvc_valnone.value[0]=None
return pvc_valnone
return PVCtrlHolderToStruct(pvc, dt)
##################################################################################
#END: def getCtrl(self, handlePV, dt='native'):
##################################################################################
##################################################################################
def getCtrlCache(self, handlePV, str dt='native'):
##################################################################################
cdef str _METHOD_="getCtrlCache(handlePV, str dt='native')"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
raise Exception ("EXCEPTION RAISED IN PyCafe def getCtrlCache. \n\
First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
cdef PVCtrlHolder pvc
pvc.setNelem(self.hh.getNelemToRetrieveFromCtrlCache(handle))
status=self._c_cafe.getCtrlCache(handle, pvc)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
pvc_valnone=PVCtrlHolderToStruct(pvc, dt)
pvc_valnone.value[0]=None
return pvc_valnone
return PVCtrlHolderToStruct(pvc, dt)
##################################################################################
#END: def getCtrlCache(self, handlePV, dt='native'):
##################################################################################
##################################################################################
def groupMonitorStop(self, ghandleName):
##################################################################################
cdef str _METHOD_="groupMonitorStop(ghandleName)"
cdef unsigned int ghandle=0
if isinstance(ghandleName, (int,long)) == 1:
ghandle=ghandleName
elif isinstance(ghandleName, (str)) == 1:
ghandle=self.checkForGroupHandle(ghandleName)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if group handle, else <type 'str'> if group name")
raise Exception(_cyCafeException)
cdef PVGroup pvg
with nogil:
self._c_cafe.groupAttach(ghandle, pvg)
cdef vector[int] vStatus
vStatus.reserve(pvg.getNPV())
with nogil:
status=self._c_cafe.groupMonitorStop(ghandle, vStatus)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
return status, vStatus
##################################################################################
#END: def groupMonitorStop(self, ghandleName):
##################################################################################
def getMonitorPolicyVector(self, handlePV, _monid):
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)):
handle=handlePV
elif isinstance(handlePV, (str)):
handle=self.checkForHandle(handlePV, force=True)
else:
raise Exception ("EXCEPTION RAISED IN PyCafe def getMonitorPolicyVector \n\
First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
cdef vector[MonitorPolicy] mpV
self.hh.getMonitorPolicyVector(handle, mpV)
cdef monitorpolicy mp
mp = monitorpolicy()
cdef unsigned int i
for i in range (0, mpV.size()):
if mpV[i].getMonitorID()== _monid:
mp.monid=mpV[i].getMonitorID()
mp.nelem=mpV[i].getNelem()
mp.dataType=mpV[i].getDataType()
mp.userArgs=<long>mpV[i].getUserArgs()
mp.dbrDataType=mpV[i].getDbrDataType()
mp.cafeDbrType=mpV[i].getCafeDbrType()
mp.mask=mpV[i].getMask()
mp.maskHasDBE_PROPERTY=mpV[i].maskHasDBE_PROPERTY()
mp.maskHasDBE_VALUE=mpV[i].maskHasDBE_VALUE()
mp.maskHasDBE_LOG=mpV[i].maskHasDBE_LOG()
mp.maskHasDBE_ALARM=mpV[i].maskHasDBE_ALARM()
break
return mp
##################################################################################
def groupMonitorStart(self, ghandleName, object cb=None, DBR_TYPE dbr=DBR_TIME, unsigned int mask=DBE_VALUE|DBE_LOG|DBE_ALARM):
##########################################################################################
cdef str _METHOD_="groupMonitorStart(ghandleName, object cb=None, DBR_TYPE dbr=DBR_TIME, unsigned int mask=DBE_VALUE|DBE_LOG|DBE_ALARM)"
cdef unsigned int ghandle=0
if isinstance(ghandleName, (int,long)) == 1:
ghandle=ghandleName
elif isinstance(ghandleName, (str)) == 1:
ghandle=self.checkForGroupHandle(ghandleName)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if group handle, else <type 'str'> if group name")
raise Exception(_cyCafeException)
global monDictGlobal
if dbr:
if dbr not in [DBR_PLAIN, DBR_STS, DBR_TIME, DBR_GR, DBR_CTRL]:
print ("***Warning*** from groupMonitorStart for handle(orPV)=", ghandleName)
print ("dbr base type should be one of DBR_PLAIN, DBR_STS, DBR_TIME, DBR_GR, DBR_CTRL")
print ("Assuming DBR_TIME")
dbr=DBR_TIME
global py_cb
cdef vector[MonitorPolicy] mpV
cdef unsigned int mpid
cdef PVGroup pvg
with nogil:
self._c_cafe.groupAttach(ghandle, pvg)
cdef MonitorPolicy * mp
mp=self._c_cafe.createMonitorPolicyArray(pvg.getNPV())
for i in range(0, pvg.getNPV()):
mp[i].setMask(mask)
mp[i].setCafeDbrType(dbr)
mpid=mp[i].getMonitorID()
if cb:
a=inspect.getargspec(cb)
monDictGlobal[mpid]=cb
if (len(a[0])==1):
mp[i].setUserArgs(<void*> mpid)
mp[i].setPyHandler()
else:
mp[i].setPyHandlerData()
mpV.push_back(mp[i])
cdef vector[int] vStatus
vStatus.reserve(pvg.getNPV())
with nogil:
status=self._c_cafe.groupMonitorStart(ghandle, vStatus, mpV)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
return status, vStatus
##################################################################################
##################################################################################
def groupMonitorStartWithCBList(self, ghandleName, list cb=None, DBR_TYPE dbr=DBR_TIME, unsigned int mask=DBE_VALUE|DBE_LOG|DBE_ALARM):
##########################################################################################
cdef str _METHOD_="groupMonitorStartWithCBList(ghandleName, list cb=None, DBR_TYPE dbr=DBR_TIME, unsigned int mask=DBE_VALUE|DBE_LOG|DBE_ALARM)"
cdef unsigned int ghandle=0
if isinstance(ghandleName, (int,long)) == 1:
ghandle=ghandleName
elif isinstance(ghandleName, (str)) == 1:
ghandle=self.checkForGroupHandle(ghandleName)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if group handle, else <type 'str'> if group name")
raise Exception(_cyCafeException)
global monDictGlobal
if dbr:
if dbr not in [DBR_PLAIN, DBR_STS, DBR_TIME, DBR_GR, DBR_CTRL]:
print ("***Warning*** from groupMonitorStartWithCBList for handle(orPV)=", ghandleName)
print ("dbr base type should be one of DBR_PLAIN, DBR_STS, DBR_TIME, DBR_GR, DBR_CTRL")
print ("Assuming DBR_TIME")
dbr=DBR_TIME
if not isinstance(cb,(list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def groupMonitorStartWithCBList. \n\
Input cb should be of type<list> and give the list of cb objects")
global py_cb
cdef vector[MonitorPolicy] mpV
cdef unsigned int mpid
cdef PVGroup pvg
with nogil:
self._c_cafe.groupAttach(ghandle, pvg)
if (len(cb) != pvg.getNPV() ):
print("No of group members is ", pvg.getNPV(), " while list of callback objects is", len(cb))
raise Exception ("EXCEPTION RAISED IN PyCafe def groupMonitorStartWithCBList. \n\
No of group members doe not match the length of callback object list")
cdef MonitorPolicy * mp
mp=self._c_cafe.createMonitorPolicyArray(pvg.getNPV())
for i in range(0, pvg.getNPV()):
mp[i].setMask(mask)
mp[i].setCafeDbrType(dbr)
mpid=mp[i].getMonitorID()
if cb[i]:
a=inspect.getargspec(cb[i])
monDictGlobal[mpid]=cb[i]
if (len(a[0])==1):
mp[i].setUserArgs(<void*> mpid)
mp[i].setPyHandler()
else:
mp[i].setPyHandlerData()
mpV.push_back(mp[i])
cdef vector[int] vStatus
vStatus.reserve(pvg.getNPV())
with nogil:
status=self._c_cafe.groupMonitorStart(ghandle, vStatus, mpV)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
return status, vStatus
##################################################################################
def getGroupStr(self, ghandleName):
return self.getGroup(ghandleName, 'str')
def getGroupInt(self, ghandleName):
return self.getGroup(ghandleName, 'int')
def getGroupFloat(self, ghandleName):
return self.getGroup(ghandleName, 'float')
##################################################################################
def getGroup(self, ghandleName, str dt='native'):
cdef str _METHOD_="getGroup(ghandleName, str dt='native')"
cdef unsigned int ghandle=0
if isinstance(ghandleName, (int,long)) == 1:
ghandle=ghandleName
elif isinstance(ghandleName, (str)) == 1:
ghandle=self.checkForGroupHandle(ghandleName)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if group handle, else <type 'str'> if group name")
raise Exception(_cyCafeException)
cdef PVGroup pvg
with nogil:
self._c_cafe.groupAttach(ghandle, pvg)
cdef PVDataHolder * pvd
pvd=pvg.getPVData();
for i in range (0, pvg.getNPV()):
pvd[i].setHasAlarm(False)
pvd[i].setHasTS(False)
#pvd[i].setRule(False)
pvg.setPVData(pvd)
##pvd=pvg.getPVData();
#print "get rule 0p", pvd[0].getRule()
#print "get rule 1p", pvd[1].getRule()
#print "get rule 2p", pvd[2].getRule()
##
with nogil:
status=self._c_cafe.groupGet(ghandle, pvg)
if status == ECA_TIMEOUT :
print ("======================================================")
self._c_cafe.printStatusMessage(status)
print ("TIMEOUT in getGroup; switching to getCompoundList")
print ("======================================================")
return self.getCompoundList(pvg.getNameAsString(), dt)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
#do not raise exception
#raise Exception("EXCEPTION RAISED in PyCafe def getGroup. Status = %d" %status)
#pvg.showMaxMax(5,10)
pvd=pvg.getPVData()
localList=[]
statusList=[]
cdef unsigned int dtn, dtcheck
for i in range(0, pvg.getNPV()):
dtn = pvd[i].getDataType();
dtcheck=getMatchedDataType(dt, dtn)
statusList.append(pvd[i].getStatus())
if pvd[i].getNelem() == 1:
if dtcheck==CAFE_STRING:
localList.append(pvd[i].getAsString())
elif dtcheck==CAFE_SHORT:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_FLOAT:
localList.append(pvd[i].getAsDouble())
elif dtcheck==CAFE_ENUM:
#if enum, string taken as native
if self._c_cafe.isEnum(self.hh.getHandleFromPVWithinGroup(pvd[i].getPVName(),ghandle))==1:
localList.append(pvd[i].getAsString())
else:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_CHAR:
localList.append(<unsigned char> pvd[i].getAsChar())
elif dtcheck==CAFE_LONG:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_DOUBLE:
localList.append(pvd[i].getAsDouble())
else:
localList.append(0) #no data
else:
localListInner=[]
if dtcheck==CAFE_STRING:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsString(j))
elif dtcheck==CAFE_SHORT:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_FLOAT:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsDouble(j))
elif dtcheck==CAFE_ENUM:
for j in range(0, pvd[i].getNelem()):
#if enum, string taken as native
if self._c_cafe.isEnum(self.hh.getHandleFromPVWithinGroup(pvd[i].getPVName(),ghandle))==1:
localListInner.append(pvd[i].getAsString(j))
else:
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_CHAR:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j)) #<unsigned char> pvd[i].getAsChar(j))
elif dtcheck==CAFE_LONG:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_DOUBLE:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsDouble(j))
else:
for j in range(0, pvd[i].getNelem()):
localListInner.append(0) #no data
localList.append(localListInner)
return localList, status, statusList
##################################################################################
#END: def getGroup(self, ghandleName, dt='native'):
##################################################################################
##################################################################################
def getGroupCache(self, ghandleName, str dt='native'):
cdef str _METHOD_="getGroupCache(self, ghandleName, str dt='native')"
cdef unsigned int ghandle=0
if isinstance(ghandleName, (int,long)) == 1:
ghandle=ghandleName
elif isinstance(ghandleName, (str)) == 1:
ghandle=self.checkForGroupHandle(ghandleName)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if group handle, else <type 'str'> if group name")
raise Exception(_cyCafeException)
cdef PVGroup pvg
with nogil:
self._c_cafe.groupAttach(ghandle, pvg)
cdef PVDataHolder * pvd
with nogil:
status=self._c_cafe.groupGetCache(ghandle, pvg)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
#do not raise exception
#raise Exception("EXCEPTION RAISED in PyCafe def getGroup. Status = %d" %status)
pvd=pvg.getPVData()
localList=[]
statusList=[]
cdef unsigned int dtn, dtcheck
for i in range(0, pvg.getNPV()):
dtn = pvd[i].getDataType();
dtcheck=getMatchedDataType(dt, dtn)
statusList.append(pvd[i].getStatus())
if pvd[i].getNelem() == 1:
if dtcheck==CAFE_STRING:
localList.append(pvd[i].getAsString())
elif dtcheck==CAFE_SHORT:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_FLOAT:
localList.append(pvd[i].getAsDouble())
elif dtcheck==CAFE_ENUM:
#if enum, string taken as native
if self._c_cafe.isEnum(self.hh.getHandleFromPVWithinGroup(pvd[i].getPVName(),ghandle))==1:
localList.append(pvd[i].getAsString())
else:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_CHAR:
localList.append(<unsigned char> pvd[i].getAsChar())
elif dtcheck==CAFE_LONG:
localList.append(pvd[i].getAsLong())
elif dtcheck==CAFE_DOUBLE:
localList.append(pvd[i].getAsDouble())
else:
localList.append(0) #no data
else:
localListInner=[]
if dtcheck==CAFE_STRING:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsString(j))
elif dtcheck==CAFE_SHORT:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_FLOAT:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsDouble(j))
elif dtcheck==CAFE_ENUM:
for j in range(0, pvd[i].getNelem()):
#if enum, string taken as native
if self._c_cafe.isEnum(self.hh.getHandleFromPVWithinGroup(pvd[i].getPVName(),ghandle))==1:
localListInner.append(pvd[i].getAsString(j))
else:
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_CHAR:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j)) #<unsigned char> pvd[i].getAsChar(j))
elif dtcheck==CAFE_LONG:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsLong(j))
elif dtcheck==CAFE_DOUBLE:
for j in range(0, pvd[i].getNelem()):
localListInner.append(pvd[i].getAsDouble(j))
else:
for j in range(0, pvd[i].getNelem()):
localListInner.append(0) #no data
localList.append(localListInner)
return localList, status, statusList
##################################################################################
#END: def getGroup(self, ghandleName, dt='native'):
##################################################################################
##################################################################################
def getPVGroupStr(self, ghandleName):
return self.getPVGroup(ghandleName, dt='str')
def getPVGroupInt(self, ghandleName):
return self.getPVGroup(ghandleName, dt='int')
def getPVGroupFloat(self, ghandleName):
return self.getPVGroup(ghandleName, dt='float')
##################################################################################
def getPVGroup(self, ghandleName, str dt='native'):
cdef str _METHOD_="getPVGroup(ghandleName, str dt='native')"
cdef unsigned int ghandle=0
if isinstance(ghandleName, (int,long)) == 1:
ghandle=ghandleName
elif isinstance(ghandleName, (str)) == 1:
ghandle=self.checkForGroupHandle(ghandleName)
#elif isinstance(ghandleName, (pvgroup)) == 1:
# print ("We have a PV Group ", type(ghandleName) )
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if group handle, else <type 'str'> if group name")
raise Exception(_cyCafeException)
cdef PVGroup pvg
cdef PVDataHolder * pvd
cdef int status
with nogil:
self._c_cafe.groupAttach(ghandle, pvg)
pvd=pvg.getPVData()
'''
for i in range (0, pvg.getNPV()):
pvd[i].setHasAlarm(True)
pvd[i].setHasTS(True)
#pvd[i].setRule(True)
pvg.setPVData(pvd)
'''
with nogil:
status=self._c_cafe.groupGet(ghandle, pvg)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
print("Error in PyCafe def getPVGroup. Status = %d" %status)
self._c_cafe.printStatusMessage(status)
#do not raise exception
#raise Exception("EXCEPTION RAISED in PyCafe def getPVGroup. Status = %d" %status)
if status == ECA_TIMEOUT:
print ("======================================================")
print ("TIMEOUT in getGroup; swithing to getCompoundPVGroup")
print ("======================================================")
return self.getCompoundPVGroup(ghandle,dt)
pvd=pvg.getPVData()
localList=[]
for i in range(0, pvg.getNPV()):
#print(pvd[i].getAsString(0), " " , pvd[i].getStatus())
#print(pvd[i].getEpicsTimeStampAsUInt32().secPastEpoch, " ", pvd[i].getEpicsTimeStampAsUInt32().nsec)
localList.append(PVDataHolderToStruct(pvd[i], dt))
cpdef pvgroup pg
pg = pvgroup()
pg.pvdata=localList
pg.npv=pvg.getNPV()
pg.name=pvg.getNameAsString()
pg.groupStatus=pvg.getStatusGroup()
pg.groupHandle=pvg.getGroupHandle()
#pg.showMax(1)
return pg #localList, status
##################################################################################
#END: def getPVGroup(self, ghandleName, str dt='native')
##################################################################################
##################################################################################
def getPVGroupCache(self, ghandleName, str dt='native'):
cdef str _METHOD_="getPVGroupCache"
cdef unsigned int ghandle=0
if isinstance(ghandleName, (int,long)) == 1:
ghandle=ghandleName
elif isinstance(ghandleName, (str)) == 1:
ghandle=self.checkForGroupHandle(ghandleName)
#elif isinstance(ghandleName, (pvgroup)) == 1:
# print ("We have a PV Group ", type(ghandleName) )
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if group handle, else <type 'str'> if group name")
raise Exception(_cyCafeException)
cdef PVGroup pvg
cdef PVDataHolder * pvd
cdef int status
with nogil:
self._c_cafe.groupAttach(ghandle, pvg)
print ("==============" )
print (_METHOD_)
pvg.showMax(1)
pvd=pvg.getPVData()
status=self._c_cafe.groupGetCache(ghandle, pvg)
pvg.showMax(1)
print ("==============" )
print(status, pvg.getStatusGroup() )
print ("==============" )
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
print("Error in PyCafe def getPVGroupCache. Status = %d" %status)
self._c_cafe.printStatusMessage(status)
#do not raise exception
#raise Exception("EXCEPTION RAISED in PyCafe def getPVGroup. Status = %d" %status)
pvd=pvg.getPVData()
localList=[]
for i in range(0, pvg.getNPV()):
#print(pvd[i].getAsString(0), " " , pvd[i].getStatus())
#print(pvd[i].getEpicsTimeStampAsUInt32().secPastEpoch, " ", pvd[i].getEpicsTimeStampAsUInt32().nsec)
localList.append(PVDataHolderToStruct(pvd[i], dt))
cpdef pvgroup pg
pg = pvgroup()
pg.pvdata=localList
pg.npv=pvg.getNPV()
pg.name=pvg.getNameAsString()
pg.groupStatus= pvg.getStatusGroup()
pg.groupHandle=pvg.getGroupHandle()
return pg
##################################################################################
#END: def getPVGroup(self, ghandleName, str dt='native')
##################################################################################
##################################################################################
def PVGroupValuesToList(self, pvgroup pg):
glist=[]
for i in range(0,pg.npv):
if len(pg.pvdata[i].value)==1:
glist.append(pg.pvdata[i].value[0])
else:
iL=[]
for j in range(0, len(pg.pvdata[i].value)):
iL.append(pg.pvdata[i].value[j])
glist.append(iL)
return glist
##################################################################################
##################################################################################
def groupMemberList(self, str gname):
cdef str _METHOD_="groupMemberList(self, str gname)"
cdef vector[string] pvlist
status=self._c_cafe.groupMemberList(gname, pvlist)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
#for i in range(0, len(pvlist)):
# memberList.append(pvlist[i])
return pvlist
##################################################################################
def grouping(self, char * gname, list _pvlist):
cdef str _METHOD_="grouping(char * gname, list _pvlist)"
cdef int status
status=self._c_cafe.groupDefine(gname, _pvlist)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
cdef unsigned int ghandle=0
cdef char * _gname=gname
#try:
# self._c_cafe.groupOpen(_gname, ghandle)
#except:
# raise Exception("EXCEPTION RAISED in PyCafe def grouping. ERROR OPENING PVGROUP= %s" %_gname)
try:
status=self._c_cafe.groupOpen(_gname, ghandle)
except:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=ghandle, _pv=_gname, \
_ec=ECA_ALLOCMEM, _et=self.cs.code(ECA_ALLOCMEM), _ei=self.cs.info(ECA_ALLOCMEM))
raise Exception(_cyCafeException)
if status != ICAFE_NORMAL:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=ghandle, _pv=_gname, \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
#cdef PVGroup pvg
#self._c_cafe.groupAttach(ghandle, pvg);
cdef:
list localList
list statusList
if self._c_cafe.channelOpenGroupPolicy.getWhenToFlushSendBuffer()==FLUSH_NOW:
localList,status,statusList= self.getGroup(ghandle)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
print ("")
print ("Error in def grouping for group named", _gname)
self._c_cafe.printStatusMessage(status)
print ("Analysing statusList[]...")
for i in range(0, len(statusList)):
if statusList[i] !=ICAFE_NORMAL:
print ("PV", _pvlist[i], "[",i,"]", " has error: ")
self._c_cafe.printStatusMessage(statusList[i])
print ("")
return ghandle
##################################################################################
def defineGroup(self, char * gname, list _pvlist):
#cdef vector[const char *] pvlist
#for i in range(0, len(_pvlist)):
# pvlist.push_back(_pvlist[i])
status=self._c_cafe.groupDefine(gname, _pvlist)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
return status
##################################################################################
##################################################################################
def groupOpen(self, char * gname):
cdef str _METHOD_="groupOpen(char * gname)"
if isinstance(gname, (str)) == 0:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument should be <type 'str'> for group name")
raise Exception(_cyCafeException)
cdef unsigned int ghandle=0
cdef char * _gname=gname
try:
status=self._c_cafe.groupOpen(_gname, ghandle)
except:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=ghandle, _pv=_gname, \
_ec=ECA_ALLOCMEM, _et=self.cs.code(ECA_ALLOCMEM), _ei=self.cs.info(ECA_ALLOCMEM))
raise Exception(_cyCafeException)
if status != ICAFE_NORMAL:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=ghandle, _pv=_gname, \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return ghandle
##################################################################################
##################################################################################
def groupClose(self, gHandleName):
cdef str _METHOD_="groupClose(gHandleName)"
cdef unsigned int gHandle=0
cdef str _gname=None
status=ICAFE_NORMAL
if isinstance(gHandleName, (int,long)):
gHandle=gHandleName
elif isinstance(gHandleName, (str)):
_gname=gHandleName
gHandle=self.checkForGroupHandle(gHandleName)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if group handle, else <type 'str'> if group name")
raise Exception(_cyCafeException)
if gHandle == 0:
status=ECAFE_INVALID_GROUP_HANDLE
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=gHandle, _pv=_gname, \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
status=self._c_cafe.groupClose(gHandle)
if status != ICAFE_NORMAL:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=gHandle, _pv=_gname, \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return status
##################################################################################
def getNoMonitors(self, handlePV):
cdef str _METHOD_="getNoMonitors(handlePV)"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
return self.hh.getNmonitor(handle)
##################################################################################
##################################################################################
def getMonitorIDs(self, handlePV):
cdef str _METHOD_="getMonitorIDs(handlePV)"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
return self.hh.getMonitorIDs(handle);
##################################################################################
##########################################################################################
def monitorStart(self, handlePV, object cb=None, DBR_TYPE dbr=DBR_TIME, unsigned int mask=DBE_VALUE|DBE_LOG|DBE_ALARM):
cdef str _METHOD_="monitorStart(handlePV, object cb=None, DBR_TYPE dbr=DBR_TIME, unsigned int mask=DBE_VALUE|DBE_LOG|DBE_ALARM)"
pv=None
cdef int status=ICAFE_NORMAL
#cdef pCallback my_callback
#my_callback=<pCallback>callbackHandlerMonitor
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
pv=handlePV
handle=self.checkForHandle(handlePV)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
#py_cb_handle phase out; us fn in dictionary!
#global py_cb_handle
global py_cb
#if cb:
# py_cb=cb
#Does channel Exist?
if self._c_cafe.isValid(handle) == 0:
status=ECAFE_INVALID_HANDLE
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=pv, \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return status;
cdef MonitorPolicy mp
cdef unsigned int mpid=mp.getMonitorID()
mp.setMask(mask)
#print ("dbr=", dbr)
self._c_cafe.getChannelInfo(handle,self.channelInfo)
#print ("nativeDataType=", self.channelInfo.getDataType())
if dbr in [DBR_PLAIN, DBR_STS, DBR_TIME, DBR_GR, DBR_CTRL]:
#set Native Datatype first
mp.setDataType(self.channelInfo.getDataType());
mp.setCafeDbrType(dbr)
#print ("def monitorStart ", mp.getCafeDbrType())
#print ("def monitorStart ", mp.getDbrDataType())
else:
print ("***Warning*** from monitorStart for handle=",handlePV)
print ("dbr base type should be one of DBR_PLAIN, DBR_STS, DBR_TIME, DBR_GR, DBR_CTRL")
print ("Assuming DBR_TIME")
mp.setDataType(self.channelInfo.getDataType());
mp.setCafeDbrType(DBR_TIME)
#if cb:
#
# print "py_cb_handle", len(a[0])
global monDictGlobal
#print ("MONITOR START (self, handlePV, object cb=None, DBR_TYPE dbr=DBR_TIME, unsigned int mask) ")
#print (monDictGlobal)
if cb:
a=inspect.getargspec(cb)
#print (a)
if(len(a[0])==1):
##py_cb_handle=cb
#self.monidList.append(mpid)
#self.moncbList.append(cb)
##self.monDict[mpid]=cb
monDictGlobal[mpid]=cb
#print (monDictGlobal)
#print self.monidList
#print self.moncbList
#print self.monDict
#
#print "mpid = ", mpid
mp.setUserArgs(<void *> mpid)
mp.setPyHandler()
#print (<long>mp.getUserArgs())
else:
py_cb=cb
mp.setPyHandlerData()
#else:
# mp.setHandler(callbackHandlerMonitor_wrapper)
with nogil:
status=self._c_cafe.monitorStart(handle,mp)
#Need this to allow a fraction of a second for the callback fn to be called
#if setPyHandler is used
if (self.getMonitorWhenToFlushSendBuffer == FLUSH_NOW):
time.sleep(0.01);
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
#do not raise an exception
#raise Exception("EXCEPTION RAISED in PyCafe def monitorStart. Status = %d" %status)
return mpid
##################################################################################
##################################################################################
def monitorStop(self, handlePV, mpid=None):
cdef str _METHOD_="monitorStop(handlePV, mpid=None)"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)) == 1:
handle=handlePV
elif isinstance(handlePV, (str)) == 1:
handle=self.checkForHandle(handlePV)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
cdef int status
cdef unsigned int mpidUI
global monDictGlobal
if mpid:
if isinstance(mpid, (int,long)):
mpidUI=mpid
with nogil:
status=self._c_cafe.monitorStopWithID(handle, mpidUI)
time.sleep(0.01)
if (status==ICAFE_NORMAL):
#index=self.monidList.index(mpidUI)
#self.monidList.remove(mpidUI)
#self.moncbList.remove(self.moncbList[index])
#del self.monDict[mpidUI]
#print (monDictGlobal)
#DELETE ENTRY ONLY IF IT EXISTS!
if monDictGlobal.has_key(mpidUI):
del monDictGlobal[mpidUI]
else:
raise Exception ("EXCEPTION RAISED IN PyCafe def monitorStop. \n\
monitorPolicy ID (mpid) should be <type 'int'>")
else:
with nogil:
status=self._c_cafe.monitorStop(handle)
time.sleep(0.01)
if (status==ICAFE_NORMAL):
#print "size", self.hh.getNmonitor(handle)
mpidUIV=self.hh.getMonitorIDs(handle)
#print "size", mpidUIV.size()
for i in range(0, mpidUIV.size()):
#index=self.monidList.index(mpidUIV[i])
#self.monidList.remove(mpidUIV[i])
#self.moncbList.remove(self.moncbList[index])
#del self.monDict[mpidUIV[i]]
if monDictGlobal.has_key(mpidUIV[i]):
del monDictGlobal[mpidUIV[i]]
#monDictGlobal.remove(mpidUIV[i])
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
#do not raise an exception
#raise Exception("EXCEPTION RAISED in PyCafe def monitorStop. Status = %d" %status)
return status
##################################################################################
##################################################################################
def monitorStopAll(self):
cdef str _METHOD_="monitorStopAll()"
global monDictGlobal
cdef int status
with nogil:
status=self._c_cafe.monitorStopAll()
#give plenty of time for monitors to stop!
#print ("-----------------------------------------------------------------")
#print self.monidList
#print self.moncbList
#print self.monDict
#print (monDictGlobal)
#print ("------------------------------------------------------------------")
#del self.monidList[:]
#del self.moncbList[:]
#self.monDict.clear()
time.sleep(0.5)
monDictGlobal.clear()
#print self.monDict
#print monDictGlobal
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
raise Exception("EXCEPTION RAISED in PyCafe def monitorStopAll. Status = %d" %status)
return status
##################################################################################
##################################################################################
def set(self, handlePV, valSet):
cdef str _METHOD_="set(handlePV, valSet)"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)):
handle=handlePV
elif isinstance(handlePV, (str)):
handle=self.checkForHandle(handlePV)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
#CHECK FOR ALL DATA TYPES!
cdef unsigned short valType=CAFE_STRING
cdef int status=ICAFE_NORMAL
cdef float valSetF
cdef double valSetD
cdef int valSetI
cdef long long valSetLL
cdef short valSetShort
cdef unsigned short valSetUShort
cdef unsigned char valSetChar
cdef string valSetS
cdef vector[double] vecD
cdef vector[float] vecF
cdef vector[short] vecShort
cdef vector[unsigned short] vecUShort
cdef vector[dbr_char_t] vecChar
cdef vector[dbr_long_t] vecI
cdef vector[string] vecS
cdef unsigned int nLA=0
cdef tuple ctypesString = (ctypes.c_wchar, ctypes.c_char_p, ctypes.c_wchar_p)
cdef tuple ctypesUChar = (ctypes.c_char, ctypes.c_ubyte, ctypes.c_bool, ctypes.c_uint8, )
cdef tuple ctypesShort = (ctypes.c_int16, ctypes.c_int8, ctypes.c_short, ctypes.c_byte)
cdef tuple ctypesUShort = (ctypes.c_uint16,ctypes.c_ushort)
cdef tuple ctypesInt = (ctypes.c_int, ctypes.c_int32, \
ctypes.c_long, ctypes.c_size_t)
cdef tuple ctypesLongLong=(ctypes.c_uint, ctypes.c_uint32, ctypes.c_int64, ctypes.c_uint64, \
ctypes.c_ulong,ctypes.c_ulonglong, ctypes.c_longdouble, \
ctypes.c_longlong, ctypes.c_ssize_t, \
ctypes.c_void_p, ctypes.c_voidp)
# ctypes.c_char, ctypes.c_float, ctypes.c_double are separate
cdef tuple dtypesString = (np.str_, np.unicode_)
cdef tuple dtypesUChar = (np.ubyte, np.bool8, np.bool_, np.uint8)
cdef tuple dtypesShort = (np.byte, np.short, np.int8, np.int16)
cdef tuple dtypesUShort = (np.uint16,np.ushort)
cdef tuple dtypesInt = (np.int_, np.intc, np.int32, np.uintp)
cdef tuple dtypesLongLong= (np.uint, np.uintc, np.uint32, np.int64, np.uint64, \
np.ulonglong, np.longlong, np.intp, np.uintp)
cdef tuple dtypesFloat = (np.single, np.float16, np.float32)
cdef tuple dtypesDouble = (np.double, np.float_, np.float64)
#List: Major[0] Minor[1] Patch[2] 'final'[3] 0 [4]
#print "type= // ", type(valSet)
cdef bint isGoodType=False
cdef bint isBytesType=False
# print('set method', type(valSet))
# print("is instance array.array", isinstance(valSet, array.array))
# print("is instance np.ndarray", isinstance(valSet, np.ndarray))
# print("is instance memoryview", isinstance(valSet, memoryview))
# print("is instance ctypes float", isinstance(valSet, ctypes.c_float))
# print("is instance ctypes long ", isinstance(valSet, ctypes.c_long ))
# print("is instance ctypes int ", isinstance(valSet, ctypes.c_int ))
# print("is instance int ", isinstance(valSet, int ))
# print("is instance ctypes char_p ", isinstance(valSet, ctypes.c_char_p ))
# print("is instance ctypes Array ", isinstance(valSet, ctypes.Array ))
# print("is instance bytes ", isinstance(valSet, bytes ))
# print("is instance bytearrays ", isinstance(valSet, bytearray ))
# ctypes.c_buffer is of class function
# crtpes.c_buffer(b'abc') is of rtype ctypes.Array (!))
#print("is instance ctypes buffer ", isinstance(valSet, ctypes.c_buffer )) # no such type!
# dir(ctypes)
# print(type(valSet))
# print (valSet.__class__)
cdef str classType = (valSet.__class__).__name__
cdef str substringmv = "_memoryviewslice"
#print ("python Version", self.pythonVersion[0])
#Cython does not know about PyCafe._memoryviewslice
#if (isinstance(valSet,PyCafe._memoryviewslice)):
# print('OK for memoryview')
if ( (self.pythonVersion[0] > 2 ) or (self.pythonVersion[0] == 2 and self.pythonVersion[1]>6) ) :
if isinstance(valSet,(list, array.array, np.ndarray, cython.view.memoryview, memoryview, ctypes.Array)):
isGoodType=True
else:
if isinstance(valSet,(list, array.array, np.ndarray, ctypes.Array)):
isGoodType=True
if (isGoodType==False):
if (substringmv in classType):
isGoodType=True
#This is to cater for ctypes.c_buffer which is an instance of ctypes.Array
#where the element of the array is of type bytes - there need to match to cafe.setString
if isinstance(valSet,ctypes.Array):
if isinstance(valSet[0],bytes):
isGoodType=False
isBytesType=True
#where the element of the array is of type bytes - there need to match to cafe.setSrting
#if isinstance(valSet,np.ndarray):
#print ("np.ndarray is true")
#print (type(valSet[0]))
#if isinstance(valSet[0],bytes):
#isGoodType=False
#isBytesType=True
#print("isGoodType ", isGoodType)
#print("isBytesType ", isBytesType)
if isGoodType:
#print('set method', type(valSet[0]))
nLA=len(valSet)
#Just check on first element if array.array etc..
if not isinstance(valSet, (list)):
#if isinstance(valSet, (array.array, np.ndarray, cython.view.memoryview, memoryview)):
nLA=1
for i in range(0, nLA):
if isinstance(valSet[i],(str, bytes)):
valType=CAFE_STRING
break
elif isinstance(valSet[i],dtypesString):
valType=CAFE_STRING
break
elif isinstance(valSet[i],(float)):
valType=CAFE_DOUBLE
elif isinstance(valSet[i],(dtypesDouble)):
valType=CAFE_DOUBLE
elif isinstance(valSet[i],(dtypesFloat)):
valType=CAFE_FLOAT
elif isinstance(valSet[i],(long, int)):
valType=CAFE_LONG
elif isinstance(valSet[i], dtypesInt+dtypesLongLong+dtypesUChar):
valType=CAFE_LONG
elif isinstance(valSet[i], dtypesShort):
valType=CAFE_SHORT
elif isinstance(valSet[i], dtypesUShort):
valType=CAFE_USHORT
else:
print("PyCafe.pyx: We do not cater for type ", type(valSet[i]), " and thus assume a string" )
valType=CAFE_STRING
break
# valSet to vector since
# coercion from Python not allowed without the GIL
if valType==CAFE_DOUBLE:
vecD.reserve(len(valSet))
for i in range(0, len(valSet)):
vecD.push_back(valSet[i])
with nogil:
status=self._c_cafe.setVDouble(handle, vecD)
elif valType==CAFE_FLOAT:
vecF.reserve(len(valSet))
for i in range(0, len(valSet)):
vecF.push_back(valSet[i])
with nogil:
status=self._c_cafe.setVFloat(handle, vecF)
elif valType==CAFE_LONG:
vecI.reserve(len(valSet))
for i in range(0, len(valSet)):
vecI.push_back(valSet[i])
with nogil:
status=self._c_cafe.setVLong(handle, vecI)
elif valType==CAFE_SHORT:
vecShort.reserve(len(valSet))
for i in range(0, len(valSet)):
vecShort.push_back(valSet[i])
with nogil:
status=self._c_cafe.setVShort(handle, vecShort)
elif valType==CAFE_USHORT:
vecUShort.reserve(len(valSet))
for i in range(0, len(valSet)):
vecUShort.push_back(valSet[i])
with nogil:
status=self._c_cafe.setVUShort(handle, vecUShort)
elif valType==CAFE_CHAR:
vecChar.reserve(len(valSet))
for i in range(0, len(valSet)):
vecChar.push_back(valSet[i])
with nogil:
status=self._c_cafe.setVChar(handle, vecChar)
elif valType==CAFE_STRING:
vecS.reserve(len(valSet))
for i in range(0, len(valSet)):
vecS.push_back(str(valSet[i]))
with nogil:
status=self._c_cafe.setVString(handle, vecS)
elif isBytesType:
#print("isBytesType")
valSetS=<string>valSet.value
with nogil:
status=self._c_cafe.setString(handle, valSetS)
elif isinstance(valSet, (ctypes.c_char)):
#print("is ctypes.c_char")
#print(valSet.value)
#print(valSet.value.decode())
valSetS=valSet.value.decode()
with nogil:
status=self._c_cafe.setString(handle, valSetS)
elif isinstance(valSet, (ctypes.c_float)):
valSetF=<float>valSet.value
with nogil:
status=self._c_cafe.setFloat(handle, valSetF)
elif isinstance(valSet, (ctypes.c_double)):
valSetD=<double>valSet.value
with nogil:
status=self._c_cafe.setDouble(handle, valSetD)
elif isinstance(valSet, ctypesInt):
#print("ctypesInt")
valSetI= <int>valSet.value
with nogil:
status=self._c_cafe.setLong(handle, valSetI)
elif isinstance(valSet, ctypesLongLong):
#print("ctypesLongLong")
valSetLL=<long long>valSet.value
with nogil:
status=self._c_cafe.setLong(handle, valSetLL)
elif isinstance(valSet, ctypesShort):
#print("ctypesShort")
valSetShort=<short>valSet.value
with nogil:
status=self._c_cafe.setShort(handle, valSetShort)
elif isinstance(valSet, ctypesUShort):
#print("ctypesUShort")
valSetUShort=<unsigned short>valSet.value
with nogil:
status=self._c_cafe.setUShort(handle, valSetUShort)
elif isinstance(valSet, (ctypesString) ):
#print("ctypesString")
valSetS=<string>valSet.value
with nogil:
status=self._c_cafe.setString(handle, valSetS)
elif isinstance(valSet, ctypesUChar):
#print("ctypesUChar")
valSetUChar=<unsigned char>valSet.value
with nogil:
status=self._c_cafe.setChar(handle, valSetUChar)
elif isinstance(valSet, (float)):
#print("float type")
valSetD= <float>valSet
with nogil:
status=self._c_cafe.setDouble(handle, valSetD)
elif isinstance(valSet, (int, long)):
#print("int/long type")
valSetI= <int>valSet
with nogil:
status=self._c_cafe.setLong(handle, valSetI)
elif isinstance(valSet, (str)):
# print("str type")
valSetS=valSet
with nogil:
status=self._c_cafe.setString(handle, valSetS)
elif isinstance(valSet, (bytes,bytearray)):
#print("bytes,bytearray")
valSetS=valSet.decode('utf8')
with nogil:
status=self._c_cafe.setString(handle, valSetS)
elif isinstance(valSet, (unicode)):
#print("unicode")
valSetS=valSet
with nogil:
status=self._c_cafe.setString(handle, valSetS)
else:
print("PyCafe def set WARNING: DATA TYPE NOT SUPPORTED")
print("Input data (whether within a 'list','array.array','cython.view.memoryview','memoryview' \n\
or not) should be of <type 'int'>, <type 'float'> or <type 'str'>")
type(valSet)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
if handle == 0:
self._c_cafe.printStatusMessage(status)
else:
self._c_cafe.printStatus(handle, status)
if self.haveExceptions:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_,_handle=handle, _pv=self._c_cafe.getPVFromHandle(handle), \
_ec=status, _et=self.cs.code(status), _ei=self.cs.info(status))
raise Exception(_cyCafeException)
return status
##################################################################################
#END def set(self, handlePV, valSet):
##################################################################################
##################################################################################
def setScalarList(self, handleList, list valList):
cdef str _METHOD_="setScalarList(handleList, list valList)"
if not isinstance(handleList, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setScalarList. \n\
First input argument, should be <type 'list'> of handles or PVs")
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList)
elif not isinstance(handleList[0], (int, long)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setScalarList. \n\
First input argument, should be a 'list' of <type 'int'> if handles or <type 'str'> if PVs")
if len(handleList) != len(valList):
raise Exception ("EXCEPTION RAISED IN PyCafe def setScalarList. \
Length of handle list ", len(handleList), " does not match the length of data list ", len(valList))
nelemPrevious = []
#Better with PVDataHolder
cdef unsigned int nelemTotal=0
for i in range(0, len(handleList)):
#nelemTotal+=self.hh.getNelemNative(handleList[i])
nelemPrevious.append(self.hh.getNelemClient(handleList[i]))
#cdef int size_cdu = sizeof(CAFE_DATATYPE_UNION)
#do this to avoid compiler warning messages
cdef vector[unsigned int] v
for i in range(0, len(handleList)):
v.push_back(handleList[i])
#Create temporary group from handleList
#Does group exist?
cdef PVDataHolder * pvd = self._c_cafe.getPVData(v)
#cdef PVDataHolder * pvd = <PVDataHolder *>malloc( 100000000 + \
# len(handleList) * sizeof(PVDataHolder) + nelemTotal*size_cdu)
for i in range(0, len(handleList)):
#pvd[i].val =<shared_ptr[CAFE_DATATYPE_UNION[]]>malloc(sizeof(CAFE_DATATYPE_UNION))
#pvd[i]= PVDataHolder(1);
pvd[i].setNelem(1)
cdef unsigned short valType=CAFE_STRING
for i in range(0, len(handleList)):
if isinstance(valList[i],(str)):
pvd[i].setString(valList[i])
elif isinstance(valList[i],(float)):
pvd[i].setDouble(valList[i])
elif isinstance(valList[i],(long, int)):
pvd[i].setInt(valList[i])
else:
print ("This line in PyCafe def setScalarList should never appear!")
cdef int status=ICAFE_NORMAL
with nogil:
status=self._c_cafe.setPVArray(v, pvd)
for i in range(0, len(handleList)):
if (nelemPrevious[i] != 1):
self._c_cafe.setNelemToPrevious(handleList[i],nelemPrevious[i])
#return status for individual channels
statusList=[]
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
for i in range(0, len(handleList)):
if (pvd[i].getStatus() != ICAFE_NORMAL):
print ("Handle=", handleList[i], "PV=", self.hh.getPVFromHandle(handleList[i]) )
print ("with error status=", pvd[i].getStatus())
self._c_cafe.printStatusMessage(pvd[i].getStatus())
print ("")
statusList.append(pvd[i].getStatus())
#free(pvd)
return status, statusList
##################################################################################
##################################################################################
def setCompoundList(self, handleList, list vectorList):
cdef str _METHOD_="setCompoundList(handleList, list vectorList)"
if isinstance(handleList, (str)):
handleList=self.getHandlesFromWithinGroup(handleList)
else:
if not isinstance(handleList, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setCompoundList. \n\
First input argument, should be <type 'list'> of handles or PVs")
if isinstance(handleList[0], (str)):
handleList=self.checkForHandleList(handleList)
elif not isinstance(handleList[0], (int, long)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setCompoundList. \n\
First input argument, should be a 'list' of <type 'int'> if handles or <type 'str'> if PVs")
if len(handleList) != len(vectorList):
raise Exception ("EXCEPTION RAISED IN PyCafe def setCompoundList. \
Length of handle list ", len(handleList), " does not match the length of data list ", len(vectorList))
#do this to avoid compiler warning messages
cdef vector[unsigned int] v
cdef int i
for i in range(0, len(handleList)):
v.push_back(handleList[i])
#Create temporary group from handleList
#Does group exist?
cdef PVDataHolder * pvdata = self._c_cafe.getPVData(v)
for i in range(0, len(vectorList)):
#if not list
if isinstance(vectorList[i],(str)):
pvdata[i].setString(vectorList[i])
elif isinstance(vectorList[i],(float)):
pvdata[i].setDouble(vectorList[i])
elif isinstance(vectorList[i],(long, int)):
pvdata[i].setInt(vectorList[i])
elif isinstance(vectorList[i], (list)):
#if list
valType=CAFE_INVALID_DATATYPE
pvdata[i].setNelem(len(vectorList[i]))
#for k in range(0, len(vectorList[i])):
#Just check on first element
for k in range(0,1): # can expand this to all elemnts or reduce to 1
if isinstance(vectorList[i][k],(str)):
valType=CAFE_STRING
break
elif isinstance(vectorList[i][k],(float)):
valType=CAFE_DOUBLE
elif isinstance(vectorList[i][k],(long, int)):
if valType != CAFE_DOUBLE:
valType=CAFE_LONG
else:
valType=CAFE_STRING
break
#check dt of first element
if valType==CAFE_DOUBLE:
pvdata[i].setVDouble(vectorList[i])
elif valType==CAFE_LONG:
pvdata[i].setVInt (vectorList[i])
elif valType==CAFE_STRING:
pvdata[i].setVString(vectorList[i])
else:
print ("This line in PyCafe def setCompoundList should never appear!")
raise Exception ("EXCEPTION RAISED IN PyCafe def setCompoundList. \n\
Unknown data input; should be one of <type 'int'> , <type 'str'>, <type 'float'> , <type 'list'>")
#endForLoop
cdef int status=ICAFE_NORMAL
with nogil:
status=self._c_cafe.setPVArray(v, pvdata)
#return status for individual channels
statusList=[]
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
for i in range(0, len(handleList)):
if (pvdata[i].getStatus() != ICAFE_NORMAL):
print ("Handle=", handleList[i], "PV=", self.hh.getPVFromHandle(handleList[i]) )
print ("with error status=", pvdata[i].getStatus())
self._c_cafe.printStatusMessage(pvdata[i].getStatus())
print ("")
#raise Exception("EXCEPTION RAISED in PyCafe def setCompoundList. Status = %d" %status)
statusList.append(pvdata[i].getStatus())
return status, statusList
##################################################################################
##################################################################################
def setGroup(self, ghandleName, list vectorList):
cdef str _METHOD_="setGroup(self, ghandleName, list vectorList)"
cdef unsigned int ghandle=0
if isinstance(ghandleName, (int,long)) == 1:
ghandle=ghandleName
elif isinstance(ghandleName, (str)) == 1:
ghandle=self.checkForGroupHandle(ghandleName)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument should be <type 'int'> if group handle, else <type 'str'> if group name")
raise Exception(_cyCafeException)
cdef PVGroup pvg
with nogil:
self._c_cafe.groupAttach(ghandle, pvg)
###
#print ("len V", len(vectorList), " npv=", pvg.getNPV())
cdef PVDataHolder * pvdata = pvg.getPVData();
for i in range(0, len(vectorList)):
#if not list
if isinstance(vectorList[i],(str)):
pvdata[i].setString(vectorList[i])
elif isinstance(vectorList[i],(float)):
pvdata[i].setDouble(vectorList[i])
elif isinstance(vectorList[i],(long, int)):
pvdata[i].setInt(vectorList[i])
elif isinstance(vectorList[i], (list)):
#if list
valType=CAFE_INVALID_DATATYPE
pvdata[i].setNelem(len(vectorList[i]))
#for k in range(0, len(vectorList[i])):
#Just check on first element
for k in range(0,1): # can expand this to all elemnts or reduce to 1
if isinstance(vectorList[i][k],(str)):
valType=CAFE_STRING
break
elif isinstance(vectorList[i][k],(float)):
valType=CAFE_DOUBLE
elif isinstance(vectorList[i][k],(long, int)):
if valType != CAFE_DOUBLE:
valType=CAFE_LONG
else:
valType=CAFE_STRING
break
#check dt of first element
if valType==CAFE_DOUBLE:
pvdata[i].setVDouble(vectorList[i])
elif valType==CAFE_LONG:
pvdata[i].setVInt (vectorList[i])
elif valType==CAFE_STRING:
pvdata[i].setVString(vectorList[i])
else:
print ("PyCafe def setGroup: Unusual data type for element", i, " : ", type(vectorList[i]))
raise Exception ("EXCEPTION RAISED IN PyCafe def setGroup. \n\
Unknown data input; should be one of <type 'int'> , <type 'str'>, <type 'float'> , <type 'list'>")
#endForLoop
cdef int status=ICAFE_NORMAL
statusList=[]
pvg.setPVData(pvdata)
with nogil:
status=self._c_cafe.groupSet(ghandle, pvg)
cdef PVDataHolder * pvd
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
#do not raise exception
#raise Exception("EXCEPTION RAISED in PyCafe def setGroup. Status = %d" %status)
pvd=pvg.getPVData()
for i in range(0, pvg.getNPV()):
statusList.append(pvd[i].getStatus())
else:
statusList.append(status)
return status, statusList
##################################################################################
#END: def setGroup(self, ghandleName, dt='native')
##################################################################################
##################################################################################
def gameSetAndMatch(self, list handlePVSet, list valSet, handlePVAction, valAction, list handlePVMatch, double tolerance, double timeout, bint printFlag):
cdef str _METHOD_="setAndMatchMany(list handlePVSet, list valSet, list handlePVMatch, double tolerance, double timeout, bint printFlag)"
if not isinstance(handlePVSet, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setAndMatchMany. \n\
First input argument, should be <type 'list'> of handles or PVs")
if not isinstance(valSet, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setAndMatchMany. \n\
Second input argument, should be <type 'list'> of scalar values")
if not isinstance(handlePVMatch, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setAndMatchMany. \n\
Third input argument, should be <type 'list'> of handles or PVs")
if (len(handlePVSet) != len(valSet)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setAndMatchMany. \n\
Lengths of first (handlePVSet) and second (valSet) input lists must match!")
if (len(handlePVSet) != len(handlePVMatch)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setAndMatchMany. \n\
Lengths of first (handlePVSet) and third (handlePVMatch) input lists must match!")
if not isinstance(handlePVAction, (list)):
tmp = handlePVAction
handlePVAction = []
handlePVAction.append(tmp)
if not isinstance(valAction, (list)):
tmp = valAction
valAction = []
valAction.append(tmp)
cdef vector[unsigned int] handleSet
handleSet.reserve(len(handlePVSet))
cdef vector[unsigned int] handleMatch
handleMatch.reserve(len(handlePVMatch))
cdef vector[double] valSetV
valSetV.reserve(len(valSet))
cdef vector[unsigned int] handleAction
handleAction.reserve(len(handlePVAction))
cdef vector[string] valActionV
valActionV.reserve(len(valAction))
for i in range(0, len(handlePVSet)):
if isinstance(handlePVSet[i], (int,long)) == 1:
handleSet.push_back(handlePVSet[i])
elif isinstance(handlePVSet[i], (str)) == 1:
handleSet.push_back(self.checkForHandle(handlePVSet))
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="ThandlePVSet list member should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
for i in range(0, len(handlePVMatch)):
if isinstance(handlePVMatch[i], (int,long)) == 1:
handleMatch.push_back(handlePVMatch[i])
elif isinstance(handlePVMatch[i], (str)) == 1:
handleMatch.push_back(self.checkForHandle(handlePVMatch))
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="handleMatch list member should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
for i in range(0, len(handlePVAction)):
if isinstance(handlePVAction[i], (int,long)) == 1:
handleAction.push_back(handlePVAction[i])
elif isinstance(handlePVAction[i], (str)) == 1:
handleAction.push_back(self.checkForHandle(handlePVAction))
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="handlePVAction list member should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
for i in range(0, len(valAction)):
if not isinstance(valAction[i], (str)):
valActionV.push_back(str(valAction[i]))
else:
valActionV.push_back(valAction[i])
for i in range(0, len(valSet)):
valSetV.push_back(valSet[i])
cdef int status
with nogil:
status=self._c_cafe.gameSetAndMatch(handleSet, valSetV, handleAction, valActionV, handleMatch, tolerance, timeout, printFlag)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
raise Exception("EXCEPTION RAISED in PyCafe def gameSetAndMatch. Status = %d" %status)
return status
##################################################################################
##################################################################################
def setAndMatchMany(self, list handlePVSet, list valSet, list handlePVMatch, double tolerance, double timeout, bint printFlag):
cdef str _METHOD_="setAndMatchMany(list handlePVSet, list valSet, list handlePVMatch, double tolerance, double timeout, bint printFlag)"
if not isinstance(handlePVSet, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setAndMatchMany. \n\
First input argument, should be <type 'list'> of handles or PVs")
if not isinstance(valSet, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setAndMatchMany. \n\
Second input argument, should be <type 'list'> of scalar values")
if not isinstance(handlePVMatch, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setAndMatchMany. \n\
Third input argument, should be <type 'list'> of handles or PVs")
if (len(handlePVSet) != len(valSet)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setAndMatchMany. \n\
Lengths of first (handlePVSet) and second (valSet) input lists must match!")
if (len(handlePVSet) != len(handlePVMatch)):
raise Exception ("EXCEPTION RAISED IN PyCafe def setAndMatchMany. \n\
Lengths of first (handlePVSet) and third (handlePVMatch) input lists must match!")
cdef vector[unsigned int] handleSet
handleSet.reserve(len(handlePVSet))
cdef vector[unsigned int] handleMatch
handleMatch.reserve(len(handlePVMatch))
cdef vector[double] valSetV
valSetV.reserve(len(valSet))
for i in range(0, len(handlePVSet)):
if isinstance(handlePVSet[i], (int,long)) == 1:
handleSet.push_back(handlePVSet[i])
elif isinstance(handlePVSet[i], (str)) == 1:
handleSet.push_back(self.checkForHandle(handlePVSet))
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="ThandlePVSet list member should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
for i in range(0, len(handlePVMatch)):
if isinstance(handlePVMatch[i], (int,long)) == 1:
handleMatch.push_back(handlePVMatch[i])
elif isinstance(handlePVMatch[i], (str)) == 1:
handleMatch.push_back(self.checkForHandle(handlePVMatch))
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="handleMatch list member should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
for i in range(0, len(valSet)):
valSetV.push_back(valSet[i])
cdef int status
with nogil:
status=self._c_cafe.setAndMatchMany(handleSet, valSetV, handleMatch, tolerance, timeout, printFlag)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
raise Exception("EXCEPTION RAISED in PyCafe def setAndMatchMany. Status = %d" %status)
return status
##################################################################################
##################################################################################
def setAndMatch(self, handlePVSet, double valSet, handlePVMatch, double tolerance, double timeout, bint printFlag):
cdef str _METHOD_="setAndMatch(handlePVSet, double valSet, handlePVMatch, double tolerance, double timeout, bint printFlag)"
cdef unsigned int handleSet=0
if isinstance(handlePVSet, (int,long)) == 1:
handleSet=handlePVSet
elif isinstance(handlePVSet, (str)) == 1:
handleSet=self.checkForHandle(handlePVSet)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
cdef unsigned int handleMatch=0
if isinstance(handlePVMatch, (int,long)) == 1:
handleMatch=handlePVMatch
elif isinstance(handlePVMatch, (str)) == 1:
handleMatch=self.checkForHandle(handlePVMatch)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="Third input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
cdef int status
with nogil:
status=self._c_cafe.setAndMatch(handleSet, valSet, handleMatch, tolerance, timeout, printFlag)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
raise Exception("EXCEPTION RAISED in PyCafe def setAndMatch. Status = %d" %status)
return status
##################################################################################
##################################################################################
def matchMany(self, list valSet, list handlePVMatch, double tolerance, double timeout, bint printFlag):
cdef str _METHOD_="matchMany(self, list valSet, list handlePVMatch, double tolerance, double timeout, bint printFlag)"
if not isinstance(valSet, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def matchMany. \n\
Second input argument, should be <type 'list'> of scalar values")
if not isinstance(handlePVMatch, (list)):
raise Exception ("EXCEPTION RAISED IN PyCafe def matchMany. \n\
Third input argument, should be <type 'list'> of handles or PVs")
if (len(valSet) != len(handlePVMatch)):
raise Exception ("EXCEPTION RAISED IN PyCafe def matchMany. \n\
Lengths of first (handlePVSet) and third (handlePVMatch) input lists must match!")
cdef vector[unsigned int] handleMatch
handleMatch.reserve(len(handlePVMatch))
cdef vector[double] valSetV
valSetV.reserve(len(valSet))
for i in range(0, len(handlePVMatch)):
if isinstance(handlePVMatch[i], (int,long)) == 1:
handleMatch.push_back(handlePVMatch[i])
elif isinstance(handlePVMatch[i], (str)) == 1:
handleMatch.push_back(self.checkForHandle(handlePVMatch))
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
for i in range(0, len(valSet)):
valSetV.push_back(valSet[i])
cdef int status
with nogil:
status=self._c_cafe.matchMany( valSetV, handleMatch, tolerance, timeout, printFlag)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
raise Exception("EXCEPTION RAISED in PyCafe def matchMany. Status = %d" %status)
return status
##################################################################################
##################################################################################
def match(self, double valSet, handlePVMatch, double tolerance, double timeout, bint printFlag):
cdef str _METHOD_="match(double valSet, handlePVMatch, double tolerance, double timeout, bint printFlag)"
cdef unsigned int handleMatch=0
if isinstance(handlePVMatch, (int,long)) == 1:
handleMatch=handlePVMatch
elif isinstance(handlePVMatch, (str)) == 1:
handleMatch=self.checkForHandle(handlePVMatch)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
cdef int status
with nogil:
status=self._c_cafe.match(valSet, handleMatch, tolerance, timeout, printFlag)
if status !=ICAFE_NORMAL:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(status)
raise Exception("EXCEPTION RAISED in PyCafe def match. Status = %d" %status)
return status
##################################################################################
##################################################################################
def setNelemCtrl(self, handlePV, unsigned int nelem):
cdef str _METHOD_="setNelemCtrl(self, handlePV, unsigned int nelem)"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)):
handle=handlePV
elif isinstance(handlePV, (str)):
handle=self.checkForHandle(handlePV)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
if handle == 0:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(ECAFE_INVALID_HANDLE)
raise Exception("EXCEPTION RAISED in PyCafe def setNelemToRetrieveFromCacheToOne")
#returns nelem
return self.hh.setNelemCtrl(handle, nelem)
##################################################################################
def setNelem(self, handlePV, unsigned int nelem):
cdef str _METHOD_="setNelem(self, handlePV, unsigned int nelem)"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)):
handle=handlePV
elif isinstance(handlePV, (str)):
handle=self.checkForHandle(handlePV)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
if handle == 0:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(ECAFE_INVALID_HANDLE)
raise Exception("EXCEPTION RAISED in PyCafe def setNelemToRetrieveFromCacheToOne")
#returns nelem
return self.hh.setNelem(handle, nelem)
##################################################################################
def setNelemToNative(self, handlePV):
cdef str _METHOD_="setNelemToNative(self, handlePV)"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)):
handle=handlePV
elif isinstance(handlePV, (str)):
handle=self.checkForHandle(handlePV)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
if handle == 0:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(ECAFE_INVALID_HANDLE)
raise Exception("EXCEPTION RAISED in PyCafe def setNelemToRetrieveFromCacheToOne")
#returns nelem
return self.hh.setNelemToNative(handle)
##################################################################################
def setNelemToRetrieveFromCacheToOne(self, handlePV):
cdef str _METHOD_="setNelemToRetrieveFromCacheToOne(self, handlePV)"
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)):
handle=handlePV
elif isinstance(handlePV, (str)):
handle=self.checkForHandle(handlePV)
else:
_cyCafeException = CyCafeException(_type='cafe',_source=_METHOD_, \
_ei="First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
raise Exception(_cyCafeException)
if handle == 0:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(ECAFE_INVALID_HANDLE)
raise Exception("EXCEPTION RAISED in PyCafe def setNelemToRetrieveFromCacheToOne")
#returns previous nelem
return self._c_cafe.setNelemToRetrieveFromCacheToOne(handle)
##################################################################################
def setNelemToRetrieveFromCache(self, handlePV, netrfc):
cdef unsigned int handle=0
if isinstance(handlePV, (int,long)):
handle=handlePV
elif isinstance(handlePV, (str)):
handle=self.checkForHandle(handlePV)
else:
raise Exception ("EXCEPTION RAISED IN PyCafe def set. \n\
First input argument, should be <type 'int'> if handle, else <type 'str'> if PV")
if handle == 0:
if PYCAFE_PRINT_LEVEL>=PYCAFE_PRINT_LOW:
self._c_cafe.printStatusMessage(ECAFE_INVALID_HANDLE)
raise Exception("EXCEPTION RAISED in PyCafe def setNelemToRetrieveFromCacheToOne")
#returns new nelem
return self._c_cafe.setNelemToRetrieveFromCacheToPrevious(handle, netrfc)
##################################################################################
def terminate(self):
with nogil:
self._c_cafe.terminate()
return
##################################################################################
###################################################################################
##################################################################################
#END: cdef CAFE###################################################################
##################################################################################