-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpvConnect.py
executable file
·356 lines (291 loc) · 11.5 KB
/
pvConnect.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
#!/usr/bin/env python
#*************************************************************************
# Copyright (c) 2009 The University of Chicago, as Operator of Argonne
# National Laboratory.
# Copyright (c) 2009 The Regents of the University of California, as
# Operator of Los Alamos National Laboratory.
# This file is distributed subject to a Software License Agreement found
# in the file LICENSE that is included with this distribution.
#*************************************************************************
'''
simplified connections to an EPICS PV using CaChannel
Provides these classes:
CaPollWx
Use in WX-based GUIs to call ca.poll() in the background
@param interval_s: [float] interval between calls to ca.poll()
EpicsPv
manage a CaChannel connection with an EPICS PV
@param name: [string] EPICS PV to connect
Provides these utility routines:
on_exit(timer)
Exit handler to stop the ca.poll()
@param timer: CaPollWx object
CaPoll()
Use in non-GUI scripts to call ca.poll() in the background
GetRTYP(pv)
Returns the record type of "pv"
@param pv:[string]
@return: [string] EPICS record type or None if cannot connect
testConnect(pv)
Tests if a CaChannel connection can be established to "pv"
@param pv:[string]
@return: True if can connect, otherwise False
receiver(value)
Example response to an EPICS monitor on the channel
@param value: str(epics_args['pv_value'])
MonitoredConnection(callback, pv = None)
Connect to the EPICS PV and monitor it.
Invoke the callback routine specified by the caller.
Set the PV name to be reported in the user_args term of the callback
'''
import time
try:
# CaChannel provides access to the EPICS PVs
import CaChannel
IMPORTED_CACHANNEL = True
except Exception:
IMPORTED_CACHANNEL = False
try:
# wx is needed for the timer to call CaChannel.ca.poll()
# only use this with a wx-based GUI
import wx
IMPORTED_WX = True
except Exception:
IMPORTED_WX = False
class CaPollWx:
'''Use in WX-based GUIs to call ca.poll() in the background
Set up a separate thread to trigger periodic calls to the
EPICS CaChannel.ca.poll() connection. Awaiting (a.k.a.,
outstanding or pending) channel access background
activity executes during the poll. Calls pend_event()
with a timeout short enough to poll.
The default polling interval is 0.1 second.
@note: The code will silently do nothing if wx was not imported.
This routine use the wx.PyTimer() to call ca.poll() frequently
during the main WX event loop.
@warning: Only use this in a routine that has already called
wx.App() or an exception will occur.
Command line code will need to call ca.poll() using a different
method (such as CaPoll() below).
'''
def __init__(self, interval_s = 0.1):
'''@param interval_s: [float] interval between calls to ca.poll()'''
if IMPORTED_WX: # only if wx was imported
self.running = False
self.interval_s = interval_s
self.TIMER_ID = 100
self.timer = wx.PyTimer(self.poll)
self.start()
def start(self):
'''start polling'''
if IMPORTED_WX: # only if wx was imported
self.running = True
self.timer.Start(int(1000*self.interval_s)) # argument is in ms
def stop(self):
'''stop polling'''
if IMPORTED_WX: # only if wx was imported
self.running = False
self.timer.Stop()
def poll(self):
'''Poll for changes in Channel'''
if IMPORTED_WX: # only if wx was imported
CaChannel.ca.poll()
def GetInterval(self):
'''return the current interval between calls to CaChannel.ca.poll()'''
if IMPORTED_WX: # only if wx was imported
return self.interval_s
def SetInterval(self, interval_s):
'''set the next interval between calls to CaChannel.ca.poll()'''
if IMPORTED_WX: # only if wx was imported
self.interval_s = interval_s
class EpicsPv:
'''manage a connection with an EPICS PV'''
def __init__(self, name):
'''initialize the class and set default values
@param name: [string] EPICS PV to connect'''
self.pv = name
self.chan = None
self.value = None
self.user_callback = None
self.epics_args = None
self.user_args = None
self.mask = None
if IMPORTED_CACHANNEL:
self.mask = CaChannel.ca.DBE_VALUE
def callback(self, epics_args, user_args):
'''receive an EPICS callback, copy epics_args and user_args, then call user'''
self.epics_args = epics_args
self.user_args = user_args
self.value = epics_args['pv_value']
if self.user_callback != None:
self.user_callback(epics_args, user_args)
def connect(self):
'''initiate the connection with EPICS'''
if IMPORTED_CACHANNEL:
if len(self.pv) > 0:
self.chan = CaChannel.CaChannel()
self.chan.search(str(self.pv))
def connectw(self):
'''initiate the connection with EPICS, standard wait for the connection'''
if IMPORTED_CACHANNEL:
if len(self.pv) > 0:
self.chan = CaChannel.CaChannel()
self.chan.searchw(str(self.pv))
def release(self):
'''release the connection with EPICS
@note: Release ALL channels before calling on_exit()'''
if self.chan != None:
del self.chan
self.chan = None
def monitor(self):
'''Initiate a monitor on the EPICS channel, delivering the
CaChannel callback to the supplied function.
@note: Example:
ch = EpicsPv(test_pv)
ch.connectw()
uargs = test_pv, widget.SetLabel
ch.SetUserArgs(uargs)
ch.SetUserCallback(myCallback)
ch.monitor()
@warning: At this time, there is not an easy way to turn off monitors.
Instead, ch.release() the channel (which will set self.chan = None),
To re-start a monitor after a ch.release(), connect as usual and start
the monitor again, as the first time.
'''
if IMPORTED_CACHANNEL and self.chan != None:
type = CaChannel.ca.dbf_type_to_DBR_GR(self.chan.field_type())
# call supplied callback routine with default argument list
# self.user_callback(epics_args, user_args)
self.chan.add_masked_array_event(type,
None, self.mask, self.callback, self.user_args)
def MonitoredConnection(self, callback, pv = None):
'''
Connect to the EPICS PV and monitor it.
Invoke the callback routine specified by the caller.
Set the PV name to be reported in the user_args term of the callback
'''
if pv is None:
pv = self.pv
self.connectw()
self.SetUserCallback(callback)
self.SetUserArgs(pv)
self.monitor()
return self
def GetPv(self):
'''@return: PV name'''
return self.pv
def GetValue(self):
'''@return: value from EPICS from the most recent monitor event'''
return self.value
def SetPv(self, name):
'''redefine the PV name only if there is no connection
@param name: valid EPICS PV name'''
if self.chan is None:
self.pv = name
def GetChan(self):
'''@return: CaChannel channel'''
return self.chan
def GetEpicsArgs(self):
'''@return: epics_args from the most recent monitor event'''
return self.epics_args
def GetUserArgs(self):
'''@return: user_args from the most recent monitor event'''
return self.user_args
def SetUserArgs(self, user_args):
'''define the user_args tuple to use when monitoring
@param user_args: tuple of user data (for use in user_callback function)'''
self.user_args = user_args
def SetMask(self, mask):
'''Define the mask used when applying a channel monitor.
The default is: self.mask = CaChannel.ca.DBE_VALUE
@param mask: as defined in the CaChannel manual'''
self.pv = mask
def GetUserCallback(self):
'''return the callback function supplied by the caller
values will be set by self.user_callback(value)
@return: function object'''
return self.user_callback
def SetUserCallback(self, user_callback):
'''Set the callback function supplied by the caller
values will be set by self.user_callback(value)
@param user_callback: function object'''
self.user_callback = user_callback
def on_exit(timer = None):
'''Exit handler to stop the ca.poll()
@param timer: CaPollWx object
Call this to cleanup when program is exiting.
ONLY call this function during a program's exit handling.
If ca.task_exit() is not called, then expect to see the errors:
FATAL: exception not rethrown
Abort
'''
if IMPORTED_CACHANNEL: # only if ca binding was loaded
CaChannel.ca.task_exit()
try: # fail no matter what
if timer != None:
timer.stop()
except Exception:
pass
def CaPoll():
'''Use in non-GUI scripts to call ca.poll() in the background'''
if IMPORTED_CACHANNEL:
CaChannel.ca.poll()
def GetRTYP(pv):
'''Returns the record type of "pv"
@param pv:[string]
@return: [string] EPICS record type or None if cannot connect'''
if not IMPORTED_CACHANNEL:
return None
if len(pv) == 0:
return None
base = pv.split('.')[0]
if testConnect(base):
rtyp_pv = base + '.RTYP'
ch = EpicsPv(rtyp_pv)
ch.connectw()
rtyp = ch.chan.getw()
del ch
return rtyp
else:
return None
def testConnect(pv):
'''Tests if a CaChannel connection can be established to "pv"
@param pv:[string]
@return: True if can connect, otherwise False'''
result = False
if not IMPORTED_CACHANNEL:
return result
try:
#print 'testConnect:', type(pv), pv
chan = CaChannel.CaChannel()
chan.searchw(str(pv))
# val = chan.getw()
del chan
result = True
except (TypeError, CaChannel.CaChannelException), status:
# python3: (TypeError, CaChannel.CaChannelException) as status
#print 'testConnect:', status
pass
return result
def receiver(epics_args, user_args):
'''Example response to an EPICS monitor on the channel
@param value: str(epics_args['pv_value'])'''
value = epics_args['pv_value']
print 'receiver', 'updated value:', str(value)
if __name__ == '__main__':
if IMPORTED_CACHANNEL:
test_pv = 'S:SRcurrentAI'
if testConnect(test_pv):
print "recordType(%s) = %s" % (test_pv, GetRTYP(test_pv))
ch = EpicsPv(test_pv).MonitoredConnection(receiver)
ch.chan.pend_event()
import time
count = 5
for seconds in range(count):
time.sleep(1)
ch.chan.pend_event()
print count - seconds - 1, ch.GetPv(), '=', ch.GetValue()
ch.release()
on_exit()
else:
print "CaChannel is missing, cannot run"