Made the robot connected
[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.io.OutputStream;
7 import java.io.PrintWriter;
8 import java.util.Arrays;
9 import java.util.HashSet;
10 import java.util.List;
11 import java.util.Set;
12
13 import lejos.hardware.Sound;
14 import lejos.hardware.lcd.LCD;
15 import lejos.remote.nxt.BTConnector;
16 import lejos.remote.nxt.NXTConnection;
17 import lejos.utility.Delay;
18
19 public abstract class BTMemory extends Thread {
20 private List<String> COLORSTOFIND = Arrays.asList(new String[] { "Blue", "Red", "Yellow" });
21 private Set<String> colors;
22 protected NXTConnection connection;
23 protected OutputStream dataOutput;
24 protected DataInputStream dataInput;
25 protected static PrintWriter writer;
26
27 public BTMemory() {
28 colors = new HashSet<String>();
29 setup();
30 }
31
32 public abstract void setup();
33
34 public void addColor(String c) {
35 colors.add(c);
36 }
37
38 public boolean finished() {
39 return colors.equals(new HashSet<String>(COLORSTOFIND));
40 }
41
42 @Override
43 public void run() {
44 try {
45 while (true) {
46 if (dataInput.available() > 0) {
47 //String msg = dataInput.readLine();
48 LCDPrinter.print(Character.toChars(dataInput.read()).toString());
49 }
50 }
51 }
52 catch (IOException e) {
53 // TODO Auto-generated catch block
54 e.printStackTrace();
55 }
56 }
57
58 public static void SendMessage(String message){
59 writer.println(message);
60 writer.flush();
61 }
62
63 public static BTMemory getBTMemory(boolean master, final String rovername) {
64 if (master) {
65 return new BTMemory() {
66 @Override
67 public void setup() {
68 //LCD.drawString("Create connection", 0, 0);
69 BTConnector btconnector = new BTConnector();
70 //LCD.drawString("BTConnector created", 0, 1);
71 connection = btconnector.connect(rovername, NXTConnection.RAW);
72 //LCD.drawString("Connection created", 0, 2);
73 dataInput = connection.openDataInputStream();
74 dataOutput = connection.openOutputStream();
75 writer = new PrintWriter(dataOutput);
76 //LCD.drawString("Input output created", 0, 3);
77 try {
78 //dataOutput.write(77);
79 writer.println("Hellow");
80 writer.flush();
81 //LCD.clear();
82 //LCD.drawString("Message sent", 0, 4);
83 } catch (Exception e) {
84 e.printStackTrace();
85 }
86 }
87 };
88 } else {
89 return new BTMemory() {
90 @Override
91 public void setup() {
92 //LCD.drawString("Create connection", 0, 0);
93 BTConnector btconnector = new BTConnector();
94 //LCD.drawString("BTConnector created", 0, 1);
95 connection = btconnector.waitForConnection(60000, NXTConnection.RAW);
96 //LCD.drawString("Connection created", 0, 2);
97 dataInput = connection.openDataInputStream();
98 dataOutput = connection.openOutputStream();
99 writer = new PrintWriter(dataOutput);
100 //LCD.drawString("Input output created", 0, 3);
101 }
102 };
103 }
104 }
105 }