Implemented communication protocol
[des2015.git] / mart / ev3 / ex2 / nl / ru / des / BTMemory.java
1 package nl.ru.des;
2
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;
8
9 import lejos.remote.nxt.BTConnector;
10 import lejos.remote.nxt.NXTConnection;
11
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;
18
19 private BTController(MessageHandler sh, NXTConnection connection) {
20 this.dataInput = connection.openDataInputStream();
21 this.dataOutput = connection.openDataOutputStream();
22 this.sh = sh;
23 messageBuffer = new LinkedList<String>();
24 }
25
26 @Override
27 public void run() {
28 Thread receiver = new Thread() {
29 @Override
30 public void run() {
31 StringBuilder sb = new StringBuilder();
32 while (true) {
33 try {
34 int c = dataInput.readUnsignedByte();
35 sb.appendCodePoint(c);
36 if (c == '\n') {
37 sh.handleMessage(sb.toString());
38 sb = new StringBuilder();
39 }
40 } catch (IOException e) {
41 e.printStackTrace();
42 }
43 }
44 }
45 };
46 receiver.start();
47 while (true) {
48 if (!messageBuffer.isEmpty()) {
49 try {
50 dataOutput.write(messageBuffer.poll().getBytes());
51 dataOutput.flush();
52 } catch (IOException e) {
53 e.printStackTrace();
54 }
55 }
56 Thread.yield();
57 }
58 }
59
60 public static void SendMessage(String message) {
61 messageBuffer.add(message + "\n");
62 }
63
64 public static BTController getBTMaster(final String slave, final MessageHandler sh) {
65 BTConnector btconnector = new BTConnector();
66 return new BTController(sh, btconnector.connect(slave, NXTConnection.RAW));
67 }
68
69 public static BTController getBTSlave(MessageHandler sh) {
70 BTConnector btconnector = new BTConnector();
71 return new BTController(sh, btconnector.waitForConnection(60000, NXTConnection.RAW));
72 }
73 }