# How to

This is a small list of how-tos specific to PyTango. A more general Tango how-to list can be found here.

## How to contribute

Everyone is welcome to contribute to PyTango project. If you don’t feel comfortable with writing core PyTango we are looking for contributors to documentation or/and tests.

It refers to the next section, see How to Contribute.

## Check the default TANGO host

The default TANGO host can be defined using the environment variable `TANGO_HOST` or in a tangorc file (see Tango environment variables for complete information)

To check what is the current value that TANGO uses for the default configuration simple do:

    >>> import tango
    >>> tango.ApiUtil.get_env_var("TANGO_HOST")
    'homer.simpson.com:10000'

## Check TANGO version

There are two library versions you might be interested in checking: The PyTango version:

    >>> import tango
    >>> tango.__version__
    '9.5.0'
    >>> tango.__version_info__
    (9, 5, 0)

and the Tango C++ library version that PyTango was compiled with:

    >>> import tango
    >>> tango.constants.TgLibVers
    '9.5.0'

## Start server from command line

To start server from the command line execute the following command:

    $ python <server_file>.py <instance_name>
    Ready to accept request

To run server without database use option -nodb.

    $ python <server_file>.py <instance_name> -nodb -port 10000
    Ready to accept request

Note, that to start server in this mode you should provide a port with either --post, or --ORBendPoint option

Additionally, you can use the following options:

> -h, -?, --help : show usage help

> -v, --verbose: set the trace level. Can be user in count way: -vvvv set level to 4 or –verbose –verbose set to 2

> -vN: directly set the trace level to N, e.g., -v3 - set level to 3

> --file <file_name>: start a device server using an ASCII file instead of the Tango database

> --host <host_name>: force the host from which server accept requests

> --port <port>: force the port on which the device server listens

> --nodb: run server without DB

> --dlist <dev1,dev2,etc>: the device name list. This option is supported only with the -nodb option

> --ORBendPoint giop:tcp:<host>:<port>: Specifying the host from which server accept requests and port on which the device server listens.

Note: any ORB option can be provided if it starts with -ORB<option>

Additionally in Windows the following option can be used:

> -i: install the service

> -s: install the service and choose the automatic startup mode

> -u: uninstall the service

> --dbg: run in console mode to debug service. The service must have been installed prior to use it.

Note: all long-options can be provided in non-POSIX format: -port or --port etc…

## Report a bug

Bugs can be reported as issues in PyTango GitLab.

It is also helpful if you can put in the issue description the PyTango information. It can be a dump of:

    $ python -c "from tango.utils import info; print(info())"

## Test the connection to the Device and get it’s current state

One of the most basic examples is to get a reference to a device and determine if it is running or not:

     1from tango import DeviceProxy
     2
     3# Get proxy on the tango_test1 device
     4print("Creating proxy to TangoTest device...")
     5tango_test = DeviceProxy("sys/tg_test/1")
     6
     7# ping it
     8print(tango_test.ping())
     9
    10# get the state
    11print(tango_test.state())

## Read and write attributes

Basic read/write attribute operations:

     1from tango import DeviceProxy
     2
     3# Get proxy on the tango_test1 device
     4print("Creating proxy to TangoTest device...")
     5tango_test = DeviceProxy("sys/tg_test/1")
     6
     7# Read a scalar attribute. This will return a tango.DeviceAttribute
     8# Member 'value' contains the attribute value
     9scalar = tango_test.read_attribute("long_scalar")
    10print(f"Long_scalar value = {scalar.value}")
    11
    12# PyTango provides a shorter way:
    13scalar = tango_test.long_scalar
    14print(f"Long_scalar value = {scalar}")
    15
    16# Read a spectrum attribute
    17spectrum = tango_test.read_attribute("double_spectrum")
    18# ... or, the shorter version:
    19spectrum = tango_test.double_spectrum
    20
    21# Write a scalar attribute
    22scalar_value = 18
    23tango_test.write_attribute("long_scalar", scalar_value)
    24
    25#  PyTango provides a shorter way:
    26tango_test.long_scalar = scalar_value
    27
    28# Write a spectrum attribute
    29spectrum_value = [1.2, 3.2, 12.3]
    30tango_test.write_attribute("double_spectrum", spectrum_value)
    31# ... or, the shorter version:
    32tango_test.double_spectrum = spectrum_value
    33
    34# Write an image attribute
    35image_value = [ [1, 2], [3, 4] ]
    36tango_test.write_attribute("long_image", image_value)
    37# ... or, the shorter version:
    38tango_test.long_image = image_value

Note that the values got when reading a spectrum or an image are numpy arrays. This results in a faster and more memory efficient PyTango. You can also use numpy to specify the values when writing attributes, especially if you know the exact attribute type:

     1import numpy
     2from tango import DeviceProxy
     3
     4# Get proxy on the tango_test1 device
     5print("Creating proxy to TangoTest device...")
     6tango_test = DeviceProxy("sys/tg_test/1")
     7
     8data_1d_long = numpy.arange(0, 100, dtype=numpy.int32)
     9
    10tango_test.long_spectrum = data_1d_long
    11
    12data_2d_float = numpy.zeros((10,20), dtype=numpy.float64)
    13
    14tango_test.double_image = data_2d_float

## Execute commands

As you can see in the following example, when scalar types are used, the Tango binding automagically manages the data types, and writing scripts is quite easy:

     1from tango import DeviceProxy
     2
     3# Get proxy on the tango_test1 device
     4print("Creating proxy to TangoTest device...")
     5tango_test = DeviceProxy("sys/tg_test/1")
     6
     7# First use the classical command_inout way to execute the DevString command
     8# (DevString in this case is a command of the Tango_Test device)
     9
    10result = tango_test.command_inout("DevString", "First hello to device")
    11print(f"Result of execution of DevString command = {result}")
    12
    13# the same can be achieved with a helper method
    14result = tango_test.DevString("Second Hello to device")
    15print(f"Result of execution of DevString command = {result}")
    16
    17# Please note that argin argument type is automatically managed by python
    18result = tango_test.DevULong(12456)
    19print(f"Result of execution of DevULong command = {result}")

## Execute commands with more complex types

In this case you have to use put your arguments data in the correct python structures:

     1from tango import DeviceProxy
     2
     3# Get proxy on the tango_test1 device
     4print("Creating proxy to TangoTest device...")
     5tango_test = DeviceProxy("sys/tg_test/1")
     6
     7# The input argument is a DevVarLongStringArray so create the argin
     8# variable containing an array of longs and an array of strings
     9argin = ([1,2,3], ["Hello", "TangoTest device"])
    10
    11result = tango_test.DevVarLongStringArray(argin)
    12print(f"Result of execution of DevVarLongArray command = {result}")

## Work with Groups

Todo

write this how to

## Handle errors

Todo

write this how to

For now check Exception API.

## Registering devices

Here is how to define devices in the Tango DataBase:

     1from tango import Database, DbDevInfo
     2
     3#  A reference on the DataBase
     4db = Database()
     5
     6# The 3 devices name we want to create
     7# Note: these 3 devices will be served by the same DServer
     8new_device_name1 = "px1/tdl/mouse1"
     9new_device_name2 = "px1/tdl/mouse2"
    10new_device_name3 = "px1/tdl/mouse3"
    11
    12# Define the Tango Class served by this  DServer
    13new_device_info_mouse = DbDevInfo()
    14new_device_info_mouse._class = "Mouse"
    15new_device_info_mouse.server = "ds_Mouse/server_mouse"
    16
    17# add the first device
    18print("Creating device: %s" % new_device_name1)
    19new_device_info_mouse.name = new_device_name1
    20db.add_device(new_device_info_mouse)
    21
    22# add the next device
    23print("Creating device: %s" % new_device_name2)
    24new_device_info_mouse.name = new_device_name2
    25db.add_device(new_device_info_mouse)
    26
    27# add the third device
    28print("Creating device: %s" % new_device_name3)
    29new_device_info_mouse.name = new_device_name3
    30db.add_device(new_device_info_mouse)

### Setting up device properties

A more complex example using python subtilities. The following python script example (containing some functions and instructions manipulating a Galil motor axis device server) gives an idea of how the Tango API should be accessed from Python:

     1from tango import DeviceProxy
     2
     3# connecting to the motor axis device
     4axis1 = DeviceProxy("microxas/motorisation/galilbox")
     5
     6# Getting Device Properties
     7property_names = ["AxisBoxAttachement",
     8                  "AxisEncoderType",
     9                  "AxisNumber",
    10                  "CurrentAcceleration",
    11                  "CurrentAccuracy",
    12                  "CurrentBacklash",
    13                  "CurrentDeceleration",
    14                  "CurrentDirection",
    15                  "CurrentMotionAccuracy",
    16                  "CurrentOvershoot",
    17                  "CurrentRetry",
    18                  "CurrentScale",
    19                  "CurrentSpeed",
    20                  "CurrentVelocity",
    21                  "EncoderMotorRatio",
    22                  "logging_level",
    23                  "logging_target",
    24                  "UserEncoderRatio",
    25                  "UserOffset"]
    26
    27axis_properties = axis1.get_property(property_names)
    28for prop in axis_properties.keys():
    29    print("%s: %s" % (prop, axis_properties[prop][0]))
    30
    31# Changing Properties
    32axis_properties["AxisBoxAttachement"] = ["microxas/motorisation/galilbox"]
    33axis_properties["AxisEncoderType"] = ["1"]
    34axis_properties["AxisNumber"] = ["6"]
    35axis1.put_property(axis_properties)

## Using clients with multiprocessing

Since version 9.3.0 PyTango provides `cleanup()` which resets CORBA connection. This static function is needed when you want to use `tango` with `multiprocessing` in your client code.

In the case when both your parent process and your child process create `DeviceProxy`, `Database` or/and `AttributeProxy` your child process inherits the context from your parent process, i.e. open file descriptors, the TANGO and the CORBA state. Sharing the above objects between the processes may cause unpredictable errors, e.g., TRANSIENT_CallTimedout, unidentifiable C++ exception. Therefore, when you start a new process you must reset CORBA connection:

     1import time
     2import tango
     3
     4from multiprocessing import Process
     5
     6
     7class Worker(Process):
     8
     9    def __init__(self):
    10        Process.__init__(self)
    11
    12    def run(self):
    13        # reset CORBA connection
    14        tango.ApiUtil.cleanup()
    15
    16        proxy = tango.DeviceProxy('test/tserver/1')
    17
    18        stime = time.time()
    19        etime = stime
    20        while etime - stime < 1.:
    21            try:
    22                proxy.read_attribute("Value")
    23            except Exception as e:
    24                print(str(e))
    25            etime = time.time()
    26
    27
    28def runworkers():
    29    workers = [Worker() for _ in range(6)]
    30    for wk in workers:
    31        wk.start()
    32    for wk in workers:
    33        wk.join()
    34
    35
    36db = tango.Database()
    37dp = tango.DeviceProxy('test/tserver/1')
    38
    39for i in range(4):
    40    runworkers()

After cleanup() all references to `DeviceProxy`, `AttributeProxy` or `Database` objects in the current process become invalid and these objects need to be reconstructed.

## Multithreading - clients and servers

When performing Tango I/O from user-created threads, there can be problems. This is often more noticeable with event subscription/unsubscription, and when pushing events, but it could affect any Tango I/O.

A client subscribing and unsubscribing to events via a user thread may see a crash, a deadlock, or `Event channel is not responding anymore` errors.

A device server pushing events from a user-created thread (including asyncio callbacks) might see `Not able to acquire serialization (dev, class or process) monitor` errors.

As PyTango wraps the cppTango library, we need to consider how cppTango’s threads work. cppTango was originally developed at a time where C++ didn’t have standard threads. All the threads currently created in cppTango are “omni threads”, since this is what the omniORB library is using to create threads and since this implementation is available for free with omniORB.

In C++, users used to create omni threads in the past so there was no issue. Since C++11, C++ comes with an implementation of standard threads. cppTango is currently (version 9.4.1) not directly thread safe when a user is using C++11 standard threads or threads different than omni threads. This lack of thread safety includes threads created from Python’s `threading` module.

In an ideal future cppTango should protect itself, regardless of what type of threads are used. In the meantime, we need a work-around.

The work-around when using threads which are not omni threads is to create an object of the C++ class `omni_thread::ensure_self` in the user thread, just after the thread creation, and to delete this object only when the thread has finished its job. This `omni_thread::ensure_self` object provides a dummy omniORB ID for the thread. This ID is used when accessing thread locks within cppTango, so the ID must remain the same for the lifetime of the thread. Also note that this object MUST be released before the thread has exited, otherwise omniORB will throw an exception.

A Pythonic way to implement this work-around for multithreaded applications is available via the `EnsureOmniThread` class. It was added in PyTango version 9.3.2. This class is best used as a context handler to wrap the target method of the user thread. An example is shown below:

     1import tango
     2from threading import Thread
     3from time import sleep
     4
     5
     6def thread_task():
     7    with tango.EnsureOmniThread():
     8        eid = dp.subscribe_event(
     9            "double_scalar", tango.EventType.PERIODIC_EVENT, cb)
    10        while running:
    11            print(f"num events stored {len(cb.get_events())}")
    12            sleep(1)
    13        dp.unsubscribe_event(eid)
    14
    15
    16cb = tango.utils.EventCallback()  # print events to stdout
    17dp = tango.DeviceProxy("sys/tg_test/1")
    18dp.poll_attribute("double_scalar", 1000)
    19thread = Thread(target=thread_task)
    20running = True
    21thread.start()
    22sleep(5)
    23running = False
    24thread.join()

Another way to create threads in Python is the `concurrent.futures.ThreadPoolExecutor`. The problem with this is that the API does not provide an easy way for the context handler to cover the lifetime of the threads, which are created as daemons. One option is to at least use the context handler for the functions that are submitted to the executor. I.e., `executor.submit(thread_task)`. This is not guaranteed to work. A second option to investigate (if using at least Python 3.7) is the `initializer` argument which could be used to ensure a call to the `__enter__()` method for a thread-specific instance of `EnsureOmniThread`. However, calling the `__exit__()` method on the corresponding object at shutdown is a problem. Maybe it could be submitted as work.

## Write a server

Before reading this chapter you should be aware of the TANGO basic concepts. This chapter does not explain what a Tango device or a device server is. This is explained in detail in the Tango control system manual

Since version 8.1, PyTango provides a helper module which simplifies the development of a Tango device server. This helper is provided through the `tango.server` module.

Here is a simple example on how to write a Clock device server using the high level API

     1 import time
     2 from tango.server import Device, device_property, attribute, command, pipe
     3
     4
     5 class Clock(Device):
     6
     7     model = device_property(dtype=str)
     8
     9     @attribute
    10     def time(self):
    11         return time.time()
    12
    13     @command(dtype_in=str, dtype_out=str)
    14     def strftime(self, format):
    15         return time.strftime(format)
    16
    17     @pipe
    18     def info(self):
    19         return ('Information',
    20                 dict(manufacturer='Tango',
    21                      model=self.model,
    22                      version_number=123))
    23
    24
    25 if __name__ == "__main__":
    26     Clock.run_server()

line 2

  import the necessary symbols

line 5

  tango device class definition. A Tango device must inherit from `tango.server.Device`

line 7

  definition of the model property. Check the `device_property` for the complete list of options

line 9-11

  definition of the time attribute. By default, attributes are double, scalar, read-only. Check the `attribute` for the complete list of attribute options.

line 13-15

  the method strftime is exported as a Tango command. In receives a string as argument and it returns a string. If a method is to be exported as a Tango command, it must be decorated as such with the `command()` decorator

line 17-22

  definition of the info pipe. Check the `pipe` for the complete list of pipe options.

line 26

  start the Tango run loop. This method automatically determines the Python class name and exports it as a Tango class. For more complicated cases, check `run()` for the complete list of options

There is a more detailed clock device server in the examples/Clock folder.

Here is a more complete example on how to write a PowerSupply device server using the high level API. The example contains:

1. a host device property

2. a port class property

3. the standard initialisation method called init_device

4. a read/write double scalar expert attribute current

5. a read-only double scalar attribute called voltage

6. a read-only double image attribute called noise

7. a read/write float scalar attribute range, defined with pythonic-style decorators, which can be always read, but conditionally written

8. a read/write float scalar attribute compliance, defined with alternative decorators

9. an output_on_off command

     1from time import time
     2from numpy.random import random_sample
     3
     4from tango import AttrQuality, AttrWriteType, DevState, DispLevel, AttReqType
     5from tango.server import Device, attribute, command
     6from tango.server import class_property, device_property
     7
     8
     9class PowerSupply(Device):
    10    _my_current = 2.3456
    11    _my_range = 0.0
    12    _my_compliance = 0.0
    13    _output_on = False
    14
    15    host = device_property(dtype=str)
    16    port = class_property(dtype=int, default_value=9788)
    17
    18    def init_device(self):
    19        super().init_device()
    20        self.info_stream(f"Power supply connection details: {self.host}:{self.port}")
    21        self.set_state(DevState.ON)
    22        self.set_status("Power supply is ON")
    23
    24    current = attribute(
    25        label="Current",
    26        dtype=float,
    27        display_level=DispLevel.EXPERT,
    28        access=AttrWriteType.READ_WRITE,
    29        unit="A",
    30        format="8.4f",
    31        min_value=0.0,
    32        max_value=8.5,
    33        min_alarm=0.1,
    34        max_alarm=8.4,
    35        min_warning=0.5,
    36        max_warning=8.0,
    37        fget="get_current",
    38        fset="set_current",
    39        doc="the power supply current",
    40    )
    41
    42    noise = attribute(
    43        label="Noise",
    44        dtype=((float,),),
    45        max_dim_x=1024,
    46        max_dim_y=1024,
    47        fget="get_noise",
    48    )
    49
    50    @attribute
    51    def voltage(self):
    52        return 10.0
    53
    54    def get_current(self):
    55        return self._my_current
    56
    57    def set_current(self, current):
    58        print("Current set to %f" % current)
    59        self._my_current = current
    60
    61    def get_noise(self):
    62        return random_sample((1024, 1024))
    63
    64    range = attribute(label="Range", dtype=float)
    65
    66    @range.setter
    67    def range(self, new_range):
    68        self._my_range = new_range
    69
    70    @range.getter
    71    def current_range(self):
    72        return self._my_range, time(), AttrQuality.ATTR_WARNING
    73
    74    @range.is_allowed
    75    def can_range_be_changed(self, req_type):
    76        if req_type == AttReqType.WRITE_REQ:
    77            return not self._output_on
    78        return True
    79
    80    compliance = attribute(label="Compliance", dtype=float)
    81
    82    @compliance.read
    83    def compliance(self):
    84        return self._my_compliance
    85
    86    @compliance.write
    87    def new_compliance(self, new_compliance):
    88        self._my_compliance = new_compliance
    89
    90    @command(dtype_in=bool, dtype_out=bool)
    91    def output_on_off(self, on_off):
    92        self._output_on = on_off
    93        return self._output_on
    94
    95
    96if __name__ == "__main__":
    97    PowerSupply.run_server()

## Use Python type hints when declaring a device

Note

This is an experimental feature, API may change in further releases!

Starting from PyTango 9.5.0 the data type of properties, attributes and commands in high-level API device servers can be declared using Python type hints.

This is the same simple PowerSupply device server, but using type hints in various ways:

     1 from time import time
     2 from numpy.random import random_sample
     3
     4 from tango import AttrQuality, AttrWriteType, DevState, DispLevel, AttReqType
     5 from tango.server import Device, attribute, command
     6 from tango.server import class_property, device_property
     7
     8
     9 class PowerSupply(Device):
    10     _my_current = 2.3456
    11     _my_range = 0
    12     _my_compliance = 0.0
    13     _output_on = False
    14
    15     host: str = device_property()
    16     port: int = class_property(default_value=9788)
    17
    18     def init_device(self):
    19         super().init_device()
    20         self.info_stream(f"Power supply connection details: {self.host}:{self.port}")
    21         self.set_state(DevState.ON)
    22         self.set_status("Power supply is ON")
    23
    24     current: float = attribute(
    25         label="Current",
    26         display_level=DispLevel.EXPERT,
    27         access=AttrWriteType.READ_WRITE,
    28         unit="A",
    29         format="8.4f",
    30         min_value=0.0,
    31         max_value=8.5,
    32         min_alarm=0.1,
    33         max_alarm=8.4,
    34         min_warning=0.5,
    35         max_warning=8.0,
    36         fget="get_current",
    37         fset="set_current",
    38         doc="the power supply current",
    39     )
    40
    41     noise: list[list[float]] = attribute(
    42         label="Noise", max_dim_x=1024, max_dim_y=1024, fget="get_noise"
    43     )
    44
    45     @attribute
    46     def voltage(self) -> float:
    47         return 10.0
    48
    49     def get_current(self):
    50         return self._my_current
    51
    52     def set_current(self, current):
    53         print("Current set to %f" % current)
    54         self._my_current = current
    55
    56     def get_noise(self):
    57         return random_sample((1024, 1024))
    58
    59     range = attribute(label="Range")
    60
    61     @range.getter
    62     def current_range(self) -> tuple[float, float, AttrQuality]:
    63         return self._my_range, time(), AttrQuality.ATTR_WARNING
    64
    65     @range.setter
    66     def range(self, new_range: float):
    67         self._my_range = new_range
    68
    69     @range.is_allowed
    70     def can_range_be_changed(self, req_type):
    71         if req_type == AttReqType.WRITE_REQ:
    72             return not self._output_on
    73         return True
    74
    75     compliance = attribute(label="Compliance")
    76
    77     @compliance.read
    78     def compliance(self) -> float:
    79         return self._my_compliance
    80
    81     @compliance.write
    82     def new_compliance(self, new_compliance: float):
    83         self._my_compliance = new_compliance
    84
    85     @command
    86     def output_on_off(self, on_off: bool) -> bool:
    87         self._output_on = on_off
    88         return self._output_on
    89
    90
    91 if __name__ == "__main__":
    92     PowerSupply.run_server()

Note

To defining DevEncoded attribute you can use type hints tuple[str, bytes] and tuple[str, bytearray] (or tuple[str, bytes, float, AttrQuality] and tuple[str, bytearray, float, AttrQuality]).

Type hints tuple[str, str] (or tuple[str, str, float, AttrQuality]) will be recognized as SPECTRUM DevString attribute with max_dim_x=2

If you want to create DevEncoded attribute with (str, str) return you have to use dtype kwarg

Properties

To define device property you can use:

    host: str = device_property()

If you want to create list property you can use tuple[], list[] or numpy.typing.NDArray[] annotation:

    channels: tuple[int] = device_property()

or

    channels: list[int] = device_property()

or

    channels: numpy.typing.NDArray[np.int_] = device_property()

Attributes For the attributes you can use one of the following patterns:

    voltage: float = attribute()

or

    voltage = attribute()

    def read_voltage(self) -> float:
        return 10.0

or

    voltage = attribute(fget="query_voltage")

    def query_voltage(self) -> float:
        return 10.0

or

    @attribute
    def voltage(self) -> float:
        return 10.0

For writable (AttrWriteType.READ_WRITE and AttrWriteType.WRITE) attributes you can also define the type in write functions.

Note

Defining the type hint of a READ_WRITE attribute only in the write function is not recommended as it can lead to inconsistent code.

    data_to_save = attribute(access=AttrWriteType.WRITE)

    # since WRITE attribute can have only write method,
    # its type can be defined here
    def write_data_to_save(self, data: float)
        self._hardware.save(value)

Note

If you provide a type hint in several places (e.g., dtype kwarg and read function): there is no check, that types are the same and attribute type will be taken according to the following priority:

1. dtype kwarg

2. attribute assignment

3. read function

4. write function

E.g., if you create the following attribute:

    voltage: int = attribute(dtype=float)

    def read_voltage(self) -> str:
        return 10

the attribute type will be float

SPECTRUM and IMAGE attributes

As for the case of properties, the SPECTRUM and IMAGE attributes can be defined by tuple[], list[] or numpy.typing.NDArray[] annotation.

Note

Since there isn’t yet official support for numpy.typing.NDArray[] shape definitions (as at 12 October 2023: https://github.com/numpy/numpy/issues/16544) you must provide a dformat kwarg as well as max_dim_x (and, if necessary, max_dim_y):

    @attribute(dformat=AttrDataFormat.SPECTRUM, max_dim_x=3)
    def get_time(self) -> numpy.typing.NDArray[np.int_]:
        return hours, minutes, seconds

In case of tuple[], list[] you can automatically specify attribute dimension:

    @attribute
    def get_time(self) -> tuple[int, int, int]:
        return hours, minutes, seconds

or you can use max_x_dim(max_y_dim) kwarg with just one element in tuple/list:

    @attribute(max_x_dim=3)
    def get_time(self) -> list[int]: # can be also tuple[int]
        return hours, minutes, seconds

Note

If you provide both max_x_dim(max_y_dim) kwarg and use tuple[] annotation, kwarg will have priority

Note

Mixing element types within a spectrum(image) attribute definition is not supported by Tango and will raise a RuntimeError.

e.g., attribute

    @attribute(max_x_dim=3)
    def get_time(self) -> tuple[float, str]:
        return hours, minutes, seconds

will result in RuntimeError

Dimension of SPECTRUM attributes can be also taken from annotation:

    @attribute()
    def not_matrix(self) -> tuple[tuple[bool, bool], tuple[bool, bool]]:
        return [[False, True],[True, False]]

Note

max_y will be len of outer tuple (or list), max_x - len of the inner. Note, that all inner tuples(lists) must be the same length

e.g.,

    tuple[tuple[bool, bool], tuple[bool, bool], tuple[bool, bool]]

will result in max_y=3, max_x=2

while

    tuple[tuple[bool, bool], tuple[bool], tuple[bool]]

will result in RuntimeError

Commands

Declaration of commands is the same as declaration of attributes with decorators:

    @command
    def set_and_check_voltage(self, voltage_to_set: float) -> float:
        device.set_voltage(voltage_to_set)
        return device.get_voltage()

Note

If you provide both type hints and dtype kwargs, the kwargs take priority:

e.g.,

    @command(dtype_in=float, dtype_out=float)
    def set_and_check_voltage(self, voltage_to_set: str) -> str:
        device.set_voltage(voltage_to_set)
        return device.get_voltage()

will be a command that accepts float and returns float.

As in case of attributes, the SPECTRUM commands can be declared with tuple[] or list[] annotation:

    @command
    def set_and_check_voltages(self, voltages_set: tuple[float, float]) -> tuple[float, float]:
        device.set_voltage(channel1, voltages_set[0])
        device.set_voltage(channel2, voltages_set[1])
        return device.get_voltage(channel=1), device.get_voltage(channel=2)

Note

Since commands do not have dimension parameters, length of tuple/list does not matter. If the type hints indicates 2 floats in the input, PyTango does not check that the input for each call received arrived with length 2.

## Server logging

This chapter instructs you on how to use the tango logging API (log4tango) to create tango log messages on your device server.

The logging system explained here is the Tango Logging Service (TLS). For detailed information on how this logging system works please check:

> - Usage

> - Property reference

The easiest way to start seeing log messages on your device server console is by starting it with the verbose option. Example:

    python PyDsExp.py PyDs1 -v4

This activates the console tango logging target and filters messages with importance level DEBUG or more. The links above provided detailed information on how to configure log levels and log targets. In this document we will focus on how to write log messages on your device server.

### Basic logging

The most basic way to write a log message on your device is to use the `Device` logging related methods:

> - `debug_stream()`

> - `info_stream()`

> - `warn_stream()`

> - `error_stream()`

> - `fatal_stream()`

Example:

    def read_voltage(self):
        self.info_stream("read voltage attribute")
        # ...
        return voltage_value

This will print a message like:

    1282206864 [-1215867200] INFO test/power_supply/1 read voltage attribute

every time a client asks to read the voltage attribute value.

The logging methods support argument list feature (since PyTango 8.1). Example:

    def read_voltage(self):
        self.info_stream("read_voltage(%s, %d)", self.host, self.port)
        # ...
        return voltage_value

### Logging with print statement

This feature is only possible since PyTango 7.1.3

It is possible to use the print statement to log messages into the tango logging system. This is achieved by using the python’s print extend form sometimes refered to as print chevron.

Same example as above, but now using print chevron:

    def read_voltage(self, the_att):
        print >>self.log_info, "read voltage attribute"
        # ...
        return voltage_value

Or using the python 3k print function:

    def read_Long_attr(self, the_att):
        print("read voltage attribute", file=self.log_info)
        # ...
        return voltage_value

### Logging with decorators

This feature is only possible since PyTango 7.1.3

PyTango provides a set of decorators that place automatic log messages when you enter and when you leave a python method. For example:

    @tango.DebugIt()
    def read_Long_attr(self, the_att):
        the_att.set_value(self.attr_long)

will generate a pair of log messages each time a client asks for the ‘Long_attr’ value. Your output would look something like:

    1282208997 [-1215965504] DEBUG test/pydsexp/1 -> read_Long_attr()
    1282208997 [-1215965504] DEBUG test/pydsexp/1 <- read_Long_attr()

Decorators exist for all tango log levels:

  - `tango.DebugIt`

  - `tango.InfoIt`

  - `tango.WarnIt`

  - `tango.ErrorIt`

  - `tango.FatalIt`

The decorators receive three optional arguments:

  - show_args - shows method arguments in log message (defaults to False)

  - show_kwargs shows keyword method arguments in log message (defaults to False)

  - show_ret - shows return value in log message (defaults to False)

Example:

    @tango.DebugIt(show_args=True, show_ret=True)
    def IOLong(self, in_data):
        return in_data * 2

will output something like:

    1282221947 [-1261438096] DEBUG test/pydsexp/1 -> IOLong(23)
    1282221947 [-1261438096] DEBUG test/pydsexp/1 46 <- IOLong()

## Multiple device classes (Python and C++) in a server

Within the same python interpreter, it is possible to mix several Tango classes. Let’s say two of your colleagues programmed two separate Tango classes in two separated python files: A `PLC` class in a `PLC.py`:

     1# PLC.py
     2
     3from tango.server import Device
     4
     5class PLC(Device):
     6
     7    # bla, bla my PLC code
     8
     9if __name__ == "__main__":
    10    PLC.run_server()

… and a `IRMirror` in a `IRMirror.py`:

     1# IRMirror.py
     2
     3from tango.server import Device
     4
     5class IRMirror(Device):
     6
     7    # bla, bla my IRMirror code
     8
     9if __name__ == "__main__":
    10    IRMirror.run_server()

You want to create a Tango server called PLCMirror that is able to contain devices from both PLC and IRMirror classes. All you have to do is write a `PLCMirror.py` containing the code:

    # PLCMirror.py

    from tango.server import run
    from PLC import PLC
    from IRMirror import IRMirror

    run([PLC, IRMirror])

It is also possible to add C++ Tango class in a Python device server as soon as:

  1. The Tango class is in a shared library

  2. It exist a C function to create the Tango class

For a Tango class called MyTgClass, the shared library has to be called MyTgClass.so and has to be in a directory listed in the LD_LIBRARY_PATH environment variable. The C function creating the Tango class has to be called _create_MyTgClass_class() and has to take one parameter of type “char *” which is the Tango class name. Here is an example of the main function of the same device server than before but with one C++ Tango class called SerialLine:

     1import tango
     2import sys
     3
     4if __name__ == '__main__':
     5    util = tango.Util(sys.argv)
     6    util.add_class('SerialLine', 'SerialLine', language="c++")
     7    util.add_class(PLCClass, PLC, 'PLC')
     8    util.add_class(IRMirrorClass, IRMirror, 'IRMirror')
     9
    10    U = tango.Util.instance()
    11    U.server_init()
    12    U.server_run()

Line 6:

  The C++ class is registered in the device server

Line 7 and 8:

  The two Python classes are registered in the device server

## Create attributes dynamically

It is also possible to create dynamic attributes within a Python device server. There are several ways to create dynamic attributes. One of the ways, is to create all the devices within a loop, then to create the dynamic attributes and finally to make all the devices available for the external world. In a C++ device server, this is typically done within the <Device>Class::device_factory() method. In Python device server, this method is generic and the user does not have one. Nevertheless, this generic device_factory provides the user with a way to create dynamic attributes.

Using the high-level API, you can re-define a method called `initialize_dynamic_attributes()` on each <Device>. This method will be called automatically by the device_factory for each device. Within this method you create all the dynamic attributes.

If you are still using the low-level API with a <Device>Class instead of just a <Device>, then you can use the generic device_factory’s call to the `dyn_attr()` method. It is simply necessary to re-define this method within your <Device>Class and to create the dynamic attributes within this method.

Internally, the high-level API re-defines `dyn_attr()` to call `initialize_dynamic_attributes()` for each device.

Note

The `dyn_attr()` (and `initialize_dynamic_attributes()` for high-level API) methods are only called once when the device server starts, since the Python device_factory method is only called once. Within the device_factory method, `init_device()` is called for all devices and only after that is `dyn_attr()` called for all devices. If the `Init` command is executed on a device it will not call the `dyn_attr()` method again (and will not call `initialize_dynamic_attributes()` either).

There is another point to be noted regarding dynamic attributes within a Python device server. The Tango Python device server core checks that for each static attribute there exists methods named <attribute_name>_read and/or <attribute_name>_write and/or is_<attribute_name>_allowed. Using dynamic attributes, it is not possible to define these methods because attribute names and number are known only at run-time. To address this issue, you need to provide references to these methods when calling `add_attribute()`.

The recommended approach with the high-level API is to reference these methods when instantiating a `tango.server.attribute` object using the fget, fset and/or fisallowed kwargs (see example below). Where fget is the method which has to be executed when the attribute is read, fset is the method to be executed when the attribute is written and fisallowed is the method to be executed to implement the attribute state machine. This `tango.server.attribute` object is then passed to the `add_attribute()` method.

Note

If the fget (fread), fset (fwrite) and fisallowed are given as str(name) they must be methods that exist on your Device class. If you want to use plain functions, or functions belonging to a different class, you should pass a callable.

Which arguments you have to provide depends on the type of the attribute. For example, a WRITE attribute does not need a read method.

Note

Starting from PyTango 9.4.0 the read methods for dynamic attributes can also be implemented with the high-level API. Prior to that, only the low-level API was available.

For the read function it is possible to use one of the following signatures:

    def low_level_read(self, attr):
        attr.set_value(self.attr_value)

    def high_level_read(self, attr):
        return self.attr_value

For the write function there is only one signature:

    def low_level_write(self, attr):
        self.attr_value = attr.get_write_value()

Here is an example of a device which creates a dynamic attribute on startup:

     1from tango import AttrWriteType
     2from tango.server import Device, attribute
     3
     4class MyDevice(Device):
     5
     6    def initialize_dynamic_attributes(self):
     7        self._values = {"dyn_attr": 0}
     8        attr = attribute(
     9            name="dyn_attr",
    10            dtype=int,
    11            access=AttrWriteType.READ_WRITE,
    12            fget=self.generic_read,
    13            fset=self.generic_write,
    14            fisallowed=self.generic_is_allowed,
    15        )
    16        self.add_attribute(attr)
    17
    18    def generic_read(self, attr):
    19        attr_name = attr.get_name()
    20        value = self._values[attr_name]
    21        return value
    22
    23    def generic_write(self, attr):
    24        attr_name = attr.get_name()
    25        value = attr.get_write_value()
    26        self._values[attr_name] = value
    27
    28    def generic_is_allowed(self, request_type):
    29        # note: we don't know which attribute is being read!
    30        # request_type will be either AttReqType.READ_REQ or AttReqType.WRITE_REQ
    31        return True

Another way to create dynamic attributes is to do it some time after the device has started. For example, using a command. In this case, we just call the `add_attribute()` method when necessary.

Here is an example of a device which has a TANGO command called CreateFloatAttribute. When called, this command creates a new scalar floating point attribute with the specified name:

     1from tango import AttrWriteType
     2from tango.server import Device, attribute, command
     3
     4class MyDevice(Device):
     5
     6    def init_device(self):
     7        super(MyDevice, self).init_device()
     8        self._values = {}
     9
    10    @command(dtype_in=str)
    11    def CreateFloatAttribute(self, attr_name):
    12        if attr_name not in self._values:
    13            self._values[attr_name] = 0.0
    14            attr = attribute(
    15                name=attr_name,
    16                dtype=float,
    17                access=AttrWriteType.READ_WRITE,
    18                fget=self.generic_read,
    19                fset=self.generic_write,
    20            )
    21            self.add_attribute(attr)
    22            self.info_stream("Added dynamic attribute %r", attr_name)
    23        else:
    24            raise ValueError(f"Already have an attribute called {repr(attr_name)}")
    25
    26    def generic_read(self, attr):
    27        attr_name = attr.get_name()
    28        self.info_stream("Reading attribute %s", attr_name)
    29        value = self._values[attr.get_name()]
    30        attr.set_value(value)
    31
    32    def generic_write(self, attr):
    33        attr_name = attr.get_name()
    34        value = attr.get_write_value()
    35        self.info_stream("Writing attribute %s - value %s", attr_name, value)
    36        self._values[attr.get_name()] = value

An approach more in line with the low-level API is also possible, but not recommended for new devices. The Device_3Impl::add_attribute() method has the following signature:

> `add_attribute(self, attr, r_meth=None, w_meth=None, is_allo_meth=None)`

attr is an instance of the `tango.Attr` class, r_meth is the method which has to be executed when the attribute is read, w_meth is the method to be executed when the attribute is written and is_allo_meth is the method to be executed to implement the attribute state machine.

Old example:

     1from tango import Attr, AttrWriteType
     2from tango.server import Device, command
     3
     4class MyOldDevice(Device):
     5
     6    @command(dtype_in=str)
     7    def CreateFloatAttribute(self, attr_name):
     8        attr = Attr(attr_name, tango.DevDouble, AttrWriteType.READ_WRITE)
     9        self.add_attribute(attr, self.read_General, self.write_General)
    10
    11    def read_General(self, attr):
    12        self.info_stream("Reading attribute %s", attr.get_name())
    13        attr.set_value(99.99)
    14
    15    def write_General(self, attr):
    16        self.info_stream("Writing attribute %s - value %s", attr.get_name(), attr.get_write_value())

Dynamic attributes with type hint

Note

Starting from PyTango 9.5.0 dynamic attribute type can be defined by type hints in the read/write methods.

Usage of type hints is described in Use Python type hints when declaring a device . The only difference in case of dynamic attributes is, that there is no option to use type hint in attribute at assignment

e.g., the following code won’t work:

    def initialize_dynamic_attributes(self):
        voltage: float = attribute() # CANNOT BE AN OPTION FOR DYNAMIC ATTRIBUTES!!!!!!!!
        self.add_attribute(attr)

## Create/Delete devices dynamically

This feature is only possible since PyTango 7.1.2

Starting from PyTango 7.1.2 it is possible to create devices in a device server “en caliente”. This means that you can create a command in your “management device” of a device server that creates devices of (possibly) several other tango classes. There are two ways to create a new device which are described below.

Tango imposes a limitation: the tango class(es) of the device(s) that is(are) to be created must have been registered before the server starts. If you use the high level API, the tango class(es) must be listed in the call to `run()`. If you use the lower level server API, it must be done using individual calls to `add_class()`.

### Dynamic device from a known tango class name

If you know the tango class name but you don’t have access to the `tango.DeviceClass` (or you are too lazy to search how to get it ;-) the way to do it is call `create_device()` / `delete_device()`. Here is an example of implementing a tango command on one of your devices that creates a device of some arbitrary class (the example assumes the tango commands ‘CreateDevice’ and ‘DeleteDevice’ receive a parameter of type DevVarStringArray with two strings. No error processing was done on the code for simplicity sake):

     1from tango import Util
     2from tango.server import Device, command
     3
     4class MyDevice(Device):
     5
     6    @command(dtype_in=[str])
     7    def CreateDevice(self, pars):
     8        klass_name, dev_name = pars
     9        util = Util.instance()
    10        util.create_device(klass_name, dev_name, alias=None, cb=None)
    11
    12    @command(dtype_in=[str])
    13    def DeleteDevice(self, pars):
    14        klass_name, dev_name = pars
    15        util = Util.instance()
    16        util.delete_device(klass_name, dev_name)

An optional callback can be registered that will be executed after the device is registed in the tango database but before the actual device object is created and its init_device method is called. It can be used, for example, to initialize some device properties.

### Dynamic device from a known tango class

If you already have access to the `DeviceClass` object that corresponds to the tango class of the device to be created you can call directly the `create_device()` / `delete_device()`. For example, if you wish to create a clone of your device, you can create a tango command called Clone:

     1class MyDevice(tango.Device):
     2
     3    def fill_new_device_properties(self, dev_name):
     4        prop_names = db.get_device_property_list(self.get_name(), "*")
     5        prop_values = db.get_device_property(self.get_name(), prop_names.value_string)
     6        db.put_device_property(dev_name, prop_values)
     7
     8        # do the same for attributes...
     9        ...
    10
    11    def Clone(self, dev_name):
    12        klass = self.get_device_class()
    13        klass.create_device(dev_name, alias=None, cb=self.fill_new_device_properties)
    14
    15    def DeleteSibling(self, dev_name):
    16        klass = self.get_device_class()
    17        klass.delete_device(dev_name)

Note that the cb parameter is optional. In the example it is given for demonstration purposes only.

## Write a server (original API)

This chapter describes how to develop a PyTango device server using the original PyTango server API. This API mimics the C++ API and is considered low level. You should write a server using this API if you are using code generated by Pogo tool or if for some reason the high level API helper doesn’t provide a feature you need (in that case think of writing a mail to tango mailing list explaining what you cannot do).

### The main part of a Python device server

The rule of this part of a Tango device server is to:

> - Create the `Util` object passing it the Python interpreter command line arguments

> - Add to this object the list of Tango class(es) which have to be hosted by this interpreter

> - Initialize the device server

> - Run the device server loop

The following is a typical code for this main function:

    if __name__ == '__main__':
        util = tango.Util(sys.argv)
        util.add_class(PyDsExpClass, PyDsExp)

        U = tango.Util.instance()
        U.server_init()
        U.server_run()

Line 2

  Create the Util object passing it the interpreter command line arguments

Line 3

  Add the Tango class PyDsExp to the device server. The `Util.add_class()` method of the Util class has two arguments which are the Tango class PyDsExpClass instance and the Tango PyDsExp instance. This `Util.add_class()` method is only available since version 7.1.2. If you are using an older version please use `Util.add_TgClass()` instead.

Line 7

  Initialize the Tango device server

Line 8

  Run the device server loop

### The PyDsExpClass class in Python

The rule of this class is to :

> - Host and manage data you have only once for the Tango class whatever devices of this class will be created

> - Define Tango class command(s)

> - Define Tango class attribute(s)

In our example, the code of this Python class looks like:

     1class PyDsExpClass(tango.DeviceClass):
     2
     3    cmd_list = { 'IOLong' : [ [ tango.ArgType.DevLong, "Number" ],
     4                              [ tango.ArgType.DevLong, "Number * 2" ] ],
     5                 'IOStringArray' : [ [ tango.ArgType.DevVarStringArray, "Array of string" ],
     6                                     [ tango.ArgType.DevVarStringArray, "This reversed array"] ],
     7    }
     8
     9    attr_list = { 'Long_attr' : [ [ tango.ArgType.DevLong ,
    10                                    tango.AttrDataFormat.SCALAR ,
    11                                    tango.AttrWriteType.READ],
    12                                  { 'min alarm' : 1000, 'max alarm' : 1500 } ],
    13
    14                 'Short_attr_rw' : [ [ tango.ArgType.DevShort,
    15                                       tango.AttrDataFormat.SCALAR,
    16                                       tango.AttrWriteType.READ_WRITE ] ]
    17    }

Line 1

  The PyDsExpClass class has to inherit from the `DeviceClass` class

Line 3 to 7

  Definition of the cmd_list `dict` defining commands. The IOLong command is defined at lines 3 and 4. The IOStringArray command is defined in lines 5 and 6

Line 9 to 17

  Definition of the attr_list `dict` defining attributes. The Long_attr attribute is defined at lines 9 to 12 and the Short_attr_rw attribute is defined at lines 14 to 16

If you have something specific to do in the class constructor like initializing some specific data member, you will have to code a class constructor. An example of such a contructor is

    def __init__(self, name):
        tango.DeviceClass.__init__(self, name)
        self.set_type("TestDevice")

The device type is set at line 3.

### Defining commands

As shown in the previous example, commands have to be defined in a `dict` called cmd_list as a data member of the xxxClass class of the Tango class. This `dict` has one element per command. The element key is the command name. The element value is a python list which defines the command. The generic form of a command definition is:

> `'cmd_name' : [ [in_type, <"In desc">], [out_type, <"Out desc">], <{opt parameters}>]`

The first element of the value list is itself a list with the command input data type (one of the `tango.ArgType` pseudo enumeration value) and optionally a string describing this input argument. The second element of the value list is also a list with the command output data type (one of the `tango.ArgType` pseudo enumeration value) and optionaly a string describing it. These two elements are mandatory. The third list element is optional and allows additional command definition. The authorized element for this `dict` are summarized in the following array:

> key | Value | Definition
> --- | --- | ---
> “display level” | DispLevel enum value | The command display level
> “polling period” | Any number | The command polling period (mS)
> “default command” | True or False | To define that it is the default command

### Defining attributes

As shown in the previous example, attributes have to be defined in a `dict` called attr_list as a data member of the xxxClass class of the Tango class. This `dict` has one element per attribute. The element key is the attribute name. The element value is a python `list` which defines the attribute. The generic form of an attribute definition is:

> `'attr_name' : [ [mandatory parameters], <{opt parameters}>]`

For any kind of attributes, the mandatory parameters are:

> `[attr data type, attr data format, attr data R/W type]`

The attribute data type is one of the possible value for attributes of the `tango.ArgType` pseudo enunmeration. The attribute data format is one of the possible value of the `tango.AttrDataFormat` pseudo enumeration and the attribute R/W type is one of the possible value of the `tango.AttrWriteType` pseudo enumeration. For spectrum attribute, you have to add the maximum X size (a number). For image attribute, you have to add the maximun X and Y dimension (two numbers). The authorized elements for the `dict` defining optional parameters are summarized in the following array:

> key | value | definition
> --- | --- | ---
> “display level” | tango.DispLevel enum value | The attribute display level
> “polling period” | Any number | The attribute polling period (mS)
> “memorized” | “true” or “true_without_hard_applied” | Define if and how the att. is memorized
> “label” | A string | The attribute label
> “description” | A string | The attribute description
> “unit” | A string | The attribute unit
> “standard unit” | A number | The attribute standard unit
> “display unit” | A string | The attribute display unit
> “format” | A string | The attribute display format
> “max value” | A number | The attribute max value
> “min value” | A number | The attribute min value
> “max alarm” | A number | The attribute max alarm
> “min alarm” | A number | The attribute min alarm
> “min warning” | A number | The attribute min warning
> “max warning” | A number | The attribute max warning
> “delta time” | A number | The attribute RDS alarm delta time
> “delta val” | A number | The attribute RDS alarm delta val

### The PyDsExp class in Python

The rule of this class is to implement methods executed by commands and attributes. In our example, the code of this class looks like:

     1class PyDsExp(tango.Device):
     2
     3    def __init__(self,cl,name):
     4        tango.Device.__init__(self, cl, name)
     5        self.info_stream('In PyDsExp.__init__')
     6        PyDsExp.init_device(self)
     7
     8    def init_device(self):
     9        self.info_stream('In Python init_device method')
    10        self.set_state(tango.DevState.ON)
    11        self.attr_short_rw = 66
    12        self.attr_long = 1246
    13
    14    #------------------------------------------------------------------
    15
    16    def delete_device(self):
    17        self.info_stream('PyDsExp.delete_device')
    18
    19    #------------------------------------------------------------------
    20    # COMMANDS
    21    #------------------------------------------------------------------
    22
    23    def is_IOLong_allowed(self):
    24        return self.get_state() == tango.DevState.ON
    25
    26    def IOLong(self, in_data):
    27        self.info_stream('IOLong', in_data)
    28        in_data = in_data * 2
    29        self.info_stream('IOLong returns', in_data)
    30        return in_data
    31
    32    #------------------------------------------------------------------
    33
    34    def is_IOStringArray_allowed(self):
    35        return self.get_state() == tango.DevState.ON
    36
    37    def IOStringArray(self, in_data):
    38        l = range(len(in_data)-1, -1, -1)
    39        out_index=0
    40        out_data=[]
    41        for i in l:
    42            self.info_stream('IOStringArray <-', in_data[out_index])
    43            out_data.append(in_data[i])
    44            self.info_stream('IOStringArray ->',out_data[out_index])
    45            out_index += 1
    46        self.y = out_data
    47        return out_data
    48
    49    #------------------------------------------------------------------
    50    # ATTRIBUTES
    51    #------------------------------------------------------------------
    52
    53    def read_attr_hardware(self, data):
    54        self.info_stream('In read_attr_hardware')
    55
    56    def read_Long_attr(self, the_att):
    57        self.info_stream("read_Long_attr")
    58
    59        the_att.set_value(self.attr_long)
    60
    61    def is_Long_attr_allowed(self, req_type):
    62        return self.get_state() in (tango.DevState.ON,)
    63
    64    def read_Short_attr_rw(self, the_att):
    65        self.info_stream("read_Short_attr_rw")
    66
    67        the_att.set_value(self.attr_short_rw)
    68
    69    def write_Short_attr_rw(self, the_att):
    70        self.info_stream("write_Short_attr_rw")
    71
    72        self.attr_short_rw = the_att.get_write_value()
    73
    74    def is_Short_attr_rw_allowed(self, req_type):
    75        return self.get_state() in (tango.DevState.ON,)

Line 1

  The PyDsExp class has to inherit from the tango.Device (this will used the latest device implementation class available, e.g., Device_5Impl)

Line 3 to 6

  PyDsExp class constructor. Note that at line 6, it calls the init_device() method

Line 8 to 12

  The init_device() method. It sets the device state (line 9) and initialises some data members

Line 16 to 17

  The delete_device() method. This method is not mandatory. You define it only if you have to do something specific before the device is destroyed

Line 23 to 30

  The two methods for the IOLong command. The first method is called is_IOLong_allowed() and it is the command is_allowed method (line 23 to 24). The second method has the same name than the command name. It is the method which executes the command. The command input data type is a Tango long and therefore, this method receives a python integer.

Line 34 to 47

  The two methods for the IOStringArray command. The first method is its is_allowed method (Line 34 to 35). The second one is the command execution method (Line 37 to 47). The command input data type is a string array. Therefore, the method receives the array in a python list of python strings.

Line 53 to 54

  The read_attr_hardware() method. Its argument is a Python sequence of Python integer.

Line 56 to 59

  The method executed when the Long_attr attribute is read. Note that before PyTango 7 it sets the attribute value with the tango.set_attribute_value function. Now the same can be done using the set_value of the attribute object

Line 61 to 62

  The is_allowed method for the Long_attr attribute. This is an optional method that is called when the attribute is read or written. Not defining it has the same effect as always returning True. The parameter req_type is of type `AttReqtype` which tells if the method is called due to a read or write request. Since this is a read-only attribute, the method will only be called for read requests, obviously.

Line 64 to 67

  The method executed when the Short_attr_rw attribute is read.

Line 69 to 72

  The method executed when the Short_attr_rw attribute is written. Note that before PyTango 7 it gets the attribute value with a call to the Attribute method get_write_value with a list as argument. Now the write value can be obtained as the return value of the get_write_value call. And in case it is a scalar there is no more the need to extract it from the list.

Line 74 to 75

  The is_allowed method for the Short_attr_rw attribute. This is an optional method that is called when the attribute is read or written. Not defining it has the same effect as always returning True. The parameter req_type is of type `AttReqtype` which tells if the method is called due to a read or write request.

#### General methods

The following array summarizes how the general methods we have in a Tango device server are implemented in Python.

Name | Input par (with “self”) | return value | mandatory
--- | --- | --- | ---
init_device | None | None | Yes
delete_device | None | None | No
always_executed_hook | None | None | No
signal_handler | `int` | None | No
read_attr_hardware | sequence<`int`> | None | No

#### Implementing a command

Commands are defined as described above. Nevertheless, some methods implementing them have to be written. These methods names are fixed and depend on command name. They have to be called:

> - `is_<Cmd_name>_allowed(self)`

> - `<Cmd_name>(self, arg)`

For instance, with a command called MyCmd, its is_allowed method has to be called is_MyCmd_allowed and its execution method has to be called simply MyCmd. The following array gives some more info on these methods.

Name | Input par (with “self”) | return value | mandatory
--- | --- | --- | ---
is_<Cmd_name>_allowed | None | Python boolean | No
Cmd_name | Depends on cmd type | Depends on cmd type | Yes

Please check Data types chapter to understand the data types that can be used in command parameters and return values.

The following code is an example of how you write code executed when a client calls a command named IOLong:

    def is_IOLong_allowed(self):
        self.debug_stream("in is_IOLong_allowed")
        return self.get_state() == tango.DevState.ON

    def IOLong(self, in_data):
        self.info_stream('IOLong', in_data)
        in_data = in_data * 2
        self.info_stream('IOLong returns', in_data)
        return in_data

Line 1-3

  the is_IOLong_allowed method determines in which conditions the command ‘IOLong’ can be executed. In this case, the command can only be executed if the device is in ‘ON’ state.

Line 6

  write a log message to the tango INFO stream (click here for more information about PyTango log system).

Line 7

  does something with the input parameter

Line 8

  write another log message to the tango INFO stream (click here for more information about PyTango log system).

Line 9

  return the output of executing the tango command

#### Implementing an attribute

Attributes are defined as described in chapter 5.3.2. Nevertheless, some methods implementing them have to be written. These methods names are fixed and depend on attribute name. They have to be called:

> - `is_<Attr_name>_allowed(self, req_type)`

> - `read_<Attr_name>(self, attr)`

> - `write_<Attr_name>(self, attr)`

For instance, with an attribute called MyAttr, its is_allowed method has to be called is_MyAttr_allowed, its read method has to be called read_MyAttr and its write method has to be called write_MyAttr. The attr parameter is an instance of `Attr`. Unlike the commands, the is_allowed method for attributes receives a parameter of type `AttReqtype`.

Please check Data types chapter to understand the data types that can be used in attribute.

The following code is an example of how you write code executed when a client read an attribute which is called Long_attr:

    def read_Long_attr(self, the_att):
        self.info_stream("read attribute name Long_attr")
        the_att.set_value(self.attr_long)

Line 1

  Method declaration with “the_att” being an instance of the Attribute class representing the Long_attr attribute

Line 2

  write a log message to the tango INFO stream (click here for more information about PyTango log system).

Line 3

  Set the attribute value using the method set_value() with the attribute value as parameter.

The following code is an example of how you write code executed when a client write the Short_attr_rw attribute:

    def write_Short_attr_rw(self,the_att):
        self.info_stream("In write_Short_attr_rw for attribute ",the_att.get_name())
        self.attr_short_rw = the_att.get_write_value(data)

Line 1

  Method declaration with “the_att” being an instance of the Attribute class representing the Short_attr_rw attribute

Line 2

  write a log message to the tango INFO stream (click here for more information about PyTango log system).

Line 3

  Get the value sent by the client using the method get_write_value() and store the value written in the device object. Our attribute is a scalar short attribute so the return value is an int