001package jmri.jmrix.tmcc;
002
003import jmri.util.StringUtil;
004
005/**
006 * Contains the data payload of a TMCC serial packet.
007 * <p>
008 * Note that <i>only</i> the payload, not the header or trailer, nor the padding
009 * DLE characters are included. These are added during transmission.
010 *
011 * @author Bob Jacobsen Copyright (C) 2001,2003, 2006
012 */
013public class SerialMessage extends jmri.jmrix.AbstractMRMessage {
014    // is this logically an abstract class?
015
016    public SerialMessage() {
017        super(3);
018        setOpCode(0xFE);
019        setTimeout(100);
020    }
021
022    // copy one
023    public SerialMessage(SerialMessage m) {
024        super(m);
025        setTimeout(100);
026    }
027
028    /**
029     * This ctor interprets the String as the exact sequence to send,
030     * byte-for-byte.
031     *
032     * @param m string form of bytes to send
033     *
034     */
035    public SerialMessage(String m) {
036        super(m);
037        setTimeout(100);
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        setTimeout(100);
048    }
049
050    /**
051     * This ctor takes an int value for the 16 bit data content
052     *
053     * @param value The value stored in the content of the packet
054     */
055    public SerialMessage(int value) {
056        super(3);
057        setOpCode(0xFE);
058        putAsWord(value);
059        setTimeout(100);
060    }
061
062    @Override
063    public String toString() {
064        StringBuilder s = new StringBuilder("");
065        for (int i = 0; i < getNumDataElements(); i++) {
066            if (i != 0) {
067                s.append(" ");
068            }
069            s.append(StringUtil.twoHexFromInt(getElement(i)));
070        }
071        return s.toString();
072    }
073
074    public void putAsWord(int val) {
075        setElement(1, (val / 256) & 0xFF);
076        setElement(2, val & 0xFF);
077    }
078
079    public int getAsWord() {
080        return (getElement(1) & 0xFF) * 256 + (getElement(2) & 0xFF);
081    }
082}