High level server API

Server helper classes for writing Tango device servers.

This module provides a high level device server API. It implements TEP1. It exposes an easier API for developing a Tango device server.

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

import time
from tango.server import run
from tango.server import Device
from tango.server import attribute, command


class Clock(Device):

    time = attribute()

    def read_time(self):
        return time.time()

    @command(dtype_in=str, dtype_out=str)
    def strftime(self, format):
        return time.strftime(format)


if __name__ == "__main__":
    run((Clock,))

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

  1. device description (via docstring), which user can get later as DeviceProxy.description()

  2. default state DevState.ON and default status “Device is current supply mode”

  3. a read-only double scalar attribute called voltage

  4. a read/write double scalar expert attribute current

  5. a read-only double image attribute called noise

  6. a ramp command

  7. a host device property

  8. a port class property

 1from time import time
 2from numpy.random import random_sample
 3
 4from tango import AttrQuality, AttrWriteType, DevState, DispLevel
 5from tango.server import Device, attribute, command
 6from tango.server import class_property, device_property
 7
 8class PowerSupply(Device):
 9    """PyTango example of PowerSuppy device."""
10
11    # alternative way to add device description (see note below)
12    DEVICE_CLASS_DESCRIPTION = "PyTango example of PowerSuppy device."
13
14    DEVICE_CLASS_INITIAL_STATUS = "Device is in current supply mode"
15    DEVICE_CLASS_INITIAL_STATE  = DevState.ON
16
17    voltage = attribute()
18
19    current = attribute(label="Current", dtype=float,
20                        display_level=DispLevel.EXPERT,
21                        access=AttrWriteType.READ_WRITE,
22                        unit="A", format="8.4f",
23                        min_value=0.0, max_value=8.5,
24                        min_alarm=0.1, max_alarm=8.4,
25                        min_warning=0.5, max_warning=8.0,
26                        fget="get_current", fset="set_current",
27                        doc="the power supply current")
28
29    noise = attribute(label="Noise", dtype=((float,),),
30                      max_dim_x=1024, max_dim_y=1024,
31                      fget="get_noise")
32
33    host = device_property(dtype=str)
34    port = class_property(dtype=int, default_value=9788)
35
36    def read_voltage(self):
37        self.info_stream(f"Get voltage({self.host}, {self.port})")
38        return 10.0
39
40    def get_current(self):
41        return 2.3456, time(), AttrQuality.ATTR_CHANGING
42
43    def set_current(self, current):
44        self.info_stream(f"Current set to {current}")
45
46    def get_noise(self):
47        return random_sample((1024, 1024))
48
49    @command(dtype_in=float)
50    def ramp(self, value):
51        self.info_stream(f"Ramp up requested: {value} seconds")
52
53if __name__ == "__main__":
54    PowerSupply.run_server()

Pretty cool, uh?

Note

the device description can be added either by class docstring or by DEVICE_CLASS_DESCRIPTION class member, the latter has priority over the docstring. The important difference is that DEVICE_CLASS_DESCRIPTION will be inherited by child classes, while the docstring will not be.

Data types

When declaring attributes, properties or commands, one of the most important details is the data type. It is given by the keyword argument dtype. In order to provide a more pythonic interface, this argument is not restricted to the CmdArgType options.

For example, to define a SCALAR DevLong attribute you have several possibilities:

  1. int

  2. ‘int’

  3. ‘int64’

  4. tango.CmdArgType.DevLong64

  5. ‘DevLong64’

  6. numpy.int64

To define a SPECTRUM attribute simply wrap the scalar data type in any python sequence:

  • using a tuple: (:obj:`int`,) or

  • using a list: [:obj:`int`] or

  • any other sequence type

To define an IMAGE attribute simply wrap the scalar data type in any python sequence of sequences:

  • using a tuple: ((:obj:`int`,),) or

  • using a list: [[:obj:`int`]] or

  • any other sequence type

Below is the complete table of equivalences.

dtype argument

converts to tango type

None

DevVoid

'None'

DevVoid

DevVoid

DevVoid

'DevVoid'

DevVoid

DevState

DevState

'DevState'

DevState

bool

DevBoolean

'bool'

DevBoolean

'boolean'

DevBoolean

DevBoolean

DevBoolean

'DevBoolean'

DevBoolean

numpy.bool_

DevBoolean

'char'

DevUChar

'chr'

DevUChar

'byte'

DevUChar

chr

DevUChar

DevUChar

DevUChar

'DevUChar'

DevUChar

numpy.uint8

DevUChar

'int16'

DevShort

DevShort

DevShort

'DevShort'

DevShort

numpy.int16

DevShort

'uint16'

DevUShort

DevUShort

DevUShort

'DevUShort'

DevUShort

numpy.uint16

DevUShort

'int32'

DevLong

DevLong

DevLong

'DevLong'

DevLong

numpy.int32

DevLong

'uint32'

DevULong

DevULong

DevULong

'DevULong'

DevULong

numpy.uint32

DevULong

int

DevLong64

'int'

DevLong64

'int64'

DevLong64

DevLong64

DevLong64

'DevLong64'

DevLong64

numpy.int64

DevLong64

'uint'

DevULong64

'uint64'

DevULong64

DevULong64

DevULong64

'DevULong64'

DevULong64

numpy.uint64

DevULong64

'float32'

DevFloat

DevFloat

DevFloat

'DevFloat'

DevFloat

numpy.float32

DevFloat

float

DevDouble

'double'

DevDouble

'float'

DevDouble

'float64'

DevDouble

DevDouble

DevDouble

'DevDouble'

DevDouble

numpy.float64

DevDouble

str

DevString

'str'

DevString

'string'

DevString

'text'

DevString

DevString

DevString

'DevString'

DevString

bytearray

DevEncoded

'bytearray'

DevEncoded

'bytes'

DevEncoded

DevEncoded

DevEncoded

'DevEncoded'

DevEncoded

DevVarBooleanArray

DevVarBooleanArray

'DevVarBooleanArray'

DevVarBooleanArray

DevVarCharArray

DevVarCharArray

'DevVarCharArray'

DevVarCharArray

DevVarShortArray

DevVarShortArray

'DevVarShortArray'

DevVarShortArray

DevVarLongArray

DevVarLongArray

'DevVarLongArray'

DevVarLongArray

DevVarLong64Array

DevVarLong64Array

'DevVarLong64Array'

DevVarLong64Array

DevVarULong64Array

DevVarULong64Array

'DevVarULong64Array'

DevVarULong64Array

DevVarFloatArray

DevVarFloatArray

'DevVarFloatArray'

DevVarFloatArray

DevVarDoubleArray

DevVarDoubleArray

'DevVarDoubleArray'

DevVarDoubleArray

DevVarUShortArray

DevVarUShortArray

'DevVarUShortArray'

DevVarUShortArray

DevVarULongArray

DevVarULongArray

'DevVarULongArray'

DevVarULongArray

DevVarStringArray

DevVarStringArray

'DevVarStringArray'

DevVarStringArray

DevVarLongStringArray

DevVarLongStringArray

'DevVarLongStringArray'

DevVarLongStringArray

DevVarDoubleStringArray

DevVarDoubleStringArray

'DevVarDoubleStringArray'

DevVarDoubleStringArray

class tango.server.Device(cl, name)[source]

Bases: BaseDevice

Device class for the high-level API.

All device-specific classes should inherit from this class.

DEVICE_CLASS_DESCRIPTION: ClassVar[str | None]

Description of the device class (optional).

If not specified, the class docstring is used. Available to clients via tango.DeviceProxy.description(). Use as a class variable.

DEVICE_CLASS_INITIAL_STATE: ClassVar[DevState]

Initial state value for all instances of the device (optional).

Use as a class variable.

DEVICE_CLASS_INITIAL_STATUS: ClassVar[str]

Initial status string for all instances of the device (optional).

Use as a class variable.

TangoClassClass

alias of DeviceClass

add_attribute(self, attr, r_meth=None, w_meth=None, is_allo_meth=None) Attr

Add a new attribute to the device attribute list.

Please, note that if you add an attribute to a device at device creation time, this attribute will be added to the device class attribute list. Therefore, all devices belonging to the same class created after this attribute addition will also have this attribute.

If you pass a reference to unbound method for read, write or is_allowed method (e.g. DeviceClass.read_function or self.__class__.read_function), during execution the corresponding bound method (self.read_function) will be used.

Note: Calling the synchronous add_attribute method from a coroutine function in an asyncio server may cause a deadlock. Use await async_add_attribute() instead. However, if overriding the synchronous method initialize_dynamic_attributes, then the synchronous add_attribute method must be used, even in asyncio servers.

Parameters:
  • attr (server.attribute or Attr or AttrData) – the new attribute to be added to the list.

  • r_meth (callable) – the read method to be called on a read request (if attr is of type server.attribute, then use the fget field in the attr object instead)

  • w_meth (callable) – the write method to be called on a write request (if attr is writable) (if attr is of type server.attribute, then use the fset field in the attr object instead)

  • is_allo_meth (callable) – the method that is called to check if it is possible to access the attribute or not (if attr is of type server.attribute, then use the fisallowed field in the attr object instead)

Returns:

the newly created attribute.

Return type:

Attr

Raises:

DevFailed

add_command(self, cmd, device_level=True) cmd

Add a new command to the device command list.

Parameters:
  • cmd – the new command to be added to the list

  • device_level – Set this flag to true if the command must be added for only this device

Returns:

The command to add

Return type:

Command

Raises:

DevFailed

add_version_info(self: tango._tango.DeviceImpl, key: str, value: str) None

add_version_info (self, key, value) -> dict

Method to add information about the module version a device is using

Parameters:
  • key (str) – Module name

  • value (str) – Module version, or other relevant information.

Added in version 10.0.0.

always_executed_hook()

Tango always_executed_hook. Default implementation does nothing

append_status(self: tango._tango.DeviceImpl, status: str, new_line: bool = False) None

append_status(self, status, new_line=False)

Appends a string to the device status.

Parameters:
  • status (str) – the string to be appended to the device status

  • new_line (bool) – If true, appends a new line character before the string. Default is False

async async_add_attribute(self, attr, r_meth=None, w_meth=None, is_allo_meth=None) Attr

Add a new attribute to the device attribute list.

Please, note that if you add an attribute to a device at device creation time, this attribute will be added to the device class attribute list. Therefore, all devices belonging to the same class created after this attribute addition will also have this attribute.

If you pass a reference to unbound method for read, write or is_allowed method (e.g. DeviceClass.read_function or self.__class__.read_function), during execution the corresponding bound method (self.read_function) will be used.

Parameters:
  • attr (server.attribute or Attr or AttrData) – the new attribute to be added to the list.

  • r_meth (callable) – the read method to be called on a read request (if attr is of type server.attribute, then use the fget field in the attr object instead)

  • w_meth (callable) – the write method to be called on a write request (if attr is writable) (if attr is of type server.attribute, then use the fset field in the attr object instead)

  • is_allo_meth (callable) – the method that is called to check if it is possible to access the attribute or not (if attr is of type server.attribute, then use the fisallowed field in the attr object instead)

Returns:

the newly created attribute.

Return type:

Attr

Raises:

DevFailed

Added in version 10.0.0.

async async_remove_attribute(self, attr_name, free_it=False, clean_db=True)

Remove one attribute from the device attribute list.

Parameters:
  • attr_name (str) – attribute name

  • free_it (bool) – free Attr object flag. Default False

  • clean_db (bool) – clean attribute related info in db. Default True

Raises:

DevFailed

Added in version 10.0.0.

check_command_exists(self: tango._tango.DeviceImpl, cmd_name: str) None

check_command_exists(self, cmd_name)

Check that a command is supported by the device and does not need input value.

The method throws an exception if the command is not defined or needs an input value.

Parameters:

cmd_name (str) – the command name

Raises:
  • DevFailed

  • API_IncompatibleCmdArgumentType

  • API_CommandNotFound

create_telemetry_tracer(device_tracer_provider) opentelemetry.trace.Tracer

Factory method returning a Tracer for telemetry.

The default implementation can be overridden.

Added in version 10.0.0.

create_telemetry_tracer_provider(class_name, device_name) opentelemetry.trace.TracerProvider

Factory method returning a TracerProvider for telemetry.

The default implementation can be overridden.

Added in version 10.0.0.

debug_stream(self, msg, *args, source=None)

Sends the given message to the tango debug stream.

Since PyTango 7.1.3, the same can be achieved with:

print(msg, file=self.log_debug)
Parameters:
  • msg (str) – the message to be sent to the debug stream

  • *args – Arguments to format a message string.

  • source (Callable) – Function that will be inspected for filename and lineno in the log message.

Added in version 9.4.2: added source parameter

delete_device()

Code to handle device clean-up.

This method is called automatically when the device is shut down gracefully. It also gets called if the device is re-initialised by a call to the Init command (before a new call to init_device()).

If overwriting this method, it is important to call the super class method last:

  • For synchronous devices: super().delete_device()

  • For asyncio green mode devices: await super().delete_device()

dev_state(self: tango._tango.Device_6Impl) tango._tango.DevState
dev_status(self: tango._tango.Device_6Impl) str
error_stream(self, msg, *args, source=None)

Sends the given message to the tango error stream.

Since PyTango 7.1.3, the same can be achieved with:

print(msg, file=self.log_error)
Parameters:
  • msg (str) – the message to be sent to the error stream

  • *args – Arguments to format a message string.

  • source (Callable) – Function that will be inspected for filename and lineno in the log message.

Added in version 9.4.2: added source parameter

fatal_stream(self, msg, *args, source=None)

Sends the given message to the tango fatal stream.

Since PyTango 7.1.3, the same can be achieved with:

print(msg, file=self.log_fatal)
Parameters:
  • msg (str) – the message to be sent to the fatal stream

  • *args – Arguments to format a message string.

  • source (Callable) – Function that will be inspected for filename and lineno in the log message.

Added in version 9.4.2: added source parameter

fill_attr_polling_buffer(self, attribute_name, attr_history_stack) None

Fill attribute polling buffer with your own data. E.g.:

def fill_history(self):
    # note is such case quality will ATTR_VALID, and time_stamp will be time.time()
    self.fill_attr_polling_buffer(attribute_name, TimedAttrData(my_new_value))

or:

def fill_history(self):
    data = TimedAttrData(value=my_new_value,
                         quality=AttrQuality.ATTR_WARNING,
                         w_value=my_new_w_value,
                         time_stamp=my_time)

    self.fill_attr_polling_buffer(attribute_name, data)

or:

def fill_history(self):
    data = [TimedAttrData(my_new_value),
            TimedAttrData(error=RuntimeError("Cannot read value")]

    self.fill_attr_polling_buffer(attribute_name, data)
Parameters:
Returns:

None

Raises:

tango.DevFailed

Added in version 10.1.0.

fill_cmd_polling_buffer(self, device, command_name, cmd_history_stack) None

Fill command polling buffer with your own data. E.g.:

def fill_history(self):
    # note is such case time_stamp will be set to time.time()
    self.fill_cmd_polling_buffer(command_name, TimedCmdData(my_new_value))

or:

def fill_history(self):
    data = TimedCmdData(value=my_new_value,
                         time_stamp=my_time)

    self.fill_cmd_polling_buffer(command_name, data)

or:

def fill_history(self):
    data = [TimedCmdData(my_new_value),
            TimedCmdData(error=RuntimeError("Cannot read value")]

    self.fill_cmd_polling_buffer(command_name, data)
Parameters:
Returns:

None

Raises:

tango.DevFailed

Added in version 10.1.0.

get_attr_min_poll_period(self: tango._tango.DeviceImpl) tango._tango.StdStringVector

get_attr_min_poll_period (self) -> Sequence[str]

Returns the min attribute poll period in milliseconds

Returns:

the min attribute poll period in ms

Return type:

Sequence[str]

New in PyTango 7.2.0

get_attr_poll_ring_depth(self: tango._tango.DeviceImpl, attr_name: str) int

get_attr_poll_ring_depth (self, attr_name) -> int

Returns the attribute poll ring depth.

Parameters:

attr_name (str) – the attribute name

Returns:

the attribute poll ring depth

Return type:

int

New in PyTango 7.1.2

get_attribute_config(attr_names) list[AttributeConfig]

Returns the list of tango.AttributeConfig for the requested names

Parameters:

attr_names (list[str] | str) – sequence of str with attribute names, or single attribute name

Returns:

tango.AttributeConfig for each requested attribute name

Return type:

list[tango.AttributeConfig]

get_attribute_config_2(attr_names) list[AttributeConfig_2]

Returns the list of tango.AttributeConfig_2 for the requested names

Parameters:

attr_names (list[str] | str) – sequence of str with attribute names, or single attribute name

Returns:

tango.AttributeConfig_2 for each requested attribute name

Return type:

list[tango.AttributeConfig_2]

get_attribute_config_3(attr_names) list[AttributeConfig_3]

Returns the list of tango.AttributeConfig_3 for the requested names

Parameters:

attr_names (list[str] | str) – sequence of str with attribute names, or single attribute name

Returns:

tango.AttributeConfig_3 for each requested attribute name

Return type:

list[tango.AttributeConfig_3]

get_attribute_poll_period(self: tango._tango.DeviceImpl, attr_name: str) int

get_attribute_poll_period (self, attr_name) -> int

Returns the attribute polling period (milliseconds) or 0 if the attribute is not polled.

Parameters:

attr_name (str) – attribute name

Returns:

attribute polling period (ms) or 0 if it is not polled

Return type:

int

New in PyTango 8.0.0

get_client_ident(self: tango._tango.DeviceImpl) tango._tango.ClientAddr

get_client_ident (self) -> ClientAddr | None

Get client identification.

This method is only useful while handling a command or attribute read/write. I.e., when a method has been invoked by a client. It will return None if the method was not invoked in the context of a client call. E.g., called on startup, or called internally (e.g., from the polling loop).

It can only be used with tango.GreenMode.Synchronous device servers. Other device servers will not have the correct context active at the time the attribute/command handler is running. E.g., for an asyncio device server, the handler is running in the asyncio event loop thread.

Returns:

client identification structure

Return type:

ClientAddr | None

get_cmd_min_poll_period(self: tango._tango.DeviceImpl) tango._tango.StdStringVector

get_cmd_min_poll_period (self) -> Sequence[str]

Returns the min command poll period in milliseconds.

Returns:

the min command poll period in ms

Return type:

Sequence[str]

New in PyTango 7.2.0

get_cmd_poll_ring_depth(self: tango._tango.DeviceImpl, cmd_name: str) int

get_cmd_poll_ring_depth (self, cmd_name) -> int

Returns the command poll ring depth.

Parameters:

cmd_name (str) – the command name

Returns:

the command poll ring depth

Return type:

int

New in PyTango 7.1.2

get_command_poll_period(self: tango._tango.DeviceImpl, cmd_name: str) int

get_command_poll_period (self, cmd_name) -> int

Returns the command polling period (milliseconds) or 0 if the command is not polled.

Parameters:

cmd_name (str) – command name

Returns:

command polling period (ms) or 0 if it is not polled

Return type:

int

New in PyTango 8.0.0

get_dev_idl_version(self: tango._tango.DeviceImpl) int

get_dev_idl_version (self) -> int

Returns the IDL version.

Returns:

the IDL version

Return type:

int

New in PyTango 7.1.2

get_device_attr(self: tango._tango.DeviceImpl) tango._tango.MultiAttribute

get_device_attr (self) -> MultiAttribute

Get device multi attribute object.

Returns:

the device’s MultiAttribute object

Return type:

MultiAttribute

get_device_class(self)

Get device class singleton.

Returns:

the device class singleton (device_class field)

Return type:

DeviceClass

get_device_properties(self, ds_class=None)

Utility method that fetches all the device properties from the database and converts them into members of this DeviceImpl.

Parameters:

ds_class (DeviceClass) – the DeviceClass object. Optional. Default value is None meaning that the corresponding DeviceClass object for this DeviceImpl will be used

Raises:

DevFailed

get_exported_flag(self: tango._tango.DeviceImpl) bool

get_exported_flag (self) -> bool

Returns the state of the exported flag

Returns:

the state of the exported flag

Return type:

bool

New in PyTango 7.1.2

get_logger(self: tango._tango.DeviceImpl) tango._tango.Logger

get_logger (self) -> Logger

Returns the Logger object for this device

Returns:

the Logger object for this device

Return type:

Logger

get_min_poll_period(self: tango._tango.DeviceImpl) int

get_min_poll_period (self) -> int

Returns the min poll period in milliseconds.

Returns:

the min poll period in ms

Return type:

int

New in PyTango 7.2.0

get_name(self: tango._tango.DeviceImpl) str

get_name (self) -> (str)

Get a COPY of the device name.

Returns:

the device name

Return type:

str

get_non_auto_polled_attr(self: tango._tango.DeviceImpl) tango._tango.StdStringVector

get_non_auto_polled_attr (self) -> Sequence[str]

Returns a COPY of the list of non automatic polled attributes

Returns:

a COPY of the list of non automatic polled attributes

Return type:

Sequence[str]

New in PyTango 7.1.2

get_non_auto_polled_cmd(self: tango._tango.DeviceImpl) tango._tango.StdStringVector

get_non_auto_polled_cmd (self) -> Sequence[str]

Returns a COPY of the list of non automatic polled commands

Returns:

a COPY of the list of non automatic polled commands

Return type:

Sequence[str]

New in PyTango 7.1.2

get_poll_old_factor(self: tango._tango.DeviceImpl) int

get_poll_old_factor (self) -> int

Returns the poll old factor

Returns:

the poll old factor

Return type:

int

New in PyTango 7.1.2

get_poll_ring_depth(self: tango._tango.DeviceImpl) int

get_poll_ring_depth (self) -> int

Returns the poll ring depth

Returns:

the poll ring depth

Return type:

int

New in PyTango 7.1.2

get_polled_attr(self: tango._tango.DeviceImpl) tango._tango.StdStringVector

get_polled_attr (self) -> Sequence[str]

Returns a COPY of the list of polled attributes

Returns:

a COPY of the list of polled attributes

Return type:

Sequence[str]

New in PyTango 7.1.2

get_polled_cmd(self: tango._tango.DeviceImpl) tango._tango.StdStringVector

get_polled_cmd (self) -> Sequence[str]

Returns a COPY of the list of polled commands

Returns:

a COPY of the list of polled commands

Return type:

Sequence[str]

New in PyTango 7.1.2

get_prev_state(self: tango._tango.DeviceImpl) tango._tango.DevState

get_prev_state (self) -> DevState

Get a COPY of the device’s previous state.

Returns:

the device’s previous state

Return type:

DevState

get_state(self: tango._tango.DeviceImpl) tango._tango.DevState

get_state (self) -> DevState

Get a COPY of the device state.

Returns:

Current device state

Return type:

DevState

get_status(self: tango._tango.DeviceImpl) str

get_status (self) -> str

Get a COPY of the device status.

Returns:

the device status

Return type:

str

get_telemetry_tracer() opentelemetry.trace.Tracer

Returns device telemetry tracer, or None if telemetry disabled.

Added in version 10.0.0.

get_version_info(self: tango._tango.DeviceImpl) dict

get_version_info (self) -> dict

Returns a dict with versioning of different modules related to the pytango device.

Example:
{
    "Build.PyTango.NumPy": "1.26.4",
    "Build.PyTango.Pybind11": "3.0.1",
    "Build.PyTango.Python": "3.12.2",
    "Build.PyTango.cppTango":"10.0.0",
    "NumPy": "1.26.4",
    "PyTango": "10.0.0.dev0",
    "Python": "3.12.2",
    "cppTango": "10.0.0",
    "omniORB": "4.3.2",
    "zmq": "4.3.5"
}
Returns:

modules version dict

Return type:

dict

Added in version 10.0.0.

info_stream(self, msg, *args, source=None)

Sends the given message to the tango info stream.

Since PyTango 7.1.3, the same can be achieved with:

print(msg, file=self.log_info)
Parameters:
  • msg (str) – the message to be sent to the info stream

  • *args – Arguments to format a message string.

  • source (Callable) – Function that will be inspected for filename and lineno in the log message.

Added in version 9.4.2: added source parameter

init_device()

Code to handle device initialisation.

This method is called automatically when the device starts, but before it is available to clients (i.e., before it is “exported”). It also gets called if the device is re-initialised by a call to the Init command (after delete_device()).

Default implementation calls get_device_properties()

If overwriting this method, it is important to call the super class method first:

  • For synchronous devices: super().init_device()

  • For asyncio green mode devices: await super().init_device()

init_logger(self: tango._tango.DeviceImpl) None

init_logger (self) -> None

Setups logger for the device. Called automatically when device starts.

initialize_dynamic_attributes()

Method executed at initializion phase to create dynamic attributes. Default implementation does nothing. Overwrite when necessary.

Note

This method is only called once when the device server starts, after init_device(), but before the device is marked as exported. If the Init command is executed on the device, the initialize_dynamic_attributes() method will not be called again.

is_attribute_polled(self: tango._tango.DeviceImpl, attr_name: str) bool

is_attribute_polled (self, attr_name) -> bool

True if the attribute is polled.

Parameters:

attr_name (str) – attribute name

Returns:

True if the attribute is polled

Return type:

bool

is_command_polled(self: tango._tango.DeviceImpl, cmd_name: str) bool

is_command_polled (self, cmd_name) -> bool

True if the command is polled.

Parameters:

cmd_name (str) – attribute name

Returns:

True if the command is polled

Return type:

bool

is_device_locked(self: tango._tango.DeviceImpl) bool

is_device_locked (self) -> bool

Returns if this device is locked by a client.

Returns:

True if it is locked or False otherwise

Return type:

bool

New in PyTango 7.1.2

is_kernel_tracing_enabled(self: tango._tango.DeviceImpl) bool

is_kernel_tracing_enabled (self) -> bool

Indicates if telemetry tracing of the cppTango kernel API is enabled.

Always False if telemetry support isn’t compiled into cppTango.

Returns:

if kernel tracing is enabled

Return type:

bool

Added in version 10.0.0.

is_polled(self: tango._tango.DeviceImpl) bool

is_polled (self) -> bool

Returns if it is polled

Returns:

True if it is polled or False otherwise

Return type:

bool

New in PyTango 7.1.2

is_telemetry_enabled(self: tango._tango.DeviceImpl) bool

is_telemetry_enabled (self) -> bool

Indicates if telemetry tracing is enabled for the device.

Always False if telemetry support isn’t compiled into cppTango.

Returns:

if device telemetry tracing is enabled

Return type:

bool

Added in version 10.0.0.

is_there_subscriber(self: tango._tango.DeviceImpl, attr_name: str, event_type: tango._tango.EventType) bool

is_there_subscriber (self, attr_name, event_type) -> bool

Check if there is subscriber(s) listening for the event.

This method returns a boolean set to true if there are some subscriber(s) listening on the event specified by the two method arguments. Be aware that there is some delay (up to 600 sec) between this method returning false and the last subscriber unsubscription or crash…

The device interface change event is not supported by this method.

Parameters:
  • attr_name (str) – the attribute name

  • event_type (EventType) – the event type

Returns:

True if there is at least one listener or False otherwise

Return type:

bool

poll_attribute(self: tango._tango.DeviceImpl, attr_name: str, period_ms: SupportsInt) None

poll_attribute (self, attr_name, period_ms) -> None

Add an attribute to the list of polled attributes.

Parameters:
  • attr_name (str) – attribute name

  • period_ms (int) – polling period in milliseconds

Returns:

None

Return type:

None

poll_command(self: tango._tango.DeviceImpl, cmd_name: str, period_ms: SupportsInt) None

poll_command (self, cmd_name, period_ms) -> None

Add a command to the list of polled commands.

Parameters:
  • cmd_name (str) – command name

  • period_ms (int) – polling period in milliseconds

Returns:

None

Return type:

None

push_alarm_event(attr_name, *args, **kwargs)
push_alarm_event(self, attr_name, except)
push_alarm_event(self, attr_name, data)
push_alarm_event(self, attr_name, data, time_stamp, quality)
push_alarm_event(self, attr_name, str_data, data)
push_alarm_event(self, attr_name, str_data, data, time_stamp, quality)

Push an alarm event for the given attribute name.

Parameters:
  • attr_name (str) – attribute name

  • data – the data to be sent as attribute event data. Data must be compatible with the attribute type and format. for SPECTRUM and IMAGE attributes, data can be any type of sequence of elements compatible with the attribute type

  • str_data (str) – special variation for DevEncoded data type. In this case ‘data’ must be a str or an object with the buffer interface.

  • except (DevFailed) – Instead of data, you may want to send an exception.

  • time_stamp (double) – the time stamp

  • quality (AttrQuality) – the attribute quality factor

Raises:

DevFailed – If the attribute data type is not coherent.

Changed in version 10.1.0: Removed optional ‘dim_x’ and ‘dim_y’ arguments. The dimensions are automatically determined from the data.

push_archive_event(attr_name, *args, **kwargs)
push_archive_event(self, attr_name, except)
push_archive_event(self, attr_name, data)
push_archive_event(self, attr_name, data, time_stamp, quality)
push_archive_event(self, attr_name, str_data, data)
push_archive_event(self, attr_name, str_data, data, time_stamp, quality)

Push an archive event for the given attribute name.

Parameters:
  • attr_name (str) – attribute name

  • data – the data to be sent as attribute event data. Data must be compatible with the attribute type and format. for SPECTRUM and IMAGE attributes, data can be any type of sequence of elements compatible with the attribute type

  • str_data (str) – special variation for DevEncoded data type. In this case ‘data’ must be a str or an object with the buffer interface.

  • except (DevFailed) – Instead of data, you may want to send an exception.

  • time_stamp (double) – the time stamp

  • quality (AttrQuality) – the attribute quality factor

Raises:

DevFailed – If the attribute data type is not coherent.

Changed in version 10.1.0: Removed optional ‘dim_x’ and ‘dim_y’ arguments. The dimensions are automatically determined from the data.

push_att_conf_event(self: tango._tango.DeviceImpl, attr: tango._tango.Attribute) None

push_att_conf_event(self, attr)

Push an attribute configuration event.

Parameters:

attr (Attribute) – the attribute for which the configuration event will be sent.

New in PyTango 7.2.1

push_change_event(attr_name, *args, **kwargs)
push_change_event(self, attr_name, except)
push_change_event(self, attr_name, data)
push_change_event(self, attr_name, data, time_stamp, quality)
push_change_event(self, attr_name, str_data, data)
push_change_event(self, attr_name, str_data, data, time_stamp, quality)

Push a change event for the given attribute name.

Parameters:
  • attr_name (str) – attribute name

  • data – the data to be sent as attribute event data. Data must be compatible with the attribute type and format. for SPECTRUM and IMAGE attributes, data can be any type of sequence of elements compatible with the attribute type

  • str_data (str) – special variation for DevEncoded data type. In this case ‘data’ must be a str or an object with the buffer interface.

  • except (DevFailed) – Instead of data, you may want to send an exception.

  • time_stamp (double) – the time stamp

  • quality (AttrQuality) – the attribute quality factor

Raises:

DevFailed – If the attribute data type is not coherent.

Changed in version 10.1.0: Removed optional ‘dim_x’ and ‘dim_y’ arguments. The dimensions are automatically determined from the data.

push_data_ready_event(self: tango._tango.DeviceImpl, attr_name: str, counter: SupportsInt) None

push_data_ready_event(self, attr_name, counter)

Push a data ready event for the given attribute name.

The method needs the attribute name and a “counter” which will be passed within the event

Parameters:
  • attr_name (str) – attribute name

  • counter (int) – the user counter

Raises:

DevFailed – If the attribute name is unknown.

push_event(attr_name, filt_names, filt_vals, *args, **kwargs)
push_event(self, attr_name, filt_names, filt_vals, except)
push_event(self, attr_name, filt_names, filt_vals, data)
push_event(self, attr_name, filt_names, filt_vals, str_data, data)
push_event(self, attr_name, filt_names, filt_vals, data, time_stamp, quality)
push_event(self, attr_name, filt_names, filt_vals, str_data, data, time_stamp, quality)

Push a user event for the given attribute name.

Parameters:
  • attr_name (str) – attribute name

  • filt_names (Sequence[str]) – unused (kept for backwards compatibility) - pass an empty list.

  • filt_vals (Sequence[double]) – unused (kept for backwards compatibility) - pass an empty list.

  • data – the data to be sent as attribute event data. Data must be compatible with the attribute type and format. for SPECTRUM and IMAGE attributes, data can be any type of sequence of elements compatible with the attribute type

  • str_data (str) – special variation for DevEncoded data type. In this case ‘data’ must be a str or an object with the buffer interface.

  • except (DevFailed) – Instead of data, you may want to send an exception.

  • time_stamp (double) – the time stamp

  • quality (AttrQuality) – the attribute quality factor

Raises:

DevFailed – If the attribute data type is not coherent.

Changed in version 10.1.0: Removed optional ‘dim_x’ and ‘dim_y’ arguments. The dimensions are automatically determined from the data.

read_attr_hardware(self: tango._tango.Device_6Impl, arg0: tango._tango.StdLongVector) None
register_signal(self: tango._tango.DeviceImpl, signo: SupportsInt, own_handler: bool) None

register_signal(self, signo, own_handler)

Register this device as device to be informed when signal signo is sent to to the device server process

Parameters:
  • signo (int) – signal identifier

  • own_handler (bool) – true if you want the device signal handler to be executed in its own handler instead of being executed by the signal thread. If this parameter is set to true, care should be taken on how the handler is written. A default false value is provided

remove_attribute(self, attr_name)

Remove one attribute from the device attribute list.

Note: Call of synchronous remove_attribute method from a coroutine function in an asyncio server may cause a deadlock. Use await async_remove_attribute() instead. However, if overriding the synchronous method initialize_dynamic_attributes, then the synchronous remove_attribute method must be used, even in asyncio servers.

Parameters:
  • attr_name (str) – attribute name

  • free_it (bool) – free Attr object flag. Default False

  • clean_db (bool) – clean attribute related info in db. Default True

Raises:

DevFailed

Added in version 9.5.0: free_it parameter. clean_db parameter.

remove_command(self, cmd_name, free_it=False, clean_db=True)

Remove one command from the device command list.

Parameters:
  • cmd_name (str) – command name to be removed from the list

  • free_it (bool) – set to true if the command object must be freed.

  • clean_db – Clean command related information (included polling info if the command is polled) from database.

Raises:

DevFailed

classmethod run_server(args=None, **kwargs)

Run the class as a device server. It is based on the tango.server.run method.

The difference is that the device class and server name are automatically given.

Args:
args (iterable): args as given in the tango.server.run method

without the server name. If None, the sys.argv list is used

kwargs: the other keywords argument are as given

in the tango.server.run method.

server_init_hook()

Tango server_init_hook. Called once the device server admin device (DServer) is exported. Default implementation does nothing.

set_alarm_event(self: tango._tango.DeviceImpl, attr_name: str, implemented: bool, detect: bool = True) None

set_alarm_event(self, attr_name, implemented, detect=True)

Set an implemented flag for the attribute to indicate that the server fires alarm events manually, without the polling to be started.

If the detect parameter is set to true, the criteria specified for the alarm event (rel_change and abs_change) are verified and the event is only pushed if a least one of them are fulfilled (change in value compared to previous event exceeds a threshold). If detect is set to false the event is fired without any value checking!

Parameters:
  • attr_name (str) – attribute name

  • implemented (bool) – True when the server fires alarm events manually.

  • detect (bool) – Triggers the verification of the alarm event properties when set to true. Default value is true.

Added in version 10.0.0.

set_archive_event(self: tango._tango.DeviceImpl, attr_name: str, implemented: bool, detect: bool = True) None

set_alarm_event(self, attr_name, implemented, detect)

Set an implemented flag for the attribute to indicate that the server fires archive events manually, without the polling to be started.

If the detect parameter is set to true, the criteria specified for the archive event (rel_change and abs_change) are verified and the event is only pushed if a least one of them are fulfilled (change in value compared to previous event exceeds a threshold). If detect is set to false the event is fired without any value checking!

Parameters:
  • attr_name (str) – attribute name

  • implemented (bool) – True when the server fires change events manually.

  • detect (bool) – Triggers the verification of the change event properties when set to true. Default value is true.

set_attribute_config(self: tango._tango.DeviceImpl, new_conf: list[AttributeConfig]) None

set_attribute_config (self, new_conf) -> None

Sets attribute configuration locally and in the Tango database

Parameters:

new_conf (list[tango.AttributeConfig]) – The new attribute(s) configuration. One AttributeConfig structure is needed for each attribute to update

Returns:

None

Return type:

None

Added in version 10.0.0.

set_attribute_config_3(self: tango._tango.Device_3Impl, new_conf: list[AttributeConfig_3]) None

set_attribute_config_3 (self, new_conf) -> None

Sets attribute configuration locally and in the Tango database

Parameters:

new_conf (list[tango.AttributeConfig_3]) – The new attribute(s) configuration. One AttributeConfig structure is needed for each attribute to update

Returns:

None

Return type:

None

set_change_event(self: tango._tango.DeviceImpl, attr_name: str, implemented: bool, detect: bool = True) None

set_change_event(self, attr_name, implemented, detect=True)

Set an implemented flag for the attribute to indicate that the server fires change events manually, without the polling to be started.

If the detect parameter is set to true, the criteria specified for the change event (rel_change and abs_change) are verified and the event is only pushed if a least one of them are fulfilled (change in value compared to previous event exceeds a threshold). If detect is set to false the event is fired without any value checking!

Parameters:
  • attr_name (str) – attribute name

  • implemented (bool) – True when the server fires change events manually.

  • detect (bool) – Triggers the verification of the change event properties when set to true. Default value is true.

set_data_ready_event(self: tango._tango.DeviceImpl, attr_name: str, implemented: bool) None

set_alarm_event(self, attr_name, implemented)

Set an implemented flag for the attribute to indicate that the server fires data ready events manually.

Parameters:
  • attr_name (str) – attribute name

  • implemented (bool) – True when the server fires change events manually.

set_kernel_tracing_enabled(self, enabled) None

Enable or disable telemetry tracing of cppTango kernel methods, and for high-level PyTango devices, tracing of the PyTango kernel (BaseDevice) methods.

This is a no-op if telemetry support isn’t compiled into cppTango.

Parameters:

enabled (bool) – True to enable kernel tracing

Added in version 10.0.0.

set_state(self: tango._tango.DeviceImpl, new_state: tango._tango.DevState) None

set_state(self, new_state)

Set device state.

Parameters:

new_state (DevState) – the new device state

set_status(self: tango._tango.DeviceImpl, new_status: str) None

set_status(self, new_status)

Set device status.

Parameters:

new_status (str) – the new device status

set_telemetry_enabled(self, enabled) None

Enable or disable the device’s telemetry interface.

This is a no-op if telemetry support isn’t compiled into cppTango.

Parameters:

enabled (bool) – True to enable telemetry tracing

Added in version 10.0.0.

signal_handler(self: tango._tango.Device_3Impl, signo: SupportsInt) None

signal_handler(self, signo)

Signal handler.

The method executed when the signal arrived in the device server process. This method is defined as virtual and then, can be redefined following device needs.

Parameters:

signo (int) – the signal number

Raises:

DevFailed – This method does not throw exception but a redefined method can.

start_logging(self: tango._tango.DeviceImpl) None

start_logging (self) -> None

Starts logging

stop_logging(self: tango._tango.DeviceImpl) None

stop_logging (self) -> None

Stops logging

stop_poll_attribute(self: tango._tango.DeviceImpl, attr_name: str) None

stop_poll_attribute (self, attr_name) -> None

Remove an attribute from the list of polled attributes.

Parameters:

attr_name (str) – attribute name

Returns:

None

Return type:

None

stop_poll_command(self: tango._tango.DeviceImpl, cmd_name: str) None

stop_poll_command (self, cmd_name) -> None

Remove a command from the list of polled commands.

Parameters:

cmd_name (str) – cmd_name name

Returns:

None

Return type:

None

stop_polling(*args, **kwargs)

Overloaded function.

  1. stop_polling(self: tango._tango.DeviceImpl) -> None

stop_polling(self)

Stop all polling for a device. if the device is polled, call this method before deleting it.

New in PyTango 7.1.2

  1. stop_polling(self: tango._tango.DeviceImpl, with_db_upd: bool) -> None

stop_polling(self, with_db_upd)(self)

Stop all polling for a device. if the device is polled, call this method before deleting it.

Parameters:

with_db_upd (bool) – Is it necessary to update db?

New in PyTango 7.1.2

unregister_signal(self: tango._tango.DeviceImpl, signo: SupportsInt) None

unregister_signal(self, signo)

Unregister this device as device to be informed when signal signo is sent to to the device server process

Parameters:

signo (int) – signal identifier

warn_stream(self, msg, *args, source=None)

Sends the given message to the tango warn stream.

Since PyTango 7.1.3, the same can be achieved with:

print(msg, file=self.log_warn)
Parameters:
  • msg (str) – the message to be sent to the warn stream

  • *args – Arguments to format a message string.

  • source (Callable) – Function that will be inspected for filename and lineno in the log message.

Added in version 9.4.2: added source parameter

write_attr_hardware(self: tango._tango.Device_6Impl, arg0: tango._tango.StdLongVector) None
class tango.server.attribute(fget=None, **kwargs)[source]

Declares a new tango attribute in a Device. To be used like the python native property function. For example, to declare a scalar, tango.DevDouble, read-only attribute called voltage in a PowerSupply Device do:

class PowerSupply(Device):

    voltage = attribute()

    def read_voltage(self):
        return 999.999

The same can be achieved with:

class PowerSupply(Device):

    @attribute
    def voltage(self):
        return 999.999

Note

avoid using dformat parameter. If you need a SPECTRUM attribute of say, boolean type, use instead dtype=(bool,).

Example of an integer writable attribute with a customized label, unit and description:

class PowerSupply(Device):

    current = attribute(label="Current", unit="mA", dtype=int,
                        access=AttrWriteType.READ_WRITE,
                        doc="the power supply current")

    def init_device(self):
        Device.init_device(self)
        self._current = -1

    def read_current(self):
        return self._current

    def write_current(self, current):
        self._current = current

The same, but using attribute as a decorator:

class PowerSupply(Device):

    def init_device(self):
        Device.init_device(self)
        self._current = -1

    @attribute(label="Current", unit="mA", dtype=int)
    def current(self):
        """the power supply current"""
        return 999.999

    @current.write
    def current(self, current):
        self._current = current

In this second format, defining the write implicitly sets the attribute access to READ_WRITE.

Receives multiple keyword arguments:

Parameters:
  • name (str) – attribute name. Default: name of decorated read method, or variable assigned to.

  • dtype (CmdArgType) – Data type (see Data type equivalence). Default: DevDouble (float).

  • dformat (AttrDataFormat) – Data format: SCALAR (0D), SPECTRUM (1D) or IMAGE (2D). Default: SCALAR.

  • max_dim_x (int) – Maximum size for x dimension (ignored for SCALAR format). Default: 1.

  • max_dim_y (int) – Maximum size for y dimension (ignored for SCALAR and SPECTRUM formats). Default: 0.

  • enum_labels (list | tuple | None) – List of enumeration label strings (for enum data type). Default: None.

  • access (AttrWriteType) – Type of the attribute: read-only / read-write / write-only/ read-with-write. Default: READ.

  • fget (str | callable) – Read method name or method object. If not provided, then PyTango will search the method, named "read_<attr_name>".

  • fread (str | callable) – Alias for parameter fget

  • fset (str | callable) – Write method name or method object. If not provided, then PyTango will search the method, named "write_<attr_name>".

  • fwrite (str | callable) – Alias for parameter fset

  • fisallowed (str | callable) – Is-allowed method name or method object. If not provided, then PyTango will search the method, named "is_<attr_name>_allowed".

  • doc (str) – Attribute description. Default: "" [Note_1]

  • description – Alias for parameter doc.

  • label (str) – Attribute label for user interfaces. Default: "<attr_name>".

  • display_level (DispLevel) – Display level on user interfaces. Default: OPERATOR.

  • unit (str) – Physical units the attribute value is in. Default: "".

  • standard_unit (str | int | float | None) – The conversion factor to transform attribute’s value into SI units. Default: "" [Note_2]

  • display_unit (str | int | float | None) – The conversion factor to transform attribute’s value into value usable in user interfaces (hint for clients). Default: "" [Note_2]

  • format (str) – Attribute representation format for user interfaces. Default: "6.2f".

  • min_value (str | int | float | None) – Minimum allowed value. Default: None [Note_2]

  • max_value (str | int | float | None) – Maximum allowed value. Default: None [Note_2]

  • min_alarm (str | int | float | None) – Minimum value to trigger attribute quality to be tango.AttrQuality.ALARM. Default: None [Note_2]

  • max_alarm (str | int | float | None) – Maximum value to trigger attribute quality to be tango.AttrQuality.ALARM. Default: None [Note_2]

  • min_warning (str | int | float | None) – Minimum value to trigger attribute quality to be tango.AttrQuality.WARNING. Default: None [Note_2]

  • max_warning (str | int | float | None) – Maximum value to trigger attribute quality to be tango.AttrQuality.WARNING. Default: None [Note_2]

  • abs_change (str | int | float | None) – Minimum absolute change of attribute value, that causes the change event. E.g., abs_change = 1 will generate an event when: (current - previous) > 1. Default: None [Note_2]

  • rel_change (str | int | float | None) – Minimum relative change (%) of attribute value, that causes change event. E.g., rel_change = 1 will generate an event when: (current - previous) / previous > 1%. Default: None [Note_2]

  • alarm_event_implemented (bool) – indicates if alarm event for this attribute emitted by the code Default: False

  • alarm_event_detect (bool) – enable or disable filtering for alarm event emitted by the code. Default: False

  • change_event_implemented (bool) – indicates if change event for this attribute emitted by the code Default: False

  • change_event_detect (bool) – enable or disable filtering for change event emitted by the code. E.g., if user emits event, by the value changed less, then abs_change or rel_change - event will be filtered out Default: False

  • period (str | int | None) – Time of periodic event generation in milliseconds. This is the minimum time between periodic events. Default: None [Note_2]

  • archive_abs_change (str | int | float | None) – Minimum absolute change of attribute value, that causes the archive event. E.g., archive_abs_change = 1 will generate an event when: (current - previous) > 1. Default: None [Note_2]

  • archive_rel_change (str | int | float | None) – Minimum relative change (%) of attribute value, that causes archive event. E.g., archive_rel_change = 1 will generate an event when: (current - previous) / previous > 1%. Default: None [Note_2]

  • archive_period (str | int | None) – Time, after which the conditions of archive event are checked in milliseconds. Default: None [Note_2]

  • archive_event_implemented (bool) – indicates if archive event for this attribute emitted by the code Default: False

  • archive_event_detect (bool) – enable or disable filtering for archive event emitted by the code. E.g., if user emits event, by the value changed less, then archive_abs_change or archive_rel_change - event will be filtered out Default: False

  • delta_val (str) – RDS (Read Different Set) difference between written and read values that triggers the tango.AttrQuality.ALARM quality. Default: None [Note_2]

  • delta_t (str | int | None) – Minimum time, after which RDS (Read Different Set) difference is checked in milliseconds. Default: None [Note_2]

  • polling_period (int) – Device polling period in milliseconds. Default: -1 (no polling) [Note_3]

  • memorized (bool) – Attribute must be memorized. If True, the latest written value is stored in the Tango database (see also hw_memorized). Default: False.

  • hw_memorized (bool) – If True, memorized value will be restored by calling the attribute write method at startup and after each Init command (only applies if memorized is True). Default: False.

  • data_ready_event_implemented (bool) – indicates if data ready event for this attribute emitted by the code Default: False

  • class_name (str) – name of the device class to which the attribute belongs (only used for error reporting when creating the attribute). Default: None

  • green_mode (bool) – Default green mode for read/write/isallowed functions. If True, run with green mode executor, otherwise run directly. Default: True.

  • read_green_mode (bool) – Green mode for read function. Default: value of green_mode.

  • write_green_mode (bool) – Green mode for write function. Default: value of green_mode.

  • isallowed_green_mode (bool) – Green mode for is_allowed function. Default: value of green_mode.

  • forwarded (bool) – If True, the attribute should be forwarded. Default: False.

[Note_1]

Note

If the attribute is defined with the @attribute decorator, then the read method docstring can be used to as the attribute description. The doc kwarg has the highest priority, then description kwarg, and then docstring:

class TestDevice(Device):

    @attribute
    def my_attr1(self) -> float:
        """This will be used as the docstring for my_attr1"""
        return 1.5

    my_attr2 = attribute()

    def read_my_attr2(self) -> float:
        """This docstring WON'T be used as the description"""
        return 2.5

    @attribute(doc="This will be used as the docstring for my_attr3)
    def my_attr3(self) -> float:
        """This docstring WON'T be used as the description"""
        return 1.5
[Note_2]

Note

The parameters , min_value, max_value, min_alarm, max_alarm, min_warning, max_warning, delta_val, abs_change, archive_abs_change, must be a valid numerical value, represented as either a string, int or float compatible with the attribute’s data type.

Parameters standard_unit, display_unit, rel_change and archive_rel_change must be a valid numerical value, represented as either a string, int or float.

Parameters period, archive_period and delta_t, must be a valid integer value, represented as either a string or int.

In all cases, the value can also be None, or an empty string, to use the default. Typically, disabled.

[Note_3]

Warning

The polling_period from the code is used ONLY if there is no polling period value stored in the Tango DB. After the first run, the value from the code will be stored in the Tango DB and will used for the following runs, even if the value in code is changed later. And vice versa: if the value in the Tango DB was changed (e.g. in Jive), but the code was not, the new value from the DB will be used. The value from the code will only be used again if the value in DB was deleted. Think of it like a default.

Added in version 8.1.7: added green_mode, read_green_mode and write_green_mode options

Added in version 10.1.0: added alarm_event_implemented, alarm_event_detect, change_event_implemented, change_event_detect, archive_event_implemented, archive_event_detect, data_ready_event_implemented options

tango.server.command(f=None, dtype_in: ~typing.Any = <class 'tango.server._DevVoid'>, dformat_in=None, doc_in='', dtype_out: ~typing.Any = <class 'tango.server._DevVoid'>, dformat_out=None, doc_out='', display_level=None, polling_period=None, green_mode=True, fisallowed=None, cmd_green_mode=None, isallowed_green_mode=None)[source]

Declares a new tango command in a Device. To be used like a decorator in the methods you want to declare as tango commands. The following example declares commands:

  • void TurnOn(void)

  • void Ramp(DevDouble current)

  • DevBool Pressurize(DevDouble pressure)

class PowerSupply(Device):

    @command
    def TurnOn(self):
        self.info_stream('Turning on the power supply')

    @command(dtype_in=float)
    def Ramp(self, current):
        self.info_stream('Ramping on %f...' % current)

    @command(dtype_in=float, doc_in='the pressure to be set',
             dtype_out=bool, doc_out='True if it worked, False otherwise')
    def Pressurize(self, pressure):
        self.info_stream('Pressurizing to %f...' % pressure)
        return True

Note

avoid using dformat parameter. If you need a SPECTRUM attribute of say, boolean type, use instead dtype=(bool,).

Parameters:
  • dtype_in – a data type describing the type of parameter. Default is None meaning no parameter.

  • dformat_in (AttrDataFormat) – parameter data format. Default is None.

  • doc_in (str) – parameter documentation

  • dtype_out – a data type describing the type of return value. Default is None meaning no return value.

  • dformat_out (AttrDataFormat) – return value data format. Default is None.

  • doc_out (str) – return value documentation

  • display_level (DispLevel) – display level for the command (optional)

  • polling_period (int) – polling period in milliseconds (optional)

  • green_mode (bool) – DEPRECATED: green mode for command method. If True: run with green mode executor, if False: run directly. See the green_mode parameter deprecation note below for more details.

  • fisallowed (str or callable) – is allowed method for command

  • cmd_green_mode (bool) – green mode for command method. If True: run with green mode executor, if False: run directly See the green_mode parameter deprecation note below for more details.

  • isallowed_green_mode (bool) – green mode for isallowed method. If True: run with green mode executor, if False: run directly See the green_mode parameter deprecation note below for more details.

Added in version 8.1.7: added green_mode option

Added in version 9.2.0: added display_level and polling_period optional argument

Added in version 9.4.0: added fisallowed option

Added in version 10.0.0: added cmd_green_mode and isallowed_green_mode options

Changed in version 10.0.0: the way that the green_mode parameter is interpreted was changed to be consistent with the same parameter for attributes. Now it expects bool, which indicates, if methods should be run with executor (green_mode=True, default) or bypass it (green_mode=False) Before it was either green_mode=None - use executor or green_mode=GreenMode.Synchronous - bypass it. However, due python by default casts GreenMode.Synchronous (which is int value 0) to False bool, old code is automatically backward compatible.

Deprecated since version 10.0.0: green_mode parameter is deprecated and may be removed in future. Use cmd_green_mode and isallowed_green_mode parameters instead. The new parameters match how attributes and pipes are defined, offer more flexibility, and are clearer. If you use both old green_mode, and new isallowed_green_mode and cmd_green_mode - the new ones take priority.

class tango.server.device_property(dtype=None, doc='', mandatory=False, default_value=None, update_db=False)[source]

Declares a new tango device property in a Device. To be used like the python native property function. For example, to declare a scalar, tango.DevString, device property called host in a PowerSupply Device do:

from tango.server import Device, DeviceMeta
from tango.server import device_property

class PowerSupply(Device):

    host = device_property(dtype=str)
    port = device_property(dtype=int, mandatory=True)
Parameters:
  • dtype – Data type (see Data types)

  • doc – property documentation (optional)

  • (optional (mandatory) – default is False)

  • default_value – default value for the property (optional)

  • update_db (bool) – tells if set value should write the value to database. [default: False]

Added in version 8.1.7: added update_db option

class tango.server.class_property(dtype=None, doc='', default_value=None, update_db=False)[source]

Declares a new tango class property in a Device. To be used like the python native property function. For example, to declare a scalar, tango.DevString, class property called port in a PowerSupply Device do:

from tango.server import Device, DeviceMeta
from tango.server import class_property

class PowerSupply(Device):

    port = class_property(dtype=int, default_value=9788)
Parameters:
  • dtype – Data type (see Data types)

  • doc – property documentation (optional)

  • default_value – default value for the property (optional)

  • update_db (bool) – tells if set value should write the value to database. [default: False]

Added in version 8.1.7: added update_db option

tango.server.run(classes, args=None, msg_stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, verbose=False, util=None, event_loop=None, pre_init_callback=None, post_init_callback=None, green_mode=None, raises=False, err_stream=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>)[source]

Provides a simple way to run a tango server. It handles exceptions by writting a message to the msg_stream.

Examples:

Example 1: registering and running a PowerSupply inheriting from Device:

from tango.server import Device, run

class PowerSupply(Device):
    pass

run((PowerSupply,))

Example 2: registering and running a MyServer defined by tango classes MyServerClass and MyServer:

from tango import Device_4Impl, DeviceClass
from tango.server import run

class MyServer(Device_4Impl):
    pass

class MyServerClass(DeviceClass):
    pass

run({'MyServer': (MyServerClass, MyServer)})

Example 3: registering and running a MyServer defined by tango classes MyServerClass and MyServer:

from tango import Device_4Impl, DeviceClass
from tango.server import Device, run

class PowerSupply(Device):
    pass

class MyServer(Device_4Impl):
    pass

class MyServerClass(DeviceClass):
    pass

run([PowerSupply, [MyServerClass, MyServer]])
# or: run({'MyServer': (MyServerClass, MyServer)})

Note

the order of registration of tango classes defines the order tango uses to initialize the corresponding devices. if using a dictionary as argument for classes be aware that the order of registration becomes arbitrary. If you need a predefined order use a sequence or an OrderedDict.

Parameters:
  • classes (Sequence[tango.server.Device] | dict) –

    Defines for which Tango Device Classes the server will run. If dict is provided, it’s key is the tango class name and value is either:

    two element sequence: DeviceClass, DeviceImpl
    three element sequence: DeviceClass, DeviceImpl, tango class name str

  • args (list) – list of command line arguments [default: None, meaning use sys.argv]

  • msg_stream – stream where to put messages [default: sys.stdout]

  • util (Util) – PyTango Util object [default: None meaning create a Util instance]

  • event_loop (callable) – event_loop callable

  • pre_init_callback (callable or tuple) – an optional callback that is executed between the calls Util.init and Util.server_init The optional pre_init_callback can be a callable (without arguments) or a tuple where the first element is the callable, the second is a list of arguments (optional) and the third is a dictionary of keyword arguments (also optional).

  • post_init_callback (callable or tuple) – an optional callback that is executed between the calls Util.server_init and Util.server_run The optional post_init_callback can be a callable (without arguments) or a tuple where the first element is the callable, the second is a list of arguments (optional) and the third is a dictionary of keyword arguments (also optional).

  • raises (bool) – Disable error handling and propagate exceptions from the server

  • err_stream – stream where to put catched exceptions [default: sys.stderr]

Returns:

The Util singleton object

Return type:

Util

Added in version 8.1.2.

Changed in version 8.1.4: when classes argument is a sequence, the items can also be a sequence <TangoClass, TangoClassClass>[, tango class name]

Changed in version 9.2.2: raises argument has been added

Changed in version 9.5.0: pre_init_callback argument has been added

Changed in version 10.0.0: err_stream argument has been added

tango.server.server_run(classes, args=None, msg_stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, verbose=False, util=None, event_loop=None, pre_init_callback=None, post_init_callback=None, green_mode=None, err_stream=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>)[source]

Since PyTango 8.1.2 it is just an alias to run(). Use run() instead.

Added in version 8.0.0.

Changed in version 8.0.3: Added util keyword parameter. Returns util object

Changed in version 8.1.1: Changed default msg_stream from stderr to stdout Added event_loop keyword parameter. Returns util object

Changed in version 8.1.2: Added post_init_callback keyword parameter

Deprecated since version 8.1.2: Use run() instead.

Changed in version 9.5.0: pre_init_callback argument has been added

Changed in version 10.0.0: err_stream argument has been added