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

org.bidib.wizard.common.script.switching.ActivateAspectCommand Maven / Gradle / Ivy

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

import java.util.LinkedList;
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.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
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;

/**
 * The activate aspect command.
 */
public class ActivateAspectCommand extends AbstractScriptCommand {
    private static final Logger LOGGER = LoggerFactory.getLogger(ActivateAspectCommand.class);

    public static final String KEY = "activateAspect";

    public static final String HELP =
        CODE_BLOCK_START + KEY + prepareHelpHtml(" [--V:P] [--all] =")
            + DIV_END + prepareHelpHtml("\nActivate the aspect of accessory.");

    private int[] vidPid;

    private boolean processAllNodes;

    private List taskList;

    public static class AccessoryAspectTask {
        private final int accessoryNumber;

        private final int aspectNumber;

        public AccessoryAspectTask(int accessoryNumber, int aspectNumber) {
            this.accessoryNumber = accessoryNumber;
            this.aspectNumber = aspectNumber;
        }

        public int getAccessoryNumber() {
            return accessoryNumber;
        }

        public int getAspectNumber() {
            return aspectNumber;
        }

        @Override
        public String toString() {
            return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
        }
    }

    public ActivateAspectCommand(final ConsoleService consoleService) {
        super(consoleService, KEY, HELP);
        this.taskList = new LinkedList<>();
    }

    @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();

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

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

            Pattern pattern = Pattern.compile("\\d+=\\d+");
            Matcher matcher = pattern.matcher(line);
            while (matcher.find()) {
                String cvPair = matcher.group();

                try {
                    String[] values = cvPair.split("=");

                    taskList.add(new AccessoryAspectTask(Integer.parseInt(values[0]), Integer.parseInt(values[1])));
                }
                catch (Exception ex) {
                    throw new IllegalArgumentException(
                        "Parse accessoryNumber or aspectNumber failed.\n" + getHelpHtml());
                }
            }
        }

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

        if (taskList.isEmpty()) {
            LOGGER.warn("No accessory to set an aspect defined!");
            throw new IllegalArgumentException("accessory configuration missing.\n" + getHelpHtml());
        }
    }

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

    public boolean isProcessAllNodes() {
        return processAllNodes;
    }

    public List getTaskList() {
        return taskList;
    }

    @Override
    protected void internalExecute(final AccessoryScripting scripting, final ApplicationContext context) {
        LOGGER.info("Activate aspects: {}", taskList);

        final List nodes = new LinkedList<>();

        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.");

                throw new ScriptExecutionException("No matching node with provided VID/PID found.", this);
            }
        }
        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) {

            for (AccessoryAspectTask task : taskList) {
                scripting.setActiveAspect(node.getSwitchingNode(), task.getAccessoryNumber(), task.getAspectNumber());
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy