Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (42.6 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
        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
                lblConnectionStatus.setText("Status: Connecting...");
428
                webcamLoader = new WebcamLoader(this);
429
                dataUpdater = new DataUpdater();
430
                csi = new ColonetServerInterface(this);
431
                csi.connect(txtHost.getText(), txtPort.getText());
432
                if (!csi.isReady()) {
433
                        lblConnectionStatus.setText("Status: Offline");
434
                } else {
435
                        btnConnect.setText("Disconnect");
436
                        lblConnectionStatus.setText("Status: Connected");
437
                        dataUpdater.start();
438
                        webcamLoader.start();
439
                }
440
        }
441

    
442
        public void disconnect () {
443
                lblConnectionStatus.setText("Status: Disconnecting...");
444
                dataUpdater.interrupt();
445
                csi.disconnect();
446
                csi = null;
447
                btnConnect.setText("Connect");
448
                lblConnectionStatus.setText("Status: Disconnected");
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
                                RobotIcon r = robotIcons.get(selectedBot);
613
                                r.destx = pt.x;
614
                                r.desty = pt.y;
615

    
616
                                if (csi != null) {
617
                                        csi.sendAbsoluteMove(r.id, r.destx, r.desty);
618

    
619
                                }
620
                                
621
                                return;
622
                        }
623

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

    
630
                                RobotIcon r = robotIcons.get(selectedBot);
631
                                r.destx = pt.x;
632
                                r.desty = pt.y;
633

    
634
                                if (csi != null) {
635
                                        csi.sendAbsoluteMove(r.id, r.destx, r.desty);
636
                                }
637

    
638
                                return;
639
                        }
640

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

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

    
670
                        repaint();
671
                }
672
        }
673

    
674
        class KeyHandler extends Thread {
675
                KeyEvent e;
676

    
677
                public KeyHandler (KeyEvent event) {
678
                        super("KeyHandler");
679
                        this.e = event;
680
                }
681

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

    
704
        class ActionHandler extends Thread {
705
                ActionEvent e;
706

    
707
                public ActionHandler (ActionEvent event) {
708
                        super("ActionHandler");
709
                        this.e = event;
710
                }
711

    
712
                public void run () {
713
                        Object source = e.getSource();
714

    
715
                        // General Actions
716
                        if (source == btnConnect) {
717
                                if (csi == null) {
718
                                        connect();
719
                                } else {
720
                                        disconnect();
721
                                }
722
                        } else if (source == btnGetXBeeIDs) {
723
                                csi.sendXBeeIDRequest();
724
                        } else if (source == btnAssignID) {
725
                                String message;
726
                                if (selectedBot < 0) {
727
                                        return;
728
                                }
729
                                int curID = robotIcons.get(selectedBot).id;
730

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

    
780
                        } else if (source == btnCommand_ResumeTask) {
781

    
782
                        } else if (source == btnCommand_ChargeNow) {
783

    
784
                        } else if (source == btnCommand_StopCharging) {
785

    
786
                        } else if (source == btnAddTask) { // Queue Management
787
                                taskAddWindow.prompt();
788
                        } else if (source == btnRemoveTask) {
789
                                if (taskList.getSelectedIndex() >= 0) {
790
                                        csi.sendQueueRemove(taskList.getSelectedIndex());
791
                                }
792
                                csi.sendQueueUpdate();
793
                        } else if (source == btnMoveTaskUp) {
794
                                csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() - 1);
795
                                csi.sendQueueUpdate();
796
                        } else if (source == btnMoveTaskDown) {
797
                                csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() + 1);
798
                                csi.sendQueueUpdate();
799
                        } else if (source == btnUpdateTasks) {
800
                                csi.sendQueueUpdate();
801
                        }
802

    
803
                        repaint();
804
                }
805
        }
806

    
807
        /*
808
        * DataUpdater thread.
809
        *                The purpose of this thread is to request data from the server at regular intervals.
810
        *
811
        */
812
        class DataUpdater extends Thread {
813
                final int DATAUPDATER_DELAY = 400;
814

    
815
                public DataUpdater () {
816
                        super("Colonet DataUpdater");
817
                }
818

    
819
                public void run () {
820
                        String line;
821
                        while (true) {
822
                                try {
823
                                        //request more data
824
                                        if (csi != null && csi.isReady()) {
825
                                                                                                csi.sendPositionRequest();
826
                                                csi.sendXBeeIDRequest();
827
                                                if (cmbRobotNum.getSelectedIndex() > 0) {
828
                                                                String sel = (String) cmbRobotNum.getSelectedItem();
829
                                                                int num = Integer.parseInt(sel);
830
                                                        csi.sendBatteryRequest(num);
831
                                                }
832
                                        }
833
                                        Thread.sleep(DATAUPDATER_DELAY);
834
                                } catch (InterruptedException e) {
835
                                        return;
836
                                }
837
                        }
838
                }
839

    
840
        }
841

    
842
        /*
843
        * GraphicsPanel class
844
        * An extension of JPanel, designed for holding an image that will be repainted regularly.
845
        */
846
        class GraphicsPanel extends JPanel {
847
                protected Image img;
848

    
849
                public GraphicsPanel (Image img) {
850
                        this(img, true);
851
                }
852

    
853
                public GraphicsPanel (Image img, boolean isDoubleBuffered) {
854
                        super(isDoubleBuffered);
855
                        this.img = img;
856
                }
857

    
858
                public void paint (Graphics g) {
859
                        // Place the buffered image on the screen, inside the panel
860
                        g.drawImage(img, 0, 0, Color.WHITE, this);
861
                }
862
        }
863

    
864
        /*
865
        * WebcamPanel class
866
        * Enables more efficient image handling in a component-controlled environment
867
        */
868
        class WebcamPanel extends JPanel {
869
                int BORDER = 16;        // this is arbitrary. it makes the image look nice inside a border.
870
                int BOT_RADIUS = 40;
871
                volatile BufferedImage img;
872
                BufferedImage buffer;
873

    
874
                public WebcamPanel () {
875
                        super(true);
876
                }
877

    
878
                public synchronized void setImage (BufferedImage newimg) {
879
                        if (img != null) {
880
                                img.flush();
881
                        }
882
                        System.gc();
883
                        img = newimg;
884
                        repaint();
885
                }
886

    
887
                public synchronized void paint (Graphics g) {
888
                        if (img == null) {
889
                                return;
890
                        }
891

    
892
                        // Calculate scaling
893
                        int maxWidth = getWidth() - 2*BORDER;
894
                        int maxHeight = getHeight() - 2*BORDER;
895
                        double widthRatio = 1.0 * maxWidth / img.getWidth();
896
                        double heightRatio = 1.0 * maxHeight / img.getHeight();
897
                        double scale = 0;
898
                        int newWidth = 0;
899
                        int newHeight = 0;
900
                        int x = 0;
901
                        int y = 0;
902

    
903
                        if (widthRatio > heightRatio) {         //height is the limiting factor
904
                                scale = heightRatio;
905
                                newHeight = maxHeight;
906
                                newWidth = (int) (img.getWidth() * scale);
907
                                y = BORDER;
908
                                x = (maxWidth - newWidth) / 2 + BORDER;
909
                        } else {        //width is the limiting factor
910
                                scale = widthRatio;
911
                                newWidth = maxWidth;
912
                                newHeight = (int) (img.getHeight() * scale);
913
                                x = BORDER;
914
                                y = (maxHeight - newHeight) / 2 + BORDER;
915
                        }
916

    
917
                        // Draw everything onto the buffer
918
                        buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
919
                        Graphics2D bufferedGraphics = (Graphics2D)buffer.getGraphics();
920
                        bufferedGraphics.setColor(Color.GRAY);
921
                        bufferedGraphics.fillRect(0, 0, this.getWidth(), this.getHeight());
922
                        Image imgScaled = img.getScaledInstance(newWidth, newHeight, Image.SCALE_FAST);
923
                        bufferedGraphics.drawImage(imgScaled, x, y, this);
924

    
925

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

    
950
                        // Identify currently-selected robot
951
                        if (selectedBot >= 0 && selectedBot < robotIcons.size()) {
952
                                bufferedGraphics.setColor(Color.BLACK);
953
                                RobotIcon r = robotIcons.get(selectedBot);
954
                                int px = (int) (x + r.x * scale);
955
                                int py = (int) (y + r.y * scale);
956
                                bufferedGraphics.drawOval(px-RADIUS-6, py-RADIUS-6, 2*r.RADIUS+12, 2*r.RADIUS+12);
957
                        }
958

    
959
                        //Display buffered content
960
                        g.drawImage(buffer, 0, 0, this);
961
                }
962

    
963
                /*
964
                * Convert a click on the webcam panel to a coordinate that is consistent with the
965
                * original size of the image that the panel contains.
966
                */
967
                public Point convertClick (MouseEvent e) {
968
                        if (img == null) {
969
                                return new Point(e.getX(), e.getY());
970
                        }
971

    
972
                        // Calculate scaling
973
                        int clickx = e.getX();
974
                        int clicky = e.getY();
975
                        int maxWidth = getWidth() - 2*BORDER;
976
                        int maxHeight = getHeight() - 2*BORDER;
977
                        double widthRatio = 1.0 * maxWidth / img.getWidth();
978
                        double heightRatio = 1.0 * maxHeight / img.getHeight();
979
                        double scale = 0;
980
                        int newWidth = 0;
981
                        int newHeight = 0;
982
                        int px = 0;
983
                        int py = 0;
984

    
985
                        if (widthRatio > heightRatio) {         //height is the limiting factor
986
                                scale = heightRatio;
987
                                newHeight = maxHeight;
988
                                newWidth = (int) (img.getWidth() * scale);
989
                                py = clicky - BORDER;
990
                                px = clickx - BORDER - (maxWidth - newWidth) / 2;
991
                                py *= scale;
992
                                px *= scale;
993
                        } else {        //width is the limiting factor
994
                                scale = widthRatio;
995
                                newWidth = maxWidth;
996
                                newHeight = (int) (img.getHeight() * scale);
997
                                px = clickx - BORDER;
998
                                py = clicky - BORDER - (maxHeight - newHeight) / 2;
999
                                px *= scale;
1000
                                py *= scale;
1001
                        }
1002

    
1003
                        return new Point(px, py);
1004
                }
1005
        }
1006

    
1007
        /*
1008
        * WebcamLoader class
1009
        * Handles the loading of the webcam image.
1010
        */
1011
        class WebcamLoader extends Thread
1012
        {
1013
                final int WEBCAMLOADER_DELAY = 400;
1014
                final String IMAGE_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet.jpg";
1015

    
1016
                URL imagePath;
1017

    
1018
                MediaTracker mt;
1019
                BufferedImage image;
1020
                Random rand;
1021

    
1022
                public WebcamLoader (JApplet applet)
1023
                {
1024
                        super("ColonetWebcamLoader");
1025
                        mt = new MediaTracker(applet);
1026
                        ImageIO.setUseCache(false);
1027
                        rand = new Random();
1028
                }
1029

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

    
1062
        }
1063

    
1064
        /*
1065
        * VectorController class
1066
        * Manages robot motion control graphically
1067
        */
1068
        class VectorController extends GraphicsPanel implements MouseListener, MouseMotionListener {
1069
                int x, y, cx, cy;
1070
                int width, height;
1071
                int side;
1072

    
1073
                public VectorController (Image img) {
1074
                        super (img);
1075
                        width = img.getWidth(null);
1076
                        height = img.getHeight(null);
1077
                        cx = img.getWidth(null)/2;
1078
                        cy = img.getHeight(null)/2;
1079
                        x = cx;
1080
                        y = cy;
1081
                        if (width < height)
1082
                                side = width;
1083
                        else
1084
                                side = height;
1085
                        this.addMouseListener(this);
1086
                        this.addMouseMotionListener(this);
1087
                }
1088

    
1089
                public void setPoint (int x, int y) {
1090
                        if (!isValidPoint(x, y))
1091
                                return;
1092
                        this.x = x;
1093
                        this.y = y;
1094
                        repaint();
1095
                }
1096

    
1097
                public boolean isValidPoint (int x, int y) {
1098
                        double xterm = Math.pow(1.0*(x - cx)/(side/2), 2);
1099
                        double yterm = Math.pow(1.0*(y - cy)/(side/2), 2);
1100
                        return (xterm + yterm <= 1);
1101
                }
1102

    
1103
                public void notifyMouseEvent (MouseEvent e, boolean send) {
1104
                        if (!isValidPoint(e.getX(), e.getY()))
1105
                                return;
1106
                        vectorController.setPoint(e.getX(), e.getY());
1107
                        vectorController.repaint();
1108
                        if (send)
1109
                                vectorController.sendToServer();
1110
                }
1111

    
1112
                public void mouseExited(MouseEvent e) {
1113
                }
1114
                public void mouseEntered(MouseEvent e) {
1115
                }
1116
                public void mouseReleased(MouseEvent e) {
1117
                        this.notifyMouseEvent(e, true);
1118
                }
1119
                public void mouseClicked(MouseEvent e) {
1120
                        this.notifyMouseEvent(e, false);
1121
                }
1122
                public void mousePressed(MouseEvent e) {
1123
                }
1124
                public void mouseDragged(MouseEvent e) {
1125
                        vectorController.notifyMouseEvent(e, false);
1126
                }
1127
                public void mouseMoved(MouseEvent e) {
1128
                }
1129

    
1130
                public int getSpeed () {
1131
                        int dx = x - cx;
1132
                        int dy = y - cy;
1133
                        int v = (int) Math.sqrt( Math.pow(dx, 2) + Math.pow(dy, 2) );
1134
                        return v;
1135
                }
1136

    
1137
                /**
1138
                * Returns the angle of the control vector in positive degrees west of north,
1139
                * or negative degrees east of north, whichever is less than or equal to
1140
                * 180 degrees total.
1141
                */
1142
                public int getAngle () {
1143
                        int dx = x - cx;
1144
                        int dy = cy - y;
1145
                        // find reference angle in radians
1146
                        double theta = Math.atan2(Math.abs(dx), Math.abs(dy));
1147
                        // transform to degrees
1148
                        theta = theta * 180 / Math.PI;
1149
                        // adjust for quadrant
1150
                        if (dx < 0 && dy < 0)
1151
                                theta = 90 + theta;
1152
                        else if (dx < 0 && dy >= 0)
1153
                                theta = 90 - theta;
1154
                        else if (dx >= 0 && dy < 0)
1155
                                theta = -90 - theta;
1156
                        else
1157
                                theta = -90 + theta;
1158
                        return (int) theta;
1159
                }
1160

    
1161
                public void paint (Graphics g) {
1162
                        g.setColor(Color.BLACK);
1163
                        g.fillRect(0, 0, width, height);
1164
                        ((Graphics2D)g).setStroke(new BasicStroke(1));
1165
                        g.setColor(Color.RED);
1166
                        g.drawOval(cx-side/2, cy-side/2, side, side);
1167
                        ((Graphics2D)g).setStroke(new BasicStroke(2));
1168
                        g.setColor(Color.GREEN);
1169
                        g.drawLine(cx, cy, x, y);
1170
                        g.fillOval(x-3, y-3, 6, 6);
1171
                }
1172

    
1173
                public void setMaxForward () {
1174
                        setPoint(cx, cy - (side/2) + 1);
1175
                }
1176

    
1177
                public void setMaxReverse () {
1178
                        setPoint(cx, cy + (side/2) - 1);
1179
                }
1180

    
1181
                public void setMaxLeft () {
1182
                        setPoint(cx - (side/2) + 1, cy);
1183
                }
1184

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

    
1189
                public void setZero () {
1190
                        setPoint(cx, cy);
1191
                }
1192

    
1193
                public void sendToServer () {
1194
                        System.out.println("Attempting to send angle = " + getAngle() + ", speed = " + getSpeed() + "");
1195
                        String dest = ColonetServerInterface.GLOBAL_DEST;
1196
                        if (cmbRobotNum != null && cmbRobotNum.getSelectedIndex() > 0) {
1197
                                dest = (String)cmbRobotNum.getSelectedItem();
1198
                        }
1199

    
1200
                        if (csi != null) {
1201
                                /*
1202
                                csi.sendData(ColonetServerInterface.MOVE + " " + getSpeed() + " " + getAngle(), dest);
1203
                                */
1204

    
1205
                                //Directional commands
1206
                                if (x > cx && y == cy) {        //move right
1207
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 200", dest);
1208
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 200", dest);
1209
                                } else if (x < cx && y == cy) {         //move left
1210
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 200", dest);
1211
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 200", dest);
1212
                                } else if (x == cx && y > cy) {         //move forward
1213
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 225", dest);
1214
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 225", dest);
1215
                                } else if (x == cx && y < cy) {         //move backward
1216
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 225", dest);
1217
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 225", dest);
1218
                                } else if (x == cx && y == cy) {        //stop!
1219
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 0", dest);
1220
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 0", dest);
1221
                                }
1222
                        }
1223
                }
1224

    
1225
        }
1226

    
1227
        /*
1228
        * TaskAddWindow class
1229
        * A window that provides a simple way to add tasks to a task queue.
1230
        */
1231
        class TaskAddWindow extends JFrame implements ActionListener, ListSelectionListener {
1232
                JPanel panelButtons;
1233
                JPanel panelParameters;
1234
                JPanel panelSouth;
1235
                JPanel panelSelection;
1236
                JButton btnSubmit;
1237
                JButton btnCancel;
1238
                DefaultListModel availableListModel;
1239
                JList availableList;
1240
                JScrollPane spAvailableTasks;
1241
                JTextArea txtDescription;
1242
                JTextField txtParameters;
1243

    
1244
                public TaskAddWindow () {
1245
                        super("Add a Task");
1246
                        super.setSize(500,500);
1247
                        super.setLayout(new BorderLayout());
1248

    
1249
                        // set up buttons
1250
                        btnSubmit = new JButton("Submit");
1251
                        btnCancel = new JButton("Cancel");
1252
                        panelButtons = new JPanel();
1253
                        panelButtons.setLayout(new FlowLayout());
1254
                        panelButtons.add(btnSubmit);
1255
                        panelButtons.add(btnCancel);
1256
                        this.getRootPane().setDefaultButton(btnSubmit);
1257

    
1258
                        // set up task list
1259
                        availableListModel = new DefaultListModel();
1260
                        availableListModel.addElement("Map the Environment");
1261
                        availableListModel.addElement("Clean Up Chemical Spill");
1262
                        availableListModel.addElement("Grow Plants");
1263
                        availableListModel.addElement("Save the Cheerleader");
1264
                        availableListModel.addElement("Save the World");
1265
                        availableList = new JList(availableListModel);
1266
                        availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
1267
                        availableList.setSelectedIndex(-1);
1268
                        spAvailableTasks = new JScrollPane(availableList);
1269
                        spAvailableTasks.setBorder(BorderFactory.createTitledBorder("Select A Task"));
1270
                        txtDescription = new JTextArea();
1271
                        txtDescription.setEditable(false);
1272
                        txtDescription.setLineWrap(true);
1273
                        txtDescription.setWrapStyleWord(true);
1274
                        txtDescription.setBorder(BorderFactory.createTitledBorder("Description"));
1275

    
1276
                        //set up parameter area
1277
                        panelParameters = new JPanel();
1278
                        panelParameters.setLayout(new BorderLayout());
1279
                        txtParameters = new JTextField();
1280
                        panelParameters.add(new JLabel("Optional parameters for this task: "), BorderLayout.WEST);
1281
                        panelParameters.add(txtParameters);
1282

    
1283
                        // assemble objects
1284
                        panelSelection = new JPanel();
1285
                        panelSelection.setLayout(new GridLayout(1,2));
1286
                        panelSelection.add(spAvailableTasks);
1287
                        panelSelection.add(txtDescription);
1288

    
1289
                        panelSouth = new JPanel();
1290
                        panelSouth.setLayout(new GridLayout(2,1));
1291
                        panelSouth.add(panelParameters);
1292
                        panelSouth.add(panelButtons);
1293

    
1294
                        this.getContentPane().add(panelSouth, BorderLayout.SOUTH);
1295
                        this.getContentPane().add(panelSelection, BorderLayout.CENTER);
1296
                        this.setLocationRelativeTo(null);
1297

    
1298
                        // add listeners here
1299
                        availableList.addListSelectionListener(this);
1300
                        btnSubmit.addActionListener(this);
1301
                        btnCancel.addActionListener(this);
1302
                }
1303

    
1304
                public void prompt () {
1305
                        this.setVisible(true);
1306
                }
1307

    
1308
                private String getDescription (int index) {
1309
                        if (index < 0)
1310
                                return "";
1311
                        switch (index) {
1312
                                case 0: return "SLAM and junk";
1313
                                case 1: return "I'm not sure this works";
1314
                                case 2: return "Push them into the light";
1315
                                case 3: return "...";
1316
                                case 4: return "...";
1317

    
1318
                                default: return "Task not recognized";
1319
                        }
1320
                }
1321

    
1322
                public void actionPerformed (ActionEvent e) {
1323
                        Object source = e.getSource();
1324
                        if (source == btnSubmit) {
1325
                                txtParameters.setText(txtParameters.getText().trim());
1326

    
1327

    
1328
                                this.setVisible(false);
1329
                        } else if (source == btnCancel) {
1330
                                this.setVisible(false);
1331
                        }
1332
                }
1333

    
1334
                public void valueChanged (ListSelectionEvent e) {
1335
                        int index = availableList.getSelectedIndex();
1336
                        if (index >= 0)
1337
                                txtDescription.setText(getDescription(index));
1338
                }
1339

    
1340
        }
1341

    
1342
        /*
1343
        *         BatteryIcon class
1344
        *         Graphical representation of battery level
1345
        */
1346
        class BatteryIcon implements Icon {
1347
                private int width;
1348
                        private int height;
1349
                        private int level;
1350

    
1351
                /**
1352
                * Constructs a new BatteryIcon with all default parameters.
1353
                * Default width and height are 50.
1354
                * Default level is 100.
1355
                */
1356
                        public BatteryIcon(){
1357
                                this(100, 50, 50);
1358
                        }
1359

    
1360
                /**
1361
                * Constructs a new BatteryIcon with default width and height, and with the specified level.
1362
                * Default width and height are 50.
1363
                */
1364
                        public BatteryIcon(int startLevel){
1365
                                this(startLevel, 50, 50);
1366
                        }
1367

    
1368
                /**
1369
                * Constructs a new BatteryIcon with the specified level, width, and height.
1370
                */
1371
                        public BatteryIcon(int startLevel, int w, int h){
1372
                                level = startLevel;
1373
                                width = w;
1374
                                height = h;
1375
                        }
1376

    
1377
                        public void paintIcon(Component c, Graphics g, int x, int y) {
1378
                                        Graphics2D g2d = (Graphics2D) g.create();
1379
                                        //clear the background
1380
                                        g2d.setColor(Color.WHITE);
1381
                                        g2d.fillRect(x + 1, y + 1, width - 2, height - 2);
1382
                                        //outline
1383
                                        g2d.setColor(Color.BLACK);
1384
                                        g2d.drawRect((int)(x + width*.3), y + 2, (int)(width*.4), height - 4);
1385
                                        //battery life rectangle
1386
                        if (level > 50)
1387
                                g2d.setColor(Color.GREEN);
1388
                        else if (level > 25)
1389
                                g2d.setColor(Color.YELLOW);
1390
                        else
1391
                                g2d.setColor(Color.RED);
1392
                                        int greenX = (int)(x + 1 + width*.3);
1393
                                        int greenY = (int)((y+3) + Math.abs(level-100.0)*(height-6)/(100));
1394
                                        int greenWidth = (int)(width*.4 - 2)+1;
1395
                                        int greenHeight = 1+(int)(level-0.0)*(height-6)/(100);
1396
                                        g2d.fillRect(greenX, greenY, greenWidth, greenHeight);
1397
                                        //text
1398
                                        g2d.setColor(Color.BLACK);
1399
                                        g2d.drawString(level + "%", greenX + greenWidth/2 - 10, greenY + greenHeight/2 + 5);
1400

    
1401
                                        g2d.dispose();
1402
                        }
1403

    
1404
                /**
1405
                * Sets the battery level for this BatteryIcon. The level should be given in raw form, i.e. 0-255 directly
1406
                * from the robot. The value will be converted to a representative percentage automatically.
1407
                *
1408
                * @param newLevel the new battery reading from the robot that this BatteryIcon will display.
1409
                */
1410
                        public void setLevel(int newLevel) {
1411
                                level = convert(newLevel);
1412
                                repaint();
1413
                                System.out.println("Updated level to " + level);
1414
                        }
1415

    
1416
                        public int getIconWidth() {
1417
                                        return width;
1418
                        }
1419

    
1420
                        public int getIconHeight() {
1421
                                        return height;
1422
                        }
1423

    
1424
                /**
1425
                * Converts a robot battery reading into representable form.
1426
                * Readings from the robot are returned as raw values, 0-255. This method converts the reading into a value
1427
                * from 0 to 100 so that the practical remaining charge is represented.
1428
                *
1429
                * @param level The battery level as returned by the robot.
1430
                * @returns The representable battery percentage.
1431
                */
1432
                private int convert (int level) {
1433
                        // TODO: make this a forreals conversion.
1434
                        return (int) (100.0 * level / 170);
1435
                }
1436

    
1437
        }
1438

    
1439

    
1440

    
1441
}