File: server_old_api.md

package info (click to toggle)
pytango 10.0.2-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 10,216 kB
  • sloc: python: 28,206; cpp: 16,380; sql: 255; sh: 82; makefile: 43
file content (498 lines) | stat: -rw-r--r-- 19,105 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
```{eval-rst}
.. currentmodule:: tango
```

(server-old-api)=

# 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](https://tango-controls.readthedocs.io/en/latest/tools-and-extensions/built-in/pogo/index.html)
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 {class}`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:

```{code-block} python
:linenos: true
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 {meth}`Util.add_class`
  method of the Util class has two arguments which are the Tango class
  PyDsExpClass instance and the Tango PyDsExp instance.
  This {meth}`Util.add_class` method is only available since version
  7.1.2. If you are using an older version please use
  {meth}`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:

```{code-block} python
:linenos: true
class PyDsExpClass(tango.DeviceClass):

    cmd_list = { 'IOLong' : [ [ tango.ArgType.DevLong, "Number" ],
                              [ tango.ArgType.DevLong, "Number * 2" ] ],
                 'IOStringArray' : [ [ tango.ArgType.DevVarStringArray, "Array of string" ],
                                     [ tango.ArgType.DevVarStringArray, "This reversed array"] ],
    }

    attr_list = { 'Long_attr' : [ [ tango.ArgType.DevLong ,
                                    tango.AttrDataFormat.SCALAR ,
                                    tango.AttrWriteType.READ],
                                  { 'min alarm' : 1000, 'max alarm' : 1500 } ],

                 'Short_attr_rw' : [ [ tango.ArgType.DevShort,
                                       tango.AttrDataFormat.SCALAR,
                                       tango.AttrWriteType.READ_WRITE ] ]
    }
```

**Line 1**

: The PyDsExpClass class has to inherit from the {class}`DeviceClass` class

**Line 3 to 7**

: Definition of the cmd_list {class}`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 {class}`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

```{code-block} python
:linenos: true
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 {class}`dict`
called *cmd_list* as a data member of the xxxClass class of the Tango class.
This {class}`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 {class}`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
{class}`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 {class}`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 {class}`dict`
called **attr_list** as a data
member of the xxxClass class of the Tango class. This {class}`dict` has one element
per attribute. The element key is the attribute name. The element value is a
python {class}`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
{class}`tango.ArgType` pseudo enunmeration. The attribute data format is one
of the possible value of the {class}`tango.AttrDataFormat` pseudo enumeration
and the attribute R/W type is one of the possible value of the
{class}`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 {class}`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:

```{code-block} python
:linenos: true
class PyDsExp(tango.Device):

    def __init__(self,cl,name):
        tango.Device.__init__(self, cl, name)
        self.info_stream('In PyDsExp.__init__')
        PyDsExp.init_device(self)

    def init_device(self):
        self.info_stream('In Python init_device method')
        self.set_state(tango.DevState.ON)
        self.attr_short_rw = 66
        self.attr_long = 1246

    #------------------------------------------------------------------

    def delete_device(self):
        self.info_stream('PyDsExp.delete_device')

    #------------------------------------------------------------------
    # COMMANDS
    #------------------------------------------------------------------

    def is_IOLong_allowed(self):
        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

    #------------------------------------------------------------------

    def is_IOStringArray_allowed(self):
        return self.get_state() == tango.DevState.ON

    def IOStringArray(self, in_data):
        l = range(len(in_data)-1, -1, -1)
        out_index=0
        out_data=[]
        for i in l:
            self.info_stream('IOStringArray <-', in_data[out_index])
            out_data.append(in_data[i])
            self.info_stream('IOStringArray ->',out_data[out_index])
            out_index += 1
        self.y = out_data
        return out_data

    #------------------------------------------------------------------
    # ATTRIBUTES
    #------------------------------------------------------------------

    def read_attr_hardware(self, data):
        self.info_stream('In read_attr_hardware')

    def read_Long_attr(self, the_att):
        self.info_stream("read_Long_attr")

        the_att.set_value(self.attr_long)

    def is_Long_attr_allowed(self, req_type):
        return self.get_state() in (tango.DevState.ON,)

    def read_Short_attr_rw(self, the_att):
        self.info_stream("read_Short_attr_rw")

        the_att.set_value(self.attr_short_rw)

    def write_Short_attr_rw(self, the_att):
        self.info_stream("write_Short_attr_rw")

        self.attr_short_rw = the_att.get_write_value()

    def is_Short_attr_rw_allowed(self, req_type):
        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 {class}`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 {class}`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       | {py:obj}`int`            | None         | No        |
| read_attr_hardware   | sequence\<{py:obj}`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 {ref}`pytango-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:

```{code-block} python
:linenos: true
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](#logging) 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](#logging) 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 {class}`Attr`.
Unlike the commands, the is_allowed method for attributes receives a parameter
of type {class}`AttReqtype`.

Please check {ref}`pytango-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*:

```{code-block} python
:linenos: true
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](#logging)
  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:

```{code-block} python
:linenos: true
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](#logging) 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