Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (43.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
                //Start a new Thread to handle the KeyEvent
568
            SwingUtilities.invokeLater(new KeyHandler(e));
569
        }
570
        public void keyReleased (KeyEvent e) {
571
        }
572
        public void keyTyped (KeyEvent e) {
573
        }
574
        
575
        //
576
        // ActionListener method
577
        //
578
        public void actionPerformed (ActionEvent e) {
579
                // Start a new Thread to handle the ActionEvent
580
                SwingUtilities.invokeLater(new ActionHandler(e));
581
        }
582
        
583
        class MouseHandler extends Thread {
584
            
585
            MouseEvent e;
586
            
587
            public MouseHandler (MouseEvent event) {
588
                super("MouseHandler");
589
                this.e = event;
590
            }
591
        
592
            public void run () {
593
                
594
                // If we are selecting a waypoint (destination) for a specific bot
595
                if (setWaypoint && setWaypointID  >= 0) {
596
                    setWaypoint = false;
597
                    panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
598
                    if (selectedBot < 0)
599
                        return;
600
                    
601
                    RobotIcon r = robotIcons.get(selectedBot);
602
                    r.destx = e.getX();
603
                    r.desty = e.getY();
604
                    
605
                    if (csi != null)
606
                        csi.sendAbsoluteMove(r.id, r.destx, r.desty);
607
                    
608
                    return;
609
                }
610
                
611
                // Right-click also means we are moving a robot
612
                if (e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON3) {
613
                    if (selectedBot < 0)
614
                        return;
615
                    
616
                    RobotIcon r = robotIcons.get(selectedBot);
617
                    r.destx = e.getX();
618
                    r.desty = e.getY();
619
                    
620
                    if (csi != null)
621
                        csi.sendAbsoluteMove(r.id, r.destx, r.desty);
622
                    
623
                    return;
624
                }
625
                
626
                // If we are setting all waypoints
627
                if (setWaypoint) {
628
                    setWaypoint = false;
629
                    panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
630
                    for (int i = 0; i < robotIcons.size(); i++) {
631
                        RobotIcon r = robotIcons.get(i);
632
                        r.destx = e.getX();
633
                        r.desty = e.getY();
634
                    }
635
                    return;
636
                }
637
                
638
                // Otherwise, we are selecting a bot, or doing nothing
639
                    for (int i = 0; i < robotIcons.size(); i++) {
640
                        RobotIcon r = robotIcons.get(i);
641
                        if (r.contains(e.getX(), e.getY())) {
642
                            selectedBot = i;
643
                            lblSelected.setText(" " + r.id);
644
                                        // Try to select the clicked bot, if its XBee ID is detected.
645
                                        for (int j = 1; j < cmbRobotNum.getItemCount(); j++) {
646
                                                if (Integer.parseInt(cmbRobotNum.getItemAt(j).toString()) == selectedBot)
647
                                                        cmbRobotNum.setSelectedIndex(j);
648
                                        }
649
                                        return;
650
                        }
651
                    }
652
                    
653
                    repaint();
654
            }
655
        }
656
        
657
        class KeyHandler extends Thread {
658
        
659
                KeyEvent e;
660
                
661
                public KeyHandler (KeyEvent event) {
662
                        super("KeyHandler");
663
                        this.e = event;
664
                }
665
                
666
                public void run () {
667
                        int code = e.getKeyCode();
668
                        if (code == KeyEvent.VK_UP) {
669
                                vectorController.setMaxForward();
670
                                vectorController.sendToServer();
671
                        } else if (code == KeyEvent.VK_DOWN) {
672
                                vectorController.setMaxReverse();
673
                                vectorController.sendToServer();
674
                        } else if (code == KeyEvent.VK_LEFT) {
675
                                vectorController.setMaxLeft();
676
                                vectorController.sendToServer();
677
                        } else if (code == KeyEvent.VK_RIGHT) {
678
                                vectorController.setMaxRight();
679
                                vectorController.sendToServer();
680
                        } else if (code == KeyEvent.VK_S) {
681
                                vectorController.setZero();
682
                                vectorController.sendToServer();
683
                        }
684
                }
685
        }
686
        
687
        class ActionHandler extends Thread {
688
        
689
            ActionEvent e;
690
        
691
            public ActionHandler (ActionEvent event) {
692
                super("ActionHandler");
693
                this.e = event;
694
            }
695
            
696
            public void run () {
697
                Object source = e.getSource();
698
                
699
                    // General Actions
700
                    if (source == btnConnect) {
701
                            connect();
702
                    } else if (source == btnGetXBeeIDs) {
703
                            csi.sendXBeeIDRequest();
704
                    } else if (source == btnAssignID) {
705
                        String message;
706
                        if (selectedBot < 0)
707
                            return;
708
                        int curID = robotIcons.get(selectedBot).id;
709
                        if (curID < 0)
710
                            message = "That robot is unidentified. Please specify its ID.";
711
                        else
712
                            message = "That robot has ID " + curID + ". You may reassign it now.";
713
                        String result = JOptionPane.showInputDialog(self, message, "Robot Identification", JOptionPane.QUESTION_MESSAGE);
714
                        if (result == null)
715
                            return;
716
                    int newID = -1;
717
                        try {
718
                            newID = Integer.parseInt(result);
719
                        } catch (Exception ex) {
720
                            csi.warn("Invalid ID.");
721
                            return;
722
                        }
723
                        // Assign new ID and update display  
724
                            csi.sendIDAssignment(curID, newID);
725
                        robotIcons.get(selectedBot).id = newID;
726
                        robotIcons.get(selectedBot).color = Color.GREEN;
727
                        lblSelected.setText(" " + newID);
728
                        
729
                        
730
                    }
731
                
732
                    // Robot Movement Controls
733
                    else if (source == btnF) {
734
                            vectorController.setMaxForward();
735
                            vectorController.sendToServer();
736
                    } else if (source == btnB) {
737
                            vectorController.setMaxReverse();
738
                            vectorController.sendToServer();
739
                    } else if (source == btnL) {
740
                            vectorController.setMaxLeft();
741
                            vectorController.sendToServer();
742
                    } else if (source == btnR) {
743
                            vectorController.setMaxRight();
744
                            vectorController.sendToServer();
745
                    } else if (source == btnActivate) {
746
                            vectorController.setZero();
747
                            vectorController.sendToServer();
748
                    }
749
                    // Robot Commands (non-movement)
750
                    else if (source == btnCommand_MoveTo) {
751
                        if (selectedBot < 0)
752
                            return;
753
                        panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
754
                        setWaypoint = true;
755
                        setWaypointID = selectedBot;
756
                                        
757
                    } else if (source == btnCommand_MoveAll) {
758
                        panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
759
                        setWaypoint = true;
760
                        setWaypointID = -1;
761
                                        
762
                    } else if (source == btnCommand_StopTask) {
763
                
764
                    } else if (source == btnCommand_ResumeTask) {
765
                
766
                    } else if (source == btnCommand_ChargeNow) {
767
                
768
                    } else if (source == btnCommand_StopCharging) {
769
                
770
                    }
771
                        
772
                    // Queue Management
773
                    else if (source == btnAddTask) {
774
                            taskAddWindow.prompt();
775
                    } else if (source == btnRemoveTask) {
776
                            if (taskList.getSelectedIndex() >= 0);
777
                                    csi.sendQueueRemove(taskList.getSelectedIndex());
778
                            csi.sendQueueUpdate();
779
                    } else if (source == btnMoveTaskUp) {
780
                            csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() - 1);
781
                            csi.sendQueueUpdate();
782
                    } else if (source == btnMoveTaskDown) {
783
                            csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() + 1);
784
                            csi.sendQueueUpdate();
785
                    } else if (source == btnUpdateTasks) {
786
                            csi.sendQueueUpdate();
787
                    }
788
            
789
            }
790
        
791
        }
792
        
793
        /*
794
        *        DataUpdater thread.
795
        *   The purpose of this thread is to request data from the server at regular intervals.
796
        *
797
        */
798
        class DataUpdater extends Thread {
799
                final int DATAUPDATER_DELAY = 1200;
800
                
801
                public DataUpdater () {
802
                        super("Colonet DataUpdater");
803
                }
804
                
805
                public void run () {
806
                        String line;
807
                        while (true) {
808
                                try {
809
                                        //request more data
810
                                        if (csi != null && csi.isReady()) {
811
                        csi.sendPositionRequest();
812
                                                csi.sendXBeeIDRequest();
813
                                                if (cmbRobotNum.getSelectedIndex() > 0) {
814
                                                    String sel = (String) cmbRobotNum.getSelectedItem();
815
                                                    int num = Integer.parseInt(sel);
816
                                                        csi.sendBatteryRequest(num);
817
                                                }
818
                                        }
819
                                        Thread.sleep(DATAUPDATER_DELAY);
820
                                } catch (InterruptedException e) {
821
                                        return;
822
                                } 
823
                        }
824
                }
825

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

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

    
1440

    
1441

    
1442
}