-
Notifications
You must be signed in to change notification settings - Fork 76
/
signal.py
1908 lines (1562 loc) · 69.3 KB
/
signal.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# vi: ts=4 sw=4
import os
import time
import threading
import warnings
import weakref
import numpy as np
from .utils import (ReadOnlyError, LimitError, DestroyedError, set_and_wait,
doc_annotation_forwarder)
from .utils.epics_pvs import (waveform_to_string,
raise_if_disconnected, data_type, data_shape,
AlarmStatus, AlarmSeverity, validate_pv_name)
from .ophydobj import OphydObject, Kind
from .status import Status
from . import get_cl
# Catch semi-frequent issue with scripts accidentally run from inside module
if __name__ != 'ophyd.signal':
raise RuntimeError(
'A script tried to import ophyd.signal instead of the signal built-in '
'module. This usually happens when a script is run from inside the '
'ophyd directory and can cause extremely confusing bugs. Please '
'run your script elsewhere for better results.'
)
# Sentinels used for default values; see set_defaults() below for details.
DEFAULT_AUTO_MONITOR = object()
DEFAULT_CONNECTION_TIMEOUT = object()
DEFAULT_TIMEOUT = object()
DEFAULT_WRITE_TIMEOUT = object()
# Sentinel to identify if we have never turned the crank on updating a PV
DEFAULT_EPICSSIGNAL_VALUE = object()
class ReadTimeoutError(TimeoutError):
...
class ConnectionTimeoutError(TimeoutError):
...
class Signal(OphydObject):
r'''A signal, which can have a read-write or read-only value.
Parameters
----------
name : string, keyword only
value : any, optional
The initial value
kind : a member the Kind IntEnum (or equivalent integer), optional
Default is Kind.normal. See Kind for options.
parent : Device, optional
The parent Device holding this signal
timestamp : float, optional
The timestamp associated with the initial value. Defaults to the
current local time.
tolerance : any, optional
The absolute tolerance associated with the value
rtolerance : any, optional
The relative tolerance associated with the value, used in
set_and_wait as follows
.. math::
|setpoint - readback| \leq (tolerance + rtolerance * |readback|)
cl : namespace, optional
Control Layer. Must provide 'get_pv' and 'thread_class'
attr_name : str, optional
The parent Device attribute name that corresponds to this Signal
Attributes
----------
rtolerance : any, optional
The relative tolerance associated with the value
'''
SUB_VALUE = 'value'
SUB_META = 'meta'
_default_sub = SUB_VALUE
_metadata_keys = None
_core_metadata_keys = ('connected', 'read_access', 'write_access', 'timestamp')
def __init__(self, *, name, value=0., timestamp=None, parent=None,
labels=None, kind=Kind.hinted, tolerance=None,
rtolerance=None, metadata=None, cl=None, attr_name=''):
super().__init__(name=name, parent=parent, kind=kind, labels=labels,
attr_name=attr_name)
if cl is None:
cl = get_cl()
self.cl = cl
self._dispatcher = cl.get_dispatcher()
self._metadata_thread_ctx = self._dispatcher.get_thread_context('monitor')
self._readback = value
if timestamp is None:
timestamp = time.time()
self._destroyed = False
self._set_thread = None
self._tolerance = tolerance
# self.tolerance is a property
self.rtolerance = rtolerance
# Signal defaults to being connected, with full read/write access.
# Subclasses are expected to clear these on init, if applicable.
self._metadata = dict(
connected=True,
read_access=True,
write_access=True,
timestamp=timestamp,
status=None,
severity=None,
precision=None,
)
if metadata is not None:
self._metadata.update(**metadata)
if self._metadata_keys is None:
self._metadata_keys = tuple(self._metadata.keys())
else:
unset_metadata = {key: None for key in self._metadata_keys
if key not in self._metadata}
self._metadata.update(**unset_metadata)
def trigger(self):
'''Call that is used by bluesky prior to read()'''
# NOTE: this is a no-op that exists here for bluesky purposes
# it may need to be moved in the future
d = Status(self)
d._finished()
return d
def wait_for_connection(self, timeout=0.0):
'''Wait for the underlying signals to initialize or connect'''
pass
@property
def metadata_keys(self):
'Metadata keys that will be passed along on value subscriptions'
return tuple(self._metadata_keys)
@property
def timestamp(self):
'''Timestamp of the readback value'''
return self._metadata['timestamp']
@property
def tolerance(self):
'''The absolute tolerance associated with the value.'''
return self._tolerance
@tolerance.setter
def tolerance(self, tolerance):
self._tolerance = tolerance
def _repr_info(self):
'Yields pairs of (key, value) to generate the Signal repr'
yield from super()._repr_info()
try:
value = self._readback
except Exception:
value = None
if value is not DEFAULT_EPICSSIGNAL_VALUE:
yield ('value', value)
yield ('timestamp', self._metadata['timestamp'])
if self.tolerance is not None:
yield ('tolerance', self.tolerance)
if self.rtolerance is not None:
yield ('rtolerance', self.rtolerance)
# yield ('metadata', self._metadata)
def get(self, **kwargs):
'''The readback value'''
return self._readback
def put(self, value, *, timestamp=None, force=False, metadata=None,
timeout=DEFAULT_WRITE_TIMEOUT, **kwargs):
'''Put updates the internal readback value
The value is optionally checked first, depending on the value of force.
In addition, VALUE subscriptions are run.
Extra kwargs are ignored (for API compatibility with EpicsSignal kwargs
pass through).
Parameters
----------
value : any
Value to set
timestamp : float, optional
The timestamp associated with the value, defaults to time.time()
metadata : dict, optional
Further associated metadata with the value (such as alarm status,
severity, etc.)
force : bool, optional
Check the value prior to setting it, defaults to False
'''
self.control_layer_log.debug(
'put(value=%s, timestamp=%s, force=%s, metadata=%s)',
value, timestamp, force, metadata
)
# TODO: consider adding set_and_wait here as a kwarg
if kwargs:
warnings.warn('Signal.put no longer takes keyword arguments; '
'These are ignored and will be deprecated.')
if not force:
if not self.write_access:
raise ReadOnlyError('Signal does not allow write access')
self.check_value(value)
old_value = self._readback
self._readback = value
if metadata is None:
metadata = {}
if timestamp is None:
timestamp = metadata.get('timestamp', time.time())
metadata = metadata.copy()
metadata['timestamp'] = timestamp
self._metadata.update(**metadata)
md_for_callback = {key: metadata[key]
for key in self._metadata_keys
if key in metadata}
if 'timestamp' not in self._metadata_keys:
md_for_callback['timestamp'] = timestamp
self._run_subs(sub_type=self.SUB_VALUE, old_value=old_value,
value=value, **md_for_callback)
def _set_and_wait(self, value, timeout):
'''
Overridable hook for subclasses to override :meth:`.set` functionality.
This will be called in a separate thread (`_set_thread`), but will not
be called in parallel.
Parameters
----------
value : any
The value
timeout : float, optional
Maximum time to wait for value to be successfully set, or None
'''
return set_and_wait(self, value, timeout=timeout, atol=self.tolerance,
rtol=self.rtolerance)
def set(self, value, *, timeout=None, settle_time=None):
'''Set is like `put`, but is here for bluesky compatibility
Returns
-------
st : Status
This status object will be finished upon return in the
case of basic soft Signals
'''
self.log.info(
'set(value=%s, timeout=%s, settle_time=%s)',
value, timeout, settle_time
)
def set_thread():
try:
self._set_and_wait(value, timeout)
except TimeoutError:
success = False
self.log.warning(
'%s: set_and_wait(value=%s, timeout=%s, atol=%s, rtol=%s)',
self.name, value, timeout, self.tolerance, self.rtolerance
)
except Exception:
success = False
self.log.exception(
'%s: set_and_wait(value=%s, timeout=%s, atol=%s, rtol=%s)',
self.name, value, timeout, self.tolerance, self.rtolerance
)
else:
success = True
self.log.info(
'%s: set_and_wait(value=%s, timeout=%s, atol=%s, rtol=%s) succeeded => %s',
self.name, value, timeout, self.tolerance, self.rtolerance, self._readback)
if settle_time is not None:
self.log.info('settling for %d seconds', settle_time)
time.sleep(settle_time)
finally:
# keep a local reference to avoid any GC shenanigans
th = self._set_thread
# these two must be in this order to avoid a race condition
self._set_thread = None
st._finished(success=success)
del th
if self._set_thread is not None:
raise RuntimeError('Another set() call is still in progress '
f'for {self.name}')
st = Status(self)
self._status = st
self._set_thread = self.cl.thread_class(target=set_thread)
self._set_thread.daemon = True
self._set_thread.start()
return self._status
@property
def value(self):
'''The signal's value'''
fix_msg = ("We are falling back to calling `.get` and interrogating "
"the underlying control system, however this may cause several "
"other problems:\n"
" 1. This property access may take an arbitrarily long time\n"
" 2. This property access, which you expect to be read only "
"may change other state in the Signal.\n"
"Your options to fix this are:\n"
" - do not use obj.value.\n"
" - If you are using this is in a plan you "
"like want to be using bps.read, bps.rd, bpp.reset_positions_decorator, "
"bpp.reset_positions_wrapper, bpp.relative_set_decorator, or "
"bpp.relative_set_wrapper\n"
" - if you are doing this in an ophyd method use `self.get`\n"
" - set up the Signal to monitor\n\n"
"This behavior will likely change in the future.")
if self._readback is DEFAULT_EPICSSIGNAL_VALUE:
# If we are here, then we have never turned the crank on this Signal. The current
# behavior is to fallback to poking the control system to get the value, however this
# is problematic and we may want to change in the future so warn verbosely
if not os.getenv("OPHYD_SILENCE_VALUE_WARNING") == "1":
warnings.warn(f"You have called obj.value on {self} "
f"({self.name}.{self.dotted_name}) "
"which has not gotten value from the control system yet.\n" + fix_msg,
stacklevel=2)
return self.get()
else:
# if we are in here then we have put/get at least once and/or are monitored
has_monitors = (hasattr(self, '_monitors') and
all(v is not None for v in self._monitors.values())
)
if not has_monitors:
# If we are not monitored, then warn that this may change in the future.
if not os.getenv("OPHYD_SILENCE_VALUE_WARNING") == "1":
warnings.warn(f"You have called obj.value on {self} "
f"({self.name}.{self.dotted_name}) "
"which is a non-monitored signal.\n" + fix_msg,
stacklevel=2)
return self.get()
# else return our cached value and assume something else is keeping us up-to-date
# so we can trust the latest news
return self._readback
@value.setter
def value(self, value):
self.put(value)
@raise_if_disconnected
def read(self):
'''Put the status of the signal into a simple dictionary format
for data acquisition
Returns
-------
dict
'''
value = self.get()
return {self.name: {'value': value,
'timestamp': self.timestamp}}
def describe(self):
"""Provide schema and meta-data for :meth:`~BlueskyInterface.read`
This keys in the `OrderedDict` this method returns must match the
keys in the `OrderedDict` return by :meth:`~BlueskyInterface.read`.
This provides schema related information, (ex shape, dtype), the
source (ex PV name), and if available, units, limits, precision etc.
Returns
-------
data_keys : OrderedDict
The keys must be strings and the values must be dict-like
with the ``event_model.event_descriptor.data_key`` schema.
"""
if self._readback is DEFAULT_EPICSSIGNAL_VALUE:
val = self.get()
else:
val = self._readback
return {self.name: {'source': 'SIM:{}'.format(self.name),
'dtype': data_type(val),
'shape': data_shape(val)}}
def read_configuration(self):
'Dictionary mapping names to value dicts with keys: value, timestamp'
return self.read()
def describe_configuration(self):
"""Provide schema & meta-data for `~BlueskyInterface.read_configuration`
This keys in the `OrderedDict` this method returns must match the keys
in the `OrderedDict` return by :meth:`~BlueskyInterface.read`.
This provides schema related information, (ex shape, dtype), the source
(ex PV name), and if available, units, limits, precision etc.
Returns
-------
data_keys : OrderedDict
The keys must be strings and the values must be dict-like
with the ``event_model.event_descriptor.data_key`` schema.
"""
return self.describe()
@property
def limits(self):
'''The control limits (low, high), such that low <= value <= high'''
# NOTE: subclasses are expected to override this property
# Always override, never extend this
return (0, 0)
@property
def low_limit(self):
'The low, inclusive control limit for the Signal'
return self.limits[0]
@property
def high_limit(self):
'The high, inclusive control limit for the Signal'
return self.limits[1]
@property
def hints(self):
'Field hints for plotting'
if (~Kind.normal & Kind.hinted) & self.kind:
return {'fields': [self.name]}
else:
return {'fields': []}
@property
def connected(self):
'Is the signal connected to its associated hardware, and ready to use?'
return self._metadata['connected'] and not self._destroyed
@property
def read_access(self):
'Can the signal be read?'
return self._metadata['read_access']
@property
def write_access(self):
'Can the signal be written to?'
return self._metadata['write_access']
@property
def metadata(self):
'A copy of the metadata dictionary associated with the signal'
return self._metadata.copy()
def destroy(self):
'''Disconnect the Signal from the underlying control layer; destroy it
Clears all subscriptions on this Signal. Once destroyed, the signal
may no longer be used.
'''
self._destroyed = True
super().destroy()
def _run_metadata_callbacks(self):
'Run SUB_META in the appropriate dispatcher thread'
self._metadata_thread_ctx.run(self._run_subs, sub_type=self.SUB_META,
**self._metadata)
class SignalRO(Signal):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._metadata.update(
connected=True,
write_access=False,
)
def put(self, value, *, timestamp=None, force=False):
raise ReadOnlyError("The signal {} is readonly.".format(self.name))
def set(self, value, *, timestamp=None, force=False):
raise ReadOnlyError("The signal {} is readonly.".format(self.name))
class DerivedSignal(Signal):
def __init__(self, derived_from, *, write_access=None, name=None,
parent=None, **kwargs):
'''A signal which is derived from another one
Calculations of the DerivedSignal value can be done in subclasses of
DerivedSignal, overriding the `forward` and `inverse` methods.
Metadata keys and write access are inherited from the main signal,
referred to as `derived_from`.
The description of this Signal, from `describe` will include an
additional key indicating the signal name from where it was derived.
Parameters
----------
derived_from : Union[Signal, str]
The signal from which this one is derived. This may be a string
attribute name that indicates a sibling to use. When used in a
Device, this is then simply the attribute name of another
Component.
name : str, optional
The signal name
parent : Device, optional
The parent device
'''
if isinstance(derived_from, str):
derived_from = getattr(parent, derived_from)
# Metadata keys from the class itself take precedence
self._metadata_keys = getattr(self, '_metadata_keys', None)
# However, if not specified, the keys from the original signal are used
if self._metadata_keys is None:
self._metadata_keys = getattr(derived_from, 'metadata_keys', None)
# And failing that, they are the defaults from all signals
super().__init__(name=name, parent=parent,
metadata=derived_from.metadata, **kwargs)
self._derived_from = derived_from
self._allow_writes = (write_access is not False)
self._metadata['write_access'] = (derived_from.write_access and
self._allow_writes)
if self.connected:
# set up the initial timestamp reporting, if connected
self._metadata['timestamp'] = derived_from.timestamp
derived_from.subscribe(self._derived_value_callback,
event_type=self.SUB_VALUE,
run=self.connected)
derived_from.subscribe(self._derived_metadata_callback,
event_type=self.SUB_META,
run=self.connected)
@property
def derived_from(self):
'''Signal that this one is derived from'''
return self._derived_from
def describe(self):
'''Description based on the original signal description'''
desc = super().describe()[self.name] # Description of this signal
desc['derived_from'] = self._derived_from.name
# Description of the derived signal
derived_desc = self._derived_from.describe()[self._derived_from.name]
derived_desc.update(desc)
return {self.name: derived_desc}
def _update_metadata_from_callback(self, **kwargs):
updated_md = {key: kwargs[key] for key in self.metadata_keys
if key in kwargs
}
if 'write_access' in updated_md:
updated_md['write_access'] = (updated_md['write_access'] and
self._allow_writes)
self._metadata.update(**updated_md)
return updated_md
def _derived_metadata_callback(self, *, connected, read_access,
write_access, timestamp, **kwargs):
'Main signal metadata updated - update the DerivedSignal'
self._update_metadata_from_callback(connected=connected,
read_access=read_access,
write_access=write_access,
timestamp=timestamp, **kwargs)
self._run_metadata_callbacks()
def _derived_value_callback(self, value, **kwargs):
'Main signal value updated - update the DerivedSignal'
# if some how we get cycled with the default value sentinel, just bail
if value is DEFAULT_EPICSSIGNAL_VALUE:
return
value = self.inverse(value)
self._readback = value
updated_md = self._update_metadata_from_callback(**kwargs)
self._run_subs(sub_type=self.SUB_VALUE, value=value, **updated_md)
def get(self, **kwargs):
'Get the value from the original signal, with `inverse` applied to it'
value = self._derived_from.get(**kwargs)
self._readback = self.inverse(value)
self._metadata['timestamp'] = self._derived_from.timestamp
return self._readback
def inverse(self, value):
'''Compute original signal value -> derived signal value'''
return value
def put(self, value, **kwargs):
'''Put the value to the original signal'''
if not self.write_access:
raise ReadOnlyError('DerivedSignal is marked as read-only')
value = self.forward(value)
res = self._derived_from.put(value, **kwargs)
self._metadata['timestamp'] = self._derived_from.timestamp
return res
def forward(self, value):
'''Compute derived signal value -> original signal value'''
return value
def wait_for_connection(self, timeout=0.0):
'''Wait for the original signal to connect'''
return self._derived_from.wait_for_connection(timeout=timeout)
@property
def connected(self):
'''Mirrors the connection state of the original signal'''
return self._derived_from.connected
@property
def limits(self):
'''Limits from the original signal (low, high), such that low <= value <= high'''
return tuple(sorted(self.inverse(v) for v in self._derived_from.limits))
def _repr_info(self):
'Yields pairs of (key, value) to generate the Signal repr'
yield from super()._repr_info()
if self.parent is not None:
yield ('derived_from', self._derived_from.dotted_name)
else:
yield ('derived_from', self._derived_from)
class EpicsSignalBase(Signal):
'''A read-only EpicsSignal -- that is, one with no `write_pv`
Keyword arguments are passed on to the base class (Signal) initializer
Parameters
----------
read_pv : str
The PV to read from
string : bool, optional
Attempt to cast the EPICS PV value to a string by default
auto_monitor : bool, optional
Use automonitor with epics.PV
name : str, optional
Name of signal. If not given defaults to read_pv
metadata : dict
Merged with metadata received from EPICS
all_pvs : set
Set of PVs to watch for connection and access rights callbacks.
Defaults to ``{read_pvs}``.
timeout : float or None, optional
The timeout for serving a read request on a connected channel. This is
only applied if the PV is connected within connection_timeout (below).
The default value DEFAULT_TIMEOUT means, "Fall back to class-wide
default." See EpicsSignalBase.set_defaults to configure class
defaults.
Explicitly passing None means, "Wait forever."
write_timeout : float or None, optional
The timeout for a reply when put completion is used. This is
only applied if the PV is connected within connection_timeout (below).
This is very different than the connection and read timeouts
above. It relates to how long an action takes to complete, such motor
motion or data acquisition. Any default value we choose here is likely
to cause problems---either by being too short and giving up too early
on a lengthy action or being too long and delaying the report of a
failure. A finite value can be injected here or, perhaps more usefully,
via `set` at the Device level, where a context-appropriate value can be
chosen.
connection_timeout : float or None, optional
Timeout for connection. This includes the time to search and establish
a channel.
The default value DEFAULT_CONNECTION_TIMEOUT means, "Fall back to
class-wide default." See EpicsSignalBase.set_defaults to
configure class defaults.
Explicitly passing None means, "Wait forever."
'''
# This is set to True when the first instance is made. It is used to ensure
# that certain class-global settings can only be made before any
# instantiation.
__any_instantiated = False
# See set_defaults() for more on these.
__default_connection_timeout = 1.0
__default_timeout = 2.0 # *read* timeout
__default_write_timeout = None # Wait forever.
__default_auto_monitor = False
_read_pv_metadata_key_map = dict(
status=('status', AlarmStatus),
severity=('severity', AlarmSeverity),
precision=('precision', None),
lower_ctrl_limit=('lower_ctrl_limit', None),
upper_ctrl_limit=('upper_ctrl_limit', None),
timestamp=('timestamp', None),
units=('units', None),
enum_strs=('enum_strs', tuple),
# ignored: read_access, write_access, connected, etc.
)
_metadata_keys = (Signal._core_metadata_keys +
('status', 'severity', 'precision', 'lower_ctrl_limit',
'upper_ctrl_limit', 'units', 'enum_strs',
)
)
def __init__(self, read_pv, *,
string=False,
auto_monitor=DEFAULT_AUTO_MONITOR,
name=None,
metadata=None,
all_pvs=None,
timeout=DEFAULT_TIMEOUT,
write_timeout=DEFAULT_WRITE_TIMEOUT,
connection_timeout=DEFAULT_CONNECTION_TIMEOUT,
**kwargs):
self._metadata_lock = threading.RLock()
self._read_pv = None
self._read_pvname = read_pv
self._string = bool(string)
self._signal_is_ready = threading.Event()
self._first_connection = True
if auto_monitor is DEFAULT_AUTO_MONITOR:
auto_monitor = self.__default_auto_monitor
self._auto_monitor = auto_monitor
if connection_timeout is DEFAULT_CONNECTION_TIMEOUT:
connection_timeout = self.__default_connection_timeout
self._connection_timeout = connection_timeout
if timeout is DEFAULT_TIMEOUT:
timeout = self.__default_timeout
self._timeout = timeout
if write_timeout is DEFAULT_WRITE_TIMEOUT:
write_timeout = self.__default_write_timeout
self._write_timeout = write_timeout
if name is None:
name = read_pv
if metadata is None:
metadata = {}
metadata.update(
connected=False,
)
kwargs.setdefault('value', DEFAULT_EPICSSIGNAL_VALUE)
super().__init__(name=name, metadata=metadata, **kwargs)
validate_pv_name(read_pv)
# Keep track of all associated PV's connectivity and access rights
# callbacks. These map `pvname` to bool:
if all_pvs is None:
all_pvs = {read_pv}
self._connection_states = {pv: False for pv in all_pvs}
self._access_rights_valid = {pv: False for pv in all_pvs}
self._received_first_metadata = {pv: False for pv in all_pvs}
self._monitors = {pv: None for pv in all_pvs}
self._metadata_key_map = {read_pv: self._read_pv_metadata_key_map}
for pv in all_pvs:
if pv not in self._metadata_key_map:
self._metadata_key_map[pv] = {}
self._read_pv = self.cl.get_pv(
read_pv, auto_monitor=self._auto_monitor,
connection_callback=self._pv_connected,
access_callback=self._pv_access_callback)
self._read_pv._reference_count += 1
if not self.__any_instantiated:
self.log.debug("This is the first instance of EpicsSignalBase. "
"name={self.name}, id={id(self)}")
EpicsSignalBase._mark_as_instantiated()
def finalize(read_pv, cl):
cl.release_pvs(read_pv)
self._read_pv_finalizer = weakref.finalize(self, finalize, self._read_pv, self.cl)
def destroy(self):
super().destroy()
self._read_pv_finalizer()
@classmethod
def _mark_as_instantiated(cls):
"Update state indicated that this class has been instantiated."
cls.__any_instantiated = True
@classmethod
def set_defaults(cls,
*,
timeout=__default_timeout,
connection_timeout=__default_connection_timeout,
write_timeout=__default_write_timeout,
auto_monitor=__default_auto_monitor):
"""
Set class-wide defaults for EPICS CA communications
This may be called only before any instances of EpicsSignalBase are
made.
This setting applies to the class it is called on and all its
subclasses. For example,
>>> EpicsSignalBase.set_defaults(...)
will apply to ``EpicsSignalRO`` and ``EpicsSignal``, which are both
subclasses of ``EpicsSignalBase``.
but
>>> EpicsSignal.set_defaults(...)
will not apply to ``EpicsSignalRO``.
Parameters
----------
auto_monitor: bool, optional
If ``True``, update cached value from EPICS CA monitor callbacks.
If ``False``, request new value from EPICS each time get() is called.
connection_timeout: float, optional
Time (seconds) allocated for establishing a connection with the
IOC.
timeout: float, optional
Total time budget (seconds) for reading, not including connection time.
write_timeout: float, optional
Time (seconds) allocated for writing, not including connection time.
The write_timeout is very different than the connection and read timeouts
above. It relates to how long an action takes to complete. Any
default value we choose here is likely to cause problems---either
by being too short and giving up too early on a lengthy action or
being too long and delaying the report of a failure. The default,
None, waits forever.
Raises
------
RuntimeError
If called after :class:`EpicsSignalBase` has been instantiated for
the first time.
"""
if EpicsSignalBase.__any_instantiated:
raise RuntimeError(
"The method EpicsSignalBase.set_defaults may only "
"be called before the first instance of EpicsSignalBase is "
"created. This is to ensure that all instances are created "
"with the same default settings in place.")
cls.__default_auto_monitor = auto_monitor
cls.__default_connection_timeout = connection_timeout
cls.__default_timeout = timeout
# The write_timeout is very different than the connection and read timeouts
# above. It relates to how long an action takes to complete. Any
# default value we choose here is likely to cause problems---either
# by being too short and giving up too early on a lengthy action or
# being too long and delaying the report of a failure.
cls.__default_write_timeout = write_timeout
# TODO Is there a good reason to prohibit setting these three timeout
# properties?
@classmethod
def set_default_timeout(cls, **kwargs):
warnings.warn(
"set_default_timeout() will be removed "
"in a future release. Use set_defaults() instead."
)
cls.set_defaults(**kwargs)
@property
def connection_timeout(self):
return self._connection_timeout
@property
def timeout(self):
return self._timeout
@property
def write_timeout(self):
return self._write_timeout
def __getnewargs_ex__(self):
args, kwargs = super().__getnewargs_ex__()
# 'value' shows up in the EpicsSignal repr, but should not be used to
# copy the Signal
kwargs.pop('value', None)
return (args, kwargs)
def _initial_metadata_callback(self, pvname, cl_metadata):
'Control-layer callback: all initial metadata - control and status'
self._metadata_changed(pvname, cl_metadata, require_timestamp=True,
update=True, from_monitor=False)
self._received_first_metadata[pvname] = True
self._set_event_if_ready()
def _metadata_changed(self, pvname, cl_metadata, *, from_monitor,
update, require_timestamp=False):
'Notification: the metadata of a single PV has changed'
metadata = self._get_metadata_from_kwargs(
pvname, cl_metadata, require_timestamp=require_timestamp)
if update:
self._metadata.update(**metadata)
return metadata
def _pv_connected(self, pvname, conn, pv):
'Control-layer callback: PV has [dis]connected'
if self._destroyed:
return
was_connected = self.connected
if not conn:
self._signal_is_ready.clear()
self._metadata['connected'] = False
self._access_rights_valid[pvname] = False
self._connection_states[pvname] = conn
if conn and not self._received_first_metadata[pvname]:
pv.get_all_metadata_callback(self._initial_metadata_callback,
timeout=10)
self._set_event_if_ready()
if was_connected and not conn:
# Send a notification of disconnection
self._run_metadata_callbacks()
if self._auto_monitor:
if getattr(self, '_read_pvname', None) == pvname:
self._add_callback(pvname, pv, self._read_changed)
if getattr(self, '_setpoint_pvname', None) == pvname:
self._add_callback(pvname, pv, self._write_changed)
def _set_event_if_ready(self):
'''If connected and access rights received, set the "ready" event used
in wait_for_connection.'''
with self._metadata_lock:
already_connected = self._metadata['connected']
if self._destroyed or already_connected:
return
elif not all([*self._connection_states.values(),
*self._access_rights_valid.values(),
*self._received_first_metadata.values()]):
if self._metadata['connected']:
self._metadata['connected'] = False
# subs are run in _pv_connected
return
self._metadata['connected'] = True
self._signal_is_ready.set()
self._run_metadata_callbacks()
def _pv_access_callback(self, read_access, write_access, pv):
'Control-layer callback: PV access rights have changed'
self._access_rights_valid[pv.pvname] = True
@property
def as_string(self):
'''Attempt to cast the EPICS PV value to a string by default'''
return self._string
@property
def precision(self):