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

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

There is a newer version: 2.0.25
Show newest version
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.BoosterStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BoosterSetStateCommand extends AbstractScriptCommand {

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

    public static final String KEY = "boosterSetState";

    public static final String HELP =
        CODE_BLOCK_START + KEY + prepareHelpHtml(" [--V:P] [--all] [--uid=] [off|on]") + DIV_END
            + prepareHelpHtml(
                "\nSet the booster state. If '--uid' is specified the VID/PID and --all params are ignored. The uniqueId is the hex-encoded uniqueId of the node without the classbits.\n\nExample:\n")
            + CODE_BLOCK_START + prepareHelpHtml(KEY + " --uid=0x0D2C000502 on") + DIV_END;

    private int[] vidPid;

    private boolean processAllNodes;

    private BoosterStatus requestedStatus;

    private String uniqueId;

    public BoosterSetStateCommand(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]);
                }

                if (line.indexOf("--all") > -1) {
                    LOGGER.info("Process all nodes is activated.");
                    processAllNodes = true;

                    scanner.next();
                }
            }

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

                requestedStatus = BoosterStatus.fromString(expectedBoosterStatus);
            }
        }

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

    }

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

    public boolean isProcessAllNodes() {
        return processAllNodes;
    }

    public BoosterStatus getRequestedStatus() {
        return requestedStatus;
    }

    @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) {
                // addError(context, "No matching node with provided VID/PID found.");
                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)) {
                if (processAllNodes) {
                    nodes.addAll(currentNodes);
                }
                else {
                    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 set booster state.");
            throw new ScriptExecutionException("No registered node in execution context.", this);
        }

        for (NodeInterface node : nodes) {
            LOGGER.info("Found node: {}", node);
            final BoosterStatus boosterStatus = node.getBoosterNode().getBoosterStatus();
            LOGGER.info("Current boosterStatus: {}", boosterStatus);

            scripting.setBoosterStatus(node.getBoosterNode(), requestedStatus);
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy