Project

General

Profile

Statistics
| Revision:

root / trunk / code / projects / colonet / client / Colonet.java @ 549

History | View | Annotate | Download (42.7 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
* The Colonet Graphical User Interface Applet for use locally and over an internet connection.
17
* @author Gregory Tress
18
*
19
* To generate javadoc on this file or other java files, use javadoc *.java -d doc, where doc
20
* is the name of the folder into which the files should be written.
21
*/
22
public class Colonet extends JApplet implements ActionListener, MouseInputListener, KeyListener, Runnable {
23

    
24
        // Used for images
25
        final int CANVAS_SIZE = 500;        //the applet may be slow if the canvas gets too large
26
        final int BUFFER = 50;
27
        final int RADIUS = 30;
28

    
29
        //Used for the robot controller
30
        final int VECTOR_CONTROLLER_HEIGHT = 220;
31
        final int VECTOR_CONTROLLER_WIDTH = 350;
32

    
33
        // Connection
34
        JTextField txtHost;
35
        JTextField txtPort;
36
        JButton btnConnect;
37
        JButton btnGetXBeeIDs;
38
        JLabel lblConnectionStatus;
39
        JTextArea txtMatrix;
40
        JTextArea txtInfo;
41
        JPanel panelConnect;
42
        JPanel panelServerInterface;
43
        Socket socket;
44
        OutputStreamWriter out;
45
        DataUpdater dataUpdater;
46

    
47
        // South
48
        JPanel panelSouth;
49
        JTextArea log;
50
        JScrollPane spLog;
51

    
52
        // Control
53
        JPanel panelControl;
54
        JTabbedPane tabPaneControl;
55
        JPanel panelRobotControl;
56
        JPanel panelRobotDirection;
57
        JPanel panelRobotDirectionButtons;
58
        JPanel panelRobotCommands;
59
        JButton btnF, btnB, btnL, btnR, btnActivate;
60
        JComboBox cmbRobotNum;
61
        JLabel lblBattery;
62
        JLabel lblSelected;
63
        BatteryIcon batteryIcon;
64
        JPanel panelBattery;
65
        VectorController vectorController;
66
        BufferedImage imageVectorControl;
67
        JButton btnAssignID;
68
        boolean setWaypoint;
69
        int setWaypointID;
70
        JButton btnCommand_MoveTo;
71
        JButton btnCommand_MoveAll;
72
        JButton btnCommand_StopTask;
73
        JButton btnCommand_ResumeTask;
74
        JButton btnCommand_ChargeNow;
75
        JButton btnCommand_StopCharging;
76

    
77
        // Task Manager
78
        JPanel panelTaskManager;
79
        JScrollPane spTaskManager;
80
        JPanel panelTaskManagerControls;
81
        JPanel panelTaskManagerControlsPriority;
82
        DefaultListModel taskListModel;
83
        JList taskList;
84
        JButton btnAddTask;
85
        JButton btnRemoveTask;
86
        JButton btnMoveTaskUp;
87
        JButton btnMoveTaskDown;
88
        JButton btnUpdateTasks;
89
        TaskAddWindow taskAddWindow;
90

    
91
        //Webcam
92
        WebcamPanel panelWebcam;
93
        GraphicsPanel panelGraph;
94
        GraphicsConfiguration gc;
95
        volatile BufferedImage image;
96
        volatile Graphics2D canvas;
97
        int cx, cy;
98
        JTabbedPane tabPaneMain;
99

    
100
        Font botFont;
101
        volatile int numBots;
102
        volatile int selectedBot;         //the user has selected this bot graphically
103
        volatile java.util.List <RobotIcon> robotIcons;         //contains boundary shapes around bots for click detection
104
        volatile int[] xbeeID;
105

    
106
        Colonet self = this;
107
        Thread paintThread;
108
        WebcamLoader webcamLoader;
109
        volatile ColonetServerInterface csi;
110

    
111
        public void init () {
112
                // Set the default look and feel - choose one
113
                //String laf = UIManager.getSystemLookAndFeelClassName();
114
                String laf = UIManager.getCrossPlatformLookAndFeelClassName();
115
                //String laf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
116
                try {
117
                        UIManager.setLookAndFeel(laf);
118
                } catch (UnsupportedLookAndFeelException exc) {
119
                        System.err.println ("Warning: UnsupportedLookAndFeel: " + laf);
120
                } catch (Exception exc) {
121
                        System.err.println ("Error loading " + laf + ": " + exc);
122
                }
123

    
124
                // We should invoke and wait to avoid browser display difficulties
125
                Runnable r = new Runnable() {
126
                        public void run() {
127
                                createAndShowGUI();
128
                        }
129
                };
130

    
131
                try {
132
                        SwingUtilities.invokeAndWait(r);
133
                } catch (InterruptedException e) {
134
                        //Not really sure why we would be in this situation
135
                        System.out.println("InterruptedException in init: " + e);
136
                } catch (java.lang.reflect.InvocationTargetException e) {
137
                        //This could happen for various reasons if there is a problem in createAndShowGUI
138
                        e.printStackTrace();
139
                }
140
        }
141

    
142
        public void destroy () {
143
                try { paintThread.interrupt(); } catch (Exception e) { }
144
        }
145

    
146
        private synchronized void createAndShowGUI () {
147
                // init graphical elements
148
                // Get the graphics configuration of the screen to create a buffer
149
                gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
150
                image = gc.createCompatibleImage(CANVAS_SIZE,CANVAS_SIZE);
151
                canvas = image.createGraphics();
152
                canvas.setStroke(new BasicStroke(2));         //set pen width
153
                panelGraph = new GraphicsPanel(image, false);         //set automatic double-buffering to false. we are doing it manually.
154
                panelWebcam = new WebcamPanel();
155
                tabPaneMain = new JTabbedPane();
156
                tabPaneMain.add(panelWebcam, "Webcam");
157
                //tabPaneMain.add(panelGraph, "Graph");
158

    
159
                // Calculate center of canvas
160
                cx = image.getWidth() / 2;
161
                cy = image.getHeight() / 2;
162

    
163
                // Set up robots
164
                botFont = new Font("Arial", Font.PLAIN, 14);
165
                numBots = 0;
166
                selectedBot = -1;
167
                robotIcons = new ArrayList <RobotIcon> ();
168

    
169
                // Connection area
170
                txtMatrix = new JTextArea();
171
                txtMatrix.setBorder(BorderFactory.createTitledBorder("Info"));
172
                txtInfo = new JTextArea();
173
                txtInfo.setBorder(BorderFactory.createTitledBorder("Info"));
174
                txtInfo.setEditable(false);
175
                txtHost = new JTextField(this.getDocumentBase().getHost());
176
                txtHost.setBorder(BorderFactory.createTitledBorder("Host"));
177
                txtPort = new JTextField("10123");
178
                txtPort.setBorder(BorderFactory.createTitledBorder("Port"));
179
                btnConnect = new JButton("Connect");
180
                btnGetXBeeIDs = new JButton("Get XBee IDs");
181
                getRootPane().setDefaultButton(btnConnect);
182
                lblConnectionStatus = new JLabel("Status: Offline");
183
                panelConnect = new JPanel();
184
                panelConnect.setLayout(new GridLayout(6,1));
185
                panelConnect.add(lblConnectionStatus);
186
                panelConnect.add(txtHost);
187
                panelConnect.add(txtPort);
188
                panelConnect.add(btnConnect);
189
                //panelConnect.add(btnGetXBeeIDs);
190
                panelServerInterface = new JPanel();
191
                panelServerInterface.setLayout(new GridLayout(2,1));
192
                panelServerInterface.add(panelConnect);
193
                panelServerInterface.add(txtMatrix);
194

    
195
                // Robot direction panel
196
                panelRobotDirection = new JPanel();
197
                panelRobotDirectionButtons = new JPanel();
198
                btnF = new JButton("^");
199
                btnB = new JButton("v");
200
                btnL = new JButton("<");
201
                btnR = new JButton(">");
202
                btnActivate = new JButton("o");
203
                panelRobotDirectionButtons.setLayout(new GridLayout(1,5));
204
                panelRobotDirectionButtons.add(btnActivate);
205
                panelRobotDirectionButtons.add(btnF);
206
                panelRobotDirectionButtons.add(btnB);
207
                panelRobotDirectionButtons.add(btnL);
208
                panelRobotDirectionButtons.add(btnR);
209

    
210
                imageVectorControl = gc.createCompatibleImage(VECTOR_CONTROLLER_WIDTH, VECTOR_CONTROLLER_HEIGHT);
211
                vectorController = new VectorController(imageVectorControl);
212
                panelRobotDirection.setLayout(new BorderLayout());
213
                panelRobotDirection.add(vectorController, BorderLayout.CENTER);
214
                panelRobotDirection.add(panelRobotDirectionButtons, BorderLayout.SOUTH);
215

    
216
                // Robot Control and Commands
217
                panelRobotCommands = new JPanel();
218
                panelRobotCommands.setLayout(new GridLayout(5,2));
219
                cmbRobotNum = new JComboBox();
220
                // Battery subset
221
                batteryIcon = new BatteryIcon(0);
222
                lblBattery = new JLabel(batteryIcon);
223
                lblSelected = new JLabel("None");
224
                // Command subset
225
                setWaypoint = false;
226
                setWaypointID = -1;
227
                btnAssignID = new JButton("Assign ID");
228
                btnCommand_MoveTo = new JButton("Move to ...");
229
                btnCommand_MoveAll = new JButton("Move all ...");
230
                btnCommand_StopTask = new JButton("Stop Current Task");
231
                btnCommand_ResumeTask = new JButton("Resume Current Task");
232
                btnCommand_ChargeNow = new JButton("Recharge Now");
233
                btnCommand_StopCharging = new JButton("Stop Recharging");
234
                panelRobotCommands.add(new JLabel("Select Robot to Control: "));
235
                panelRobotCommands.add(cmbRobotNum);
236
                panelRobotCommands.add(new JLabel("Battery Level: "));
237
                panelRobotCommands.add(lblBattery);
238
                panelRobotCommands.add(new JLabel("Selected Icon: "));
239
                panelRobotCommands.add(lblSelected);
240
                panelRobotCommands.add(btnAssignID);
241
                panelRobotCommands.add(new JLabel(""));
242
                panelRobotCommands.add(btnCommand_MoveTo);
243
                panelRobotCommands.add(btnCommand_MoveAll);
244
                //panelRobotCommands.add(btnCommand_StopTask);
245
                //panelRobotCommands.add(btnCommand_ResumeTask);
246
                //panelRobotCommands.add(btnCommand_ChargeNow);
247
                //panelRobotCommands.add(btnCommand_StopCharging);
248
                panelRobotControl = new JPanel();
249
                panelRobotControl.setLayout(new GridLayout(2,1));
250
                panelRobotControl.add(panelRobotDirection);
251
                panelRobotControl.add(panelRobotCommands);
252

    
253

    
254
                // Task Manager
255
                panelTaskManager = new JPanel();
256
                panelTaskManager.setLayout(new BorderLayout());
257
                taskListModel = new DefaultListModel();
258
                taskList = new JList(taskListModel);
259
                taskList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
260
                taskList.setSelectedIndex(0);
261
                spTaskManager = new JScrollPane(taskList);
262
                panelTaskManagerControls = new JPanel();
263
                panelTaskManagerControls.setLayout(new GridLayout(1,4));
264
                panelTaskManagerControlsPriority = new JPanel();
265
                panelTaskManagerControlsPriority.setLayout(new GridLayout(1,2));
266
                btnAddTask = new JButton("Add...");
267
                btnRemoveTask = new JButton("Remove");
268
                btnMoveTaskUp = new JButton("^");
269
                btnMoveTaskDown = new JButton("v");
270
                btnUpdateTasks = new JButton("Update");
271
                panelTaskManagerControlsPriority.add(btnMoveTaskUp);
272
                panelTaskManagerControlsPriority.add(btnMoveTaskDown);
273
                panelTaskManagerControls.add(btnAddTask);
274
                panelTaskManagerControls.add(btnRemoveTask);
275
                panelTaskManagerControls.add(btnUpdateTasks);
276
                panelTaskManagerControls.add(panelTaskManagerControlsPriority);
277
                panelTaskManager.add(spTaskManager, BorderLayout.CENTER);
278
                panelTaskManager.add(panelTaskManagerControls, BorderLayout.SOUTH);
279
                panelTaskManager.add(new JLabel("Current Task Queue"), BorderLayout.NORTH);
280
                taskAddWindow = new TaskAddWindow();
281

    
282
                // Message log
283
                log = new JTextArea();
284
                spLog = new JScrollPane(log, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
285
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
286
                spLog.setBorder(BorderFactory.createTitledBorder("Log"));
287
                spLog.setPreferredSize(new Dimension(0, 120));
288
                log.setEditable(false);
289

    
290
                // Main control mechanism
291
                panelControl = new JPanel();
292
                panelControl.setLayout(new GridLayout(1,1));
293
                tabPaneControl = new JTabbedPane(JTabbedPane.TOP);
294
                tabPaneControl.setPreferredSize(new Dimension(VECTOR_CONTROLLER_WIDTH, 0));
295
                tabPaneControl.addTab("Connection", panelServerInterface);
296
                tabPaneControl.addTab("Robots", panelRobotControl);
297
                //tabPaneControl.addTab("Tasks", panelTaskManager);
298
                panelControl.add(tabPaneControl);
299

    
300
                // Set up elements in the south
301
                panelSouth = new JPanel();
302
                panelSouth.setLayout(new GridLayout(1,2));
303
                //panelSouth.add(spLog);
304

    
305
                // Put all elements in the ContentPane
306
                this.getContentPane().setLayout(new BorderLayout());
307
                this.getContentPane().add(tabPaneMain, BorderLayout.CENTER);
308
                this.getContentPane().add(panelSouth, BorderLayout.SOUTH);
309
                this.getContentPane().add(panelControl, BorderLayout.EAST);
310
                this.setVisible(true);
311

    
312
                /* Add all listeners here */
313
                // Task Management
314
                btnAddTask.addActionListener(this);
315
                btnRemoveTask.addActionListener(this);
316
                btnMoveTaskUp.addActionListener(this);
317
                btnMoveTaskDown.addActionListener(this);
318
                btnUpdateTasks.addActionListener(this);
319
                // Robot Control
320
                btnF.addActionListener(this);
321
                btnB.addActionListener(this);
322
                btnL.addActionListener(this);
323
                btnR.addActionListener(this);
324
                btnF.addKeyListener(this);
325
                btnB.addKeyListener(this);
326
                btnL.addKeyListener(this);
327
                btnR.addKeyListener(this);
328
                btnActivate.addActionListener(this);
329
                btnActivate.addKeyListener(this);
330
                cmbRobotNum.addKeyListener(this);
331
                btnCommand_MoveTo.addActionListener(this);
332
                btnCommand_MoveAll.addActionListener(this);
333
                btnCommand_StopTask.addActionListener(this);
334
                btnCommand_ResumeTask.addActionListener(this);
335
                btnCommand_ChargeNow.addActionListener(this);
336
                btnCommand_StopCharging.addActionListener(this);
337
                // Other
338
                btnConnect.addActionListener(this);
339
                btnGetXBeeIDs.addActionListener(this);
340
                btnAssignID.addActionListener(this);
341
                panelWebcam.addMouseListener(this);
342
        }
343

    
344
        public void run () {
345
                while (true) {
346
                        repaint();
347
                        try {
348
                                Thread.sleep(90);
349
                        } catch (InterruptedException e) {
350
                                return;
351
                        }
352
                }
353
        }
354

    
355
        public void paint (Graphics g) {
356
                super.paint(g);
357
        }
358

    
359
        public void update (Graphics g) {
360
                paint(g);
361
        }
362

    
363
        /**
364
        * Gets the JTextArea used for storing the activity log. This method returns a reference to the
365
        * JTextArea that stores the log. The log can contain any activity that is revelant to the use
366
        * of the applet, and may optionally display debugging information.
367
        *
368
        * @return the JTextArea where BOM matrix information is stored.
369
        */
370
        public JTextArea getLog () {
371
                return log;
372
        }
373

    
374
        /**
375
        * Gets the JTextArea used for storing the BOM matrix data. This method returns a reference to the
376
        * JTextArea that stores the BOM matrix. The values in the matrix are stored as integers separated
377
        * by spaces, and the lines should be separated by a newline.
378
        *
379
        * @return the JTextArea where BOM matrix information is stored.
380
        */
381
        public JTextArea getMatrixInput () {
382
                return txtMatrix;
383
        }
384

    
385
        /**
386
        * Parses a String containing BOM matrix information.
387
        * The ColonetServerInterface receives lines of the BOM matrix.        (For encoding
388
        * information, see the ColonetServerInterface documentation.)         The entire matrix is passed
389
        * to the client when requested. This method takes a string of the form
390
        * "[command code] [command code] [number of robots] [data0] [data1] ..."
391
        * with tokens separated by spaces and containing no brackets.
392
        * The [command code]s are predefined values identifying this String as a BOM data
393
        * String, [number of robots] is an integer, and the values that follow are
394
        * the sensor readings of the robots in order, starting with robot 0.        Only [number of robots]^2
395
        * data entries will be read.        The matrix values are saved locally until the next String is parsed.
396
        *
397
        *
398
        * @param line the String containing BOM matrix information.
399
        * @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots]^2 data entries in the String
400
        */
401
        public void parseMatrix (String line) {
402
                txtMatrix.setText("");
403
                String [] str = line.split(" ");
404
                int num = Integer.parseInt(str[2]);
405
                for (int i = 0; i < num; i++) {
406
                        for (int j = 0; j < num; j++) {
407
                                String next = str[3 + i*num + j];
408
                                if (next.equals("-1")) {
409
                                        txtMatrix.append("-");
410
                                } else {
411
                                        txtMatrix.append(next);
412
                                }
413

    
414
                                if (j < num - 1) {
415
                                        txtMatrix.append(" ");
416
                                }
417
                        }
418

    
419
                        if (i < num - 1) {
420
                                txtMatrix.append("\n");
421
                        }
422
                }
423
                repaint();
424
        }
425

    
426
        public void connect () {
427
                if (csi != null)
428
                        return;
429
                csi = new ColonetServerInterface(this);
430
                csi.connect(txtHost.getText(), txtPort.getText());
431
                if (!csi.isReady()) {
432
                        csi = null;
433
                        return;
434
                }
435
                webcamLoader = new WebcamLoader(this);
436
                dataUpdater = new DataUpdater();
437
                dataUpdater.start();
438
                webcamLoader.start();
439
                btnConnect.setText("Disconnect");
440
                lblConnectionStatus.setText("Status: Connected");
441
        }
442

    
443
        public void disconnect () {
444
                lblConnectionStatus.setText("Status: Disconnecting...");
445
                btnConnect.setText("Connect");
446
                lblConnectionStatus.setText("Status: Disconnected");
447
                dataUpdater.interrupt();
448
                csi = null;
449
        }
450

    
451
        /**
452
        * Parses a String containing a task queue update.
453
        * Format is currently not specified.
454
        * This method currently does nothing.
455
        *
456
        * @param line the String containing task queue update information.
457
        */
458
        public void parseQueue (String line) {
459
                log.append("Got queue update\n");
460
                //TODO: display new queue data in tasks tab
461
        }
462

    
463
        /**
464
        * Parses a String containing XBee ID values.
465
        * The ColonetServerInterface receives Strings of XBee information.        (For encoding
466
        * information, see the ColonetServerInterface documentation.)         This method takes
467
        * a string of the form "[command code] [command code] [number of robots] [id0] [id1] ..."
468
        * with tokens separated by spaces and containing no brackets.
469
        * The [command code]s are predefined values identifying this String as an XBee
470
        * ID String, [number of robots] is an integer, and the values that follow are
471
        * the IDs of the robots in order, starting with robot 0.        Only [number of robots]
472
        * will be read.         The ID values are saved locally until the next String is parsed.
473
        * The purpose of having this list is to ensure that robots are properly identified for control purposes.
474
        * This keeps robot identification consistent between sessions and prevents arbitrary assignment.
475
        *
476
        * @param line the String containing XBee ID information.
477
        * @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots] IDs in the String
478
        * @see ColonetServerInterface#sendXBeeIDRequest()
479
        */
480
        public void parseXBeeIDs (String line) {
481
                String [] str = line.split(" ");
482
                int num = Integer.parseInt(str[2]);
483
                xbeeID = new int[num];
484
                for (int i = 0; i < num; i++) {
485
                        xbeeID[i] = Integer.parseInt(str[i+3]);
486
                }
487

    
488
                //update the list of robots to control
489
                //but save the old value first
490
                Object oldSelection = cmbRobotNum.getSelectedItem();
491
                cmbRobotNum.removeAllItems();
492
                cmbRobotNum.addItem(new String("         All         "));
493
                for (int i = 0; i < num; i++) {
494
                        cmbRobotNum.addItem(new String("" + xbeeID[i]));
495
                }
496
                cmbRobotNum.setSelectedItem(oldSelection);
497
                repaint();
498
        }
499

    
500
        /**
501
        * Parses a String containing battery information.
502
        * The ColonetServerInterface receives Strings of battery information.         (For encoding
503
        * information, see the ColonetServerInterface documentation.)         This method takes
504
        * a string of the form "[command code] [command code] [robot ID] [value]"
505
        * with tokens separated by spaces and containing no brackets.
506
        * The [command code]s are predefined values identifying this String as a battery
507
        * information String, [robot ID] is an integer, and [value] is a battery measurement.
508
        * This updates the batery information for a single robot.
509
        *
510
        *
511
        * @param line the String containing battery information.
512
        * @see ColonetServerInterface#sendBatteryRequest(int)
513
        */
514
        public void parseBattery (String line) {
515
                String [] str = line.split(" ");
516
                int botNum = Integer.parseInt(str[2]);
517
                int level = Integer.parseInt(str[3]);
518
                int selected = -1;
519
                try {
520
                        selected = Integer.parseInt((String)cmbRobotNum.getSelectedItem());
521
                } catch (Exception e) {
522
                        System.out.println("Exception in parseBattery.");
523
                }
524

    
525
                if (selected == botNum) {
526
                        batteryIcon.setLevel(level);
527
                }
528
                repaint();
529
        }
530

    
531
        /**
532
        * Parses a String containing visual robot position information along with
533
        * canonical ID assignments.
534
        */
535
        public void parsePositions (String line) {
536
                String [] str = line.split(" ");
537
                java.util.List <RobotIcon> newList = new ArrayList <RobotIcon> ();
538

    
539
                for (int i = 2; i < str.length; i+=3) {
540
                        int id = Integer.parseInt(str[i]);
541
                        int x = Integer.parseInt(str[i+1]);
542
                        int y = Integer.parseInt(str[i+2]);
543
                        RobotIcon newIcon = new RobotIcon(id, x, y);
544
                        if (newIcon.id >= 0) {
545
                                newIcon.color = Color.GREEN;
546
                        }
547
                        newList.add(newIcon);
548
                }
549
                robotIcons = newList;
550
                repaint();
551
        }
552

    
553
        //
554
        // MouseListener methods
555
        //
556
        public void mousePressed(MouseEvent e) {
557
                //Start a new Thread to handle the MouseEvent
558
                (new MouseHandler(e)).start();
559
        }
560
        public void mouseExited(MouseEvent e) {
561
        }
562
        public void mouseEntered(MouseEvent e) {
563
        }
564
        public void mouseReleased(MouseEvent e) {
565
        }
566
        public void mouseClicked(MouseEvent e) {
567
        }
568
        public void mouseDragged(MouseEvent e) {
569
        }
570
        public void mouseMoved(MouseEvent e) {
571
        }
572

    
573
        //
574
        // KeyListener methods
575
        //
576
        public void keyPressed (KeyEvent e) {
577
                //Start a new Thread to handle the KeyEvent
578
                (new KeyHandler(e)).start();
579
        }
580
        public void keyReleased (KeyEvent e) {
581
        }
582
        public void keyTyped (KeyEvent e) {
583
        }
584

    
585
        //
586
        // ActionListener method
587
        //
588
        public void actionPerformed (ActionEvent e) {
589
                // Start a new Thread to handle the ActionEvent
590
                (new ActionHandler(e)).start();
591
        }
592

    
593
        class MouseHandler extends Thread {
594
                MouseEvent e;
595

    
596
                public MouseHandler (MouseEvent event) {
597
                        super("MouseHandler");
598
                        this.e = event;
599
                }
600

    
601
                public void run () {
602
                        Point pt = panelWebcam.convertClick(e);
603

    
604
                        // If we are selecting a waypoint (destination) for a specific bot
605
                        if (setWaypoint && setWaypointID        >= 0) {
606
                                setWaypoint = false;
607
                                panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
608
                                if (selectedBot < 0) {
609
                                        return;
610
                                }
611

    
612
                                for (int i = 0; i < robotIcons.size(); i++) {
613
                                        RobotIcon r = robotIcons.get(i);
614
                                        if (r.id == selectedBot) {
615
                                                r.destx = pt.x;
616
                                                r.desty = pt.y;
617
                                                if (csi != null) {
618
                                                        csi.sendAbsoluteMove(r.id, r.destx, r.desty);
619
                                                }
620
                                        }
621
                                }
622

    
623
                                return;
624
                        }
625

    
626
                        // Right-click also means we are moving a robot
627
                        if (e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON3) {
628
                                if (selectedBot < 0) {
629
                                        return;
630
                                }
631

    
632
                                for (int i = 0; i < robotIcons.size(); i++) {
633
                                        RobotIcon r = robotIcons.get(i);
634
                                        if (r.id == selectedBot) {
635
                                                r.destx = pt.x;
636
                                                r.desty = pt.y;
637
                                                if (csi != null) {
638
                                                        csi.sendAbsoluteMove(r.id, r.destx, r.desty);
639
                                                }
640
                                        }
641
                                }
642

    
643
                                return;
644
                        }
645

    
646
                        // If we are setting all waypoints
647
                        if (setWaypoint) {
648
                                setWaypoint = false;
649
                                panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
650
                                for (int i = 0; i < robotIcons.size(); i++) {
651
                                        RobotIcon r = robotIcons.get(i);
652
                                        r.destx = pt.x;
653
                                        r.desty = pt.y;
654
                                }
655
                                
656
                                return;
657
                        }
658

    
659
                        // Otherwise, we are selecting a bot, or doing nothing
660
                        for (int i = 0; i < robotIcons.size(); i++) {
661
                                RobotIcon r = robotIcons.get(i);
662
                                if (r.contains(pt.x, pt.y)) {
663
                                        selectedBot = r.id;
664
                                        lblSelected.setText("" + r.id);
665
                                        // Try to select the clicked bot, if its XBee ID is detected.
666
                                        for (int j = 1; j < cmbRobotNum.getItemCount(); j++) {
667
                                                if (Integer.parseInt(cmbRobotNum.getItemAt(j).toString()) == selectedBot) {
668
                                                        cmbRobotNum.setSelectedIndex(j);
669
                                                }
670
                                        }
671
                                        return;
672
                                }
673
                        }
674

    
675
                        repaint();
676
                }
677
        }
678

    
679
        class KeyHandler extends Thread {
680
                KeyEvent e;
681

    
682
                public KeyHandler (KeyEvent event) {
683
                        super("KeyHandler");
684
                        this.e = event;
685
                }
686

    
687
                public void run () {
688
                        int code = e.getKeyCode();
689
                        if (code == KeyEvent.VK_UP) {
690
                                vectorController.setMaxForward();
691
                                vectorController.sendToServer();
692
                        } else if (code == KeyEvent.VK_DOWN) {
693
                                vectorController.setMaxReverse();
694
                                vectorController.sendToServer();
695
                        } else if (code == KeyEvent.VK_LEFT) {
696
                                vectorController.setMaxLeft();
697
                                vectorController.sendToServer();
698
                        } else if (code == KeyEvent.VK_RIGHT) {
699
                                vectorController.setMaxRight();
700
                                vectorController.sendToServer();
701
                        } else if (code == KeyEvent.VK_S) {
702
                                vectorController.setZero();
703
                                vectorController.sendToServer();
704
                        }
705
                        repaint();
706
                }
707
        }
708

    
709
        class ActionHandler extends Thread {
710
                ActionEvent e;
711

    
712
                public ActionHandler (ActionEvent event) {
713
                        super("ActionHandler");
714
                        this.e = event;
715
                }
716

    
717
                public void run () {
718
                        Object source = e.getSource();
719

    
720
                        // General Actions
721
                        if (source == btnConnect) {
722
                                if (csi == null) {
723
                                        connect();
724
                                } else {
725
                                        disconnect();
726
                                }
727
                        } else if (source == btnGetXBeeIDs) {
728
                                csi.sendXBeeIDRequest();
729
                        } else if (source == btnAssignID) {
730
                                String message;
731
                                int curID = selectedBot;
732
                                if (curID < 0) {
733
                                        message = "That robot is unidentified. Please specify its ID.";
734
                                } else {
735
                                        message = "That robot has ID " + curID + ". You may reassign it now.";
736
                                }
737
                                String result = JOptionPane.showInputDialog(self, message, "Robot Identification", JOptionPane.QUESTION_MESSAGE);
738
                                if (result == null) {
739
                                        return;
740
                                }
741
                                int newID = -1;
742
                                try {
743
                                        newID = Integer.parseInt(result);
744
                                } catch (Exception ex) {
745
                                        csi.warn("Invalid ID.");
746
                                        return;
747
                                }
748
                                // Assign new ID and update display
749
                                if (csi != null) {
750
                                        csi.sendIDAssignment(curID, newID);
751
                                }
752
                                for (int i = 0; i < robotIcons.size(); i++) {
753
                                        RobotIcon r = robotIcons.get(i);
754
                                        if (r.id == curID) {
755
                                                r.id = newID;
756
                                                r.color = Color.GREEN;
757
                                                break;
758
                                        }
759
                                }
760
                                lblSelected.setText("" + newID);
761
                        } else if (source == btnF) { // Robot Movement Controls
762
                                vectorController.setMaxForward();
763
                                vectorController.sendToServer();
764
                        } else if (source == btnB) {
765
                                vectorController.setMaxReverse();
766
                                vectorController.sendToServer();
767
                        } else if (source == btnL) {
768
                                vectorController.setMaxLeft();
769
                                vectorController.sendToServer();
770
                        } else if (source == btnR) {
771
                                vectorController.setMaxRight();
772
                                vectorController.sendToServer();
773
                        } else if (source == btnActivate) {
774
                                vectorController.setZero();
775
                                vectorController.sendToServer();
776
                        } else if (source == btnCommand_MoveTo) { // Robot Commands (non-movement)
777
                                if (selectedBot < 0) {
778
                                        return;
779
                                }
780
                                panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
781
                                setWaypoint = true;
782
                                setWaypointID = selectedBot;
783
                        } else if (source == btnCommand_MoveAll) {
784
                                panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
785
                                setWaypoint = true;
786
                                setWaypointID = -1;
787
                        } else if (source == btnCommand_StopTask) {
788

    
789
                        } else if (source == btnCommand_ResumeTask) {
790

    
791
                        } else if (source == btnCommand_ChargeNow) {
792

    
793
                        } else if (source == btnCommand_StopCharging) {
794

    
795
                        } else if (source == btnAddTask) { // Queue Management
796
                                taskAddWindow.prompt();
797
                        } else if (source == btnRemoveTask) {
798
                                if (taskList.getSelectedIndex() >= 0) {
799
                                        csi.sendQueueRemove(taskList.getSelectedIndex());
800
                                }
801
                                csi.sendQueueUpdate();
802
                        } else if (source == btnMoveTaskUp) {
803
                                csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() - 1);
804
                                csi.sendQueueUpdate();
805
                        } else if (source == btnMoveTaskDown) {
806
                                csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() + 1);
807
                                csi.sendQueueUpdate();
808
                        } else if (source == btnUpdateTasks) {
809
                                csi.sendQueueUpdate();
810
                        }
811

    
812
                        repaint();
813
                }
814
        }
815

    
816
        /*
817
        * DataUpdater thread.
818
        *                The purpose of this thread is to request data from the server at regular intervals.
819
        *
820
        */
821
        class DataUpdater extends Thread {
822
                final int DATAUPDATER_DELAY = 250;
823

    
824
                public DataUpdater () {
825
                        super("Colonet DataUpdater");
826
                }
827

    
828
                public void run () {
829
                        String line;
830
                        while (true) {
831
                                try {
832
                                        //request more data
833
                                        if (csi != null && csi.isReady()) {
834
                                                csi.sendPositionRequest();
835
                                                csi.sendXBeeIDRequest();
836
                                                if (cmbRobotNum.getSelectedIndex() > 0) {
837
                                                        String sel = (String) cmbRobotNum.getSelectedItem();
838
                                                        int num = Integer.parseInt(sel);
839
                                                        csi.sendBatteryRequest(num);
840
                                                }
841
                                        }
842
                                        Thread.sleep(DATAUPDATER_DELAY);
843
                                } catch (InterruptedException e) {
844
                                        return;
845
                                }
846
                        }
847
                }
848
        }
849

    
850
        /*
851
        * GraphicsPanel class
852
        * An extension of JPanel, designed for holding an image that will be repainted regularly.
853
        */
854
        class GraphicsPanel extends JPanel {
855
                protected Image img;
856

    
857
                public GraphicsPanel (Image img) {
858
                        this(img, true);
859
                }
860

    
861
                public GraphicsPanel (Image img, boolean isDoubleBuffered) {
862
                        super(isDoubleBuffered);
863
                        this.img = img;
864
                }
865

    
866
                public void paint (Graphics g) {
867
                        // Place the buffered image on the screen, inside the panel
868
                        g.drawImage(img, 0, 0, Color.WHITE, this);
869
                }
870
        }
871

    
872
        /*
873
        * WebcamPanel class
874
        * Enables more efficient image handling in a component-controlled environment
875
        */
876
        class WebcamPanel extends JPanel {
877
                int BORDER = 16;        // this is arbitrary. it makes the image look nice inside a border.
878
                int BOT_RADIUS = 40;
879
                volatile BufferedImage img;
880
                BufferedImage buffer;
881

    
882
                public WebcamPanel () {
883
                        super(true);
884
                }
885

    
886
                public synchronized void setImage (BufferedImage newimg) {
887
                        if (img != null) {
888
                                img.flush();
889
                        }
890
                        System.gc();
891
                        img = newimg;
892
                        repaint();
893
                }
894

    
895
                public synchronized void paint (Graphics g) {
896
                        if (img == null) {
897
                                return;
898
                        }
899

    
900
                        // Calculate scaling
901
                        int maxWidth = getWidth() - 2*BORDER;
902
                        int maxHeight = getHeight() - 2*BORDER;
903
                        double widthRatio = 1.0 * maxWidth / img.getWidth();
904
                        double heightRatio = 1.0 * maxHeight / img.getHeight();
905
                        double scale = 0;
906
                        int newWidth = 0;
907
                        int newHeight = 0;
908
                        int x = 0;
909
                        int y = 0;
910

    
911
                        if (widthRatio > heightRatio) {         //height is the limiting factor
912
                                scale = heightRatio;
913
                                newHeight = maxHeight;
914
                                newWidth = (int) (img.getWidth() * scale);
915
                                y = BORDER;
916
                                x = (maxWidth - newWidth) / 2 + BORDER;
917
                        } else {        //width is the limiting factor
918
                                scale = widthRatio;
919
                                newWidth = maxWidth;
920
                                newHeight = (int) (img.getHeight() * scale);
921
                                x = BORDER;
922
                                y = (maxHeight - newHeight) / 2 + BORDER;
923
                        }
924

    
925
                        // Draw everything onto the buffer
926
                        buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
927
                        Graphics2D bufferedGraphics = (Graphics2D)buffer.getGraphics();
928
                        bufferedGraphics.setColor(Color.GRAY);
929
                        bufferedGraphics.fillRect(0, 0, this.getWidth(), this.getHeight());
930
                        Image imgScaled = img.getScaledInstance(newWidth, newHeight, Image.SCALE_FAST);
931
                        bufferedGraphics.drawImage(imgScaled, x, y, this);
932

    
933

    
934
                        // Draw Identifiers and battery levels
935
                        if (robotIcons != null) {
936
                                bufferedGraphics.setStroke(new BasicStroke(2));
937
                                for (int i = 0; i < robotIcons.size(); i++) {
938
                                        RobotIcon r = robotIcons.get(i);
939
                                        bufferedGraphics.setColor(r.color);
940
                                        // Identifier circle
941
                                        int px = (int) (x + r.x * scale);
942
                                        int py = (int) (y + r.y * scale);
943
                                        bufferedGraphics.drawOval(px-RADIUS, py-RADIUS, 2*r.RADIUS, 2*r.RADIUS);
944
                                        // Battery
945
                                        //if (r.battery >= 0) {
946
                                                bufferedGraphics.setColor(Color.GREEN);
947
                                                bufferedGraphics.fillRect(px+20, py+20, 30, 10);
948
                                                bufferedGraphics.setColor(Color.BLACK);
949
                                                bufferedGraphics.drawRect(px+20, py+20, 50, 10);
950
                                        //}
951
                                        // If the robot has a destination, draw the vector
952
                                        if (r.destx >= 0) {
953
                                                bufferedGraphics.drawLine(px, py, (int)(x + r.destx * scale), (int)(y + r.desty * scale));
954
                                        }
955
                                }
956
                        }
957

    
958
                        // Identify currently-selected robot
959
                        for (int i = 0; i < robotIcons.size(); i++) {
960
                                RobotIcon r = robotIcons.get(i);
961
                                if (r.id == selectedBot) {
962
                                        int px = (int) (x + r.x * scale);
963
                                        int py = (int) (y + r.y * scale);
964
                                        bufferedGraphics.setColor(Color.BLACK);
965
                                        bufferedGraphics.drawOval(px-RADIUS-6, py-RADIUS-6, 2*r.RADIUS+12, 2*r.RADIUS+12);
966
                                }
967
                        }
968

    
969
                        //Display buffered content
970
                        g.drawImage(buffer, 0, 0, this);
971
                }
972

    
973
                /*
974
                * Convert a click on the webcam panel to a coordinate that is consistent with the
975
                * original size of the image that the panel contains.
976
                */
977
                public Point convertClick (MouseEvent e) {
978
                        if (img == null) {
979
                                return new Point(e.getX(), e.getY());
980
                        }
981

    
982
                        // Calculate scaling
983
                        int clickx = e.getX();
984
                        int clicky = e.getY();
985
                        int maxWidth = getWidth() - 2*BORDER;
986
                        int maxHeight = getHeight() - 2*BORDER;
987
                        double widthRatio = 1.0 * maxWidth / img.getWidth();
988
                        double heightRatio = 1.0 * maxHeight / img.getHeight();
989
                        double scale = 0;
990
                        int newWidth = 0;
991
                        int newHeight = 0;
992
                        int px = 0;
993
                        int py = 0;
994

    
995
                        if (widthRatio > heightRatio) {         //height is the limiting factor
996
                                scale = heightRatio;
997
                                newHeight = maxHeight;
998
                                newWidth = (int) (img.getWidth() * scale);
999
                                py = clicky - BORDER;
1000
                                px = clickx - BORDER - (maxWidth - newWidth) / 2;
1001
                        } else {        //width is the limiting factor
1002
                                scale = widthRatio;
1003
                                newWidth = maxWidth;
1004
                                newHeight = (int) (img.getHeight() * scale);
1005
                                px = clickx - BORDER;
1006
                                py = clicky - BORDER - (maxHeight - newHeight) / 2;
1007
                        }
1008
                        py = (int) (py / scale);
1009
                        px = (int) (px / scale);
1010

    
1011
                        txtMatrix.setText("(" + clickx + "," + clicky + ") => (" + px + "," + py + ")");
1012
                        return new Point(px, py);
1013
                }
1014
        }
1015

    
1016
        /*
1017
        * WebcamLoader class
1018
        * Handles the loading of the webcam image.
1019
        */
1020
        class WebcamLoader extends Thread
1021
        {
1022
                final int WEBCAMLOADER_DELAY = 400;
1023
                final String IMAGE_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet.jpg";
1024

    
1025
                URL imagePath;
1026

    
1027
                MediaTracker mt;
1028
                BufferedImage image;
1029
                Random rand;
1030

    
1031
                public WebcamLoader (JApplet applet)
1032
                {
1033
                        super("ColonetWebcamLoader");
1034
                        mt = new MediaTracker(applet);
1035
                        ImageIO.setUseCache(false);
1036
                        rand = new Random();
1037
                }
1038

    
1039
                public void run ()
1040
                {
1041
                        while (true) {
1042
                                try {
1043
                                        Thread.sleep(WEBCAMLOADER_DELAY);
1044
                                        if (image != null)
1045
                                                image.flush();
1046
                                        System.gc();
1047
                                        try {
1048
                                                imagePath = new URL(IMAGE_PATH + "?rand=" + rand.nextInt(50000));
1049
                                        } catch (MalformedURLException e) {
1050
                                                System.out.println("Malformed URL: could not form URL from: [" + IMAGE_PATH + "]\n");
1051
                                        }
1052
                                        image = ImageIO.read(imagePath);
1053
                                        // The MediaTracker waitForID pauses the thread until the image is loaded.
1054
                                        // We don't want to display a half-downloaded image.
1055
                                        mt.addImage(image, 1);
1056
                                        mt.waitForID(1);
1057
                                        mt.removeImage(image);
1058
                                        // Save
1059
                                        panelWebcam.setImage(image);
1060
                                } catch (InterruptedException e) {
1061
                                        return;
1062
                                } catch (java.security.AccessControlException e) {
1063
                                        csi.warn("Could not load webcam.\n" + e);
1064
                                        return;
1065
                                } catch (IOException e) {
1066
                                        log.append("IOException while trying to load image.");
1067
                                }
1068
                        }
1069
                }
1070
        }
1071

    
1072
        /*
1073
        * VectorController class
1074
        * Manages robot motion control graphically
1075
        */
1076
        class VectorController extends GraphicsPanel implements MouseListener, MouseMotionListener {
1077
                int x, y, cx, cy;
1078
                int width, height;
1079
                int side;
1080

    
1081
                public VectorController (Image img) {
1082
                        super (img);
1083
                        width = img.getWidth(null);
1084
                        height = img.getHeight(null);
1085
                        cx = img.getWidth(null)/2;
1086
                        cy = img.getHeight(null)/2;
1087
                        x = cx;
1088
                        y = cy;
1089
                        if (width < height) {
1090
                                side = width;
1091
                        } else {
1092
                                side = height;
1093
                        }
1094
                        this.addMouseListener(this);
1095
                        this.addMouseMotionListener(this);
1096
                }
1097

    
1098
                public void setPoint (int x, int y) {
1099
                        if (isValidPoint(x, y)) {
1100
                                this.x = x;
1101
                                this.y = y;
1102
                                repaint();
1103
                        }
1104
                }
1105

    
1106
                public boolean isValidPoint (int x, int y) {
1107
                        double xterm = Math.pow(1.0*(x - cx)/(side/2), 2);
1108
                        double yterm = Math.pow(1.0*(y - cy)/(side/2), 2);
1109
                        return (xterm + yterm <= 1);
1110
                }
1111

    
1112
                public void notifyMouseEvent (MouseEvent e, boolean send) {
1113
                        if (!isValidPoint(e.getX(), e.getY())) {
1114
                                return;
1115
                        }
1116

    
1117
                        vectorController.setPoint(e.getX(), e.getY());
1118
                        vectorController.repaint();
1119
                        if (send) {
1120
                                vectorController.sendToServer();
1121
                        }
1122
                }
1123

    
1124
                public void mouseExited(MouseEvent e) {
1125
                }
1126
                public void mouseEntered(MouseEvent e) {
1127
                }
1128
                public void mouseReleased(MouseEvent e) {
1129
                        this.notifyMouseEvent(e, true);
1130
                }
1131
                public void mouseClicked(MouseEvent e) {
1132
                        this.notifyMouseEvent(e, false);
1133
                }
1134
                public void mousePressed(MouseEvent e) {
1135
                }
1136
                public void mouseDragged(MouseEvent e) {
1137
                        vectorController.notifyMouseEvent(e, false);
1138
                }
1139
                public void mouseMoved(MouseEvent e) {
1140
                }
1141

    
1142
                public int getSpeed () {
1143
                        int dx = x - cx;
1144
                        int dy = y - cy;
1145
                        int v = (int) Math.sqrt( Math.pow(dx, 2) + Math.pow(dy, 2) );
1146
                        return v;
1147
                }
1148

    
1149
                /**
1150
                * Returns the angle of the control vector in positive degrees west of north,
1151
                * or negative degrees east of north, whichever is less than or equal to
1152
                * 180 degrees total.
1153
                */
1154
                public int getAngle () {
1155
                        int dx = x - cx;
1156
                        int dy = cy - y;
1157
                        // find reference angle in radians
1158
                        double theta = Math.atan2(Math.abs(dx), Math.abs(dy));
1159
                        // transform to degrees
1160
                        theta = theta * 180 / Math.PI;
1161
                        // adjust for quadrant
1162
                        if (dx < 0 && dy < 0)
1163
                                theta = 90 + theta;
1164
                        else if (dx < 0 && dy >= 0)
1165
                                theta = 90 - theta;
1166
                        else if (dx >= 0 && dy < 0)
1167
                                theta = -90 - theta;
1168
                        else
1169
                                theta = -90 + theta;
1170
                        return (int) theta;
1171
                }
1172

    
1173
                public void paint (Graphics g) {
1174
                        g.setColor(Color.BLACK);
1175
                        g.fillRect(0, 0, width, height);
1176
                        ((Graphics2D)g).setStroke(new BasicStroke(1));
1177
                        g.setColor(Color.RED);
1178
                        g.drawOval(cx-side/2, cy-side/2, side, side);
1179
                        ((Graphics2D)g).setStroke(new BasicStroke(2));
1180
                        g.setColor(Color.GREEN);
1181
                        g.drawLine(cx, cy, x, y);
1182
                        g.fillOval(x-3, y-3, 6, 6);
1183
                }
1184

    
1185
                public void setMaxForward () {
1186
                        setPoint(cx, cy - (side/2) + 1);
1187
                }
1188

    
1189
                public void setMaxReverse () {
1190
                        setPoint(cx, cy + (side/2) - 1);
1191
                }
1192

    
1193
                public void setMaxLeft () {
1194
                        setPoint(cx - (side/2) + 1, cy);
1195
                }
1196

    
1197
                public void setMaxRight () {
1198
                        setPoint(cx + (side/2) - 1, cy);
1199
                }
1200

    
1201
                public void setZero () {
1202
                        setPoint(cx, cy);
1203
                }
1204

    
1205
                public void sendToServer () {
1206
                        System.out.println("Attempting to send angle = " + getAngle() + ", speed = " + getSpeed() + "");
1207
                        String dest = ColonetServerInterface.GLOBAL_DEST;
1208
                        if (cmbRobotNum != null && cmbRobotNum.getSelectedIndex() > 0) {
1209
                                dest = (String)cmbRobotNum.getSelectedItem();
1210
                        }
1211

    
1212
                        if (csi != null) {
1213
                                /*
1214
                                csi.sendData(ColonetServerInterface.MOVE + " " + getSpeed() + " " + getAngle(), dest);
1215
                                */
1216

    
1217
                                //Directional commands
1218
                                if (x > cx && y == cy) {        //move right
1219
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 200", dest);
1220
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 200", dest);
1221
                                } else if (x < cx && y == cy) {         //move left
1222
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 200", dest);
1223
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 200", dest);
1224
                                } else if (x == cx && y > cy) {         //move forward
1225
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 225", dest);
1226
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 225", dest);
1227
                                } else if (x == cx && y < cy) {         //move backward
1228
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 225", dest);
1229
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 225", dest);
1230
                                } else if (x == cx && y == cy) {        //stop!
1231
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 0", dest);
1232
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 0", dest);
1233
                                }
1234
                        }
1235
                }
1236

    
1237
        }
1238

    
1239
        /*
1240
        * TaskAddWindow class
1241
        * A window that provides a simple way to add tasks to a task queue.
1242
        */
1243
        class TaskAddWindow extends JFrame implements ActionListener, ListSelectionListener {
1244
                JPanel panelButtons;
1245
                JPanel panelParameters;
1246
                JPanel panelSouth;
1247
                JPanel panelSelection;
1248
                JButton btnSubmit;
1249
                JButton btnCancel;
1250
                DefaultListModel availableListModel;
1251
                JList availableList;
1252
                JScrollPane spAvailableTasks;
1253
                JTextArea txtDescription;
1254
                JTextField txtParameters;
1255

    
1256
                public TaskAddWindow () {
1257
                        super("Add a Task");
1258
                        super.setSize(500,500);
1259
                        super.setLayout(new BorderLayout());
1260

    
1261
                        // set up buttons
1262
                        btnSubmit = new JButton("Submit");
1263
                        btnCancel = new JButton("Cancel");
1264
                        panelButtons = new JPanel();
1265
                        panelButtons.setLayout(new FlowLayout());
1266
                        panelButtons.add(btnSubmit);
1267
                        panelButtons.add(btnCancel);
1268
                        this.getRootPane().setDefaultButton(btnSubmit);
1269

    
1270
                        // set up task list
1271
                        availableListModel = new DefaultListModel();
1272
                        availableListModel.addElement("Map the Environment");
1273
                        availableListModel.addElement("Clean Up Chemical Spill");
1274
                        availableListModel.addElement("Grow Plants");
1275
                        availableListModel.addElement("Save the Cheerleader");
1276
                        availableListModel.addElement("Save the World");
1277
                        availableList = new JList(availableListModel);
1278
                        availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
1279
                        availableList.setSelectedIndex(-1);
1280
                        spAvailableTasks = new JScrollPane(availableList);
1281
                        spAvailableTasks.setBorder(BorderFactory.createTitledBorder("Select A Task"));
1282
                        txtDescription = new JTextArea();
1283
                        txtDescription.setEditable(false);
1284
                        txtDescription.setLineWrap(true);
1285
                        txtDescription.setWrapStyleWord(true);
1286
                        txtDescription.setBorder(BorderFactory.createTitledBorder("Description"));
1287

    
1288
                        //set up parameter area
1289
                        panelParameters = new JPanel();
1290
                        panelParameters.setLayout(new BorderLayout());
1291
                        txtParameters = new JTextField();
1292
                        panelParameters.add(new JLabel("Optional parameters for this task: "), BorderLayout.WEST);
1293
                        panelParameters.add(txtParameters);
1294

    
1295
                        // assemble objects
1296
                        panelSelection = new JPanel();
1297
                        panelSelection.setLayout(new GridLayout(1,2));
1298
                        panelSelection.add(spAvailableTasks);
1299
                        panelSelection.add(txtDescription);
1300

    
1301
                        panelSouth = new JPanel();
1302
                        panelSouth.setLayout(new GridLayout(2,1));
1303
                        panelSouth.add(panelParameters);
1304
                        panelSouth.add(panelButtons);
1305

    
1306
                        this.getContentPane().add(panelSouth, BorderLayout.SOUTH);
1307
                        this.getContentPane().add(panelSelection, BorderLayout.CENTER);
1308
                        this.setLocationRelativeTo(null);
1309

    
1310
                        // add listeners here
1311
                        availableList.addListSelectionListener(this);
1312
                        btnSubmit.addActionListener(this);
1313
                        btnCancel.addActionListener(this);
1314
                }
1315

    
1316
                public void prompt () {
1317
                        this.setVisible(true);
1318
                }
1319

    
1320
                private String getDescription (int index) {
1321
                        if (index < 0)
1322
                                return "";
1323
                        switch (index) {
1324
                                case 0: return "SLAM and junk";
1325
                                case 1: return "I'm not sure this works";
1326
                                case 2: return "Push them into the light";
1327
                                case 3: return "...";
1328
                                case 4: return "...";
1329

    
1330
                                default: return "Task not recognized";
1331
                        }
1332
                }
1333

    
1334
                public void actionPerformed (ActionEvent e) {
1335
                        Object source = e.getSource();
1336
                        if (source == btnSubmit) {
1337
                                txtParameters.setText(txtParameters.getText().trim());
1338

    
1339

    
1340
                                this.setVisible(false);
1341
                        } else if (source == btnCancel) {
1342
                                this.setVisible(false);
1343
                        }
1344
                }
1345

    
1346
                public void valueChanged (ListSelectionEvent e) {
1347
                        int index = availableList.getSelectedIndex();
1348
                        if (index >= 0)
1349
                                txtDescription.setText(getDescription(index));
1350
                }
1351

    
1352
        }
1353

    
1354
        /*
1355
        *         BatteryIcon class
1356
        *         Graphical representation of battery level
1357
        */
1358
        class BatteryIcon implements Icon {
1359
                private int width;
1360
                private int height;
1361
                private int level;
1362

    
1363
                /**
1364
                * Constructs a new BatteryIcon with all default parameters.
1365
                * Default width and height are 50.
1366
                * Default level is 100.
1367
                */
1368
                public BatteryIcon(){
1369
                        this(100, 50, 50);
1370
                }
1371

    
1372
                /**
1373
                * Constructs a new BatteryIcon with default width and height, and with the specified level.
1374
                * Default width and height are 50.
1375
                */
1376
                public BatteryIcon(int startLevel){
1377
                        this(startLevel, 50, 50);
1378
                }
1379

    
1380
                /**
1381
                * Constructs a new BatteryIcon with the specified level, width, and height.
1382
                */
1383
                public BatteryIcon(int startLevel, int w, int h){
1384
                        level = startLevel;
1385
                        width = w;
1386
                        height = h;
1387
                }
1388

    
1389
                public void paintIcon(Component c, Graphics g, int x, int y) {
1390
                        Graphics2D g2d = (Graphics2D) g.create();
1391
                        //clear the background
1392
                        g2d.setColor(Color.WHITE);
1393
                        g2d.fillRect(x + 1, y + 1, width - 2, height - 2);
1394
                        //outline
1395
                        g2d.setColor(Color.BLACK);
1396
                        g2d.drawRect((int)(x + width*.3), y + 2, (int)(width*.4), height - 4);
1397
                        //battery life rectangle
1398

    
1399
                        if (level > 50)
1400
                                g2d.setColor(Color.GREEN);
1401
                        else if (level > 25)
1402
                                g2d.setColor(Color.YELLOW);
1403
                        else
1404
                                g2d.setColor(Color.RED);
1405

    
1406
                        int greenX = (int)(x + 1 + width*.3);
1407
                        int greenY = (int)((y+3) + Math.abs(level-100.0)*(height-6)/(100));
1408
                        int greenWidth = (int)(width*.4 - 2)+1;
1409
                        int greenHeight = 1+(int)(level-0.0)*(height-6)/(100);
1410
                        g2d.fillRect(greenX, greenY, greenWidth, greenHeight);
1411
                        //text
1412
                        g2d.setColor(Color.BLACK);
1413
                        g2d.drawString(level + "%", greenX + greenWidth/2 - 10, greenY + greenHeight/2 + 5);
1414

    
1415
                        g2d.dispose();
1416
                }
1417

    
1418
                /**
1419
                * Sets the battery level for this BatteryIcon. The level should be given in raw form, i.e. 0-255 directly
1420
                * from the robot. The value will be converted to a representative percentage automatically.
1421
                *
1422
                * @param newLevel the new battery reading from the robot that this BatteryIcon will display.
1423
                */
1424
                public void setLevel(int newLevel) {
1425
                        level = convert(newLevel);
1426
                        repaint();
1427
                        System.out.println("Updated level to " + level);
1428
                }
1429

    
1430
                public int getIconWidth() {
1431
                        return width;
1432
                }
1433

    
1434
                public int getIconHeight() {
1435
                        return height;
1436
                }
1437

    
1438
                /**
1439
                * Converts a robot battery reading into representable form.
1440
                * Readings from the robot are returned as raw values, 0-255. This method converts the reading into a value
1441
                * from 0 to 100 so that the practical remaining charge is represented.
1442
                *
1443
                * @param level The battery level as returned by the robot.
1444
                * @returns The representable battery percentage.
1445
                */
1446
                private int convert (int level) {
1447
                        // TODO: make this a forreals conversion.
1448
                        return (int) (100.0 * level / 170);
1449
                }
1450
        }
1451
}