001package jmri.jmrix.easydcc;
002
003import jmri.CommandStation;
004import org.slf4j.Logger;
005import org.slf4j.LoggerFactory;
006
007/**
008 * EasyDCC implementation of the CommandStation interface.
009 *
010 * @author Bob Jacobsen Copyright (C) 2007
011 */
012public class EasyDccCommandStation implements CommandStation {
013
014    public EasyDccCommandStation(EasyDccSystemConnectionMemo memo) {
015        this.memo = memo;
016    }
017
018    /**
019     * Send a specific packet to the rails.
020     *
021     * @param packet  Byte array representing the packet, including the
022     *                error-correction byte. Must not be null.
023     * @param repeats Number of times to repeat the transmission, capped at 9
024     */
025    @Override
026    public boolean sendPacket(byte[] packet, int repeats) {
027
028        if (repeats > 9) {
029            repeats = 9;
030        }
031        if (repeats < 0) {
032            log.error("repeat count out of range: {}", repeats);
033            repeats = 1;
034        }
035
036        EasyDccMessage m = new EasyDccMessage(4 + 3 * packet.length);
037        int i = 0; // counter to make it easier to format the message
038        m.setElement(i++, 'S');  // "S 02 " means send it twice
039        m.setElement(i++, ' ');
040        m.setElement(i++, '0');
041        m.setElement(i++, '0' + repeats);
042
043        for (int j = 0; j < packet.length; j++) {
044            m.setElement(i++, ' ');
045            String s = Integer.toHexString(packet[j] & 0xFF).toUpperCase();
046            if (s.length() == 1) {
047                m.setElement(i++, '0');
048                m.setElement(i++, s.charAt(0));
049            } else {
050                m.setElement(i++, s.charAt(0));
051                m.setElement(i++, s.charAt(1));
052            }
053        }
054
055        memo.getTrafficController().sendEasyDccMessage(m, null);
056
057        return true;
058    }
059
060    EasyDccSystemConnectionMemo memo = null;
061
062    @Override
063    public String getUserName() {
064        if (memo == null) {
065            return "EasyDCC";
066        }
067        return memo.getUserName();
068    }
069
070    @Override
071    public String getSystemPrefix() {
072        if (memo == null) {
073            return "E";
074        }
075        return memo.getSystemPrefix();
076    }
077
078    private final static Logger log = LoggerFactory.getLogger(EasyDccCommandStation.class);
079
080}