Commit e1ccf4f1 authored by Matias Guijarro's avatar Matias Guijarro

made code PEP8 compliant

parent 40307e9c
This diff is collapsed.
This diff is collapsed.
......@@ -17,6 +17,8 @@ import sys
# the behaviour we want ; it's not because a receiver doesn't handle a
# signal properly that the whole chain should stop
robustapply._robust_apply = robustapply.robust_apply
def __my_robust_apply(*args, **kwargs):
try:
return robustapply._robust_apply(*args, **kwargs)
......@@ -29,9 +31,10 @@ else:
del louie
del __my_robust_apply
def send(sender, signal, *args, **kwargs):
dispatcher.send(signal, sender, *args, **kwargs)
def connect(sender, signal, callback):
dispatcher.connect(callback, signal, sender)
......@@ -2,61 +2,68 @@ import sys
import types
import gevent
class cleanup:
def __init__(self,*args,**keys):
self.cleanup_funcs = args
self.keys = keys
def __enter__(self):
pass
def __exit__(self, exc_type, value, traceback):
if self.cleanup_funcs:
for cleanup_func in self.cleanup_funcs:
if not callable(cleanup_func):
continue
try:
cleanup_func(**self.keys)
except:
sys.excepthook(exc_type, value, traceback)
continue
# the previous try..except is resetting exception,
# so re-raise it from here
if exc_type is not None:
raise exc_type, value, traceback
def __init__(self, *args, **keys):
self.cleanup_funcs = args
self.keys = keys
def __enter__(self):
pass
def __exit__(self, exc_type, value, traceback):
if self.cleanup_funcs:
for cleanup_func in self.cleanup_funcs:
if not callable(cleanup_func):
continue
try:
cleanup_func(**self.keys)
except:
sys.excepthook(exc_type, value, traceback)
continue
# the previous try..except is resetting exception,
# so re-raise it from here
if exc_type is not None:
raise exc_type, value, traceback
class error_cleanup:
def __init__(self,*args,**keys):
self.error_funcs = args
self.keys = keys
def __enter__(self):
pass
def __exit__(self, exc_type, value, traceback):
if exc_type is not None:
if self.error_funcs:
for error_func in self.error_funcs:
if not callable(error_func):
continue
return
try:
error_func(**self.keys)
except:
sys.excepthook(*sys.exc_info())
continue
# the previous try..except is resetting exception,
# so re-raise it from here
raise exc_type, value, traceback
def __init__(self, *args, **keys):
self.error_funcs = args
self.keys = keys
def __enter__(self):
pass
def __exit__(self, exc_type, value, traceback):
if exc_type is not None:
if self.error_funcs:
for error_func in self.error_funcs:
if not callable(error_func):
continue
return
try:
error_func(**self.keys)
except:
sys.excepthook(*sys.exc_info())
continue
# the previous try..except is resetting exception,
# so re-raise it from here
raise exc_type, value, traceback
class TaskException:
def __init__(self, exception, error_string, tb):
self.exception = exception
self.error_string = error_string
self.tb = tb
class wrap_errors(object):
def __init__(self, func):
"""Make a new function from `func', such that it catches all exceptions
and return it as a TaskException object
......@@ -79,49 +86,51 @@ class wrap_errors(object):
def __getattr__(self, item):
return getattr(self.func, item)
#def task_done(task):
# def task_done(task):
# ret = task._get()
# if isinstance(ret, TaskException):
# sys.excepthook(ret.exception, ret.error_string, ret.tb)
def task(func):
def start_task(*args, **kwargs):
try:
wait = kwargs["wait"]
wait = kwargs["wait"]
except KeyError:
wait = True
wait = True
else:
del kwargs["wait"]
del kwargs["wait"]
try:
timeout = kwargs["timeout"]
timeout = kwargs["timeout"]
except KeyError:
timeout = None
timeout = None
else:
del kwargs["timeout"]
del kwargs["timeout"]
try:
t = gevent.spawn(wrap_errors(func), *args, **kwargs)
#t.link(task_done)
# t.link(task_done)
t._get = t.get
def special_get(self, *args, **kwargs):
#self.unlink(task_done)
# self.unlink(task_done)
try:
ret = self._get(*args, **kwargs)
if isinstance(ret, TaskException):
raise ret.exception, ret.error_string, ret.tb
raise ret.exception, ret.error_string, ret.tb
else:
return ret
return ret
except KeyboardInterrupt:
t.kill(KeyboardInterrupt)
setattr(t, "get", types.MethodType(special_get, t))
setattr(t, "get", types.MethodType(special_get, t))
if wait:
return t.get(timeout=timeout)
return t.get(timeout=timeout)
else:
return t
return t
except:
t.kill()
raise
return start_task
......@@ -4,102 +4,125 @@ from bliss.common.axis import Axis, AxisRef, Group
BACKEND = 'xml'
CONTROLLER_MODULES_PATH = [os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "controllers"))]
CONTROLLER_MODULES_PATH = [
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"..",
"..","controllers","motors"))]
AXIS_MODULES_PATH = []
CONTROLLERS = {}
CONTROLLER_BY_AXIS = {}
CONTROLLER_BY_AXIS = {}
GROUPS = {}
def _get_module(module_name, path_list):
try:
module = sys.modules[module_name]
except KeyError:
old_syspath = sys.path[:]
for path in path_list:
sys.path.insert(0, path)
try:
return __import__(module_name, globals(), locals(), [""])
finally:
sys.path = old_syspath
else:
return module
module = sys.modules[module_name]
except KeyError:
old_syspath = sys.path[:]
for path in path_list:
sys.path.insert(0, path)
try:
return __import__(module_name, globals(), locals(), [""])
finally:
sys.path = old_syspath
else:
return module
def get_controller_class(controller_class_name, controller_modules_path=CONTROLLER_MODULES_PATH):
controller_module = _get_module(controller_class_name, controller_modules_path)
def get_controller_class(
controller_class_name,
controller_modules_path=CONTROLLER_MODULES_PATH):
controller_module = _get_module(
controller_class_name,
controller_modules_path)
try:
controller_class = getattr(controller_module, controller_class_name)
except:
try:
controller_class = getattr(controller_module, controller_class_name.title())
controller_class = getattr(controller_module, controller_class_name)
except:
raise RuntimeError("could not find class '%s` in module '%s`" % (controller_class_name, controller_module))
try:
controller_class = getattr(
controller_module,
controller_class_name.title())
except:
raise RuntimeError(
"could not find class '%s` in module '%s`" %
(controller_class_name, controller_module))
return controller_class
return controller_class
def get_axis_class(axis_class_name, axis_modules_path=AXIS_MODULES_PATH):
axis_module = _get_module(axis_class_name, axis_modules_path)
try:
axis_class = getattr(axis_module, axis_class_name)
except:
raise RuntimeError("could not find class '%s` in module '%s`" % (axis_class_name, axis_module))
else:
return axis_class
def add_controller(controller_name, controller_config, controller_class, controller_axes):
axes = []
for axis_name, axis_class_name, axis_config in controller_axes:
if not CONTROLLER_BY_AXIS.get(axis_name):
# new axis
CONTROLLER_BY_AXIS[axis_name]=controller_name
if axis_class_name is None:
axis_class = Axis
else:
axis_class = get_axis_class(axis_class_name)
axes.append((axis_name, axis_class, axis_config))
axis_module = _get_module(axis_class_name, axis_modules_path)
try:
axis_class = getattr(axis_module, axis_class_name)
except:
raise RuntimeError(
"could not find class '%s` in module '%s`" %
(axis_class_name, axis_module))
else:
# existing axis
axes.append((axis_name, AxisRef, axis_config))
controller = controller_class(controller_name, controller_config, axes)
CONTROLLERS[controller_name] = { "object": controller,
"initialized": False }
return axis_class
def add_controller(
controller_name,
controller_config,
controller_class,
controller_axes):
axes = []
for axis_name, axis_class_name, axis_config in controller_axes:
if not CONTROLLER_BY_AXIS.get(axis_name):
# new axis
CONTROLLER_BY_AXIS[axis_name] = controller_name
if axis_class_name is None:
axis_class = Axis
else:
axis_class = get_axis_class(axis_class_name)
axes.append((axis_name, axis_class, axis_config))
else:
# existing axis
axes.append((axis_name, AxisRef, axis_config))
controller = controller_class(controller_name, controller_config, axes)
CONTROLLERS[controller_name] = {"object": controller,
"initialized": False}
def add_group(group_name, group_config, group_class=Group):
global GROUPS
GROUPS[group_name] = { "object": group_class(group_name, group_config) }
global GROUPS
GROUPS[group_name] = {"object": group_class(group_name, group_config)}
def get_axis(axis_name):
try:
controller_name = CONTROLLER_BY_AXIS[axis_name]
controller_name = CONTROLLER_BY_AXIS[axis_name]
except KeyError:
raise RuntimeError("no axis '%s` in config" % axis_name)
raise RuntimeError("no axis '%s` in config" % axis_name)
else:
try:
controller = CONTROLLERS[controller_name]
except KeyError:
raise RuntimeError("no controller can be found for axis '%s`" % axis_name)
try:
controller = CONTROLLERS[controller_name]
except KeyError:
raise RuntimeError(
"no controller can be found for axis '%s`" %
axis_name)
try:
controller_instance = controller["object"]
controller_instance = controller["object"]
except KeyError:
raise RuntimeError("could not get controller instance for axis '%s`" % axis_name)
raise RuntimeError(
"could not get controller instance for axis '%s`" %
axis_name)
if not controller["initialized"]:
controller_instance._update_refs()
controller_instance.initialize()
controller["initialized"] = True
controller_instance._update_refs()
controller_instance.initialize()
controller["initialized"] = True
axis = controller_instance.get_axis(axis_name)
......@@ -107,41 +130,41 @@ def get_axis(axis_name):
def axis_names_list():
return CONTROLLER_BY_AXIS.keys()
return CONTROLLER_BY_AXIS.keys()
def group_names_list():
return GROUPS.keys()
return GROUPS.keys()
def get_group(group_name):
try:
group = GROUPS[group_name]
except KeyError:
raise RuntimeError("no group '%s` in config" % group_name)
try:
group = GROUPS[group_name]
except KeyError:
raise RuntimeError("no group '%s` in config" % group_name)
return group["object"]
return group["object"]
def clear_cfg():
global CONTROLLERS
global CONTROLLER_BY_AXIS
for controller_name, controller in CONTROLLERS.iteritems():
controller["object"].finalize()
CONTROLLERS = {}
CONTROLLER_BY_AXIS = {}
global CONTROLLERS
global CONTROLLER_BY_AXIS
for controller_name, controller in CONTROLLERS.iteritems():
controller["object"].finalize()
CONTROLLERS = {}
CONTROLLER_BY_AXIS = {}
def load_cfg(filename):
clear_cfg()
if BACKEND == 'xml':
from bliss.config.motors.xml_backend import load_cfg
return load_cfg(filename)
clear_cfg()
if BACKEND == 'xml':
from bliss.config.motors.xml_backend import load_cfg
return load_cfg(filename)
def load_cfg_fromstring(config_str):
clear_cfg()
if BACKEND == 'xml':
from bliss.config.motors.xml_backend import load_cfg_fromstring
return load_cfg_fromstring(config_str)
clear_cfg()
if BACKEND == 'xml':
from bliss.config.motors.xml_backend import load_cfg_fromstring
return load_cfg_fromstring(config_str)
class StaticConfig(object):
def __init__(self, config_dict):
self.config_dict = config_dict
def get(self, property_name, converter=str, default=None):
property_attrs = self.config_dict.get(property_name)
if property_attrs is not None:
return converter(property_attrs.get("value"))
else:
if default is not None:
return default
def __init__(self, config_dict):
self.config_dict = config_dict
raise KeyError("no property '%s` in config" % property_name)
def get(self, property_name, converter=str, default=None):
property_attrs = self.config_dict.get(property_name)
if property_attrs is not None:
return converter(property_attrs.get("value"))
else:
if default is not None:
return default
raise KeyError("no property '%s` in config" % property_name)
import xml.etree.cElementTree as ElementTree
from . import get_controller_class, get_axis_class, add_controller, add_group
class XmlListConfig(list):
def __init__(self, aList):
for element in aList:
if element:
......@@ -18,6 +20,7 @@ class XmlListConfig(list):
class XmlDictConfig(dict):
def __init__(self, parent_element):
if parent_element.items():
self.update(dict(parent_element.items()))
......@@ -32,7 +35,7 @@ class XmlDictConfig(dict):
else:
# here, we put the list in dictionary; the key is the
# tag name the list elements all share in common, and
# the value is the list itself
# the value is the list itself
aDict = {element[0].tag: XmlListConfig(element)}
# if the tag has attributes, add those to the dict
if element.items():
......@@ -40,45 +43,54 @@ class XmlDictConfig(dict):
self.update({element.tag: aDict})
# this assumes that if you've got an attribute in a tag,
# you won't be having any text.
elif element.items():
elif element.items():
self.update({element.tag: dict(element.items())})
# finally, if there are no child tags and no attributes, extract
# the text
else:
self.update({element.tag: element.text})
def load_cfg_fromstring(config_xml):
return _load_config(ElementTree.fromstring(config_xml))
return _load_config(ElementTree.fromstring(config_xml))
def load_cfg(config_file):
return _load_config(ElementTree.parse(config_file))
return _load_config(ElementTree.parse(config_file))
def _load_config(config_tree):
for controller_config in config_tree.findall("controller"):
controller_name = controller_config.get("name")
controller_class_name = controller_config.get("class")
if controller_name is None:
controller_name = "%s_%d" % (controller_class_name, id(controller_config))
for controller_config in config_tree.findall("controller"):
controller_name = controller_config.get("name")
controller_class_name = controller_config.get("class")
if controller_name is None:
controller_name = "%s_%d" % (
controller_class_name, id(controller_config))
controller_class = get_controller_class(controller_class_name)
controller_class = get_controller_class(controller_class_name)
add_controller(
controller_name,
XmlDictConfig(controller_config),
controller_class,
load_axes(controller_config))
add_controller(controller_name, XmlDictConfig(controller_config), controller_class, load_axes(controller_config))
for group_node in config_tree.findall("group"):
group_name = group_node.get('name')
if group_name is None:
raise RuntimeError("%s: group with no name" % group_node)
add_group(group_name, XmlDictConfig(group_node))
for group_node in config_tree.findall("group"):
group_name = group_node.get('name')
if group_name is None:
raise RuntimeError("%s: group with no name" % group_node)
add_group(group_name, XmlDictConfig(group_node))
def load_axes(config_node):
"""Return list of (axis name, axis_class_name, axis_config_node)"""
axes = []
for axis_config in config_node.findall('axis'):
axis_name = axis_config.get("name")
if axis_name is None:
raise RuntimeError("%s: configuration for axis does not have a name" % config_node)
axis_class_name = axis_config.get("class")
axes.append((axis_name, axis_class_name, XmlDictConfig(axis_config)))
axis_name = axis_config.get("name")
if axis_name is None:
raise RuntimeError(
"%s: configuration for axis does not have a name" %
config_node)
axis_class_name = axis_config.get("class")
axes.append((axis_name, axis_class_name, XmlDictConfig(axis_config)))
return axes
This diff is collapsed.
from bliss.common import event
class AxisSettings:
def __init__(self):
self.setting_names = ["velocity", "position", "state"]
self.convert_funcs = { "velocity": float, "position": float, "state":str }
self.axis_settings_dict = dict()
self.axis_settings_class = None
#self.state_updated_callback = None
def add(self, setting_name, convert_func):
self.setting_names.append(setting_name)
self.convert_funcs[setting_name]=convert_func
def __init__(self):
self.setting_names = ["velocity", "position", "state"]
self.convert_funcs = {
"velocity": float,
"position": float,
"state": str}
self.axis_settings_dict = dict()
self.axis_settings_class = None
#self.state_updated_callback = None
def set(self, axis, setting_name, value):
settings = self.axis_settings_dict.setdefault(axis, dict(zip(self.setting_names, (None,)*len(self.setting_names))))
convert_func = self.convert_funcs.get(setting_name, str)
settings[setting_name]=convert_func(value)
event.send(axis, setting_name, settings[setting_name])
def add(self, setting_name, convert_func):
self.setting_names.append(setting_name)
self.convert_funcs[setting_name] = convert_func
def get(self, axis, setting_name):
return self.axis_settings_dict[axis][setting_name]
def set(self, axis, setting_name, value):
settings = self.axis_settings_dict.setdefault(
axis,
dict(zip(self.setting_names, (None,) * len(self.setting_names))))
convert_func = self.convert_funcs.get(setting_name, str)
settings[setting_name] = convert_func(value)
event.send(axis, setting_name, settings[setting_name])