001package jmri.jmrix.jmriclient;
002
003import org.slf4j.Logger;
004import org.slf4j.LoggerFactory;
005
006/**
007 * Carries the reply to an JMRIClientMessage.
008 *
009 * @author Bob Jacobsen Copyright (C) 2001, 2004, 2008
010 */
011public class JMRIClientReply extends jmri.jmrix.AbstractMRReply {
012
013    // create a new one
014    public JMRIClientReply() {
015        super();
016    }
017
018    public JMRIClientReply(String s) {
019        super(s);
020    }
021
022    public JMRIClientReply(JMRIClientReply l) {
023        super(l);
024    }
025
026    public boolean isResponseOK() {
027        return getResponseCode().charAt(0) == '1' || getResponseCode().charAt(0) == '2';
028    }
029
030    public String getResponseCode() {
031        // split into 3 parts {TIMESTAMP, ResponseCode, Rest}
032        // and use the second one (ResponseCode)
033        String[] part = toString().split("\\s", 3);
034        return part[1];
035    }
036
037    @Override
038    protected int skipPrefix(int index) {
039        // start at index, passing any whitespace & control characters at the start of the buffer
040        while (index < getNumDataElements() - 1
041                && ((char) getElement(index) <= ' ')) {
042            index++;
043        }
044        return index;
045    }
046
047    /**
048     * Extracts Read-CV returned value from a message. Returns -1 if message
049     * can't be parsed. Expects a message of the form 1264343601.156 100 INFO 1
050     * SM -1 CV 8 99
051     */
052    @Override
053    public int value() {
054        String s = toString();
055        String[] part = s.split("\\s", 10);
056        int val = -1;
057
058        try {
059            int tmp = Integer.valueOf(part[8], 10).intValue();
060            val = tmp;  // don't do this assign until now in case the conversion throws
061        } catch (Exception e) {
062            log.error("Unable to get number from reply: \"{}\"", s);
063        }
064        return val;
065    }
066
067    @Override
068    public boolean isUnsolicited() {
069        String s = toString();
070        // Split in 7 is enough for initial handshake 
071        String[] part = s.split("\\s", 7);
072        // Test for initial handshake message with key "JMRIClient".
073        if (part[2].equals("JMRIClient")) {
074            setUnsolicited();
075            return true;
076        } else {
077            return false;
078        }
079    }
080
081    private final static Logger log = LoggerFactory.getLogger(JMRIClientReply.class);
082
083}
084
085
086