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

org.bidib.wizard.simulation.OneDMXSimulator Maven / Gradle / Ivy

The newest version!
package org.bidib.wizard.simulation;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.bidib.jbidibc.messages.BidibLibrary;
import org.bidib.jbidibc.messages.BidibPort;
import org.bidib.jbidibc.messages.Feature;
import org.bidib.jbidibc.messages.LcConfigX;
import org.bidib.jbidibc.messages.LcMacro;
import org.bidib.jbidibc.messages.enums.LcMacroOperationCode;
import org.bidib.jbidibc.messages.enums.LcMacroState;
import org.bidib.jbidibc.messages.enums.LcOutputType;
import org.bidib.jbidibc.messages.enums.LightPortEnum;
import org.bidib.jbidibc.messages.enums.PortModelEnum;
import org.bidib.jbidibc.messages.exception.ProtocolException;
import org.bidib.jbidibc.messages.message.AccessoryGetMessage;
import org.bidib.jbidibc.messages.message.AccessoryParaGetMessage;
import org.bidib.jbidibc.messages.message.AccessoryParaResponse;
import org.bidib.jbidibc.messages.message.AccessoryParaSetMessage;
import org.bidib.jbidibc.messages.message.AccessorySetMessage;
import org.bidib.jbidibc.messages.message.AccessoryStateResponse;
import org.bidib.jbidibc.messages.message.BidibMessageInterface;
import org.bidib.jbidibc.messages.message.BidibRequestFactory;
import org.bidib.jbidibc.messages.message.LcConfigGetMessage;
import org.bidib.jbidibc.messages.message.LcConfigResponse;
import org.bidib.jbidibc.messages.message.LcConfigSetMessage;
import org.bidib.jbidibc.messages.message.LcConfigXGetAllMessage;
import org.bidib.jbidibc.messages.message.LcConfigXGetMessage;
import org.bidib.jbidibc.messages.message.LcConfigXResponse;
import org.bidib.jbidibc.messages.message.LcConfigXSetMessage;
import org.bidib.jbidibc.messages.message.LcKeyMessage;
import org.bidib.jbidibc.messages.message.LcKeyResponse;
import org.bidib.jbidibc.messages.message.LcMacroGetMessage;
import org.bidib.jbidibc.messages.message.LcMacroHandleMessage;
import org.bidib.jbidibc.messages.message.LcMacroParaGetMessage;
import org.bidib.jbidibc.messages.message.LcMacroParaResponse;
import org.bidib.jbidibc.messages.message.LcMacroParaSetMessage;
import org.bidib.jbidibc.messages.message.LcMacroResponse;
import org.bidib.jbidibc.messages.message.LcMacroSetMessage;
import org.bidib.jbidibc.messages.message.LcMacroStateResponse;
import org.bidib.jbidibc.messages.message.LcNotAvailableResponse;
import org.bidib.jbidibc.messages.message.LcOutputMessage;
import org.bidib.jbidibc.messages.message.LcPortQueryAllMessage;
import org.bidib.jbidibc.messages.message.LcPortQueryMessage;
import org.bidib.jbidibc.messages.message.LcStatResponse;
import org.bidib.jbidibc.messages.port.BytePortConfigValue;
import org.bidib.jbidibc.messages.port.Int16PortConfigValue;
import org.bidib.jbidibc.messages.port.PortConfigUtils;
import org.bidib.jbidibc.messages.port.PortConfigValue;
import org.bidib.jbidibc.messages.utils.ByteUtils;
import org.bidib.jbidibc.messages.utils.MacroUtils;
import org.bidib.jbidibc.messages.utils.NodeUtils;
import org.bidib.jbidibc.simulation.DmxNode;
import org.bidib.jbidibc.simulation.SimulationBidibMessageProcessor;
import org.bidib.jbidibc.simulation.SwitchingFunctionsNode;
import org.bidib.jbidibc.simulation.annotation.BidibNodeSimulator;
import org.bidib.jbidibc.simulation.annotation.BidibNodeSimulators;
import org.bidib.jbidibc.simulation.nodes.BacklightPortParamsType;
import org.bidib.jbidibc.simulation.nodes.BacklightPortType;
import org.bidib.jbidibc.simulation.nodes.DefaultNodeSimulator;
import org.bidib.jbidibc.simulation.nodes.DmxChannelParamsType;
import org.bidib.jbidibc.simulation.nodes.DmxChannelsType;
import org.bidib.jbidibc.simulation.nodes.FlatPortType;
import org.bidib.jbidibc.simulation.nodes.InputPortType;
import org.bidib.jbidibc.simulation.nodes.LightPortParamsType;
import org.bidib.jbidibc.simulation.nodes.LightPortType;
import org.bidib.jbidibc.simulation.nodes.PortType;
import org.bidib.wizard.model.dmx.DmxChannel;
import org.bidib.wizard.model.dmx.DmxChannelWrapper;
import org.bidib.wizard.model.ports.BacklightPort;
import org.bidib.wizard.model.ports.DmxLightPort;
import org.bidib.wizard.model.ports.InputPort;
import org.bidib.wizard.model.ports.LightPort;
import org.bidib.wizard.model.ports.Port;
import org.bidib.wizard.model.status.BacklightPortStatus;
import org.bidib.wizard.model.status.InputPortStatus;
import org.bidib.wizard.model.status.LightPortStatus;
import org.bidib.wizard.simulation.events.BacklightPortStatusEvent;
import org.bidib.wizard.simulation.events.InputPortSetStatusEvent;
import org.bidib.wizard.simulation.events.InputPortStatusEvent;
import org.bidib.wizard.simulation.events.LightPortStatusEvent;
import org.bidib.wizard.simulation.macro.MacroContainer;
import org.bushe.swing.event.EventBus;
import org.bushe.swing.event.annotation.AnnotationProcessor;
import org.bushe.swing.event.annotation.EventSubscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@BidibNodeSimulators({ @BidibNodeSimulator(vid = "13", pid = "115"), @BidibNodeSimulator(vid = "251", pid = "112") })
public class OneDMXSimulator extends DefaultNodeSimulator implements SwitchingFunctionsNode, DmxNode {
    private static final Logger LOGGER = LoggerFactory.getLogger(OneDMXSimulator.class);

    private static final String SIMULATION_PANEL_CLASS = "org.bidib.wizard.simulation.client.view.panel.OneDMXPanel";

    protected final Map inputPorts = new HashMap();

    private final Map lightPorts = new HashMap();

    private final Map backlightPorts = new HashMap();

    private final Map macros = new HashMap();

    private final Map dmxChannels = new HashMap();

    protected int inputPortCount;

    protected int inputPortOffset;

    private int lightPortCount;

    private int backlightPortCount;

    public OneDMXSimulator(byte[] nodeAddress, long uniqueId, boolean autoAddFeature,
        SimulationBidibMessageProcessor messageReceiver, final BidibRequestFactory bidibRequestFactory) {
        super(nodeAddress, uniqueId, autoAddFeature, messageReceiver, bidibRequestFactory);
    }

    @Override
    protected void prepareFeatures() {
        LOGGER.info("Prepare the features.");
        super.prepareFeatures();

        // features.add(new Feature(BidibLibrary.FEATURE_CTRL_LIGHT_COUNT, lightPortCount));
        // features.add(new Feature(BidibLibrary.FEATURE_CTRL_BACKLIGHT_COUNT, backlightPortCount));

        features.add(new Feature(BidibLibrary.FEATURE_CTRL_PORT_QUERY_AVAILABLE, 1));

        features.add(new Feature(BidibLibrary.FEATURE_CTRL_STRETCH_DIMM, 100));

        features.add(new Feature(BidibLibrary.FEATURE_CTRL_INPUT_NOTIFY, 1));

        features.add(new Feature(BidibLibrary.FEATURE_CTRL_MAC_COUNT, 32));
        features.add(new Feature(BidibLibrary.FEATURE_CTRL_MAC_SIZE, 30));
        features.add(new Feature(BidibLibrary.FEATURE_CTRL_MAC_SAVE, 32));
        features.add(new Feature(BidibLibrary.FEATURE_CTRL_MAC_LEVEL, 2));

        features.add(new Feature(BidibLibrary.FEATURE_ACCESSORY_COUNT, 8));
        features.add(new Feature(BidibLibrary.FEATURE_ACCESSORY_SURVEILLED, 0));
        features.add(new Feature(BidibLibrary.FEATURE_ACCESSORY_MACROMAPPED, 2));
    }

    @Override
    public void postConstruct() {
        super.postConstruct();

        if (inputPortCount > 0) {
            features.add(new Feature(BidibLibrary.FEATURE_CTRL_INPUT_COUNT, inputPortCount));
        }

        features.add(new Feature(BidibLibrary.FEATURE_CTRL_LIGHT_COUNT, lightPortCount));
        features.add(new Feature(BidibLibrary.FEATURE_CTRL_BACKLIGHT_COUNT, backlightPortCount));
    }

    protected void setupInputPorts() {
        if (CollectionUtils.isNotEmpty(inputPorts.values())) {
            LOGGER.info("InputPorts are set externally already.");
            return;
        }

        for (int id = 0; id < inputPortCount; id++) {
            InputPort port = new InputPort();

            port.setId(id);
            port.setStatus(id % 2 == 0 ? InputPortStatus.ON : InputPortStatus.OFF);
            inputPorts.put(id, port);
        }
    }

    @Override
    protected void prepareCVs() {

        super.prepareCVs();

        // don't restore accessory during startup
        configurationVariables.put(String.valueOf(31), String.valueOf(0));
    }

    @Override
    public String getSimulationPanelClass() {
        return SIMULATION_PANEL_CLASS;
    }

    @Override
    public void start() {
        LOGGER.info("Start the simulator for address: {}", getAddress());

        AnnotationProcessor.process(this);

        // prepare the input ports
        setupInputPorts();

        super.start();
    }

    @Override
    public void stop() {
        AnnotationProcessor.unprocess(this);
        super.stop();
    }

    @EventSubscriber(eventClass = InputPortSetStatusEvent.class)
    public void inputPortSetStatus(InputPortSetStatusEvent setStatusEvent) {
        LOGGER.info("The change of the input port was requested.");
        String nodeAddress = setStatusEvent.getNodeAddr();

        // check if the node is addressed
        if (!isAddressEqual(nodeAddress)) {
            LOGGER.trace("Another node is addressed.");
            return;
        }

        int portNum = setStatusEvent.getPortNum();

        changeInputPortStatus(portNum);
    }

    protected void changeInputPortStatus(int portNum) {

        InputPort port = inputPorts.get(portNum);
        if (port != null) {
            switch (port.getStatus()) {
                case OFF:
                    port.setStatus(InputPortStatus.ON);
                    break;
                default:
                    port.setStatus(InputPortStatus.OFF);
                    break;
            }

            // prepare the request
            final LcKeyMessage lcKeyMessage = new LcKeyMessage(portNum) {
                @Override
                public byte[] getAddr() {
                    return getNodeAddress();
                }
            };
            processRequest(lcKeyMessage);
        }
        else {
            LOGGER.warn("The requested light port is not available: {}", portNum);
        }
    }

    @Override
    protected byte[] prepareResponse(BidibMessageInterface bidibMessage) {

        byte[] response = null;
        switch (ByteUtils.getInt(bidibMessage.getType())) {
            case BidibLibrary.MSG_LC_OUTPUT:
                response = processLcOutputRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_CONFIG_GET:
                response = processLcConfigGetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_CONFIG_SET:
                response = processLcConfigSetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_KEY_QUERY:
                response = processLcKeyQueryRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_PORT_QUERY:
                response = processLcPortQueryRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_CONFIGX_SET:
                response = processLcConfigXSetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_CONFIGX_GET:
                response = processLcConfigXGetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_CONFIGX_GET_ALL:
                processLcConfigXGetAllRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_PORT_QUERY_ALL:
                processLcPortQueryAllRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_MACRO_HANDLE:
                response = processLcMacroHandleRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_MACRO_PARA_GET:
                response = processLcMacroParaGetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_MACRO_PARA_SET:
                response = processLcMacroParaSetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_MACRO_GET:
                response = processLcMacroGetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_LC_MACRO_SET:
                response = processLcMacroSetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_ACCESSORY_SET:
                response = processAccessorySetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_ACCESSORY_GET:
                response = processAccessoryGetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_ACCESSORY_GETALL:
                response = processAccessoryGetAllRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_ACCESSORY_PARA_SET:
                response = processAccessoryParaSetRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_ACCESSORY_PARA_GET:
                response = processAccessoryParaGetRequest(bidibMessage);
                break;
            default:
                response = super.prepareResponse(bidibMessage);
                break;
        }
        return response;
    }

    protected byte[] processLcOutputRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcOutput request: {}", bidibMessage);
        byte[] response = null;
        try {
            LcOutputMessage lcOutputMessage = (LcOutputMessage) bidibMessage;
            LcOutputType outputType = lcOutputMessage.getOutputType(getPortModel());
            int outputNumber = lcOutputMessage.getOutputNumber(getPortModel());
            byte outputStatus = lcOutputMessage.getOutputStatus();

            Port port = null;
            switch (outputType) {
                case LIGHTPORT:
                    DmxLightPort dmxLightPort = lightPorts.get(Integer.valueOf(outputNumber));
                    dmxLightPort.getLightPort().setStatus(LightPortStatus.valueOf(LightPortEnum.valueOf(outputStatus)));
                    port = dmxLightPort.getLightPort();
                    break;
                case BACKLIGHTPORT:
                    BacklightPort backlightPort = backlightPorts.get(Integer.valueOf(outputNumber));
                    backlightPort.setValue(ByteUtils.getInt(outputStatus), true);
                    port = backlightPort;
                    break;
                default:
                    LOGGER.warn("LcOutput request for unsupported port type detected: {}", outputType);
                    break;
            }

            BidibPort bidibPort = prepareBidibPort(getPortModel(), outputType, outputNumber);

            LcStatResponse lcStatResponse =
                new LcStatResponse(bidibMessage.getAddr(), getNextSendNum(), bidibPort,
                    lcOutputMessage.getOutputStatus());
            response = lcStatResponse.getContent();

            if (port != null) {
                switch (outputType) {
                    case LIGHTPORT:
                        publishLightPortChange(port);
                        break;
                    case BACKLIGHTPORT:
                        publishBacklightPortChange(port);
                        break;
                    default:
                        break;
                }
            }
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcStat response failed.", ex);
        }
        return response;
    }

    private void publishLightPortChange(Port port) {
        LightPort lightPort = (LightPort) port;
        LightPortStatus status = lightPort.getStatus();

        LOGGER.info("The lightport status has changed, notify the listeners, nodeAddress: {}", nodeAddress);
        EventBus.publish(new LightPortStatusEvent(NodeUtils.formatAddress(nodeAddress), lightPort.getId(), status));
    }

    private void publishBacklightPortChange(Port port) {
        BacklightPort backlightPort = (BacklightPort) port;
        BacklightPortStatus status = backlightPort.getStatus();

        LOGGER.info("The backlightport status has changed, notify the listeners, nodeAddress: {}", nodeAddress);
        EventBus.publish(new BacklightPortStatusEvent(NodeUtils.formatAddress(nodeAddress), port.getId(), status));
    }

    protected byte[] processLcConfigGetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcConfigGet request: {}", bidibMessage);
        byte[] response = null;

        try {
            LcConfigGetMessage lcConfigGetMessage = (LcConfigGetMessage) bidibMessage;
            LcOutputType outputType = lcConfigGetMessage.getPortType(getPortModel());
            int outputNumber = lcConfigGetMessage.getPortNumber(getPortModel());

            Port port = null;
            switch (outputType) {
                case LIGHTPORT:
                    port = lightPorts.get(Integer.valueOf(outputNumber));
                    break;
                case BACKLIGHTPORT:
                    port = backlightPorts.get(Integer.valueOf(outputNumber));
                    break;
                default:
                    LOGGER.warn("LcConfigGet request for unsupported port type detected: {}", outputType);
                    break;
            }

            LOGGER.info("Return config of port: {}", port);
            BidibPort bidibPort = prepareBidibPort(getPortModel(), outputType, outputNumber);

            LcConfigResponse lcConfigResponse =
                new LcConfigResponse(bidibMessage.getAddr(), getNextSendNum(), bidibPort, port.getPortConfig());
            response = lcConfigResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcConfig response failed.", ex);
        }
        return response;
    }

    protected byte[] processLcConfigSetRequest(BidibMessageInterface bidibMessage) {

        LOGGER.info("Process the LcConfigSet request: {}", bidibMessage);
        byte[] response = null;
        try {
            LcConfigSetMessage lcConfigSetMessage = (LcConfigSetMessage) bidibMessage;
            LcOutputType outputType = lcConfigSetMessage.getPortType(getPortModel());
            int outputNumber = lcConfigSetMessage.getPortNumber(getPortModel());

            Port port = null;
            switch (outputType) {
                case LIGHTPORT:
                    DmxLightPort dmxLightPort = lightPorts.get(Integer.valueOf(outputNumber));
                    if (dmxLightPort != null) {
                        dmxLightPort.getLightPort().setPortConfig(lcConfigSetMessage.getPortConfig());
                        port = dmxLightPort;
                    }
                    else {
                        LOGGER.warn("Lightport not available, outputNumber: {}", outputNumber);
                    }
                    break;
                case BACKLIGHTPORT:
                    BacklightPort backlightPort = backlightPorts.get(Integer.valueOf(outputNumber));
                    if (backlightPort != null) {
                        backlightPort.setPortConfig(lcConfigSetMessage.getPortConfig());
                        port = backlightPort;
                    }
                    else {
                        LOGGER.warn("Backlightport not available, outputNumber: {}", outputNumber);
                    }
                    break;
                default:
                    LOGGER.warn("LcConfigSet request for unsupported port type detected: {}", outputType);
                    break;
            }

            BidibPort bidibPort = prepareBidibPort(getPortModel(), outputType, outputNumber);

            if (port == null) {
                LOGGER.warn("No port assigned!");
                LcNotAvailableResponse magicResponse =
                    new LcNotAvailableResponse(bidibMessage.getAddr(), getNextSendNum(), bidibPort);
                response = magicResponse.getContent();
            }
            else {
                LcConfigResponse magicResponse =
                    new LcConfigResponse(bidibMessage.getAddr(), getNextSendNum(), bidibPort, port.getPortConfig());
                response = magicResponse.getContent();
            }
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcConfigResponse response failed.", ex);
        }
        return response;
    }

    protected byte[] processLcConfigXSetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcConfigXSet request: {}", bidibMessage);
        byte[] response = null;
        try {
            LcConfigXSetMessage lcConfigXSetMessage = (LcConfigXSetMessage) bidibMessage;
            int outputNumber = lcConfigXSetMessage.getPortNumber(getPortModel());

            LcOutputType outputType = lcConfigXSetMessage.getPortType(getPortModel());

            Port port = null;
            switch (outputType) {
                case LIGHTPORT:
                    DmxLightPort dmxLightPort = lightPorts.get(Integer.valueOf(outputNumber));
                    if (dmxLightPort != null) {

                        dmxLightPort
                            .getLightPort()
                            .setPortConfigX(lcConfigXSetMessage.getLcConfigX(messageLogger).getPortConfig());
                        port = dmxLightPort;
                    }
                    else {
                        LOGGER.warn("Lightport not available, outputNumber: {}", outputNumber);
                    }
                    break;
                case BACKLIGHTPORT:
                    BacklightPort backlightPort = backlightPorts.get(Integer.valueOf(outputNumber));
                    if (backlightPort != null) {

                        backlightPort.setPortConfigX(lcConfigXSetMessage.getLcConfigX(messageLogger).getPortConfig());
                        port = backlightPort;
                    }
                    else {
                        LOGGER.warn("Backlightport not available, outputNumber: {}", outputNumber);
                    }
                    break;
                default:
                    LOGGER.warn("LcConfigSet request for unsupported port type detected: {}", outputType);
                    break;
            }

            BidibPort bidibPort = prepareBidibPort(getPortModel(), outputType, outputNumber);

            if (port != null) {
                LcConfigX lcConfigX =
                    new LcConfigX(bidibPort, lcConfigXSetMessage.getLcConfigX(messageLogger).getPortConfig());

                LcConfigXResponse lcConfigXResponse =
                    new LcConfigXResponse(bidibMessage.getAddr(), getNextSendNum(),
                        LcConfigX.getCodedPortConfig(null, lcConfigX, getPortModel()));
                response = lcConfigXResponse.getContent();
            }
            else {
                LOGGER.warn("No port assigned!");
                LcNotAvailableResponse magicResponse =
                    new LcNotAvailableResponse(bidibMessage.getAddr(), getNextSendNum(), bidibPort);
                response = magicResponse.getContent();
            }
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcConfigX response failed.", ex);
        }
        return response;
    }

    protected byte[] processLcConfigXGetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcConfigXGet request: {}", bidibMessage);
        byte[] response = null;

        try {
            LcConfigXGetMessage lcConfigXGetMessage = (LcConfigXGetMessage) bidibMessage;
            int outputNumber = lcConfigXGetMessage.getPortNumber(getPortModel());
            LcOutputType lcOutputType = lcConfigXGetMessage.getPortType(getPortModel());
            Port port = null;
            Map> values = new LinkedHashMap<>();
            switch (lcOutputType) {
                case LIGHTPORT:
                    port = lightPorts.get(Integer.valueOf(outputNumber));

                    final DmxLightPort dmxLightPort = (DmxLightPort) port;
                    LightPort lightPort = ((DmxLightPort) port).getLightPort();
                    values
                        .put(BidibLibrary.BIDIB_PCFG_LEVEL_PORT_ON,
                            new BytePortConfigValue(ByteUtils.getLowByte(lightPort.getPwmMax())));
                    values
                        .put(BidibLibrary.BIDIB_PCFG_LEVEL_PORT_OFF,
                            new BytePortConfigValue(ByteUtils.getLowByte(lightPort.getPwmMin())));
                    values.put(BidibLibrary.BIDIB_PCFG_DIMM_UP_8_8, new Int16PortConfigValue(lightPort.getDimMax()));
                    values.put(BidibLibrary.BIDIB_PCFG_DIMM_DOWN_8_8, new Int16PortConfigValue(lightPort.getDimMin()));

                    if (lightPort.getDmxMapping() != null) {
                        values
                            .put(BidibLibrary.BIDIB_PCFG_OUTPUT_MAP,
                                new BytePortConfigValue(ByteUtils.getLowByte(lightPort.getDmxMapping())));
                    }
                    // else if (dmxLightPort.getDmxTargetChannel() != null) {
                    // dmxLightPort.getDmxTargetChannel().getAssignedPorts()
                    // }
                    break;
                case BACKLIGHTPORT:
                    port = backlightPorts.get(Integer.valueOf(outputNumber));
                    // portConfig = port.getPortConfig();
                    BacklightPort backlightPort = (BacklightPort) port;
                    values
                        .put(BidibLibrary.BIDIB_PCFG_DIMM_UP_8_8,
                            new Int16PortConfigValue(backlightPort.getDimSlopeUp()));
                    values
                        .put(BidibLibrary.BIDIB_PCFG_DIMM_DOWN_8_8,
                            new Int16PortConfigValue(backlightPort.getDimSlopeDown()));
                    values
                        .put(BidibLibrary.BIDIB_PCFG_OUTPUT_MAP,
                            new BytePortConfigValue(ByteUtils.getLowByte(backlightPort.getDmxMapping())));
                    break;
                default:
                    LOGGER.warn("LcConfigGet request for unsupported port type detected: {}", lcOutputType);
                    break;
            }

            LOGGER.info("Return config of port: {}", port);
            BidibPort bidibPort = prepareBidibPort(getPortModel(), lcOutputType, outputNumber);
            LcConfigX lcConfigX = new LcConfigX(bidibPort, values);

            LcConfigXResponse lcConfigXResponse =
                new LcConfigXResponse(bidibMessage.getAddr(), getNextSendNum(),
                    LcConfigX.getCodedPortConfig(null, lcConfigX, getPortModel()));
            response = lcConfigXResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcConfigX response failed.", ex);
        }
        return response;
    }

    protected void processLcConfigXGetAllRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcConfigXGetAll request: {}", bidibMessage);
        byte[] response = null;

        try {
            LcConfigXGetAllMessage lcConfigXGetAllMessage = (LcConfigXGetAllMessage) bidibMessage;
            LcOutputType lcOutputType = lcConfigXGetAllMessage.getPortTypeFrom(getPortModel());

            // TODO evaluate port type/range to

            Map> values = new LinkedHashMap<>();

            if (lcOutputType != null) {
                LOGGER.info("Get all ports for output type: {}", lcOutputType);

                switch (lcOutputType) {
                    case LIGHTPORT:
                        for (DmxLightPort lightPort : lightPorts.values()) {
                            values.clear();
                            values.putAll(lightPort.getLightPort().getPortConfigX());

                            LOGGER.info("Return config of light port: {}", lightPort);
                            BidibPort bidibPort = prepareBidibPort(getPortModel(), lcOutputType, lightPort.getId());
                            LcConfigX lcConfigX = new LcConfigX(bidibPort, values);

                            LcConfigXResponse lcConfigXResponse =
                                new LcConfigXResponse(bidibMessage.getAddr(), getNextSendNum(),
                                    LcConfigX.getCodedPortConfig(null, lcConfigX, getPortModel()));
                            response = lcConfigXResponse.getContent();

                            LOGGER.info("Prepared lcConfigXResponse: {}", ByteUtils.bytesToHex(response));
                            sendSpontanousResponse(response);
                            response = null;
                        }
                        break;
                    case BACKLIGHTPORT:
                        for (BacklightPort backlightPort : backlightPorts.values()) {
                            values.clear();
                            values.putAll(backlightPort.getPortConfigX());

                            LOGGER.info("Return config of backlight port: {}", backlightPort);
                            BidibPort bidibPort = prepareBidibPort(getPortModel(), lcOutputType, backlightPort.getId());
                            LcConfigX lcConfigX = new LcConfigX(bidibPort, values);

                            LcConfigXResponse lcConfigXResponse =
                                new LcConfigXResponse(bidibMessage.getAddr(), getNextSendNum(),
                                    LcConfigX.getCodedPortConfig(null, lcConfigX, getPortModel()));
                            response = lcConfigXResponse.getContent();

                            LOGGER.info("Prepared lcConfigXResponse: {}", ByteUtils.bytesToHex(response));
                            sendSpontanousResponse(response);
                            response = null;
                        }
                        break;
                    case INPUTPORT:
                        for (InputPort inputPort : inputPorts.values()) {
                            values.clear();

                            LOGGER.info("Return config of input port: {}", inputPort);
                            BidibPort bidibPort = prepareBidibPort(getPortModel(), lcOutputType, inputPort.getId());
                            LcConfigX lcConfigX = new LcConfigX(bidibPort, values);

                            LcConfigXResponse lcConfigXResponse =
                                new LcConfigXResponse(bidibMessage.getAddr(), getNextSendNum(),
                                    LcConfigX.getCodedPortConfig(null, lcConfigX, getPortModel()));
                            response = lcConfigXResponse.getContent();

                            LOGGER.info("Prepared lcConfigXResponse: {}", ByteUtils.bytesToHex(response));
                            sendSpontanousResponse(response);
                            response = null;
                        }
                        break;
                    default:
                        LOGGER.warn("Unsupported port type requested: {}", lcOutputType);
                        break;
                }
            }
            else {
                // deliver light ports
                for (DmxLightPort lightPort : lightPorts.values()) {
                    values.clear();

                    values.putAll(lightPort.getLightPort().getPortConfigX());

                    LOGGER.info("Return config of light port: {}", lightPort);
                    BidibPort bidibPort = prepareBidibPort(getPortModel(), lcOutputType, lightPort.getId());
                    LcConfigX lcConfigX = new LcConfigX(bidibPort, values);

                    LcConfigXResponse lcConfigXResponse =
                        new LcConfigXResponse(bidibMessage.getAddr(), getNextSendNum(),
                            LcConfigX.getCodedPortConfig(null, lcConfigX, getPortModel()));
                    response = lcConfigXResponse.getContent();

                    LOGGER.info("Prepared lcConfigXResponse: {}", ByteUtils.bytesToHex(response));
                    sendSpontanousResponse(response);
                    response = null;
                }

                // deliver backlight ports
                for (BacklightPort backlightPort : backlightPorts.values()) {
                    values.clear();
                    values.putAll(backlightPort.getPortConfigX());

                    LOGGER.info("Return config of backlight port: {}", backlightPort);
                    BidibPort bidibPort = prepareBidibPort(getPortModel(), lcOutputType, backlightPort.getId());
                    LcConfigX lcConfigX = new LcConfigX(bidibPort, values);

                    LcConfigXResponse lcConfigXResponse =
                        new LcConfigXResponse(bidibMessage.getAddr(), getNextSendNum(),
                            LcConfigX.getCodedPortConfig(null, lcConfigX, getPortModel()));
                    response = lcConfigXResponse.getContent();

                    LOGGER.info("Prepared lcConfigXResponse: {}", ByteUtils.bytesToHex(response));
                    sendSpontanousResponse(response);
                    response = null;
                }

                // deliver input ports
                for (InputPort inputPort : inputPorts.values()) {
                    values.clear();

                    LOGGER.info("Return config of input port: {}", inputPort);
                    BidibPort bidibPort = prepareBidibPort(getPortModel(), LcOutputType.INPUTPORT, inputPort.getId());
                    LcConfigX lcConfigX = new LcConfigX(bidibPort, values);

                    LcConfigXResponse lcConfigXResponse =
                        new LcConfigXResponse(bidibMessage.getAddr(), getNextSendNum(),
                            LcConfigX.getCodedPortConfig(null, lcConfigX, getPortModel()));
                    response = lcConfigXResponse.getContent();

                    LOGGER.info("Prepared lcConfigXResponse: {}", ByteUtils.bytesToHex(response));
                    sendSpontanousResponse(response);
                    response = null;
                }

            }
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create lcConfigXResponse response failed.", ex);
        }

    }

    protected byte[] processLcKeyQueryRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcKeyQuery request: {}", bidibMessage);
        byte[] response = null;

        byte keyState = 0;
        Port port = null;
        try {
            LcKeyMessage lcKeyMessage = (LcKeyMessage) bidibMessage;
            int portNumber = lcKeyMessage.getBidibPort().getPortNumber(PortModelEnum.type);
            port = inputPorts.get(portNumber);
            keyState = port.getStatus().getType().getType();
            LcKeyResponse lcKeyResponse =
                new LcKeyResponse(bidibMessage.getAddr(), getNextSendNum(), ByteUtils.getLowByte(portNumber), keyState);
            response = lcKeyResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcKey response failed.", ex);
        }

        if (port != null) {
            publishInputPortChange(port);
        }

        return response;
    }

    private void publishInputPortChange(Port port) {
        InputPort inputPort = (InputPort) port;
        InputPortStatus status = inputPort.getStatus();

        LOGGER.info("The inputport status has changed, notify the listeners, nodeAddress: {}", nodeAddress);
        EventBus.publish(new InputPortStatusEvent(NodeUtils.formatAddress(nodeAddress), inputPort.getId(), status));
    }

    protected byte[] processLcPortQueryRequest(BidibMessageInterface bidibMessage) {

        LOGGER.info("Process the LcOutputQuery request: {}", bidibMessage);
        byte[] response = null;

        byte portState = 0;

        try {
            final LcPortQueryMessage lcPortQueryMessage = (LcPortQueryMessage) bidibMessage;
            LcOutputType outputType = lcPortQueryMessage.getPortType(getPortModel());
            int outputNumber = lcPortQueryMessage.getPortNumber(getPortModel());
            LOGGER.info("Get port with portNumber: {}", outputNumber);

            switch (outputType) {
                case INPUTPORT:
                    portState = inputPorts.get(outputNumber).getStatus().getType().getType();
                    break;
                case LIGHTPORT:
                    portState = lightPorts.get(outputNumber).getStatus().getType().getType();
                    break;
                case BACKLIGHTPORT:
                    portState = backlightPorts.get(outputNumber).getStatus().getType().getType();
                    break;
                default:
                    LOGGER.warn("LcOutputQuery for unsupported port type detected: {}", outputType);
                    break;
            }
            BidibPort bidibPort = prepareBidibPort(getPortModel(), outputType, outputNumber);

            LcStatResponse lcStatResponse =
                new LcStatResponse(bidibMessage.getAddr(), getNextSendNum(), bidibPort, portState);
            response = lcStatResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcStat response failed.", ex);
        }
        return response;
    }

    protected byte[] processLcPortQueryAllRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the PortQueryAll request: {}", bidibMessage);
        byte[] response = null;
        try {
            LcPortQueryAllMessage portQueryAllMessage = (LcPortQueryAllMessage) bidibMessage;
            int portRangeFrom = portQueryAllMessage.getPortRangeFrom(getPortModel());
            int portRangeTo = portQueryAllMessage.getPortRangeTo(getPortModel());

            int portTypeMask = portQueryAllMessage.getPortTypeMask();

            LOGGER
                .info("Query all port states, portRangeFrom: {}, portRangeTo: {}, portModel: {}, portTypeMask: {}",
                    portRangeFrom, portRangeTo, getPortModel(), portTypeMask);

            if (PortConfigUtils.isSupportsInputPort(portTypeMask) && MapUtils.isNotEmpty(inputPorts)) {
                for (InputPort inputPort : inputPorts.values()) {

                    if (inputPort.getId() >= portRangeFrom && inputPort.getId() < portRangeTo) {
                        try {
                            InputPortStatus inputPortStatus = inputPort.getStatus();
                            byte portStatus = inputPortStatus.getType().getType();

                            publishPortState(bidibMessage.getAddr(), LcOutputType.INPUTPORT, inputPort.getId(),
                                portStatus);
                        }
                        catch (Exception ex) {
                            LOGGER.warn("Publish port state failed for port: {}", inputPort, ex);
                        }
                    }
                    else {
                        LOGGER.info("Skip input port that is out of port range: {}", inputPort);
                    }
                }
            }

            if (PortConfigUtils.isSupportsLightPort(portTypeMask) && MapUtils.isNotEmpty(lightPorts)) {
                for (DmxLightPort lightPort : lightPorts.values()) {
                    if (lightPort.getId() >= portRangeFrom && lightPort.getId() < portRangeTo) {
                        try {
                            LightPortStatus lightPortStatus = lightPort.getStatus();
                            byte portStatus = lightPortStatus.getType().getType();

                            publishPortState(bidibMessage.getAddr(), LcOutputType.LIGHTPORT, lightPort.getId(),
                                portStatus);
                        }
                        catch (Exception ex) {
                            LOGGER.warn("Publish port state failed for port: {}", lightPort, ex);
                        }
                    }
                    else {
                        LOGGER.info("Skip light port that is out of port range: {}", lightPort);
                    }
                }
            }

            if (PortConfigUtils.isSupportsBacklightPort(portTypeMask) && MapUtils.isNotEmpty(backlightPorts)) {
                for (BacklightPort backlightPort : backlightPorts.values()) {
                    if (backlightPort.getId() >= portRangeFrom && backlightPort.getId() < portRangeTo) {
                        try {
                            BacklightPortStatus backlightPortStatus = backlightPort.getStatus();
                            byte portStatus = backlightPortStatus.getType().getType();

                            publishPortState(bidibMessage.getAddr(), LcOutputType.BACKLIGHTPORT, backlightPort.getId(),
                                portStatus);
                        }
                        catch (Exception ex) {
                            LOGGER.warn("Publish port state failed for port: {}", backlightPort, ex);
                        }
                    }
                    else {
                        LOGGER.info("Skip backlight port that is out of port range: {}", backlightPort);
                    }
                }
            }

            LOGGER.info("Send the terminating LC_NA message.");
            publishLcNaResponse(bidibMessage.getAddr());

        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcStat response failed.", ex);
        }
        return response;
    }

    protected void publishPortState(byte[] address, LcOutputType outputType, int outputNumber, byte portStatus)
        throws ProtocolException {

        BidibPort bidibPort = prepareBidibPort(getPortModel(), outputType, outputNumber);

        LcStatResponse lcStatResponse = new LcStatResponse(address, getNextSendNum(), bidibPort, portStatus);

        LOGGER.info("Prepared LcStatResponse: {}", lcStatResponse);

        byte[] response = lcStatResponse.getContent();
        sendSpontanousResponse(response);
    }

    protected void publishLcNaResponse(byte[] address) throws ProtocolException {

        BidibPort bidibPort = new BidibPort(new byte[] { ByteUtils.getLowByte(0xFF), ByteUtils.getLowByte(0xFF) });

        LcNotAvailableResponse lcNotAvailableResponse =
            new LcNotAvailableResponse(address, getNextSendNum(), bidibPort);

        LOGGER.info("Prepared LcNotAvailableResponse: {}", lcNotAvailableResponse);

        byte[] response = lcNotAvailableResponse.getContent();
        sendSpontanousResponse(response);
    }

    protected byte[] processLcMacroParaGetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcMacroParaGet request: {}", bidibMessage);
        byte[] response = null;

        try {
            LcMacroParaGetMessage lcMacroParaGetMessage = (LcMacroParaGetMessage) bidibMessage;
            int macroNumber = lcMacroParaGetMessage.getMacroNumber();
            int paramId = lcMacroParaGetMessage.getParameterIndex();
            LOGGER.info("Process macroNumber: {}, paramId: {}", macroNumber, paramId);

            // return the stored parameter value
            MacroContainer container = macros.get(macroNumber);
            if (container == null) {
                LOGGER.info("Create new MacroContainer for macro number: {}", macroNumber);
                // initialize a new macro container
                container = new MacroContainer(macroNumber);
                macros.put(macroNumber, container);
            }
            byte[] parameter = container.getMacroParameter(paramId);

            LcMacroParaResponse lcMacroParaResponse =
                new LcMacroParaResponse(bidibMessage.getAddr(), getNextSendNum(), (byte) macroNumber, (byte) paramId,
                    parameter);
            response = lcMacroParaResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcMacroPara response failed.", ex);
        }
        return response;
    }

    protected byte[] processLcMacroParaSetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcMacroParaSet request: {}", bidibMessage);
        byte[] response = null;

        try {
            LcMacroParaSetMessage lcMacroParaSetMessage = (LcMacroParaSetMessage) bidibMessage;
            int macroNumber = lcMacroParaSetMessage.getMacroNumber();
            int paramId = lcMacroParaSetMessage.getParameterIndex();
            byte[] parameter = lcMacroParaSetMessage.getValue();

            // store the parameter value
            MacroContainer container = macros.get(macroNumber);
            if (container == null) {
                // initialize a new macro container
                container = new MacroContainer(macroNumber);
                macros.put(macroNumber, container);
            }
            container.setMacroParameter(paramId, parameter);

            LcMacroParaResponse lcMacroParaResponse =
                new LcMacroParaResponse(bidibMessage.getAddr(), getNextSendNum(), (byte) macroNumber, (byte) paramId,
                    parameter);
            response = lcMacroParaResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcMacroPara response failed.", ex);
        }
        return response;
    }

    protected byte[] processLcMacroHandleRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcMacroHandle request: {}", bidibMessage);
        byte[] response = null;

        try {
            LcMacroHandleMessage lcMacroHandleMessage = (LcMacroHandleMessage) bidibMessage;
            Integer macroNumber = lcMacroHandleMessage.getMacroNumber();
            LcMacroOperationCode lcMacroOperationCode = lcMacroHandleMessage.getMacroOperationCode();

            LOGGER
                .info("Handle macro request, macroNumber: {}, lcMacroOperationCode: {}", macroNumber,
                    lcMacroOperationCode);

            // TODO store the macro state value
            LcMacroState macroState = null;
            switch (lcMacroOperationCode) {
                case START:
                    macroState = LcMacroState.RUNNING;
                    break;
                case DELETE:
                    macroState = LcMacroState.DELETE;
                    LOGGER.info("Remove macro with number: {}", macroNumber);
                    macros.remove(macroNumber);
                    break;
                case OFF:
                    macroState = LcMacroState.OFF;
                    break;
                case RESTORE:
                    macroState = LcMacroState.RESTORE;
                    break;
                case SAVE:
                    macroState = LcMacroState.SAVE;
                    break;
                default:
                    macroState = LcMacroState.NOTEXIST;
                    break;
            }

            LcMacroStateResponse lcMacroStateResponse =
                new LcMacroStateResponse(bidibMessage.getAddr(), getNextSendNum(), ByteUtils.getLowByte(macroNumber),
                    macroState);
            response = lcMacroStateResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcMacroState response failed.", ex);
        }
        return response;
    }

    protected byte[] processLcMacroGetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcMacroGet request: {}", bidibMessage);
        byte[] response = null;

        try {
            LcMacroGetMessage lcMacroGetMessage = (LcMacroGetMessage) bidibMessage;
            Integer macroNumber = lcMacroGetMessage.getMacroNumber();
            int stepNumber = lcMacroGetMessage.getStep();

            // fetch the macro content and test if the macro is available
            MacroContainer container = macros.get(macroNumber);
            if (container == null) {
                // initialize a new macro container
                container = new MacroContainer(macroNumber);
                macros.put(macroNumber, container);
            }
            LcMacro macroStep = container.getMacroStep(stepNumber);

            LcMacro value = macroStep;

            LcMacroResponse lcMacroResponse =
                new LcMacroResponse(bidibMessage.getAddr(), getNextSendNum(), ByteUtils.getLowByte(macroNumber),
                    ByteUtils.getLowByte(stepNumber), value);
            response = lcMacroResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcMacro response failed.", ex);
        }
        return response;
    }

    protected byte[] processLcMacroSetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the LcMacroSet request: {}", bidibMessage);
        byte[] response = null;

        try {
            LcMacroSetMessage lcMacroSetMessage = (LcMacroSetMessage) bidibMessage;
            int macroNumber = lcMacroSetMessage.getMacroNumber();
            int stepNumber = lcMacroSetMessage.getStep();

            LcMacro macroStep = MacroUtils.getMacro(lcMacroSetMessage.getData());
            LOGGER.info("Current macroNumber: {}, stepNumber: {}, macroStep: {}", macroNumber, stepNumber, macroStep);

            // fetch the macro content and test if the macro container is available
            MacroContainer container = macros.get(macroNumber);
            if (container == null) {
                container = new MacroContainer(macroNumber);
                macros.put(macroNumber, container);
            }
            container.setMacroStep(stepNumber, macroStep);
            try {
                LcMacroResponse lcMacroResponse =
                    new LcMacroResponse(bidibMessage.getAddr(), getNextSendNum(), ByteUtils.getLowByte(macroNumber),
                        ByteUtils.getLowByte(stepNumber), macroStep);
                response = lcMacroResponse.getContent();
            }
            catch (NullPointerException npe) {
                LOGGER.warn("create response failed.", npe);
            }
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create LcMacro response failed.", ex);
        }
        return response;
    }

    protected byte[] processAccessorySetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the AccessorySet request: {}", bidibMessage);
        byte[] response = null;

        try {
            AccessorySetMessage accessorySetMessage = (AccessorySetMessage) bidibMessage;
            int accessoryNumber = accessorySetMessage.getAccessoryNumber();
            int aspect = accessorySetMessage.getAspect();

            byte[] value = new byte[] { 0, 0, 0 };

            AccessoryStateResponse accessoryStateResponse =
                new AccessoryStateResponse(bidibMessage.getAddr(), getNextSendNum(), (byte) accessoryNumber,
                    (byte) aspect, value);
            response = accessoryStateResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create AccessoryState response failed.", ex);
        }
        return response;
    }

    protected byte[] processAccessoryGetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the AccessoryGet request: {}", bidibMessage);
        byte[] response = null;

        try {
            AccessoryGetMessage accessoryGetMessage = (AccessoryGetMessage) bidibMessage;
            int accessoryNumber = accessoryGetMessage.getAccessoryNumber();
            int aspect = 0;
            byte[] value = new byte[] { 0, 0, 0 };

            AccessoryStateResponse accessoryStateResponse =
                new AccessoryStateResponse(bidibMessage.getAddr(), getNextSendNum(), (byte) accessoryNumber,
                    (byte) aspect, value);
            response = accessoryStateResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create AccessoryState response failed.", ex);
        }
        return response;
    }

    protected byte[] processAccessoryGetAllRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the AccessoryGetAll request: {}", bidibMessage);
        byte[] response = null;

        try {

            Feature featureAccessoryCount = Feature.findFeature(features, BidibLibrary.FEATURE_ACCESSORY_COUNT);
            int accessoryCount = featureAccessoryCount.getValue();

            int aspect = 0;

            for (int accessoryNumber = 0; accessoryNumber < accessoryCount; accessoryNumber++) {

                byte[] value = new byte[] { 3 /* total */, 0 /* execute */, 0 /* wait */ };

                Feature featureAccessoryMacroMapped =
                    Feature.findFeature(features, BidibLibrary.FEATURE_ACCESSORY_MACROMAPPED);

                if (featureAccessoryMacroMapped != null && featureAccessoryMacroMapped.getValue() > 0) {
                    value[0] = 0; // no aspects by default if macro-mapped

                    if (accessoryNumber == 2) {
                        value[0] = 8; // 8 non-macro mapped aspects for accessory number 2
                        aspect = 2; // aspect 2 is active
                    }
                }

                LOGGER.info("Return data for accessory: {}, data: {}", accessoryNumber, ByteUtils.bytesToHex(value));

                AccessoryStateResponse accessoryStateResponse =
                    new AccessoryStateResponse(bidibMessage.getAddr(), getNextSendNum(), (byte) accessoryNumber,
                        (byte) aspect, value);
                response = accessoryStateResponse.getContent();

                sendSpontanousResponse(response);
            }
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create AccessoryState response failed.", ex);
        }
        return null;
    }

    protected byte[] processAccessoryParaSetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the AccessoryParaSet request: {}", bidibMessage);
        byte[] response = null;

        try {
            AccessoryParaSetMessage accessoryParaSetMessage = (AccessoryParaSetMessage) bidibMessage;
            int accessoryNumber = accessoryParaSetMessage.getAccessoryNumber();
            int paraNumber = accessoryParaSetMessage.getParaNumber();

            byte[] value = accessoryParaSetMessage.getValue();

            AccessoryParaResponse accessoryParaResponse =
                new AccessoryParaResponse(bidibMessage.getAddr(), getNextSendNum(),
                    ByteUtils.getLowByte(accessoryNumber), ByteUtils.getLowByte(paraNumber), value);
            response = accessoryParaResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create AccessoryPara response failed.", ex);
        }
        return response;
    }

    protected byte[] processAccessoryParaGetRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the AccessoryParaGet request: {}", bidibMessage);
        byte[] response = null;

        try {
            AccessoryParaGetMessage accessoryParaGetMessage = (AccessoryParaGetMessage) bidibMessage;
            int accessoryNumber = accessoryParaGetMessage.getAccessoryNumber();
            int paraNumber = accessoryParaGetMessage.getParaNumber();

            // TODO provide the correct data here ...
            byte[] value = new byte[] { 0, 0, 0, 0 };

            AccessoryParaResponse accessoryParaResponse =
                new AccessoryParaResponse(bidibMessage.getAddr(), getNextSendNum(),
                    ByteUtils.getLowByte(accessoryNumber), ByteUtils.getLowByte(paraNumber), value);
            response = accessoryParaResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create AccessoryPara response failed.", ex);
        }
        return response;
    }

    @Override
    public void queryStatus(Class portClass) {
        if (InputPort.class.equals(portClass)) {
            for (InputPort inputPort : inputPorts.values()) {
                publishInputPortChange(inputPort);
            }
        }
        else if (LightPort.class.equals(portClass)) {
            for (DmxLightPort lightPort : lightPorts.values()) {
                publishLightPortChange(lightPort.getLightPort());
            }
        }
        else if (BacklightPort.class.equals(portClass)) {
            for (BacklightPort backlightPort : backlightPorts.values()) {
                publishBacklightPortChange(backlightPort);
            }
        }
    }

    @Override
    public void setPortsConfig(FlatPortType portType) {
    }

    @Override
    public void setPortsConfig(PortType portType) {
        if (portType == null) {
            return;
        }

        if (portType instanceof LightPortType) {
            LightPortType lightPortType = (LightPortType) portType;
            lightPortCount = lightPortType.getCount();
            LOGGER.info("Total number of lightports: {}", lightPortCount);

            // prepare initial lightports
            for (int portId = 0; portId < lightPortCount; portId++) {

                LightPort lightPort = new LightPort();
                lightPort.setId(portId);

                lightPort.setStatus(portId % 3 == 0 ? LightPortStatus.ON : LightPortStatus.OFF);

                Map> portConfig = new HashMap<>();
                portConfig.put(BidibLibrary.BIDIB_PCFG_DIMM_UP_8_8, new Int16PortConfigValue(65535));
                portConfig.put(BidibLibrary.BIDIB_PCFG_DIMM_DOWN_8_8, new Int16PortConfigValue(0));
                portConfig
                    .put(BidibLibrary.BIDIB_PCFG_LEVEL_PORT_OFF, new BytePortConfigValue(ByteUtils.getLowByte(0)));
                portConfig
                    .put(BidibLibrary.BIDIB_PCFG_LEVEL_PORT_ON, new BytePortConfigValue(ByteUtils.getLowByte(255)));

                lightPort.setKnownPortConfigKeys(portConfig.keySet());

                lightPort.setPortConfigX(portConfig);

                DmxLightPort dmxLightPort = new DmxLightPort(lightPort);

                // add the unconfigured lightport
                lightPorts.put(dmxLightPort.getId(), dmxLightPort);
            }

            // overwrite configured ports
            if (CollectionUtils.isNotEmpty(lightPortType.getPort())) {
                final int cvBaseOffset = 215 /* offset */;
                // evaluate the configured ports
                for (LightPortParamsType portParams : lightPortType.getPort()) {
                    LightPort lightPort = new LightPort();
                    lightPort.setId(portParams.getPortId());
                    lightPort.setDimMin8_8(portParams.getDimSlopeDown());
                    lightPort.setDimMax8_8(portParams.getDimSlopeUp());
                    lightPort.setPwmMax(portParams.getIntensityOn());
                    lightPort.setPwmMin(portParams.getIntensityOff());
                    lightPort.setDmxMapping(portParams.getDmxMapping());

                    lightPort.setStatus(LightPortStatus.OFF);

                    // set the KnownPortConfigKeys
                    Set knownPortConfigKeys = new HashSet<>();
                    knownPortConfigKeys.add(BidibLibrary.BIDIB_PCFG_DIMM_UP_8_8);
                    knownPortConfigKeys.add(BidibLibrary.BIDIB_PCFG_DIMM_DOWN_8_8);
                    knownPortConfigKeys.add(BidibLibrary.BIDIB_PCFG_LEVEL_PORT_ON);
                    knownPortConfigKeys.add(BidibLibrary.BIDIB_PCFG_LEVEL_PORT_OFF);
                    knownPortConfigKeys.add(BidibLibrary.BIDIB_PCFG_OUTPUT_MAP);
                    lightPort.setKnownPortConfigKeys(knownPortConfigKeys);

                    DmxLightPort dmxLightPort = new DmxLightPort(lightPort);

                    DmxChannel dmxChannel = dmxChannels.get(portParams.getDmxMapping());
                    dmxLightPort.setDmxTargetChannel(dmxChannel);

                    LOGGER.info("Add configured port: {}", lightPort);

                    // add the configured port
                    lightPorts.put(dmxLightPort.getId(), dmxLightPort);

                    // prepare the CVs
                    int cvOffset = cvBaseOffset + portParams.getPortId() * 7 /* next */;
                    if (dmxLightPort.getDmxTargetChannel() != null) {
                        configurationVariables
                            .put(String.valueOf(cvOffset), String.valueOf(portParams.getDmxMapping()));
                    }
                    else {
                        configurationVariables.put(String.valueOf(cvOffset), String.valueOf(-1));
                    }
                    configurationVariables.put(String.valueOf(cvOffset + 1), String.valueOf(lightPort.getPwmMin()));
                    configurationVariables.put(String.valueOf(cvOffset + 2), String.valueOf(lightPort.getPwmMax()));
                    configurationVariables
                        .put(String.valueOf(cvOffset + 3), String.valueOf(ByteUtils.getLowByte(lightPort.getDimMin())));
                    configurationVariables
                        .put(String.valueOf(cvOffset + 4),
                            String.valueOf(ByteUtils.getHighByte(lightPort.getDimMin())));
                    configurationVariables
                        .put(String.valueOf(cvOffset + 5), String.valueOf(ByteUtils.getLowByte(lightPort.getDimMax())));
                    configurationVariables
                        .put(String.valueOf(cvOffset + 6),
                            String.valueOf(ByteUtils.getHighByte(lightPort.getDimMax())));
                }

                // use the number of configured ports
                lightPortCount = lightPorts.size();
            }
        }
        else if (portType instanceof BacklightPortType) {
            BacklightPortType backlightPortType = (BacklightPortType) portType;
            backlightPortCount = portType.getCount();
            LOGGER.info("Total number of backlight ports: {}", backlightPortCount);

            // prepare initial backlight ports
            for (int portId = 0; portId < backlightPortCount; portId++) {

                BacklightPort backlightPort = new BacklightPort();
                backlightPort.setId(portId);

                // add the unconfigured backlight port
                backlightPorts.put(backlightPort.getId(), backlightPort);
            }

            // overwrite configured ports
            if (CollectionUtils.isNotEmpty(backlightPortType.getPort())) {
                final int cvBaseOffset = 1111 /* offset */;
                // evaluate the configured ports
                for (BacklightPortParamsType portParams : backlightPortType.getPort()) {
                    BacklightPort backlightPort = new BacklightPort();
                    backlightPort.setId(portParams.getPortId());
                    backlightPort.setDmxMapping(portParams.getDmxMapping());
                    backlightPort.setDimSlopeDown(portParams.getDimSlopeDown());
                    backlightPort.setDimSlopeUp(portParams.getDimSlopeUp());

                    backlightPort.setStatus(BacklightPortStatus.START);

                    // set the KnownPortConfigKeys
                    Set knownPortConfigKeys = new HashSet<>();
                    knownPortConfigKeys.add(BidibLibrary.BIDIB_PCFG_DIMM_UP_8_8);
                    knownPortConfigKeys.add(BidibLibrary.BIDIB_PCFG_DIMM_DOWN_8_8);
                    knownPortConfigKeys.add(BidibLibrary.BIDIB_PCFG_LEVEL_PORT_ON);
                    knownPortConfigKeys.add(BidibLibrary.BIDIB_PCFG_LEVEL_PORT_OFF);
                    knownPortConfigKeys.add(BidibLibrary.BIDIB_PCFG_OUTPUT_MAP);
                    backlightPort.setKnownPortConfigKeys(knownPortConfigKeys);

                    LOGGER.info("Add configured port: {}", backlightPort);

                    // add the configured port
                    backlightPorts.put(backlightPort.getId(), backlightPort);

                    // prepare the CVs
                    int cvOffset = cvBaseOffset + portParams.getPortId() * 5 /* next */;
                    // target channel
                    configurationVariables.put(String.valueOf(cvOffset), String.valueOf(backlightPort.getDmxMapping()));
                    // dimm slope down
                    configurationVariables
                        .put(String.valueOf(cvOffset + 1),
                            String.valueOf(ByteUtils.getLowByte(backlightPort.getDimSlopeDown())));
                    configurationVariables
                        .put(String.valueOf(cvOffset + 2),
                            String.valueOf(ByteUtils.getHighByte(backlightPort.getDimSlopeDown())));
                    configurationVariables
                        .put(String.valueOf(cvOffset + 3),
                            String.valueOf(ByteUtils.getLowByte(backlightPort.getDimSlopeUp())));
                    configurationVariables
                        .put(String.valueOf(cvOffset + 4),
                            String.valueOf(ByteUtils.getHighByte(backlightPort.getDimSlopeUp())));
                }

                // use the number of configured ports
                backlightPortCount = backlightPorts.size();
            }
        }
        else if (portType instanceof InputPortType) {
            inputPortCount = portType.getCount();
            inputPortOffset = (portType.getOffset() != null ? portType.getOffset() : 0);

            LOGGER.info("Configured number of input ports: {}", inputPortCount);
        }

    }

    public int getInputPortOffset() {
        return inputPortOffset;
    }

    @Override
    public void setDmxConfig(DmxChannelsType dmxChannelType) {
        LOGGER.info("Prepare the DMX channels.");

        if (dmxChannelType == null) {
            LOGGER.warn("No DMX channels provided.");
            return;
        }

        if (dmxChannelType.getCount() != null) {
            // initialize all channels with '1'
            int cvOffset = 71 /* offset */;
            for (int channelId = 0; channelId < dmxChannelType.getCount().intValue(); channelId++) {
                configurationVariables.put(String.valueOf(cvOffset + channelId), String.valueOf(1));

                // the DMX channelId starts from 1
                int realDmxChannelId = channelId + 1;
                DmxChannel dmxChannel =
                    new DmxChannel(null,
                        DmxChannelWrapper.searchKey(realDmxChannelId))/* .withDmxChannel(realDmxChannelId) */;
                dmxChannel.setInitialState(0);
                dmxChannels.put(realDmxChannelId, dmxChannel);
            }
        }

        if (CollectionUtils.isNotEmpty(dmxChannelType.getChannel())) {
            // override with values from xml file
            int cvOffset = 71 /* offset */;

            // get the configured initial values
            for (DmxChannelParamsType dmxChannelParams : dmxChannelType.getChannel()) {
                int dmxChannelId = dmxChannelParams.getChannelId();

                if (dmxChannelId > 0 && dmxChannelId < 65) {
                    DmxChannel dmxChannel =
                        new DmxChannel(null,
                            DmxChannelWrapper.searchKey(dmxChannelId))/* .withDmxChannel(dmxChannelId) */;
                    dmxChannel.setInitialState(dmxChannelParams.getInitialState());

                    dmxChannels.put(dmxChannelId, dmxChannel);

                    // -1 because dmxChannelId starts from 1 but we have the offset from cvOffset start from 0
                    configurationVariables
                        .put(String.valueOf(cvOffset + dmxChannelId - 1),
                            String.valueOf(dmxChannelParams.getInitialState()));
                }
                else {
                    LOGGER.warn("Current DMX channelId is out of range: {}", dmxChannelId);
                }
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy