Commit 293091ef authored by Enrico Faulhaber's avatar Enrico Faulhaber Committed by Georg Brandl
Browse files

switch import from PyTango to tango

Change-Id: I4bb4c85111b28a15f6d8cfa5558bc35ed38afc06
Reviewed-on: https://forge.frm2.tum.de/review/c/frm2/tango/entangle/+/23274

Tested-by: default avatarEnrico Faulhaber <enrico.faulhaber@frm2.tum.de>
Reviewed-by: default avatarEnrico Faulhaber <enrico.faulhaber@frm2.tum.de>
Reviewed-by: default avatarGeorg Brandl <g.brandl@fz-juelich.de>
parent baf9ddf7
......@@ -31,8 +31,7 @@ import argparse
from os import path
import serial
import PyTango
from PyTango import DevFailed
import tango
from serial.serialutil import SerialException
# Add import path for inplace usage
......@@ -251,7 +250,7 @@ class SerialCommunicationDevice(CommunicationDevice):
class TangoCommunicationDevice(CommunicationDevice):
def __init__(self, device_path):
CommunicationDevice.__init__(self)
self.dev = PyTango.DeviceProxy(device_path)
self.dev = tango.DeviceProxy(device_path)
self.binary_io = any(cmd.cmd_name == 'BinaryCommunicate'
for cmd in self.dev.command_list_query())
......@@ -288,7 +287,7 @@ def main():
if arguments['tango']:
try:
dev = TangoCommunicationDevice(arguments['dev'])
except DevFailed:
except tango.DevFailed:
print('Could not connect to device: %s' % arguments['dev'])
return 1
else:
......
......@@ -144,7 +144,7 @@ Device state
This is a method that combines the return values from ``State`` and
``Status`` of a Tango device. You should return a tuple with a status code
from the Entangle states given below (*not* PyTango.DevState), and a string.
from the Entangle states given below (*not* tango.DevState), and a string.
The string should not be empty; it can reflect the status constant if there
is no more specific information to add. Example: ``return ON, 'idle'`` or
......
......@@ -26,9 +26,11 @@
Tango client wrappers.
"""
from __future__ import absolute_import
import functools
import PyTango
import tango
from entangle.core.errors import CommunicationFailure, ConfigurationError, \
EntangleError, reason2class
......@@ -45,8 +47,8 @@ def wrap_exceptions(proxy):
def new_method(*args, **kwds):
try:
return method(*args, **kwds)
except PyTango.DevFailed as err:
if err.args and isinstance(err.args[0], PyTango.DevError):
except tango.DevFailed as err:
if err.args and isinstance(err.args[0], tango.DevError):
deverror = err.args[0]
cls = reason2class.get(deverror.reason, EntangleError)
instance = cls(deverror.desc)
......@@ -80,7 +82,7 @@ def check_interface(proxy, interface):
continue
dev_attrs = {}
for att in proxy.attribute_list_query():
dev_attrs[att.name] = att.writable == PyTango.READ_WRITE
dev_attrs[att.name] = att.writable == tango.READ_WRITE
for attname, attdef in sorted(interface.attributes.items()):
if attname not in dev_attrs:
errors.append('missing attribute %r' % attname)
......@@ -92,7 +94,7 @@ def check_interface(proxy, interface):
def tango_client(devuri, interface=None):
proxy = PyTango.DeviceProxy(devuri)
proxy = tango.DeviceProxy(devuri)
# check the version: this really checks for the device working
try:
proxy.version
......
......@@ -33,9 +33,9 @@ from entangle.core.errors import ConfigurationError, InvalidValue
from entangle.lib.pycompat import PY3, number_types, string_types
try:
import PyTango
vector_types = (PyTango.StdStringVector, PyTango.StdDoubleVector,
PyTango.StdLongVector)
import tango
vector_types = (tango.StdStringVector, tango.StdDoubleVector,
tango.StdLongVector)
except ImportError:
vector_types = ()
......
......@@ -41,8 +41,8 @@ except ImportError:
SystemdJournalHandler = object
try:
import PyTango
pytango_exceptions = (PyTango.DevFailed, PyTango.DevError)
import tango
pytango_exceptions = (tango.DevFailed, tango.DevError)
except ImportError:
pytango_exceptions = ()
......
......@@ -22,7 +22,7 @@
#
# *****************************************************************************
from __future__ import print_function
from __future__ import absolute_import, print_function
import argparse
import logging
......@@ -32,7 +32,7 @@ import socket
import sys
from os import path
import PyTango
import tango
import entangle.device
from entangle.core import log
......@@ -182,8 +182,8 @@ class Server(object):
if 'wrapper' in info else '')
for (name, info) in iteritems(all_device_props)
}
pyutil = PyTango.Util(pt_args)
util = PyTango.Util.instance()
pyutil = tango.Util(pt_args)
util = tango.Util.instance()
# sort classes by priority, since devices are created in the order
# of the calls to add_class()
......@@ -231,8 +231,8 @@ class Server(object):
restart = self.restart < self.RESTART
# but not if it's an intentional fatal error
restart = restart and not (
isinstance(err, PyTango.DevFailed) and
isinstance(err.args[0], PyTango.DevError) and
isinstance(err, tango.DevFailed) and
isinstance(err.args[0], tango.DevError) and
err.args[0].reason in (WRONG_CONF, CODE_ERROR)
)
if restart:
......@@ -254,9 +254,9 @@ class Server(object):
os._exit(exitcode)
def check_prereqs(self):
if [int(v) for v in PyTango.__version__.split('.')[:3]] < [8, 1, 0]:
if [int(v) for v in tango.__version__.split('.')[:3]] < [9, 3, 0]:
raise RuntimeError('Entangle needs at least PyTango version '
'8.1.0 to run a server')
'9.3.0 to run a server')
def handle_args(self):
"""Parse command line arguments."""
......@@ -328,7 +328,7 @@ class Server(object):
"""
if self.noconfig:
# read devices and types from DB if -n is given
db = PyTango.Database()
db = tango.Database()
devices = read_devices(db, self.fullname)
log.info('devices read from database: %s', ', '.join(devices))
else:
......@@ -349,7 +349,7 @@ class Server(object):
if not self.nodb_port:
# register ourselves in the server
log.info('server description: %s', srv_desc)
db = PyTango.Database()
db = tango.Database()
register_server(db, self.fullname, devices, self.force)
return devices
......
......@@ -22,7 +22,7 @@
#
# *****************************************************************************
import PyTango
import tango
from entangle.core import log
......@@ -59,7 +59,7 @@ def register_server(db, fullname, devices, unregister=False):
# register server (by registering an admin device)
if fullname not in server_list or unregister:
log.info('registering server %r', fullname)
di = PyTango.DbDevInfo()
di = tango.DbDevInfo()
di.name = 'dserver/' + fullname
di._class = 'DServer'
di.server = fullname
......@@ -82,7 +82,7 @@ def register_server(db, fullname, devices, unregister=False):
exists = False
if not exists:
log.info('registering device %r', dev)
di = PyTango.DbDevInfo()
di = tango.DbDevInfo()
di.name = dev
di._class = devclass
di.server = fullname
......@@ -100,6 +100,6 @@ def register_server(db, fullname, devices, unregister=False):
for dev in devices:
for prop, value in devices[dev].items():
log.debug('registering property %r', (dev + '/' + prop))
datum = PyTango.DbDatum(str(prop))
datum = tango.DbDatum(str(prop))
datum.extend(value)
db.put_device_property(dev, datum)
......@@ -28,7 +28,7 @@ Base device class interface.
import sys
import PyTango
import tango
from entangle.core import ALARM, BUSY, FAULT, INIT, OFF, ON, UNKNOWN, defs, log
from entangle.core.errors import CODE_ERROR, INIT_FAIL, WRONG_CONF, \
......@@ -38,17 +38,17 @@ from entangle.lib.pycompat import integer_types, iteritems, string_types
from entangle.lib.util import simple_exc_desc
STATES = {
INIT: PyTango.DevState.INIT,
OFF: PyTango.DevState.OFF,
ON: PyTango.DevState.ON,
ALARM: PyTango.DevState.ALARM,
BUSY: PyTango.DevState.MOVING,
FAULT: PyTango.DevState.FAULT,
UNKNOWN: PyTango.DevState.UNKNOWN,
INIT: tango.DevState.INIT,
OFF: tango.DevState.OFF,
ON: tango.DevState.ON,
ALARM: tango.DevState.ALARM,
BUSY: tango.DevState.MOVING,
FAULT: tango.DevState.FAULT,
UNKNOWN: tango.DevState.UNKNOWN,
}
class DeviceClass(PyTango.DeviceClass):
class DeviceClass(tango.DeviceClass):
"""
Interface base class for devices.
"""
......@@ -80,10 +80,10 @@ class DeviceClass(PyTango.DeviceClass):
# actually want to create
device_list[:] = [dev for dev in device_list
if dev in self.devices_to_create]
return PyTango.DeviceClass.device_factory(self, device_list)
return tango.DeviceClass.device_factory(self, device_list)
class Device(PyTango.Device_4Impl):
class Device(tango.Device_4Impl):
"""
Implementation base class for devices.
"""
......@@ -107,7 +107,7 @@ class Device(PyTango.Device_4Impl):
# initialize the base device
# PY3: remove str() here
PyTango.Device_4Impl.__init__(self, cls, str(name))
tango.Device_4Impl.__init__(self, cls, str(name))
# set device properties as attributes of the instance
if DeviceClass.nodb_operation:
......@@ -123,8 +123,7 @@ class Device(PyTango.Device_4Impl):
def device_properties_from_resources(self, values):
for prop, info in self.tango_class.device_property_list.items():
if prop in values:
value = PyTango.utils.seqStr_2_obj(values[prop],
info[0])
value = tango.utils.seqStr_2_obj(values[prop], info[0])
else:
if info[2] == []:
self.throw(WRONG_CONF, 'mandatory property %s not in '
......@@ -133,7 +132,7 @@ class Device(PyTango.Device_4Impl):
setattr(self, prop, value)
def device_properties_from_database(self):
db = PyTango.Util.instance().get_database()
db = tango.Util.instance().get_database()
prop_dict = self.tango_class.device_property_list
prop_names = list(prop_dict)
prop_values = db.get_device_property(self.get_name(), prop_names)
......@@ -146,7 +145,7 @@ class Device(PyTango.Device_4Impl):
'database' % prop)
setattr(self, prop, prop_def.default)
continue
if prop_dict[prop][0] in PyTango.utils._array_types:
if prop_dict[prop][0] in tango.utils._array_types:
value = prop_value
else:
value = prop_value[0]
......@@ -177,13 +176,13 @@ class Device(PyTango.Device_4Impl):
self.poll_attribute(attr, period)
self.log.debug('executing init_device')
self._initialized = False
self.set_dev_state(PyTango.DevState.INIT, 'initializing')
self.set_dev_state(tango.DevState.INIT, 'initializing')
try:
self._init_worker()
except Exception as e:
desc = 'could not initialize Tango device: ' + simple_exc_desc(e)
self.log_exception(desc)
self.set_dev_state(PyTango.DevState.FAULT, desc)
self.set_dev_state(tango.DevState.FAULT, desc)
if reraise:
# used in always_executed_hook, so that the actual command is
# not executed if the (re-)init try failed
......@@ -191,7 +190,7 @@ class Device(PyTango.Device_4Impl):
self.handle_exception(e, tb)
else:
self.log.info('Tango device is now initialized')
self.set_dev_state(PyTango.DevState.ON, 'on')
self.set_dev_state(tango.DevState.ON, 'on')
self._initialized = True
def _init_worker(self):
......@@ -216,7 +215,7 @@ class Device(PyTango.Device_4Impl):
self._set_units()
try:
# set memorized attributes on the worker instance
db = PyTango.Util.instance().get_database()
db = tango.Util.instance().get_database()
if db:
for name, attr in iteritems(self._worker.attributes):
if attr.memorized:
......@@ -236,13 +235,13 @@ class Device(PyTango.Device_4Impl):
def _set_units(self):
"""Set the attr units from the worker on the Tango attr objects."""
db = PyTango.Util.instance().get_database()
db = tango.Util.instance().get_database()
for attr in self.tango_class.attr_list:
unit = getattr(self._worker, 'get_%s_unit' % attr)()
if unit and db:
try:
attr = self.get_device_attr().get_attr_by_name(attr)
except PyTango.DevFailed:
except tango.DevFailed:
self.log.warning('device attribute %r not found when '
'setting unit', attr)
continue
......@@ -280,14 +279,14 @@ class Device(PyTango.Device_4Impl):
ns[name] = value
self.device_properties_from_resources(ns)
else:
db = PyTango.Util.instance().get_database()
db = tango.Util.instance().get_database()
for name, value in properties.items():
if name not in self.tango_class.device_property_list:
# validating this is the job of the worker layer
continue
datum = PyTango.DbDatum(name)
datum = tango.DbDatum(name)
if self.tango_class.device_property_list[name][0] in \
PyTango.utils._array_types:
tango.utils._array_types:
datum.extend(map(str, value))
else:
datum.append(str(value))
......@@ -312,7 +311,7 @@ class Device(PyTango.Device_4Impl):
def update_memorized_attribute(self, atname, value):
"""Callback to update the value of a memorized attribute in the DB."""
try:
db = PyTango.Util.instance().get_database()
db = tango.Util.instance().get_database()
self.log.debug('memorizing %s', atname)
props = {atname: {'__value': value}}
db.put_device_attribute_property(self.get_name(), props)
......@@ -323,7 +322,7 @@ class Device(PyTango.Device_4Impl):
"""Callback to clear all dynamic subdevices of this device still
registered in the DB.
"""
util = PyTango.Util.instance()
util = tango.Util.instance()
servername = util.get_ds_name()
db = util.get_database()
for class_ in db.get_server_class_list(servername):
......@@ -335,16 +334,16 @@ class Device(PyTango.Device_4Impl):
def create_dynamic_device(self, devname, cls, props):
"""Callback to create a dynamic device."""
# NOTE: not using PyTango.Util.create_device since it silences any
# NOTE: not using tango.Util.create_device since it silences any
# exceptions raised while creating the device
util = PyTango.Util.instance()
util = tango.Util.instance()
db = util.get_database()
# make sure device does not exist
device_exists = True
try:
db.import_device(devname)
except PyTango.DevFailed as df:
except tango.DevFailed as df:
device_exists = df.args[0].reason != "DB_DeviceNotDefined"
if device_exists:
self.throw(INIT_FAIL, 'dynamic device %r already defined in '
......@@ -356,7 +355,7 @@ class Device(PyTango.Device_4Impl):
return
# register device in DB
di = PyTango.DbDevInfo()
di = tango.DbDevInfo()
di.name = devname
di._class = cls.class_name
di.server = util.get_ds_name()
......@@ -372,7 +371,7 @@ class Device(PyTango.Device_4Impl):
# register properties in DB
for prop, value in props.items():
self.log.debug('registering property %r', (devname + '/' + prop))
datum = PyTango.DbDatum(prop)
datum = tango.DbDatum(prop)
if isinstance(value, list):
datum.extend(map(str, value))
else:
......@@ -383,7 +382,7 @@ class Device(PyTango.Device_4Impl):
def get_additional_version(self):
"""Callback to extract an additional entry for the version attr."""
return 'PyTango %s' % PyTango.__version__
return 'tango %s' % tango.__version__
# PyTango API
......@@ -396,8 +395,8 @@ class Device(PyTango.Device_4Impl):
def dev_state(self):
self.log.debug('executing State')
cur_state = self.get_state()
if cur_state == PyTango.DevState.FAULT and not self._initialized:
new_state = PyTango.DevState.FAULT
if cur_state == tango.DevState.FAULT and not self._initialized:
new_state = tango.DevState.FAULT
else:
try:
new_state = self.map_state(self._worker.do_state())
......@@ -414,7 +413,7 @@ class Device(PyTango.Device_4Impl):
def dev_status(self):
self.log.debug('executing Status')
cur_state = self.get_state()
if cur_state == PyTango.DevState.FAULT and not self._initialized:
if cur_state == tango.DevState.FAULT and not self._initialized:
new_status = self.get_status()
else:
try:
......@@ -434,11 +433,11 @@ class Device(PyTango.Device_4Impl):
self.set_status(status)
def throw(self, reason, message, origin=None):
"""Throw PyTango exception."""
"""Throw a PyTango exception."""
if origin is None:
origin = sys._getframe(1).f_code.co_name
PyTango.Except.throw_exception(reason, message,
self.get_name() + '::' + origin)
tango.Except.throw_exception(reason, message,
self.get_name() + '::' + origin)
def log_exception(self, desc, *args):
"""Log exception, but ignore multiple HardwareUnavailable in a row."""
......@@ -448,18 +447,18 @@ class Device(PyTango.Device_4Impl):
self._hw_unavail = is_hw_unavail
def handle_exception(self, err, _tb):
"""Handle Entangle exception and convert to PyTango."""
"""Handle an Entangle exception and convert to PyTango."""
if isinstance(err, HardwareFailure):
if self.get_state() != PyTango.DevState.FAULT:
if self.get_state() != tango.DevState.FAULT:
self.log.error('device state FAULT: %s', err)
self.set_dev_state(PyTango.DevState.FAULT, str(err))
self.set_dev_state(tango.DevState.FAULT, str(err))
# fall through
if isinstance(err, EntangleError):
PyTango.Except.throw_exception(err.reason, str(err),
self.get_name() + '::' + err.origin)
tango.Except.throw_exception(err.reason, str(err),
self.get_name() + '::' + err.origin)
else:
# XXX extract origin from tb
PyTango.Except.throw_exception(
tango.Except.throw_exception(
CODE_ERROR, '%s: %s' % (err.__class__.__name__, err), '')
def map_state(self, state):
......@@ -468,49 +467,49 @@ class Device(PyTango.Device_4Impl):
def tango_type_for_validator(val): # pylint: disable=too-many-return-statements
if val is None:
return PyTango.DevVoid
return tango.DevVoid
elif val is float:
return PyTango.DevDouble
return tango.DevDouble
elif val in integer_types:
return PyTango.DevLong
return tango.DevLong
elif val in string_types:
return PyTango.DevString
return tango.DevString
elif val is defs.bytes_obj:
return PyTango.DevString
return tango.DevString
elif val in (bool, defs.boolean):
return PyTango.DevBoolean
return tango.DevBoolean
elif isinstance(val, defs.intrange):
if val.fr < 0:
if -(1 << 15) <= val.fr <= val.to < (1 << 15):
return PyTango.DevShort
return tango.DevShort
elif -(1 << 31) <= val.fr <= val.to < (1 << 31):
return PyTango.DevLong
return tango.DevLong
else:
return PyTango.DevLong64
return tango.DevLong64
else:
maxval = max(val.fr, val.to)
# NOTE: not using DevUChar because it does not work for properties.
if maxval < (1 << 16):
return PyTango.DevUShort
return tango.DevUShort
elif maxval < (1 << 32):
return PyTango.DevULong
return tango.DevULong
else:
return PyTango.DevULong64
return tango.DevULong64
elif isinstance(val, defs.floatrange):
return PyTango.DevDouble
return tango.DevDouble
elif isinstance(val, defs.oneof):
return tango_type_for_validator(type(val.vals[0]))
elif isinstance(val, defs.empty_or):
return tango_type_for_validator(val.validator)
elif isinstance(val, defs.regex):
return PyTango.DevString
return tango.DevString
elif isinstance(val, (defs.listof, defs.nonemptylistof, defs.pairsof)):
inner = tango_type_for_validator(val.conv)
try:
# Special case required because DevUChar is not used (see above).
if val.conv is defs.uint8:
return PyTango.DevVarCharArray
return PyTango.utils._scalar_to_array_type[inner]
return tango.DevVarCharArray
return tango.utils._scalar_to_array_type[inner]
except KeyError:
raise RuntimeError('no Tango type for lists of %s' % inner)
elif isinstance(val, defs.pair):
......@@ -521,14 +520,14 @@ def tango_type_for_validator(val): # pylint: disable=too-many-return-statements
raise RuntimeError('no Tango type for %s' % val.__doc__)
left = val.left.conv
if left is float:
return PyTango.DevVarDoubleStringArray
return tango.DevVarDoubleStringArray
if left in integer_types or isinstance(left, defs.intrange):
return PyTango.DevVarLongStringArray
return tango.DevVarLongStringArray
else:
raise RuntimeError('no Tango type for %s' % val.__doc__)
elif val in (defs.nonemptystring, defs.nicosdev, defs.tangodev,
defs.subdev, defs.host):
return PyTango.DevString
return tango.DevString
else:
raise RuntimeError('no Tango type mapping found for validator: %r' %
val)
......@@ -544,13 +543,13 @@ def pytango_command(cdef):
def pytango_attribute(adef):
access = PyTango.READ_WRITE if adef.writable else PyTango.READ
dtypes = {0: PyTango.SCALAR, 1: PyTango.SPECTRUM, 2: PyTango.IMAGE}
access = tango.READ_WRITE if adef.writable else tango.READ
dtypes = {0: tango.SCALAR, 1: tango.SPECTRUM, 2: tango.IMAGE}
dtype = dtypes[adef.dims]
deflist = [tango_type_for_validator(adef.validator), dtype, access]
if dtype in (PyTango.SPECTRUM, PyTango.IMAGE):
if dtype in (tango.SPECTRUM, tango.IMAGE):
deflist.append(adef.max_x)
if dtype == PyTango.IMAGE:
if dtype == tango.IMAGE:
deflist.append(adef.max_y)
atts = {'description': adef.description}
# NOTE: NOT setting 'Memorized' attribute here
......@@ -560,7 +559,7 @@ def pytango_attribute(adef):
if adef.unit:
atts['unit'] = adef.unit
if adef.expert_only:
atts['Display level'] = PyTango.DispLevel.EXPERT
atts['Display level'] = tango.DispLevel.EXPERT
return [deflist, atts]
......@@ -573,7 +572,7 @@ def pytango_property(pdef):
def generate_command_wrapper(cmdname, inargtype):
"""Generate a wrapper method for Tango devices calling into the worker."""
if inargtype == PyTango.DevVoid:
if inargtype == tango.DevVoid:
def cmdmethod(self):
self.log.debug('executing %s', cmdname)
try:
......@@ -684,7 +683,7 @@ def create_tango_device(worker_cls):
access = tg_cls.attr_list[atname][0][2]
if not hasattr(cls, 'read_' + atname):
setattr(cls, 'read_' + atname, generate_att_reader(atname))
if access == PyTango.READ_WRITE:
if access == tango.READ_WRITE:
if not hasattr(cls, 'write_' + atname):
setattr(cls, 'write_' + atname, generate_att_writer(atname))
......
......@@ -35,7 +35,7 @@ import threading
from os import path
from time import sleep