# Writing TANGO servers with 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:

    1if __name__ == '__main__':
    2    util = tango.Util(sys.argv)
    3    util.add_class(PyDsExpClass, PyDsExp)
    4
    5    U = tango.Util.instance()
    6    U.server_init()
    7    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

    1def __init__(self, name):
    2    tango.DeviceClass.__init__(self, name)
    3    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_6Impl)

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:

    1def is_IOLong_allowed(self):
    2    self.debug_stream("in is_IOLong_allowed")
    3    return self.get_state() == tango.DevState.ON
    4
    5def IOLong(self, in_data):
    6    self.info_stream('IOLong', in_data)
    7    in_data = in_data * 2
    8    self.info_stream('IOLong returns', in_data)
    9    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:

    1def read_Long_attr(self, the_att):
    2    self.info_stream("read attribute name Long_attr")
    3    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:

    1def write_Short_attr_rw(self,the_att):
    2    self.info_stream("In write_Short_attr_rw for attribute ",the_att.get_name())
    3    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