
/**
 * TestRCX.java
 *
 *
 * Created: Wed Jun  2 13:34:12 1999
 *
 * @author Jan Newmarch
 * @version 1.0
 */

package standalone;

import rcx.*;

public class TestRCX implements RCXListener {
    static final String PORT_NAME = "/dev/ttyS0"; // Linux

    public TestRCX() {
	RCXPort port = new RCXPort(PORT_NAME);

	port.addRCXListener(this);

	byte[] byteArray;

	// send ping message, reply should be e7 or ef
	byteArray = RCXOpcode.parseString("10"); // Alive
	port.write(byteArray);

	// beep twice
	byteArray = RCXOpcode.parseString("51 01"); // Play sound
	port.write(byteArray);

	// turn motor A on (forwards)
	byteArray = RCXOpcode.parseString("e1 81"); // Set motor direction
	port.write(byteArray);
	byteArray = RCXOpcode.parseString("21 81"); // Set motor on
	port.write(byteArray);
	try {
	    Thread.currentThread().sleep(1000);
	} catch(Exception e) {
	}

	// turn motor A off
	byteArray = RCXOpcode.parseString("21 41"); // Set motor off
	port.write(byteArray);

	// turn motor A on (backwards)
	byteArray = RCXOpcode.parseString("e1 41"); // Set motor direction
	port.write(byteArray);
	byteArray = RCXOpcode.parseString("21 81"); // Set motor on
	port.write(byteArray);
	try {
	    Thread.currentThread().sleep(1000);
	} catch(Exception e) {
	}

	// turn motor A off
	byteArray = RCXOpcode.parseString("21 41"); // Set motor off
	port.write(byteArray);
    }

    /**
     * listener method for messages from the RCX
     */
    public void receivedMessage(byte[] message) {
	if (message == null) {
	    return;
	}
	StringBuffer sbuffer = new StringBuffer();
        for(int n = 0; n < message.length; n++) {       
            int newbyte = (int) message[n];
            if (newbyte < 0) {
		newbyte += 256;
	    }
            sbuffer.append(Integer.toHexString(newbyte) + " ");
	}
	System.out.println("response: " + sbuffer.toString());
    }

    /**
     * listener method for error messages from the RCX
     */
    public void receivedError(String error) {
	System.err.println("Error: " + error);
    }
    
    public static void main(String[] args) {
	new TestRCX();
    }
    
} // TestRCX
