1 package nl
.ru
.des
.bluetooth
;
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
;
12 public class BTController
extends Thread
{
13 protected NXTConnection connection
;
14 protected DataOutputStream dataOutput
;
15 protected DataInputStream dataInput
;
16 protected MessageHandler sh
;
17 public static Queue
<String
> messageBuffer
;
19 private BTController(MessageHandler sh
, NXTConnection connection
) {
20 this.dataInput
= connection
.openDataInputStream();
21 this.dataOutput
= connection
.openDataOutputStream();
23 messageBuffer
= new LinkedList
<String
>();
28 Thread receiver
= new Thread() {
31 StringBuilder sb
= new StringBuilder();
34 int c
= dataInput
.readUnsignedByte();
36 sh
.handleMessage(sb
.toString());
37 sb
= new StringBuilder();
39 sb
.appendCodePoint(c
);
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 btconnector
= new BTConnector();
67 return new BTController(sh
, btconnector
.connect(slave
, NXTConnection
.RAW
));
70 public static BTController
getBTSlave(MessageHandler sh
) {
71 BTConnector btconnector
= new BTConnector();
72 return new BTController(sh
, btconnector
.waitForConnection(60000, NXTConnection
.RAW
));