root / trunk / code / projects / colonet / client / Colonet.java @ 625
History | View | Annotate | Download (40.1 KB)
1 |
|
---|---|
2 |
import javax.swing.*; |
3 |
import javax.swing.event.*; |
4 |
import javax.imageio.*; |
5 |
import java.awt.*; |
6 |
import java.awt.image.*; |
7 |
import java.awt.event.*; |
8 |
import java.net.*; |
9 |
import java.io.*; |
10 |
import java.util.*; |
11 |
|
12 |
/**
|
13 |
* The Colonet Graphical User Interface Applet for use locally and over an internet connection.
|
14 |
* @author Gregory Tress
|
15 |
*
|
16 |
* To generate javadoc on this file or other java files, use javadoc *.java -d doc, where doc
|
17 |
* is the name of the folder into which the files should be written.
|
18 |
*/
|
19 |
public class Colonet extends JApplet implements ActionListener, MouseInputListener, KeyListener, Runnable { |
20 |
|
21 |
// Used for painting
|
22 |
final int BUFFER = 50; |
23 |
final int RADIUS = 30; |
24 |
|
25 |
// Used for the robot controller
|
26 |
final int VECTOR_CONTROLLER_HEIGHT = 190; |
27 |
final int VECTOR_CONTROLLER_WIDTH = 320; |
28 |
|
29 |
// Connection
|
30 |
JTextField txtHost;
|
31 |
JTextField txtPort;
|
32 |
JButton btnConnect;
|
33 |
JButton btnGetXBeeIDs;
|
34 |
JLabel lblConnectionStatus;
|
35 |
JTextArea txtInfo;
|
36 |
JPanel panelConnect;
|
37 |
JPanel panelServerInterface;
|
38 |
Socket socket;
|
39 |
DataUpdater dataUpdater; |
40 |
|
41 |
// Control
|
42 |
JPanel panelControl;
|
43 |
JTabbedPane tabPaneControl;
|
44 |
JPanel panelRobotControl;
|
45 |
JPanel panelRobotDirection;
|
46 |
JPanel panelRobotDirectionButtons;
|
47 |
JPanel panelRobotCommands;
|
48 |
JButton btnF, btnB, btnL, btnR, btnActivate;
|
49 |
JComboBox cmbRobotNum;
|
50 |
JLabel lblBattery;
|
51 |
JLabel lblSelected;
|
52 |
BatteryIcon batteryIcon; |
53 |
JPanel panelBattery;
|
54 |
VectorController vectorController; |
55 |
BufferedImage imageVectorControl;
|
56 |
JButton btnAssignID;
|
57 |
boolean setWaypoint;
|
58 |
int setWaypointID;
|
59 |
JButton btnCommand_MoveTo;
|
60 |
JButton btnCommand_MoveAll;
|
61 |
JButton btnCommand_StopTask;
|
62 |
JButton btnCommand_ResumeTask;
|
63 |
JButton btnCommand_ChargeNow;
|
64 |
JButton btnCommand_StopCharging;
|
65 |
|
66 |
// Task Manager
|
67 |
JPanel panelTaskManager;
|
68 |
JScrollPane spTaskManager;
|
69 |
JPanel panelTaskManagerControls;
|
70 |
JPanel panelTaskManagerControlsPriority;
|
71 |
DefaultListModel taskListModel;
|
72 |
JList taskList;
|
73 |
JButton btnAddTask;
|
74 |
JButton btnRemoveTask;
|
75 |
JButton btnMoveTaskUp;
|
76 |
JButton btnMoveTaskDown;
|
77 |
JButton btnUpdateTasks;
|
78 |
TaskAddWindow taskAddWindow; |
79 |
|
80 |
// Webcam
|
81 |
WebcamPanel panelWebcam; |
82 |
GraphicsConfiguration gc;
|
83 |
JTabbedPane tabPaneMain;
|
84 |
WebcamLoader webcamLoader; |
85 |
|
86 |
// Robots
|
87 |
volatile int selectedBot; //the user has selected this bot graphically |
88 |
volatile java.util.Map <Integer, RobotIcon> robotIcons; //contains boundary shapes around bots for click detection |
89 |
volatile int[] xbeeID; |
90 |
|
91 |
Colonet self = this;
|
92 |
volatile ColonetServerInterface csi;
|
93 |
Thread paintThread;
|
94 |
|
95 |
public void init () { |
96 |
// Set the default look and feel - choose one
|
97 |
String laf = UIManager.getSystemLookAndFeelClassName(); |
98 |
//String laf = UIManager.getCrossPlatformLookAndFeelClassName();
|
99 |
//String laf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
|
100 |
try {
|
101 |
UIManager.setLookAndFeel(laf);
|
102 |
} catch (UnsupportedLookAndFeelException exc) { |
103 |
System.err.println ("Warning: UnsupportedLookAndFeel: " + laf); |
104 |
} catch (Exception exc) { |
105 |
System.err.println ("Error loading " + laf + ": " + exc); |
106 |
} |
107 |
|
108 |
// We should invoke and wait to avoid browser display difficulties
|
109 |
Runnable r = new Runnable() { |
110 |
public void run() { |
111 |
createAndShowGUI(); |
112 |
} |
113 |
}; |
114 |
|
115 |
try {
|
116 |
SwingUtilities.invokeAndWait(r);
|
117 |
} catch (InterruptedException e) { |
118 |
//Not really sure why we would be in this situation
|
119 |
System.out.println("InterruptedException in init: " + e); |
120 |
} catch (java.lang.reflect.InvocationTargetException e) {
|
121 |
//This could happen for various reasons if there is a problem in createAndShowGUI
|
122 |
e.printStackTrace(); |
123 |
} |
124 |
} |
125 |
|
126 |
public void destroy () { |
127 |
if (csi != null) { |
128 |
csi.disconnect(); |
129 |
} |
130 |
} |
131 |
|
132 |
private synchronized void createAndShowGUI () { |
133 |
paintThread = new Thread(this, "PaintThread"); |
134 |
paintThread.start(); |
135 |
|
136 |
// Webcam
|
137 |
gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
|
138 |
panelWebcam = new WebcamPanel();
|
139 |
tabPaneMain = new JTabbedPane(); |
140 |
tabPaneMain.setFont(new Font("arial", Font.PLAIN, 16)); |
141 |
tabPaneMain.add(panelWebcam, "Webcam");
|
142 |
|
143 |
// Robots
|
144 |
selectedBot = -1;
|
145 |
robotIcons = new HashMap <Integer, RobotIcon> (); |
146 |
|
147 |
// Connection area
|
148 |
txtInfo = new JTextArea(); |
149 |
txtInfo.setBorder(BorderFactory.createTitledBorder("Info")); |
150 |
txtHost = new JTextField(this.getDocumentBase().getHost()); |
151 |
txtHost.setBorder(BorderFactory.createTitledBorder("Host")); |
152 |
txtPort = new JTextField("10123"); |
153 |
txtPort.setBorder(BorderFactory.createTitledBorder("Port")); |
154 |
btnConnect = new JButton("Connect"); |
155 |
btnConnect.setFont(new Font("arial", Font.BOLD, 16)); |
156 |
btnGetXBeeIDs = new JButton("Get XBee IDs"); |
157 |
getRootPane().setDefaultButton(btnConnect); |
158 |
lblConnectionStatus = new JLabel("Status: Offline"); |
159 |
panelConnect = new JPanel(); |
160 |
panelConnect.setLayout(new GridLayout(6,1)); |
161 |
panelConnect.add(lblConnectionStatus); |
162 |
panelConnect.add(txtHost); |
163 |
panelConnect.add(txtPort); |
164 |
panelConnect.add(btnConnect); |
165 |
//panelConnect.add(btnGetXBeeIDs);
|
166 |
panelServerInterface = new JPanel(); |
167 |
panelServerInterface.setLayout(new GridLayout(2,1)); |
168 |
panelServerInterface.add(panelConnect); |
169 |
panelServerInterface.add(txtInfo); |
170 |
|
171 |
// Robot direction panel
|
172 |
panelRobotDirection = new JPanel(); |
173 |
panelRobotDirectionButtons = new JPanel(); |
174 |
|
175 |
Font f = new Font(null, Font.PLAIN, 18); |
176 |
btnF = new JButton("\u2191"); |
177 |
btnF.setFont(f); |
178 |
btnB = new JButton("\u2193"); |
179 |
btnB.setFont(f); |
180 |
btnL = new JButton("\u2190"); |
181 |
btnL.setFont(f); |
182 |
btnR = new JButton("\u2192"); |
183 |
btnR.setFont(f); |
184 |
btnActivate = new JButton("\u25A0"); |
185 |
btnActivate.setFont(new Font(null, Font.BOLD, 36)); |
186 |
|
187 |
panelRobotDirectionButtons.setLayout(new GridLayout(1,5)); |
188 |
panelRobotDirectionButtons.add(btnActivate); |
189 |
panelRobotDirectionButtons.add(btnF); |
190 |
panelRobotDirectionButtons.add(btnB); |
191 |
panelRobotDirectionButtons.add(btnL); |
192 |
panelRobotDirectionButtons.add(btnR); |
193 |
|
194 |
imageVectorControl = gc.createCompatibleImage(VECTOR_CONTROLLER_WIDTH, VECTOR_CONTROLLER_HEIGHT); |
195 |
vectorController = new VectorController(imageVectorControl);
|
196 |
panelRobotDirection.setLayout(new BorderLayout()); |
197 |
panelRobotDirection.add(vectorController, BorderLayout.CENTER);
|
198 |
panelRobotDirection.add(panelRobotDirectionButtons, BorderLayout.SOUTH);
|
199 |
|
200 |
// Robot Control and Commands
|
201 |
panelRobotCommands = new JPanel(); |
202 |
panelRobotCommands.setLayout(new GridLayout(5,2)); |
203 |
cmbRobotNum = new JComboBox(); |
204 |
// Battery subset
|
205 |
batteryIcon = new BatteryIcon(0); |
206 |
lblBattery = new JLabel(batteryIcon); |
207 |
lblSelected = new JLabel("None"); |
208 |
// Command subset
|
209 |
setWaypoint = false;
|
210 |
setWaypointID = -1;
|
211 |
btnAssignID = new JButton("Assign ID"); |
212 |
btnCommand_MoveTo = new JButton("Move to ..."); |
213 |
btnCommand_MoveAll = new JButton("Move all ..."); |
214 |
btnCommand_StopTask = new JButton("Stop Current Task"); |
215 |
btnCommand_ResumeTask = new JButton("Resume Current Task"); |
216 |
btnCommand_ChargeNow = new JButton("Recharge Now"); |
217 |
btnCommand_StopCharging = new JButton("Stop Recharging"); |
218 |
panelRobotCommands.add(new JLabel("Select Robot to Control: ")); |
219 |
panelRobotCommands.add(cmbRobotNum); |
220 |
panelRobotCommands.add(new JLabel("Battery Level: ")); |
221 |
panelRobotCommands.add(lblBattery); |
222 |
panelRobotCommands.add(new JLabel("Selected Icon: ")); |
223 |
panelRobotCommands.add(lblSelected); |
224 |
panelRobotCommands.add(btnAssignID); |
225 |
panelRobotCommands.add(new JLabel("")); |
226 |
panelRobotCommands.add(btnCommand_MoveTo); |
227 |
panelRobotCommands.add(btnCommand_MoveAll); |
228 |
//panelRobotCommands.add(btnCommand_StopTask);
|
229 |
//panelRobotCommands.add(btnCommand_ResumeTask);
|
230 |
//panelRobotCommands.add(btnCommand_ChargeNow);
|
231 |
//panelRobotCommands.add(btnCommand_StopCharging);
|
232 |
panelRobotControl = new JPanel(); |
233 |
panelRobotControl.setLayout(new GridLayout(2,1)); |
234 |
panelRobotControl.add(panelRobotDirection); |
235 |
panelRobotControl.add(panelRobotCommands); |
236 |
|
237 |
|
238 |
// Task Manager
|
239 |
panelTaskManager = new JPanel(); |
240 |
panelTaskManager.setLayout(new BorderLayout()); |
241 |
taskListModel = new DefaultListModel(); |
242 |
taskList = new JList(taskListModel); |
243 |
taskList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
|
244 |
taskList.setSelectedIndex(0);
|
245 |
spTaskManager = new JScrollPane(taskList); |
246 |
panelTaskManagerControls = new JPanel(); |
247 |
panelTaskManagerControls.setLayout(new GridLayout(1,4)); |
248 |
panelTaskManagerControlsPriority = new JPanel(); |
249 |
panelTaskManagerControlsPriority.setLayout(new GridLayout(1,2)); |
250 |
btnAddTask = new JButton("Add..."); |
251 |
btnRemoveTask = new JButton("Remove"); |
252 |
btnMoveTaskUp = new JButton("^"); |
253 |
btnMoveTaskDown = new JButton("v"); |
254 |
btnUpdateTasks = new JButton("Update"); |
255 |
panelTaskManagerControlsPriority.add(btnMoveTaskUp); |
256 |
panelTaskManagerControlsPriority.add(btnMoveTaskDown); |
257 |
panelTaskManagerControls.add(btnAddTask); |
258 |
panelTaskManagerControls.add(btnRemoveTask); |
259 |
panelTaskManagerControls.add(btnUpdateTasks); |
260 |
panelTaskManagerControls.add(panelTaskManagerControlsPriority); |
261 |
panelTaskManager.add(spTaskManager, BorderLayout.CENTER);
|
262 |
panelTaskManager.add(panelTaskManagerControls, BorderLayout.SOUTH);
|
263 |
panelTaskManager.add(new JLabel("Current Task Queue"), BorderLayout.NORTH); |
264 |
taskAddWindow = new TaskAddWindow();
|
265 |
|
266 |
// Main control mechanism
|
267 |
panelControl = new JPanel(); |
268 |
panelControl.setLayout(new GridLayout(1,1)); |
269 |
tabPaneControl = new JTabbedPane(JTabbedPane.TOP); |
270 |
tabPaneControl.setFont(new Font("arial", Font.PLAIN, 16)); |
271 |
tabPaneControl.setPreferredSize(new Dimension(VECTOR_CONTROLLER_WIDTH, 0)); |
272 |
tabPaneControl.addTab("Connection", panelServerInterface);
|
273 |
tabPaneControl.addTab("Robots", panelRobotControl);
|
274 |
//tabPaneControl.addTab("Tasks", panelTaskManager);
|
275 |
panelControl.add(tabPaneControl); |
276 |
|
277 |
|
278 |
// Put all elements in the ContentPane
|
279 |
this.getContentPane().setLayout(new BorderLayout()); |
280 |
this.getContentPane().add(tabPaneMain, BorderLayout.CENTER); |
281 |
this.getContentPane().add(panelControl, BorderLayout.EAST); |
282 |
this.setVisible(true); |
283 |
|
284 |
// Disable components before connecting
|
285 |
btnConnect.setText("Connect");
|
286 |
lblConnectionStatus.setText("Status: Disconnected");
|
287 |
btnF.setEnabled(false);
|
288 |
btnB.setEnabled(false);
|
289 |
btnL.setEnabled(false);
|
290 |
btnR.setEnabled(false);
|
291 |
btnActivate.setEnabled(false);
|
292 |
cmbRobotNum.setEnabled(false);
|
293 |
btnAssignID.setEnabled(false);
|
294 |
btnCommand_MoveTo.setEnabled(false);
|
295 |
btnCommand_MoveAll.setEnabled(false);
|
296 |
|
297 |
/* Add all listeners here */
|
298 |
// Task Management
|
299 |
btnAddTask.addActionListener(this);
|
300 |
btnRemoveTask.addActionListener(this);
|
301 |
btnMoveTaskUp.addActionListener(this);
|
302 |
btnMoveTaskDown.addActionListener(this);
|
303 |
btnUpdateTasks.addActionListener(this);
|
304 |
// Robot Control
|
305 |
btnF.addActionListener(this);
|
306 |
btnB.addActionListener(this);
|
307 |
btnL.addActionListener(this);
|
308 |
btnR.addActionListener(this);
|
309 |
btnF.addKeyListener(this);
|
310 |
btnB.addKeyListener(this);
|
311 |
btnL.addKeyListener(this);
|
312 |
btnR.addKeyListener(this);
|
313 |
btnActivate.addActionListener(this);
|
314 |
btnActivate.addKeyListener(this);
|
315 |
cmbRobotNum.addKeyListener(this);
|
316 |
btnCommand_MoveTo.addActionListener(this);
|
317 |
btnCommand_MoveAll.addActionListener(this);
|
318 |
btnCommand_StopTask.addActionListener(this);
|
319 |
btnCommand_ResumeTask.addActionListener(this);
|
320 |
btnCommand_ChargeNow.addActionListener(this);
|
321 |
btnCommand_StopCharging.addActionListener(this);
|
322 |
// Other
|
323 |
btnConnect.addActionListener(this);
|
324 |
btnGetXBeeIDs.addActionListener(this);
|
325 |
btnAssignID.addActionListener(this);
|
326 |
panelWebcam.addMouseListener(this);
|
327 |
} |
328 |
|
329 |
public void paint (Graphics g) { |
330 |
super.paint(g);
|
331 |
} |
332 |
|
333 |
public void update (Graphics g) { |
334 |
paint(g); |
335 |
} |
336 |
|
337 |
public void run () { |
338 |
final int PAINT_DELAY = 300; |
339 |
while (true) { |
340 |
try {
|
341 |
Thread.sleep(PAINT_DELAY);
|
342 |
} catch (Exception e) { |
343 |
System.out.println(e);
|
344 |
return;
|
345 |
} |
346 |
repaint(); |
347 |
} |
348 |
} |
349 |
|
350 |
/**
|
351 |
* Gets the JTextArea used for displaying debugging information.
|
352 |
*
|
353 |
* @return the JTextArea where debugging information can be displayed.
|
354 |
*/
|
355 |
public JTextArea getInfoPanel () { |
356 |
return txtInfo;
|
357 |
} |
358 |
|
359 |
/**
|
360 |
* Parses a String containing BOM matrix information.
|
361 |
* The ColonetServerInterface receives lines of the BOM matrix. (For encoding
|
362 |
* information, see the ColonetServerInterface documentation.) The entire matrix is passed
|
363 |
* to the client when requested. This method takes a string of the form
|
364 |
* "[command code] [command code] [number of robots] [data0] [data1] ..."
|
365 |
* with tokens separated by spaces and containing no brackets.
|
366 |
* The [command code]s are predefined values identifying this String as a BOM data
|
367 |
* String, [number of robots] is an integer, and the values that follow are
|
368 |
* the sensor readings of the robots in order, starting with robot 0. Only [number of robots]^2
|
369 |
* data entries will be read. The matrix values are saved locally until the next String is parsed.
|
370 |
*
|
371 |
*
|
372 |
* @param line the String containing BOM matrix information.
|
373 |
* @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots]^2 data entries in the String
|
374 |
*/
|
375 |
public void parseMatrix (String line) { |
376 |
txtInfo.setText("");
|
377 |
String [] str = line.split(" "); |
378 |
int num = Integer.parseInt(str[2]); |
379 |
for (int i = 0; i < num; i++) { |
380 |
for (int j = 0; j < num; j++) { |
381 |
String next = str[3 + i*num + j]; |
382 |
if (next.equals("-1")) { |
383 |
txtInfo.append("-");
|
384 |
} else {
|
385 |
txtInfo.append(next); |
386 |
} |
387 |
|
388 |
if (j < num - 1) { |
389 |
txtInfo.append(" ");
|
390 |
} |
391 |
} |
392 |
|
393 |
if (i < num - 1) { |
394 |
txtInfo.append("\n");
|
395 |
} |
396 |
} |
397 |
repaint(); |
398 |
} |
399 |
|
400 |
public void connect () { |
401 |
if (csi != null) |
402 |
return;
|
403 |
csi = new ColonetServerInterface(self);
|
404 |
csi.connect(txtHost.getText(), txtPort.getText()); |
405 |
if (!csi.isReady()) {
|
406 |
csi = null;
|
407 |
return;
|
408 |
} |
409 |
webcamLoader = new WebcamLoader(self);
|
410 |
dataUpdater = new DataUpdater();
|
411 |
dataUpdater.start(); |
412 |
webcamLoader.start(); |
413 |
Runnable r = new Runnable() { |
414 |
public void run () { |
415 |
btnConnect.setText("Disconnect");
|
416 |
lblConnectionStatus.setText("Status: Connected");
|
417 |
btnF.setEnabled(true);
|
418 |
btnB.setEnabled(true);
|
419 |
btnL.setEnabled(true);
|
420 |
btnR.setEnabled(true);
|
421 |
btnActivate.setEnabled(true);
|
422 |
cmbRobotNum.setEnabled(true);
|
423 |
btnAssignID.setEnabled(true);
|
424 |
btnCommand_MoveTo.setEnabled(true);
|
425 |
btnCommand_MoveAll.setEnabled(true);
|
426 |
} |
427 |
}; |
428 |
SwingUtilities.invokeLater(r);
|
429 |
} |
430 |
|
431 |
public void disconnect () { |
432 |
try {
|
433 |
dataUpdater.interrupt(); |
434 |
} catch (Exception e) { |
435 |
} |
436 |
csi = null;
|
437 |
Runnable r = new Runnable() { |
438 |
public void run () { |
439 |
btnConnect.setText("Connect");
|
440 |
lblConnectionStatus.setText("Status: Disconnected");
|
441 |
btnF.setEnabled(false);
|
442 |
btnB.setEnabled(false);
|
443 |
btnL.setEnabled(false);
|
444 |
btnR.setEnabled(false);
|
445 |
btnActivate.setEnabled(false);
|
446 |
cmbRobotNum.setEnabled(false);
|
447 |
btnAssignID.setEnabled(false);
|
448 |
btnCommand_MoveTo.setEnabled(false);
|
449 |
btnCommand_MoveAll.setEnabled(false);
|
450 |
} |
451 |
}; |
452 |
SwingUtilities.invokeLater(r);
|
453 |
} |
454 |
|
455 |
/**
|
456 |
* Parses a String containing a task queue update.
|
457 |
* Format is currently not specified.
|
458 |
* This method currently does nothing.
|
459 |
*
|
460 |
* @param line the String containing task queue update information.
|
461 |
*/
|
462 |
public void parseQueue (String line) { |
463 |
|
464 |
} |
465 |
|
466 |
/**
|
467 |
* Parses a String containing XBee ID values.
|
468 |
* The ColonetServerInterface receives Strings of XBee information. (For encoding
|
469 |
* information, see the ColonetServerInterface documentation.) This method takes
|
470 |
* a string of the form "[command code] [command code] [number of robots] [id0] [id1] ..."
|
471 |
* with tokens separated by spaces and containing no brackets.
|
472 |
* The [command code]s are predefined values identifying this String as an XBee
|
473 |
* ID String, [number of robots] is an integer, and the values that follow are
|
474 |
* the IDs of the robots in order, starting with robot 0. Only [number of robots]
|
475 |
* will be read. The ID values are saved locally until the next String is parsed.
|
476 |
* The purpose of having this list is to ensure that robots are properly identified for control purposes.
|
477 |
* This keeps robot identification consistent between sessions and prevents arbitrary assignment.
|
478 |
*
|
479 |
* @param line the String containing XBee ID information.
|
480 |
* @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots] IDs in the String
|
481 |
* @see ColonetServerInterface#sendXBeeIDRequest()
|
482 |
*/
|
483 |
public void parseXBeeIDs (String line) { |
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 |
|
491 |
//update the list of robots to control
|
492 |
//but save the old value first
|
493 |
Object oldSelection = cmbRobotNum.getSelectedItem();
|
494 |
cmbRobotNum.removeAllItems(); |
495 |
cmbRobotNum.addItem(new String(" All ")); |
496 |
for (int i = 0; i < num; i++) { |
497 |
cmbRobotNum.addItem(new String("" + xbeeID[i])); |
498 |
} |
499 |
cmbRobotNum.setSelectedItem(oldSelection); |
500 |
repaint(); |
501 |
} |
502 |
|
503 |
/**
|
504 |
* Parses a String containing battery information.
|
505 |
* The ColonetServerInterface receives Strings of battery information. (For encoding
|
506 |
* information, see the ColonetServerInterface documentation.) This method takes
|
507 |
* a string of the form "[command code] [command code] [robot ID] [value]"
|
508 |
* with tokens separated by spaces and containing no brackets.
|
509 |
* The [command code]s are predefined values identifying this String as a battery
|
510 |
* information String, [robot ID] is an integer, and [value] is a battery measurement.
|
511 |
* This updates the batery information for a single robot.
|
512 |
*
|
513 |
*
|
514 |
* @param line the String containing battery information.
|
515 |
* @see ColonetServerInterface#sendBatteryRequest(int)
|
516 |
*/
|
517 |
public void parseBattery (String line) { |
518 |
int botNum, level;
|
519 |
System.out.println("Got battery update:" + line); |
520 |
try {
|
521 |
String [] str = line.split(" "); |
522 |
botNum = Integer.parseInt(str[2]); |
523 |
level = Integer.parseInt(str[3]); |
524 |
} catch (NumberFormatException e) { |
525 |
System.out.println("Could not parse battery update"); |
526 |
return;
|
527 |
} |
528 |
|
529 |
RobotIcon r = robotIcons.get(botNum); |
530 |
if (r != null) { |
531 |
r.battery = batteryIcon.convert(level); // set contextual battery meter
|
532 |
batteryIcon.setLevel(level); // set solo battery meter
|
533 |
System.out.println("Set " + r.id + " battery value to " + level); |
534 |
} |
535 |
repaint(); |
536 |
} |
537 |
|
538 |
/**
|
539 |
* Parses a String containing visual robot position information along with
|
540 |
* canonical ID assignments.
|
541 |
*/
|
542 |
public void parsePositions (String line) { |
543 |
String [] str = line.split(" "); |
544 |
java.util.Map <Integer, RobotIcon> newMap = new HashMap <Integer, RobotIcon> (); |
545 |
|
546 |
for (int i = 2; i < str.length; i+=3) { |
547 |
int id = Integer.parseInt(str[i]); |
548 |
int x = Integer.parseInt(str[i+1]); |
549 |
int y = Integer.parseInt(str[i+2]); |
550 |
RobotIcon newIcon = new RobotIcon(id, x, y);
|
551 |
// Save previous battery value
|
552 |
if (robotIcons.get(id) != null) |
553 |
newIcon.battery = robotIcons.get(id).battery; |
554 |
if (newIcon.id >= 0) { |
555 |
newIcon.color = Color.GREEN;
|
556 |
} |
557 |
newMap.put(id, newIcon); |
558 |
} |
559 |
robotIcons = newMap; |
560 |
repaint(); |
561 |
} |
562 |
|
563 |
//
|
564 |
// MouseListener methods
|
565 |
//
|
566 |
public void mousePressed(MouseEvent e) { |
567 |
//Start a new Thread to handle the MouseEvent
|
568 |
(new MouseHandler(e)).start();
|
569 |
repaint(); |
570 |
} |
571 |
public void mouseExited(MouseEvent e) { |
572 |
} |
573 |
public void mouseEntered(MouseEvent e) { |
574 |
} |
575 |
public void mouseReleased(MouseEvent e) { |
576 |
} |
577 |
public void mouseClicked(MouseEvent e) { |
578 |
} |
579 |
public void mouseDragged(MouseEvent e) { |
580 |
} |
581 |
public void mouseMoved(MouseEvent e) { |
582 |
} |
583 |
|
584 |
//
|
585 |
// KeyListener methods
|
586 |
//
|
587 |
public void keyPressed (KeyEvent e) { |
588 |
//Start a new Thread to handle the KeyEvent
|
589 |
(new KeyHandler(e)).start();
|
590 |
repaint(); |
591 |
} |
592 |
public void keyReleased (KeyEvent e) { |
593 |
} |
594 |
public void keyTyped (KeyEvent e) { |
595 |
} |
596 |
|
597 |
//
|
598 |
// ActionListener method
|
599 |
//
|
600 |
public void actionPerformed (ActionEvent e) { |
601 |
// Start a new Thread to handle the ActionEvent
|
602 |
(new ActionHandler(e)).start();
|
603 |
repaint(); |
604 |
} |
605 |
|
606 |
class MouseHandler extends Thread { |
607 |
MouseEvent e;
|
608 |
|
609 |
public MouseHandler (MouseEvent event) { |
610 |
super("MouseHandler"); |
611 |
this.e = event;
|
612 |
} |
613 |
|
614 |
public void run () { |
615 |
Point pt = panelWebcam.convertClick(e);
|
616 |
|
617 |
// If we are selecting a waypoint (destination) for a specific bot
|
618 |
if (setWaypoint && setWaypointID >= 0) { |
619 |
setWaypoint = false;
|
620 |
panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); |
621 |
if (selectedBot < 0) { |
622 |
return;
|
623 |
} |
624 |
|
625 |
RobotIcon r = robotIcons.get(selectedBot); |
626 |
if (r != null) { |
627 |
r.destx = pt.x; |
628 |
r.desty = pt.y; |
629 |
if (csi != null) { |
630 |
csi.sendAbsoluteMove(r.id, r.destx, r.desty); |
631 |
} |
632 |
} |
633 |
|
634 |
return;
|
635 |
} |
636 |
|
637 |
// Right-click also means we are moving a robot
|
638 |
if (e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON3) { |
639 |
if (selectedBot < 0) { |
640 |
return;
|
641 |
} |
642 |
|
643 |
RobotIcon r = robotIcons.get(selectedBot); |
644 |
if (r != null) { |
645 |
r.destx = pt.x; |
646 |
r.desty = pt.y; |
647 |
if (csi != null) { |
648 |
csi.sendAbsoluteMove(r.id, r.destx, r.desty); |
649 |
} |
650 |
} |
651 |
|
652 |
return;
|
653 |
} |
654 |
|
655 |
// If we are setting all waypoints
|
656 |
if (setWaypoint) {
|
657 |
setWaypoint = false;
|
658 |
panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); |
659 |
for (Map.Entry<Integer,RobotIcon> entry : robotIcons.entrySet()) { |
660 |
RobotIcon r = entry.getValue(); |
661 |
r.destx = pt.x; |
662 |
r.desty = pt.y; |
663 |
} |
664 |
return;
|
665 |
} |
666 |
|
667 |
// Otherwise, we are selecting a bot, or doing nothing
|
668 |
for (Map.Entry<Integer,RobotIcon> entry : robotIcons.entrySet()) { |
669 |
RobotIcon r = entry.getValue(); |
670 |
if (r.contains(pt.x, pt.y)) {
|
671 |
selectedBot = r.id; |
672 |
lblSelected.setText("" + r.id);
|
673 |
// Try to select the clicked bot, if its XBee ID is detected.
|
674 |
for (int j = 1; j < cmbRobotNum.getItemCount(); j++) { |
675 |
if (Integer.parseInt(cmbRobotNum.getItemAt(j).toString()) == selectedBot) { |
676 |
cmbRobotNum.setSelectedIndex(j); |
677 |
} |
678 |
} |
679 |
return;
|
680 |
} |
681 |
} |
682 |
|
683 |
} |
684 |
} |
685 |
|
686 |
class KeyHandler extends Thread { |
687 |
KeyEvent e;
|
688 |
|
689 |
public KeyHandler (KeyEvent event) { |
690 |
super("KeyHandler"); |
691 |
this.e = event;
|
692 |
} |
693 |
|
694 |
public void run () { |
695 |
int code = e.getKeyCode();
|
696 |
if (code == KeyEvent.VK_UP) { |
697 |
vectorController.setMaxForward(); |
698 |
vectorController.sendToServer(); |
699 |
} else if (code == KeyEvent.VK_DOWN) { |
700 |
vectorController.setMaxReverse(); |
701 |
vectorController.sendToServer(); |
702 |
} else if (code == KeyEvent.VK_LEFT) { |
703 |
vectorController.setMaxLeft(); |
704 |
vectorController.sendToServer(); |
705 |
} else if (code == KeyEvent.VK_RIGHT) { |
706 |
vectorController.setMaxRight(); |
707 |
vectorController.sendToServer(); |
708 |
} else if (code == KeyEvent.VK_S) { |
709 |
vectorController.setZero(); |
710 |
vectorController.sendToServer(); |
711 |
} |
712 |
} |
713 |
} |
714 |
|
715 |
class ActionHandler extends Thread { |
716 |
ActionEvent e;
|
717 |
|
718 |
public ActionHandler (ActionEvent event) { |
719 |
super("ActionHandler"); |
720 |
this.e = event;
|
721 |
} |
722 |
|
723 |
public void run () { |
724 |
Object source = e.getSource();
|
725 |
|
726 |
// General Actions
|
727 |
if (source == btnConnect) {
|
728 |
if (csi == null) { |
729 |
connect(); |
730 |
} else {
|
731 |
disconnect(); |
732 |
} |
733 |
} else if (source == btnGetXBeeIDs) { |
734 |
csi.sendXBeeIDRequest(); |
735 |
} else if (source == btnAssignID) { |
736 |
String message;
|
737 |
if (selectedBot < 0) { |
738 |
message = "That robot is unidentified. Please specify its ID.";
|
739 |
} else {
|
740 |
message = "That robot has ID " + selectedBot + ". You may reassign it now."; |
741 |
} |
742 |
String result = JOptionPane.showInputDialog(self, message, "Robot Identification", JOptionPane.QUESTION_MESSAGE); |
743 |
if (result == null) { |
744 |
return;
|
745 |
} |
746 |
int newID = -1; |
747 |
try {
|
748 |
newID = Integer.parseInt(result);
|
749 |
} catch (Exception ex) { |
750 |
csi.warn("Invalid ID.");
|
751 |
return;
|
752 |
} |
753 |
// Assign new ID and update display
|
754 |
if (csi != null) { |
755 |
csi.sendIDAssignment(selectedBot, newID); |
756 |
} |
757 |
selectedBot = newID; |
758 |
lblSelected.setText("" + newID);
|
759 |
} else if (source == btnF) { // Robot Movement Controls |
760 |
vectorController.setMaxForward(); |
761 |
vectorController.sendToServer(); |
762 |
} else if (source == btnB) { |
763 |
vectorController.setMaxReverse(); |
764 |
vectorController.sendToServer(); |
765 |
} else if (source == btnL) { |
766 |
vectorController.setMaxLeft(); |
767 |
vectorController.sendToServer(); |
768 |
} else if (source == btnR) { |
769 |
vectorController.setMaxRight(); |
770 |
vectorController.sendToServer(); |
771 |
} else if (source == btnActivate) { |
772 |
vectorController.setZero(); |
773 |
vectorController.sendToServer(); |
774 |
} else if (source == btnCommand_MoveTo) { // Robot Commands (non-movement) |
775 |
if (selectedBot < 0) { |
776 |
return;
|
777 |
} |
778 |
panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); |
779 |
setWaypoint = true;
|
780 |
setWaypointID = selectedBot; |
781 |
} else if (source == btnCommand_MoveAll) { |
782 |
panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); |
783 |
setWaypoint = true;
|
784 |
setWaypointID = -1;
|
785 |
} else if (source == btnCommand_StopTask) { |
786 |
|
787 |
} else if (source == btnCommand_ResumeTask) { |
788 |
|
789 |
} else if (source == btnCommand_ChargeNow) { |
790 |
|
791 |
} else if (source == btnCommand_StopCharging) { |
792 |
|
793 |
} else if (source == btnAddTask) { // Queue Management |
794 |
taskAddWindow.prompt(); |
795 |
} else if (source == btnRemoveTask) { |
796 |
if (taskList.getSelectedIndex() >= 0) { |
797 |
csi.sendQueueRemove(taskList.getSelectedIndex()); |
798 |
} |
799 |
csi.sendQueueUpdate(); |
800 |
} else if (source == btnMoveTaskUp) { |
801 |
csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() - 1);
|
802 |
csi.sendQueueUpdate(); |
803 |
} else if (source == btnMoveTaskDown) { |
804 |
csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() + 1);
|
805 |
csi.sendQueueUpdate(); |
806 |
} else if (source == btnUpdateTasks) { |
807 |
csi.sendQueueUpdate(); |
808 |
} |
809 |
|
810 |
} |
811 |
} |
812 |
|
813 |
/*
|
814 |
* DataUpdater thread.
|
815 |
* The purpose of this thread is to request data from the server at regular intervals.
|
816 |
*
|
817 |
*/
|
818 |
class DataUpdater extends Thread { |
819 |
final int DATAUPDATER_DELAY = 3000; |
820 |
public DataUpdater () {
|
821 |
super("Colonet DataUpdater"); |
822 |
} |
823 |
|
824 |
public synchronized void run () { |
825 |
String line;
|
826 |
while (true) { |
827 |
try {
|
828 |
//request more data
|
829 |
if (csi != null && csi.isReady()) { |
830 |
csi.sendPositionRequest(); |
831 |
csi.sendXBeeIDRequest(); |
832 |
for (Map.Entry<Integer,RobotIcon> entry : robotIcons.entrySet()) { |
833 |
RobotIcon r = entry.getValue(); |
834 |
int id = r.id;
|
835 |
if (id >= 0) { |
836 |
csi.sendBatteryRequest(id); |
837 |
System.out.println("Sent battery request (" + id + ")"); |
838 |
} |
839 |
} |
840 |
} |
841 |
Thread.sleep(DATAUPDATER_DELAY);
|
842 |
} catch (InterruptedException e) { |
843 |
return;
|
844 |
} catch (NullPointerException e) { |
845 |
// This probably indicates that an object was destroyed by shutdown.
|
846 |
return;
|
847 |
} |
848 |
} |
849 |
} |
850 |
} |
851 |
|
852 |
/*
|
853 |
* GraphicsPanel class
|
854 |
* An extension of JPanel, designed for holding an image that will be repainted regularly.
|
855 |
*/
|
856 |
class GraphicsPanel extends JPanel { |
857 |
protected Image img; |
858 |
|
859 |
public GraphicsPanel (Image img) { |
860 |
this(img, true); |
861 |
} |
862 |
|
863 |
public GraphicsPanel (Image img, boolean isDoubleBuffered) { |
864 |
super(isDoubleBuffered);
|
865 |
this.img = img;
|
866 |
} |
867 |
|
868 |
public void paint (Graphics g) { |
869 |
// Place the buffered image on the screen, inside the panel
|
870 |
g.drawImage(img, 0, 0, Color.WHITE, this); |
871 |
} |
872 |
} |
873 |
|
874 |
/*
|
875 |
* WebcamPanel class
|
876 |
* Enables more efficient image handling in a component-controlled environment
|
877 |
*/
|
878 |
class WebcamPanel extends JPanel { |
879 |
final int BORDER = 16; // this is arbitrary. it makes the image look nice inside a border. |
880 |
final int BATTERY_WIDTH = 50; |
881 |
final int BATTERY_HEIGHT = 10; |
882 |
volatile BufferedImage img; |
883 |
BufferedImage buffer;
|
884 |
|
885 |
public WebcamPanel () {
|
886 |
super(true); |
887 |
} |
888 |
|
889 |
public synchronized void setImage (BufferedImage newimg) { |
890 |
if (img != null) { |
891 |
img.flush(); |
892 |
} |
893 |
System.gc();
|
894 |
img = newimg; |
895 |
repaint(); |
896 |
} |
897 |
|
898 |
public synchronized void paint (Graphics g) { |
899 |
if (img == null) { |
900 |
return;
|
901 |
} |
902 |
|
903 |
// Calculate scaling
|
904 |
int maxWidth = getWidth() - 2*BORDER; |
905 |
int maxHeight = getHeight() - 2*BORDER; |
906 |
double widthRatio = 1.0 * maxWidth / img.getWidth(); |
907 |
double heightRatio = 1.0 * maxHeight / img.getHeight(); |
908 |
double scale = 0; |
909 |
int newWidth = 0; |
910 |
int newHeight = 0; |
911 |
int x = 0; |
912 |
int y = 0; |
913 |
|
914 |
if (widthRatio > heightRatio) { //height is the limiting factor |
915 |
scale = heightRatio; |
916 |
newHeight = maxHeight; |
917 |
newWidth = (int) (img.getWidth() * scale);
|
918 |
y = BORDER; |
919 |
x = (maxWidth - newWidth) / 2 + BORDER;
|
920 |
} else { //width is the limiting factor |
921 |
scale = widthRatio; |
922 |
newWidth = maxWidth; |
923 |
newHeight = (int) (img.getHeight() * scale);
|
924 |
x = BORDER; |
925 |
y = (maxHeight - newHeight) / 2 + BORDER;
|
926 |
} |
927 |
|
928 |
// Draw everything onto the buffer
|
929 |
buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); |
930 |
Graphics2D bufferedGraphics = (Graphics2D)buffer.getGraphics(); |
931 |
bufferedGraphics.setColor(Color.GRAY);
|
932 |
bufferedGraphics.fillRect(0, 0, this.getWidth(), this.getHeight()); |
933 |
Image imgScaled = img.getScaledInstance(newWidth, newHeight, Image.SCALE_FAST); |
934 |
bufferedGraphics.drawImage(imgScaled, x, y, this);
|
935 |
|
936 |
|
937 |
// Draw Identifiers and battery levels
|
938 |
if (robotIcons != null) { |
939 |
bufferedGraphics.setStroke(new BasicStroke(2)); |
940 |
for (Map.Entry<Integer,RobotIcon> entry : robotIcons.entrySet()) { |
941 |
RobotIcon r = entry.getValue(); |
942 |
bufferedGraphics.setColor(r.color); |
943 |
// Identifier circle
|
944 |
int px = (int) (x + r.x * scale); |
945 |
int py = (int) (y + r.y * scale); |
946 |
bufferedGraphics.drawOval(px-RADIUS, py-RADIUS, 2*r.RADIUS, 2*r.RADIUS); |
947 |
// Battery
|
948 |
if (r.battery >= 0) { |
949 |
int pixels = r.battery * BATTERY_WIDTH / 160; // 160 should be fully charged |
950 |
if (r.battery > 50) |
951 |
bufferedGraphics.setColor(Color.GREEN);
|
952 |
else if (r.battery > 25) |
953 |
bufferedGraphics.setColor(Color.YELLOW);
|
954 |
else
|
955 |
bufferedGraphics.setColor(Color.RED);
|
956 |
bufferedGraphics.fillRect(px+20, py+20, pixels, BATTERY_HEIGHT); |
957 |
bufferedGraphics.setColor(Color.BLACK);
|
958 |
bufferedGraphics.drawRect(px+20, py+20, BATTERY_WIDTH, BATTERY_HEIGHT); |
959 |
} |
960 |
// If the robot has a destination, draw the vector
|
961 |
if (r.destx >= 0) { |
962 |
bufferedGraphics.drawLine(px, py, (int)(x + r.destx * scale), (int)(y + r.desty * scale)); |
963 |
} |
964 |
} |
965 |
} |
966 |
|
967 |
// Identify currently-selected robot
|
968 |
RobotIcon r = robotIcons.get(selectedBot); |
969 |
if (r != null) { |
970 |
int px = (int) (x + r.x * scale); |
971 |
int py = (int) (y + r.y * scale); |
972 |
bufferedGraphics.setColor(Color.BLACK);
|
973 |
bufferedGraphics.drawOval(px-RADIUS-6, py-RADIUS-6, 2*r.RADIUS+12, 2*r.RADIUS+12); |
974 |
} |
975 |
|
976 |
//Display buffered content
|
977 |
g.drawImage(buffer, 0, 0, this); |
978 |
} |
979 |
|
980 |
/*
|
981 |
* Convert a click on the webcam panel to a coordinate that is consistent with the
|
982 |
* original size of the image that the panel contains.
|
983 |
*/
|
984 |
public Point convertClick (MouseEvent e) { |
985 |
if (img == null) { |
986 |
return new Point(e.getX(), e.getY()); |
987 |
} |
988 |
|
989 |
// Calculate scaling
|
990 |
int clickx = e.getX();
|
991 |
int clicky = e.getY();
|
992 |
int maxWidth = getWidth() - 2*BORDER; |
993 |
int maxHeight = getHeight() - 2*BORDER; |
994 |
double widthRatio = 1.0 * maxWidth / img.getWidth(); |
995 |
double heightRatio = 1.0 * maxHeight / img.getHeight(); |
996 |
double scale = 0; |
997 |
int newWidth = 0; |
998 |
int newHeight = 0; |
999 |
int px = 0; |
1000 |
int py = 0; |
1001 |
|
1002 |
if (widthRatio > heightRatio) { //height is the limiting factor |
1003 |
scale = heightRatio; |
1004 |
newHeight = maxHeight; |
1005 |
newWidth = (int) (img.getWidth() * scale);
|
1006 |
py = clicky - BORDER; |
1007 |
px = clickx - BORDER - (maxWidth - newWidth) / 2;
|
1008 |
} else { //width is the limiting factor |
1009 |
scale = widthRatio; |
1010 |
newWidth = maxWidth; |
1011 |
newHeight = (int) (img.getHeight() * scale);
|
1012 |
px = clickx - BORDER; |
1013 |
py = clicky - BORDER - (maxHeight - newHeight) / 2;
|
1014 |
} |
1015 |
py = (int) (py / scale);
|
1016 |
px = (int) (px / scale);
|
1017 |
return new Point(px, py); |
1018 |
} |
1019 |
} |
1020 |
|
1021 |
/*
|
1022 |
* WebcamLoader class
|
1023 |
* Handles the loading of the webcam image.
|
1024 |
*/
|
1025 |
class WebcamLoader extends Thread |
1026 |
{ |
1027 |
final int WEBCAMLOADER_DELAY = 250; |
1028 |
final String IMAGE_PATH = "http://128.2.99.176/colonet.jpg"; |
1029 |
|
1030 |
URL imagePath;
|
1031 |
|
1032 |
MediaTracker mt;
|
1033 |
BufferedImage image;
|
1034 |
Random rand;
|
1035 |
|
1036 |
public WebcamLoader (JApplet applet) |
1037 |
{ |
1038 |
super("ColonetWebcamLoader"); |
1039 |
mt = new MediaTracker(applet); |
1040 |
ImageIO.setUseCache(false); |
1041 |
rand = new Random(); |
1042 |
} |
1043 |
|
1044 |
public void run () |
1045 |
{ |
1046 |
while (true) { |
1047 |
try {
|
1048 |
Thread.sleep(WEBCAMLOADER_DELAY);
|
1049 |
if (image != null) |
1050 |
image.flush(); |
1051 |
System.gc();
|
1052 |
try {
|
1053 |
imagePath = new URL(IMAGE_PATH + "?rand=" + rand.nextInt(100000)); |
1054 |
} catch (MalformedURLException e) { |
1055 |
System.out.println("Malformed URL: could not form URL from: [" + IMAGE_PATH + "]\n"); |
1056 |
} |
1057 |
image = ImageIO.read(imagePath);
|
1058 |
// The MediaTracker waitForID pauses the thread until the image is loaded.
|
1059 |
// We don't want to display a half-downloaded image.
|
1060 |
mt.addImage(image, 1);
|
1061 |
mt.waitForID(1);
|
1062 |
mt.removeImage(image); |
1063 |
// Save
|
1064 |
panelWebcam.setImage(image); |
1065 |
} catch (InterruptedException e) { |
1066 |
return;
|
1067 |
} catch (java.security.AccessControlException e) {
|
1068 |
csi.warn("Could not load webcam.\n" + e);
|
1069 |
return;
|
1070 |
} catch (IOException e) { |
1071 |
getInfoPanel().append("IOException while trying to load image.");
|
1072 |
} |
1073 |
} |
1074 |
} |
1075 |
} |
1076 |
|
1077 |
/*
|
1078 |
* VectorController class
|
1079 |
* Manages robot motion control graphically
|
1080 |
*/
|
1081 |
class VectorController extends GraphicsPanel implements MouseListener, MouseMotionListener { |
1082 |
int x, y, cx, cy;
|
1083 |
final int WIDTH, HEIGHT; |
1084 |
final int SIDE; |
1085 |
final int BOT_SIZE = 70; |
1086 |
final int WHEEL_SIZE = 15; |
1087 |
|
1088 |
public VectorController (Image img) { |
1089 |
super (img);
|
1090 |
WIDTH = img.getWidth(null);
|
1091 |
HEIGHT = img.getHeight(null);
|
1092 |
cx = WIDTH/2;
|
1093 |
cy = HEIGHT/2;
|
1094 |
x = cx; |
1095 |
y = cy; |
1096 |
if (WIDTH < HEIGHT) {
|
1097 |
SIDE = WIDTH; |
1098 |
} else {
|
1099 |
SIDE = HEIGHT; |
1100 |
} |
1101 |
this.addMouseListener(this); |
1102 |
this.addMouseMotionListener(this); |
1103 |
} |
1104 |
|
1105 |
public void setPoint (int x, int y) { |
1106 |
if (isValidPoint(x, y)) {
|
1107 |
this.x = x;
|
1108 |
this.y = y;
|
1109 |
} |
1110 |
} |
1111 |
|
1112 |
public boolean isValidPoint (int x, int y) { |
1113 |
double xsq = Math.pow(1.0*(x - cx)/(SIDE/2), 2); |
1114 |
double ysq = Math.pow(1.0*(y - cy)/(SIDE/2), 2); |
1115 |
return (xsq + ysq <= 1); |
1116 |
} |
1117 |
|
1118 |
public void notifyMouseEvent (MouseEvent e, boolean send) { |
1119 |
if (!isValidPoint(e.getX(), e.getY())) {
|
1120 |
return;
|
1121 |
} |
1122 |
setPoint(e.getX(), e.getY()); |
1123 |
repaint(); |
1124 |
if (send) {
|
1125 |
Runnable r = new Runnable () { |
1126 |
public void run () { |
1127 |
sendToServer(); |
1128 |
} |
1129 |
}; |
1130 |
(new Thread(r)).start(); |
1131 |
} |
1132 |
} |
1133 |
|
1134 |
public void mouseExited(MouseEvent e) { |
1135 |
} |
1136 |
public void mouseEntered(MouseEvent e) { |
1137 |
} |
1138 |
public void mouseReleased(MouseEvent e) { |
1139 |
this.notifyMouseEvent(e, true); |
1140 |
} |
1141 |
public void mouseClicked(MouseEvent e) { |
1142 |
this.notifyMouseEvent(e, false); |
1143 |
} |
1144 |
public void mousePressed(MouseEvent e) { |
1145 |
} |
1146 |
public void mouseDragged(MouseEvent e) { |
1147 |
vectorController.notifyMouseEvent(e, false);
|
1148 |
} |
1149 |
public void mouseMoved(MouseEvent e) { |
1150 |
} |
1151 |
|
1152 |
public int getSpeed () { |
1153 |
int dx = x - cx;
|
1154 |
int dy = y - cy;
|
1155 |
int s = (int) Math.sqrt( Math.pow(dx, 2) + Math.pow(dy, 2) ); |
1156 |
int maxspeed = SIDE/2; |
1157 |
return s * 512 / SIDE; |
1158 |
} |
1159 |
|
1160 |
/**
|
1161 |
* Returns the angle of the control vector in positive degrees west of north,
|
1162 |
* or negative degrees east of north, whichever is less than or equal to
|
1163 |
* 180 degrees total.
|
1164 |
*/
|
1165 |
public int getAngle () { |
1166 |
int dx = x - cx;
|
1167 |
int dy = cy - y;
|
1168 |
// find reference angle in radians
|
1169 |
double theta = Math.atan2(Math.abs(dx), Math.abs(dy)); |
1170 |
// transform to degrees
|
1171 |
theta = theta * 180 / Math.PI; |
1172 |
// adjust for quadrant
|
1173 |
if (dx < 0 && dy < 0) |
1174 |
theta = 90 + theta;
|
1175 |
else if (dx < 0 && dy >= 0) |
1176 |
theta = 90 - theta;
|
1177 |
else if (dx >= 0 && dy < 0) |
1178 |
theta = -90 - theta;
|
1179 |
else
|
1180 |
theta = -90 + theta;
|
1181 |
return (int) theta; |
1182 |
} |
1183 |
|
1184 |
public int getMotorL () { |
1185 |
if (getSpeed() == 0) |
1186 |
return 0; |
1187 |
int dx = x - cx;
|
1188 |
int dy = (cy - y) * 255 / getSpeed(); |
1189 |
int val = 0; |
1190 |
// Dependent on quadrant
|
1191 |
if (dx < 0 && dy < 0) |
1192 |
val = -255;
|
1193 |
else if (dx < 0 && dy >= 0) |
1194 |
val = dy * 1024 / SIDE - 255; |
1195 |
else if (dx >= 0 && dy < 0) |
1196 |
val = dy * 1024 / SIDE + 255; |
1197 |
else
|
1198 |
val = 255;
|
1199 |
// Normalize to 0-255
|
1200 |
return val * getSpeed() / 255; |
1201 |
} |
1202 |
|
1203 |
public int getMotorR () { |
1204 |
if (getSpeed() == 0) |
1205 |
return 0; |
1206 |
int dx = x - cx;
|
1207 |
int dy = (cy - y) * 255 / getSpeed(); |
1208 |
int val = 0; |
1209 |
// Dependent on quadrant
|
1210 |
if (dx < 0 && dy < 0) |
1211 |
val = dy * 1024 / SIDE + 255; |
1212 |
else if (dx < 0 && dy >= 0) |
1213 |
val = 255;
|
1214 |
else if (dx >= 0 && dy < 0) |
1215 |
val = -255;
|
1216 |
else
|
1217 |
val = dy * 1024 / SIDE - 255; |
1218 |
// Normalize to 0-255
|
1219 |
return val * getSpeed() / 255; |
1220 |
} |
1221 |
|
1222 |
private int eliminateDeadZone (int x) { |
1223 |
final int START = 150; |
1224 |
int val;
|
1225 |
if (x == 0) |
1226 |
return 0; |
1227 |
if (x > 0) |
1228 |
val = (int) ((1 - 1.0 * START / 255) * x + START); |
1229 |
else
|
1230 |
val = (int) ((1 - 1.0 * START / 255) * x - START); |
1231 |
return val;
|
1232 |
|
1233 |
} |
1234 |
|
1235 |
public void paint (Graphics g) { |
1236 |
// Clear image
|
1237 |
g.setColor(Color.BLACK);
|
1238 |
g.fillRect(0, 0, WIDTH, HEIGHT); |
1239 |
((Graphics2D)g).setStroke(new BasicStroke(1)); |
1240 |
|
1241 |
// Motor indicators
|
1242 |
int motor1 = getMotorL() * BOT_SIZE / 512; |
1243 |
int motor2 = getMotorR() * BOT_SIZE / 512; |
1244 |
g.setColor(Color.YELLOW);
|
1245 |
if (motor1 < 0) |
1246 |
g.fillRect(cx-BOT_SIZE/2 - WHEEL_SIZE, cy, WHEEL_SIZE, -motor1);
|
1247 |
else
|
1248 |
g.fillRect(cx-BOT_SIZE/2 - WHEEL_SIZE, cy-motor1, WHEEL_SIZE, motor1);
|
1249 |
if (motor2 < 0) |
1250 |
g.fillRect(cx+BOT_SIZE/2, cy, WHEEL_SIZE, -motor2);
|
1251 |
else
|
1252 |
g.fillRect(cx+BOT_SIZE/2, cy-motor2, WHEEL_SIZE, motor2);
|
1253 |
|
1254 |
// Watermark
|
1255 |
g.setColor(Color.GRAY);
|
1256 |
g.drawOval(cx-BOT_SIZE/2, cy-BOT_SIZE/2, BOT_SIZE, BOT_SIZE); |
1257 |
g.drawRect(cx-BOT_SIZE/2 - WHEEL_SIZE, cy-BOT_SIZE/2, WHEEL_SIZE, BOT_SIZE); |
1258 |
g.drawRect(cx+BOT_SIZE/2, cy-BOT_SIZE/2, WHEEL_SIZE, BOT_SIZE); |
1259 |
|
1260 |
// Targeting circle
|
1261 |
g.setColor(Color.RED);
|
1262 |
g.drawOval(cx-SIDE/2, cy-SIDE/2, SIDE, SIDE); |
1263 |
((Graphics2D)g).setStroke(new BasicStroke(2)); |
1264 |
|
1265 |
// Vector Line
|
1266 |
g.setColor(Color.GREEN);
|
1267 |
g.drawLine(cx, cy, x, y); |
1268 |
g.fillOval(x-3, y-3, 6, 6); |
1269 |
} |
1270 |
|
1271 |
public void setMaxForward () { |
1272 |
setPoint(cx, cy - (SIDE/2) + 1); |
1273 |
} |
1274 |
|
1275 |
public void setMaxReverse () { |
1276 |
setPoint(cx, cy + (SIDE/2) - 1); |
1277 |
} |
1278 |
|
1279 |
public void setMaxLeft () { |
1280 |
setPoint(cx - (SIDE/2) + 1, cy); |
1281 |
} |
1282 |
|
1283 |
public void setMaxRight () { |
1284 |
setPoint(cx + (SIDE/2) - 1, cy); |
1285 |
} |
1286 |
|
1287 |
public void setZero () { |
1288 |
setPoint(cx, cy); |
1289 |
} |
1290 |
|
1291 |
public void sendToServer () { |
1292 |
// Determine destination ID
|
1293 |
String dest = ColonetServerInterface.GLOBAL_DEST;
|
1294 |
if (cmbRobotNum != null && cmbRobotNum.getSelectedIndex() > 0) { |
1295 |
dest = (String)cmbRobotNum.getSelectedItem();
|
1296 |
} |
1297 |
|
1298 |
if (csi == null) |
1299 |
return;
|
1300 |
|
1301 |
String motor1_string;
|
1302 |
String motor2_string;
|
1303 |
int motor1 = eliminateDeadZone(getMotorL());
|
1304 |
int motor2 = eliminateDeadZone(getMotorR());
|
1305 |
|
1306 |
if (motor1 > 0) { |
1307 |
motor1_string = " 1 " + motor1;
|
1308 |
} else {
|
1309 |
motor1_string = " 0 " + (-motor1);
|
1310 |
} |
1311 |
if (motor2 > 0) { |
1312 |
motor2_string = " 1 " + motor2;
|
1313 |
} else {
|
1314 |
motor2_string = " 0 " + (-motor2);
|
1315 |
} |
1316 |
|
1317 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + motor1_string, dest); |
1318 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + motor2_string, dest); |
1319 |
|
1320 |
/*
|
1321 |
// Directional commands
|
1322 |
if (x > cx && y == cy) { //move right
|
1323 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 200", dest);
|
1324 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 200", dest);
|
1325 |
} else if (x < cx && y == cy) { //move left
|
1326 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 200", dest);
|
1327 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 200", dest);
|
1328 |
} else if (x == cx && y > cy) { //move forward
|
1329 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 225", dest);
|
1330 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 225", dest);
|
1331 |
} else if (x == cx && y < cy) { //move backward
|
1332 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 225", dest);
|
1333 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 225", dest);
|
1334 |
} else if (x == cx && y == cy) { //stop!
|
1335 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 0", dest);
|
1336 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 0", dest);
|
1337 |
}
|
1338 |
*/
|
1339 |
|
1340 |
/*
|
1341 |
// Atomic Directional commands
|
1342 |
if (x > cx && y == cy) { //move right
|
1343 |
csi.sendData(ColonetServerInterface.MOVE_R, dest);
|
1344 |
} else if (x < cx && y == cy) { //move left
|
1345 |
csi.sendData(ColonetServerInterface.MOVE_L, dest);
|
1346 |
} else if (x == cx && y > cy) { //move forward
|
1347 |
csi.sendData(ColonetServerInterface.MOVE_F, dest);
|
1348 |
} else if (x == cx && y < cy) { //move backward
|
1349 |
csi.sendData(ColonetServerInterface.MOVE_B, dest);
|
1350 |
} else if (x == cx && y == cy) { //stop
|
1351 |
csi.sendData(ColonetServerInterface.MOTORS_OFF, dest);
|
1352 |
}
|
1353 |
*/
|
1354 |
} |
1355 |
|
1356 |
} |
1357 |
|
1358 |
|
1359 |
|
1360 |
} |