3 import java
.io
.DataInputStream
;
4 import java
.io
.DataOutputStream
;
5 import java
.io
.IOException
;
6 import java
.util
.LinkedList
;
7 import java
.util
.Queue
;
9 import lejos
.remote
.nxt
.BTConnector
;
10 import lejos
.remote
.nxt
.NXTConnection
;
11 import nl
.ru
.des
.bluetooth
.MessageHandler
;
13 public class BTController
extends Thread
{
14 protected NXTConnection connection
;
15 protected DataOutputStream dataOutput
;
16 protected DataInputStream dataInput
;
17 protected MessageHandler sh
;
18 public static Queue
<String
> messageBuffer
;
20 private BTController(MessageHandler sh
, NXTConnection connection
) {
22 dataInput
= connection
.openDataInputStream();
23 dataOutput
= connection
.openDataOutputStream();
24 messageBuffer
= new LinkedList
<String
>();
29 Thread receiver
= new Thread() {
32 StringBuilder sb
= new StringBuilder();
35 int c
= dataInput
.readUnsignedByte();
36 sb
.appendCodePoint(c
);
38 sh
.handleMessage(sb
.toString());
39 sb
= new StringBuilder();
41 } catch (IOException e
) {
49 if (!messageBuffer
.isEmpty()) {
51 dataOutput
.write(messageBuffer
.poll().getBytes());
53 } catch (IOException e
) {
61 public static void SendMessage(String message
) {
62 messageBuffer
.add(message
+ "\n");
65 public static BTController
getBTMaster(final String slave
, final MessageHandler sh
) {
66 BTConnector bt
= new BTConnector();
67 return new BTController(sh
, bt
.connect(slave
, NXTConnection
.RAW
));
70 public static BTController
getBTSlave(MessageHandler sh
) {
71 BTConnector bt
= new BTConnector();
72 return new BTController(sh
, bt
.waitForConnection(60000, NXTConnection
.RAW
));