root / trunk / code / projects / colonet / ColonetGUI / Colonet.java @ 389
History | View | Annotate | Download (45.5 KB)
1 |
//
|
---|---|
2 |
// Colonet.java
|
3 |
//
|
4 |
|
5 |
import javax.swing.*; |
6 |
import javax.swing.event.*; |
7 |
import javax.imageio.*; |
8 |
import java.awt.*; |
9 |
import java.awt.image.*; |
10 |
import java.awt.event.*; |
11 |
import java.net.*; |
12 |
import java.io.*; |
13 |
import java.util.Random; |
14 |
|
15 |
|
16 |
/**
|
17 |
* The Colonet Graphical User Interface Applet for use locally and over an internet connection.
|
18 |
* @author Gregory Tress
|
19 |
*
|
20 |
* To generate javadoc on this file or other java files, use javadoc *.java -d doc, where doc
|
21 |
* is the name of the folder into which the files should be written.
|
22 |
*/
|
23 |
public class Colonet extends JApplet implements ActionListener, MouseInputListener, KeyListener, Runnable { |
24 |
|
25 |
// Used for the robot graph
|
26 |
final int CANVAS_SIZE = 500; //the applet may be slow if the canvas gets too large |
27 |
final int BUFFER = 50; |
28 |
final int RADIUS = 30; |
29 |
|
30 |
//Used for the robot controller
|
31 |
final int VECTOR_CONTROLLER_HEIGHT = 220; |
32 |
final int VECTOR_CONTROLLER_WIDTH = 250; |
33 |
|
34 |
|
35 |
// Connection
|
36 |
JTextField txtHost;
|
37 |
JTextField txtPort;
|
38 |
JButton btnConnect;
|
39 |
JButton btnGraph;
|
40 |
JLabel lblConnectionStatus;
|
41 |
JTextArea txtMatrix;
|
42 |
JTextArea txtInfo;
|
43 |
JPanel panelConnect;
|
44 |
JPanel panelServerInterface;
|
45 |
|
46 |
// South
|
47 |
JPanel panelSouth;
|
48 |
JTextArea log;
|
49 |
JScrollPane spLog;
|
50 |
|
51 |
// Control
|
52 |
JPanel panelControl;
|
53 |
JTabbedPane tabPaneControl;
|
54 |
JPanel panelRobotControl;
|
55 |
JPanel panelRobotDirection;
|
56 |
JPanel panelRobotDirectionButtons;
|
57 |
JPanel panelRobotCommands;
|
58 |
JButton btnF, btnB, btnL, btnR, btnActivate;
|
59 |
JComboBox cmbRobotNum;
|
60 |
JLabel lblBattery;
|
61 |
BatteryIcon batteryIcon; |
62 |
JPanel panelBattery;
|
63 |
VectorController vectorController; |
64 |
BufferedImage imageVectorControl;
|
65 |
JButton btnCommand_StopTask;
|
66 |
JButton btnCommand_ResumeTask;
|
67 |
JButton btnCommand_ChargeNow;
|
68 |
JButton btnCommand_StopCharging;
|
69 |
|
70 |
// Task Manager
|
71 |
JPanel panelTaskManager;
|
72 |
JScrollPane spTaskManager;
|
73 |
JPanel panelTaskManagerControls;
|
74 |
JPanel panelTaskManagerControlsPriority;
|
75 |
DefaultListModel taskListModel;
|
76 |
JList taskList;
|
77 |
JButton btnAddTask;
|
78 |
JButton btnRemoveTask;
|
79 |
JButton btnMoveTaskUp;
|
80 |
JButton btnMoveTaskDown;
|
81 |
JButton btnUpdateTasks;
|
82 |
TaskAddWindow taskAddWindow; |
83 |
|
84 |
//Webcam and Graph
|
85 |
WebcamPanel panelWebcam; |
86 |
GraphicsPanel panelGraph; |
87 |
GraphicsConfiguration gc;
|
88 |
volatile BufferedImage image; |
89 |
volatile Graphics2D canvas; |
90 |
int cx, cy;
|
91 |
JTabbedPane tabPaneMain;
|
92 |
|
93 |
|
94 |
Socket socket;
|
95 |
OutputStreamWriter out;
|
96 |
DataUpdater dataUpdater; |
97 |
|
98 |
Font botFont;
|
99 |
volatile int tokenLoc; //the token is currently here |
100 |
volatile int numBots; |
101 |
volatile int selectedBot; //the user has selected this bot |
102 |
volatile Rectangle[] botRect; //contains boundary shapes around bots for click detection |
103 |
volatile int[] xbeeID; |
104 |
|
105 |
Thread drawThread;
|
106 |
Simulator simulator; |
107 |
SelectionIndicator indicator; |
108 |
WebcamLoader webcamLoader; |
109 |
ColonetServerInterface csi; |
110 |
|
111 |
|
112 |
public void init () { |
113 |
// set the default look and feel - choose one
|
114 |
//String laf = UIManager.getSystemLookAndFeelClassName();
|
115 |
String laf = UIManager.getCrossPlatformLookAndFeelClassName(); |
116 |
//String laf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
|
117 |
try {
|
118 |
UIManager.setLookAndFeel(laf);
|
119 |
} catch (UnsupportedLookAndFeelException exc) { |
120 |
System.err.println ("Warning: UnsupportedLookAndFeel: " + laf); |
121 |
} catch (Exception exc) { |
122 |
System.err.println ("Error loading " + laf + ": " + exc); |
123 |
} |
124 |
// We should invoke and wait to avoid browser display difficulties
|
125 |
Runnable r = new Runnable() { |
126 |
public void run() { |
127 |
createAndShowGUI(); |
128 |
} |
129 |
}; |
130 |
try {
|
131 |
SwingUtilities.invokeAndWait(r);
|
132 |
} catch (InterruptedException e) { |
133 |
//Not really sure why we would be in this situation
|
134 |
System.out.println("InterruptedException in init: " + e); |
135 |
} catch (java.lang.reflect.InvocationTargetException e) {
|
136 |
//This could happen for various reasons if there is a problem in createAndShowGUI
|
137 |
e.printStackTrace(); |
138 |
} |
139 |
} |
140 |
|
141 |
public void destroy () { |
142 |
try { drawThread.interrupt(); } catch (Exception e) { } |
143 |
try { indicator.interrupt(); } catch (Exception e) { } |
144 |
} |
145 |
|
146 |
private synchronized void createAndShowGUI () { |
147 |
// init graphical elements
|
148 |
// Get the graphics configuration of the screen to create a buffer
|
149 |
gc = GraphicsEnvironment.getLocalGraphicsEnvironment()
|
150 |
.getDefaultScreenDevice().getDefaultConfiguration(); |
151 |
image = gc.createCompatibleImage(CANVAS_SIZE,CANVAS_SIZE); |
152 |
canvas = image.createGraphics(); |
153 |
canvas.setStroke(new BasicStroke(2)); //set pen width |
154 |
panelGraph = new GraphicsPanel(image, false); //set automatic double-buffering to false. we are doing it manually. |
155 |
panelWebcam = new WebcamPanel();
|
156 |
tabPaneMain = new JTabbedPane(); |
157 |
tabPaneMain.add(panelWebcam, "Webcam");
|
158 |
tabPaneMain.add(panelGraph, "Graph");
|
159 |
|
160 |
// Calculate center of canvas
|
161 |
cx = image.getWidth() / 2;
|
162 |
cy = image.getHeight() / 2;
|
163 |
|
164 |
botFont = new Font("Arial", Font.PLAIN, 14); |
165 |
tokenLoc = 0;
|
166 |
numBots = 0;
|
167 |
selectedBot = 0;
|
168 |
|
169 |
// Connection area
|
170 |
txtMatrix = new JTextArea(); |
171 |
txtMatrix.setBorder(BorderFactory.createTitledBorder("Input Matrix")); |
172 |
txtInfo = new JTextArea(); |
173 |
txtInfo.setBorder(BorderFactory.createTitledBorder("Info")); |
174 |
txtInfo.setEditable(false);
|
175 |
btnGraph = new JButton("Run"); |
176 |
txtHost = new JTextField("localhost"); |
177 |
txtHost.setBorder(BorderFactory.createTitledBorder("Host")); |
178 |
txtPort = new JTextField("10123"); |
179 |
txtPort.setBorder(BorderFactory.createTitledBorder("Port")); |
180 |
btnConnect = new JButton("Connect"); |
181 |
getRootPane().setDefaultButton(btnConnect); |
182 |
lblConnectionStatus = new JLabel("Status: Offline"); |
183 |
panelConnect = new JPanel(); |
184 |
panelConnect.setLayout(new GridLayout(6,1)); |
185 |
panelConnect.add(lblConnectionStatus); |
186 |
panelConnect.add(txtHost); |
187 |
panelConnect.add(txtPort); |
188 |
panelConnect.add(btnConnect); |
189 |
//panelConnect.add(btnGraph);
|
190 |
panelServerInterface = new JPanel(); |
191 |
panelServerInterface.setLayout(new GridLayout(2,1)); |
192 |
panelServerInterface.add(panelConnect); |
193 |
panelServerInterface.add(txtMatrix); |
194 |
|
195 |
// Robot direction panel
|
196 |
panelRobotDirection = new JPanel(); |
197 |
panelRobotDirectionButtons = new JPanel(); |
198 |
btnF = new JButton("^"); |
199 |
btnB = new JButton("v"); |
200 |
btnL = new JButton("<"); |
201 |
btnR = new JButton(">"); |
202 |
btnActivate = new JButton("o"); |
203 |
panelRobotDirectionButtons.setLayout(new GridLayout(1,5)); |
204 |
panelRobotDirectionButtons.add(btnActivate); |
205 |
panelRobotDirectionButtons.add(btnF); |
206 |
panelRobotDirectionButtons.add(btnB); |
207 |
panelRobotDirectionButtons.add(btnL); |
208 |
panelRobotDirectionButtons.add(btnR); |
209 |
|
210 |
imageVectorControl = gc.createCompatibleImage(VECTOR_CONTROLLER_WIDTH, VECTOR_CONTROLLER_HEIGHT); |
211 |
vectorController = new VectorController(imageVectorControl);
|
212 |
panelRobotDirection.setLayout(new BorderLayout()); |
213 |
panelRobotDirection.add(vectorController, BorderLayout.CENTER);
|
214 |
panelRobotDirection.add(panelRobotDirectionButtons, BorderLayout.SOUTH);
|
215 |
|
216 |
// Robot Control and Commands
|
217 |
panelRobotCommands = new JPanel(); |
218 |
panelRobotCommands.setLayout(new GridLayout(5,2)); |
219 |
cmbRobotNum = new JComboBox(); |
220 |
// Battery subset
|
221 |
lblBattery = new JLabel(); |
222 |
batteryIcon = new BatteryIcon(25); |
223 |
//batteryIcon = new BatteryIcon(50, lblBattery.getMaximumSize().height, lblBattery.getMaximumSize().height);
|
224 |
lblBattery = new JLabel(batteryIcon); |
225 |
btnCommand_StopTask = new JButton("Stop Current Task"); |
226 |
btnCommand_ResumeTask = new JButton("Resume Current Task"); |
227 |
btnCommand_ChargeNow = new JButton("Recharge Now"); |
228 |
btnCommand_StopCharging = new JButton("Stop Recharging"); |
229 |
panelRobotCommands.add(new JLabel("Select Robot to Control: ")); |
230 |
panelRobotCommands.add(cmbRobotNum); |
231 |
panelRobotCommands.add(new JLabel("Battery Level: ")); |
232 |
panelRobotCommands.add(lblBattery); |
233 |
panelRobotCommands.add(btnCommand_StopTask); |
234 |
panelRobotCommands.add(btnCommand_ResumeTask); |
235 |
panelRobotCommands.add(btnCommand_ChargeNow); |
236 |
panelRobotCommands.add(btnCommand_StopCharging); |
237 |
panelRobotControl = new JPanel(); |
238 |
panelRobotControl.setLayout(new GridLayout(2,1)); |
239 |
panelRobotControl.add(panelRobotDirection); |
240 |
panelRobotControl.add(panelRobotCommands); |
241 |
|
242 |
|
243 |
// Task Manager
|
244 |
panelTaskManager = new JPanel(); |
245 |
panelTaskManager.setLayout(new BorderLayout()); |
246 |
taskListModel = new DefaultListModel(); |
247 |
taskList = new JList(taskListModel); |
248 |
taskList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
|
249 |
taskList.setSelectedIndex(0);
|
250 |
spTaskManager = new JScrollPane(taskList); |
251 |
panelTaskManagerControls = new JPanel(); |
252 |
panelTaskManagerControls.setLayout(new GridLayout(1,4)); |
253 |
panelTaskManagerControlsPriority = new JPanel(); |
254 |
panelTaskManagerControlsPriority.setLayout(new GridLayout(1,2)); |
255 |
btnAddTask = new JButton("Add..."); |
256 |
btnRemoveTask = new JButton("Remove"); |
257 |
btnMoveTaskUp = new JButton("^"); |
258 |
btnMoveTaskDown = new JButton("v"); |
259 |
btnUpdateTasks = new JButton("Update"); |
260 |
panelTaskManagerControlsPriority.add(btnMoveTaskUp); |
261 |
panelTaskManagerControlsPriority.add(btnMoveTaskDown); |
262 |
panelTaskManagerControls.add(btnAddTask); |
263 |
panelTaskManagerControls.add(btnRemoveTask); |
264 |
panelTaskManagerControls.add(btnUpdateTasks); |
265 |
panelTaskManagerControls.add(panelTaskManagerControlsPriority); |
266 |
panelTaskManager.add(spTaskManager, BorderLayout.CENTER);
|
267 |
panelTaskManager.add(panelTaskManagerControls, BorderLayout.SOUTH);
|
268 |
panelTaskManager.add(new JLabel("Current Task Queue"), BorderLayout.NORTH); |
269 |
taskAddWindow = new TaskAddWindow();
|
270 |
|
271 |
// Message log
|
272 |
log = new JTextArea(); |
273 |
spLog = new JScrollPane(log, |
274 |
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
|
275 |
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
|
276 |
spLog.setBorder(BorderFactory.createTitledBorder("Log")); |
277 |
spLog.setPreferredSize(new Dimension(0, 120)); |
278 |
log.setEditable(false);
|
279 |
|
280 |
// Main control mechanism
|
281 |
panelControl = new JPanel(); |
282 |
panelControl.setLayout(new GridLayout(1,1)); |
283 |
tabPaneControl = new JTabbedPane(JTabbedPane.TOP); |
284 |
tabPaneControl.setPreferredSize(new Dimension(VECTOR_CONTROLLER_WIDTH, 0)); |
285 |
tabPaneControl.addTab("Connection", panelServerInterface);
|
286 |
tabPaneControl.addTab("Robots", panelRobotControl);
|
287 |
tabPaneControl.addTab("Tasks", panelTaskManager);
|
288 |
panelControl.add(tabPaneControl); |
289 |
|
290 |
// Set up elements in the south
|
291 |
panelSouth = new JPanel(); |
292 |
panelSouth.setLayout(new GridLayout(1,2)); |
293 |
//panelSouth.add(spLog);
|
294 |
|
295 |
// Put all elements in the ContentPane
|
296 |
this.getContentPane().setLayout(new BorderLayout()); |
297 |
this.getContentPane().add(tabPaneMain, BorderLayout.CENTER); |
298 |
this.getContentPane().add(panelSouth, BorderLayout.SOUTH); |
299 |
this.getContentPane().add(panelControl, BorderLayout.EAST); |
300 |
this.setVisible(true); |
301 |
|
302 |
/* Add all listeners here */
|
303 |
// Task Management
|
304 |
btnAddTask.addActionListener(this);
|
305 |
btnRemoveTask.addActionListener(this);
|
306 |
btnMoveTaskUp.addActionListener(this);
|
307 |
btnMoveTaskDown.addActionListener(this);
|
308 |
btnUpdateTasks.addActionListener(this);
|
309 |
// Robot Control
|
310 |
btnF.addActionListener(this);
|
311 |
btnB.addActionListener(this);
|
312 |
btnL.addActionListener(this);
|
313 |
btnR.addActionListener(this);
|
314 |
btnF.addKeyListener(this);
|
315 |
btnB.addKeyListener(this);
|
316 |
btnL.addKeyListener(this);
|
317 |
btnR.addKeyListener(this);
|
318 |
btnActivate.addActionListener(this);
|
319 |
btnActivate.addKeyListener(this);
|
320 |
cmbRobotNum.addKeyListener(this);
|
321 |
vectorController.addMouseMotionListener(this);
|
322 |
vectorController.addMouseListener(this);
|
323 |
btnCommand_StopTask.addActionListener(this);
|
324 |
btnCommand_ResumeTask.addActionListener(this);
|
325 |
btnCommand_ChargeNow.addActionListener(this);
|
326 |
btnCommand_StopCharging.addActionListener(this);
|
327 |
// Other
|
328 |
btnGraph.addActionListener(this);
|
329 |
btnConnect.addActionListener(this);
|
330 |
panelGraph.addMouseListener(this);
|
331 |
this.addMouseMotionListener(this); |
332 |
|
333 |
|
334 |
// Set up dependent threads
|
335 |
indicator = new SelectionIndicator(canvas);
|
336 |
indicator.setRadius(RADIUS+3, 15); //a tad more than the bot radius |
337 |
simulator = new Simulator();
|
338 |
webcamLoader = new WebcamLoader(this); |
339 |
dataUpdater = new DataUpdater();
|
340 |
csi = new ColonetServerInterface(this); |
341 |
|
342 |
} |
343 |
|
344 |
public synchronized void paint (Graphics g) { |
345 |
/* Redraw the graphical components in the applet.
|
346 |
This paint method overrides the built-in paint of the
|
347 |
JApplet, and we don't want to deal with redrawing the
|
348 |
components manually. Fuck that shit. */
|
349 |
step(); |
350 |
super.paint(g);
|
351 |
} |
352 |
|
353 |
public synchronized void update (Graphics g) { |
354 |
paint(g); |
355 |
} |
356 |
|
357 |
public void drawRobot (int id, int x, int y) { |
358 |
//save the bot in memory, so we can tell if we click on it later
|
359 |
botRect[id] = new Rectangle(x-RADIUS, y-RADIUS, 2*RADIUS, 2*RADIUS); |
360 |
|
361 |
//draw the bot on the canvas
|
362 |
canvas.setColor(Color.BLACK);
|
363 |
canvas.drawOval(x-RADIUS, y-RADIUS, RADIUS*2, RADIUS*2); |
364 |
|
365 |
//draw the label
|
366 |
canvas.setFont(botFont); |
367 |
try {
|
368 |
canvas.drawString("" + xbeeID[id], x-20, y+2); |
369 |
} catch (Exception e) { |
370 |
canvas.drawString("???", x-22, y+2); |
371 |
} |
372 |
} |
373 |
|
374 |
public void drawConnection (int start, int end, int radius, Color color) { |
375 |
final int ARROW_LENGTH = 18; |
376 |
|
377 |
double angle = 2.0 * Math.PI / numBots; |
378 |
int startx, starty, endx, endy;
|
379 |
startx = cx - (int)(radius * Math.cos(start * angle)); |
380 |
starty = cy - (int)(radius * Math.sin(start * angle)); |
381 |
endx = cx - (int)(radius * Math.cos(end * angle)); |
382 |
endy = cy - (int)(radius * Math.sin(end * angle)); |
383 |
canvas.setColor(color); |
384 |
canvas.drawLine(startx, starty, endx, endy); |
385 |
|
386 |
//create arrow
|
387 |
if (color.equals(Color.BLACK)) return; |
388 |
int big_dy = starty - endy;
|
389 |
int big_dx = endx - startx;
|
390 |
double theta = 0; |
391 |
if (big_dx == 0 && starty > endy) //pointing up |
392 |
theta = Math.PI/2; |
393 |
else if (big_dx == 0 && starty < endy) //pointing down |
394 |
theta = 3*Math.PI/2; |
395 |
else if (big_dy == 0 && startx > endx) //pointing left |
396 |
theta = Math.PI;
|
397 |
else if (big_dy == 0 && startx < endx) //pointing right |
398 |
theta = 0;
|
399 |
else
|
400 |
theta = Math.atan(1.0 * big_dy / big_dx); |
401 |
|
402 |
//create ploygon
|
403 |
Polygon poly = new Polygon(); |
404 |
int dx_arrow = Math.abs((int)(ARROW_LENGTH * Math.cos(theta))); |
405 |
int dy_arrow = Math.abs((int)(ARROW_LENGTH * Math.sin(theta))); |
406 |
int dy_half = (int)(ARROW_LENGTH/2 * Math.cos(theta)); |
407 |
int dx_half = (int)(ARROW_LENGTH/2 * Math.sin(theta)); |
408 |
int rx = (big_dx > 0) ? endx - dx_arrow : endx + dx_arrow; |
409 |
int ry = (big_dy > 0) ? endy + dy_arrow : endy - dy_arrow; |
410 |
poly.addPoint(endx, endy); |
411 |
poly.addPoint(rx - dx_half, ry - dy_half); |
412 |
poly.addPoint(rx + dx_half, ry + dy_half); |
413 |
canvas.fillPolygon(poly); |
414 |
} |
415 |
|
416 |
public void run () { |
417 |
while (true) { |
418 |
repaint(); |
419 |
try {
|
420 |
Thread.sleep(90); |
421 |
} catch (InterruptedException e) { |
422 |
return;
|
423 |
} |
424 |
} |
425 |
} |
426 |
|
427 |
private void step () { |
428 |
final int DIAMETER = image.getWidth() - 2*BUFFER; |
429 |
final int BIGRADIUS = DIAMETER / 2; |
430 |
final int TOKENRADIUS = 40; |
431 |
boolean valid;
|
432 |
|
433 |
// clear image
|
434 |
canvas.setColor(Color.WHITE);
|
435 |
canvas.fillRect(0, 0, image.getWidth(), image.getHeight()); |
436 |
|
437 |
// parse the matrix, to see what robots exist
|
438 |
String [] rows = txtMatrix.getText().split("\n"); |
439 |
numBots = rows.length; |
440 |
String [][] entries = new String[numBots][numBots]; |
441 |
valid = true;
|
442 |
for (int i = 0; i < numBots; i++) { |
443 |
entries[i] = rows[i].split(" ");
|
444 |
if (entries[i].length != rows.length) valid = false; |
445 |
} |
446 |
|
447 |
if (valid) {
|
448 |
this.showStatus("Running"); |
449 |
|
450 |
// draw robots and find which one is seleced
|
451 |
double angle = 2.0 * Math.PI / numBots; |
452 |
canvas.setColor(Color.BLACK);
|
453 |
botRect = new Rectangle[numBots]; |
454 |
int x, y;
|
455 |
if (selectedBot >= numBots) selectedBot = 0; |
456 |
for (int i = 0; i < numBots; i++) { |
457 |
x = cx - (int)(BIGRADIUS * Math.cos(i * angle)); |
458 |
y = cy - (int)(BIGRADIUS * Math.sin(i * angle)); |
459 |
drawRobot(i, x, y); |
460 |
if (i == selectedBot) indicator.setCenter(x, y);
|
461 |
} |
462 |
|
463 |
// draw token marker
|
464 |
int tokenx, tokeny;
|
465 |
int tokenNum = tokenLoc;
|
466 |
tokenx = cx - (int)(BIGRADIUS * Math.cos(tokenNum * angle)); |
467 |
tokeny = cy - (int)(BIGRADIUS * Math.sin(tokenNum * angle)); |
468 |
canvas.setColor(Color.RED);
|
469 |
canvas.drawOval(tokenx-TOKENRADIUS, tokeny-TOKENRADIUS, 2*TOKENRADIUS, 2*TOKENRADIUS); |
470 |
|
471 |
// create an inner circle along which the connections are made.
|
472 |
// let the diameter of this circle be 2*RADIUS less than the outerDiameter.
|
473 |
// see what connections exist
|
474 |
for (int row = 0; row < numBots; row++) { |
475 |
for(int col = 0; col < numBots; col++) { |
476 |
if (!entries[row][col].equals("-") && entries[col][row].equals("-") && row != col) { |
477 |
//TODO: Make a standard gray
|
478 |
drawConnection(row, col, BIGRADIUS-RADIUS, new Color(200,200,200)); |
479 |
} else if (!entries[row][col].equals("-") && ! entries[col][row].equals("-") && row != col) { |
480 |
drawConnection(row, col, BIGRADIUS-RADIUS, Color.BLACK);
|
481 |
} |
482 |
} |
483 |
} |
484 |
|
485 |
// draw the selection indicator
|
486 |
indicator.draw(); |
487 |
|
488 |
} else { // if matrix is not valid |
489 |
this.showStatus("Error: Invalid matrix"); |
490 |
} |
491 |
|
492 |
} |
493 |
|
494 |
/**
|
495 |
* Gets the JTextArea used for storing the activity log. This method returns a reference to the
|
496 |
* JTextArea that stores the log. The log can contain any activity that is revelant to the use
|
497 |
* of the applet, and may optionally display debugging information.
|
498 |
*
|
499 |
* @return the JTextArea where BOM matrix information is stored.
|
500 |
*/
|
501 |
public JTextArea getLog () { |
502 |
return log;
|
503 |
} |
504 |
|
505 |
/**
|
506 |
* Gets the JTextArea used for storing the BOM matrix data. This method returns a reference to the
|
507 |
* JTextArea that stores the BOM matrix. The values in the matrix are stored as integers separated
|
508 |
* by spaces, and the lines should be separated by a newline.
|
509 |
*
|
510 |
* @return the JTextArea where BOM matrix information is stored.
|
511 |
*/
|
512 |
public JTextArea getMatrixInput () { |
513 |
return txtMatrix;
|
514 |
} |
515 |
|
516 |
/**
|
517 |
* Parses a String containing BOM matrix information.
|
518 |
* The ColonetServerInterface receives lines of the BOM matrix. (For encoding
|
519 |
* information, see the ColonetServerInterface documentation.) The entire matrix is passed
|
520 |
* to the client when requested. This method takes a string of the form
|
521 |
* "[command code] [command code] [number of robots] [data0] [data1] ..."
|
522 |
* with tokens separated by spaces and containing no brackets.
|
523 |
* The [command code]s are predefined values identifying this String as a BOM data
|
524 |
* String, [number of robots] is an integer, and the values that follow are
|
525 |
* the sensor readings of the robots in order, starting with robot 0. Only [number of robots]^2
|
526 |
* data entries will be read. The matrix values are saved locally until the next String is parsed.
|
527 |
*
|
528 |
*
|
529 |
* @param line the String containing BOM matrix information.
|
530 |
* @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots]^2 data entries in the String
|
531 |
*/
|
532 |
public void parseMatrix (String line) { |
533 |
txtMatrix.setText("");
|
534 |
String [] str = line.split(" "); |
535 |
int num = Integer.parseInt(str[2]); |
536 |
for (int i = 0; i < num; i++) { |
537 |
for (int j = 0; j < num; j++) { |
538 |
String next = str[3 + i*num + j]; |
539 |
if (next.equals("-1")) |
540 |
txtMatrix.append("-");
|
541 |
else
|
542 |
txtMatrix.append(next); |
543 |
if (j < num - 1) |
544 |
txtMatrix.append(" ");
|
545 |
} |
546 |
if (i < num - 1) |
547 |
txtMatrix.append("\n");
|
548 |
} |
549 |
|
550 |
} |
551 |
|
552 |
/**
|
553 |
* Parses a String containing a task queue update.
|
554 |
* Format is currently not specified.
|
555 |
* This method currently does nothing.
|
556 |
*
|
557 |
* @param line the String containing task queue update information.
|
558 |
*/
|
559 |
public void parseQueue (String line) { |
560 |
log.append("Got queue update\n");
|
561 |
//TODO: display new queue data in tasks tab
|
562 |
} |
563 |
|
564 |
/**
|
565 |
* Parses a String containing XBee ID values.
|
566 |
* The ColonetServerInterface receives Strings of XBee information. (For encoding
|
567 |
* information, see the ColonetServerInterface documentation.) This method takes
|
568 |
* a string of the form "[command code] [command code] [number of robots] [id0] [id1] ..."
|
569 |
* with tokens separated by spaces and containing no brackets.
|
570 |
* The [command code]s are predefined values identifying this String as an XBee
|
571 |
* ID String, [number of robots] is an integer, and the values that follow are
|
572 |
* the IDs of the robots in order, starting with robot 0. Only [number of robots]
|
573 |
* will be read. The ID values are saved locally until the next String is parsed.
|
574 |
* The purpose of having this list is to ensure that robots are properly identified for control purposes.
|
575 |
* This keeps robot identification consistent between sessions and prevents arbitrary assignment.
|
576 |
*
|
577 |
* @param line the String containing XBee ID information.
|
578 |
* @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots] IDs in the String
|
579 |
* @see ColonetServerInterface#sendXBeeIDRequest()
|
580 |
*/
|
581 |
public void parseXBeeIDs (String line) { |
582 |
//TODO: check if this string actually has xbee command codes
|
583 |
|
584 |
String [] str = line.split(" "); |
585 |
int num = Integer.parseInt(str[2]); |
586 |
xbeeID = new int[num]; |
587 |
for (int i = 0; i < num; i++) |
588 |
xbeeID[i] = Integer.parseInt(str[i+3]); |
589 |
|
590 |
//update the list of robots to control
|
591 |
//but save the old value first
|
592 |
Object oldSelection = cmbRobotNum.getSelectedItem();
|
593 |
cmbRobotNum.removeAllItems(); |
594 |
cmbRobotNum.addItem(new String(" All ")); |
595 |
for (int i = 0; i < num; i++) |
596 |
cmbRobotNum.addItem(new String("" + xbeeID[i])); |
597 |
cmbRobotNum.setSelectedItem(oldSelection); |
598 |
} |
599 |
|
600 |
/**
|
601 |
* Parses a String containing battery information.
|
602 |
* The ColonetServerInterface receives Strings of battery information. (For encoding
|
603 |
* information, see the ColonetServerInterface documentation.) This method takes
|
604 |
* a string of the form "[command code] [command code] [robot ID] [value]"
|
605 |
* with tokens separated by spaces and containing no brackets.
|
606 |
* The [command code]s are predefined values identifying this String as a battery
|
607 |
* information String, [robot ID] is an integer, and [value] is a battery measurement.
|
608 |
* This updates the batery information for a single robot.
|
609 |
*
|
610 |
*
|
611 |
* @param line the String containing battery information.
|
612 |
* @see ColonetServerInterface#sendBatteryRequest(int)
|
613 |
*/
|
614 |
public void parseBattery (String line) { |
615 |
System.out.println("Got battery update: " + line); |
616 |
String [] str = line.split(" "); |
617 |
int botNum = (int) line.charAt(4); |
618 |
int batteryVal = (int) line.charAt(6); |
619 |
if (cmbRobotNum != null && cmbRobotNum.getSelectedIndex()-1 == botNum) { |
620 |
//TODO: update battery info graphically
|
621 |
} |
622 |
// For now, just update the bar whenever we get an update.
|
623 |
batteryIcon.setLevel((int) (100.0 * batteryVal / 255)); |
624 |
} |
625 |
|
626 |
//
|
627 |
// MouseListener methods
|
628 |
//
|
629 |
public void mouseExited(MouseEvent e) { |
630 |
} |
631 |
public void mouseEntered(MouseEvent e) { |
632 |
} |
633 |
public void mouseReleased(MouseEvent e) { |
634 |
vectorController.notifyMouseEvent(e, true);
|
635 |
} |
636 |
public void mouseClicked(MouseEvent e) { |
637 |
vectorController.notifyMouseEvent(e, false);
|
638 |
} |
639 |
public void mousePressed(MouseEvent e) { |
640 |
try {
|
641 |
for (int i = 0; i < numBots; i++) { |
642 |
if (botRect[i].contains(e.getPoint())) {
|
643 |
selectedBot = i; |
644 |
cmbRobotNum.setSelectedIndex(i+1);
|
645 |
} |
646 |
} |
647 |
} catch (Exception ex) { |
648 |
} |
649 |
} |
650 |
public void mouseDragged(MouseEvent e) { |
651 |
vectorController.notifyMouseEvent(e, false);
|
652 |
} |
653 |
public void mouseMoved(MouseEvent e) { |
654 |
} |
655 |
|
656 |
//
|
657 |
// KeyListener methods
|
658 |
//
|
659 |
public void keyPressed (KeyEvent e) { |
660 |
int code = e.getKeyCode();
|
661 |
if (code == KeyEvent.VK_UP) { |
662 |
vectorController.setMaxForward(); |
663 |
vectorController.sendToServer(); |
664 |
} else if (code == KeyEvent.VK_DOWN) { |
665 |
vectorController.setMaxReverse(); |
666 |
vectorController.sendToServer(); |
667 |
} else if (code == KeyEvent.VK_LEFT) { |
668 |
vectorController.setMaxLeft(); |
669 |
vectorController.sendToServer(); |
670 |
} else if (code == KeyEvent.VK_RIGHT) { |
671 |
vectorController.setMaxRight(); |
672 |
vectorController.sendToServer(); |
673 |
} else if (code == KeyEvent.VK_S) { |
674 |
vectorController.setZero(); |
675 |
vectorController.sendToServer(); |
676 |
} |
677 |
} |
678 |
public void keyReleased (KeyEvent e) { |
679 |
} |
680 |
public void keyTyped (KeyEvent e) { |
681 |
} |
682 |
|
683 |
|
684 |
//
|
685 |
// ActionListener method
|
686 |
//
|
687 |
public void actionPerformed (ActionEvent e) { |
688 |
Object source = e.getSource();
|
689 |
if (source == btnGraph) {
|
690 |
btnGraph.setEnabled(false);
|
691 |
//Start dependent threads
|
692 |
drawThread = new Thread(this, "drawThread"); |
693 |
drawThread.start(); |
694 |
indicator.start(); |
695 |
simulator.start(); |
696 |
webcamLoader.start(); |
697 |
} else if (source == btnConnect) { |
698 |
csi.connect(txtHost.getText(), txtPort.getText()); |
699 |
dataUpdater.start(); |
700 |
drawThread = new Thread(this, "drawThread"); |
701 |
drawThread.start(); |
702 |
indicator.start(); |
703 |
simulator.start(); |
704 |
webcamLoader.start(); |
705 |
} |
706 |
// Robot Movement Controls
|
707 |
else if (source == btnF) { |
708 |
vectorController.setMaxForward(); |
709 |
vectorController.sendToServer(); |
710 |
} else if (source == btnB) { |
711 |
vectorController.setMaxReverse(); |
712 |
vectorController.sendToServer(); |
713 |
} else if (source == btnL) { |
714 |
vectorController.setMaxLeft(); |
715 |
vectorController.sendToServer(); |
716 |
} else if (source == btnR) { |
717 |
vectorController.setMaxRight(); |
718 |
vectorController.sendToServer(); |
719 |
} else if (source == btnActivate) { |
720 |
vectorController.setZero(); |
721 |
vectorController.sendToServer(); |
722 |
} |
723 |
// Robot Commands (non-movement)
|
724 |
else if (source == btnCommand_StopTask) { |
725 |
|
726 |
} else if (source == btnCommand_ResumeTask) { |
727 |
|
728 |
} else if (source == btnCommand_ChargeNow) { |
729 |
|
730 |
} else if (source == btnCommand_StopCharging) { |
731 |
|
732 |
} |
733 |
|
734 |
// Queue Management
|
735 |
else if (source == btnAddTask) { |
736 |
taskAddWindow.prompt(); |
737 |
} else if (source == btnRemoveTask) { |
738 |
if (taskList.getSelectedIndex() >= 0); |
739 |
csi.sendQueueRemove(taskList.getSelectedIndex()); |
740 |
csi.sendQueueUpdate(); |
741 |
} else if (source == btnMoveTaskUp) { |
742 |
csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() - 1);
|
743 |
csi.sendQueueUpdate(); |
744 |
} else if (source == btnMoveTaskDown) { |
745 |
csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() + 1);
|
746 |
csi.sendQueueUpdate(); |
747 |
} else if (source == btnUpdateTasks) { |
748 |
csi.sendQueueUpdate(); |
749 |
} |
750 |
} |
751 |
|
752 |
/*
|
753 |
* SelectionIndicator thread.
|
754 |
* Graphical representation of the selection marker
|
755 |
*
|
756 |
* step() and draw() are synchronized methods. step() is private and
|
757 |
* used to update the position of the crosshairs. draw() is called
|
758 |
* externally and should only run if all calculations in step() have
|
759 |
* been completed.
|
760 |
*/
|
761 |
private class SelectionIndicator extends Thread { |
762 |
|
763 |
final int INDICATOR_DELAY = 180; |
764 |
final double DTHETA = 0.4; //larger values make the marker rotate faster |
765 |
Graphics2D g; //canvas to draw on |
766 |
boolean running;
|
767 |
|
768 |
int sx, sy; //center |
769 |
int r, dr; //radius and width of marker |
770 |
double theta; //current angle |
771 |
|
772 |
volatile Polygon poly1, poly2, poly3, poly4; |
773 |
|
774 |
int px1, py1;
|
775 |
int rx1, ry1;
|
776 |
int px2, py2;
|
777 |
int rx2, ry2;
|
778 |
int px3, py3;
|
779 |
int rx3, ry3;
|
780 |
int px4, py4;
|
781 |
int rx4, ry4;
|
782 |
|
783 |
int steps;
|
784 |
|
785 |
public SelectionIndicator (Graphics2D g) { |
786 |
super("SelectionIndicator"); |
787 |
this.g = g;
|
788 |
running = false;
|
789 |
steps = 0;
|
790 |
|
791 |
theta = 0;
|
792 |
rx1 = 0; ry1 = 0; |
793 |
px1 = 0; py1 = 0; |
794 |
rx2 = 0; ry2 = 0; |
795 |
px2 = 0; py2 = 0; |
796 |
rx3 = 0; ry3 = 0; |
797 |
px3 = 0; py3 = 0; |
798 |
rx4 = 0; ry4 = 0; |
799 |
px4 = 0; py4 = 0; |
800 |
} |
801 |
|
802 |
public synchronized void setCenter (int sx, int sy) { |
803 |
if (sx == this.sx && sy == this.sy) return; |
804 |
this.sx = sx;
|
805 |
this.sy = sy;
|
806 |
steps = 0;
|
807 |
} |
808 |
|
809 |
public synchronized void setRadius (int r, int dr) { |
810 |
this.r = r;
|
811 |
this.dr = dr;
|
812 |
steps = 0;
|
813 |
} |
814 |
|
815 |
public void run () { |
816 |
running = true;
|
817 |
while (running) {
|
818 |
step(); |
819 |
try {
|
820 |
Thread.sleep(INDICATOR_DELAY);
|
821 |
} catch (InterruptedException e) { |
822 |
running = false;
|
823 |
return;
|
824 |
} |
825 |
} |
826 |
} |
827 |
|
828 |
private synchronized void step () { |
829 |
Polygon poly1_new = new Polygon(); |
830 |
Polygon poly2_new = new Polygon(); |
831 |
Polygon poly3_new = new Polygon(); |
832 |
Polygon poly4_new = new Polygon(); |
833 |
|
834 |
//the step
|
835 |
theta = (theta + DTHETA/Math.PI) % (Math.PI); |
836 |
|
837 |
//the calculation
|
838 |
//let p be the point of the pointy thing toward the center
|
839 |
//let r be the point at the opposite side
|
840 |
|
841 |
//recalculate radius, if it will look cool, lolz
|
842 |
int newr = r;
|
843 |
if (steps < 100) |
844 |
newr = (int)( r + 200/(steps+1) ); |
845 |
|
846 |
//precompute values for dx and dy
|
847 |
int dx_inner = (int)(newr * Math.cos(theta)); |
848 |
int dy_inner = (int)(newr * Math.sin(theta)); |
849 |
int dx_outer = (int)((newr+dr) * Math.cos(theta)); |
850 |
int dy_outer = (int)((newr+dr) * Math.sin(theta)); |
851 |
|
852 |
//calculate polygon constants
|
853 |
int dy_poly = (int)(dr/2 * Math.cos(theta)); |
854 |
int dx_poly = (int)(dr/2 * Math.sin(theta)); |
855 |
|
856 |
//determine critical points
|
857 |
//kansas city shuffle!
|
858 |
px1 = sx + dx_inner; |
859 |
py1 = sy - dy_inner; |
860 |
rx1 = sx + dx_outer; |
861 |
ry1 = sy - dy_outer; |
862 |
px2 = sx - dx_inner; |
863 |
py2 = sy + dy_inner; |
864 |
rx2 = sx - dx_outer; |
865 |
ry2 = sy + dy_outer; |
866 |
px3 = sx - dy_inner; |
867 |
py3 = sy - dx_inner; |
868 |
rx3 = sx - dy_outer; |
869 |
ry3 = sy - dx_outer; |
870 |
px4 = sx + dy_inner; |
871 |
py4 = sy + dx_inner; |
872 |
rx4 = sx + dy_outer; |
873 |
ry4 = sy + dx_outer; |
874 |
|
875 |
//create polygons
|
876 |
poly1_new.addPoint(px1, py1); |
877 |
poly1_new.addPoint(rx1+dx_poly, ry1+dy_poly); |
878 |
poly1_new.addPoint(rx1-dx_poly, ry1-dy_poly); |
879 |
poly2_new.addPoint(px2, py2); |
880 |
poly2_new.addPoint(rx2+dx_poly, ry2+dy_poly); |
881 |
poly2_new.addPoint(rx2-dx_poly, ry2-dy_poly); |
882 |
poly3_new.addPoint(px3, py3); |
883 |
poly3_new.addPoint(rx3-dy_poly, ry3+dx_poly); |
884 |
poly3_new.addPoint(rx3+dy_poly, ry3-dx_poly); |
885 |
poly4_new.addPoint(px4, py4); |
886 |
poly4_new.addPoint(rx4-dy_poly, ry4+dx_poly); |
887 |
poly4_new.addPoint(rx4+dy_poly, ry4-dx_poly); |
888 |
|
889 |
//reassign updated polygons
|
890 |
poly1 = poly1_new; |
891 |
poly2 = poly2_new; |
892 |
poly3 = poly3_new; |
893 |
poly4 = poly4_new; |
894 |
|
895 |
if (steps < 300) steps++; |
896 |
} |
897 |
|
898 |
public synchronized void draw () { |
899 |
if (!running) return; |
900 |
g.setColor(Color.GRAY);
|
901 |
//draw polygons
|
902 |
g.fillPolygon(poly1); |
903 |
g.fillPolygon(poly2); |
904 |
g.fillPolygon(poly3); |
905 |
g.fillPolygon(poly4); |
906 |
} |
907 |
|
908 |
} |
909 |
|
910 |
/*
|
911 |
* Simulator thread.
|
912 |
*
|
913 |
*/
|
914 |
private class Simulator extends Thread { |
915 |
final int SIMULATOR_DELAY = 300; |
916 |
boolean running;
|
917 |
|
918 |
public Simulator () {
|
919 |
super("Simulator"); |
920 |
running = false;
|
921 |
} |
922 |
|
923 |
public void run () { |
924 |
running = true;
|
925 |
while (running) {
|
926 |
step(); |
927 |
try {
|
928 |
Thread.sleep(SIMULATOR_DELAY);
|
929 |
} catch (InterruptedException e) { |
930 |
running = false;
|
931 |
return;
|
932 |
} |
933 |
} |
934 |
} |
935 |
|
936 |
private void step () { |
937 |
// don't do anything! the colonet should work on its own!
|
938 |
} |
939 |
|
940 |
} |
941 |
|
942 |
/*
|
943 |
* DataUpdater thread.
|
944 |
* The purpose of this thread is to request data from the server at regular intervals.
|
945 |
*
|
946 |
*/
|
947 |
class DataUpdater extends Thread { |
948 |
final int DATAUPDATER_DELAY = 4000; |
949 |
|
950 |
public DataUpdater () {
|
951 |
super("Colonet DataUpdater"); |
952 |
} |
953 |
|
954 |
public void run () { |
955 |
String line;
|
956 |
while (true) { |
957 |
try {
|
958 |
//request more data
|
959 |
if (csi != null && csi.isReady()) { |
960 |
//csi.sendSensorDataRequest();
|
961 |
//csi.sendXBeeIDRequest();
|
962 |
if (cmbRobotNum.getSelectedIndex() > 0) |
963 |
csi.sendBatteryRequest(cmbRobotNum.getSelectedIndex()-1);
|
964 |
else
|
965 |
csi.sendBatteryRequest(200);
|
966 |
} |
967 |
Thread.sleep(DATAUPDATER_DELAY);
|
968 |
} catch (InterruptedException e) { |
969 |
return;
|
970 |
} |
971 |
} |
972 |
} |
973 |
|
974 |
} |
975 |
|
976 |
/*
|
977 |
* GraphicsPanel class
|
978 |
* An extension of JPanel, designed for holding an image that will be repainted regularly.
|
979 |
*/
|
980 |
class GraphicsPanel extends JPanel { |
981 |
protected Image img; |
982 |
|
983 |
public GraphicsPanel (Image img) { |
984 |
super();
|
985 |
this.img = img;
|
986 |
} |
987 |
|
988 |
public GraphicsPanel (Image img, boolean isDoubleBuffered) { |
989 |
super(isDoubleBuffered);
|
990 |
this.img = img;
|
991 |
} |
992 |
|
993 |
public void paint (Graphics g) { |
994 |
// Place the buffered image on the screen, inside the panel
|
995 |
g.drawImage(img, 0, 0, Color.WHITE, this); |
996 |
} |
997 |
|
998 |
} |
999 |
|
1000 |
/*
|
1001 |
* WebcamPanel class
|
1002 |
* Enables more efficient image handling in a component-controlled environment
|
1003 |
*/
|
1004 |
class WebcamPanel extends JPanel { |
1005 |
int BORDER = 16; // this is arbitrary. it makes the image look nice inside a border. |
1006 |
int BOT_RADIUS = 40; |
1007 |
volatile BufferedImage img; |
1008 |
volatile Point [] points; |
1009 |
|
1010 |
public WebcamPanel () {
|
1011 |
super();
|
1012 |
} |
1013 |
|
1014 |
public synchronized void setImage (BufferedImage newimg) { |
1015 |
if (img != null) { |
1016 |
img.flush(); |
1017 |
img = null;
|
1018 |
img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); |
1019 |
} |
1020 |
System.gc();
|
1021 |
img = newimg; |
1022 |
} |
1023 |
|
1024 |
public synchronized void setPoints (Point [] newpoints) { |
1025 |
this.points = newpoints;
|
1026 |
} |
1027 |
|
1028 |
public synchronized void paint (Graphics g) { |
1029 |
|
1030 |
if (img == null) |
1031 |
return;
|
1032 |
// Place the image on the screen, inside the panel
|
1033 |
g.drawImage(img, |
1034 |
BORDER, //dx1 - the x coordinate of the first corner of the destination rectangle.
|
1035 |
BORDER, //dy1 - the y coordinate of the first corner of the destination rectangle.
|
1036 |
this.getWidth() - BORDER, //dx2 - the x coordinate of the second corner of the destination rectangle. |
1037 |
this.getHeight() - BORDER, //dy2 - the y coordinate of the second corner of the destination rectangle. |
1038 |
0, //sx1 - the x coordinate of the first corner of the source rectangle. |
1039 |
0, //sy1 - the y coordinate of the first corner of the source rectangle. |
1040 |
image.getWidth(), //sx2 - the x coordinate of the second corner of the source rectangle.
|
1041 |
image.getHeight(), //sy2 - the y coordinate of the second corner of the source rectangle.
|
1042 |
null //observer - object to be notified as more of the image is scaled and converted. |
1043 |
); |
1044 |
|
1045 |
// Draw Identifiers
|
1046 |
if (points == null) |
1047 |
return;
|
1048 |
g.setColor(Color.RED);
|
1049 |
((Graphics2D)g).setStroke(new BasicStroke(2)); |
1050 |
for (int i = 0; i < points.length; i++) { |
1051 |
g.drawOval(points[i].x - BOT_RADIUS, points[i].y - BOT_RADIUS, 2*BOT_RADIUS, 2*BOT_RADIUS); |
1052 |
} |
1053 |
|
1054 |
} |
1055 |
|
1056 |
} |
1057 |
|
1058 |
/*
|
1059 |
* WebcamLoader class
|
1060 |
* Handles the loading of the webcam image.
|
1061 |
*/
|
1062 |
class WebcamLoader extends Thread |
1063 |
{ |
1064 |
final int WEBCAMLOADER_DELAY = 1000; |
1065 |
final String IMAGE_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet.jpg"; |
1066 |
final String LOCATIONS_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet/locations.txt"; |
1067 |
|
1068 |
URL imagePath;
|
1069 |
URI locationsPath;
|
1070 |
|
1071 |
MediaTracker mt;
|
1072 |
BufferedImage image;
|
1073 |
|
1074 |
public WebcamLoader (JApplet applet) |
1075 |
{ |
1076 |
super("ColonetWebcamLoader"); |
1077 |
mt = new MediaTracker(applet); |
1078 |
ImageIO.setUseCache(false); |
1079 |
try {
|
1080 |
imagePath = new URL(IMAGE_PATH); |
1081 |
} catch (MalformedURLException e) { |
1082 |
System.out.println("Malformed URL: could not form URL from: [" + IMAGE_PATH + "]\n"); |
1083 |
} |
1084 |
try {
|
1085 |
locationsPath = new URI(LOCATIONS_PATH); |
1086 |
} catch (URISyntaxException x) { |
1087 |
System.out.println("Malformed URI: could not form URI from: [" + LOCATIONS_PATH + "]\n"); |
1088 |
} |
1089 |
|
1090 |
} |
1091 |
|
1092 |
public synchronized void run () |
1093 |
{ |
1094 |
while (true) { |
1095 |
try {
|
1096 |
Thread.sleep(WEBCAMLOADER_DELAY);
|
1097 |
if (image != null) |
1098 |
image.flush(); |
1099 |
System.gc();
|
1100 |
image = ImageIO.read(imagePath);
|
1101 |
// The MediaTracker waitForID pauses the thread until the image is loaded.
|
1102 |
// We don't want to display a half-downloaded image.
|
1103 |
mt.addImage(image, 1);
|
1104 |
mt.waitForID(1);
|
1105 |
mt.removeImage(image); |
1106 |
// Save
|
1107 |
panelWebcam.setImage(image); |
1108 |
parseLocations(locationsPath.toURL()); |
1109 |
} catch (InterruptedException e) { |
1110 |
return;
|
1111 |
} catch (java.security.AccessControlException e) {
|
1112 |
csi.warn("Could not load webcam.\n" + e);
|
1113 |
return;
|
1114 |
} catch (IOException e) { |
1115 |
log.append("IOException while trying to load image.");
|
1116 |
} |
1117 |
} |
1118 |
} |
1119 |
|
1120 |
private void parseLocations (URL url) { |
1121 |
URLConnection conn = null; |
1122 |
DataInputStream data = null; |
1123 |
String line;
|
1124 |
String [] lines = new String[30]; |
1125 |
StringBuffer buf = new StringBuffer(); |
1126 |
int i = 0; |
1127 |
|
1128 |
try {
|
1129 |
conn = url.openConnection(); |
1130 |
conn.connect(); |
1131 |
data = new DataInputStream(new BufferedInputStream(conn.getInputStream())); |
1132 |
while ((line = data.readLine()) != null) { |
1133 |
buf.append(line + ";");
|
1134 |
lines[i] = line; |
1135 |
i++; |
1136 |
} |
1137 |
data.close(); |
1138 |
} catch (IOException e) { |
1139 |
System.out.println("IOException:" + e.getMessage()); |
1140 |
} |
1141 |
//log.append("Got robot locations: " + buf + "\n");
|
1142 |
|
1143 |
// Get Point values from strings
|
1144 |
Point [] points = new Point[i]; |
1145 |
for (int j = 0; j < i; j++) { |
1146 |
String [] parts = lines[j].split(","); |
1147 |
int xval = Integer.parseInt(parts[0]); |
1148 |
int yval = Integer.parseInt(parts[1]); |
1149 |
Point p = new Point(xval, yval); |
1150 |
points[j] = p; |
1151 |
} |
1152 |
if (points.length != 0) |
1153 |
panelWebcam.setPoints(points); |
1154 |
|
1155 |
} |
1156 |
} |
1157 |
|
1158 |
|
1159 |
/*
|
1160 |
* VectorController class
|
1161 |
* Manages robot motion control graphically
|
1162 |
*/
|
1163 |
class VectorController extends GraphicsPanel { |
1164 |
int x, y, cx, cy;
|
1165 |
int width, height;
|
1166 |
int side;
|
1167 |
|
1168 |
public VectorController (Image img) { |
1169 |
super (img);
|
1170 |
width = img.getWidth(null);
|
1171 |
height = img.getHeight(null);
|
1172 |
cx = img.getWidth(null)/2; |
1173 |
cy = img.getHeight(null)/2; |
1174 |
x = cx; |
1175 |
y = cy; |
1176 |
if (width < height)
|
1177 |
side = width; |
1178 |
else
|
1179 |
side = height; |
1180 |
} |
1181 |
|
1182 |
public void setPoint (int x, int y) { |
1183 |
if (!isValidPoint(x, y))
|
1184 |
return;
|
1185 |
this.x = x;
|
1186 |
this.y = y;
|
1187 |
repaint(); |
1188 |
} |
1189 |
|
1190 |
public boolean isValidPoint (int x, int y) { |
1191 |
double xterm = Math.pow(1.0*(x - cx)/(side/2), 2); |
1192 |
double yterm = Math.pow(1.0*(y - cy)/(side/2), 2); |
1193 |
return (xterm + yterm <= 1); |
1194 |
} |
1195 |
|
1196 |
public void notifyMouseEvent (MouseEvent e, boolean send) { |
1197 |
if (!isValidPoint(e.getX(), e.getY()))
|
1198 |
return;
|
1199 |
vectorController.setPoint(e.getX(), e.getY()); |
1200 |
vectorController.repaint(); |
1201 |
if (send)
|
1202 |
vectorController.sendToServer(); |
1203 |
} |
1204 |
|
1205 |
public int getSpeed () { |
1206 |
int dx = x - cx;
|
1207 |
int dy = y - cy;
|
1208 |
int v = (int) Math.sqrt( Math.pow(dx, 2) + Math.pow(dy, 2) ); |
1209 |
return v;
|
1210 |
} |
1211 |
|
1212 |
/**
|
1213 |
* Returns the angle of the control vector in positive degrees west of north,
|
1214 |
* or negative degrees east of north, whichever is less than or equal to
|
1215 |
* 180 degrees total.
|
1216 |
*/
|
1217 |
public int getAngle () { |
1218 |
int dx = x - cx;
|
1219 |
int dy = cy - y;
|
1220 |
// find reference angle in radians
|
1221 |
double theta = Math.atan2(Math.abs(dx), Math.abs(dy)); |
1222 |
// transform to degrees
|
1223 |
theta = theta * 180 / Math.PI; |
1224 |
// adjust for quadrant
|
1225 |
if (dx < 0 && dy < 0) |
1226 |
theta = 90 + theta;
|
1227 |
else if (dx < 0 && dy >= 0) |
1228 |
theta = 90 - theta;
|
1229 |
else if (dx >= 0 && dy < 0) |
1230 |
theta = -90 - theta;
|
1231 |
else
|
1232 |
theta = -90 + theta;
|
1233 |
return (int) theta; |
1234 |
} |
1235 |
|
1236 |
public void paint (Graphics g) { |
1237 |
g.setColor(Color.BLACK);
|
1238 |
g.fillRect(0, 0, width, height); |
1239 |
((Graphics2D)g).setStroke(new BasicStroke(1)); |
1240 |
g.setColor(Color.RED);
|
1241 |
g.drawOval(cx-side/2, cy-side/2, side, side); |
1242 |
((Graphics2D)g).setStroke(new BasicStroke(2)); |
1243 |
g.setColor(Color.GREEN);
|
1244 |
g.drawLine(cx, cy, x, y); |
1245 |
g.fillOval(x-3, y-3, 6, 6); |
1246 |
} |
1247 |
|
1248 |
public void setMaxForward () { |
1249 |
setPoint(cx, cy - (side/2) + 1); |
1250 |
} |
1251 |
|
1252 |
public void setMaxReverse () { |
1253 |
setPoint(cx, cy + (side/2) - 1); |
1254 |
} |
1255 |
|
1256 |
public void setMaxLeft () { |
1257 |
setPoint(cx - (side/2) + 1, cy); |
1258 |
} |
1259 |
|
1260 |
public void setMaxRight () { |
1261 |
setPoint(cx + (side/2) - 1, cy); |
1262 |
} |
1263 |
|
1264 |
public void setZero () { |
1265 |
setPoint(cx, cy); |
1266 |
} |
1267 |
|
1268 |
public void sendToServer () { |
1269 |
System.out.println("Attempting to send angle = " + getAngle() + ", speed = " + getSpeed() + ""); |
1270 |
String dest = ColonetServerInterface.GLOBAL_DEST;
|
1271 |
if (cmbRobotNum != null && cmbRobotNum.getSelectedIndex() > 0) |
1272 |
dest = "" + (cmbRobotNum.getSelectedIndex()-1); |
1273 |
|
1274 |
if (csi != null) { |
1275 |
if (cx == 0 && cy == 0) { |
1276 |
csi.sendData(ColonetServerInterface.MOTORS_OFF, dest); |
1277 |
} else {
|
1278 |
csi.sendData(ColonetServerInterface.MOVE + " " + getSpeed() + " " + getAngle(), dest); |
1279 |
/*
|
1280 |
//Directional commands
|
1281 |
if (x > cx && y == cy) { //move right
|
1282 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 200", dest);
|
1283 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 200", dest);
|
1284 |
} else if (x < cx && y == cy) { //move left
|
1285 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 200", dest);
|
1286 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 200", dest);
|
1287 |
} else if (x == cx && y > cy) { //move forward
|
1288 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 225", dest);
|
1289 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 225", dest);
|
1290 |
} else if (x == cx && y < cy) { //move backward
|
1291 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 225", dest);
|
1292 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 225", dest);
|
1293 |
} else if (x == cx && y == cy) { //stop!
|
1294 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 0", dest);
|
1295 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 0", dest);
|
1296 |
}
|
1297 |
*/
|
1298 |
} |
1299 |
} |
1300 |
} |
1301 |
|
1302 |
} |
1303 |
|
1304 |
/*
|
1305 |
* TaskAddWindow class
|
1306 |
* A window that provides a simple way to add tasks to a task queue.
|
1307 |
*/
|
1308 |
class TaskAddWindow extends JFrame implements ActionListener, ListSelectionListener { |
1309 |
JPanel panelButtons;
|
1310 |
JPanel panelParameters;
|
1311 |
JPanel panelSouth;
|
1312 |
JPanel panelSelection;
|
1313 |
JButton btnSubmit;
|
1314 |
JButton btnCancel;
|
1315 |
DefaultListModel availableListModel;
|
1316 |
JList availableList;
|
1317 |
JScrollPane spAvailableTasks;
|
1318 |
JTextArea txtDescription;
|
1319 |
JTextField txtParameters;
|
1320 |
MouseListener mouseListener;
|
1321 |
|
1322 |
public TaskAddWindow () {
|
1323 |
super("Add a Task"); |
1324 |
super.setSize(500,500); |
1325 |
super.setLayout(new BorderLayout()); |
1326 |
|
1327 |
// set up buttons
|
1328 |
btnSubmit = new JButton("Submit"); |
1329 |
btnCancel = new JButton("Cancel"); |
1330 |
panelButtons = new JPanel(); |
1331 |
panelButtons.setLayout(new FlowLayout()); |
1332 |
panelButtons.add(btnSubmit); |
1333 |
panelButtons.add(btnCancel); |
1334 |
this.getRootPane().setDefaultButton(btnSubmit);
|
1335 |
|
1336 |
// set up task list
|
1337 |
availableListModel = new DefaultListModel(); |
1338 |
availableListModel.addElement("Map the Environment");
|
1339 |
availableListModel.addElement("Clean Up Chemical Spill");
|
1340 |
availableListModel.addElement("Grow Plants");
|
1341 |
availableListModel.addElement("Save the Cheerleader");
|
1342 |
availableListModel.addElement("Save the World");
|
1343 |
availableList = new JList(availableListModel); |
1344 |
availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
|
1345 |
availableList.setSelectedIndex(-1);
|
1346 |
spAvailableTasks = new JScrollPane(availableList); |
1347 |
spAvailableTasks.setBorder(BorderFactory.createTitledBorder("Select A Task")); |
1348 |
txtDescription = new JTextArea(); |
1349 |
txtDescription.setEditable(false);
|
1350 |
txtDescription.setLineWrap(true);
|
1351 |
txtDescription.setWrapStyleWord(true);
|
1352 |
txtDescription.setBorder(BorderFactory.createTitledBorder("Description")); |
1353 |
|
1354 |
//set up parameter area
|
1355 |
panelParameters = new JPanel(); |
1356 |
panelParameters.setLayout(new BorderLayout()); |
1357 |
txtParameters = new JTextField(); |
1358 |
panelParameters.add(new JLabel("Optional parameters for this task: "), BorderLayout.WEST); |
1359 |
panelParameters.add(txtParameters); |
1360 |
|
1361 |
// assemble objects
|
1362 |
panelSelection = new JPanel(); |
1363 |
panelSelection.setLayout(new GridLayout(1,2)); |
1364 |
panelSelection.add(spAvailableTasks); |
1365 |
panelSelection.add(txtDescription); |
1366 |
|
1367 |
panelSouth = new JPanel(); |
1368 |
panelSouth.setLayout(new GridLayout(2,1)); |
1369 |
panelSouth.add(panelParameters); |
1370 |
panelSouth.add(panelButtons); |
1371 |
|
1372 |
this.getContentPane().add(panelSouth, BorderLayout.SOUTH); |
1373 |
this.getContentPane().add(panelSelection, BorderLayout.CENTER); |
1374 |
this.setLocationRelativeTo(null); |
1375 |
|
1376 |
// add listeners here
|
1377 |
availableList.addListSelectionListener(this);
|
1378 |
btnSubmit.addActionListener(this);
|
1379 |
btnCancel.addActionListener(this);
|
1380 |
} |
1381 |
|
1382 |
public void prompt () { |
1383 |
this.setVisible(true); |
1384 |
} |
1385 |
|
1386 |
private String getDescription (int index) { |
1387 |
if (index < 0) |
1388 |
return ""; |
1389 |
switch (index) {
|
1390 |
case 0: return "SLAM and junk"; |
1391 |
case 1: return "I'm not sure this works"; |
1392 |
case 2: return "Push them into the light"; |
1393 |
case 3: return "..."; |
1394 |
case 4: return "..."; |
1395 |
|
1396 |
default: return "Task not recognized"; |
1397 |
} |
1398 |
} |
1399 |
|
1400 |
public void actionPerformed (ActionEvent e) { |
1401 |
Object source = e.getSource();
|
1402 |
if (source == btnSubmit) {
|
1403 |
txtParameters.setText(txtParameters.getText().trim()); |
1404 |
|
1405 |
|
1406 |
this.setVisible(false); |
1407 |
} else if (source == btnCancel) { |
1408 |
this.setVisible(false); |
1409 |
} |
1410 |
} |
1411 |
|
1412 |
public void valueChanged (ListSelectionEvent e) { |
1413 |
int index = availableList.getSelectedIndex();
|
1414 |
if (index >= 0) |
1415 |
txtDescription.setText(getDescription(index)); |
1416 |
} |
1417 |
|
1418 |
} |
1419 |
|
1420 |
class BatteryIcon implements Icon { |
1421 |
private int width; |
1422 |
private int height; |
1423 |
private int level; |
1424 |
|
1425 |
/**
|
1426 |
* Constructs a new BatteryIcon with all default parameters.
|
1427 |
* Default width and height are 50.
|
1428 |
* Default level is 100.
|
1429 |
*/
|
1430 |
public BatteryIcon(){
|
1431 |
this(100, 50, 50); |
1432 |
} |
1433 |
|
1434 |
/**
|
1435 |
* Constructs a new BatteryIcon with default width and height, and with the specified level.
|
1436 |
* Default width and height are 50.
|
1437 |
*/
|
1438 |
public BatteryIcon(int startLevel){ |
1439 |
this(startLevel, 50, 50); |
1440 |
} |
1441 |
|
1442 |
/**
|
1443 |
* Constructs a new BatteryIcon with the specified level, width, and height.
|
1444 |
*/
|
1445 |
public BatteryIcon(int startLevel, int w, int h){ |
1446 |
level = startLevel; |
1447 |
width = w; |
1448 |
height = h; |
1449 |
} |
1450 |
|
1451 |
public void paintIcon(Component c, Graphics g, int x, int y) { |
1452 |
Graphics2D g2d = (Graphics2D) g.create(); |
1453 |
//clear the background
|
1454 |
g2d.setColor(Color.WHITE);
|
1455 |
g2d.fillRect(x + 1, y + 1, width - 2, height - 2); |
1456 |
//outline
|
1457 |
g2d.setColor(Color.BLACK);
|
1458 |
g2d.drawRect((int)(x + width*.3), y + 2, (int)(width*.4), height - 4); |
1459 |
//battery life rectangle
|
1460 |
g2d.setColor(Color.GREEN);
|
1461 |
int greenX = (int)(x + 1 + width*.3); |
1462 |
int greenY = (int)((y+3) + Math.abs(level-100.0)*(height-6)/(100)); |
1463 |
int greenWidth = (int)(width*.4 - 2)+1; |
1464 |
int greenHeight = 1+(int)(level-0.0)*(height-6)/(100); |
1465 |
g2d.fillRect(greenX, greenY, greenWidth, greenHeight); |
1466 |
//text
|
1467 |
g2d.setColor(Color.BLACK);
|
1468 |
g2d.drawString(level + "%", greenX + greenWidth/2 - 10, greenY + greenHeight/2 + 5); |
1469 |
|
1470 |
g2d.dispose(); |
1471 |
} |
1472 |
|
1473 |
/**
|
1474 |
* Sets the battery level for this BatteryIcon. The level should be given in raw form, i.e. 0-255 directly
|
1475 |
* from the robot. The value will be converted to a representative percentage automatically.
|
1476 |
*
|
1477 |
* @param newLevel the new battery reading from the robot that this BatteryIcon will display.
|
1478 |
*/
|
1479 |
public void setLevel(int newLevel) { |
1480 |
level = convert(newLevel); |
1481 |
} |
1482 |
|
1483 |
public int getIconWidth() { |
1484 |
return width;
|
1485 |
} |
1486 |
|
1487 |
public int getIconHeight() { |
1488 |
return height;
|
1489 |
} |
1490 |
|
1491 |
/**
|
1492 |
* Converts a robot battery reading into representable form.
|
1493 |
* Readings from the robot are returned as raw values, 0-255. This method converts the reading into a value
|
1494 |
* from 0 to 100 so that the practical remaining charge is represented.
|
1495 |
*
|
1496 |
* @param level The battery level as returned by the robot.
|
1497 |
* @returns The representable battery percentage.
|
1498 |
*/
|
1499 |
private int convert (int level) { |
1500 |
// TODO: make this a forreals conversion.
|
1501 |
return (int) (1.0 * level / 255); |
1502 |
} |
1503 |
|
1504 |
} |
1505 |
|
1506 |
|
1507 |
} |