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