/*
 * vim: set ts=8:
 *
 * Copyright (C) 2007 Speecys Corporation
 *		Toshiaki Nozawa <nozawa@speecys.com>
 * All rights reserved.
 *
 */


package	com.speecys.remoConRT;

import	java.nio.ByteBuffer;

class Packet {
    static public final short STICK		= 0x10;
    static public final short SUBCMD 		= 0x11;
    static public final short SERVO		= 0x20;
    static public final short SERVO_NAME	= 0x21;
    static public final short GET_SERVO		= 0x30;
    static public final short GET_SERVO_NAME	= 0x31;
    static public final short GET_ROBOT		= 0x38;
    static public final short SERVO_INFO	= 0x41;
    static public final short ROBOT_INFO	= 0x42;
    static public final short FILE		= 0x60;
    static public final short FILE_ACK		= 0x61;


    static private final byte HEADER = (byte)0xfa;
    static private final byte FOOTER = (byte)0xfb;
    static protected final int MAX_DATA_LEN = 512;
    static protected final int MAX_SNAME = 5;
    static protected final byte FLG1_RET = 1;

    static final private byte[] header = {HEADER, HEADER};
    static final private byte[] footer = {FOOTER, FOOTER};

    static final protected int HEADER_and_FOOTER_LEN
	= header.length + 6 + footer.length;


    private ByteBuffer dbuf
	= ByteBuffer.allocate(HEADER_and_FOOTER_LEN + MAX_DATA_LEN );


    /**
     * ATTENTION!! -- must be dbuf.flip(), after this constructor 
     */
    protected final void setHeader(short cmd, byte[] flag, short len)
    {
	dbuf.put(header);
	dbuf.putShort(cmd);
	dbuf.put(flag, 0, 2);
	dbuf.putShort(len);
    }

    protected final void setFooter(){
	dbuf.put(footer);
	dbuf.flip();
    }

    void setData(short cmd, byte[] flag, ByteBuffer data)
    {
	setHeader(cmd, flag, (short)data.limit());
	dbuf.put(data);
	setFooter();
    }

    void writeTo(java.nio.channels.SocketChannel sc)
	throws java.io.IOException
    {
	int cnt = 0;
	while (cnt < dbuf.limit()) {
	    cnt += sc.write(dbuf);
	}

	dbuf.rewind();	// rewind dbuf for next use
    }
}
