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, with an
052     * optional leading byte.  If the value is greater than 0xFFFF,
053     * i.e. the upper byte of three is non-zero, the upper byte is
054     * used as the op code, otherwise 0xFE (TMCC 1) will be used.
055     *
056     * @param value The value stored in the content of the packet
057     */
058    public SerialMessage(int value) {
059        super(3);
060        if ( (value & 0xFF0000) != 0) {
061            setOpCode((value >> 16 ) & 0xFF);
062        } else {
063            setOpCode(0xFE);
064        }
065        putAsWord(value);
066        setTimeout(100);
067    }
068
069    @Override
070    public String toString() {
071        StringBuilder s = new StringBuilder("");
072        for (int i = 0; i < getNumDataElements(); i++) {
073            if (i != 0) {
074                s.append(" ");
075            }
076            s.append(StringUtil.twoHexFromInt(getElement(i)));
077        }
078        return s.toString();
079    }
080
081    public void putAsWord(int val) {
082        setElement(1, (val / 256) & 0xFF);
083        setElement(2, val & 0xFF);
084    }
085
086    public int getAsWord() {
087        return (getElement(1) & 0xFF) * 256 + (getElement(2) & 0xFF);
088    }
089}