diff --git a/app/scan/client/src/main/java/org/csstudio/scan/client/ScanClient.java b/app/scan/client/src/main/java/org/csstudio/scan/client/ScanClient.java index 4ca5e086c7..285bf33380 100644 --- a/app/scan/client/src/main/java/org/csstudio/scan/client/ScanClient.java +++ b/app/scan/client/src/main/java/org/csstudio/scan/client/ScanClient.java @@ -407,7 +407,8 @@ public Collection getScanDevices(final long id) throws Exception */ public long submitScan(final String name, final String xml_commands, final boolean queue) throws Exception { - final HttpURLConnection connection = connect("/scan/" + name, queue ? "" : "queue=false", long_timeout); + final String params = (queue ? "" : "queue=false") + "&pre_post=false"; + final HttpURLConnection connection = connect("/scan/" + name, params, long_timeout); connection.setReadTimeout(0); try { diff --git a/app/scan/client/src/main/java/org/csstudio/scan/client/ScanInfoModel.java b/app/scan/client/src/main/java/org/csstudio/scan/client/ScanInfoModel.java index 55f1ff4cdd..495a0f3701 100644 --- a/app/scan/client/src/main/java/org/csstudio/scan/client/ScanInfoModel.java +++ b/app/scan/client/src/main/java/org/csstudio/scan/client/ScanInfoModel.java @@ -56,7 +56,7 @@ public class ScanInfoModel private volatile List infos = Collections.emptyList(); /** Listeners */ - private List listeners = new CopyOnWriteArrayList<>(); + private List listeners = new CopyOnWriteArrayList(); /** Obtain reference to the singleton instance. diff --git a/app/scan/client/src/main/resources/scan_client_preferences.properties b/app/scan/client/src/main/resources/scan_client_preferences.properties index d1010f891d..ab20517447 100644 --- a/app/scan/client/src/main/resources/scan_client_preferences.properties +++ b/app/scan/client/src/main/resources/scan_client_preferences.properties @@ -8,5 +8,5 @@ host=localhost # TCP port of scan server REST interface port=4810 -# Poll period in milliseconds of the scan client (scan monitor, plot, ...) -poll_period=1000 +# Poll period [millisecs] of the scan client (scan monitor, plot, ...) +poll_period=1000 \ No newline at end of file diff --git a/app/scan/model/src/main/java/org/csstudio/ndarray/NDArray.java b/app/scan/model/src/main/java/org/csstudio/ndarray/NDArray.java index 09c49ef1b1..de1da21b92 100644 --- a/app/scan/model/src/main/java/org/csstudio/ndarray/NDArray.java +++ b/app/scan/model/src/main/java/org/csstudio/ndarray/NDArray.java @@ -305,7 +305,8 @@ private static int fillFlatArray(final ListNumber flat, int index, final Object if (data instanceof List) { final List list = (List)data; - for (Object o : list) index = fillFlatArray(flat, index, o); + for (int i=0; i getImages() entry("include", ScanSystem.class.getResource("/icons/includecommand.gif")), entry("log", ScanSystem.class.getResource("/icons/logcommand.gif")), entry("loop", ScanSystem.class.getResource("/icons/loopcommand.gif")), + entry("while", ScanSystem.class.getResource("/icons/loopcommand.gif")), entry("parallel", ScanSystem.class.getResource("/icons/parallelcommand.gif")), entry("script", ScanSystem.class.getResource("/icons/scriptcommand.gif")), entry("sequence", ScanSystem.class.getResource("/icons/sequencecommand.gif")), @@ -52,19 +54,20 @@ public Map getImages() @Override public Map> getCommands() { - return Map.ofEntries( - entry("comment", CommentCommand::new), - entry("config_log", ConfigLogCommand::new), - entry("delay", DelayCommand::new), - entry("if", IfCommand::new), - entry("include", IncludeCommand::new), - entry("log", LogCommand::new), - entry("loop", LoopCommand::new), - entry("parallel", ParallelCommand::new), - entry("script", ScriptCommand::new), - entry("sequence", SequenceCommand::new), - entry("set", SetCommand::new), - entry("wait", WaitCommand::new) - ); + final Map> commands = new LinkedHashMap<>(); + commands.put("comment", CommentCommand::new); + commands.put("config_log", ConfigLogCommand::new); + commands.put("log", LogCommand::new); + commands.put("delay", DelayCommand::new); + commands.put("if", IfCommand::new); + commands.put("wait", WaitCommand::new); + commands.put("set", SetCommand::new); + commands.put("loop", LoopCommand::new); + commands.put("while", WhileCommand::new); + commands.put("parallel", ParallelCommand::new); + commands.put("sequence", SequenceCommand::new); + commands.put("script", ScriptCommand::new); + commands.put("include", IncludeCommand::new); + return commands; } } diff --git a/app/scan/model/src/main/java/org/csstudio/scan/command/CommandSequence.java b/app/scan/model/src/main/java/org/csstudio/scan/command/CommandSequence.java index 4844569d60..b90e37da98 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/command/CommandSequence.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/command/CommandSequence.java @@ -66,7 +66,7 @@ public CommandSequence(final ScanCommand... commands) */ public CommandSequence(final Collection commands) { - this.commands = new ArrayList<>(); + this.commands = new ArrayList(); this.commands.addAll(commands); } diff --git a/app/scan/model/src/main/java/org/csstudio/scan/command/IfCommand.java b/app/scan/model/src/main/java/org/csstudio/scan/command/IfCommand.java index bbce324874..71697a7cd0 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/command/IfCommand.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/command/IfCommand.java @@ -127,10 +127,8 @@ public void addXMLElements(final Document dom, final Element command_element) command_element.appendChild(element); element = dom.createElement("value"); - if (desired_value instanceof String) - element.appendChild(dom.createTextNode('"' + (String)desired_value + '"')); - else - element.appendChild(dom.createTextNode(desired_value.toString())); + // Quoted: literal String; unquoted: Double or PVReference (PV name) + element.appendChild(dom.createTextNode(StringOrDouble.quote(desired_value))); command_element.appendChild(element); element = dom.createElement("comparison"); @@ -174,7 +172,7 @@ public String toString() buf.append("If '").append(device_name).append("' ") .append(comparison).append(" "); buf.append(StringOrDouble.quote(desired_value)); - if (comparison == Comparison.EQUALS) + if (comparison != Comparison.IN && comparison != Comparison.NOT_IN && tolerance > 0.0) buf.append(" (+-").append(tolerance).append(")"); return buf.toString(); } diff --git a/app/scan/model/src/main/java/org/csstudio/scan/command/LogCommand.java b/app/scan/model/src/main/java/org/csstudio/scan/command/LogCommand.java index 54e5fdcf08..59893592e6 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/command/LogCommand.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/command/LogCommand.java @@ -95,7 +95,7 @@ public void addXMLElements(final Document dom, final Element command_element) @Override public void readXML(final Element element) throws Exception { - final List devices = new ArrayList<>(); + final List devices = new ArrayList(); Element node = XMLUtil.getChildElement(element, "devices"); if (node == null) throw new Exception("Missing 'devices'"); diff --git a/app/scan/model/src/main/java/org/csstudio/scan/command/LoopCommand.java b/app/scan/model/src/main/java/org/csstudio/scan/command/LoopCommand.java index 22f046589a..99ded74d65 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/command/LoopCommand.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/command/LoopCommand.java @@ -18,6 +18,8 @@ import java.util.List; import java.util.Objects; +import org.csstudio.scan.util.PVReference; +import org.csstudio.scan.util.StringOrDouble; import org.phoebus.framework.persistence.XMLUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -49,10 +51,15 @@ @SuppressWarnings("nls") public class LoopCommand extends ScanCommandWithBody { + private static final String START_TAG = "start"; + private volatile String device_name; - private volatile double start; - private volatile double end; - private volatile double stepsize; + /** Start value: {@link Double} literal or {@link PVReference} (PV name read at runtime) */ + private volatile Object start; + /** End value: {@link Double} literal or {@link PVReference} (PV name read at runtime) */ + private volatile Object end; + /** Step size: {@link Double} literal or {@link PVReference} (PV name read at runtime) */ + private volatile Object stepsize; private volatile String readback = ""; private volatile boolean completion = false; private volatile boolean wait = true; @@ -114,9 +121,9 @@ public LoopCommand(final String device_name, final double start, { super(body); this.device_name = Objects.requireNonNull(device_name); - setStepSize(stepsize); - this.start = start; - this.end = end; + setStepSize(Double.valueOf(stepsize)); + this.start = Double.valueOf(start); + this.end = Double.valueOf(end); } /** {@inheritDoc} */ @@ -124,9 +131,9 @@ public LoopCommand(final String device_name, final double start, protected void configureProperties(final List properties) { properties.add(ScanCommandProperty.DEVICE_NAME); - properties.add(new ScanCommandProperty("start", "Initial Value", Double.class)); - properties.add(new ScanCommandProperty("end", "Final Value", Double.class)); - properties.add(new ScanCommandProperty("step_size", "Step Size", Double.class)); + properties.add(new ScanCommandProperty(START_TAG, "Initial Value", Object.class)); + properties.add(new ScanCommandProperty("end", "Final Value", Object.class)); + properties.add(new ScanCommandProperty("step_size", "Step Size", Object.class)); properties.add(ScanCommandProperty.COMPLETION); properties.add(ScanCommandProperty.WAIT); properties.add(ScanCommandProperty.READBACK); @@ -149,45 +156,50 @@ public void setDeviceName(final String device_name) this.device_name = device_name; } - /** @return Loop start value */ - public double getStart() + /** @return Loop start value: {@link Double} or {@link PVReference} */ + public Object getStart() { return start; } - /** @param start Initial loop value */ - public void setStart(final Double start) + /** @param start Initial loop value ({@link Double} or {@link PVReference}) */ + public void setStart(final Object start) { this.start = start; } - /** @return Loop end value */ - public double getEnd() + /** @return Loop end value: {@link Double} or {@link PVReference} */ + public Object getEnd() { return end; } - /** @param end Final loop value */ - public void setEnd(final Double end) + /** @param end Final loop value ({@link Double} or {@link PVReference}) */ + public void setEnd(final Object end) { this.end = end; } - /** @return Loop step size */ - public double getStepSize() + /** @return Loop step size: {@link Double} or {@link PVReference} */ + public Object getStepSize() { return stepsize; } - /** @param stepsize Increment of the loop variable */ - public void setStepSize(final Double stepsize) + /** @param stepsize Increment of the loop variable ({@link Double} or {@link PVReference}) */ + public void setStepSize(final Object stepsize) { - if (stepsize != 0.0) - this.stepsize = stepsize; + if (stepsize instanceof Double step) + { + final double s = step.doubleValue(); + this.stepsize = (s == 0.0) ? 1.0 : s; + // Use fraction of stepsize for tolerance + tolerance = Math.abs((Double) this.stepsize / 10.0); + } else - this.stepsize = 1.0; - // Use fraction of stepsize for tolerance - tolerance = Math.abs(this.stepsize / 10.0); + { // PVReference: defer tolerance calculation to runtime + this.stepsize = stepsize; + } } /** @return Wait for write completion? */ @@ -263,16 +275,16 @@ public void addXMLElements(final Document dom, final Element command_element) element.appendChild(dom.createTextNode(device_name)); command_element.appendChild(element); - element = dom.createElement("start"); - element.appendChild(dom.createTextNode(Double.toString(start))); + element = dom.createElement(START_TAG); + element.appendChild(dom.createTextNode(StringOrDouble.quote(start))); command_element.appendChild(element); element = dom.createElement("end"); - element.appendChild(dom.createTextNode(Double.toString(end))); + element.appendChild(dom.createTextNode(StringOrDouble.quote(end))); command_element.appendChild(element); element = dom.createElement("step"); - element.appendChild(dom.createTextNode(Double.toString(stepsize))); + element.appendChild(dom.createTextNode(StringOrDouble.quote(stepsize))); command_element.appendChild(element); if (completion) @@ -316,9 +328,9 @@ public void readXML(final Element element) throws Exception super.readXML(element); setDeviceName(XMLUtil.getChildString(element, ScanCommandProperty.TAG_DEVICE).orElse("")); - setStart(XMLUtil.getChildDouble(element, "start").orElse(0.0)); - setEnd(XMLUtil.getChildDouble(element, "end").orElse(10.0)); - setStepSize(XMLUtil.getChildDouble(element, "step").orElse(1.0)); + setStart(StringOrDouble.parse(XMLUtil.getChildString(element, START_TAG).orElse("0"))); + setEnd(StringOrDouble.parse(XMLUtil.getChildString(element, "end").orElse("10"))); + setStepSize(StringOrDouble.parse(XMLUtil.getChildString(element, "step").orElse("1"))); setCompletion(XMLUtil.getChildBoolean(element, ScanCommandProperty.TAG_COMPLETION).orElse(false)); setWait(XMLUtil.getChildBoolean(element, ScanCommandProperty.TAG_WAIT).orElse(true)); setReadback(XMLUtil.getChildString(element, ScanCommandProperty.TAG_READBACK).orElse("")); diff --git a/app/scan/model/src/main/java/org/csstudio/scan/command/ScanCommandFactory.java b/app/scan/model/src/main/java/org/csstudio/scan/command/ScanCommandFactory.java index 3a388d92dc..605c9041f3 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/command/ScanCommandFactory.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/command/ScanCommandFactory.java @@ -20,10 +20,10 @@ import java.net.URL; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.ServiceLoader; -import java.util.Set; import java.util.function.Supplier; import java.util.logging.Level; @@ -38,21 +38,24 @@ public class ScanCommandFactory { private static final Map images = new HashMap<>(); - private static final Map> factories = new HashMap<>(); + private static final Map> factories = new LinkedHashMap<>(); static { for (ScanCommandRegistry reg : ServiceLoader.load(ScanCommandRegistry.class)) { + logger.info(() -> "Loaded registry: " + reg.getClass().getName()); + Map> cmds = reg.getCommands(); + logger.info(() -> "Commands from " + reg.getClass().getSimpleName() + ": " + cmds.keySet()); images.putAll(reg.getImages()); factories.putAll(reg.getCommands()); + logger.info(() -> "Factories now: " + factories.keySet()); } } - /** @return All known command IDs */ - public static Set getCommandIDs() + public static List getCommandIDs() { - return factories.keySet(); + return new ArrayList<>(factories.keySet()); } /** @param id Command ID @@ -86,7 +89,7 @@ public static URL getImage(final String id) */ public static List readCommands(Node node) throws Exception { - final List commands = new ArrayList<>(); + final List commands = new ArrayList(); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE) diff --git a/app/scan/model/src/main/java/org/csstudio/scan/command/ScanCommandWithBody.java b/app/scan/model/src/main/java/org/csstudio/scan/command/ScanCommandWithBody.java index 56d6d2b887..2276e9ef9e 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/command/ScanCommandWithBody.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/command/ScanCommandWithBody.java @@ -51,7 +51,7 @@ public ScanCommandWithBody(final List body) */ protected static List toList(final ScanCommand[] commands) { - final List list = new ArrayList<>(commands.length); + final List list = new ArrayList(commands.length); for (ScanCommand command : commands) list.add(command); return list; diff --git a/app/scan/model/src/main/java/org/csstudio/scan/command/ScanScriptContext.java b/app/scan/model/src/main/java/org/csstudio/scan/command/ScanScriptContext.java index 9b21d0aaa6..ab23d8a337 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/command/ScanScriptContext.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/command/ScanScriptContext.java @@ -47,9 +47,9 @@ abstract public class ScanScriptContext public double[][] getData(final String... devices) throws Exception { ScanDataIterator sheet = new ScanDataIterator(getScanData(), devices); - final List> data = new ArrayList<>(devices.length); + final List> data = new ArrayList>(devices.length); for (int i=0; i()); + data.add(new ArrayList()); while (sheet.hasNext()) { final ScanSample[] samples = sheet.getSamples(); diff --git a/app/scan/model/src/main/java/org/csstudio/scan/command/ScriptCommand.java b/app/scan/model/src/main/java/org/csstudio/scan/command/ScriptCommand.java index 11c5beea24..3d152817eb 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/command/ScriptCommand.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/command/ScriptCommand.java @@ -118,7 +118,7 @@ public void readXML(final Element element) throws Exception { setScript(XMLUtil.getChildString(element, "path").orElse("")); - final List arguments = new ArrayList<>(); + final List arguments = new ArrayList(); Element node = XMLUtil.getChildElement(element, "arguments"); if (node != null) { diff --git a/app/scan/model/src/main/java/org/csstudio/scan/command/WaitCommand.java b/app/scan/model/src/main/java/org/csstudio/scan/command/WaitCommand.java index 639a73b00b..21f4cffce8 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/command/WaitCommand.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/command/WaitCommand.java @@ -164,10 +164,8 @@ public void addXMLElements(final Document dom, final Element command_element) command_element.appendChild(element); element = dom.createElement("value"); - if (desired_value instanceof String) - element.appendChild(dom.createTextNode('"' + (String)desired_value + '"')); - else - element.appendChild(dom.createTextNode(desired_value.toString())); + // Quoted: literal String; unquoted: Double or PVReference (PV name) + element.appendChild(dom.createTextNode(StringOrDouble.quote(desired_value))); command_element.appendChild(element); element = dom.createElement("comparison"); @@ -223,7 +221,7 @@ public String toString() final StringBuilder buf = new StringBuilder(); buf.append("Wait for '").append(device_name).append("' ").append(comparison).append(" "); buf.append(StringOrDouble.quote(desired_value)); - if (comparison == Comparison.EQUALS) + if (comparison != Comparison.IN && comparison != Comparison.NOT_IN && tolerance > 0.0) buf.append(" (+-").append(tolerance).append(")"); if (timeout > 0) buf.append(" (").append(timeout).append(" sec timeout)"); diff --git a/app/scan/model/src/main/java/org/csstudio/scan/command/WhileCommand.java b/app/scan/model/src/main/java/org/csstudio/scan/command/WhileCommand.java new file mode 100644 index 0000000000..f3ed62b06f --- /dev/null +++ b/app/scan/model/src/main/java/org/csstudio/scan/command/WhileCommand.java @@ -0,0 +1,355 @@ +/******************************************************************************* + * Copyright (c) 2011 Oak Ridge National Laboratory. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * The scan engine idea is based on the "ScanEngine" developed + * by the Software Services Group (SSG), Advanced Photon Source, + * Argonne National Laboratory, + * Copyright (c) 2011 , UChicago Argonne, LLC. + * + * This implementation, however, contains no SSG "ScanEngine" source code + * and is not endorsed by the SSG authors. + ******************************************************************************/ +package org.csstudio.scan.command; + +import java.util.List; +import java.util.Objects; + +import org.csstudio.scan.util.StringOrDouble; +import org.phoebus.framework.persistence.XMLUtil; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** Command that performs a loop + * + *

The loop steps from a start to an end value + * by some step size, for example 1 to 5 by 1: 1, 2, 3, 4, 5. + * + *

It stops at the end value, for example 1 to 6 by 2: 1, 3, 5 + * + *

When the start is larger than the end and the step size is negative, + * it will ramp down, + * for example from 5 to 1 by -1: 5, 4, 3, 2, 1. + * + *

When the order of start and end does not match the step direction, + * for example the start is smaller than the end, + * but the step is negative, + * this enables a 'reverse' toggle: + * The direction of the loop will change every time it is executed. + * + *

The loop checks if the device actually reaches the desired value + * with a timeout. + * By default, the read-back uses the device that the loop checks, + * but alternate read-back device can be configured. + * + * @author Kay Kasemir + */ +@SuppressWarnings("nls") +public class WhileCommand extends ScanCommandWithBody +{ + private static final String COMPARISON_TAG = "comparison"; + + private volatile String deviceName; + private volatile Comparison comparison; + private volatile Object desiredValue; + private volatile String readback = ""; + private volatile boolean completion = false; + private volatile boolean wait = true; + private volatile double tolerance = 0.1; + private volatile double timeout = 0.0; + + /** Initialize empty loop */ + public WhileCommand() + { + this("device", Comparison.EQUALS, 0.0, new ScanCommand[0]); + } + + /** Initialize with single command + * + *

This constructor simplifies invocation from Matlab. + * In principle, the "ScanCommand... body" constructor + * handles loops with zero, one, many commands, i.e. all cases. + * Matlab, however, turns a single-element array into a scalar + * in a way incompatible with the var-length argument + * constructor. + * + * @param deviceName Name of device to check + * @param comparison Comparison to use + * @param desiredValue Desired value of the device + * @param command Single-command body + */ + public WhileCommand(final String deviceName, + final Comparison comparison, final Object desiredValue, + final ScanCommand command) + { + this(deviceName, comparison, desiredValue, java.util.List.of(command)); + } + + /** Initialize + * @param deviceName Name of device to check + * @param comparison Comparison to use + * @param desiredValue Desired value of the device + * @param body Optional loop body commands + */ + public WhileCommand(final String deviceName, + final Comparison comparison, final Object desiredValue, + final ScanCommand... body) + { + this(deviceName, comparison, desiredValue, toList(body)); + } + + /** Initialize + * @param deviceName Device to update with the loop variable + * @param start Initial loop value + * @param end Final loop value + * @param stepsize Increment of the loop variable + * @param body While body commands + */ + public WhileCommand(final String deviceName, + final Comparison comparison, final Object desiredValue, + final List body) + { + super(body); + this.deviceName = Objects.requireNonNull(deviceName); + this.desiredValue = desiredValue; + this.comparison = comparison; + } + + /** {@inheritDoc} */ + @Override + protected void configureProperties(final List properties) + { + properties.add(ScanCommandProperty.DEVICE_NAME); + properties.add(new ScanCommandProperty(COMPARISON_TAG, "Comparison", Comparison.class)); + properties.add(new ScanCommandProperty("desired_value", "Desired Value", Object.class)); + properties.add(ScanCommandProperty.TOLERANCE); + super.configureProperties(properties); + } + + /** @return Device name (may be "" but not null) */ + public String getDeviceName() + { + return deviceName; + } + + /** @param deviceName Name of device */ + public void setDeviceName(final String deviceName) + { + this.deviceName = Objects.requireNonNull(deviceName); + } + + /** @return Desired value */ + public Object getDesiredValue() + { + return desiredValue; + } + + /** @param desiredValue Desired value */ + public void setDesiredValue(final Object desiredValue) + { + this.desiredValue = desiredValue; + } + + /** @return Desired comparison */ + public Comparison getComparison() + { + return comparison; + } + + /** @param comparison Desired comparison */ + public void setComparison(final Comparison comparison) + { + this.comparison = comparison; + } + + + /** @return Wait for write completion? */ + public boolean getCompletion() + { + return completion; + } + + /** @param completion Wait for write completion ? */ + public void setCompletion(final Boolean completion) + { + this.completion = completion; + } + + /** @return Wait for readback to match? */ + public boolean getWait() + { + return wait; + } + + /** @param wait Wait for readback to match? */ + public void setWait(final Boolean wait) + { + this.wait = wait; + } + + /** @return Name of readback device + * (may be "" to use the primary device of the loop, + * but not null) + */ + public String getReadback() + { + return readback; + } + + /** @param readback Name of readback device */ + public void setReadback(final String readback) + { + this.readback = Objects.requireNonNull(readback); + } + + /** @return Tolerance */ + public double getTolerance() + { + return tolerance; + } + + /** @param tolerance Tolerance */ + public void setTolerance(final Double tolerance) + { + this.tolerance = Math.max(0.0, tolerance); + } + + /** @return Timeout in seconds */ + public double getTimeout() + { + return timeout; + } + + /** @param timeout Time out in seconds */ + public void setTimeout(final Double timeout) + { + this.timeout = Math.max(0.0, timeout); + } + + /** {@inheritDoc} */ + @Override + public void addXMLElements(final Document dom, final Element commandElement) + { + Element element = dom.createElement("device"); + element.appendChild(dom.createTextNode(deviceName)); + commandElement.appendChild(element); + + element = dom.createElement("value"); + // Quoted: literal String; unquoted: Double or PVReference (PV name) + element.appendChild(dom.createTextNode(StringOrDouble.quote(desiredValue))); + commandElement.appendChild(element); + + element = dom.createElement(COMPARISON_TAG); + element.appendChild(dom.createTextNode(comparison.name())); + commandElement.appendChild(element); + + if (tolerance > 0.0) + { + element = dom.createElement("tolerance"); + element.appendChild(dom.createTextNode(Double.toString(tolerance))); + commandElement.appendChild(element); + } + + if (completion) + { + element = dom.createElement("completion"); + element.appendChild(dom.createTextNode(Boolean.toString(completion))); + commandElement.appendChild(element); + } + if (! wait) + { + element = dom.createElement("wait"); + element.appendChild(dom.createTextNode(Boolean.toString(wait))); + commandElement.appendChild(element); + } + if (wait && ! readback.isEmpty()) + { + element = dom.createElement("readback"); + element.appendChild(dom.createTextNode(readback)); + commandElement.appendChild(element); + } + if (tolerance > 0.0) + { + element = dom.createElement("tolerance"); + element.appendChild(dom.createTextNode(Double.toString(tolerance))); + commandElement.appendChild(element); + } + if (timeout > 0.0) + { + element = dom.createElement("timeout"); + element.appendChild(dom.createTextNode(Double.toString(timeout))); + commandElement.appendChild(element); + } + super.addXMLElements(dom, commandElement); + } + + /** {@inheritDoc} */ + @Override + public void readXML(final Element element) throws Exception + { + // Read body first, so we don't update other loop params if this fails + super.readXML(element); + + setDeviceName(XMLUtil.getChildString(element, ScanCommandProperty.TAG_DEVICE).orElse("")); + setDesiredValue(StringOrDouble.parse(XMLUtil.getChildString(element, ScanCommandProperty.TAG_VALUE).orElse("0"))); + try + { + setComparison(Comparison.valueOf(XMLUtil.getChildString(element, COMPARISON_TAG).orElse(Comparison.EQUALS.toString()))); + } + catch (Exception _) + { + setComparison(Comparison.EQUALS); + } + setTolerance(XMLUtil.getChildDouble(element, ScanCommandProperty.TAG_TOLERANCE).orElse(0.1)); + setCompletion(XMLUtil.getChildBoolean(element, ScanCommandProperty.TAG_COMPLETION).orElse(false)); + setWait(XMLUtil.getChildBoolean(element, ScanCommandProperty.TAG_WAIT).orElse(true)); + setReadback(XMLUtil.getChildString(element, ScanCommandProperty.TAG_READBACK).orElse("")); + setTolerance(XMLUtil.getChildDouble(element, ScanCommandProperty.TAG_TOLERANCE).orElse(0.1)); + setTimeout(XMLUtil.getChildDouble(element, ScanCommandProperty.TAG_TIMEOUT).orElse(0.0)); + } + + /** @param buf If the set command uses a condition, + * information about it will be appended to string builder + */ + public void appendConditionDetail(final StringBuilder buf) + { + if (completion) + { + buf.append(" with completion"); + if (timeout > 0) + buf.append(" in ").append(timeout).append(" sec"); + } + if (wait) + { + if (completion) + buf.append(" (check for '"); + else + buf.append(" (wait for '"); + if (readback.isEmpty()) + buf.append(deviceName); + else + buf.append(readback); + if (tolerance > 0) + buf.append("' +-").append(tolerance); + if (timeout > 0 && !completion) + buf.append(", ").append(timeout).append(" sec timeout"); + buf.append(")"); + } + } + + /** {@inheritDoc} */ + @Override + public String toString() + { + final StringBuilder buf = new StringBuilder(); + buf.append("While '").append(deviceName).append("' ") + .append(comparison).append(" "); + buf.append(StringOrDouble.quote(desiredValue)); + if (comparison != Comparison.IN && comparison != Comparison.NOT_IN && tolerance > 0.0) + buf.append(" (+-").append(tolerance).append(")"); + return buf.toString(); + } +} diff --git a/app/scan/model/src/main/java/org/csstudio/scan/util/PVReference.java b/app/scan/model/src/main/java/org/csstudio/scan/util/PVReference.java new file mode 100644 index 0000000000..db6dcbfb62 --- /dev/null +++ b/app/scan/model/src/main/java/org/csstudio/scan/util/PVReference.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2024 Fermi National Accelerator Laboratory. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + ******************************************************************************/ +package org.csstudio.scan.util; + +/** Wrapper that marks a string as a PV name to be read at scan execution time. + * + *

When a scan command's {@code desired_value} is a {@link PVReference}, + * the scan server will read the current value of the named PV at runtime + * and use that value as the comparison target. + * + *

In XML scan files, an unquoted, non-numeric {@code } element + * (e.g. {@code some:pv:name}) is parsed as a {@link PVReference}. + * A quoted string (e.g. {@code "hello"}) remains a literal + * {@link String} used for text comparison. + * + * @author Fermi Controls + */ +public class PVReference +{ + private final String pvName; + + /** @param pvName Name of the PV whose value will be read at runtime */ + public PVReference(final String pvName) + { + this.pvName = pvName; + } + + /** @return PV name */ + public String getPVName() + { + return pvName; + } + + @Override + public String toString() + { + return pvName; + } + + @Override + public boolean equals(final Object other) + { + if (this == other) + return true; + if (!(other instanceof PVReference pvReference)) + return false; + return pvName.equals(pvReference.pvName); + } + + @Override + public int hashCode() + { + return pvName.hashCode(); + } +} diff --git a/app/scan/model/src/main/java/org/csstudio/scan/util/StringOrDouble.java b/app/scan/model/src/main/java/org/csstudio/scan/util/StringOrDouble.java index c48846496b..14ce3d87cf 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/util/StringOrDouble.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/util/StringOrDouble.java @@ -8,36 +8,46 @@ package org.csstudio.scan.util; /** Helper for handling {@link Object}s that are - * either a {@link String} or a {@link Double} + * a {@link String}, a {@link Double}, or a {@link PVReference}. + * + *

Parsing rules: + *

    + *
  • Quoted text (e.g. {@code "hello"}) → {@link String} (literal text comparison)
  • + *
  • A number (e.g. {@code 5.3}) → {@link Double} (numeric comparison)
  • + *
  • Unquoted non-numeric text (e.g. {@code some:pv:name}) → {@link PVReference} + * (read that PV at runtime and use its value for comparison)
  • + *
* * @author Kay Kasemir */ @SuppressWarnings("nls") public class StringOrDouble { - /** @param value Value that's either String or a number - * @return Quoted string, or the text representation of the number + /** @param value Value that's a {@link String}, {@link Double}, or {@link PVReference} + * @return Quoted string for literals, or the text representation for numbers/PV references */ public static String quote(final Object value) { if (value instanceof String) return '"' + (String) value + '"'; + // PVReference and Double both render as plain text (no quotes) return value.toString(); } - /** @param text Text that contains quoted string or a number - * @return {@link String} or {@link Double} + /** @param text Text that contains a quoted string, a number, or a bare PV name + * @return {@link String} for quoted literals, {@link Double} for numbers, + * {@link PVReference} for unquoted non-numeric text */ public static Object parse(String text) { text = text.trim(); if (text.isEmpty()) - return (double) 0; + return Double.valueOf(0); if (text.startsWith("\"")) { if (text.endsWith("\"")) return text.substring(1, text.length()-1); - // Only starting quote: Still assume it's a string + // Only starting quote: Still assume it's a string literal return text.substring(1, text.length()); } try @@ -45,8 +55,8 @@ public static Object parse(String text) return Double.parseDouble(text); } catch (NumberFormatException ex) - { // Use String - return text; + { // Unquoted non-numeric text: treat as a PV name reference + return new PVReference(text); } } } diff --git a/app/scan/model/src/main/java/org/csstudio/scan/util/TextTable.java b/app/scan/model/src/main/java/org/csstudio/scan/util/TextTable.java index 6a55fedc37..6636a71e60 100644 --- a/app/scan/model/src/main/java/org/csstudio/scan/util/TextTable.java +++ b/app/scan/model/src/main/java/org/csstudio/scan/util/TextTable.java @@ -21,16 +21,16 @@ public class TextTable { /** Headers for each column */ - final private List headers = new ArrayList<>(); + final private List headers = new ArrayList(); /** Widths info for each column */ - final private List widths = new ArrayList<>(); + final private List widths = new ArrayList(); /** Rows of the table */ - final private List> rows = new ArrayList<>(); + final private List> rows = new ArrayList>(); /** Headers for each column */ - private List current_row = new ArrayList<>(); + private List current_row = new ArrayList(); /** Where to write */ final private PrintWriter writer; @@ -98,7 +98,7 @@ public void addCell(final String value) if (current_row.size() >= widths.size()) { rows.add(current_row); - current_row = new ArrayList<>(); + current_row = new ArrayList(); } } diff --git a/app/scan/model/src/test/java/org/csstudio/scan/command/PVReferenceTest.java b/app/scan/model/src/test/java/org/csstudio/scan/command/PVReferenceTest.java new file mode 100644 index 0000000000..2316ca5092 --- /dev/null +++ b/app/scan/model/src/test/java/org/csstudio/scan/command/PVReferenceTest.java @@ -0,0 +1,290 @@ +/******************************************************************************* + * Copyright (c) 2024 Fermi National Accelerator Laboratory. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + ******************************************************************************/ +package org.csstudio.scan.command; + +import org.csstudio.scan.util.PVReference; +import org.csstudio.scan.util.StringOrDouble; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Tests for the PVReference feature in scan commands. + * + *

Covers three layers: + *

    + *
  1. {@link StringOrDouble} parse/quote round-trip
  2. + *
  3. {@link IfCommand}, {@link WaitCommand}, {@link WhileCommand}, + * {@link LoopCommand} model XML round-trip
  4. + *
  5. Verification that PVReference is preserved (not silently coerced to String or Double)
  6. + *
+ * + *

To run: mvn test -pl scan-app-fnal/model -Dtest=PVReferenceTest + */ +@SuppressWarnings("nls") +public class PVReferenceTest +{ + // ------------------------------------------------------------------------- + // 1. StringOrDouble parser + // ------------------------------------------------------------------------- + + @Test + void testParseDouble() + { + Object v = StringOrDouble.parse("5.3"); + assertInstanceOf(Double.class, v, "Plain number should parse to Double"); + assertEquals(5.3, (Double) v, 1e-9); + } + + @Test + void testParseNegativeDouble() + { + Object v = StringOrDouble.parse("-12.0"); + assertInstanceOf(Double.class, v); + assertEquals(-12.0, (Double) v, 1e-9); + } + + @Test + void testParseQuotedString() + { + Object v = StringOrDouble.parse("\"hello world\""); + assertInstanceOf(String.class, v, "Quoted text should parse to String literal"); + assertEquals("hello world", (String) v); + } + + @Test + void testParseUnquotedNonNumeric_becomesPVReference() + { + Object v = StringOrDouble.parse("some:ref:pv"); + assertInstanceOf(PVReference.class, v, + "Unquoted non-numeric text should parse as PVReference, not String"); + assertEquals("some:ref:pv", ((PVReference) v).getPVName()); + } + + @Test + void testParseEmpty() + { + Object v = StringOrDouble.parse(""); + assertInstanceOf(Double.class, v); + assertEquals(0.0, (Double) v, 1e-9); + } + + @Test + void testQuoteDouble() + { + assertEquals("5.3", StringOrDouble.quote(5.3)); + } + + @Test + void testQuoteString() + { + assertEquals("\"hello\"", StringOrDouble.quote("hello")); + } + + @Test + void testQuotePVReference() + { + // PVReference must serialise without quotes so it round-trips back as PVReference + assertEquals("some:ref:pv", StringOrDouble.quote(new PVReference("some:ref:pv"))); + } + + @Test + void testRoundTrip_PVReference() + { + final String pv = "my:threshold:pv"; + final String quoted = StringOrDouble.quote(new PVReference(pv)); + final Object parsed = StringOrDouble.parse(quoted); + assertInstanceOf(PVReference.class, parsed); + assertEquals(pv, ((PVReference) parsed).getPVName()); + } + + // ------------------------------------------------------------------------- + // 2. IfCommand XML round-trip + // ------------------------------------------------------------------------- + + @Test + void testIfCommand_numericValue_roundTrip() throws Exception + { + final IfCommand cmd = new IfCommand("my:device", Comparison.ABOVE, 42.0, + Collections.emptyList()); + final String xml = XMLCommandWriter.toXMLString(List.of(cmd)); + System.out.println("IfCommand (numeric) XML:\n" + xml); + + final List readBack = XMLCommandReader.readXMLString(xml); + assertEquals(1, readBack.size()); + final IfCommand result = (IfCommand) readBack.get(0); + assertInstanceOf(Double.class, result.getDesiredValue()); + assertEquals(42.0, (Double) result.getDesiredValue(), 1e-9); + } + + @Test + void testIfCommand_stringLiteral_roundTrip() throws Exception + { + final IfCommand cmd = new IfCommand("my:device", Comparison.EQUALS, "OPEN", + Collections.emptyList()); + final String xml = XMLCommandWriter.toXMLString(List.of(cmd)); + System.out.println("IfCommand (string) XML:\n" + xml); + + final List readBack = XMLCommandReader.readXMLString(xml); + final IfCommand result = (IfCommand) readBack.get(0); + assertInstanceOf(String.class, result.getDesiredValue(), + "Quoted string should stay a String literal"); + assertEquals("OPEN", result.getDesiredValue()); + } + + @Test + void testIfCommand_pvReference_roundTrip() throws Exception + { + // desired_value is a PVReference — compare 'my:device' against live value of 'ref:threshold' + final IfCommand cmd = new IfCommand("my:device", Comparison.ABOVE, + new PVReference("ref:threshold"), + Collections.emptyList()); + final String xml = XMLCommandWriter.toXMLString(List.of(cmd)); + System.out.println("IfCommand (PVRef) XML:\n" + xml); + + // XML must contain the bare PV name WITHOUT quotes + assertTrue(xml.contains("ref:threshold"), + "PVReference should be written as bare PV name, got:\n" + xml); + + final List readBack = XMLCommandReader.readXMLString(xml); + final IfCommand result = (IfCommand) readBack.get(0); + assertInstanceOf(PVReference.class, result.getDesiredValue(), + "Unquoted non-numeric value should round-trip back as PVReference"); + assertEquals("ref:threshold", ((PVReference) result.getDesiredValue()).getPVName()); + } + + // ------------------------------------------------------------------------- + // 3. WaitCommand XML round-trip + // ------------------------------------------------------------------------- + + @Test + void testWaitCommand_pvReference_roundTrip() throws Exception + { + final WaitCommand cmd = new WaitCommand("my:device", Comparison.ABOVE, + new PVReference("ref:threshold"), 0.1, 10.0); + final String xml = XMLCommandWriter.toXMLString(List.of(cmd)); + System.out.println("WaitCommand (PVRef) XML:\n" + xml); + + assertTrue(xml.contains("ref:threshold"), + "PVReference should be written as bare PV name"); + + final List readBack = XMLCommandReader.readXMLString(xml); + final WaitCommand result = (WaitCommand) readBack.get(0); + assertInstanceOf(PVReference.class, result.getDesiredValue()); + assertEquals("ref:threshold", ((PVReference) result.getDesiredValue()).getPVName()); + assertEquals("my:device", result.getDeviceName()); + assertEquals(Comparison.ABOVE, result.getComparison()); + } + + // ------------------------------------------------------------------------- + // 4. WhileCommand XML round-trip + // ------------------------------------------------------------------------- + + @Test + void testWhileCommand_pvReference_roundTrip() throws Exception + { + final WhileCommand cmd = new WhileCommand("loop:device", Comparison.ABOVE, + new PVReference("loop:limit"), + Collections.emptyList()); + final String xml = XMLCommandWriter.toXMLString(List.of(cmd)); + System.out.println("WhileCommand (PVRef) XML:\n" + xml); + + assertTrue(xml.contains("loop:limit"), + "PVReference should be written as bare PV name"); + + final List readBack = XMLCommandReader.readXMLString(xml); + final WhileCommand result = (WhileCommand) readBack.get(0); + assertInstanceOf(PVReference.class, result.getDesiredValue()); + assertEquals("loop:limit", ((PVReference) result.getDesiredValue()).getPVName()); + } + + // ------------------------------------------------------------------------- + // 5. LoopCommand (for) XML round-trip — start / end / step as PVReference + // ------------------------------------------------------------------------- + + @Test + void testLoopCommand_allLiteral_roundTrip() throws Exception + { + final LoopCommand cmd = new LoopCommand("motor:position", 0.0, 10.0, 2.0); + final String xml = XMLCommandWriter.toXMLString(List.of(cmd)); + System.out.println("LoopCommand (literals) XML:\n" + xml); + + final List readBack = XMLCommandReader.readXMLString(xml); + final LoopCommand result = (LoopCommand) readBack.get(0); + assertInstanceOf(Double.class, result.getStart()); + assertInstanceOf(Double.class, result.getEnd()); + assertInstanceOf(Double.class, result.getStepSize()); + assertEquals(0.0, (Double) result.getStart(), 1e-9); + assertEquals(10.0, (Double) result.getEnd(), 1e-9); + assertEquals(2.0, (Double) result.getStepSize(), 1e-9); + } + + @Test + void testLoopCommand_startAsPVReference_roundTrip() throws Exception + { + final LoopCommand cmd = new LoopCommand("motor:position", 0.0, 10.0, 1.0); + cmd.setStart(new PVReference("scan:start:pv")); + final String xml = XMLCommandWriter.toXMLString(List.of(cmd)); + System.out.println("LoopCommand (start=PVRef) XML:\n" + xml); + + assertTrue(xml.contains("scan:start:pv"), + "PVReference start should be written as bare PV name, got:\n" + xml); + + final List readBack = XMLCommandReader.readXMLString(xml); + final LoopCommand result = (LoopCommand) readBack.get(0); + assertInstanceOf(PVReference.class, result.getStart()); + assertEquals("scan:start:pv", ((PVReference) result.getStart()).getPVName()); + // end and step remain literals + assertInstanceOf(Double.class, result.getEnd()); + assertInstanceOf(Double.class, result.getStepSize()); + } + + @Test + void testLoopCommand_allAsPVReference_roundTrip() throws Exception + { + final LoopCommand cmd = new LoopCommand("motor:position", 0.0, 10.0, 1.0); + cmd.setStart(new PVReference("scan:start:pv")); + cmd.setEnd(new PVReference("scan:end:pv")); + cmd.setStepSize(new PVReference("scan:step:pv")); + + final String xml = XMLCommandWriter.toXMLString(List.of(cmd)); + System.out.println("LoopCommand (all PVRef) XML:\n" + xml); + + assertTrue(xml.contains("scan:start:pv")); + assertTrue(xml.contains("scan:end:pv")); + assertTrue(xml.contains("scan:step:pv")); + + final List readBack = XMLCommandReader.readXMLString(xml); + final LoopCommand result = (LoopCommand) readBack.get(0); + assertInstanceOf(PVReference.class, result.getStart()); + assertInstanceOf(PVReference.class, result.getEnd()); + assertInstanceOf(PVReference.class, result.getStepSize()); + assertEquals("scan:start:pv", ((PVReference) result.getStart()).getPVName()); + assertEquals("scan:end:pv", ((PVReference) result.getEnd()).getPVName()); + assertEquals("scan:step:pv", ((PVReference) result.getStepSize()).getPVName()); + } + + // ------------------------------------------------------------------------- + // 6. Regression: old literal-String behaviour is now PVReference + // (previously unquoted non-numeric text was kept as String) + // ------------------------------------------------------------------------- + + @Test + void testLegacyUnquotedTextIsNowPVReference() + { + // Before this change: StringOrDouble.parse("some_text") → String + // After this change: StringOrDouble.parse("some_text") → PVReference + final Object v = StringOrDouble.parse("some_text"); + assertInstanceOf(PVReference.class, v, + "Previously unquoted non-numeric text silently became a String literal. " + + "It should now be treated as a PV reference."); + } +} diff --git a/app/scan/ui/src/main/java/org/csstudio/scan/ui/Messages.java b/app/scan/ui/src/main/java/org/csstudio/scan/ui/Messages.java index 7c65bb008c..c520488ebe 100644 --- a/app/scan/ui/src/main/java/org/csstudio/scan/ui/Messages.java +++ b/app/scan/ui/src/main/java/org/csstudio/scan/ui/Messages.java @@ -14,9 +14,6 @@ */ public class Messages { - public static String MenuPath; - public static String ScanEditor; - public static String ScanMonitor; public static String scan_active_prompt; public static String scan_abort; public static String scan_abort_all; diff --git a/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/Palette.java b/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/Palette.java index 81fac410b4..ae3585f897 100644 --- a/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/Palette.java +++ b/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/Palette.java @@ -44,8 +44,6 @@ public class Palette extends TitledPane { logger.log(Level.WARNING, "Cannot create command", ex); } - // Sort by command name - Collections.sort(commands, (a, b) -> a.getCommandName().compareTo(b.getCommandName())); } private final ListView command_list = new ListView<>(); diff --git a/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/ScanEditorApplication.java b/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/ScanEditorApplication.java index b526509d05..198d5f4c0c 100644 --- a/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/ScanEditorApplication.java +++ b/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/ScanEditorApplication.java @@ -12,7 +12,6 @@ import java.net.URL; import java.util.List; -import org.csstudio.scan.ui.Messages; import org.csstudio.scan.ui.ScanURI; import org.phoebus.framework.spi.AppResourceDescriptor; import org.phoebus.framework.util.ResourceParser; @@ -25,7 +24,7 @@ public class ScanEditorApplication implements AppResourceDescriptor { private static final List FILE_EXTENSIONS = List.of("scn"); public static final String NAME = "scan_editor"; - public static final String DISPLAY_NAME = Messages.ScanEditor; + public static final String DISPLAY_NAME = "Scan Editor"; @Override public String getName() diff --git a/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/ScanEditorMenuEntry.java b/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/ScanEditorMenuEntry.java index 00c5c8838a..00ec43b49f 100644 --- a/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/ScanEditorMenuEntry.java +++ b/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/ScanEditorMenuEntry.java @@ -11,7 +11,6 @@ import org.phoebus.framework.workbench.ApplicationService; import org.phoebus.ui.javafx.ImageCache; import org.phoebus.ui.spi.MenuEntry; -import org.csstudio.scan.ui.Messages; import javafx.scene.image.Image; @@ -36,7 +35,7 @@ public Image getIcon() @Override public String getMenuPath() { - return Messages.MenuPath; + return "Scan"; } @Override diff --git a/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/actions/RemoveCommands.java b/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/actions/RemoveCommands.java index 31b692dbec..3a2237862a 100644 --- a/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/actions/RemoveCommands.java +++ b/app/scan/ui/src/main/java/org/csstudio/scan/ui/editor/actions/RemoveCommands.java @@ -45,7 +45,7 @@ public void run() // // Similarly, removed items are remembered in reverse // so that the undo can simply undo each removed item. - removals = new ArrayList<>(); + removals = new ArrayList(); try { final int N = to_remove.size(); diff --git a/app/scan/ui/src/main/java/org/csstudio/scan/ui/monitor/ScanMonitorApplication.java b/app/scan/ui/src/main/java/org/csstudio/scan/ui/monitor/ScanMonitorApplication.java index 128235d1a3..59885950cf 100644 --- a/app/scan/ui/src/main/java/org/csstudio/scan/ui/monitor/ScanMonitorApplication.java +++ b/app/scan/ui/src/main/java/org/csstudio/scan/ui/monitor/ScanMonitorApplication.java @@ -9,7 +9,6 @@ import java.net.URL; -import org.csstudio.scan.ui.Messages; import org.phoebus.framework.spi.AppDescriptor; /** Application descriptor for "Scan Monitor" @@ -19,7 +18,7 @@ public class ScanMonitorApplication implements AppDescriptor { public static final String NAME = "scan_monitor"; - public static final String DISPLAY_NAME = Messages.ScanMonitor; + public static final String DISPLAY_NAME = "Scan Monitor"; @Override public String getName() diff --git a/app/scan/ui/src/main/java/org/csstudio/scan/ui/monitor/ScanMonitorMenuEntry.java b/app/scan/ui/src/main/java/org/csstudio/scan/ui/monitor/ScanMonitorMenuEntry.java index 2480f3d4bb..d3b424d315 100644 --- a/app/scan/ui/src/main/java/org/csstudio/scan/ui/monitor/ScanMonitorMenuEntry.java +++ b/app/scan/ui/src/main/java/org/csstudio/scan/ui/monitor/ScanMonitorMenuEntry.java @@ -12,7 +12,6 @@ import org.phoebus.ui.javafx.ImageCache; import org.phoebus.ui.spi.MenuEntry; import org.phoebus.ui.spi.ToolbarEntry; -import org.csstudio.scan.ui.Messages; import javafx.scene.image.Image; @@ -37,7 +36,7 @@ public Image getIcon() @Override public String getMenuPath() { - return Messages.MenuPath; + return "Scan"; } @Override diff --git a/app/scan/ui/src/main/resources/org/csstudio/scan/ui/messages.properties b/app/scan/ui/src/main/resources/org/csstudio/scan/ui/messages.properties index 4ea8e9d66b..e2bf775986 100644 --- a/app/scan/ui/src/main/resources/org/csstudio/scan/ui/messages.properties +++ b/app/scan/ui/src/main/resources/org/csstudio/scan/ui/messages.properties @@ -1,6 +1,3 @@ -MenuPath=Scan -ScanEditor=Scan Editor -ScanMonitor=Scan Monitor scan_active_prompt=This scan is being executed on the scan server.\n\nWhile you monitor its progress, modifications to the running scan are limited.\n\nYou can change certain command properties of the running scan, but when you add or remove commands, the ongoing scan on the server will remain unaffected, and this editor will no longer track its progress.\n\nDo you want to edit the scan, or do you want to cancel the change and continue to monitor the ongoing scan? scan_abort=Abort execution scan_abort_all=Abort all scans diff --git a/app/scan/ui/src/main/resources/org/csstudio/scan/ui/messages_fr.properties b/app/scan/ui/src/main/resources/org/csstudio/scan/ui/messages_fr.properties index c558ede669..ba6ecbdf2e 100644 --- a/app/scan/ui/src/main/resources/org/csstudio/scan/ui/messages_fr.properties +++ b/app/scan/ui/src/main/resources/org/csstudio/scan/ui/messages_fr.properties @@ -1,10 +1,7 @@ -MenuPath=Scan -ScanEditor=Scan Editor -ScanMonitor=Scan Monitor -scan_active_prompt=Ce scan est en cours d'ex\u00E9cution sur le serveur de scan.\n\nPendant que vous surveillez sa progression, les modifications du scan en cours sont limit\u00E9es.\n\nVous pouvez modifier certaines propri\u00E9t\u00E9s de commande du scan en cours, mais lorsque vous ajoutez ou supprimez des commandes, le scan en cours sur le serveur ne sera pas affect\u00E9 et cet \u00E9diteur ne suivra plus sa progression.\n\nVoulez-vous modifier le scan ou annuler le changement et continuer \u00E0 surveiller le scan en cours ? -scan_abort=Abandonner l'ex\u00E9cution +scan_active_prompt=Ce scan est en cours d\u0027ex\u00E9cution sur le serveur de scan.\n\nPendant que vous surveillez sa progression, les modifications du scan en cours sont limit\u00E9es.\n\nVous pouvez modifier certaines propri\u00E9t\u00E9s de commande du scan en cours, mais lorsque vous ajoutez ou supprimez des commandes, le scan en cours sur le serveur ne sera pas affect\u00E9 et cet \u00E9diteur ne suivra plus sa progression.\n\nVoulez-vous modifier le scan ou annuler le changement et continuer \u00E0 surveiller le scan en cours ? +scan_abort=Abandonner l\u0027ex\u00E9cution scan_abort_all=Abandonner tous les scans -scan_jump_to_current_command=D\u00E9filer jusqu'\u00E0 la commande actuelle +scan_jump_to_current_command=D\u00E9filer jusqu\u0027\u00E0 la commande actuelle scan_move_down=D\u00E9placer vers le bas scan_move_up=D\u00E9placer vers le haut scan_name_id_fmt={0} #{1} @@ -12,8 +9,8 @@ scan_next=Forcer le passage \u00E0 la commande suivante scan_pause=Pause \u00E0 la prochaine commande scan_pause_all=Mettre en pause tous les scans en cours scan_remove=Supprimer ce scan -scan_resume=Reprendre l'ex\u00E9cution +scan_resume=Reprendre l\u0027ex\u00E9cution scan_resume_all=Reprendre tous les scans en pause scan_simulate=Simuler le scan scan_submit=Soumettre le scan -scan_submit_unqueued=Soumettre le scan (non mis en file d'attente) +scan_submit_unqueued=Soumettre le scan (non mis en file d\u0027attente) diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/ScanServerInstance.java b/services/scan-server/src/main/java/org/csstudio/scan/server/ScanServerInstance.java index 49e1100e45..3757099c27 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/ScanServerInstance.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/ScanServerInstance.java @@ -246,7 +246,7 @@ else if (cmd.equals("-noshell")) help(); System.out.println(); ex.printStackTrace(); - System.exit(-1); + return; } logger.info("Scan Server (PID " + ProcessHandle.current().pid() + ")"); @@ -283,7 +283,6 @@ else if (cmd.equals("-noshell")) catch (Exception ex) { logger.log(Level.SEVERE, "Cannot start", ex); - System.exit(-1); } httpd.shutdown(); diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/command/BaseScanCommandImplFactory.java b/services/scan-server/src/main/java/org/csstudio/scan/server/command/BaseScanCommandImplFactory.java index 70b21aa5a3..0d6f629b18 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/command/BaseScanCommandImplFactory.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/command/BaseScanCommandImplFactory.java @@ -26,6 +26,7 @@ import org.csstudio.scan.command.IncludeCommand; import org.csstudio.scan.command.LogCommand; import org.csstudio.scan.command.LoopCommand; +import org.csstudio.scan.command.WhileCommand; import org.csstudio.scan.command.ParallelCommand; import org.csstudio.scan.command.ScanCommand; import org.csstudio.scan.command.ScriptCommand; @@ -54,6 +55,7 @@ public class BaseScanCommandImplFactory implements ScanCommandImplFactory entry("include", (command, jython) -> new IncludeCommandImpl((IncludeCommand)command, jython)), entry("log", (command, jython) -> new LogCommandImpl((LogCommand)command, jython)), entry("loop", (command, jython) -> new LoopCommandImpl((LoopCommand)command, jython)), + entry("while", (command, jython) -> new WhileCommandImpl((WhileCommand)command, jython)), entry("parallel", (command, jython) -> new ParallelCommandImpl((ParallelCommand)command, jython)), entry("script", (command, jython) -> new ScriptCommandImpl((ScriptCommand)command, jython)), entry("sequence", (command, jython) -> new SequenceCommandImpl((SequenceCommand)command, jython)), diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/command/IfCommandImpl.java b/services/scan-server/src/main/java/org/csstudio/scan/server/command/IfCommandImpl.java index a67d92c5b3..af135a006c 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/command/IfCommandImpl.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/command/IfCommandImpl.java @@ -28,11 +28,14 @@ import org.csstudio.scan.server.ScanCommandImpl; import org.csstudio.scan.server.ScanCommandImplTool; import org.csstudio.scan.server.ScanContext; +import org.csstudio.scan.server.ScanServerInstance; import org.csstudio.scan.server.SimulationContext; import org.csstudio.scan.server.condition.NumericValueCondition; import org.csstudio.scan.server.condition.TextValueCondition; import org.csstudio.scan.server.device.Device; import org.csstudio.scan.server.internal.JythonSupport; +import org.csstudio.scan.util.PVReference; +import org.phoebus.core.vtypes.VTypeHelper; /** Command that performs 'if' * @author Kay Kasemir @@ -77,6 +80,10 @@ public String[] getDeviceNames(final MacroContext macros) throws Exception final String device_name = command.getDeviceName(); final Set device_names = new HashSet<>(); device_names.add(macros.resolveMacros(device_name)); + // If desired_value is a PV reference, that PV also needs to be opened + final Object desired = command.getDesiredValue(); + if (desired instanceof PVReference pvReference) + device_names.add(macros.resolveMacros(pvReference.getPVName())); for (ScanCommandImpl command : implementation) { final String[] names = command.getDeviceNames(macros); @@ -113,6 +120,18 @@ public void execute(final ScanContext context) throws Exception condition.fetchInitialValue(); is_condition_met = condition.isConditionMet(); } + else if (desired instanceof PVReference pvReference) + { + // Read the referenced PV's current value at runtime and compare numerically + final Device refDevice = context.getDevice( + context.getMacros().resolveMacros(pvReference.getPVName())); + final double refValue = VTypeHelper.toDouble( + refDevice.read(ScanServerInstance.getScanConfig().getReadTimeout())); + final NumericValueCondition condition = new NumericValueCondition(device, command.getComparison(), + refValue, command.getTolerance(), Duration.ZERO); + condition.fetchInitialValue(); + is_condition_met = condition.isConditionMet(); + } else { final TextValueCondition condition = new TextValueCondition(device, command.getComparison(), desired.toString(), Duration.ZERO); diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/command/IncludeCommandImpl.java b/services/scan-server/src/main/java/org/csstudio/scan/server/command/IncludeCommandImpl.java index 330c639870..6c3db4bd49 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/command/IncludeCommandImpl.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/command/IncludeCommandImpl.java @@ -72,7 +72,7 @@ public String[] getDeviceNames(final MacroContext macros) throws Exception macros.pushMacros(command.getMacros()); try { - final Set devices = new HashSet<>(); + final Set devices = new HashSet(); for (ScanCommandImpl command : scan_impl) { for (String device_name : command.getDeviceNames(macros)) diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/command/LoopCommandImpl.java b/services/scan-server/src/main/java/org/csstudio/scan/server/command/LoopCommandImpl.java index 37ad7ebb68..f58fe8df9a 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/command/LoopCommandImpl.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/command/LoopCommandImpl.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011-2026 Oak Ridge National Laboratory. + * Copyright (c) 2011-2018 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -35,6 +35,8 @@ import org.csstudio.scan.server.device.SimulatedDevice; import org.csstudio.scan.server.internal.JythonSupport; import org.csstudio.scan.server.log.DataLog; +import org.csstudio.scan.util.PVReference; +import org.epics.vtype.VType; import org.phoebus.core.vtypes.VTypeHelper; import org.phoebus.util.time.TimeDuration; @@ -67,8 +69,13 @@ public class LoopCommandImpl extends ScanCommandImpl public LoopCommandImpl(final LoopCommand command, final JythonSupport jython) throws Exception { super(command, jython); - reverse = (command.getStart() <= command.getEnd() && command.getStepSize() < 0) || - (command.getStart() >= command.getEnd() && command.getStepSize() > 0); + final double s = toDoubleOrNaN(command.getStart()); + final double e = toDoubleOrNaN(command.getEnd()); + final double st = toDoubleOrNaN(command.getStepSize()); + // When start/end/step are PVReferences we can't compute reverse direction + // at construction time; default to non-reversing (resolved at execute time). + reverse = !Double.isNaN(s) && !Double.isNaN(e) && !Double.isNaN(st) && + ((s <= e && st < 0) || (s >= e && st > 0)); implementation = ScanCommandImplTool.implement(command.getBody(), jython); } @@ -98,10 +105,17 @@ public long getWorkUnits() public String[] getDeviceNames(final MacroContext macros) throws Exception { final String device_name = command.getDeviceName(); - final Set device_names = new HashSet<>(); + final Set device_names = new HashSet(); device_names.add(macros.resolveMacros(device_name)); if (command.getWait() && command.getReadback().length() > 0) device_names.add(macros.resolveMacros(command.getReadback())); + // If start/end/step are PV references, those PVs must also be opened + if (command.getStart() instanceof PVReference pvReference) + device_names.add(macros.resolveMacros(pvReference.getPVName())); + if (command.getEnd() instanceof PVReference pvReference) + device_names.add(macros.resolveMacros(pvReference.getPVName())); + if (command.getStepSize() instanceof PVReference pvReference) + device_names.add(macros.resolveMacros(pvReference.getPVName())); for (ScanCommandImpl command : implementation) { final String[] names = command.getDeviceNames(macros); @@ -111,47 +125,58 @@ public String[] getDeviceNames(final MacroContext macros) throws Exception return device_names.toArray(new String[device_names.size()]); } - /** @return Lower loop limit */ - double getLoopStart() + /** Resolve an Object value (Double or PVReference) to a double. + * If the value is a {@link PVReference}, reads the current value of that PV. + * @param value {@link Double} or {@link PVReference} + * @param context Scan context used when reading a PV + * @return numeric value + * @throws Exception on PV read error + */ + private double resolveDouble(final Object value, final ScanContext context) throws Exception { - return Math.min(command.getStart(), command.getEnd()); + if (value instanceof PVReference pvReference) + { + final Device refDevice = context.getDevice( + context.getMacros().resolveMacros(pvReference.getPVName())); + return VTypeHelper.toDouble( + refDevice.read(org.csstudio.scan.server.ScanServerInstance.getScanConfig().getReadTimeout())); + } + return ((Number) value).doubleValue(); } - /** @return Upper loop limit */ - double getLoopEnd() + /** Return numeric value of start/end/step, or NaN if it's a PVReference (unknown until runtime) */ + private static double toDoubleOrNaN(final Object v) { - return Math.max(command.getStart(), command.getEnd()); + if (v instanceof Number number) + return number.doubleValue(); + return Double.NaN; // PVReference — resolved at execute() time } - /** @return Loop step, might toggle direction */ - double getLoopStep() + private double getLoopStart() + { + return Math.min(toDoubleOrNaN(command.getStart()), toDoubleOrNaN(command.getEnd())); + } + private double getLoopEnd() { - final double step = direction * command.getStepSize(); + return Math.max(toDoubleOrNaN(command.getStart()), toDoubleOrNaN(command.getEnd())); + } + private double getLoopStep() + { + final double step = direction * toDoubleOrNaN(command.getStepSize()); // Revert direction for next iteration of the complete loop? if (reverse) direction = -direction; return step; } - /** @return Number of loop steps */ - int getNumSteps() - { - return (int)Math.ceil(Math.abs(((command.getEnd() - command.getStart()) / command.getStepSize()))) + 1; - } - - /** @param start Start value, might be upper or lower limit - * @param step Loop step value, positive or negative - * @param i Loop index - * @return Loop value - */ - double computeStep(double start, double step, int i) + public int getNumSteps() { - // Compute loop value, but limit to upper or lower - // end depending on step direction - if (step >= 0) - return Math.min(start + i * step, getLoopEnd()); - else - return Math.max(start + i * step, getLoopStart()); + final double s = toDoubleOrNaN(command.getStart()); + final double e = toDoubleOrNaN(command.getEnd()); + final double st = toDoubleOrNaN(command.getStepSize()); + if (Double.isNaN(s) || Double.isNaN(e) || Double.isNaN(st)) + return 1; // PV references — unknown until runtime, estimate 1 step + return (int) Math.ceil(Math.abs((e - s) / st)) + 1; } /** {@inheritDoc} */ @@ -165,7 +190,7 @@ public void simulate(final SimulationContext context) throws Exception double start = step < 0 ? getLoopEnd() : getLoopStart(); int num_steps = getNumSteps(); for (int i = 0; i < num_steps; i++) - simulateStep(context, device, computeStep(start, step, i)); + simulateStep(context, device, start + i * step); } /** Simulate one step in the loop iteration @@ -205,35 +230,78 @@ private void simulateStep(final SimulationContext context, public void execute(final ScanContext context) throws Exception { final Device device = context.getDevice(context.getMacros().resolveMacros(command.getDeviceName())); + final Device readback = resolveReadbackDevice(context, device); + final LoopExecutionState loop = resolveLoopExecutionState(context); + final NumericValueCondition condition = createWaitCondition(readback, loop.resolvedStart); - // Separate read-back device, or use 'set' device? - final Device readback; - if (command.getReadback().isEmpty()) - readback = device; - else - readback = context.getDevice(context.getMacros().resolveMacros(command.getReadback())); - - // Wait for the device to reach the value? - final NumericValueCondition condition; - if (command.getWait()) + for (int i = 0; i < loop.numSteps; i++) { - // When using completion, readback needs to match "right away" - final double check_timeout = command.getCompletion() ? 1.0 : command.getTimeout(); - condition = new NumericValueCondition(readback, Comparison.EQUALS, - command.getStart(), - command.getTolerance(), - TimeDuration.ofSeconds(check_timeout)); + final double targetValue = loop.start + i * loop.step; + executeStep(context, device, condition, readback, targetValue); + // check if inside the loop, the device was set to a value that ends the loop + final VType value = device.read(); + if (shouldStopLoop(value, loop.step, loop.loopMin, loop.loopMax)) + break; } - else - condition = null; + } - double step = getLoopStep(); - // step is < 0 means we are stepping down - double start = step < 0 ? getLoopEnd() : getLoopStart(); - int num_steps = getNumSteps(); + private Device resolveReadbackDevice(final ScanContext context, final Device device) throws Exception + { + if (command.getReadback().isEmpty()) + return device; + return context.getDevice(context.getMacros().resolveMacros(command.getReadback())); + } - for (int i = 0; i < num_steps; i++) - executeStep(context, device, condition, readback, computeStep(start, step, i)); + private NumericValueCondition createWaitCondition(final Device readback, final double resolvedStart) + { + if (!command.getWait()) + return null; + final double check_timeout = command.getCompletion() ? 1.0 : command.getTimeout(); + return new NumericValueCondition(readback, Comparison.EQUALS, + resolvedStart, + command.getTolerance(), + TimeDuration.ofSeconds(check_timeout)); + } + + private LoopExecutionState resolveLoopExecutionState(final ScanContext context) throws Exception + { + final double resolvedStart = resolveDouble(command.getStart(), context); + final double resolvedEnd = resolveDouble(command.getEnd(), context); + final double resolvedStep = resolveDouble(command.getStepSize(), context); + + final double loopMin = Math.min(resolvedStart, resolvedEnd); + final double loopMax = Math.max(resolvedStart, resolvedEnd); + final int numSteps = (int) Math.ceil(Math.abs((resolvedEnd - resolvedStart) / resolvedStep)) + 1; + final double step = direction * resolvedStep; + final double start = step < 0 ? loopMax : loopMin; + return new LoopExecutionState(resolvedStart, loopMin, loopMax, numSteps, step, start); + } + + private boolean shouldStopLoop(final VType value, final double step, final double loopMin, final double loopMax) + { + final double currentValue = VTypeHelper.toDouble(value); + return step < 0 ? currentValue < loopMin : currentValue > loopMax; + } + + private static class LoopExecutionState + { + private final double resolvedStart; + private final double loopMin; + private final double loopMax; + private final int numSteps; + private final double step; + private final double start; + + private LoopExecutionState(final double resolvedStart, final double loopMin, final double loopMax, + final int numSteps, final double step, final double start) + { + this.resolvedStart = resolvedStart; + this.loopMin = loopMin; + this.loopMax = loopMax; + this.numSteps = numSteps; + this.step = step; + this.start = start; + } } /** Execute one step of the loop diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/command/SequenceCommandImpl.java b/services/scan-server/src/main/java/org/csstudio/scan/server/command/SequenceCommandImpl.java index 83f81e1a9a..ef0e7b9f04 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/command/SequenceCommandImpl.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/command/SequenceCommandImpl.java @@ -66,7 +66,7 @@ public long getWorkUnits() @Override public String[] getDeviceNames(final MacroContext macros) throws Exception { - final Set device_names = new HashSet<>(); + final Set device_names = new HashSet(); for (ScanCommandImpl command : implementation) { final String[] names = command.getDeviceNames(macros); diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/command/WaitCommandImpl.java b/services/scan-server/src/main/java/org/csstudio/scan/server/command/WaitCommandImpl.java index b9dc4a3c67..b8977c54fb 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/command/WaitCommandImpl.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/command/WaitCommandImpl.java @@ -22,6 +22,7 @@ import org.csstudio.scan.server.MacroContext; import org.csstudio.scan.server.ScanCommandImpl; import org.csstudio.scan.server.ScanContext; +import org.csstudio.scan.server.ScanServerInstance; import org.csstudio.scan.server.SimulationContext; import org.csstudio.scan.server.condition.DeviceCondition; import org.csstudio.scan.server.condition.NumericValueCondition; @@ -29,6 +30,7 @@ import org.csstudio.scan.server.device.Device; import org.csstudio.scan.server.device.SimulatedDevice; import org.csstudio.scan.server.internal.JythonSupport; +import org.csstudio.scan.util.PVReference; import org.phoebus.core.vtypes.VTypeHelper; import org.phoebus.util.time.SecondsParser; import org.phoebus.util.time.TimeDuration; @@ -59,7 +61,13 @@ public WaitCommandImpl(final WaitCommand command) throws Exception @Override public String[] getDeviceNames(final MacroContext macros) throws Exception { - return new String[] { macros.resolveMacros(command.getDeviceName()) }; + final java.util.Set names = new java.util.HashSet<>(); + names.add(macros.resolveMacros(command.getDeviceName())); + // If desired_value is a PV reference, that PV also needs to be opened + final Object desired = command.getDesiredValue(); + if (desired instanceof PVReference pvReference) + names.add(macros.resolveMacros(pvReference.getPVName())); + return names.toArray(new String[names.size()]); } /** {@inheritDoc} */ @@ -125,6 +133,16 @@ public void execute(final ScanContext context) throws Exception condition = new NumericValueCondition(device, command.getComparison(), number, command.getTolerance(), timeout); } + else if (desired instanceof PVReference pvReference) + { + // Read the referenced PV's current value at runtime and compare numerically + final Device refDevice = context.getDevice( + context.getMacros().resolveMacros(pvReference.getPVName())); + final double refValue = VTypeHelper.toDouble( + refDevice.read(ScanServerInstance.getScanConfig().getReadTimeout())); + condition = new NumericValueCondition(device, command.getComparison(), + refValue, command.getTolerance(), timeout); + } else condition = new TextValueCondition(device, command.getComparison(), desired.toString(), timeout); try diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/command/WhileCommandImpl.java b/services/scan-server/src/main/java/org/csstudio/scan/server/command/WhileCommandImpl.java new file mode 100644 index 0000000000..858f6986a9 --- /dev/null +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/command/WhileCommandImpl.java @@ -0,0 +1,291 @@ +/******************************************************************************* + * Copyright (c) 2011-2018 Oak Ridge National Laboratory. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * The scan engine idea is based on the "ScanEngine" developed + * by the Software Services Group (SSG), Advanced Photon Source, + * Argonne National Laboratory, + * Copyright (c) 2011 , UChicago Argonne, LLC. + * + * This implementation, however, contains no SSG "ScanEngine" source code + * and is not endorsed by the SSG authors. + ******************************************************************************/ +package org.csstudio.scan.server.command; + +import static org.csstudio.scan.server.ScanServerInstance.logger; + +import java.time.Duration; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.logging.Level; +import java.util.Arrays; + +import org.csstudio.scan.command.Comparison; +import org.csstudio.scan.command.WhileCommand; +import org.csstudio.scan.server.MacroContext; +import org.csstudio.scan.server.ScanCommandImpl; +import org.csstudio.scan.server.ScanCommandImplTool; +import org.csstudio.scan.server.ScanContext; +import org.csstudio.scan.server.ScanServerInstance; +import org.csstudio.scan.server.SimulationContext; +import org.csstudio.scan.server.condition.NumericValueCondition; +import org.csstudio.scan.server.condition.TextValueCondition; +import org.csstudio.scan.server.device.Device; +import org.csstudio.scan.server.device.SimulatedDevice; +import org.csstudio.scan.server.internal.JythonSupport; +import org.csstudio.scan.util.PVReference; +import org.phoebus.core.vtypes.VTypeHelper; +import org.phoebus.util.time.TimeDuration; + + +/** Command that performs a loop + * @author Kay Kasemir + */ +@SuppressWarnings("nls") +public class WhileCommandImpl extends ScanCommandImpl +{ + private final List> implementation; + + /** Thread that executes the loop variable write + * + * SYNC on `this` to prevent race where + * executing thread tries to set thread back to null, + * while next() tries to interrupt. + */ + private Thread thread = null; + + /** Flag to indicate 'next' was invoked on current loop step */ + private volatile boolean doSkip; + + /** Initialize + * @param command Command description + * @param jython Jython interpreter, may be null + */ + public WhileCommandImpl(final WhileCommand command, final JythonSupport jython) throws Exception + { + super(command, jython); + implementation = ScanCommandImplTool.implement(command.getBody(), jython); + } + + /** Initialize without Jython support + * @param command Command description + */ + public WhileCommandImpl(final WhileCommand command) throws Exception + { + this(command, null); + } + + /** {@inheritDoc} */ + @Override + public long getWorkUnits() + { + long bodyUnits = 0; + for (ScanCommandImpl command : implementation) + bodyUnits += command.getWorkUnits(); + if (bodyUnits == 0) + return 0; + return bodyUnits; + } + + /** {@inheritDoc} */ + @Override + public String[] getDeviceNames(final MacroContext macros) throws Exception + { + final String deviceName = command.getDeviceName(); + final Set deviceNames = new HashSet(); + deviceNames.add(macros.resolveMacros(deviceName)); + if (command.getWait() && !command.getReadback().isEmpty()) + deviceNames.add(macros.resolveMacros(command.getReadback())); + // If desired_value is a PV reference, that PV also needs to be opened + final Object desired = command.getDesiredValue(); + if (desired instanceof PVReference pvReference) + deviceNames.add(macros.resolveMacros(pvReference.getPVName())); + for (ScanCommandImpl command : implementation) + { + final String[] names = command.getDeviceNames(macros); + if (logger.isLoggable(Level.INFO)) + logger.log(Level.INFO, () -> "getDeviceNames: names=" + Arrays.toString(names)); + java.util.Collections.addAll(deviceNames, names); + } + return deviceNames.toArray(new String[deviceNames.size()]); + } + + + /** {@inheritDoc} */ + @Override + public void simulate(final SimulationContext context) throws Exception + { + final SimulatedDevice device = context.getDevice(context.getMacros().resolveMacros(command.getDeviceName())); + + simulateStep(context, device, 0.0); + } + + /** Simulate one step in the loop iteration + * @param context {@link SimulationContext} + * @param device {@link SimulatedDevice} that the loop modifies + * @param value Value of the loop variable for this iteration + * @throws Exception on error + */ + private void simulateStep(final SimulationContext context, + final SimulatedDevice device, final double value) throws Exception + { + // Get previous value + final double original = VTypeHelper.toDouble(device.read()); + + + // Show command + final StringBuilder buf = new StringBuilder(); + final double time_estimate = command.getTimeout(); + buf.append("While '").append(command.getDeviceName()).append("' = ").append(value); + command.appendConditionDetail(buf); + if (! Double.isNaN(original)) + buf.append(" [was ").append(original).append("]"); + context.logExecutionStep(context.getMacros().resolveMacros(buf.toString()), time_estimate); + + + // Simulate loop body + context.simulate(implementation); + } + + /** {@inheritDoc} */ + @Override + public void execute(final ScanContext context) throws Exception + { + logger.info("execute begin"); + final Device device = context.getDevice(context.getMacros().resolveMacros(command.getDeviceName())); + + // Separate read-back device, or use 'set' device? + final Device readback; + if (command.getReadback().isEmpty()) + readback = device; + else + readback = context.getDevice(context.getMacros().resolveMacros(command.getReadback())); + + final NumericValueCondition condition = createWaitCondition(context, readback); + + logger.info("execute before while(true)..."); + while (true) + { + final boolean is_condition_met = isConditionMet(context, device); + if (!is_condition_met) break; + executeStep(context, device, condition, 0.0); + } + } + + private NumericValueCondition createWaitCondition(final ScanContext context, final Device readback) throws Exception + { + if (!command.getWait()) + return null; + + final double check_timeout = command.getCompletion() ? 1.0 : command.getTimeout(); + final double number = resolveDesiredNumericValue(context, command.getDesiredValue()); + return new NumericValueCondition(readback, Comparison.EQUALS, + number, + command.getTolerance(), + TimeDuration.ofSeconds(check_timeout)); + } + + private boolean isConditionMet(final ScanContext context, final Device device) throws Exception + { + final Object desired = command.getDesiredValue(); + if (desired instanceof Number number) + return evaluateNumericCondition(device, number.doubleValue()); + if (desired instanceof PVReference pvReference) + return evaluateNumericCondition(device, resolvePVReferenceValue(context, pvReference)); + return evaluateTextCondition(device, desired.toString()); + } + + private boolean evaluateNumericCondition(final Device device, final double desiredValue) throws Exception + { + final NumericValueCondition condition = new NumericValueCondition(device, command.getComparison(), + desiredValue, command.getTolerance(), Duration.ZERO); + condition.fetchInitialValue(); + return condition.isConditionMet(); + } + + private boolean evaluateTextCondition(final Device device, final String desiredValue) throws Exception + { + final TextValueCondition condition = new TextValueCondition(device, command.getComparison(), desiredValue, Duration.ZERO); + condition.fetchInitialValue(); + return condition.isConditionMet(); + } + + private double resolveDesiredNumericValue(final ScanContext context, final Object desired) throws Exception + { + if (desired instanceof PVReference pvReference) + return resolvePVReferenceValue(context, pvReference); + return ((Number) desired).doubleValue(); + } + + private double resolvePVReferenceValue(final ScanContext context, final PVReference pvReference) throws Exception + { + final Device refDevice = context.getDevice( + context.getMacros().resolveMacros(pvReference.getPVName())); + return VTypeHelper.toDouble(refDevice.read(ScanServerInstance.getScanConfig().getReadTimeout())); + } + + /** Execute one step of the loop + * @param context + * @param device + * @param condition + * @param value + * @throws Exception + */ + private void executeStep(final ScanContext context, final Device device, + final NumericValueCondition condition, final double value) + throws Exception + { + logger.log(Level.INFO, "While setting {0} = {1}{2}", new Object[] { device.getAlias(), value, (condition!=null ? " (waiting)" : "") }); + + // Set device to value for current step of loop + doSkip = false; + synchronized (this) + { + thread = Thread.currentThread(); + } + + try + { + // Execute loop body or show some estimate of progress + // (not including nested commands) + if (doSkip) + context.workPerformed(implementation.size()); + else + context.execute(implementation); + } + finally + { + synchronized (this) + { + thread = null; + } + } + + // If there are no commands that inc. the work units, do it yourself + if (implementation.isEmpty()) + context.workPerformed(1); + } + + /** {@inheritDoc} */ + @Override + public void next() + { + doSkip = true; + synchronized (this) + { + if (thread != null) + thread.interrupt(); + } + } + + /** {@inheritDoc} */ + @Override + public String toString() + { + return command.toString(); + } +} diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/condition/NumericValueCondition.java b/services/scan-server/src/main/java/org/csstudio/scan/server/condition/NumericValueCondition.java index 575c541c0d..8a81f9da56 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/condition/NumericValueCondition.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/condition/NumericValueCondition.java @@ -141,20 +141,26 @@ public boolean isConditionMet() throws Exception { final double value = VTypeHelper.toDouble(device.read()); // Note that these need to fail "safe" if any of the values are NaN + // Tolerance defines a deadband around the desired value: + // EQUALS/UNEQUAL treat anything within tolerance as (not) equal. + // AT_LEAST/AT_MOST are relaxed by tolerance, allowing a value that + // is within tolerance on the "wrong" side to still count as reached. + // ABOVE/BELOW are strict comparisons, so the value must clear the + // tolerance band around desired_value before the condition is met. switch (comparison) { case EQUALS: return Math.abs(desired_value - value) <= tolerance; case UNEQUAL: - return value != desired_value; + return Math.abs(desired_value - value) > tolerance; case AT_LEAST: - return value >= desired_value; + return value >= desired_value - tolerance; case ABOVE: - return value > desired_value; + return value > desired_value + tolerance; case AT_MOST: - return value <= desired_value; + return value <= desired_value + tolerance; case BELOW: - return value < desired_value; + return value < desired_value - tolerance; case INCREASE_BY: return value >= initial_value + desired_value; case DECREASE_BY: diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/condition/TextValueCondition.java b/services/scan-server/src/main/java/org/csstudio/scan/server/condition/TextValueCondition.java index 5e4a0ff2cd..617401ec94 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/condition/TextValueCondition.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/condition/TextValueCondition.java @@ -24,7 +24,6 @@ import org.csstudio.scan.server.device.DeviceListener; import org.phoebus.core.vtypes.VTypeHelper; -import org.phoebus.util.text.Strings; /** Condition that waits for a Device to reach a certain string value. * @@ -122,7 +121,7 @@ public void await() throws TimeoutException, Exception } private boolean containsValue(String value) { - return Strings.parseStringList(desired_value).stream().anyMatch( + return Arrays.stream(desired_value.split(",")).map(String::trim).anyMatch( v -> v.equals(value) || v.equals(value.strip()) // strip input value just to be sure ); } diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/config/ScanConfig.java b/services/scan-server/src/main/java/org/csstudio/scan/server/config/ScanConfig.java index 84dcc35240..8bd1f3b369 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/config/ScanConfig.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/config/ScanConfig.java @@ -22,6 +22,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.regex.Matcher; import java.util.regex.Pattern; import org.csstudio.scan.device.DeviceInfo; @@ -257,7 +258,7 @@ private void read(final InputStream stream) throws Exception .ifPresent(sec -> read_timeout = TimeDuration.ofSeconds(sec)); for (Element path : XMLUtil.getChildElements(xml, XML_PATH)) - script_paths.add(XMLUtil.getString(path)); + script_paths.add(expandEnvVars(XMLUtil.getString(path))); XMLUtil.getChildString(xml, XML_SIMULATION_HOOK) .ifPresent(hook -> simulation_hook = hook); @@ -300,4 +301,22 @@ private void read(final InputStream stream) throws Exception } } + /** Replace {@code ${ENV_VAR}} references with the corresponding + * environment variable value. + * Unresolved variables are left as-is. + * @param text Text that may contain {@code ${ENV_VAR}} references + * @return Text with environment variables expanded + */ + private static String expandEnvVars(final String text) + { + final Matcher m = Pattern.compile("\\$\\{(\\w+)\\}").matcher(text); + final StringBuilder sb = new StringBuilder(); + while (m.find()) + { + final String val = System.getenv(m.group(1)); + m.appendReplacement(sb, Matcher.quoteReplacement(val != null ? val : m.group(0))); + } + m.appendTail(sb); + return sb.toString(); + } } diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/internal/ExecutableScan.java b/services/scan-server/src/main/java/org/csstudio/scan/server/internal/ExecutableScan.java index 096cfcf271..0b64550218 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/internal/ExecutableScan.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/internal/ExecutableScan.java @@ -571,8 +571,8 @@ private void executeOrDieTrying() throws Exception { getDevice(device_status.get()).write(getName()); ScanCommandUtil.write(this, device_state.get(), getScanState().ordinal()); - ScanCommandUtil.write(this, device_active.get(), 1.0); - ScanCommandUtil.write(this, device_progress.get(), 0.0); + ScanCommandUtil.write(this, device_active.get(), Double.valueOf(1.0)); + ScanCommandUtil.write(this, device_progress.get(), Double.valueOf(0.0)); getDevice(device_finish.get()).write("Starting ..."); logger.log(Level.INFO, this + " sets " + device_active.get() + " = 1.0"); } @@ -652,7 +652,7 @@ else if (state.get() == ScanState.Aborted) ScanCommandUtil.write(this, device_state.get(), getScanState().ordinal(), true, true, device_state.get(), 0.1, state_pv_update_timeout); logger.log(Level.INFO, this + " sets " + device_state.get() + " = " + getScanState()); getDevice(device_finish.get()).write(TimestampFormats.MILLI_FORMAT.format(Instant.now())); - ScanCommandUtil.write(this, device_progress.get(), 100.0); + ScanCommandUtil.write(this, device_progress.get(), Double.valueOf(100.0)); // Update to "anything else running?" final int active = engine.hasPendingScans() ? 1 : 0; ScanCommandUtil.write(this, device_active.get(), active); @@ -706,7 +706,7 @@ public void execute(final ScanCommandImpl command) throws Exception final ScanInfo info = getScanInfo(); try { - ScanCommandUtil.write(this, device_progress.get(), (double) info.getPercentage()); + ScanCommandUtil.write(this, device_progress.get(), Double.valueOf(info.getPercentage())); getDevice(device_finish.get()).write(TimestampFormats.formatCompactDateTime(info.getFinishTime())); } catch (Exception ex) diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/internal/JythonSupport.java b/services/scan-server/src/main/java/org/csstudio/scan/server/internal/JythonSupport.java index 41805648db..6162e6ae20 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/internal/JythonSupport.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/internal/JythonSupport.java @@ -88,6 +88,14 @@ private static boolean init() throw new Exception("Error in scan script path " + pref_path); path = url.toExternalForm(); // Patch file:/path/to/the_file.jar!/path/within + // or jar:file:/path/to/the_file.jar!/path/within + // (the "jar:" scheme prefix is present when running from a jar, + // e.g. `java -jar fnal-scan-server-*.jar`, which is the normal + // deployment. Without stripping it, the resulting path is + // malformed and Jython silently fails to find built-in example + // scripts such as increment.py, "No module named 'increment'".) + if (path.startsWith("jar:")) + path = path.substring(4); if (path.startsWith("file:")) path = path.substring(5); path = path.replace(".jar!", ".jar"); diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/log/DataLogFactory.java b/services/scan-server/src/main/java/org/csstudio/scan/server/log/DataLogFactory.java index 0050432ea1..f4cc40e75d 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/log/DataLogFactory.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/log/DataLogFactory.java @@ -36,7 +36,7 @@ public static void startup(final String location) throws Exception } if (impl == null) impl = new DerbyDataLogFactory(); - logger.log(Level.CONFIG, "Data Log: " + impl); + logger.log(Level.CONFIG, "Data Log: " + impl+", with location: "+location); impl.startup(location); } diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/DerbyDataLog.java b/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/DerbyDataLog.java index 35f13b8613..f03617725b 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/DerbyDataLog.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/DerbyDataLog.java @@ -32,8 +32,14 @@ public DerbyDataLog(final long scan_id) throws Exception { this.scan_id = scan_id; // Initialize sample serial - try (RDBDataLogger derbyDataLogger = new DerbyDataLogger()) { - last_serial = derbyDataLogger.getLastScanDataSerial(scan_id); + final RDBDataLogger dataLogger = new DerbyDataLogger(); + try + { + last_serial = dataLogger.getLastScanDataSerial(scan_id); + } + finally + { + dataLogger.close(); } } @@ -51,8 +57,14 @@ public void doLog(final String device, final ScanSample sample) throws Exception public ScanData getScanData() throws Exception { // Can be called without doLog(), so use separate logger just for this call - try (RDBDataLogger derbyDataLogger = new DerbyDataLogger()) { - return derbyDataLogger.getScanData(scan_id); + final RDBDataLogger dataLogger = new DerbyDataLogger(); + try + { + return dataLogger.getScanData(scan_id); + } + finally + { + dataLogger.close(); } } diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/DerbyDataLogger.java b/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/DerbyDataLogger.java index 7cc7e6c02a..af736389b4 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/DerbyDataLogger.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/DerbyDataLogger.java @@ -39,7 +39,8 @@ public static void startup(final String location) throws Exception // Path where Derby creates databases System.setProperty("derby.system.home", location); - logger.info("Derby Data Log directory: " + System.getProperty("derby.system.home")); + if (logger.isLoggable(Level.INFO)) + logger.log(Level.INFO, "Derby Data Log directory: {0}", System.getProperty("derby.system.home")); // Debug options // System.setProperty("derby.language.logStatementText", "true"); @@ -60,12 +61,32 @@ public static void startup(final String location) throws Exception // this is called, but after the driver had // been shut down, it will unregister and // then newInstance is required to re-start. - Class.forName(DERBY_DRIVER).getDeclaredConstructor().newInstance(); - - try (DerbyDataLogger database = new DerbyDataLogger()) { - if (!database.haveTables()) + final String rdb_url = System.getProperty("org.csstudio.scan.log.rdb_url"); + if (rdb_url != null && rdb_url.startsWith("jdbc:derby://")) + { + // Use network Derby via RDBDataLogger + RDBDataLogger.setJdbcUrl(rdb_url); + logger.log(Level.INFO, "Using network Derby: {0}", rdb_url); + // SHOULD get "location" from rdb_url + Class.forName("org.apache.derby.jdbc.ClientDriver").getDeclaredConstructor().newInstance(); + } + else + { + RDBDataLogger.setJdbcUrl("jdbc:derby:scan;create=true"); + logger.log(Level.INFO, "Derby Data Log directory: {0}", location); + Class.forName(DERBY_DRIVER).getDeclaredConstructor().newInstance(); + } + + final DerbyDataLogger database = new DerbyDataLogger(); + try + { + if (! database.haveTables()) database.createTables(); } + finally + { + database.close(); + } // Start network data server programmatically // final int port = Preferences.getServerPort(); @@ -89,10 +110,11 @@ public DerbyDataLogger() throws Exception * @throws Exception on error */ @Override - protected Connection connect() throws Exception + protected Connection connect() throws SQLException { // Connect - return DriverManager.getConnection("jdbc:derby:scan;create=true"); + logger.log(Level.INFO, "calling DriverManager.getConnection(\"{0}\")", RDBDataLogger.getJdbcUrl()); + return DriverManager.getConnection(RDBDataLogger.getJdbcUrl()); } /** Check if database tables need to be created @@ -101,14 +123,23 @@ protected Connection connect() throws Exception */ private boolean haveTables() throws SQLException { - try (Statement statement = connection.createStatement()) { + logger.info("Derby Data Logger checking Tables"); + final Statement statement = connection.createStatement(); + try + { statement.executeQuery("SELECT * FROM scans WHERE id=1"); return true; - } catch (SQLException ex) { + } + catch (SQLException ex) + { if ("42X05".equals(ex.getSQLState())) return false; throw ex; } + finally + { + statement.close(); + } } /** Create database tables @@ -116,39 +147,53 @@ private boolean haveTables() throws SQLException */ private void createTables() throws Exception { - try (Statement statement = connection.createStatement()) { + final Statement statement = connection.createStatement(); + try + { logger.info("Creating new database tables"); final BufferedReader reader = new BufferedReader( - new InputStreamReader(getClass().getResourceAsStream("/config/scanlog.dbd")) - ); + new InputStreamReader(getClass().getResourceAsStream("/config/scanlog.dbd") ) + ); StringBuilder cmd = new StringBuilder(); String line = reader.readLine(); - while (line != null) { + while (line != null) + { line = line.trim(); // Skip comments - if (!line.startsWith("--")) { - if (line.endsWith(";")) { // Found end of command - cmd.append(line, 0, line.length() - 1); - if (!cmd.isEmpty()) { + if (! line.startsWith("--")) + { + if (line.endsWith(";")) + { // Found end of command + cmd.append(line.substring(0, line.length()-1)); + if (!cmd.isEmpty()) + { final String sql = cmd.toString(); - try { + try + { statement.execute(sql); - } catch (SQLException ex) { + } + catch (SQLException ex) + { // Ignore RROR 42Y55: 'DROP TABLE' cannot be performed on '...' because it does not exist. - if (!ex.getSQLState().equals("42Y55")) + if (! ex.getSQLState().equals("42Y55")) logger.log(Level.INFO, "SQL failed: " + sql, ex); } } cmd = new StringBuilder(); - } else + } + else cmd.append(line); } line = reader.readLine(); } reader.close(); } + finally + { + statement.close(); + } } /** Shut down database. diff --git a/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/RDBDataLogger.java b/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/RDBDataLogger.java index 1ee5398356..ac1816b274 100644 --- a/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/RDBDataLogger.java +++ b/services/scan-server/src/main/java/org/csstudio/scan/server/log/derby/RDBDataLogger.java @@ -7,6 +7,8 @@ ******************************************************************************/ package org.csstudio.scan.server.log.derby; +import static org.csstudio.scan.server.ScanServerInstance.logger; + import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -42,7 +44,7 @@ abstract public class RDBDataLogger implements AutoCloseable final protected Connection connection; /** Device ID cache */ - final private Map devices = new HashMap<>(); + final private Map devices = new HashMap(); /** Re-used statement */ private PreparedStatement insert_sample_statement = null; @@ -80,11 +82,31 @@ private void init(final Connection connection) throws Exception } } + /** JDBC URL to use (embedded default) */ + private static String jdbcUrl = "jdbc:derby:scan;create=true"; + + /** Set JDBC URL for network Derby */ + public static void setJdbcUrl(final String url) + { + jdbcUrl = url; + } + + /** Get JDBC URL for network/embedded Derby */ + public static String getJdbcUrl() + { + return jdbcUrl; + } + /** Connect to RDB * @return Connection * @throws Exception on error */ - abstract protected Connection connect() throws Exception; + + protected Connection connect() throws SQLException + { + logger.log(Level.INFO, "connect() calling java.sql.DriverManager.getConnection({0})", jdbcUrl); + return java.sql.DriverManager.getConnection(jdbcUrl); + } /** Create a new scan in the database * @param scan_name Name of the scan @@ -110,12 +132,18 @@ public Scan createScan(String scan_name) throws Exception statement.setString(1, scan_name); statement.setTimestamp(2, Timestamp.from(now)); statement.executeUpdate(); - try (ResultSet result = statement.getGeneratedKeys()) { - if (!result.next()) + final ResultSet result = statement.getGeneratedKeys(); + try + { + if (! result.next()) throw new Exception("Missing new scan ID"); final long id = result.getLong(1); return new Scan(id, scan_name, now); } + finally + { + result.close(); + } } } @@ -152,7 +180,7 @@ public Scan getScan(final long id) throws Exception */ public List getScans() throws Exception { - final List scans = new ArrayList<>(); + final List scans = new ArrayList(); try ( final PreparedStatement statement = connection.prepareStatement( @@ -197,13 +225,19 @@ public int getDevice(final String device_name) throws Exception { statement.setString(1, device_name); statement.executeUpdate(); - try (ResultSet result = statement.getGeneratedKeys()) { - if (!result.next()) + final ResultSet result = statement.getGeneratedKeys(); + try + { + if (! result.next()) throw new Exception("Missing new device ID"); id = result.getInt(1); devices.put(device_name, id); return id; } + finally + { + result.close(); + } } } @@ -221,11 +255,17 @@ private int findDevice(final String device_name) throws SQLException ) { statement.setString(1, device_name); - try (ResultSet result = statement.executeQuery()) { - if (!result.next()) + final ResultSet result = statement.executeQuery(); + try + { + if (! result.next()) return -1; return result.getInt(1); } + finally + { + result.close(); + } } } @@ -295,19 +335,19 @@ public long getLastScanDataSerial(final long scan_id) throws Exception */ public ScanData getScanData(final long scan_id) throws Exception { - final Map> device_logs = new HashMap<>(); + final Map> deviceLogs = new HashMap>(); // Could fetch all samples for scan ID, but // organizing the retrieval by device in case // that's helpful later on - final String[] devices = getScanDevices(scan_id); - for (String device : devices) + final String[] deviceNames = getScanDevices(scan_id); + for (String device : deviceNames) { final List samples = getScanSamples(scan_id, device); - device_logs.put(device, samples); + deviceLogs.put(device, samples); } - return new ScanData(device_logs); + return new ScanData(deviceLogs); } /** Get samples @@ -318,7 +358,7 @@ public ScanData getScanData(final long scan_id) throws Exception */ private List getScanSamples(final long scan_id, final String device_name) throws Exception { - final List samples = new ArrayList<>(); + final List samples = new ArrayList(); try ( final PreparedStatement statement = connection.prepareStatement( @@ -347,7 +387,7 @@ private List getScanSamples(final long scan_id, final String device_ */ private String[] getScanDevices(final long scan_id) throws SQLException { - final List scanDevices = new ArrayList<>(); + final List deviceNames = new ArrayList(); try ( final PreparedStatement statement = connection.prepareStatement( @@ -357,10 +397,10 @@ private String[] getScanDevices(final long scan_id) throws SQLException statement.setLong(1, scan_id); final ResultSet result = statement.executeQuery(); while (result.next()) - scanDevices.add(result.getString(1)); + deviceNames.add(result.getString(1)); result.close(); } - return scanDevices.toArray(new String[scanDevices.size()]); + return deviceNames.toArray(new String[deviceNames.size()]); } /** Delete logged data for a scan diff --git a/services/scan-server/src/main/resources/META-INF/services/org.phoebus.pv.PVFactory b/services/scan-server/src/main/resources/META-INF/services/org.phoebus.pv.PVFactory new file mode 100644 index 0000000000..46543a6f48 --- /dev/null +++ b/services/scan-server/src/main/resources/META-INF/services/org.phoebus.pv.PVFactory @@ -0,0 +1,4 @@ +org.phoebus.pv.acsys.ACsys_PVFactory +org.phoebus.pv.pva.PVA_PVFactory +org.phoebus.pv.ca.JCA_PVFactory +org.phoebus.pv.loc.LocalPVFactory diff --git a/services/scan-server/src/main/resources/META-INF/services/pv_preferences.properties b/services/scan-server/src/main/resources/META-INF/services/pv_preferences.properties new file mode 100644 index 0000000000..5e593e4b22 --- /dev/null +++ b/services/scan-server/src/main/resources/META-INF/services/pv_preferences.properties @@ -0,0 +1,6 @@ +# ---------------------- +# Package org.phoebus.pv +# ---------------------- + +# Default PV Type +default=pva \ No newline at end of file diff --git a/services/scan-server/src/main/resources/examples/increment.py b/services/scan-server/src/main/resources/examples/increment.py new file mode 100644 index 0000000000..224c3a2748 --- /dev/null +++ b/services/scan-server/src/main/resources/examples/increment.py @@ -0,0 +1,20 @@ +# increment a PV (device) +# Takes two arguments: +# 1) Name of PV from which to read-inc-write +# 2) increment amount +from org.csstudio.scan.command import ScanScript + +class Increment(ScanScript): + def __init__(self, data_pv, inc_val): + self.data_pv = data_pv + self.inc_val = inc_val + + def getDeviceNames(self): + return [ self.data_pv ] + + def run(self, context): + print("Running Increment") + data = context.read(self.data_pv) + print("type(data)="+str(type(data))) + data += float(self.inc_val) + context.write(self.data_pv,data) \ No newline at end of file diff --git a/services/scan-server/src/main/resources/examples/ossystem.py b/services/scan-server/src/main/resources/examples/ossystem.py new file mode 100644 index 0000000000..2b1d459693 --- /dev/null +++ b/services/scan-server/src/main/resources/examples/ossystem.py @@ -0,0 +1,15 @@ +# os.system +import os + +from org.csstudio.scan.command import ScanScript + +class OsSystem(ScanScript): + def __init__(self, command): + self.command = command + + def getDeviceNames(self): + return [] + + def run(self, context): + print("Running OsSystem") + os.system(self.command) diff --git a/services/scan-server/src/main/resources/examples/scan_config.xml b/services/scan-server/src/main/resources/examples/scan_config.xml index 1e270e66c4..306b240c7d 100644 --- a/services/scan-server/src/main/resources/examples/scan_config.xml +++ b/services/scan-server/src/main/resources/examples/scan_config.xml @@ -57,6 +57,7 @@ + ${HOME}/phoebus-scan-scripts