All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.bidib.wizard.common.script.test.ReadMotFuncJsonCommand Maven / Gradle / Ivy

package org.bidib.wizard.common.script.test;

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

import org.apache.commons.collections4.CollectionUtils;
import org.bidib.wizard.api.context.ApplicationContext;
import org.bidib.wizard.api.model.NodeInterface;
import org.bidib.wizard.api.service.console.ConsoleService;
import org.bidib.wizard.common.script.AbstractScriptCommand;
import org.bidib.wizard.common.script.DefaultScriptContext;
import org.bidib.wizard.common.script.ScriptExecutionException;
import org.bidib.wizard.common.script.ScriptUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReadMotFuncJsonCommand extends AbstractScriptCommand {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadMotFuncJsonCommand.class);

    public static final String KEY = "readMotFuncJson";

    public static final String HELP =
        CODE_BLOCK_START + KEY + prepareHelpHtml(
            " [--V:P] --namespace= --index= --responseTimeout= --value=\"\" --termination=\"\"\n")
            + DIV_END
            + prepareHelpHtml(
                "\nRead the Mot-Func json values from the node. The timeout is the maximum value in seconds to wait for the string values from the node.\n"
                    + "The value is the command string to request the data from the node.\nThe termination is the value that is compared to signal the end of the transmission, e.g. \"MJLI END\".");

    private int[] vidPid;

    private int namespace;

    private int index;

    private String value;

    private int responseTimeout;

    private String termination;

    public ReadMotFuncJsonCommand(final ConsoleService consoleService) {
        super(consoleService, KEY, HELP);
    }

    @Override
    public void parse(String commandLine) {
        try (Scanner scanner = new Scanner(commandLine)) {
            if (!getKey().equals(scanner.next())) {
                LOGGER.info("Invalid command is scanned, key does not match.");
                throw new IllegalArgumentException("Invalid command is scanned, key does not match.");
            }

            line = commandLine.trim();

            String arguments = line.substring(KEY.length() + 1);

            try {
                vidPid = ScriptUtils.scanVidPid(scanner, true);
                if (vidPid != null) {
                    LOGGER.info("Current vidPid: {}:{}", vidPid[0], vidPid[1]);
                }
            }
            catch (IllegalArgumentException ex) {
                LOGGER.info("Parse VID/PID failed.", ex);
                throw new IllegalArgumentException("Parse VID/PID failed.\n" + getHelpHtml());
            }
            this.namespace = ScriptUtils.parseIntParam("--namespace=\\d+", arguments);
            this.index = ScriptUtils.parseIntParam("--index=\\d+", arguments);
            this.value = ScriptUtils.parseStringParam("(?<=--value=)([\"\'])(?:(?=(\\\\?))\\2.)*?\\1", arguments);
            this.termination =
                ScriptUtils.parseStringParam("(?<=--termination=)([\"\'])(?:(?=(\\\\?))\\2.)*?\\1", arguments);
            // this.value = ScriptUtils.parseStringParam("(?<=--value=)(?s)(.*$)", arguments);
            // this.termination = ScriptUtils.parseStringParam("(?<=--termination=)(?s)(.*$)", arguments);

            if (this.value.length() > 40) {
                LOGGER.warn("Max length of value exceeded: {}", this.value.length());

                throw new IllegalArgumentException("Max length of value exceeded: " + this.value.length());
            }
        }

        LOGGER.info("Parsed command, namespace: {}", namespace);
    }

    public int getNamespace() {
        return namespace;
    }

    public int getIndex() {
        return index;
    }

    public String getValue() {
        return this.value;
    }

    public int[] getVidPid() {
        return vidPid;
    }

    public int getResponseTimeout() {
        return responseTimeout;
    }

    public String getTermination() {
        return termination;
    }

    @Override
    protected void internalExecute(final TestScripting scripting, final ApplicationContext context) {
        LOGGER
            .info("Set the string, namespace: {}, index: {}, value: '{}', , termination: '{}'", namespace, index, value,
                termination);

        final List nodes = new LinkedList<>();

        if (vidPid != null) {
            List currentNodes = scripting.getNodesByVidAndPid(vidPid[0], vidPid[1]);
            if (CollectionUtils.isNotEmpty(currentNodes)) {
                nodes.add(currentNodes.get(0));
            }
            else {
                addError(context, "No matching node with provided VID/PID found.");
                return;
            }
        }
        else {
            NodeInterface node = context.get(DefaultScriptContext.KEY_SELECTED_NODE, NodeInterface.class);
            LOGGER.info("Fetched the registered selected node: {}", node);
            nodes.add(node);
        }

        if (CollectionUtils.isEmpty(nodes)) {
            LOGGER.warn("No node selected and registered in context. Skip set CV values.");
            throw new ScriptExecutionException("No registered node in execution context.", this);
        }

        for (NodeInterface node : nodes) {
            scripting
                .setStringAndHandleReponse(node.getUniqueId(), namespace, index, value, responseTimeout,
                    (connectionId, responseNode, namespace, index, chunk, logConsole) -> {
                        LOGGER.info("Received response chunk: {}", chunk);

                        try {
                            logConsole.accept(chunk);
                        }
                        catch (Exception ex) {
                            LOGGER.warn("Add received data to console failed.", ex);
                        }

                        if (termination.equals(chunk)) {
                            LOGGER.info("Received the end marker: {}", chunk);
                            return false;
                        }
                        return true;
                    });
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy