##############################################################################
##
# This file is part of Sardana
##
# http://www.sardana-controls.org/
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Sardana is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
##
# Sardana is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
##
# You should have received a copy of the GNU Lesser General Public License
# along with Sardana. If not, see <http://www.gnu.org/licenses/>.
##
##############################################################################
"""This is the sequence macro module"""
__all__ = ["sequence"]
import xml.dom.minidom
from taurus import Attribute
from sardana.macroserver.macro import Hookable, Macro, Type
from sardana.macroserver.msexception import InterruptException
TAG_MACRO = "macro"
TAG_PARAM = "param"
TAG_PARAMREPEAT = "paramrepeat"
TAG_REPEAT = "repeat"
TAG_PARAMS = "params"
TAG_SEQUENCE = "sequence"
ATTRIBUTE_NAME = "name"
ATTRIBUTE_VALUE = "value"
ATTRIBUTE_INDEX = "nr"
ATTRIBUTE_DESCRIPTION = "description"
ATTRIBUTE_DEFVALUE = "defvalue"
ATTRIBUTE_TYPE = "type"
ATTRIBUTE_ALLOWEDHOOKS = "allowedHooks"
ATTRIBUTE_HASPARAMS = "hasParams"
ATTRIBUTE_MIN = "min"
[docs]
class sequence(Macro):
"""This macro executes a sequence of macros. As a parameter
it receives a string which is a xml structure. These macros which allow
hooks can nest another sequence (xml structure). In such a case,
this macro is executed recursively."""
param_def = [["xml", Type.String, None, "Xml string representing a sequence"]]
[docs]
def run(self, *pars):
self.warning(
"This macro is deprecated and will be removed in a future release."
)
xmlDoc = xml.dom.minidom.parseString(pars[0])
macros = self.parseXml(xmlDoc)
for macro in macros:
self.runMacro(macro)
# self.pausePoint()
def parseXml(self, xmlDoc):
macros = []
sequenceElement = xmlDoc.getElementsByTagName(TAG_SEQUENCE)[0]
childElement = sequenceElement.firstChild
while childElement:
if childElement.localName == TAG_MACRO:
params, hookElement = self.parseMacro(childElement)
macro = self.createMacro(params)
if hookElement is not None:
hook = self.createExecMacroHook(
[self.__class__.__name__, hookElement.toxml()]
)
macro.hooks = [hook]
macros.append(macro)
childElement = childElement.nextSibling
return macros
def parseMacro(self, xmlElement):
name = str(xmlElement.getAttribute(ATTRIBUTE_NAME))
params = (name,)
hookElement = None
childElement = xmlElement.firstChild
while childElement:
if childElement.localName == TAG_PARAM:
params += self.parseParam(childElement)
elif childElement.localName == TAG_PARAMREPEAT:
params += self.parseParamRepeat(childElement)
elif childElement.localName == TAG_SEQUENCE:
hookElement = childElement
childElement = childElement.nextSibling
return (params, hookElement)
def parseParam(self, xmlElement):
return (str(xmlElement.getAttribute(ATTRIBUTE_VALUE)),)
def parseParamRepeat(self, xmlElement):
params = ()
childElement = xmlElement.firstChild
while childElement:
if childElement.localName == TAG_REPEAT:
params += self.parseRepeat(childElement)
childElement = childElement.nextSibling
return params
def parseRepeat(self, xmlElement):
params = ()
childElement = xmlElement.firstChild
while childElement:
if childElement.localName == TAG_PARAM:
params += self.parseParam(childElement)
elif childElement.localName == TAG_PARAMREPEAT:
params += self.parseParamRepeat(childElement)
childElement = childElement.nextSibling
return params
# Note: The following macros are experimental and subject to change.
#
# Some macros for controlling sequence flow. These macros don't
# do anything by themselves, they run other macros in various ways.
class cond(Hookable, Macro):
"""
Conditional execution of macros.
Takes an expression in Taurus eval format as argument. It will be evaluated
at run time, and the result interpreted as a boolean. If True, executes
macros hooked at on-true, otherwise execute on-false macros.
Example:
cond "{sys/tg_test/1/ampli} == 0"
sleep 1 @on-true
sleep 2 @on-false
Sleeps 1 second if ampli is 0, otherwise 2 seconds.
Ideas:
- Could also be based on the value of an env var (cond_env?)
"""
hints = {"allowsHooks": ("on-true", "on-false")}
param_def = [["expression", Type.String, None, "Taurus eval expression"]]
def run(self, expression: str):
if not (self.getHooks("on-true") or self.getHooks("on-false")):
self.warning(
"This macro will do nothing unless it has something hooked to on-true and/or on-false."
)
self.debug("Evaluating expression %r", expression)
evaluator = Attribute(f"eval:{expression}")
try:
result = evaluator.read().rvalue.magnitude
except AttributeError:
result = evaluator.read().rvalue
self.debug("Condition evaluated to %r = %r", result, bool(result))
hook_place = "on-true" if bool(result) else "on-false"
for hook in self.getHooks(hook_place):
hook()
class select(Hookable, Macro):
"""
Execute one out of any number of body macros.
Takes an expression in Taurus eval format as argument. It will be evaluated
at run time, and the result should be an integer 0..i. Only the body macro
at index i will be executed.
If there is no body macro at index i, the macro will fail. Unless there is
one or more macros hooked as 'default', in which case those will be run,
in order.
Example:
select "{sys/tg_test/1/ampli}"
sleep 0
sleep 1
sleep 2
sleep 10 @default
If ampli's value is 2, we'll sleep for 2 seconds.
If it's -7 or 100, we sleep for 10.
Ideas:
- Could also be based on the value of an env var (select_env?)
"""
hints = {"allowsHooks": ("body", "default")}
param_def = [["expression", Type.String, None, "Taurus eval expression"]]
def run(self, expression: str):
self.debug("Evaluating expression %r", expression)
evaluator = Attribute(f"eval:{expression}")
index = int(evaluator.read().rvalue.magnitude)
self.debug("Condition evaluated to %r", index)
hooks = list(self.getHooks("body"))
try:
hook = hooks[index]
hook()
except IndexError:
hooks = list(self.getHooks("default"))
if not hooks:
raise RuntimeError(
f"Index {index} didn't match any hooked macro, and no default hook set!"
)
for hook in hooks:
hook()
class retry(Hookable, Macro):
"""
Macro that runs body-hook macros, and if any of the macros fails,
we retry from the top, up to nr times. By default retries once.
There is an optional sleep time before each retry.
Example:
retry 3 5
timescan 1 0.1 0.1
Also allows some other hooks, not sure they make sense.
"""
hints = {"allowsHooks": ("body", "pre-retry", "on-failure")}
param_def = [
["times", Type.Integer, 1, "Number of times to retry"],
["sleep", Type.Float, 0, "Seconds to wait before retry"],
]
def run(self, times: int, sleep: float):
for i in range(0, times + 1):
self.debug("Trying attempt %i...", i)
if i > 0:
for hook in self.getHooks("pre-retry"):
hook()
self.checkPoint()
try:
for hook in self.getHooks("body"):
hook()
except InterruptException:
raise
except Exception as e:
if i < times:
self.warning(f"Failed attempt {i} ({e}), retrying...")
progress = (i / times) * 100
yield progress
if sleep:
self.info(f"Sleeping {sleep} s before retry...")
self.execMacro(f"sleep {sleep}")
else:
for hook in self.getHooks("on-failure"):
hook()
yield 100
self._fail(e)
else:
yield 100
break
def _fail(self, exc):
raise RuntimeError(f"Failed ({exc}) maximum number of attempts!") from exc
class retry_continue(retry):
"""
Like retry, but doesn't raise an error even if all retries fail.
"""
def _fail(self, exc):
self.warning(f"Failed maximum number of attempts ({exc}), continuing.")
class failure(Macro):
"""This macro does nothing but always fails"""
def run(self):
raise RuntimeError("Failure!")