001package jmri.jmrix.cmri.serial;
002
003/**
004 * Contains the data payload of a CMRI serial packet.
005 * <p>
006 * Note that <i>only</i> the payload, not the header or trailer, nor the padding
007 * DLE characters are included. These are added during transmission.
008 *
009 * @author Bob Jacobsen Copyright (C) 2001,2003
010 */
011public class SerialMessage extends jmri.jmrix.AbstractMRMessage {
012    // is this logically an abstract class?
013
014    final static int POLL_TIMEOUT = 250;
015
016    public SerialMessage() {
017        super();
018    }
019
020    // create a new one
021    public SerialMessage(int i) {
022        super(i);
023    }
024
025    // copy one
026    public SerialMessage(SerialMessage m) {
027        super(m);
028    }
029
030    /**
031     * This ctor interprets the String as the exact sequence to send,
032     * byte-for-byte.
033     *
034     * @param m message string.
035     */
036    public SerialMessage(String m) {
037        super(m);
038    }
039
040    /**
041     * This ctor interprets the byte array as a sequence of characters to send.
042     *
043     * @param a Array of bytes to send
044     */
045    public SerialMessage(byte[] a) {
046        super(String.valueOf(a));
047    }
048
049    @Override
050    public String toString() {
051        StringBuilder s = new StringBuilder();
052        for (int i = 0; i < getNumDataElements(); i++) {
053            if (i != 0) {
054                s.append(" ");
055            }
056            s.append(jmri.util.StringUtil.twoHexFromInt(getElement(i)));
057        }
058        return s.toString();
059    }
060
061    // static methods to recognize a message
062    public boolean isPoll() {
063        return getElement(1) == 0x50;
064    }
065
066    public boolean isXmt() {
067        return getElement(1) == 0x54;
068    }
069
070    public boolean isInit() {
071        return (getElement(1) == 0x49);
072    }
073
074    public int getUA() {
075        return getElement(0) - 65;
076    }
077
078    // static methods to return a formatted message
079    static public SerialMessage getPoll(int UA) {
080        SerialMessage m = new SerialMessage(2);
081        m.setElement(0, 65 + UA);
082        m.setElement(1, 0x50); // 'P'
083        m.setTimeout(POLL_TIMEOUT);    // minumum reasonable timeout
084        return m;
085    }
086
087}