--- /dev/null
+package lejos.nxt.comm;\r
+import lejos.nxt.*;\r
+import java.io.*;\r
+\r
+/**\r
+ * This class provides a simple way of sending output for viewing on a \r
+ * PC. The output is transmitted via the nxt USB connection or via Bluetooth.\r
+ * If open is not called or if the connection to the PC is timed out, then\r
+ * the output is dicarded.\r
+ */\r
+public class RConsole {\r
+ static PrintStream ps;\r
+ static NXTConnection conn;\r
+ \r
+ private static void init(NXTConnection c)\r
+ {\r
+ if (c == null)\r
+ {\r
+ LCD.drawString("No connection ", 0, 0);\r
+ return;\r
+ }\r
+ conn = c;\r
+ try {\r
+ LCD.drawString("Got connection ", 0, 0);\r
+ byte [] hello = new byte[32];\r
+ int len = conn.read(hello, hello.length);\r
+ if (len != 3 || hello[0] != 'C' || hello[1] != 'O' || hello[2] != 'N')\r
+ {\r
+ LCD.drawString("Console no h/s ", 0, 0);\r
+ conn.close();\r
+ return;\r
+ }\r
+ LCD.drawString("Console open ", 0, 0);\r
+ if (conn == null) return;\r
+ ps = new PrintStream(conn.openOutputStream());\r
+ LCD.refresh();\r
+ println("Console open");\r
+ }\r
+ catch (Exception e)\r
+ {\r
+ LCD.drawString("Console error " + e.getMessage(), 0, 0);\r
+ LCD.refresh();\r
+ }\r
+ }\r
+ \r
+ public static void openUSB(int timeout)\r
+ {\r
+ LCD.drawString("USB Console... ", 0, 0);\r
+ init(USB.waitForConnection(timeout, 0));\r
+\r
+ }\r
+ \r
+ public static void open()\r
+ {\r
+ openUSB(0);\r
+ }\r
+ \r
+ public static void openBluetooth(int timeout)\r
+ {\r
+ LCD.drawString("BT Console... ", 0, 0);\r
+ init(Bluetooth.waitForConnection(timeout, null));\r
+ }\r
+ \r
+ public static void print(String s)\r
+ {\r
+ if (ps == null) return;\r
+ synchronized (ps){\r
+ ps.print(s);\r
+ ps.flush();\r
+ }\r
+ }\r
+ \r
+ public static void println(String s)\r
+ {\r
+ if (ps == null) return;\r
+ synchronized(ps){\r
+ ps.println(s);\r
+ }\r
+ }\r
+ \r
+ public static void close()\r
+ {\r
+ if (conn == null) return;\r
+ try {\r
+ println("Console closed");\r
+ conn.close();\r
+ LCD.drawString("Console closed ", 0, 0);\r
+ LCD.refresh(); \r
+ Thread.sleep(2000);\r
+ }\r
+ catch (Exception e)\r
+ {\r
+ }\r
+ }\r
+ \r
+ public static boolean isOpen() {\r
+ return (ps != null);\r
+ }\r
+ \r
+ public static OutputStream openOutputStream()\r
+ {\r
+ return (conn != null ? conn.openOutputStream() : null);\r
+ }\r
+}\r
+\r
+\r