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