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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
|
.. _pv-label:
==============================
PV: Epics Process Variables
==============================
.. module:: pv
:synopsis: PV objects for Epics Channel Access
The :mod:`pv` module provides a higher-level class :class:`pv.PV`, which
creates a `PV` object for an EPICS Process Variable. A `PV` object has
both methods and attributes for accessing it's properties.
The :class:`PV` class
=======================
.. class:: PV(pvname[, callback=None[, form='time'[, verbose=False[, auto_monitor=None[, count=None[, connection_callback=None[, connection_timeout=None[, access_callback=None]]]]]]]] )
create a PV object for a named Epics Process Variable.
:param pvname: name of Epics Process Variable
:param callback: user-defined callback function on changes to PV value or state.
:type callback: callable, tuple, list or None
:param form: which epics *data type* to use: the 'native', 'time', or the 'ctrl' (Control) variant.
:type form: string, one of ('native','ctrl', or 'time')
:param verbose: whether to print out debugging messages
:type verbose: ``True``/``False``
:param auto_monitor: whether to automatically monitor the PV for changes.
:type auto_monitor: ``None``, ``True``, ``False``, or bitmask (see :ref:`pv-automonitor-label`)
:param count: number of data elements to return by default (see :ref:`here <pv-get-label>`)
:type count: int
:param connection_callback: user-defined function called on changes to PV connection status.
:type connection_callback: callable or ``None``
:param connection_timeout: time (in seconds) to wait for connection before giving up
:type connection_timeout: float or ``None``
:param access_callback: user-defined function called on changes to PV access rights
:type access_callback: callable or ``None``
Once created, a PV should (barring any network issues) automatically
connect and be ready to use.
>>> from epics import PV
>>> p = PV('XX:m1.VAL')
>>> print p.get()
>>> print p.count, p.type
The *pvname* is required, and is the name of an existing Process Variable.
The *callback* parameter specifies one or more python methods to be called
on changes, as discussed in more detail at :ref:`pv-callbacks-label`
The *connection_callback* parameter specifies a python method to be called
on changes to the connection status of the PV (that is, when it connects or
disconnects). This is discussed in more detail at :ref:`pv-connection_callbacks-label`
The *form* parameter specifies which of the three variants 'native', 'ctrl'
(Control) or 'time' (the default) to use for the PV. The 'native' form
returns just the value, the 'time' form includes the timestamp from the
server the PV lives on, as well as status information. The control form
includes several additional fields such as limits to the PV, which can be
useful in some cases. Also note that the additional 'ctrl' value fields
(see the :ref:`Table of Control Attributes <ctrlvars_table>`) can be
obtained with :meth:`get_ctrlvars` even for PVs of 'native' or 'time' form.
The *auto_monitor* parameter specifies whether the PV should be
automatically monitored. See :ref:`pv-automonitor-label` for a detailed
description of this.
The *verbose* parameter specifies more verbose output on changes, and is
intended for debugging purposes.
The *access_callback* parameter specifies a python method to be called on
changes to the access rights of the PV (read/write access changes). This
is discussed in more detail :ref:`here <pv-access-rights-callback-label>`.
methods
~~~~~~~~
A `PV` has several methods for getting and setting its value and defining
callbacks to be executed when the PV changes.
.. _pv-get-label:
.. method:: get([, count=None[, as_string=False[, as_numpy=True[, timeout=None[, use_monitor=True, [with_ctrlvars=False]]]]]])
get and return the current value of the PV
:param count: maximum number of array elements to return
:type count: integer or ``None``
:param as_string: whether to return the string representation of the value.
:type as_string: ``True``/``False``
:param as_numpy: whether to try to return a numpy array where appropriate.
:type as_string: ``True``/``False``
:param timeout: maximum time to wait for data before returning ``None``.
:type timeout: float or ``None``
:param use_monitor: whether to rely on monitor callbacks or explicitly get value now.
:type use_monitor: ``True``/``False``
see :ref:`pv-as-string-label` for details on how the string
representation is determined.
With the *as_numpy* option, an array PV (that is, a PV whose value has
more than one element) will be returned as a numpy array, provided the
numpy module is available. See :ref:`arrays-large-label` for a
discussion of strategies for how to best deal with very large arrays.
The *use_monitor* option controls whether the most recent value from the automatic
monitoring will be used or whether the value will be explicitly asked
for right now. Usually, you can rely on a PVs value being kept up to
date, and so the default here is ``True``. But, since network traffic
is not instantaneous and hard to predict, the value returned with
`use_monitor=True` may be out-of-date.
The *timeout* sets how long (in seconds) to wait for the value to be
sent. This only applies with `use_monitor=False`, or if the PV is not
automatically monitored. Otherwise, the most recently received value
will be sent immediately.
The *with_ctrlvars* option requests DBR_CTRL data, including control limits,
precision, and so on, in addition to the value normally returned. This metadata
will be available by accessing various attributes such as
``lower_ctrl_limit``.
See :ref:`pv-automonitor-label` for more on monitoring PVs and
:ref:`advanced-get-timeouts-label` for more details on what happens when
a :func:`pv.get` times out.
.. method:: get_with_metadata([, form=None, [count=None[, as_string=False[, as_numpy=True[, timeout=None[, use_monitor=True, [with_ctrlvars=False]]]]]]])
Returns a dictionary of the current value and associated metadata
:param form: EPICS *data type* to request: the 'native', or the 'ctrl' (Control) or 'time' variant. Defaults to the PV instance attribute ``form``.
:type form: {'native', 'time', 'ctrl', None}
:param count: maximum number of array elements to return
:type count: integer or ``None``
:param as_string: whether to return the string representation of the value.
:type as_string: ``True``/``False``
:param as_numpy: whether to try to return a numpy array where appropriate.
:type as_string: ``True``/``False``
:param timeout: maximum time to wait for data before returning ``None``.
:type timeout: float or ``None``
:param use_monitor: whether to rely on monitor callbacks or explicitly get value now.
:type use_monitor: ``True``/``False``
See ``PV.get``, above, for further notes on each of these parameters.
Each request to EPICS can optionally contain additional metadata associated
with the value. While ``PV.get`` updates the PV instance with any metadata,
``get_with_metadata`` will return the requested metadata and value in a
dictionary.
The exception is when the PV is set to auto-monitor and the `use_monitor`
parameter here is set. This means that both the value and metadata will
used the cached values instead of making a new request. Because of this,
the metadata and value returned here will be a full dictionary of all known
metadata for the PV instance.
.. method:: put(value[, wait=False[, timeout=30.0[, use_complete=False[, callback=None[, callback_data=None]]]]])
set the PV value, optionally waiting to return until processing has
completed, or setting the :attr:`put_complete` to indicate complete-ness.
:param value: value to set PV
:param wait: whether to wait for processing to complete (or time-out) before returning.
:type wait: ``True``/``False``
:param timeout: maximum time to wait for processing to complete before returning anyway.
:type timeout: float
:param use_complete: whether to use a built-in callback to set :attr:`put_complete`.
:type use_complete: ``True``/``False``
:param callback: user-supplied function to run when processing has completed.
:type callback: ``None`` or a valid python function
:param callback_data: extra data to pass on to a user-supplied callback function.
The `wait` and `callback` arguments, as well as the 'use_complete' / :attr:`put_complete`
attribute give a few options for knowing that a :meth:`put` has
completed. See :ref:`pv-putwait-label` for more details.
.. _pv-get-ctrlvars-label:
.. method:: get_ctrlvars()
returns a dictionary of the **control values** for the PV. This
dictionary may have many members, depending on the data type of PV. See
the :ref:`Table of Control Attributes <ctrlvars_table>` for details.
.. method:: get_timevars()
returns a dictionary of the **time values** for the PV, which
include `status`, `severity`, and the `timestamp` from the CA
server.
.. method:: poll([evt=1.e-4, [iot=1.0]])
poll for changes. This simply calls :meth:`epics.ca.poll`
:param evt: time to pass to :meth:`epics.ca.pend_event`
:type evt: float
:param iot: time to pass to :meth:`epics.ca.pend_io`
:type iot: float
.. method:: connect([timeout=None])
this explicitly connects a PV, and returns whether or not it has
successfully connected. It is probably not that useful, as connection
should happen automatically. See :meth:`wait_for_connection`.
:param timeout: maximum connection time, passed to :meth:`epics.ca.connect_channel`
:type timeout: float
:rtype: ``True``/``False``
if timeout is ``None``, the PVs connection_timeout parameter will be used. If that is also ``None``,
:data:`episc.ca.DEFAULT_CONNECTION_TIMEOUT` will be used.
.. method:: wait_for_connection([timeout=None])
this waits until a PV is connected, or has timed-out waiting for a
connection. Returns whether the connection has occurred.
:param timeout: maximum connection time.
:type timeout: float
:rtype: ``True``/``False``
if timeout is ``None``, the PVs connection_timeout parameter will be used. If that is also ``None``,
:data:`epics.ca.DEFAULT_CONNECTION_TIMEOUT` will be used.
.. method:: disconnect()
disconnect a PV, clearing all callbacks.
.. method:: reconnect()
reconnect (or try to) a disconnected PV.
.. method:: clear_auto_monitor()
turn off automatic monitoring of a PV. Note that this will suspend
all event callbacks on a PV at the CA level by calling
:func:`epics.ca.clear_subscription`, but will not clear the list of PVs
callbacks. This means that doing :meth:`reconnect` will resume
event processing including any callbacks or the PV.
.. method:: add_callback(callback=None[, index=None [, with_ctrlvars=True[, **kw]])
adds a user-defined callback routine to be run on each change event for
this PV. Returns the integer *index* for the callback.
:param callback: user-supplied function to run when PV changes.
:type callback: ``None`` or callable
:param index: identifying key for this callback
:param with_ctrlvars: whether to (try to) make sure that accurate ``control values`` will be sent to the callback.
:type index: ``None`` (integer will be produced) or immutable
:param kw: additional keyword/value arguments to pass to each execution of the callback.
:rtype: integer
Note that multiple callbacks can be defined, each having its own index
(a dictionary key, typically an integer). When a PV changes, all the
defined callbacks will be executed. They will be called in order (by
sorting the keys of the :attr:`callbacks` dictionary)
See also: :attr:`callbacks` attribute, :ref:`pv-callbacks-label`
.. method:: remove_callback(index=None)
remove a user-defined callback routine using supplied
:param index: index of user-supplied function, as returned by :meth:`add_callback`,
and also to key for this callback in the :attr:`callbacks` dictionary.
:type index: ``None`` or integer
:rtype: integer
If only one callback is defined an index=``None``, this will clear the
only defined callback.
See also: :attr:`callbacks` attribute, :ref:`pv-callbacks-label`
.. method:: clear_callbacks()
remove all user-defined callback routine.
.. method:: run_callbacks()
execute all user-defined callbacks right now, even if the PV has not
changed. Useful for debugging!
See also: :attr:`callbacks` attribute, :ref:`pv-callbacks-label`
.. method:: run_callback(index)
execute a particular user-defined callback right now, even if the PV
has not changed. Useful for debugging!
See also: :attr:`callbacks` attribute, :ref:`pv-callbacks-label`
.. method:: force_read_access_rights()
force a read of the access rights for a PV. Normally, a PV will
have access rights determined automatically and subscribe to
changes in access rights. But sometimes (especially 64-bit
Windows), the automatically reported values are wrong. This
methods will explicitly read the access rights.
attributes
~~~~~~~~~~
A PV object has many attributes, each associated with some property of the
underlying PV: its *value*, *host*, *count*, and so on. For properties
that can change, the PV attribute will hold the latest value for the
corresponding property, Most attributes are **read-only**, and cannot be
assigned to. The exception to this rule is the :attr:`value` attribute.
.. attribute:: value
The current value of the PV.
**Note**: The :attr:`value` attribute can be assigned to.
When read, the latest value will be returned, even if that means a
:meth:`get` needs to be called.
Assigning to :attr:`value` is equivalent to setting the value with the
:meth:`put` method.
>>> from epics import PV
>>> p1 = PV('xxx.VAL')
>>> print p1.value
1.00
>>> p1.value = 2.00
.. attribute:: char_value
The string representation of the string, as described in :meth:`get`.
.. attribute:: status
The PV status, which will be 1 for a Normal, connected PV.
.. attribute:: type
string describing data type of PV, such as `double`, `float`, `enum`, `string`,
`int`, `long`, `char`, or one of the `ctrl` or `time` variants of these, which
will be named `ctrl_double`, `time_enum`, and so on. See the
:ref:`Table of DBR Types <dbrtype_table>`
.. attribute:: ftype
The integer value (from the underlying C library) indicating the PV data
type according to :ref:`Table of DBR Types <dbrtype_table>`
.. attribute:: host
string of host machine provide this PV.
.. attribute:: count
number of data elements in a PV. 1 except for waveform PVs, where it
gives the number of elements in the waveform. For recent versions of
Epics Base (3.14.11 and later?), this gives the `.NORD` field, which
gives the number of elements last put into the PV and which may be less
than the maximum number allowed (see `nelm` below).
.. attribute:: nelm
number of data elements in a PV. 1 except for waveform PVs where it
gives the maximum number of elements in the waveform. For recent
versions of Epics Base (3.14.11 and later?), this gives the `.NELM`
parameter. See also the `count` attribute above.
.. attribute:: read_access
Boolean (``True``/``False``) for whether PV is readable
.. attribute:: write_access
Boolean (``True``/``False``) for whether PV is writable
.. attribute:: access
string describing read/write access. One of
'read/write','read-only','write-only', 'no access'.
.. attribute:: severity
severity value of PV. Usually 0 for PVs that are not in an alarm
condition.
.. attribute:: timestamp
floating point timestamp (relative to the POSIX time origin, not the
EPICS time origin) of the last event seen for this PV. Note that this
is will contain the timestamp from the Epics server if the PV object was
created with the ``form='time'`` option. Otherwise, the timestamp will
be set to time according to the client, indicating when the data arrive
from the server.
.. attribute:: posixseconds
Integer number of seconds (relative to the POSIX time origin, not the
EPICS time origin) of the last event seen for this PV. This will be set
only if the PV object was created with the ``form='time'`` option, and
will reflect the timestamp from the server. Otherwise, this value will
be 0 which can be used to signal that the `timestamp` attribute is from
the client.
.. attribute:: nanoseconds
Integer number of nanoseconds for the last event seen for this PV. This
will be set only if the PV object was created with the ``form='time'``
option, and will give higher time resolution than the `timestamp`
attribute.
.. attribute:: precision
number of decimal places of precision to use for float and double PVs
.. attribute:: units
string of engineering units for PV
.. attribute:: enum_strs
a list of strings for the enumeration states of this PV (for enum PVs)
.. attribute:: info
a string paragraph (ie, including newlines) showing much of the
information about the PV.
.. attribute:: upper_disp_limit
.. attribute:: lower_disp_limit
.. attribute:: upper_alarm_limit
.. attribute:: lower_alarm_limit
.. attribute:: lower_warning_limit
.. attribute:: upper_warning_limit
.. attribute:: upper_ctrl_limit
.. attribute:: lower_ctrl_limit
These are all the various kinds of limits for a PV.
.. attribute:: put_complete
a Boolean (``True``/``False``) value for whether the most recent
:meth:`put` has completed.
.. attribute:: callbacks
a dictionary of currently defined callbacks, to be run on changes to the
PV. This dictionary has integer keys (generally in increasing order of
when they were defined) which sets which order for executing the
callbacks. The values of this dictionary are tuples of `(callback,
keyword_arguments)`.
**Note**: The :attr:`callbacks` attribute can be assigned to or
manipulated directly. This is not recommended. Use the
methods :meth:`add_callback`, :meth:`remove_callback`, and
:meth:`clear_callbacks` instead of altering this dictionary directly.
.. attribute:: connection_callbacks
a simple list of connection callbacks: functions to be run when the
connection status of the PV changes. See
:ref:`pv-connection_callbacks-label` for more details.
.. attribute:: access_callbacks
an :attr:`list` of access callbacks: functions to be run when the
access rights of the PV changes. See
:ref:`pv-access-rights-callback-label` for more details.
.. _pv-as-string-label:
String representation for a PV
================================
The string representation for a `PV`, as returned either with the
*as_string* argument to :meth:`epics.ca.get` or from the :attr:`char_value`
attribute (they are equivalent) needs some further explanation.
The value of the string representation (hereafter, the :attr:`char_value`),
will depend on the native type and count of a `PV`.
:ref:`Table of String Representations <charvalue_table>`
.. _charvalue_table:
Table of String Representations: How raw data :attr:`value` is mapped
to :attr:`char_value` for different native data types.
=============== ========== ==============================
*data types* *count* *char_value*
=============== ========== ==============================
string 1 = value
char 1 = value
short 1 = str(value)
long 1 = str(value)
enum 1 = enum_str[value]
double 1 = ("%%.%if" % (precision)) % value
float 1 = ("%%.%if" % (precision)) % value
char > 1 = long string from bytes in array
all others > 1 = <array size=*count*, type=*type*>
=============== ========== ==============================
For double/float values with large exponents, the formatting will be
`("%%.%ig" % (precision)) % value`. For character waveforms (*char* data
with *count* > 1), the :attr:`char_value` will be set according to::
>>> firstnull = val.index(0)
>>> if firstnull == -1: firstnull= len(val)
>>> char_value = ''.join([chr(i) for i in val[:firstnull]).rstrip()
.. _pv-automonitor-label:
Automatic Monitoring of a PV
================================
When creating a PV, the *auto_monitor* parameter specifies whether the PV
should be automatically monitored or not. Automatic monitoring means that
an internal callback will be registered for changes. Any callbacks defined
by the user will be called by this internal callback when changes occur.
For most scalar-value PVs, this automatic monitoring is desirable, as the
PV will see all changes (and run callbacks) without any additional
interaction from the user. The PV's value will always be up-to-date and no
unnecessary network traffic is needed.
Possible values for :attr:`auto_monitor` are:
``False``
For some PVs, especially those that change much more rapidly than you care
about or those that contain large arrays as values, auto_monitoring can add
network traffic that you don't need. For these, you may wish to create
your PVs with *auto_monitor=False*. When you do this, you will need to
make calls to :meth:`get` to explicitly get the latest value.
``None``
The default value for *auto_monitor* is ``None``, and is set to
``True`` if the element count for the PV is smaller than
:data:`epics.ca.AUTOMONITOR_MAXLENGTH` (default of 65536). To suppress
monitoring of PVs with fewer array values, you will have to explicitly
turn *auto_monitor* to ``False``. For waveform arrays with more elements,
automatic monitoring will not be done unless you explicitly set
*auto_monitor=True*, or to an explicit mask. See
:ref:`arrays-large-label` for more details.
``True``
When *auto_monitor* is set to ``True``, the value will be monitored using
the default subscription mask set at :data:`epics.ca.DEFAULT_SUBSCRIPTION_MASK`.
This mask determines which kinds of changes cause the PV to update. By
default, the subscription updates when the PV value changes by more
than the monitor deadband, or when the PV alarm status changes. This
behavior is the same as the default in EPICS' *camonitor* tool.
*Mask*
It is also possible to request an explicit type of CA subscription by
setting *auto_monitor* to a numeric subscription mask made up of
dbr.DBE_ALARM, dbr.DBE_LOG and/or dbr.DBE_VALUE. This mask will be
passed directly to :meth:`epics.ca.create_subscription` An example would be::
pv1 = PV('AAA', auto_monitor=dbr.DBE_VALUE)
pv2 = PV('BBB', auto_monitor=dbr.DBE_VALUE|dbr.DBE_ALARM)
pv3 = PV('CCC', auto_monitor=dbr.DBE_VALUE|dbr.DBE_ALARM|dbr.DBE_LOG)
which will generate callbacks for pv1 only when the value of 'AAA'
changes, while pv2 will receive callbacks if the value or alarm state of
'BBB' changes, and pv3 will receive callbacks for all changes to 'CCC'.
Note that these dbr.DBE_**** constants are ORed together as a bitmask.
.. _pv-callbacks-label:
User-supplied Callback functions
================================
This section describes user-defined functions that are called when the
value of a PV changes. These callback functions are useful as they allow
you to be notified of changes without having to continually ask for a PVs
current value. Much of this information is similar to that in
:ref:`ca-callbacks-label` for the :mod:`ca` module, though there are some
important enhancements to callbacks on `PV` objects.
You can define more than one callback function per PV to be run on value
changes. These functions can be specified when creating a PV, with the
*callback* argument which can take either a single callback function or a
list or tuple of callback functions. After a PV has been created, you can
add callback functions with :meth:`add_callback`, remove them with
:meth:`remove_callback`, and explicitly run them with :meth:`run_callback`.
Each callback has an internal unique *index* (a small integer number) that
can be used for specifying which one to add, remove, and run.
When defining a callback function to be run on changes to a PV, it is
important to know two things:
1) how your function will be called.
2) what is permissible to do inside your callback function.
Callback functions will be called with several keyword arguments. You
should be prepared to have them passed to your function, and should always
include `**kw` to catch all arguments. Your callback will be sent the
following keyword parameters:
* `pvname`: the name of the pv
* `value`: the latest value
* `char_value`: string representation of value
* `count`: the number of data elements
* `ftype`: the numerical CA type indicating the data type
* `type`: the python type for the data
* `status`: the status of the PV (1 for OK)
* `precision`: number of decimal places of precision for floating point values
* `units`: string for PV units
* `severity`: PV severity
* `timestamp`: timestamp from CA server.
* `read_access`: read access (``True``/``False``)
* `write_access`: write access (``True``/``False``)
* `access`: string description of read- and write-access
* `host`: host machine and CA port serving PV
* `enum_strs`: the list of enumeration strings
* `upper_disp_limit`: upper display limit
* `lower_disp_limit`: lower display limit
* `upper_alarm_limit`: upper alarm limit
* `lower_alarm_limit`: lower alarm limit
* `upper_warning_limit`: upper warning limit
* `lower_warning_limit`: lower warning limit
* `upper_ctrl_limit`: upper control limit
* `lower_ctrl_limit`: lower control limit
* `chid`: integer channel ID
* `cb_info`: (index, self) tuple containing callback ID
and the PV object
Some of these may not be directly applicable to all PV data types, and some
values may be ``None`` if the control parameters have not yet been fetched with
:meth:`get_ctrlvars`.
It is important to keep in mind that the callback function will be run
*inside* a CA function, and cannot reliably make any other CA calls. It is
helpful to think "this all happens inside of a :func:`pend_event` call",
and in an epics thread that may or may not be the main thread of your
program. It is advisable to keep the callback functions short and not
resource-intensive. Consider strategies which use the callback only to
record that a change has occurred and then act on that change later --
perhaps in a separate thread, perhaps after :func:`pend_event` has
completed.
The `cb_info` parameter supplied to the callback needs special attention,
as it is the only non-Epics information passed. The `cb_info` parameter
will be a tuple containing (:attr:`index`, :attr:`self`) where
:attr:`index` is the key for the :attr:`callbacks` dictionary for the PV
and :attr:`self` *is* PV object. A principle use of this tuple is to
**remove the current callback** if an error happens, as for example in GUI
code if the widget that the callback is meant to update disappears.
.. _pv-connection_callbacks-label:
User-supplied Connection Callback functions
=============================================
A *connection* callback is a user-defined function that is called when the
connection status of a PV changes -- that is, when a PV initially
connects, disconnects or reconnects due to the process serving the PV going
away, or loss of network connection. A connection callback can be
specified when a PV is created, or can be added by appending to the
:attr:`connection_callbacks` list. If there is more than one connection
callback defined, they will all be run when the connection state changes.
A connection callback should be prepared to receive the following keyword arguments:
* `pvname`: the name of the pv
* `conn`: the connection status
where *conn* will be either ``True` or ``False``, specifying whether the PV is
now connected. A simple example is given below.
.. _pv-access-rights-callback-label:
User-supplied Access Rights Callback functions
===============================================
An *access rights* callback is a user-defined function that is called when the
access rights - read/write permissions - of a PV undergo changes. The callback
will be invoked upon successful initialization and at all events that change
a PV's access rights, including disconnection and reconnection events.
An *access rights* callback can be specified when a PV is created, or can be
added by appending to the :attr:`access_callbacks` list of the PV object.
If there are multiple access rights callbacks defined for a PV, they will all
be run on access rights events.
.. _pv-putwait-label:
Put with wait, put callbacks, and put_complete
========================================================
Some EPICS records take a significant amount of time to fully process, and
sometimes you want to wait until the processing completes before going on.
There are a few ways to accomplish this. First, one can simply wait until
the processing is done::
import epics
p = epics.PV('XXX')
p.put(1.0, wait=True)
print 'Done'
This will hang until the processing of the PV completes (motor moving, etc)
before printing 'Done'. You can also specify a maximum time to wait -- a
*timeout* (in seconds)::
p.put(1.0, wait=True, timeout=30)
which will wait up to 30 seconds. For the pedantic, this timeout should
not be used as an accurate clock -- the actual wait time may be slightly
longer.
A second method is to use the 'use_complete' option and watch for the
:attr:`put_complete` attribute to become ``True`` after a :meth:`put`. This is
somewhat more flexible than using `wait=True` as above, because you can more
carefully control how often you look for a :meth:`put` to complete, and
what to do in the interim. A simple example would be::
p.put(1.0, use_complete=True)
waiting = True
while waiting:
time.sleep(0.001)
waiting = not p.put_complete
An additional advantage of this approach is that you can easily wait for
multiple PVs to complete with python's built-in *all* function, as with::
pvgroup = (epics.PV('XXX'), epics.PV('YYY'), epics.PV('ZZZ'))
newvals = (1.0, 2.0, 3.0)
for pv, val in zip(pvgroup, newvals):
pv.put(val, use_complete=True)
waiting = True
while waiting:
time.sleep(0.001)
waiting = not all([pv.put_complete for pv in pvgroup])
print 'All puts are done!'
For maximum flexibility, one can all define a *put callback*, a function to
be run when the :meth:`put` has completed. This function requires a
*pvname* keyword argument, but will receive no others, unless you pass in
data with the *callback_data* argument (which should be dict-like) to
:meth:`put`. A simple example would be::
pv = epics.PV('XXX')
def onPutComplete(pvname=None, **kws):
print 'Put done for %s' % pvname
pv.put(1.0, callback=onPutComplete)
.. _pv-cache-label:
The :func:`get_pv` function and :attr:`_PVcache_` cache of PVs
============================================================================
As mentioned in the previous chapter, a cache of PVs is maintained for each
process using pyepics. When using :func:`epics.caget`, :func:`epics.caput`
and so forth, or when creating a :class:`PV` directly, the corresponding PV
is kept in a global cache, held in :attr:`pv._PVcache_`.
The function :func:`get_pv` will retrieve the named PV from this cache, or
create a new :class:`PV` if one is not found. In long-running or complex
processes, it is not unusual to access a particular PV many times, perhaps
calling a function that creates a PV but only keeping that PV object for
the life of the function. Using :func:`get_pv` instead of creating a
:class:`PV` can improve performance (the PV is already connected) and is
highly recommended.
.. function:: get_pv(pvname[, form='time'[, connect=False[, timeout=5[, context=None[, **kws]]]]])
retrieves a PV from :attr:`_PVcache` or creates and returns a new PV.
:param pvname: name of Epics Process Variable
:param form: which epics *data type* to use: the 'native' , or the 'ctrl' (Control) or 'time' variant.
:type form: string, one of ('native','ctrl', or 'time')
:param connect: whether to wait for the PV to connect.
:type connect: ``True``/``False``
:param timeout: maximum time to wait (in seconds) for value before returning None.
:type timeout: float or ``None``
:param context: integer threading context.
:type context: integer or ``None`` (default)
Additional keywords are passed directly to :class:`PV`.
.. attribute:: _PVcache_
A cache of :class:`PV` objects for the process.
.. _pv-examples-label:
Examples
============
Some simple examples using PVs follow.
Basic Use
~~~~~~~~~~~~
The simplest approach is to simply create a PV and use its :attr:`value`
attribute:
>>> from epics import PV
>>> p1 = PV('xxx.VAL')
>>> print p1.value
1.00
>>> p1.value = 2.00
The *print p1.value* line automatically fetches the current PV value. The
*p1.value = 2.00* line does a :func:`put` to set the value, causing any
necessary processing over the network.
The above example is equivalent to
>>> from epics import PV
>>> p1 = PV('xxx.VAL')
>>> print p1.get()
1.00
>>> p1.put(value = 2.00)
To get a string representation of the value, you can use either
>>> print p1.get(as_string=True)
'1.000'
or, equivalently
>>> print p1.char_value
'1.000'
Requests including Metadata
~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is also possible to get the metadata associated with a single Channel Access
request using :func:`get_with_metadata`::
>>> from epics import PV
>>> p1 = PV('xxx.VAL', form='time')
>>> print(p1.get())
1.00
>>> p1.get_with_metadata()
{'status': 0,
'severity': 0,
'timestamp': 1543429156.811018,
'posixseconds': 1543429156.0,
'nanoseconds': 811018603,
'value': 1.0}
>>> print(p1.get_with_metadata(form='ctrl'))
{'upper_disp_limit': 100.0,
'lower_disp_limit': -100.0,
'upper_alarm_limit': 0.0,
'upper_warning_limit': 0.0,
'lower_warning_limit': 0.0,
'lower_alarm_limit': 0.0,
'upper_ctrl_limit': 100.0,
'lower_ctrl_limit': -100.0,
'precision': 3,
'units': 'deg',
'status': 0,
'severity': 0,
'value': 1.0}
Example of using info and more properties examples
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A PV has many attributes. This can be seen from its *info* paragraph:
>>> import epics
>>> p = epics.PV('13IDA:m3')
>>> print p.info
== 13IDA:m3 (native_double) ==
value = 0.2
char_value = '0.200'
count = 1
type = double
units = mm
precision = 3
host = ioc13ida.cars.aps.anl.gov:5064
access = read/write
status = 0
severity = 0
timestamp = 1274809682.967 (2010-05-25 12:48:02.967364)
upper_ctrl_limit = 5.49393415451
lower_ctrl_limit = -14.5060658455
upper_disp_limit = 5.49393415451
lower_disp_limit = -14.5060658455
upper_alarm_limit = 0.0
lower_alarm_limit = 0.0
upper_warning_limit = 0.0
lower_warning_limit = 0.0
PV is internally monitored, with 0 user-defined callbacks:
=============================
The individual attributes can also be accessed as below. Many of these
(the *control attributes*, see :ref:`Table of Control Attributes
<ctrlvars_table>`) will not be filled in until either the :attr:`info`
attribute is accessed or until :meth:`get_ctrlvars` is called.
>>> print p.type
double
>>> print p.units, p.precision, p.lower_disp_limit
mm 3 -14.5060658455
Getting a string value
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is not uncommon to want a string representation of a PVs value, for
example to show in a display window or to write to some report. For string
PVs and integer PVs, this is a simple task. For floating point values,
there is ambiguity how many significant digits to show. EPICS PVs all have
a :attr:`precision` field. which sets how many digits after the decimal
place should be described. In addition, for ENUM PVs, it would be
desire able to get at the name of the ENUM state, not just its integer
value.
To get the string representation of a PVs value, use either the
:attr:`char_value` attribute or the `as_string=True` argument to :meth:`get`
Example of :meth:`put`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To put a new value to a variable, either of these two approaches can be
used:
>>> import epics
>>> p = epics.PV('XXX')
>>> p.put(1.0)
Or (equivalently):
>>> import epics
>>> p = epics.PV('XXX')
>>> p.value = 1.0
The :attr:`value` attribute is the only attribute that can be set.
Example of simple callback
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is often useful to get a notification of when a PV changes. In general,
it would be inconvenient (and possibly inefficient) to have to continually
ask if a PVs value has changed. Instead, it is better to set a *callback*
function: a function to be run when the value has changed.
A simple example of this would be::
import epics
import time
def onChanges(pvname=None, value=None, char_value=None, **kw):
print 'PV Changed! ', pvname, char_value, time.ctime()
mypv = epics.PV(pvname)
mypv.add_callback(onChanges)
print 'Now wait for changes'
t0 = time.time()
while time.time() - t0 < 60.0:
time.sleep(1.e-3)
print 'Done.'
This first defines a *callback function* called `onChanges()` and then
simply waits for changes to happen. Note that the callback function should
take keyword arguments, and generally use `**kw` to catch all arguments.
See :ref:`pv-callbacks-label` for more details.
Example of connection callback
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A connection callback:
.. literalinclude:: ../tests/pv_connection_callback.py
Example of an access rights callback
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Associating an access rights callback with a PV::
import epics
import time
def access_rights_callback(read_access, write_access, pv=None):
print "%s - read=%s, write=%s" % (pv.pvname, read_access, write_access)
# should immediately see the message upon connection
apv = epics.PV('pvname', access_callback=access_rights_callback)
try:
start = time.time()
while (time.time() - start) < 30:
time.sleep(0.25)
except KeyboardInterrupt:
pass
|