Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (42.4 KB)

1
//
2
//  Colonet.java
3
//
4

    
5
import javax.swing.*;
6
import javax.swing.event.*;
7
import javax.imageio.*;
8
import java.awt.*;
9
import java.awt.image.*;
10
import java.awt.event.*;
11
import java.net.*;
12
import java.io.*;
13
import java.util.*;
14

    
15

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

    
25
        // Used for images
26
        final int CANVAS_SIZE = 500;  //the applet may be slow if the canvas gets too large
27
        final int BUFFER = 50;
28
        final int RADIUS = 30;
29
        
30
        //Used for the robot controller
31
        final int VECTOR_CONTROLLER_HEIGHT = 220;
32
        final int VECTOR_CONTROLLER_WIDTH = 350;
33
        
34

    
35
        // Connection
36
        JTextField txtHost;                                
37
        JTextField txtPort;                                
38
        JButton btnConnect;        
39
        JButton btnGetXBeeIDs;
40
        JLabel lblConnectionStatus;
41
        JTextArea txtMatrix;
42
        JTextArea txtInfo; 
43
        JPanel panelConnect;
44
        JPanel panelServerInterface;
45
        Socket socket;                                        
46
        OutputStreamWriter out;
47
        DataUpdater dataUpdater;  
48
        
49
        // South
50
        JPanel panelSouth;
51
        JTextArea log;
52
        JScrollPane spLog;
53
        
54
        // Control
55
        JPanel panelControl;
56
        JTabbedPane tabPaneControl;
57
        JPanel panelRobotControl;
58
        JPanel panelRobotDirection;
59
        JPanel panelRobotDirectionButtons;
60
        JPanel panelRobotCommands;
61
        JButton btnF, btnB, btnL, btnR, btnActivate;
62
        JComboBox cmbRobotNum;
63
        JLabel lblBattery;
64
        JLabel lblSelected;
65
        BatteryIcon batteryIcon;
66
        JPanel panelBattery;
67
        VectorController vectorController;
68
        BufferedImage imageVectorControl;
69
        JButton btnAssignID;
70
        boolean setWaypoint;
71
        int setWaypointID;
72
        JButton btnCommand_MoveTo;
73
        JButton btnCommand_MoveAll;
74
        JButton btnCommand_StopTask;
75
        JButton btnCommand_ResumeTask;
76
        JButton btnCommand_ChargeNow;
77
        JButton btnCommand_StopCharging;
78
        
79
        // Task Manager
80
        JPanel panelTaskManager;
81
        JScrollPane spTaskManager;
82
        JPanel panelTaskManagerControls;
83
        JPanel panelTaskManagerControlsPriority;
84
        DefaultListModel taskListModel;
85
        JList taskList;
86
        JButton btnAddTask;
87
        JButton btnRemoveTask;
88
        JButton btnMoveTaskUp;
89
        JButton btnMoveTaskDown;
90
        JButton btnUpdateTasks;
91
        TaskAddWindow taskAddWindow;
92
        
93
        //Webcam
94
        WebcamPanel panelWebcam;
95
        GraphicsPanel panelGraph;
96
        GraphicsConfiguration gc;
97
        volatile BufferedImage image;
98
        volatile Graphics2D canvas;
99
        int cx, cy;
100
        JTabbedPane tabPaneMain;
101
        
102
        Font botFont;
103
        volatile int numBots;
104
        volatile int selectedBot;  //the user has selected this bot graphically
105
        volatile java.util.List <RobotIcon> robotIcons;  //contains boundary shapes around bots for click detection
106
        volatile int[] xbeeID;
107
        
108
        Colonet self = this;
109
        Thread paintThread;
110
        WebcamLoader webcamLoader;
111
        ColonetServerInterface csi;
112

    
113
        
114
        public void init () {
115
                // Set the default look and feel - choose one
116
        //String laf = UIManager.getSystemLookAndFeelClassName();
117
                String laf = UIManager.getCrossPlatformLookAndFeelClassName();
118
                //String laf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
119
        try {
120
            UIManager.setLookAndFeel(laf);
121
        } catch (UnsupportedLookAndFeelException exc) {
122
            System.err.println ("Warning: UnsupportedLookAndFeel: " + laf);
123
        } catch (Exception exc) {
124
            System.err.println ("Error loading " + laf + ": " + exc);
125
        }
126
                // We should invoke and wait to avoid browser display difficulties
127
                Runnable r = new Runnable() {
128
                        public void run() {
129
                                createAndShowGUI();
130
                        }
131
                };
132
                try {
133
                        SwingUtilities.invokeAndWait(r);
134
                } catch (InterruptedException e) {
135
                        //Not really sure why we would be in this situation
136
                        System.out.println("InterruptedException in init: " + e);
137
                } catch (java.lang.reflect.InvocationTargetException e) {
138
                        //This could happen for various reasons if there is a problem in createAndShowGUI
139
                        e.printStackTrace();
140
                }
141
        }
142
        
143
        public void destroy () {
144
                try { paintThread.interrupt(); } catch (Exception e) { }
145
        }
146

    
147
        private synchronized void createAndShowGUI () {
148
                // init graphical elements
149
                // Get the graphics configuration of the screen to create a buffer
150
                gc = GraphicsEnvironment.getLocalGraphicsEnvironment()
151
                        .getDefaultScreenDevice().getDefaultConfiguration();
152
                image = gc.createCompatibleImage(CANVAS_SIZE,CANVAS_SIZE);
153
                canvas = image.createGraphics();
154
                canvas.setStroke(new BasicStroke(2));  //set pen width
155
                panelGraph = new GraphicsPanel(image, false);  //set automatic double-buffering to false. we are doing it manually.
156
                panelWebcam = new WebcamPanel();
157
                tabPaneMain = new JTabbedPane();
158
                tabPaneMain.add(panelWebcam, "Webcam");
159
                //tabPaneMain.add(panelGraph, "Graph");
160
                
161
                // Calculate center of canvas
162
                cx = image.getWidth() / 2;
163
                cy = image.getHeight() / 2;
164
                
165
                // Set up robots
166
                botFont = new Font("Arial", Font.PLAIN, 14);
167
                numBots = 0;
168
                selectedBot = -1;
169
                robotIcons = new ArrayList <RobotIcon> ();
170
                
171
                // Connection area
172
                txtMatrix = new JTextArea();
173
                txtMatrix.setBorder(BorderFactory.createTitledBorder("Info"));
174
                txtInfo = new JTextArea();
175
                txtInfo.setBorder(BorderFactory.createTitledBorder("Info"));
176
                txtInfo.setEditable(false);
177
                txtHost = new JTextField(this.getDocumentBase().getHost());
178
                txtHost.setBorder(BorderFactory.createTitledBorder("Host"));
179
                txtPort = new JTextField("10123");
180
                txtPort.setBorder(BorderFactory.createTitledBorder("Port"));
181
                btnConnect = new JButton("Connect");
182
                btnGetXBeeIDs = new JButton("Get XBee IDs");
183
                getRootPane().setDefaultButton(btnConnect);
184
                lblConnectionStatus = new JLabel("Status: Offline");
185
                panelConnect = new JPanel();
186
                panelConnect.setLayout(new GridLayout(6,1));
187
                panelConnect.add(lblConnectionStatus);
188
                panelConnect.add(txtHost);
189
                panelConnect.add(txtPort);
190
                panelConnect.add(btnConnect);
191
                //panelConnect.add(btnGetXBeeIDs);
192
                panelServerInterface = new JPanel();
193
                panelServerInterface.setLayout(new GridLayout(2,1));
194
                panelServerInterface.add(panelConnect);
195
                panelServerInterface.add(txtMatrix);
196
        
197
                // Robot direction panel
198
                panelRobotDirection = new JPanel();
199
                panelRobotDirectionButtons = new JPanel();
200
                btnF = new JButton("^");
201
                btnB = new JButton("v");
202
                btnL = new JButton("<");
203
                btnR = new JButton(">");
204
                btnActivate = new JButton("o");
205
                panelRobotDirectionButtons.setLayout(new GridLayout(1,5));
206
                panelRobotDirectionButtons.add(btnActivate);
207
                panelRobotDirectionButtons.add(btnF);
208
                panelRobotDirectionButtons.add(btnB);
209
                panelRobotDirectionButtons.add(btnL);
210
                panelRobotDirectionButtons.add(btnR);
211
                
212
                imageVectorControl = gc.createCompatibleImage(VECTOR_CONTROLLER_WIDTH, VECTOR_CONTROLLER_HEIGHT);
213
                vectorController = new VectorController(imageVectorControl);
214
                panelRobotDirection.setLayout(new BorderLayout());
215
                panelRobotDirection.add(vectorController, BorderLayout.CENTER);
216
                panelRobotDirection.add(panelRobotDirectionButtons, BorderLayout.SOUTH);
217
                
218
                // Robot Control and Commands
219
                panelRobotCommands = new JPanel();
220
                panelRobotCommands.setLayout(new GridLayout(5,2));
221
                cmbRobotNum = new JComboBox();
222
                // Battery subset
223
                batteryIcon = new BatteryIcon(25);
224
                lblBattery = new JLabel(batteryIcon);
225
                lblSelected = new JLabel("None");
226
                // Command subset
227
                setWaypoint = false;
228
                setWaypointID = -1;
229
                btnAssignID = new JButton("Assign ID");
230
                btnCommand_MoveTo = new JButton("Move to ...");
231
                btnCommand_MoveAll = new JButton("Move all ...");
232
                btnCommand_StopTask = new JButton("Stop Current Task");
233
                btnCommand_ResumeTask = new JButton("Resume Current Task");
234
                btnCommand_ChargeNow = new JButton("Recharge Now");
235
                btnCommand_StopCharging = new JButton("Stop Recharging");
236
                panelRobotCommands.add(new JLabel("Select Robot to Control: "));
237
                panelRobotCommands.add(cmbRobotNum);
238
                panelRobotCommands.add(new JLabel("Battery Level: "));
239
                panelRobotCommands.add(lblBattery);
240
                panelRobotCommands.add(new JLabel("Selected Icon: "));
241
                panelRobotCommands.add(lblSelected);
242
                panelRobotCommands.add(btnAssignID);
243
                panelRobotCommands.add(new JLabel(""));
244
                panelRobotCommands.add(btnCommand_MoveTo);
245
                panelRobotCommands.add(btnCommand_MoveAll);
246
                //panelRobotCommands.add(btnCommand_StopTask);
247
                //panelRobotCommands.add(btnCommand_ResumeTask);
248
                //panelRobotCommands.add(btnCommand_ChargeNow);
249
                //panelRobotCommands.add(btnCommand_StopCharging);
250
                panelRobotControl = new JPanel();
251
                panelRobotControl.setLayout(new GridLayout(2,1));
252
                panelRobotControl.add(panelRobotDirection);
253
                panelRobotControl.add(panelRobotCommands);
254
                
255
                
256
                // Task Manager
257
                panelTaskManager = new JPanel();
258
                panelTaskManager.setLayout(new BorderLayout());
259
                taskListModel = new DefaultListModel();
260
                taskList = new JList(taskListModel);
261
                taskList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
262
                taskList.setSelectedIndex(0);
263
                spTaskManager = new JScrollPane(taskList);
264
                panelTaskManagerControls = new JPanel();
265
                panelTaskManagerControls.setLayout(new GridLayout(1,4));
266
                panelTaskManagerControlsPriority = new JPanel();
267
                panelTaskManagerControlsPriority.setLayout(new GridLayout(1,2));
268
                btnAddTask = new JButton("Add...");
269
                btnRemoveTask = new JButton("Remove");
270
                btnMoveTaskUp = new JButton("^");
271
                btnMoveTaskDown = new JButton("v");
272
                btnUpdateTasks = new JButton("Update");
273
                panelTaskManagerControlsPriority.add(btnMoveTaskUp);
274
                panelTaskManagerControlsPriority.add(btnMoveTaskDown);
275
                panelTaskManagerControls.add(btnAddTask);
276
                panelTaskManagerControls.add(btnRemoveTask);
277
                panelTaskManagerControls.add(btnUpdateTasks);
278
                panelTaskManagerControls.add(panelTaskManagerControlsPriority);
279
                panelTaskManager.add(spTaskManager, BorderLayout.CENTER);
280
                panelTaskManager.add(panelTaskManagerControls, BorderLayout.SOUTH);
281
                panelTaskManager.add(new JLabel("Current Task Queue"), BorderLayout.NORTH);
282
                taskAddWindow = new TaskAddWindow();
283
                
284
                // Message log
285
                log = new JTextArea();
286
                spLog = new JScrollPane(log,
287
                        ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, 
288
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
289
                spLog.setBorder(BorderFactory.createTitledBorder("Log"));
290
                spLog.setPreferredSize(new Dimension(0, 120));
291
                log.setEditable(false);
292
                
293
                // Main control mechanism
294
                panelControl = new JPanel();
295
                panelControl.setLayout(new GridLayout(1,1));
296
                tabPaneControl = new JTabbedPane(JTabbedPane.TOP);
297
                tabPaneControl.setPreferredSize(new Dimension(VECTOR_CONTROLLER_WIDTH, 0));
298
                tabPaneControl.addTab("Connection", panelServerInterface);
299
                tabPaneControl.addTab("Robots", panelRobotControl);
300
                tabPaneControl.addTab("Tasks", panelTaskManager);
301
                panelControl.add(tabPaneControl);
302
                
303
                // Set up elements in the south
304
                panelSouth = new JPanel();
305
                panelSouth.setLayout(new GridLayout(1,2));
306
                //panelSouth.add(spLog);
307

    
308
                // Put all elements in the ContentPane
309
                this.getContentPane().setLayout(new BorderLayout());
310
                this.getContentPane().add(tabPaneMain, BorderLayout.CENTER);
311
                this.getContentPane().add(panelSouth, BorderLayout.SOUTH);
312
                this.getContentPane().add(panelControl, BorderLayout.EAST);
313
                this.setVisible(true);
314
                
315
                /* Add all listeners here */
316
                // Task Management
317
                btnAddTask.addActionListener(this);
318
                btnRemoveTask.addActionListener(this);
319
                btnMoveTaskUp.addActionListener(this);
320
                btnMoveTaskDown.addActionListener(this);
321
                btnUpdateTasks.addActionListener(this);
322
                // Robot Control
323
                btnF.addActionListener(this);
324
                btnB.addActionListener(this);
325
                btnL.addActionListener(this);
326
                btnR.addActionListener(this);
327
                btnF.addKeyListener(this);
328
                btnB.addKeyListener(this);
329
                btnL.addKeyListener(this);
330
                btnR.addKeyListener(this);
331
                btnActivate.addActionListener(this);
332
                btnActivate.addKeyListener(this);
333
                cmbRobotNum.addKeyListener(this);
334
                btnCommand_MoveTo.addActionListener(this);
335
                btnCommand_MoveAll.addActionListener(this);
336
                btnCommand_StopTask.addActionListener(this);
337
                btnCommand_ResumeTask.addActionListener(this);
338
                btnCommand_ChargeNow.addActionListener(this);
339
                btnCommand_StopCharging.addActionListener(this);
340
                // Other
341
                btnConnect.addActionListener(this);
342
                btnGetXBeeIDs.addActionListener(this);
343
                btnAssignID.addActionListener(this);
344
                panelWebcam.addMouseListener(this);        
345
        
346
        }
347
        
348
        public void run () {
349
                while (true) {
350
                        repaint();
351
                        try { 
352
                                Thread.sleep(90);
353
                        } catch (InterruptedException e) {
354
                                return;
355
                        }
356
                }
357
        }
358
        
359
        public void paint (Graphics g) {
360
            super.paint(g);
361
        }
362
        
363
        public void update (Graphics g) {
364
            paint(g);
365
        }
366
                
367
        /** 
368
        * Gets the JTextArea used for storing the activity log. This method returns a reference to the 
369
        * JTextArea that stores the log. The log can contain any activity that is revelant to the use
370
        * of the applet, and may optionally display debugging information.
371
        *
372
        * @return the JTextArea where BOM matrix information is stored.
373
        */ 
374
        public JTextArea getLog () {
375
                return log;
376
        }
377
        
378
        /** 
379
        * Gets the JTextArea used for storing the BOM matrix data. This method returns a reference to the 
380
        * JTextArea that stores the BOM matrix. The values in the matrix are stored as integers separated 
381
        * by spaces, and the lines should be separated by a newline.
382
        * 
383
        * @return the JTextArea where BOM matrix information is stored.
384
        */
385
        public JTextArea getMatrixInput () {
386
                return txtMatrix;
387
        }
388
        
389
        /**
390
        * Parses a String containing BOM matrix information.
391
        * The ColonetServerInterface receives lines of the BOM matrix.  (For encoding 
392
        * information, see the ColonetServerInterface documentation.)  The entire matrix is passed
393
        * to the client when requested. This method takes a string of the form 
394
        * "[command code] [command code] [number of robots] [data0] [data1] ..."
395
        * with tokens separated by spaces and containing no brackets.  
396
        * The [command code]s are predefined values identifying this String as a BOM data
397
        * String, [number of robots] is an integer, and the values that follow are 
398
        * the sensor readings of the robots in order, starting with robot 0.  Only [number of robots]^2
399
        * data entries will be read.  The matrix values are saved locally until the next String is parsed.
400
        * 
401
        *
402
        * @param line the String containing BOM matrix information.
403
        * @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots]^2 data entries in the String
404
        */
405
        public void parseMatrix (String line) {
406
                txtMatrix.setText("");
407
                String [] str = line.split(" ");
408
                int num = Integer.parseInt(str[2]);
409
                for (int i = 0; i < num; i++) {
410
                        for (int j = 0; j < num; j++) {
411
                                String next = str[3 + i*num + j];
412
                                if (next.equals("-1"))
413
                                        txtMatrix.append("-");
414
                                else 
415
                                        txtMatrix.append(next);
416
                                if (j < num - 1) 
417
                                        txtMatrix.append(" ");
418
                        }
419
                        if (i < num - 1) 
420
                                txtMatrix.append("\n");
421
                }
422
                
423
        }
424
        
425
        public void connect () {
426
            webcamLoader = new WebcamLoader(this);
427
                dataUpdater = new DataUpdater();
428
                paintThread = new Thread(this, "paintThread");
429
                csi = new ColonetServerInterface(this);
430
                csi.connect(txtHost.getText(), txtPort.getText());
431
                if (!csi.isReady())
432
                        return;
433
                btnConnect.setEnabled(false);
434
                lblConnectionStatus.setText("Status: Connected");
435
                //paintThread.start();
436
                dataUpdater.start();
437
                webcamLoader.start();
438
        }
439
        
440
        public void disconnect () {
441
            btnConnect.setEnabled(true);
442
            lblConnectionStatus.setText("Status: Disconnected");
443
            try { paintThread.interrupt(); } catch (Exception e) { }
444
                
445
        }
446
        
447
        /**
448
        * Parses a String containing a task queue update.
449
        * Format is currently not specified.
450
        * This method currently does nothing.
451
        *
452
        * @param line the String containing task queue update information.
453
        */
454
        public void parseQueue (String line) {
455
                log.append("Got queue update\n");
456
                //TODO: display new queue data in tasks tab
457
        }
458
        
459
        /**
460
        * Parses a String containing XBee ID values.
461
        * The ColonetServerInterface receives Strings of XBee information.  (For encoding 
462
        * information, see the ColonetServerInterface documentation.)  This method takes
463
        * a string of the form "[command code] [command code] [number of robots] [id0] [id1] ..."
464
        * with tokens separated by spaces and containing no brackets.  
465
        * The [command code]s are predefined values identifying this String as an XBee
466
        * ID String, [number of robots] is an integer, and the values that follow are 
467
        * the IDs of the robots in order, starting with robot 0.  Only [number of robots] 
468
        * will be read.  The ID values are saved locally until the next String is parsed.
469
        * The purpose of having this list is to ensure that robots are properly identified for control purposes.
470
        * This keeps robot identification consistent between sessions and prevents arbitrary assignment. 
471
        *
472
        * @param line the String containing XBee ID information.
473
        * @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots] IDs in the String
474
        * @see ColonetServerInterface#sendXBeeIDRequest()
475
        */
476
        public void parseXBeeIDs (String line) {
477
        
478
                String [] str = line.split(" ");
479
                int num = Integer.parseInt(str[2]);
480
                xbeeID = new int[num];
481
                for (int i = 0; i < num; i++)
482
                        xbeeID[i] = Integer.parseInt(str[i+3]);
483
                
484
                //update the list of robots to control
485
                //but save the old value first
486
                Object oldSelection = cmbRobotNum.getSelectedItem();
487
                cmbRobotNum.removeAllItems();
488
                cmbRobotNum.addItem(new String("   All   "));
489
                for (int i = 0; i < num; i++)
490
                        cmbRobotNum.addItem(new String("" + xbeeID[i]));
491
                cmbRobotNum.setSelectedItem(oldSelection);
492
        }
493
        
494
        /**
495
        * Parses a String containing battery information.
496
        * The ColonetServerInterface receives Strings of battery information.  (For encoding 
497
        * information, see the ColonetServerInterface documentation.)  This method takes
498
        * a string of the form "[command code] [command code] [robot ID] [value]"
499
        * with tokens separated by spaces and containing no brackets.  
500
        * The [command code]s are predefined values identifying this String as a battery
501
        * information String, [robot ID] is an integer, and [value] is a battery measurement.
502
        * This updates the batery information for a single robot.
503
        * 
504
        *
505
        * @param line the String containing battery information.
506
        * @see ColonetServerInterface#sendBatteryRequest(int)
507
        */
508
        public void parseBattery (String line) {
509
                String [] str = line.split(" ");
510
                int botNum = Integer.parseInt(str[2]);
511
                int level = Integer.parseInt(str[3]);
512
                int selected = -1;
513
                try { 
514
                    selected = Integer.parseInt((String)cmbRobotNum.getSelectedItem());
515
                } catch (Exception e) {
516
                }
517
                if (selected == botNum) {
518
                        batteryIcon.setLevel(level);
519
                }
520
        }
521
        
522
        /**
523
        * Parses a String containing visual robot position information along with 
524
        * canonical ID assignments.
525
        */
526
        public void parsePositions (String line) {
527
                String [] str = line.split(" ");
528
                java.util.List <RobotIcon> newList = new ArrayList <RobotIcon> ();
529
                
530
                for (int i = 2; i < str.length; i+=3) {
531
                        int id = Integer.parseInt(str[i]);
532
                        int x = Integer.parseInt(str[i+1]);
533
                        int y = Integer.parseInt(str[i+2]);
534
                        RobotIcon newIcon = new RobotIcon(id, x, y);
535
                        newList.add(newIcon);
536
                }
537
                
538
                robotIcons = newList;
539
        
540
        }
541
        
542
        
543
        //
544
        // MouseListener methods
545
        //
546
        public void mousePressed(MouseEvent e) {
547
            //Start a new Thread to handle the MouseEvent
548
            SwingUtilities.invokeLater(new MouseHandler(e));
549
        }
550
        public void mouseExited(MouseEvent e) {
551
        }
552
        public void mouseEntered(MouseEvent e) {
553
        }
554
        public void mouseReleased(MouseEvent e) {
555
        }
556
        public void mouseClicked(MouseEvent e) {
557
        }
558
        public void mouseDragged(MouseEvent e) {
559
        }
560
        public void mouseMoved(MouseEvent e) {
561
        }
562
        
563
        //
564
        // KeyListener methods
565
        //
566
        public void keyPressed (KeyEvent e) {
567
                int code = e.getKeyCode();
568
                if (code == KeyEvent.VK_UP) {
569
                        vectorController.setMaxForward();
570
                        vectorController.sendToServer();
571
                } else if (code == KeyEvent.VK_DOWN) {
572
                        vectorController.setMaxReverse();
573
                        vectorController.sendToServer();
574
                } else if (code == KeyEvent.VK_LEFT) {
575
                        vectorController.setMaxLeft();
576
                        vectorController.sendToServer();
577
                } else if (code == KeyEvent.VK_RIGHT) {
578
                        vectorController.setMaxRight();
579
                        vectorController.sendToServer();
580
                } else if (code == KeyEvent.VK_S) {
581
                        vectorController.setZero();
582
                        vectorController.sendToServer();
583
                }
584
        }
585
        public void keyReleased (KeyEvent e) {
586
        }
587
        public void keyTyped (KeyEvent e) {
588
        }
589
        
590
        
591
        //
592
        // ActionListener method
593
        //
594
        public void actionPerformed (ActionEvent e) {
595
                // Start a new Thread to handle the ActionEvent
596
                SwingUtilities.invokeLater(new ActionHandler(e));
597
        }
598
        
599
        class MouseHandler extends Thread {
600
            
601
            MouseEvent e;
602
            
603
            public MouseHandler (MouseEvent event) {
604
                super("MouseHandler");
605
                this.e = event;
606
            }
607
        
608
            public void run () {
609
                
610
                // If we are selecting a waypoint (destination) for a specific bot
611
                if (setWaypoint && setWaypointID  >= 0) {
612
                    setWaypoint = false;
613
                    panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
614
                    if (selectedBot < 0)
615
                        return;
616
                    
617
                    RobotIcon r = robotIcons.get(selectedBot);
618
                    r.destx = e.getX();
619
                    r.desty = e.getY();
620
                    
621
                    if (csi != null)
622
                        csi.sendAbsoluteMove(r.id, r.destx, r.desty);
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
                    RobotIcon r = robotIcons.get(selectedBot);
633
                    r.destx = e.getX();
634
                    r.desty = e.getY();
635
                    
636
                    if (csi != null)
637
                        csi.sendAbsoluteMove(r.id, r.destx, r.desty);
638
                    
639
                    return;
640
                }
641
                
642
                // If we are setting all waypoints
643
                if (setWaypoint) {
644
                    setWaypoint = false;
645
                    panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
646
                    for (int i = 0; i < robotIcons.size(); i++) {
647
                        RobotIcon r = robotIcons.get(i);
648
                        r.destx = e.getX();
649
                        r.desty = e.getY();
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(e.getX(), e.getY())) {
658
                            selectedBot = i;
659
                            lblSelected.setText(" " + r.id);
660
                        }
661
                    }
662
                    
663
                    repaint();
664
            }
665
        }
666
        
667
        class ActionHandler extends Thread {
668
        
669
            ActionEvent e;
670
        
671
            public ActionHandler (ActionEvent event) {
672
                super("ActionHandler");
673
                this.e = event;
674
            }
675
            
676
            public void run () {
677
                Object source = e.getSource();
678
                
679
                    // General Actions
680
                    if (source == btnConnect) {
681
                            connect();
682
                    } else if (source == btnGetXBeeIDs) {
683
                            csi.sendXBeeIDRequest();
684
                    } else if (source == btnAssignID) {
685
                        String message;
686
                        if (selectedBot < 0)
687
                            return;
688
                        int curID = robotIcons.get(selectedBot).id;
689
                        if (curID < 0)
690
                            message = "That robot is unidentified. Please specify its ID.";
691
                        else
692
                            message = "That robot has ID " + curID + ". You may reassign it now.";
693
                        String result = JOptionPane.showInputDialog(self, message, "Robot Identification", JOptionPane.QUESTION_MESSAGE);
694
                        if (result == null)
695
                            return;
696
                    int newID = -1;
697
                        try {
698
                            newID = Integer.parseInt(result);
699
                        } catch (Exception ex) {
700
                            csi.warn("Invalid ID.");
701
                            return;
702
                        }
703
                        // Assign new ID and update display  
704
                            csi.sendIDAssignment(curID, newID);
705
                        robotIcons.get(selectedBot).id = newID;
706
                        robotIcons.get(selectedBot).color = Color.GREEN;
707
                        lblSelected.setText(" " + newID);
708
                        
709
                        
710
                    }
711
                
712
                    // Robot Movement Controls
713
                    else if (source == btnF) {
714
                            vectorController.setMaxForward();
715
                            vectorController.sendToServer();
716
                    } else if (source == btnB) {
717
                            vectorController.setMaxReverse();
718
                            vectorController.sendToServer();
719
                    } else if (source == btnL) {
720
                            vectorController.setMaxLeft();
721
                            vectorController.sendToServer();
722
                    } else if (source == btnR) {
723
                            vectorController.setMaxRight();
724
                            vectorController.sendToServer();
725
                    } else if (source == btnActivate) {
726
                            vectorController.setZero();
727
                            vectorController.sendToServer();
728
                    }
729
                    // Robot Commands (non-movement)
730
                    else if (source == btnCommand_MoveTo) {
731
                        if (selectedBot < 0)
732
                            return;
733
                        panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
734
                        setWaypoint = true;
735
                        setWaypointID = selectedBot;
736
                                        
737
                    } else if (source == btnCommand_MoveAll) {
738
                        panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
739
                        setWaypoint = true;
740
                        setWaypointID = -1;
741
                                        
742
                    } else if (source == btnCommand_StopTask) {
743
                
744
                    } else if (source == btnCommand_ResumeTask) {
745
                
746
                    } else if (source == btnCommand_ChargeNow) {
747
                
748
                    } else if (source == btnCommand_StopCharging) {
749
                
750
                    }
751
                        
752
                    // Queue Management
753
                    else if (source == btnAddTask) {
754
                            taskAddWindow.prompt();
755
                    } else if (source == btnRemoveTask) {
756
                            if (taskList.getSelectedIndex() >= 0);
757
                                    csi.sendQueueRemove(taskList.getSelectedIndex());
758
                            csi.sendQueueUpdate();
759
                    } else if (source == btnMoveTaskUp) {
760
                            csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() - 1);
761
                            csi.sendQueueUpdate();
762
                    } else if (source == btnMoveTaskDown) {
763
                            csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() + 1);
764
                            csi.sendQueueUpdate();
765
                    } else if (source == btnUpdateTasks) {
766
                            csi.sendQueueUpdate();
767
                    }
768
            
769
            }
770
        
771
        }
772
        
773
        /*
774
        *        DataUpdater thread.
775
        *   The purpose of this thread is to request data from the server at regular intervals.
776
        *
777
        */
778
        class DataUpdater extends Thread {
779
                final int DATAUPDATER_DELAY = 1200;
780
                
781
                public DataUpdater () {
782
                        super("Colonet DataUpdater");
783
                }
784
                
785
                public void run () {
786
                        String line;
787
                        while (true) {
788
                                try {
789
                                        //request more data
790
                                        if (csi != null && csi.isReady()) {
791
                        csi.sendPositionRequest();
792
                                                csi.sendXBeeIDRequest();
793
                                                if (cmbRobotNum.getSelectedIndex() > 0) {
794
                                                    String sel = (String) cmbRobotNum.getSelectedItem();
795
                                                    int num = Integer.parseInt(sel);
796
                                                        csi.sendBatteryRequest(num);
797
                                                }
798
                                        }
799
                                        Thread.sleep(DATAUPDATER_DELAY);
800
                                } catch (InterruptedException e) {
801
                                        return;
802
                                } 
803
                        }
804
                }
805

    
806
        }
807
        
808
        /*
809
        *        GraphicsPanel class
810
        *        An extension of JPanel, designed for holding an image that will be repainted regularly.
811
        */
812
        class GraphicsPanel extends JPanel {
813
                protected Image img;
814
        
815
                public GraphicsPanel (Image img) {
816
                        super();
817
                        this.img = img;
818
                }
819
                
820
                public GraphicsPanel (Image img, boolean isDoubleBuffered) {
821
                        super(isDoubleBuffered);
822
                        this.img = img;
823
                }
824
                
825
                public void paint (Graphics g) {
826
                        // Place the buffered image on the screen, inside the panel
827
                        g.drawImage(img, 0, 0, Color.WHITE, this);
828
                }
829
        
830
        }
831
        
832
        /*
833
        *        WebcamPanel class
834
        *        Enables more efficient image handling in a component-controlled environment
835
        */
836
        class WebcamPanel extends JPanel {
837
                int BORDER = 16;  // this is arbitrary. it makes the image look nice inside a border.
838
                int BOT_RADIUS = 40;
839
                volatile BufferedImage img;
840
        
841
                public WebcamPanel () {
842
                        super();
843
                }
844
                
845
                public void setImage (BufferedImage newimg) {
846
                        if (img != null) {
847
                                img.flush();
848
                        }
849
                        System.gc();
850
                        img = newimg;
851
                }
852
                
853
                                
854
                public void paint (Graphics g) {
855
                        
856
                        if (img == null)
857
                                return;
858
                        // Place the image on the screen, inside the panel
859
                        
860
                        int maxWidth = getWidth() - 2*BORDER;
861
                        int maxHeight = getHeight() - 2*BORDER;
862
                        double widthRatio = 1.0 * maxWidth / img.getWidth();
863
                        double heightRatio = 1.0 * maxHeight / img.getHeight();
864
                        int newWidth = 0;
865
                        int newHeight = 0;
866
                        int x = 0;
867
                        int y = 0;
868
                        
869
                        if (widthRatio > heightRatio) {  //height is the limiting factor
870
                            newHeight = maxHeight;
871
                            newWidth = img.getWidth() * maxHeight / img.getHeight();
872
                            y = BORDER;
873
                            x = (maxWidth - newWidth) / 2 + BORDER;
874
                        } else {  //width is the limiting factor
875
                            newWidth = maxWidth;
876
                            newHeight = img.getHeight() * maxWidth / img.getWidth();
877
                            x = BORDER;
878
                            y = (maxHeight - newHeight) / 2 + BORDER;
879
                        }
880
                        
881
                        Image imgScaled = img.getScaledInstance(newWidth, newHeight, Image.SCALE_FAST);
882
                        g.drawImage(imgScaled, x, y, this);
883
                        
884
                                                
885
                        // Draw Identifiers
886
                        if (robotIcons == null)
887
                                return;
888
                        
889
                        ((Graphics2D)g).setStroke(new BasicStroke(2));
890
                        for (int i = 0; i < robotIcons.size(); i++) {
891
                                RobotIcon r = robotIcons.get(i);
892
                                g.setColor(r.color);
893
                                if (widthRatio > heightRatio) {
894
                                    
895
                                
896
                                } else {
897
                                    
898
                                }
899
                                g.drawOval(r.x-RADIUS, r.y-RADIUS, 2*r.RADIUS, 2*r.RADIUS);
900
                                // If the robot has a destination, draw the vector
901
                                if (r.destx >= 0) {
902
                                    g.drawLine(r.x, r.y, r.destx, r.desty);
903
                                }
904
                        }
905
                        
906
                        // Identify currently-selected robot
907
                        if (selectedBot == -1)
908
                            return;
909
                        g.setColor(Color.YELLOW);
910
                        RobotIcon r = robotIcons.get(selectedBot);
911
                        g.drawOval(r.x-RADIUS-6, r.y-RADIUS-6, 2*r.RADIUS+12, 2*r.RADIUS+12);
912
                        
913
                }
914
        
915
        }
916
        
917
        /*
918
        *        WebcamLoader class
919
        *        Handles the loading of the webcam image.
920
        */
921
        class WebcamLoader extends Thread 
922
        {
923
                final int WEBCAMLOADER_DELAY = 500;
924
                final String IMAGE_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet.jpg";
925
                                
926
                URL imagePath;
927
                
928
                MediaTracker mt;
929
                BufferedImage image;
930
                Random rand;
931
                
932
                public WebcamLoader (JApplet applet)
933
                {
934
                        super("ColonetWebcamLoader");
935
                        mt = new MediaTracker(applet);
936
                        ImageIO.setUseCache(false);
937
                        rand = new Random();
938
                }
939
                
940
                public void run ()
941
                {
942
                        while (true) {
943
                                try {
944
                                        Thread.sleep(WEBCAMLOADER_DELAY);
945
                                        if (image != null) 
946
                                                image.flush();
947
                                        System.gc();
948
                                        try {
949
                                        imagePath = new URL(IMAGE_PATH + "?rand=" + rand.nextInt(50000));
950
                                } catch (MalformedURLException e) {
951
                                        System.out.println("Malformed URL: could not form URL from: [" + IMAGE_PATH + "]\n");
952
                                }
953
                                        image = ImageIO.read(imagePath);
954
                                        // The MediaTracker waitForID pauses the thread until the image is loaded.
955
                                        // We don't want to display a half-downloaded image.
956
                                        mt.addImage(image, 1);
957
                                        mt.waitForID(1);
958
                                        mt.removeImage(image);
959
                                        // Save
960
                                        panelWebcam.setImage(image);
961
                                } catch (InterruptedException e) {
962
                                        return;
963
                                } catch (java.security.AccessControlException e) {
964
                                        csi.warn("Could not load webcam.\n" + e);
965
                                        return;
966
                                } catch (IOException e) {
967
                                        log.append("IOException while trying to load image.");
968
                                }
969
                        }
970
                }
971
                
972
        }
973
        
974
        /*
975
        *  RobotIcon class
976
        *  Provides a means for graphically representing and keeping track of webcam bots.
977
        */
978
        class RobotIcon {
979
                public final int RADIUS = 30;
980
                public final int CLOSE = 80;
981
                
982
                public int x, y;
983
                public int destx, desty;
984
                public int id;
985
                public Color color;
986
                
987
                public RobotIcon (int id, int x, int y) {
988
                        this.color = Color.RED;
989
                        this.x = x;
990
                        this.y = y;
991
                        this.id = id;
992
                        this.destx = -1;
993
                        this.desty = -1;
994
                }
995
                
996
                /**
997
                *  Relocates this RobotIcon to a new coordinate point.
998
                *
999
                */
1000
                public void move (int newX, int newY) {
1001
                        this.x = newX;
1002
                        this.y = newY;
1003
                }
1004
                
1005
                /**
1006
                *  Determines if a given point is within a reasonable range of the current location
1007
                *  to be considered the same robot when moving. The threshold is determined by the 
1008
                *  CLOSE value.
1009
                *
1010
                *  @returns Whether or not the given point is reasonably close to the current location.
1011
                *
1012
                */
1013
                public boolean isClose (int nx, int ny) {
1014
                        int dist = (int) Point.distance(this.x, this.y, nx, ny);
1015
                        return (dist < CLOSE);
1016
                }
1017
                
1018
                /**
1019
                *  Determines whether a given point is within the rectangle that circumscribes the
1020
                *  robot's circlular icon. Used for clicking on robots in webcam view.
1021
        *
1022
        */
1023
                public boolean contains (int px, int py) {
1024
                    Rectangle rect = new Rectangle(x-RADIUS, y-RADIUS, 2*RADIUS, 2*RADIUS);
1025
                    return rect.contains(px, py);
1026
                }
1027
                
1028
                public String toString () {
1029
                        String s = "RobotIcon at (" + x + "," + y + "), id " + id;
1030
                        return s;
1031
                }
1032
                
1033
        }
1034

    
1035
        
1036
        /*
1037
        *        VectorController class
1038
        *        Manages robot motion control graphically
1039
        */
1040
        class VectorController extends GraphicsPanel implements MouseListener, MouseMotionListener {
1041
                int x, y, cx, cy;
1042
                int width, height;
1043
                int side;
1044
                
1045
                public VectorController (Image img) {
1046
                        super (img);
1047
                        width = img.getWidth(null);
1048
                        height = img.getHeight(null);
1049
                        cx = img.getWidth(null)/2;
1050
                        cy = img.getHeight(null)/2;
1051
                        x = cx;
1052
                        y = cy;
1053
                        if (width < height)
1054
                                side = width;
1055
                        else
1056
                                side = height;
1057
                        this.addMouseListener(this);
1058
                        this.addMouseMotionListener(this);
1059
                }
1060
                
1061
                public void setPoint (int x, int y) {
1062
                        if (!isValidPoint(x, y))
1063
                                return;
1064
                        this.x = x;
1065
                        this.y = y;
1066
                        repaint();
1067
                }
1068
                
1069
                public boolean isValidPoint (int x, int y) {
1070
                        double xterm = Math.pow(1.0*(x - cx)/(side/2), 2);
1071
                        double yterm = Math.pow(1.0*(y - cy)/(side/2), 2);
1072
                        return (xterm + yterm <= 1);
1073
                }
1074
                
1075
                public void notifyMouseEvent (MouseEvent e, boolean send) {
1076
                        if (!isValidPoint(e.getX(), e.getY()))
1077
                                return;
1078
                        vectorController.setPoint(e.getX(), e.getY());
1079
                        vectorController.repaint();
1080
                        if (send)
1081
                                vectorController.sendToServer();
1082
                }
1083
                
1084
                public void mouseExited(MouseEvent e) {
1085
                }
1086
                public void mouseEntered(MouseEvent e) {
1087
                }
1088
                public void mouseReleased(MouseEvent e) {
1089
                        this.notifyMouseEvent(e, true);
1090
                }
1091
                public void mouseClicked(MouseEvent e) {
1092
                        this.notifyMouseEvent(e, false);
1093
                }
1094
                public void mousePressed(MouseEvent e) {
1095
                }
1096
                public void mouseDragged(MouseEvent e) {
1097
                        vectorController.notifyMouseEvent(e, false);
1098
                }
1099
                public void mouseMoved(MouseEvent e) {
1100
                }
1101
                
1102
                public int getSpeed () {
1103
                        int dx = x - cx;
1104
                        int dy = y - cy;
1105
                        int v = (int) Math.sqrt( Math.pow(dx, 2) + Math.pow(dy, 2) );
1106
                        return v;
1107
                }
1108
                
1109
                /** 
1110
                * Returns the angle of the control vector in positive degrees west of north,
1111
                * or negative degrees east of north, whichever is less than or equal to
1112
                * 180 degrees total.
1113
                */
1114
                public int getAngle () {
1115
                        int dx = x - cx;
1116
                        int dy = cy - y;
1117
                        // find reference angle in radians
1118
                        double theta = Math.atan2(Math.abs(dx), Math.abs(dy));
1119
                        // transform to degrees
1120
                        theta = theta * 180 / Math.PI;
1121
                        // adjust for quadrant
1122
                        if (dx < 0 && dy < 0)
1123
                                theta = 90 + theta;
1124
                        else if (dx < 0 && dy >= 0)
1125
                                theta = 90 - theta;
1126
                        else if (dx >= 0 && dy < 0)
1127
                                theta = -90 - theta;
1128
                        else
1129
                                theta = -90 + theta;
1130
                        return (int) theta;
1131
                }
1132
                
1133
                public void paint (Graphics g) {
1134
                        g.setColor(Color.BLACK);
1135
                        g.fillRect(0, 0, width, height);
1136
                        ((Graphics2D)g).setStroke(new BasicStroke(1));
1137
                        g.setColor(Color.RED);
1138
                        g.drawOval(cx-side/2, cy-side/2, side, side);
1139
                        ((Graphics2D)g).setStroke(new BasicStroke(2));
1140
                        g.setColor(Color.GREEN);
1141
                        g.drawLine(cx, cy, x, y);
1142
                        g.fillOval(x-3, y-3, 6, 6);
1143
                }
1144
                
1145
                public void setMaxForward () {
1146
                        setPoint(cx, cy - (side/2) + 1);
1147
                }
1148
                
1149
                public void setMaxReverse () {
1150
                        setPoint(cx, cy + (side/2) - 1);
1151
                }
1152
                
1153
                public void setMaxLeft () {
1154
                        setPoint(cx - (side/2) + 1, cy);
1155
                }
1156
                
1157
                public void setMaxRight () {
1158
                        setPoint(cx + (side/2) - 1, cy);
1159
                }
1160
                
1161
                public void setZero () {
1162
                        setPoint(cx, cy);
1163
                }
1164
                
1165
                public void sendToServer () {
1166
                        System.out.println("Attempting to send angle = " + getAngle() + ", speed = " + getSpeed() + "");
1167
                        String dest = ColonetServerInterface.GLOBAL_DEST;
1168
                        if (cmbRobotNum != null && cmbRobotNum.getSelectedIndex() > 0) {
1169
                                dest = (String)cmbRobotNum.getSelectedItem();
1170
                        }
1171
                        
1172
                        if (csi != null) {
1173
                                /*
1174
                                csi.sendData(ColonetServerInterface.MOVE + " " + getSpeed() + " " + getAngle(), dest);
1175
                                */
1176
                                
1177
                                //Directional commands
1178
                                if (x > cx && y == cy) {  //move right
1179
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 200", dest);
1180
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 200", dest);
1181
                                } else if (x < cx && y == cy) {  //move left
1182
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 200", dest);
1183
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 200", dest);
1184
                                } else if (x == cx && y > cy) {  //move forward
1185
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 225", dest);
1186
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 225", dest);
1187
                                } else if (x == cx && y < cy) {  //move backward
1188
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 225", dest);
1189
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 225", dest);
1190
                                } else if (x == cx && y == cy) {  //stop!
1191
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 0", dest);
1192
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 0", dest);
1193
                                }
1194
                        }
1195
                }
1196
        
1197
        }
1198
        
1199
        /*
1200
        *        TaskAddWindow class
1201
        *        A window that provides a simple way to add tasks to a task queue.
1202
        */
1203
        class TaskAddWindow extends JFrame implements ActionListener, ListSelectionListener {
1204
                JPanel panelButtons;
1205
                JPanel panelParameters;
1206
                JPanel panelSouth;
1207
                JPanel panelSelection;
1208
                JButton btnSubmit;
1209
                JButton btnCancel;
1210
                DefaultListModel availableListModel;
1211
                JList availableList;
1212
                JScrollPane spAvailableTasks;
1213
                JTextArea txtDescription;
1214
                JTextField txtParameters;
1215
                
1216
                public TaskAddWindow () {
1217
                        super("Add a Task");
1218
                        super.setSize(500,500);
1219
                        super.setLayout(new BorderLayout());
1220
                        
1221
                        // set up buttons
1222
                        btnSubmit = new JButton("Submit");
1223
                        btnCancel = new JButton("Cancel");
1224
                        panelButtons = new JPanel();
1225
                        panelButtons.setLayout(new FlowLayout());
1226
                        panelButtons.add(btnSubmit);
1227
                        panelButtons.add(btnCancel);
1228
                        this.getRootPane().setDefaultButton(btnSubmit);
1229
                        
1230
                        // set up task list
1231
                        availableListModel = new DefaultListModel();
1232
                        availableListModel.addElement("Map the Environment");
1233
                        availableListModel.addElement("Clean Up Chemical Spill");
1234
                        availableListModel.addElement("Grow Plants");
1235
                        availableListModel.addElement("Save the Cheerleader");
1236
                        availableListModel.addElement("Save the World");
1237
                        availableList = new JList(availableListModel);
1238
                        availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
1239
                        availableList.setSelectedIndex(-1);
1240
                        spAvailableTasks = new JScrollPane(availableList);
1241
                        spAvailableTasks.setBorder(BorderFactory.createTitledBorder("Select A Task"));
1242
                        txtDescription = new JTextArea();
1243
                        txtDescription.setEditable(false);
1244
                        txtDescription.setLineWrap(true);
1245
                        txtDescription.setWrapStyleWord(true);
1246
                        txtDescription.setBorder(BorderFactory.createTitledBorder("Description"));
1247
                        
1248
                        //set up parameter area
1249
                        panelParameters = new JPanel();
1250
                        panelParameters.setLayout(new BorderLayout());
1251
                        txtParameters = new JTextField();
1252
                        panelParameters.add(new JLabel("Optional parameters for this task: "), BorderLayout.WEST);
1253
                        panelParameters.add(txtParameters);
1254
                        
1255
                        // assemble objects
1256
                        panelSelection = new JPanel();
1257
                        panelSelection.setLayout(new GridLayout(1,2));
1258
                        panelSelection.add(spAvailableTasks);
1259
                        panelSelection.add(txtDescription);
1260
                        
1261
                        panelSouth = new JPanel();
1262
                        panelSouth.setLayout(new GridLayout(2,1));
1263
                        panelSouth.add(panelParameters);
1264
                        panelSouth.add(panelButtons);
1265
                        
1266
                        this.getContentPane().add(panelSouth, BorderLayout.SOUTH);
1267
                        this.getContentPane().add(panelSelection, BorderLayout.CENTER);
1268
                        this.setLocationRelativeTo(null);
1269
                        
1270
                        // add listeners here
1271
                        availableList.addListSelectionListener(this);
1272
                        btnSubmit.addActionListener(this);
1273
                        btnCancel.addActionListener(this);
1274
                }
1275
                
1276
                public void prompt () {
1277
                        this.setVisible(true);
1278
                }
1279
                
1280
                private String getDescription (int index) {
1281
                        if (index < 0)
1282
                                return "";
1283
                        switch (index) {
1284
                                case 0: return "SLAM and junk";
1285
                                case 1: return "I'm not sure this works";
1286
                                case 2: return "Push them into the light";
1287
                                case 3: return "...";
1288
                                case 4: return "...";
1289
                        
1290
                                default: return "Task not recognized";
1291
                        }
1292
                }
1293
                
1294
                public void actionPerformed (ActionEvent e) {
1295
                        Object source = e.getSource();
1296
                        if (source == btnSubmit) {
1297
                                txtParameters.setText(txtParameters.getText().trim());
1298
                                
1299
                                
1300
                                this.setVisible(false);
1301
                        } else if (source == btnCancel) {
1302
                                this.setVisible(false);
1303
                        }
1304
                }
1305
                
1306
                public void valueChanged (ListSelectionEvent e) {
1307
                        int index = availableList.getSelectedIndex();
1308
                        if (index >= 0)
1309
                                txtDescription.setText(getDescription(index));
1310
                }
1311
        
1312
        }
1313
        
1314
        /*
1315
        *  BatteryIcon class
1316
        *  Graphical representation of battery level
1317
        */
1318
        class BatteryIcon implements Icon {
1319
                private int width;
1320
            private int height;
1321
            private int level;
1322
            
1323
                /** 
1324
                * Constructs a new BatteryIcon with all default parameters.
1325
                * Default width and height are 50.
1326
                * Default level is 100.
1327
                */
1328
            public BatteryIcon(){
1329
                    this(100, 50, 50);
1330
            }
1331
            
1332
                /** 
1333
                * Constructs a new BatteryIcon with default width and height, and with the specified level.
1334
                * Default width and height are 50.
1335
                */
1336
            public BatteryIcon(int startLevel){
1337
                    this(startLevel, 50, 50);
1338
            }
1339
            
1340
                /** 
1341
                * Constructs a new BatteryIcon with the specified level, width, and height.
1342
                */
1343
            public BatteryIcon(int startLevel, int w, int h){
1344
                    level = startLevel;
1345
                    width = w;
1346
                    height = h;
1347
            }
1348
            
1349
            public void paintIcon(Component c, Graphics g, int x, int y) {
1350
                Graphics2D g2d = (Graphics2D) g.create();
1351
                //clear the background
1352
                g2d.setColor(Color.WHITE);
1353
                g2d.fillRect(x + 1, y + 1, width - 2, height - 2);
1354
                //outline
1355
                g2d.setColor(Color.BLACK);
1356
                g2d.drawRect((int)(x + width*.3), y + 2, (int)(width*.4), height - 4);
1357
                //battery life rectangle
1358
                g2d.setColor(Color.GREEN);
1359
                int greenX = (int)(x + 1 + width*.3);
1360
                int greenY = (int)((y+3) + Math.abs(level-100.0)*(height-6)/(100));
1361
                int greenWidth = (int)(width*.4 - 2)+1;
1362
                int greenHeight = 1+(int)(level-0.0)*(height-6)/(100);
1363
                g2d.fillRect(greenX, greenY, greenWidth, greenHeight);
1364
                //text
1365
                g2d.setColor(Color.BLACK);
1366
                g2d.drawString(level + "%", greenX + greenWidth/2 - 10, greenY + greenHeight/2 + 5);
1367
                
1368
                g2d.dispose();
1369
            }
1370
            
1371
                /**
1372
                * Sets the battery level for this BatteryIcon. The level should be given in raw form, i.e. 0-255 directly 
1373
                * from the robot. The value will be converted to a representative percentage automatically.
1374
                *
1375
                * @param newLevel the new battery reading from the robot that this BatteryIcon will display.
1376
                */
1377
            public void setLevel(int newLevel) {
1378
                    level = convert(newLevel);
1379
                    repaint();
1380
                    System.out.println("Updated level to " + level);
1381
            }
1382
                
1383
            public int getIconWidth() {
1384
                return width;
1385
            }
1386
            
1387
            public int getIconHeight() {
1388
                return height;
1389
            }
1390
                
1391
                /**
1392
                * Converts a robot battery reading into representable form.
1393
                * Readings from the robot are returned as raw values, 0-255. This method converts the reading into a value
1394
                * from 0 to 100 so that the practical remaining charge is represented.
1395
                *
1396
                * @param level The battery level as returned by the robot.
1397
                * @returns The representable battery percentage.
1398
                */
1399
                private int convert (int level) {
1400
                        // TODO: make this a forreals conversion.
1401
                        return (int) (100.0 * level / 128);
1402
                }
1403
                
1404
        }
1405

    
1406

    
1407

    
1408
}