Project

General

Profile

Statistics
| Revision:

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

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
                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
                dataUpdater.interrupt();
446
                csi.disconnect();
447
                csi = null;
448
                btnConnect.setText("Connect");
449
                lblConnectionStatus.setText("Status: Disconnected");
450
        }
451

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

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

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

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

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

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

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

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

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

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

    
594
        class MouseHandler extends Thread {
595
                MouseEvent e;
596

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

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

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

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

    
624
                                return;
625
                        }
626

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

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

    
644
                                return;
645
                        }
646

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

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

    
676
                        repaint();
677
                }
678
        }
679

    
680
        class KeyHandler extends Thread {
681
                KeyEvent e;
682

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

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

    
710
        class ActionHandler extends Thread {
711
                ActionEvent e;
712

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

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

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

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

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

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

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

    
811
                        repaint();
812
                }
813
        }
814

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
932

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

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

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

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

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

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

    
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
}