Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (44 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
                repaint();
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
                repaint();
493
        }
494
        
495
        /**
496
        * Parses a String containing battery information.
497
        * The ColonetServerInterface receives Strings of battery information.  (For encoding 
498
        * information, see the ColonetServerInterface documentation.)  This method takes
499
        * a string of the form "[command code] [command code] [robot ID] [value]"
500
        * with tokens separated by spaces and containing no brackets.  
501
        * The [command code]s are predefined values identifying this String as a battery
502
        * information String, [robot ID] is an integer, and [value] is a battery measurement.
503
        * This updates the batery information for a single robot.
504
        * 
505
        *
506
        * @param line the String containing battery information.
507
        * @see ColonetServerInterface#sendBatteryRequest(int)
508
        */
509
        public void parseBattery (String line) {
510
                String [] str = line.split(" ");
511
                int botNum = Integer.parseInt(str[2]);
512
                int level = Integer.parseInt(str[3]);
513
                int selected = -1;
514
                try { 
515
                    selected = Integer.parseInt((String)cmbRobotNum.getSelectedItem());
516
                } catch (Exception e) {
517
                }
518
                if (selected == botNum) {
519
                        batteryIcon.setLevel(level);
520
                }
521
                repaint();
522
        }
523
        
524
        /**
525
        * Parses a String containing visual robot position information along with 
526
        * canonical ID assignments.
527
        */
528
        public void parsePositions (String line) {
529
                String [] str = line.split(" ");
530
                java.util.List <RobotIcon> newList = new ArrayList <RobotIcon> ();
531
                
532
                for (int i = 2; i < str.length; i+=3) {
533
                        int id = Integer.parseInt(str[i]);
534
                        int x = Integer.parseInt(str[i+1]);
535
                        int y = Integer.parseInt(str[i+2]);
536
                        RobotIcon newIcon = new RobotIcon(id, x, y);
537
                        newList.add(newIcon);
538
                }
539
                
540
                robotIcons = newList;
541
                repaint();
542
        
543
        }
544
        
545
        
546
        //
547
        // MouseListener methods
548
        //
549
        public void mousePressed(MouseEvent e) {
550
            //Start a new Thread to handle the MouseEvent
551
            (new MouseHandler(e)).start();
552
        }
553
        public void mouseExited(MouseEvent e) {
554
        }
555
        public void mouseEntered(MouseEvent e) {
556
        }
557
        public void mouseReleased(MouseEvent e) {
558
        }
559
        public void mouseClicked(MouseEvent e) {
560
        }
561
        public void mouseDragged(MouseEvent e) {
562
        }
563
        public void mouseMoved(MouseEvent e) {
564
        }
565
        
566
        //
567
        // KeyListener methods
568
        //
569
        public void keyPressed (KeyEvent e) {
570
                //Start a new Thread to handle the KeyEvent
571
            (new KeyHandler(e)).start();
572
        }
573
        public void keyReleased (KeyEvent e) {
574
        }
575
        public void keyTyped (KeyEvent e) {
576
        }
577
        
578
        //
579
        // ActionListener method
580
        //
581
        public void actionPerformed (ActionEvent e) {
582
                // Start a new Thread to handle the ActionEvent
583
                (new ActionHandler(e)).start();
584
        }
585
        
586
        class MouseHandler extends Thread {
587
            
588
            MouseEvent e;
589
            
590
            public MouseHandler (MouseEvent event) {
591
                super("MouseHandler");
592
                this.e = event;
593
            }
594
        
595
            public void run () {
596
                
597
                // If we are selecting a waypoint (destination) for a specific bot
598
                if (setWaypoint && setWaypointID  >= 0) {
599
                    setWaypoint = false;
600
                    panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
601
                    if (selectedBot < 0)
602
                        return;
603
                    
604
                    RobotIcon r = robotIcons.get(selectedBot);
605
                    r.destx = e.getX();
606
                    r.desty = e.getY();
607
                    
608
                    if (csi != null)
609
                        csi.sendAbsoluteMove(r.id, r.destx, r.desty);
610
                    
611
                    return;
612
                }
613
                
614
                // Right-click also means we are moving a robot
615
                if (e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON3) {
616
                    if (selectedBot < 0)
617
                        return;
618
                    
619
                    RobotIcon r = robotIcons.get(selectedBot);
620
                    r.destx = e.getX();
621
                    r.desty = e.getY();
622
                    
623
                    if (csi != null)
624
                        csi.sendAbsoluteMove(r.id, r.destx, r.desty);
625
                    
626
                    return;
627
                }
628
                
629
                // If we are setting all waypoints
630
                if (setWaypoint) {
631
                    setWaypoint = false;
632
                    panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
633
                    for (int i = 0; i < robotIcons.size(); i++) {
634
                        RobotIcon r = robotIcons.get(i);
635
                        r.destx = e.getX();
636
                        r.desty = e.getY();
637
                    }
638
                    return;
639
                }
640
                
641
                // Otherwise, we are selecting a bot, or doing nothing
642
                    for (int i = 0; i < robotIcons.size(); i++) {
643
                        RobotIcon r = robotIcons.get(i);
644
                        if (r.contains(e.getX(), e.getY())) {
645
                            selectedBot = i;
646
                            lblSelected.setText(" " + r.id);
647
                                        // Try to select the clicked bot, if its XBee ID is detected.
648
                                        for (int j = 1; j < cmbRobotNum.getItemCount(); j++) {
649
                                                if (Integer.parseInt(cmbRobotNum.getItemAt(j).toString()) == selectedBot)
650
                                                        cmbRobotNum.setSelectedIndex(j);
651
                                        }
652
                                        return;
653
                        }
654
                    }
655
                    
656
                    repaint();
657
            }
658
        }
659
        
660
        class KeyHandler extends Thread {
661
        
662
                KeyEvent e;
663
                
664
                public KeyHandler (KeyEvent event) {
665
                        super("KeyHandler");
666
                        this.e = event;
667
                }
668
                
669
                public void run () {
670
                        int code = e.getKeyCode();
671
                        if (code == KeyEvent.VK_UP) {
672
                                vectorController.setMaxForward();
673
                                vectorController.sendToServer();
674
                        } else if (code == KeyEvent.VK_DOWN) {
675
                                vectorController.setMaxReverse();
676
                                vectorController.sendToServer();
677
                        } else if (code == KeyEvent.VK_LEFT) {
678
                                vectorController.setMaxLeft();
679
                                vectorController.sendToServer();
680
                        } else if (code == KeyEvent.VK_RIGHT) {
681
                                vectorController.setMaxRight();
682
                                vectorController.sendToServer();
683
                        } else if (code == KeyEvent.VK_S) {
684
                                vectorController.setZero();
685
                                vectorController.sendToServer();
686
                        }
687
                        repaint();
688
                }
689
        }
690
        
691
        class ActionHandler extends Thread {
692
        
693
            ActionEvent e;
694
        
695
            public ActionHandler (ActionEvent event) {
696
                super("ActionHandler");
697
                this.e = event;
698
            }
699
            
700
            public void run () {
701
                Object source = e.getSource();
702
                
703
                    // General Actions
704
                    if (source == btnConnect) {
705
                            connect();
706
                    } else if (source == btnGetXBeeIDs) {
707
                            csi.sendXBeeIDRequest();
708
                    } else if (source == btnAssignID) {
709
                        String message;
710
                        if (selectedBot < 0)
711
                            return;
712
                        int curID = robotIcons.get(selectedBot).id;
713
                        if (curID < 0)
714
                            message = "That robot is unidentified. Please specify its ID.";
715
                        else
716
                            message = "That robot has ID " + curID + ". You may reassign it now.";
717
                        String result = JOptionPane.showInputDialog(self, message, "Robot Identification", JOptionPane.QUESTION_MESSAGE);
718
                        if (result == null)
719
                            return;
720
                    int newID = -1;
721
                        try {
722
                            newID = Integer.parseInt(result);
723
                        } catch (Exception ex) {
724
                            csi.warn("Invalid ID.");
725
                            return;
726
                        }
727
                        // Assign new ID and update display  
728
                            csi.sendIDAssignment(curID, newID);
729
                        robotIcons.get(selectedBot).id = newID;
730
                        robotIcons.get(selectedBot).color = Color.GREEN;
731
                        lblSelected.setText(" " + newID);
732
                        
733
                        
734
                    }
735
                
736
                    // Robot Movement Controls
737
                    else if (source == btnF) {
738
                            vectorController.setMaxForward();
739
                            vectorController.sendToServer();
740
                    } else if (source == btnB) {
741
                            vectorController.setMaxReverse();
742
                            vectorController.sendToServer();
743
                    } else if (source == btnL) {
744
                            vectorController.setMaxLeft();
745
                            vectorController.sendToServer();
746
                    } else if (source == btnR) {
747
                            vectorController.setMaxRight();
748
                            vectorController.sendToServer();
749
                    } else if (source == btnActivate) {
750
                            vectorController.setZero();
751
                            vectorController.sendToServer();
752
                    }
753
                    // Robot Commands (non-movement)
754
                    else if (source == btnCommand_MoveTo) {
755
                        if (selectedBot < 0)
756
                            return;
757
                        panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
758
                        setWaypoint = true;
759
                        setWaypointID = selectedBot;
760
                                        
761
                    } else if (source == btnCommand_MoveAll) {
762
                        panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
763
                        setWaypoint = true;
764
                        setWaypointID = -1;
765
                                        
766
                    } else if (source == btnCommand_StopTask) {
767
                
768
                    } else if (source == btnCommand_ResumeTask) {
769
                
770
                    } else if (source == btnCommand_ChargeNow) {
771
                
772
                    } else if (source == btnCommand_StopCharging) {
773
                
774
                    }
775
                        
776
                    // Queue Management
777
                    else if (source == btnAddTask) {
778
                            taskAddWindow.prompt();
779
                    } else if (source == btnRemoveTask) {
780
                            if (taskList.getSelectedIndex() >= 0);
781
                                    csi.sendQueueRemove(taskList.getSelectedIndex());
782
                            csi.sendQueueUpdate();
783
                    } else if (source == btnMoveTaskUp) {
784
                            csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() - 1);
785
                            csi.sendQueueUpdate();
786
                    } else if (source == btnMoveTaskDown) {
787
                            csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() + 1);
788
                            csi.sendQueueUpdate();
789
                    } else if (source == btnUpdateTasks) {
790
                            csi.sendQueueUpdate();
791
                    }
792
                
793
                repaint();
794
            }
795
        
796
        }
797
        
798
        /*
799
        *        DataUpdater thread.
800
        *   The purpose of this thread is to request data from the server at regular intervals.
801
        *
802
        */
803
        class DataUpdater extends Thread {
804
                final int DATAUPDATER_DELAY = 800;
805
                
806
                public DataUpdater () {
807
                        super("Colonet DataUpdater");
808
                }
809
                
810
                public void run () {
811
                        String line;
812
                        while (true) {
813
                                try {
814
                                        //request more data
815
                                        if (csi != null && csi.isReady()) {
816
                        csi.sendPositionRequest();
817
                                                csi.sendXBeeIDRequest();
818
                                                if (cmbRobotNum.getSelectedIndex() > 0) {
819
                                                    String sel = (String) cmbRobotNum.getSelectedItem();
820
                                                    int num = Integer.parseInt(sel);
821
                                                        csi.sendBatteryRequest(num);
822
                                                }
823
                                        }
824
                                        Thread.sleep(DATAUPDATER_DELAY);
825
                                } catch (InterruptedException e) {
826
                                        return;
827
                                } 
828
                        }
829
                }
830

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

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

    
1453

    
1454

    
1455
}