tango-frame 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ from .auto_dispatch import AutoDispatchClient, AutoDispatchDevice
2
+ from .server import run_device_server
3
+
4
+ __all__ = [
5
+ "AutoDispatchClient",
6
+ "AutoDispatchDevice",
7
+ "run_device_server",
8
+ ]
@@ -0,0 +1,379 @@
1
+ """Automatic adaptation between ordinary Python classes and TANGO devices."""
2
+
3
+ from types import MethodType
4
+ from typing import Any, Dict, Optional, Set, Type
5
+
6
+ from tango import AttrWriteType, DevState
7
+ from tango.server import Device, attribute, command
8
+
9
+ from .codec import pack_call, pack_value, unpack_call, unpack_value
10
+ from .config import Config
11
+ from .introspection import PropertySpec, public_methods, public_properties
12
+ from .type_mapping import (
13
+ input_type,
14
+ output_type,
15
+ tango_value_type,
16
+ uses_encoded_input,
17
+ uses_encoded_output,
18
+ )
19
+
20
+
21
+ class AutoDispatchDevice(Device):
22
+ """Expose an ordinary Python device class as a TANGO device server.
23
+
24
+ Subclasses set ``device_class`` to the transport-independent Python class.
25
+ Public methods become TANGO commands and public properties become TANGO
26
+ attributes.
27
+ """
28
+
29
+ device_class = None # type: Optional[Type[Any]]
30
+ excluded_commands = set() # type: Set[str]
31
+
32
+ def init_device(self) -> None:
33
+ """Create the local Python device object when TANGO initializes it.
34
+
35
+ Raises:
36
+ RuntimeError: If no Python device class has been configured.
37
+ """
38
+ Device.init_device(self)
39
+ if self.device_class is None:
40
+ raise RuntimeError("device_class is not configured")
41
+
42
+ # The authoritative local device class is reconstructed inside the
43
+ # TANGO device server process.
44
+ self._device_object = self.device_class()
45
+ self.set_state(DevState.ON)
46
+
47
+ def delete_device(self) -> None:
48
+ """Release the wrapped Python device object when available."""
49
+ device_object = getattr(self, "_device_object", None)
50
+ if device_object is not None:
51
+ release = getattr(device_object, "release", None)
52
+ if callable(release):
53
+ release()
54
+
55
+ def initialize_dynamic_attributes(self) -> None:
56
+ """Install TANGO commands and attributes from the Python class.
57
+
58
+ Raises:
59
+ RuntimeError: If no Python device class has been configured.
60
+ """
61
+ if self.device_class is None:
62
+ raise RuntimeError("device_class is not configured")
63
+
64
+ _install_commands(self, self.device_class)
65
+ _install_attributes(self, self.device_class)
66
+
67
+
68
+ def _command_handler(
69
+ name: str,
70
+ has_input: bool,
71
+ encoded_input: bool,
72
+ encoded_output: bool,
73
+ ) -> Any:
74
+ """Build a dynamic TANGO command handler.
75
+
76
+ Args:
77
+ name: Python method and TANGO command name.
78
+ has_input: Whether the command accepts a TANGO input value.
79
+ encoded_input: Whether the input uses the JSON call envelope.
80
+ encoded_output: Whether the result uses JSON value encoding.
81
+
82
+ Returns:
83
+ Unbound handler function ready to bind to a device instance.
84
+ """
85
+ if not has_input:
86
+ def handler(device_self: AutoDispatchDevice) -> Any:
87
+ """Dispatch a command without TANGO input."""
88
+ target = getattr(device_self._device_object, name)
89
+ result = target()
90
+ if encoded_output:
91
+ return pack_value(result)
92
+ return result
93
+ else:
94
+ def handler(device_self: AutoDispatchDevice, value: Any) -> Any:
95
+ """Dispatch a command with native or encoded TANGO input."""
96
+ target = getattr(device_self._device_object, name)
97
+ if encoded_input:
98
+ args, kwargs = unpack_call(value)
99
+ result = target(*args, **kwargs)
100
+ else:
101
+ result = target(value)
102
+ if encoded_output:
103
+ return pack_value(result)
104
+ return result
105
+
106
+ handler.__name__ = name
107
+ return handler
108
+
109
+
110
+ def _install_commands(device: AutoDispatchDevice, device_class: Type[Any]) -> None:
111
+ """Install public Python methods as dynamic TANGO commands.
112
+
113
+ Args:
114
+ device: Running PyTango device instance.
115
+ device_class: Ordinary Python device class being exposed.
116
+ """
117
+ for spec in public_methods(device_class):
118
+ if spec.name in device.excluded_commands:
119
+ continue
120
+
121
+ parameters = list(spec.signature.parameters.values())
122
+ has_input = len(parameters) != 0
123
+ encoded_input = uses_encoded_input(spec.signature)
124
+ encoded_output = uses_encoded_output(spec.signature)
125
+ handler = _command_handler(
126
+ spec.name,
127
+ has_input,
128
+ encoded_input,
129
+ encoded_output,
130
+ )
131
+
132
+ # add_command() installs the supplied callable on this device instance.
133
+ # Bind the generated method explicitly before creating the command.
134
+ bound_handler = MethodType(handler, device)
135
+ tango_command = command(
136
+ bound_handler,
137
+ dtype_in=input_type(spec.signature),
138
+ dtype_out=output_type(spec.signature),
139
+ )
140
+ device.add_command(tango_command, device_level=True)
141
+
142
+
143
+ def _property_reader(name: str, encoded: bool) -> Any:
144
+ """Build a dynamic TANGO attribute reader.
145
+
146
+ Args:
147
+ name: Python property and TANGO attribute name.
148
+ encoded: Whether the value uses JSON encoding.
149
+
150
+ Returns:
151
+ Unbound attribute reader.
152
+ """
153
+ def reader(device_self: AutoDispatchDevice, attr: Any) -> Any:
154
+ """Read a wrapped Python property."""
155
+ value = getattr(device_self._device_object, name)
156
+ if encoded:
157
+ return pack_value(value)
158
+ return value
159
+
160
+ reader.__name__ = "read_" + name
161
+ return reader
162
+
163
+
164
+ def _property_writer(name: str, encoded: bool) -> Any:
165
+ """Build a dynamic TANGO attribute writer.
166
+
167
+ Args:
168
+ name: Python property and TANGO attribute name.
169
+ encoded: Whether the value uses JSON encoding.
170
+
171
+ Returns:
172
+ Unbound attribute writer.
173
+ """
174
+ def writer(device_self: AutoDispatchDevice, attr: Any) -> None:
175
+ """Write a wrapped Python property."""
176
+ value = attr.get_write_value()
177
+ if encoded:
178
+ value = unpack_value(value)
179
+ setattr(device_self._device_object, name, value)
180
+
181
+ writer.__name__ = "write_" + name
182
+ return writer
183
+
184
+
185
+ def _install_attributes(device: AutoDispatchDevice, device_class: Type[Any]) -> None:
186
+ """Install public Python properties as dynamic TANGO attributes.
187
+
188
+ Args:
189
+ device: Running PyTango device instance.
190
+ device_class: Ordinary Python device class being exposed.
191
+ """
192
+ for spec in public_properties(device_class):
193
+ dtype = tango_value_type(spec.annotation)
194
+ encoded = dtype is None
195
+ if encoded:
196
+ dtype = str
197
+
198
+ access = AttrWriteType.READ
199
+ if spec.writable:
200
+ access = AttrWriteType.READ_WRITE
201
+
202
+ reader = MethodType(_property_reader(spec.name, encoded), device)
203
+ kwargs = {
204
+ "name": spec.name,
205
+ "dtype": dtype,
206
+ "access": access,
207
+ "fget": reader,
208
+ }
209
+
210
+ if spec.writable:
211
+ writer = MethodType(_property_writer(spec.name, encoded), device)
212
+ kwargs["fset"] = writer
213
+
214
+ tango_attribute = attribute(**kwargs)
215
+ device.add_attribute(tango_attribute)
216
+
217
+
218
+ class AutoDispatchClient(object):
219
+ """Reconstruct a Python device API over a TANGO connection.
220
+
221
+ ``device_class`` defines the local Python interface. The remote TANGO
222
+ device may be generated by this framework or independently implemented, as
223
+ long as its commands and attributes match that interface.
224
+ """
225
+
226
+ device_class = None # type: Optional[Type[Any]]
227
+ config = None # type: Optional[Config]
228
+
229
+ def __init__(self, config: Optional[Config] = None) -> None:
230
+ """Create a reconstructed client for a TANGO device.
231
+
232
+ Args:
233
+ config: Connection configuration. If omitted, the class-level
234
+ ``config`` value is used.
235
+
236
+ Raises:
237
+ RuntimeError: If ``device_class`` or connection configuration is
238
+ missing.
239
+ """
240
+ from .client import TangoTransport
241
+
242
+ if self.device_class is None:
243
+ raise RuntimeError("device_class is not configured")
244
+
245
+ selected_config = config
246
+ if selected_config is None:
247
+ selected_config = type(self).config
248
+ if selected_config is None:
249
+ raise RuntimeError("config is not configured")
250
+
251
+ object.__setattr__(self, "_config", selected_config)
252
+ object.__setattr__(self, "_transport", TangoTransport(selected_config))
253
+
254
+ property_specs = {} # type: Dict[str, PropertySpec]
255
+ for item in public_properties(self.device_class):
256
+ property_specs[item.name] = item
257
+ object.__setattr__(self, "_property_specs", property_specs)
258
+ _install_client_methods(self)
259
+
260
+ def __getattr__(self, name: str) -> Any:
261
+ """Read a reconstructed Python property through TANGO.
262
+
263
+ Args:
264
+ name: Python property name.
265
+
266
+ Returns:
267
+ Remote attribute value.
268
+
269
+ Raises:
270
+ AttributeError: If the name is not a reconstructed property.
271
+ """
272
+ specs = object.__getattribute__(self, "_property_specs")
273
+ if name in specs:
274
+ spec = specs[name]
275
+ encoded = tango_value_type(spec.annotation) is None
276
+ value = self._transport.read_attribute(name)
277
+ if encoded:
278
+ return unpack_value(value)
279
+ return value
280
+ raise AttributeError(name)
281
+
282
+ def __setattr__(self, name: str, value: Any) -> None:
283
+ """Write a reconstructed Python property through TANGO.
284
+
285
+ Args:
286
+ name: Python property name.
287
+ value: Value to assign.
288
+
289
+ Raises:
290
+ AttributeError: If a reconstructed property is read-only.
291
+ """
292
+ if name.startswith("_"):
293
+ object.__setattr__(self, name, value)
294
+ return
295
+
296
+ specs = object.__getattribute__(self, "_property_specs")
297
+ if name in specs:
298
+ spec = specs[name]
299
+ if not spec.writable:
300
+ raise AttributeError("read-only property: " + name)
301
+
302
+ encoded = tango_value_type(spec.annotation) is None
303
+ if encoded:
304
+ value = pack_value(value)
305
+
306
+ self._transport.write_attribute(name, value)
307
+ return
308
+
309
+ object.__setattr__(self, name, value)
310
+
311
+ @property
312
+ def tango_config(self) -> Config:
313
+ """Return the TANGO connection configuration.
314
+
315
+ Returns:
316
+ Configuration used by this reconstructed client.
317
+ """
318
+ return object.__getattribute__(self, "_config")
319
+
320
+
321
+ def _client_method(name: str, signature: Any) -> Any:
322
+ """Build a client method that dispatches a TANGO command.
323
+
324
+ Args:
325
+ name: Python method and TANGO command name.
326
+ signature: Original Python method signature without ``self``.
327
+
328
+ Returns:
329
+ Unbound client method ready to bind to a client instance.
330
+ """
331
+ encoded_input = uses_encoded_input(signature)
332
+ encoded_output = uses_encoded_output(signature)
333
+
334
+ def method(
335
+ client_self: AutoDispatchClient,
336
+ *args: Any,
337
+ **kwargs: Any
338
+ ) -> Any:
339
+ """Dispatch one reconstructed Python method through TANGO."""
340
+ if encoded_input:
341
+ value = pack_call(tuple(args), dict(kwargs))
342
+ result = client_self._transport.command(name, value)
343
+ else:
344
+ parameters = list(signature.parameters.values())
345
+ if len(parameters) == 0:
346
+ result = client_self._transport.command(name)
347
+ else:
348
+ bound = signature.bind(*args, **kwargs)
349
+ bound.apply_defaults()
350
+ value = next(iter(bound.arguments.values()))
351
+ result = client_self._transport.command(name, value)
352
+
353
+ if encoded_output:
354
+ return unpack_value(result)
355
+ return result
356
+
357
+ method.__name__ = name
358
+ method.__signature__ = signature
359
+ return method
360
+
361
+
362
+ def _install_client_methods(client: AutoDispatchClient) -> None:
363
+ """Install reconstructed remote methods on one client instance.
364
+
365
+ Args:
366
+ client: Auto-dispatch client instance.
367
+ """
368
+ client_class = type(client)
369
+ if client.device_class is None:
370
+ raise RuntimeError("device_class is not configured")
371
+
372
+ for spec in public_methods(client.device_class):
373
+ # Device-specific client methods are local overrides and must not be
374
+ # replaced by automatically generated remote dispatch methods.
375
+ if spec.name in client_class.__dict__:
376
+ continue
377
+
378
+ method = _client_method(spec.name, spec.signature)
379
+ object.__setattr__(client, spec.name, MethodType(method, client))
tango_frame/client.py ADDED
@@ -0,0 +1,124 @@
1
+ """Client-side adapters for native and reconstructed TANGO devices."""
2
+
3
+ from typing import Any, Optional
4
+
5
+ from tango import DeviceProxy as NativeDeviceProxy
6
+
7
+ from .config import Config
8
+
9
+
10
+ class DeviceProxy(object):
11
+ """Framework proxy for a native TANGO device.
12
+
13
+ This class does not reconstruct a Python device class. It creates the
14
+ native PyTango ``DeviceProxy`` from ``Config`` and transparently
15
+ delegates the normal TANGO client API to it.
16
+
17
+ Args:
18
+ config: TANGO connection configuration.
19
+ """
20
+
21
+ def __init__(self, config: Config) -> None:
22
+ """Create a native TANGO proxy from framework configuration.
23
+
24
+ Args:
25
+ config: TANGO connection configuration.
26
+ """
27
+ self._config = config
28
+ self._proxy = NativeDeviceProxy(config.device_url())
29
+
30
+ def __getattr__(self, name: str) -> Any:
31
+ """Delegate unknown members to the native PyTango proxy.
32
+
33
+ Args:
34
+ name: Attribute or command name requested by the caller.
35
+
36
+ Returns:
37
+ Member exposed by the native ``tango.DeviceProxy``.
38
+ """
39
+ return getattr(self._proxy, name)
40
+
41
+ @property
42
+ def config(self) -> Config:
43
+ """Return the framework connection configuration.
44
+
45
+ Returns:
46
+ TANGO connection configuration used by this proxy.
47
+ """
48
+ return self._config
49
+
50
+ @property
51
+ def native_proxy(self) -> NativeDeviceProxy:
52
+ """Return the underlying native PyTango proxy.
53
+
54
+ Returns:
55
+ Native ``tango.DeviceProxy`` instance.
56
+ """
57
+ return self._proxy
58
+
59
+
60
+ class TangoTransport(object):
61
+ """Transport used by ``AutoDispatchClient`` for reconstructed Python APIs.
62
+
63
+ Args:
64
+ config: TANGO connection configuration.
65
+ """
66
+
67
+ def __init__(self, config: Config) -> None:
68
+ """Initialize transport through the framework ``DeviceProxy``.
69
+
70
+ Args:
71
+ config: TANGO connection configuration.
72
+ """
73
+ self._device = DeviceProxy(config=config)
74
+
75
+ def command(self, name: str, value: Any = None) -> Any:
76
+ """Execute a TANGO command.
77
+
78
+ Args:
79
+ name: TANGO command name.
80
+ value: Optional command input value.
81
+
82
+ Returns:
83
+ Command result returned by PyTango.
84
+ """
85
+ if value is None:
86
+ return self._device.native_proxy.command_inout(name)
87
+ return self._device.native_proxy.command_inout(name, value)
88
+
89
+ def read_attribute(self, name: str) -> Any:
90
+ """Read a TANGO attribute value.
91
+
92
+ Args:
93
+ name: TANGO attribute name.
94
+
95
+ Returns:
96
+ Attribute value.
97
+ """
98
+ return self._device.native_proxy.read_attribute(name).value
99
+
100
+ def write_attribute(self, name: str, value: Any) -> None:
101
+ """Write a TANGO attribute value.
102
+
103
+ Args:
104
+ name: TANGO attribute name.
105
+ value: Value written to the attribute.
106
+ """
107
+ self._device.native_proxy.write_attribute(name, value)
108
+
109
+ def ping(self) -> int:
110
+ """Ping the remote TANGO device.
111
+
112
+ Returns:
113
+ Round-trip time reported by PyTango in microseconds.
114
+ """
115
+ return self._device.native_proxy.ping()
116
+
117
+ @property
118
+ def proxy(self) -> NativeDeviceProxy:
119
+ """Return the underlying native PyTango proxy.
120
+
121
+ Returns:
122
+ Native ``tango.DeviceProxy`` instance.
123
+ """
124
+ return self._device.native_proxy
tango_frame/codec.py ADDED
@@ -0,0 +1,111 @@
1
+ """JSON codec used when a Python call cannot use a native TANGO type."""
2
+
3
+ import base64
4
+ import json
5
+ from typing import Any, Dict, Tuple
6
+
7
+
8
+ _TYPE_KEY = "__tango_frame_type__"
9
+
10
+
11
+ def _encode(value: Any) -> Any:
12
+ """Convert Python values into JSON-serializable values.
13
+
14
+ Args:
15
+ value: Python value to encode.
16
+
17
+ Returns:
18
+ JSON-serializable representation.
19
+ """
20
+ if isinstance(value, bytes):
21
+ return {
22
+ _TYPE_KEY: "bytes",
23
+ "data": base64.b64encode(value).decode("ascii"),
24
+ }
25
+ if isinstance(value, tuple):
26
+ return {
27
+ _TYPE_KEY: "tuple",
28
+ "items": [_encode(item) for item in value],
29
+ }
30
+ if isinstance(value, list):
31
+ return [_encode(item) for item in value]
32
+ if isinstance(value, dict):
33
+ return {str(key): _encode(item) for key, item in value.items()}
34
+ return value
35
+
36
+
37
+ def _decode(value: Any) -> Any:
38
+ """Restore a Python value from its JSON-compatible representation.
39
+
40
+ Args:
41
+ value: Decoded JSON value.
42
+
43
+ Returns:
44
+ Restored Python value.
45
+ """
46
+ if isinstance(value, list):
47
+ return [_decode(item) for item in value]
48
+ if isinstance(value, dict):
49
+ value_type = value.get(_TYPE_KEY)
50
+ if value_type == "bytes":
51
+ return base64.b64decode(value["data"].encode("ascii"))
52
+ if value_type == "tuple":
53
+ return tuple(_decode(item) for item in value["items"])
54
+ return {key: _decode(item) for key, item in value.items()}
55
+ return value
56
+
57
+
58
+ def pack_call(args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> str:
59
+ """Serialize positional and keyword arguments into one TANGO string.
60
+
61
+ Args:
62
+ args: Positional call arguments.
63
+ kwargs: Keyword call arguments.
64
+
65
+ Returns:
66
+ Compact JSON payload.
67
+ """
68
+ return json.dumps(
69
+ {"args": _encode(args), "kwargs": _encode(kwargs)},
70
+ ensure_ascii=False,
71
+ separators=(",", ":"),
72
+ )
73
+
74
+
75
+ def unpack_call(payload: str) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
76
+ """Deserialize a call payload.
77
+
78
+ Args:
79
+ payload: JSON call payload.
80
+
81
+ Returns:
82
+ Tuple containing positional arguments and keyword arguments.
83
+ """
84
+ data = json.loads(payload)
85
+ args = _decode(data["args"])
86
+ kwargs = _decode(data["kwargs"])
87
+ return tuple(args), dict(kwargs)
88
+
89
+
90
+ def pack_value(value: Any) -> str:
91
+ """Serialize a non-native Python value.
92
+
93
+ Args:
94
+ value: Python value to serialize.
95
+
96
+ Returns:
97
+ Compact JSON payload.
98
+ """
99
+ return json.dumps(_encode(value), ensure_ascii=False, separators=(",", ":"))
100
+
101
+
102
+ def unpack_value(payload: str) -> Any:
103
+ """Deserialize a non-native Python value.
104
+
105
+ Args:
106
+ payload: JSON payload.
107
+
108
+ Returns:
109
+ Restored Python value.
110
+ """
111
+ return _decode(json.loads(payload))
tango_frame/config.py ADDED
@@ -0,0 +1,67 @@
1
+ """Configuration objects for TANGO client connections."""
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class Config(object):
7
+ """Store the connection settings for a TANGO device.
8
+
9
+ Normal operation uses the TANGO database namespace. A database-less
10
+ connection is supported only for local tests and requires ``tango_host``.
11
+
12
+ Args:
13
+ device_name: TANGO device name in ``domain/family/member`` form, or a
14
+ device alias when a database is used.
15
+ tango_host: TANGO database endpoint in ``host:port`` form. If omitted
16
+ for a database connection, PyTango resolves the device using the
17
+ process TANGO_HOST configuration.
18
+ database: Whether the normal TANGO database namespace is used.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ device_name: str,
24
+ tango_host: Optional[str] = None,
25
+ database: bool = True,
26
+ ) -> None:
27
+ """Initialize TANGO connection settings.
28
+
29
+ Args:
30
+ device_name: TANGO device name or database alias.
31
+ tango_host: TANGO database endpoint in ``host:port`` form.
32
+ database: Whether to resolve the device through the TANGO database.
33
+
34
+ Raises:
35
+ ValueError: If required configuration is missing or inconsistent.
36
+ """
37
+ if not device_name:
38
+ raise ValueError("device_name must not be empty")
39
+ if not database and not tango_host:
40
+ raise ValueError("tango_host is required when database is False")
41
+
42
+ self.device_name = device_name
43
+ self.tango_host = tango_host
44
+ self.database = database
45
+
46
+ def device_url(self) -> str:
47
+ """Return the device identifier passed to native ``tango.DeviceProxy``.
48
+
49
+ Returns:
50
+ Device name, alias, or a fully qualified TANGO URL.
51
+ """
52
+ # With no explicit host, leave namespace resolution to the normal
53
+ # PyTango/TANGO_HOST configuration.
54
+ if self.database and self.tango_host is None:
55
+ return self.device_name
56
+
57
+ if self.database:
58
+ return "tango://{0}/{1}".format(
59
+ self.tango_host,
60
+ self.device_name,
61
+ )
62
+
63
+ # Database-less addressing is intentionally isolated to local tests.
64
+ return "tango://{0}/{1}#dbase=no".format(
65
+ self.tango_host,
66
+ self.device_name,
67
+ )
@@ -0,0 +1,91 @@
1
+ """Introspection helpers for ordinary Python device classes."""
2
+
3
+ import inspect
4
+ from typing import Any, List, NamedTuple, Type
5
+
6
+
7
+ class MethodSpec(NamedTuple):
8
+ """Describe one public Python method.
9
+
10
+ Attributes:
11
+ name: Public method name.
12
+ signature: Method signature without the instance ``self`` parameter.
13
+ """
14
+
15
+ name: str
16
+ signature: inspect.Signature
17
+
18
+
19
+ class PropertySpec(NamedTuple):
20
+ """Describe one public Python property.
21
+
22
+ Attributes:
23
+ name: Public property name.
24
+ descriptor: Original Python property descriptor.
25
+ annotation: Getter return annotation used for TANGO type mapping.
26
+ writable: Whether the property has a setter.
27
+ """
28
+
29
+ name: str
30
+ descriptor: property
31
+ annotation: Any
32
+ writable: bool
33
+
34
+
35
+ def public_methods(device_class: Type[Any]) -> List[MethodSpec]:
36
+ """Return public callable methods declared by a device class.
37
+
38
+ Args:
39
+ device_class: Ordinary Python device class to inspect.
40
+
41
+ Returns:
42
+ Public method specifications.
43
+ """
44
+ result = [] # type: List[MethodSpec]
45
+ for name in dir(device_class):
46
+ if name.startswith("_"):
47
+ continue
48
+
49
+ raw = getattr(device_class, name)
50
+ if not callable(raw):
51
+ continue
52
+
53
+ signature = inspect.signature(raw)
54
+ parameters = list(signature.parameters.values())
55
+ if parameters and parameters[0].name == "self":
56
+ signature = signature.replace(parameters=parameters[1:])
57
+
58
+ result.append(MethodSpec(name=name, signature=signature))
59
+ return result
60
+
61
+
62
+ def public_properties(device_class: Type[Any]) -> List[PropertySpec]:
63
+ """Return public properties declared by a device class.
64
+
65
+ Args:
66
+ device_class: Ordinary Python device class to inspect.
67
+
68
+ Returns:
69
+ Public property specifications.
70
+ """
71
+ result = [] # type: List[PropertySpec]
72
+ for name in dir(device_class):
73
+ if name.startswith("_"):
74
+ continue
75
+
76
+ descriptor = getattr(device_class, name)
77
+ if not isinstance(descriptor, property):
78
+ continue
79
+
80
+ # A property getter is required by Python's property protocol for a
81
+ # readable property. Its return annotation defines the TANGO type.
82
+ annotation = inspect.signature(descriptor.fget).return_annotation
83
+ result.append(
84
+ PropertySpec(
85
+ name=name,
86
+ descriptor=descriptor,
87
+ annotation=annotation,
88
+ writable=descriptor.fset is not None,
89
+ )
90
+ )
91
+ return result
tango_frame/server.py ADDED
@@ -0,0 +1,26 @@
1
+ """Helpers for starting TANGO device servers."""
2
+
3
+ from typing import Any, List, Optional, Sequence, Type
4
+
5
+ from tango.server import run
6
+
7
+
8
+ def run_device_server(
9
+ device_class: Type[Any],
10
+ args: Optional[Sequence[str]] = None,
11
+ ) -> None:
12
+ """Run a PyTango device server class.
13
+
14
+ The helper does not force database-less operation. Normal TANGO database
15
+ startup arguments can therefore be supplied by the application. ``-nodb``
16
+ remains an application-level option for local tests only.
17
+
18
+ Args:
19
+ device_class: PyTango ``Device`` subclass to run.
20
+ args: Optional argument sequence passed to ``tango.server.run``.
21
+ """
22
+ run_args = None # type: Optional[List[str]]
23
+ if args is not None:
24
+ run_args = list(args)
25
+
26
+ run((device_class,), args=run_args)
@@ -0,0 +1,166 @@
1
+ """Map Python 3.7 type annotations onto PyTango value types."""
2
+
3
+ import inspect
4
+ from typing import Any, List, Optional, Type
5
+
6
+
7
+ def _list_element_type(annotation: Any) -> Optional[Type[Any]]:
8
+ """Return the supported element type of a homogeneous list annotation.
9
+
10
+ Python 3.7 does not provide ``typing.get_origin`` or ``typing.get_args``.
11
+ The compatibility path therefore uses the ``__origin__`` and ``__args__``
12
+ attributes exposed by ``typing.List``.
13
+
14
+ Args:
15
+ annotation: Python type annotation.
16
+
17
+ Returns:
18
+ Supported list element type, or ``None`` when unsupported.
19
+ """
20
+ origin = getattr(annotation, "__origin__", None)
21
+ args = getattr(annotation, "__args__", ())
22
+ if origin in (list, List) and len(args) == 1:
23
+ element = args[0]
24
+ if element in (bool, int, float, str):
25
+ return element
26
+ return None
27
+
28
+
29
+ def tango_scalar_type(annotation: Any) -> Optional[Any]:
30
+ """Map a scalar Python annotation to a PyTango high-level type.
31
+
32
+ Args:
33
+ annotation: Python type annotation.
34
+
35
+ Returns:
36
+ PyTango-compatible scalar type, or ``None`` when unsupported.
37
+ """
38
+ if annotation is bool:
39
+ return bool
40
+ if annotation is int:
41
+ return int
42
+ if annotation is float:
43
+ return float
44
+ if annotation is str:
45
+ return str
46
+ return None
47
+
48
+
49
+ def tango_array_type(annotation: Any) -> Optional[Any]:
50
+ """Map a homogeneous list annotation to a PyTango spectrum type.
51
+
52
+ Args:
53
+ annotation: Python type annotation.
54
+
55
+ Returns:
56
+ PyTango high-level spectrum type, or ``None`` when unsupported.
57
+ """
58
+ element = _list_element_type(annotation)
59
+ if element is None:
60
+ return None
61
+ return (element,)
62
+
63
+
64
+ def tango_value_type(annotation: Any) -> Optional[Any]:
65
+ """Map a supported Python annotation to a PyTango value type.
66
+
67
+ Args:
68
+ annotation: Python type annotation.
69
+
70
+ Returns:
71
+ PyTango-compatible type, or ``None`` when JSON fallback is required.
72
+ """
73
+ scalar = tango_scalar_type(annotation)
74
+ if scalar is not None:
75
+ return scalar
76
+ return tango_array_type(annotation)
77
+
78
+
79
+ def is_void(annotation: Any) -> bool:
80
+ """Return whether an annotation represents no return value.
81
+
82
+ Args:
83
+ annotation: Python return annotation.
84
+
85
+ Returns:
86
+ ``True`` for ``None`` or ``NoneType``.
87
+ """
88
+ return annotation is None or annotation is type(None)
89
+
90
+
91
+ def input_type(signature: inspect.Signature) -> Optional[Any]:
92
+ """Determine the TANGO command input type for a Python signature.
93
+
94
+ Args:
95
+ signature: Python method signature without ``self``.
96
+
97
+ Returns:
98
+ Native PyTango type, ``str`` for encoded input, or ``None`` for void.
99
+ """
100
+ parameters = list(signature.parameters.values())
101
+ if len(parameters) == 0:
102
+ return None
103
+ if len(parameters) == 1:
104
+ parameter = parameters[0]
105
+ if parameter.kind in (
106
+ inspect.Parameter.POSITIONAL_ONLY,
107
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
108
+ ):
109
+ native = tango_value_type(parameter.annotation)
110
+ if native is not None:
111
+ return native
112
+ return str
113
+
114
+
115
+ def output_type(signature: inspect.Signature) -> Optional[Any]:
116
+ """Determine the TANGO command output type for a Python signature.
117
+
118
+ Args:
119
+ signature: Python method signature without ``self``.
120
+
121
+ Returns:
122
+ Native PyTango type, ``str`` for encoded output, or ``None`` for void.
123
+ """
124
+ annotation = signature.return_annotation
125
+ if is_void(annotation):
126
+ return None
127
+
128
+ native = tango_value_type(annotation)
129
+ if native is not None:
130
+ return native
131
+ return str
132
+
133
+
134
+ def uses_encoded_input(signature: inspect.Signature) -> bool:
135
+ """Return whether a call requires the JSON input envelope.
136
+
137
+ Args:
138
+ signature: Python method signature without ``self``.
139
+
140
+ Returns:
141
+ ``True`` when the input cannot be represented by one native TANGO value.
142
+ """
143
+ parameters = list(signature.parameters.values())
144
+ if len(parameters) == 0:
145
+ return False
146
+ if len(parameters) == 1:
147
+ parameter = parameters[0]
148
+ native = tango_value_type(parameter.annotation)
149
+ if native is not None:
150
+ return False
151
+ return True
152
+
153
+
154
+ def uses_encoded_output(signature: inspect.Signature) -> bool:
155
+ """Return whether a return value requires JSON encoding.
156
+
157
+ Args:
158
+ signature: Python method signature without ``self``.
159
+
160
+ Returns:
161
+ ``True`` when the return type has no native TANGO representation.
162
+ """
163
+ annotation = signature.return_annotation
164
+ if is_void(annotation):
165
+ return False
166
+ return tango_value_type(annotation) is None
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: tango-frame
3
+ Version: 0.1.1
4
+ Summary: Automatic TANGO dispatch framework for ordinary Python device classes
5
+ Requires-Python: >=3.8
6
+ License-File: LICENSE
7
+ Requires-Dist: pytango>=10
8
+ Dynamic: license-file
@@ -0,0 +1,13 @@
1
+ tango_frame/__init__.py,sha256=Z9z8s_HPREosom2y7IhrqJg8og8ArYKlfgSRgv5aeFA,196
2
+ tango_frame/auto_dispatch.py,sha256=cVex_O05G81wRMrHMzbPPbKNwWQ1j89vi3rzoU1UBcQ,12640
3
+ tango_frame/client.py,sha256=sI4kpaF9npR19iSqGJfAgNnOhbCUZhEvKzrYRnIKsyU,3464
4
+ tango_frame/codec.py,sha256=avyQ8KbCAMcnIAwkpx_wnjPC7SU1JSKBAbW5rzJnfgo,2840
5
+ tango_frame/config.py,sha256=9u6xHmD9er7LfG4FoF__vG2cO81bhGV_8QFkliXhFWY,2359
6
+ tango_frame/introspection.py,sha256=pUodfK5ZYcKBYomgGuO79klNzhjtYIFN17Wf6tG_FKU,2588
7
+ tango_frame/server.py,sha256=Ggw8o89l9ov3q5aneduTjIaQqI1mPWv46fSlIv600us,799
8
+ tango_frame/type_mapping.py,sha256=ILC0PRYlsSX0k9G5twRdZ3WxvlUuor4ASE_BD-YKq2Q,4733
9
+ tango_frame-0.1.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
10
+ tango_frame-0.1.1.dist-info/METADATA,sha256=NlXUXqZoYiUPrIaE9bTJomGEh6MGT74sysAuiH8xjTw,228
11
+ tango_frame-0.1.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
12
+ tango_frame-0.1.1.dist-info/top_level.txt,sha256=yuN0q1K-UfHh1NzOuF0Y89R-tD98GtfVb5swStOlslc,12
13
+ tango_frame-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ tango_frame