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

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

There is a newer version: 2.0.26
Show newest version
package org.bidib.wizard.simulation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.commons.collections4.CollectionUtils;
import org.bidib.jbidibc.messages.AddressData;
import org.bidib.jbidibc.messages.BidibLibrary;
import org.bidib.jbidibc.messages.Feature;
import org.bidib.jbidibc.messages.FeedbackAddressData;
import org.bidib.jbidibc.messages.enums.AddressTypeEnum;
import org.bidib.jbidibc.messages.enums.BoosterState;
import org.bidib.jbidibc.messages.enums.EnrailmentDirectionEnum;
import org.bidib.jbidibc.messages.enums.FeatureEnum;
import org.bidib.jbidibc.messages.enums.PositionLocationEnum;
import org.bidib.jbidibc.messages.exception.ProtocolException;
import org.bidib.jbidibc.messages.message.BidibMessage;
import org.bidib.jbidibc.messages.message.BidibMessageInterface;
import org.bidib.jbidibc.messages.message.BidibRequestFactory;
import org.bidib.jbidibc.messages.message.BoostDiagnosticResponse;
import org.bidib.jbidibc.messages.message.BoostOffMessage;
import org.bidib.jbidibc.messages.message.BoostOnMessage;
import org.bidib.jbidibc.messages.message.BoostStatResponse;
import org.bidib.jbidibc.messages.message.FeedbackAddressResponse;
import org.bidib.jbidibc.messages.message.FeedbackConfidenceResponse;
import org.bidib.jbidibc.messages.message.FeedbackFreeResponse;
import org.bidib.jbidibc.messages.message.FeedbackGetRangeMessage;
import org.bidib.jbidibc.messages.message.FeedbackMultipleResponse;
import org.bidib.jbidibc.messages.message.FeedbackOccupiedResponse;
import org.bidib.jbidibc.messages.message.FeedbackPositionResponse;
import org.bidib.jbidibc.messages.utils.ByteUtils;
import org.bidib.jbidibc.messages.utils.NodeUtils;
import org.bidib.jbidibc.messages.utils.ThreadFactoryBuilder;
import org.bidib.jbidibc.simulation.SimulationBidibMessageProcessor;
import org.bidib.jbidibc.simulation.annotation.BidibNodeSimulator;
import org.bidib.jbidibc.simulation.nodes.DefaultNodeSimulator;
import org.bidib.wizard.model.ports.FeedbackPort;
import org.bidib.wizard.model.ports.Port;
import org.bidib.wizard.model.status.FeedbackPortStatus;
import org.bidib.wizard.simulation.events.FeedbackConfidenceSetEvent;
import org.bidib.wizard.simulation.events.FeedbackConfidenceStatusEvent;
import org.bidib.wizard.simulation.events.FeedbackPortSetStatusEvent;
import org.bidib.wizard.simulation.events.FeedbackPortStatusEvent;
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;

@BidibNodeSimulator(vid = "13", pid = "103")
public class GBMboostNodeSimulator extends DefaultNodeSimulator {
    private static final Logger LOGGER = LoggerFactory.getLogger(GBMboostNodeSimulator.class);

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

    private final Map feedbackPorts = new HashMap();

    private final AtomicBoolean statusFreeze = new AtomicBoolean(false);

    private final AtomicBoolean statusVoid = new AtomicBoolean(false);

    private final AtomicBoolean statusNoSignal = new AtomicBoolean(false);

    private BoosterState boosterState = BoosterState.OFF;

    protected static final int MAX_NUM_OF_FEEDBACK_PORTS = 48;

    protected final ScheduledExecutorService boosterDiagWorker =
        Executors
            .newScheduledThreadPool(2,
                new ThreadFactoryBuilder().setNameFormat("simBoostDiagWorkers-thread-%d").build());

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

    @Override
    protected void prepareFeatures() {
        super.prepareFeatures();

        features.add(new Feature(BidibLibrary.FEATURE_BM_SIZE, MAX_NUM_OF_FEEDBACK_PORTS));
        features.add(new Feature(BidibLibrary.FEATURE_BM_ON, 1));

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

        features.add(new Feature(BidibLibrary.FEATURE_BM_SECACK_AVAILABLE, 1));
        features.add(new Feature(BidibLibrary.FEATURE_BM_SECACK_ON, 20));
        features.add(new Feature(BidibLibrary.FEATURE_BM_ADDR_DETECT_AVAILABLE, 1));
        features.add(new Feature(BidibLibrary.FEATURE_BM_ADDR_DETECT_ON, 1));
        features.add(new Feature(BidibLibrary.FEATURE_BM_ADDR_AND_DIR, 1));
        features.add(new Feature(BidibLibrary.FEATURE_BM_ISTSPEED_AVAILABLE, 1));
        features.add(new Feature(BidibLibrary.FEATURE_BM_ISTSPEED_INTERVAL, 10));
        features.add(new Feature(BidibLibrary.FEATURE_BM_CV_AVAILABLE, 1));
        features.add(new Feature(BidibLibrary.FEATURE_BM_CV_ON, 1));

        features.add(new Feature(BidibLibrary.FEATURE_BST_CUTOUT_AVAIALABLE, 1));
        features.add(new Feature(BidibLibrary.FEATURE_BST_CUTOUT_ON, 1));
        features.add(new Feature(BidibLibrary.FEATURE_BST_TURNOFF_TIME, 8));
        features.add(new Feature(BidibLibrary.FEATURE_BST_INRUSH_TURNOFF_TIME, 30));
        features.add(new Feature(BidibLibrary.FEATURE_BST_AMPERE_ADJUSTABLE, /* 1 */0));
        features.add(new Feature(BidibLibrary.FEATURE_BST_AMPERE, 155));
        features.add(new Feature(BidibLibrary.FEATURE_BST_CURMEAS_INTERVAL, 200));
        features.add(new Feature(BidibLibrary.FEATURE_BST_INHIBIT_AUTOSTART, 0));
        features.add(new Feature(BidibLibrary.FEATURE_BST_INHIBIT_LOCAL_ONOFF, 0));

        features.add(new Feature(BidibLibrary.FEATURE_BM_DYN_STATE_INTERVAL, 5));
        features.add(new Feature(BidibLibrary.FEATURE_BM_EXT_AVAILABLE, 1));

        features.add(new Feature(BidibLibrary.FEATURE_STRING_SIZE, 24));
        features.add(new Feature(BidibLibrary.FEATURE_FW_UPDATE_MODE, 1));
    }

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

        super.start();
    }

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

        if (boosterDiagWorker != null) {
            LOGGER.info("Stop the booster diag worker.");
            boosterDiagWorker.shutdownNow();
        }

        super.stop();
    }

    private void setupFeedbackPorts() {
        for (int id = 0; id < MAX_NUM_OF_FEEDBACK_PORTS; id++) {
            FeedbackPort port = new FeedbackPort();

            port.setId(id);
            // port.setStatus(id % 3 == 0 ? FeedbackPortStatus.FREE : FeedbackPortStatus.OCCUPIED);
            port.setStatus(FeedbackPortStatus.FREE);
            feedbackPorts.put(id, port);
        }
    }

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

        byte[] response = null;
        switch (ByteUtils.getInt(bidibMessage.getType())) {
            case BidibLibrary.MSG_BM_GET_RANGE:
                response = processBmGetRangeRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_BM_MIRROR_MULTIPLE:
                processBmMirrorMultipleRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_BM_MIRROR_OCC:
                processBmMirrorOccupiedRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_BM_MIRROR_FREE:
                processBmMirrorFreeRequest(bidibMessage);
                break;

            case BidibLibrary.MSG_BM_ADDR_GET_RANGE:
                processBmAddrGetRangeRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_BM_GET_CONFIDENCE:
                response = processBmGetConfidenceRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_BOOST_QUERY:
                response = processBoostQueryRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_BOOST_ON:
                response = processBoostOnRequest(bidibMessage);
                break;
            case BidibLibrary.MSG_BOOST_OFF:
                response = processBoostOffRequest(bidibMessage);
                break;
            default:
                response = super.prepareResponse(bidibMessage);
                break;
        }
        return response;
    }

    protected byte[] processBmGetRangeRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the FeedbackGetRangeMessage: {}", bidibMessage);

        byte[] response = null;
        try {
            FeedbackGetRangeMessage feedbackGetRangeMessage = (FeedbackGetRangeMessage) bidibMessage;
            int baseAddress = feedbackGetRangeMessage.getBeginRange();
            int end = feedbackGetRangeMessage.getEndRange();
            int feedbackSize = feedbackGetRangeMessage.getEndRange() - feedbackGetRangeMessage.getBeginRange();

            byte value = 0x00;
            int index = 0;

            int feedbackByteSize = feedbackSize / 8 + (feedbackSize % 8 > 0 ? 1 : 0);

            byte[] feedbackMultiple = new byte[feedbackByteSize];
            int position = feedbackMultiple.length;

            for (int portNum = end; portNum > baseAddress; portNum--) {
                value = (byte) ((value & 0xFF) << 1);
                FeedbackPort fbp = feedbackPorts.get(portNum - 1);

                byte status = 0;
                if (fbp != null) {
                    status = ByteUtils.getLowByte(fbp.getStatus().getType().getType(), 0x01);
                }
                value |= status;
                feedbackMultiple[position - 1] = value;

                index++;
                if (index > 7) {
                    value = 0;
                    index = 0;
                    position--;
                }
            }

            LOGGER.info("Prepared feedback multiple: {}", ByteUtils.bytesToHex(feedbackMultiple));

            FeedbackMultipleResponse feedbackMultipleResponse =
                new FeedbackMultipleResponse(bidibMessage.getAddr(), getNextSendNum(),
                    ByteUtils.getLowByte(baseAddress), ByteUtils.getLowByte(feedbackSize), feedbackMultiple);
            response = feedbackMultipleResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create feedbackMultiple response failed.", ex);
        }
        return response;
    }

    protected void processBmMirrorMultipleRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the FeedbackMirrorMultipleMessage: {}, do nothing ...", bidibMessage);
    }

    protected void processBmMirrorOccupiedRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the processBmMirrorOccupiedRequest: {}, do nothing ...", bidibMessage);
    }

    protected void processBmMirrorFreeRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the processBmMirrorFreeRequest: {}, do nothing ...", bidibMessage);
    }

    protected void processBmAddrGetRangeRequest(BidibMessageInterface bidibMessage) {

        try {
            for (FeedbackPort port : feedbackPorts.values()) {

                int detectorNumber = port.getId();
                List bidibAddresses = new ArrayList<>();
                List addresses = port.getAddresses();
                if (CollectionUtils.isNotEmpty(addresses)) {
                    for (FeedbackAddressData addressData : addresses) {
                        final EnrailmentDirectionEnum enrailmentDirection = addressData.getType();
                        AddressTypeEnum addressType = null;
                        switch (enrailmentDirection) {
                            case LOCOMOTIVE_LEFT:
                            case LOCOMOTIVE_RIGHT:
                                addressType = AddressTypeEnum.LOCOMOTIVE_FORWARD;
                                break;
                            case BASIC_ACCESSORY:
                                addressType = AddressTypeEnum.ACCESSORY;
                                break;
                            case EXTENDED_ACCESSORY:
                                addressType = AddressTypeEnum.EXTENDED_ACCESSORY;
                                break;
                            default:
                                break;
                        }
                        AddressData bidibAddress = new AddressData(addressData.getAddress(), addressType);
                        bidibAddresses.add(bidibAddress);
                    }
                }
                FeedbackAddressResponse feedbackAddressResponse =
                    new FeedbackAddressResponse(bidibMessage.getAddr(), getNextSendNum(), detectorNumber,
                        bidibAddresses);
                byte[] response = feedbackAddressResponse.getContent();
                LOGGER.info("Prepare feedbackAddressResponse: {}", ByteUtils.bytesToHex(response));
                sendSpontanousResponse(response);
            }
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create feedbackAddress response failed.", ex);
        }
    }

    protected byte[] processBmGetConfidenceRequest(BidibMessageInterface bidibMessage) {

        byte[] response = null;
        try {

            byte valid = (byte) (statusVoid.get() ? 1 : 0);
            byte freeze = (byte) (statusFreeze.get() ? 1 : 0);
            byte signal = (byte) (statusNoSignal.get() ? 1 : 0);

            // TODO if more than a single GBM16T is attached we must set more bits? See 4.7.4. Uplink: Nachrichten für
            // Belegtmelder --> MSG_BM_CONFIDENCE
            // Test with real system: See MainMessageListener.confidence()

            FeedbackConfidenceResponse feedbackConfidenceResponse =
                new FeedbackConfidenceResponse(bidibMessage.getAddr(), getNextSendNum(), valid, freeze, signal);
            response = feedbackConfidenceResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create feedbackConfidence response failed.", ex);
        }
        return response;
    }

    protected byte[] processBoostQueryRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the BoostQuery request: {}", bidibMessage);
        byte[] response = null;
        try {
            BoostStatResponse boostStatResponse =
                new BoostStatResponse(bidibMessage.getAddr(), getNextSendNum(), boosterState);
            response = boostStatResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create BoostStatResponse response failed.", ex);
        }
        return response;
    }

    private ScheduledFuture futureTriggerBoostDiagnostic;

    private ScheduledFuture futureTriggerFeedbackMessage;

    protected byte[] processBoostOnRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the BoostOn request: {}", bidibMessage);
        byte[] response = null;
        try {
            BoostOnMessage boostOnMessage = (BoostOnMessage) bidibMessage;
            byte broadcast = boostOnMessage.getBroadcast();
            LOGGER.info("BoostOn with broadcast: {}", broadcast);

            if (broadcast == BoostOnMessage.BROADCAST_MESSAGE) {
                // TODO handle the requested broadcast
            }

            // activate the booster
            boosterState = BoosterState.ON;

            // update the confidence
            statusNoSignal.set(false);

            BoostStatResponse boostStatResponse =
                new BoostStatResponse(bidibMessage.getAddr(), getNextSendNum(), boosterState);
            response = boostStatResponse.getContent();

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

        // use executor to send response
        if (futureTriggerBoostDiagnostic == null) {

            Feature curMeasInterval =
                features
                    .stream().filter(f -> f.getFeatureEnum().equals(FeatureEnum.FEATURE_BST_CURMEAS_INTERVAL))
                    .findFirst().orElse(null);

            LOGGER.info("Schedule the boost diagnostic trigger, curMeasInterval: {}", curMeasInterval);

            int interval = (curMeasInterval != null ? curMeasInterval.getValue() : 200) * 10 /* ms */;

            futureTriggerBoostDiagnostic = boosterDiagWorker.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    LOGGER.info("Trigger boost diag");
                    try {
                        triggerBoostDiagnosticResponse();
                    }
                    catch (Exception ex) {
                        LOGGER.warn("Trigger the boost diagnostic failed.", ex);
                    }
                    LOGGER.info("Trigger boost has finished.");
                }
            }, 500, interval, TimeUnit.MILLISECONDS);
        }

        // use executor to send response
        if (isFeedbackChangesEnabled() && futureTriggerFeedbackMessage == null) {

            LOGGER.info("Schedule the feedback message trigger");

            int interval = 5;

            futureTriggerFeedbackMessage = boosterDiagWorker.scheduleAtFixedRate(() -> {
                LOGGER.info("Trigger feedback response");
                try {
                    triggerFeedbackResponse();
                }
                catch (Exception ex) {
                    LOGGER.warn("Trigger the feedback response failed.", ex);
                }
                LOGGER.info("Trigger feedback response has finished.");
            }, 5, interval, TimeUnit.SECONDS);
        }

        return response;
    }

    protected byte[] processBoostOffRequest(BidibMessageInterface bidibMessage) {
        LOGGER.info("Process the BoostOff request: {}", bidibMessage);
        byte[] response = null;
        try {
            BoostOffMessage boostOffMessage = (BoostOffMessage) bidibMessage;
            byte broadcast = boostOffMessage.getBroadcast();
            LOGGER.info("BoostOn with broadcast: {}", broadcast);

            if (broadcast == BoostOnMessage.BROADCAST_MESSAGE) {
                // TODO handle the requested broadcast
            }

            // deactivate the booster
            boosterState = BoosterState.OFF;

            // update the confidence
            statusNoSignal.set(true);

            BoostStatResponse boostStatResponse =
                new BoostStatResponse(bidibMessage.getAddr(), getNextSendNum(), boosterState);
            response = boostStatResponse.getContent();

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

        if (futureTriggerBoostDiagnostic != null) {
            LOGGER.info("Stop the boost diagnostic trigger.");
            boolean success = futureTriggerBoostDiagnostic.cancel(false);
            LOGGER.info("Stopped the boost diagnostic trigger, success: {}", success);

            futureTriggerBoostDiagnostic = null;
        }

        if (futureTriggerFeedbackMessage != null) {
            LOGGER.info("Stop the feedback message trigger.");
            boolean success = futureTriggerFeedbackMessage.cancel(false);
            LOGGER.info("Stopped the feedback message trigger, success: {}", success);

            futureTriggerFeedbackMessage = null;
        }

        return response;
    }

    protected void triggerBoostDiagnosticResponse() {
        byte[] response = null;

        int currentValue = ThreadLocalRandom.current().nextInt(10, 180 + 1);
        int tempValue = ThreadLocalRandom.current().nextInt(25, 70);
        LOGGER.info("Trigger the boostDiagnostic repsonse, currentValue: {}, tempValue: {}", currentValue, tempValue);

        try {
            BoostDiagnosticResponse boostDiagnosticResponse =
                new BoostDiagnosticResponse(nodeAddress, getNextSendNum(), currentValue, 0xA9, tempValue);
            response = boostDiagnosticResponse.getContent();
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Create boostDiagnostic response failed.", ex);
        }
        sendSpontanousResponse(response);
    }

    protected void triggerConfidenceResponse() {

        LOGGER.info("Trigger the confidence repsonse");

        byte valid = (byte) (statusVoid.get() ? 1 : 0);
        byte freeze = (byte) (statusFreeze.get() ? 1 : 0);
        byte signal = (byte) (statusNoSignal.get() ? 1 : 0);

        try {
            FeedbackConfidenceResponse feedbackConfidenceResponse =
                new FeedbackConfidenceResponse(this.nodeAddress, getNextSendNum(), valid, freeze, signal);
            LOGGER.info("Prepared feedbackConfidenceResponse: {}", feedbackConfidenceResponse);
            sendSpontanousResponse(feedbackConfidenceResponse.getContent());
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Send feedbackConfidenceResponse failed.", ex);
        }
    }

    protected void triggerFeedbackResponse() {

        int maxPortId = Feature.getIntFeatureValue(features, BidibLibrary.FEATURE_BM_SIZE);

        Random generator = new Random();
        int portNum = generator.nextInt(maxPortId);

        try {
            changeFeedbackPortStatus(portNum);
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Publish feedback status failed for portNum: {}", portNum, ex);
        }
    }

    private void publishFeedbackPortChange(Port port) {
        FeedbackPort feedbackPort = (FeedbackPort) port;
        FeedbackPortStatus status = feedbackPort.getStatus();

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

    @Override
    public void queryStatus(Class portClass) {
        if (FeedbackPort.class.equals(portClass)) {
            for (FeedbackPort feedbackPort : feedbackPorts.values()) {
                publishFeedbackPortChange(feedbackPort);
            }

            // publish the confidence
            publishFeedbackConfidenceStatusEvent(statusVoid.get(), statusFreeze.get(), statusNoSignal.get());
        }
    }

    @EventSubscriber(eventClass = FeedbackConfidenceSetEvent.class)
    public void feedbackConfidenceSetEvent(FeedbackConfidenceSetEvent feedbackConfidenceEvent) {
        String nodeAddress = feedbackConfidenceEvent.getNodeAddr();
        LOGGER.info("The change of the feedback confidence was requested, nodeAddress: {}", nodeAddress);

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

        statusVoid.set(feedbackConfidenceEvent.getValid());
        statusFreeze.set(feedbackConfidenceEvent.getFreeze());
        statusNoSignal.set(feedbackConfidenceEvent.getSignal());

        triggerConfidenceResponse();

        publishFeedbackConfidenceStatusEvent(statusVoid.get(), statusFreeze.get(), statusNoSignal.get());
    }

    private void publishFeedbackConfidenceStatusEvent(boolean statusVoid, boolean freeze, boolean noSignal) {

        LOGGER
            .info("The feedbackport confidence status has changed, notify the listeners, nodeAddress: {}", nodeAddress);
        EventBus
            .publish(
                new FeedbackConfidenceStatusEvent(NodeUtils.formatAddress(nodeAddress), statusVoid, freeze, noSignal));
    }

    @EventSubscriber(eventClass = FeedbackPortSetStatusEvent.class)
    public void feedbackPortSetStatus(FeedbackPortSetStatusEvent setStatusEvent) {
        LOGGER.info("The change of the feedback 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();
        try {
            changeFeedbackPortStatus(portNum);
        }
        catch (ProtocolException ex) {
            LOGGER.warn("Publish feedback status failed.", ex);
        }
    }

    private int timestamp;

    private int getTimestamp() {
        timestamp += 10;
        if (timestamp > 65000) {
            timestamp = 0;
        }
        return timestamp;
    }

    private boolean hasTimestampFeature() {
        Feature feature = Feature.findFeature(features, BidibLibrary.FEATURE_BM_TIMESTAMP_ON);

        return (feature != null && feature.getValue() > 0);
    }

    private int decoderAddress = 10;

    private int getDecoderAddress() {
        decoderAddress++;

        if (decoderAddress > 15) {
            decoderAddress = 10;
        }

        return decoderAddress;
    }

    private int locationAddress = 120;

    private int getLocationAddress() {
        locationAddress++;

        if (locationAddress > 150) {
            locationAddress = 120;
        }

        return locationAddress;
    }

    protected void changeFeedbackPortStatus(int portNum) throws ProtocolException {

        FeedbackPort port = feedbackPorts.get(portNum);
        if (port != null) {
            BidibMessage response = null;

            BidibMessage responsePosition = null;

            switch (port.getStatus()) {
                case FREE:
                    port.setStatus(FeedbackPortStatus.OCCUPIED);
                    if (hasTimestampFeature()) {
                        response =
                            new FeedbackOccupiedResponse(getNodeAddress(), getNextSendNum(), portNum, getTimestamp());
                    }
                    else {
                        response = new FeedbackOccupiedResponse(getNodeAddress(), getNextSendNum(), portNum);
                    }

                    int locationType = ByteUtils.getInt(PositionLocationEnum.LOCATOR_BADGE.getType());
                    responsePosition =
                        new FeedbackPositionResponse(getNodeAddress(), getNextSendNum(), getDecoderAddress(),
                            locationType, getLocationAddress());
                    break;
                default:
                    port.setStatus(FeedbackPortStatus.FREE);

                    response = new FeedbackFreeResponse(getNodeAddress(), getNextSendNum(), portNum);
                    break;
            }

            sendSpontanousResponse(response.getContent());

            if (responsePosition != null) {
                sendSpontanousResponse(responsePosition.getContent());
            }

            publishFeedbackPortChange(port);
        }
        else {
            LOGGER.warn("The requested feedback port is not available: {}", portNum);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy