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

org.bidib.wizard.common.script.booster.CommandStationQueryStateAndExpectCommand Maven / Gradle / Ivy

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

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.bidib.jbidibc.messages.utils.NodeUtils;
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.bidib.wizard.model.status.CommandStationStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CommandStationQueryStateAndExpectCommand extends AbstractScriptCommand {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommandStationQueryStateAndExpectCommand.class);

    public static final String KEY = "csQueryState";

    public static final String HELP =
        CODE_BLOCK_START + KEY + prepareHelpHtml(" [--V:P] [--uid=] ")
            + DIV_END
            + prepareHelpHtml(
                "\nQuery the booster state and compare the expected status. If '--uid' is specified the VID/PID param is ignored. The uniqueId is the hex-encoded uniqueId of the node without the classbits."
                    + "\nA dialog is displayed for a maximum of 30s or when the command station state is changed.\n\nExample:\n")
            + CODE_BLOCK_START + prepareHelpHtml(KEY + " --uid=0x0D2C000502 off") + DIV_END;

    private int[] vidPid;

    private CommandStationStatus expectedStatus;

    private String uniqueId;

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

    protected String getUniqueId() {
        return uniqueId;
    }

    @Override
    public void parse(String commandLine) {
        setLine(commandLine.trim());

        try (Scanner scanner = new Scanner(commandLine)) {
            if (!getKey().equals(scanner.next())) {
                LOGGER.info("Invalid command is scanned, key does not match.");
            }
            line = commandLine.trim();

            try {
                uniqueId = scanner.next("--uid=(0x|0X)?[a-fA-F0-9]+").substring(6);
            }
            catch (Exception ex) {
                LOGGER.info("No uniqueId found. Fallback to VID/PID.");
            }

            if (uniqueId == null) {

                vidPid = ScriptUtils.scanVidPid(scanner, true);
                if (vidPid != null) {
                    LOGGER.info("Current vidPid: {}:{}", vidPid[0], vidPid[1]);
                }
            }

            String expectedCsStatus = scanner.next();
            if (StringUtils.isNotEmpty(expectedCsStatus)) {

                expectedStatus = CommandStationStatus.fromString(expectedCsStatus);
            }
        }

        LOGGER.info("Current vidPid: {}, expectedStatus: {}", vidPid, expectedStatus);

    }

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

    public CommandStationStatus getExpectedStatus() {
        return expectedStatus;
    }

    @Override
    protected void internalExecute(BoosterScripting scripting, ApplicationContext context) {

        final List nodes = new ArrayList<>();

        if (uniqueId != null) {
            long uniqueId = 0;
            Pattern pattern = Pattern.compile("(0x|0X)?([a-fA-F0-9]+)");
            Matcher matcher = pattern.matcher(this.uniqueId);
            if (matcher.matches()) {
                String raw = matcher.group(2);
                uniqueId = Long.parseLong(raw, 16);
                LOGGER.info("UniqueId: {}", uniqueId);
            }
            else {
                addError(context, "No UniqueId provided.");
                return;
            }

            final NodeInterface node = scripting.getNodeByUniqueIdWithoutClassBits(NodeUtils.getUniqueId(uniqueId));
            if (node == null) {
                throw new ScriptExecutionException("No matching node with provided uniqueId found.", this);
            }
            nodes.add(node);
        }
        else 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, VID: " + vidPid[0] + ", PID: " + vidPid[1]);

                throw new IllegalArgumentException(
                    "No matching node with provided VID/PID found, VID: " + vidPid[0] + ", PID: " + vidPid[1]);
            }
        }
        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 query booster state.");
            throw new ScriptExecutionException("No registered node in execution context.", this);
        }

        for (NodeInterface node : nodes) {
            LOGGER.info("Found node: {}", node);
            final CommandStationStatus commandStationStatus =
                scripting.queryCommandStationStatus(node.getCommandStationNode());
            LOGGER.info("Current commandStationStatus: {}", commandStationStatus);

            if (commandStationStatus != expectedStatus) {
                addError(context, "The current command station status does not match the expected status.");

                throw new ScriptExecutionException(
                    "The current command station status does not match the expected status.", this);
            }
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy