Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (45.3 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
        Thread paintThread;
109
        SelectionIndicator indicator;
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
                try { indicator.interrupt(); } catch (Exception e) { }
146
        }
147

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

    
309
                // Put all elements in the ContentPane
310
                this.getContentPane().setLayout(new BorderLayout());
311
                this.getContentPane().add(tabPaneMain, BorderLayout.CENTER);
312
                this.getContentPane().add(panelSouth, BorderLayout.SOUTH);
313
                this.getContentPane().add(panelControl, BorderLayout.EAST);
314
                this.setVisible(true);
315
                
316
                /* Add all listeners here */
317
                // Task Management
318
                btnAddTask.addActionListener(this);
319
                btnRemoveTask.addActionListener(this);
320
                btnMoveTaskUp.addActionListener(this);
321
                btnMoveTaskDown.addActionListener(this);
322
                btnUpdateTasks.addActionListener(this);
323
                // Robot Control
324
                btnF.addActionListener(this);
325
                btnB.addActionListener(this);
326
                btnL.addActionListener(this);
327
                btnR.addActionListener(this);
328
                btnF.addKeyListener(this);
329
                btnB.addKeyListener(this);
330
                btnL.addKeyListener(this);
331
                btnR.addKeyListener(this);
332
                btnActivate.addActionListener(this);
333
                btnActivate.addKeyListener(this);
334
                cmbRobotNum.addKeyListener(this);
335
                btnCommand_MoveTo.addActionListener(this);
336
                btnCommand_MoveAll.addActionListener(this);
337
                btnCommand_StopTask.addActionListener(this);
338
                btnCommand_ResumeTask.addActionListener(this);
339
                btnCommand_ChargeNow.addActionListener(this);
340
                btnCommand_StopCharging.addActionListener(this);
341
                // Other
342
                btnConnect.addActionListener(this);
343
                btnGetXBeeIDs.addActionListener(this);
344
                btnAssignID.addActionListener(this);
345
                panelWebcam.addMouseListener(this);        
346
                                
347
                // Set up animation threads
348
                indicator = new SelectionIndicator(canvas);
349
                indicator.setRadius(RADIUS+3, 15);  //a tad more than the bot radius
350
        
351
        }
352
        
353
        public void run () {
354
                while (true) {
355
                        repaint();
356
                        try { 
357
                                Thread.sleep(90);
358
                        } catch (InterruptedException e) {
359
                                return;
360
                        }
361
                }
362
        }
363
        
364
        public void paint (Graphics g) {
365
            super.paint(g);
366
        }
367
        
368
        public void update (Graphics g) {
369
            paint(g);
370
        }
371
                
372
        /** 
373
        * Gets the JTextArea used for storing the activity log. This method returns a reference to the 
374
        * JTextArea that stores the log. The log can contain any activity that is revelant to the use
375
        * of the applet, and may optionally display debugging information.
376
        *
377
        * @return the JTextArea where BOM matrix information is stored.
378
        */ 
379
        public JTextArea getLog () {
380
                return log;
381
        }
382
        
383
        /** 
384
        * Gets the JTextArea used for storing the BOM matrix data. This method returns a reference to the 
385
        * JTextArea that stores the BOM matrix. The values in the matrix are stored as integers separated 
386
        * by spaces, and the lines should be separated by a newline.
387
        * 
388
        * @return the JTextArea where BOM matrix information is stored.
389
        */
390
        public JTextArea getMatrixInput () {
391
                return txtMatrix;
392
        }
393
        
394
        /**
395
        * Parses a String containing BOM matrix information.
396
        * The ColonetServerInterface receives lines of the BOM matrix.  (For encoding 
397
        * information, see the ColonetServerInterface documentation.)  The entire matrix is passed
398
        * to the client when requested. This method takes a string of the form 
399
        * "[command code] [command code] [number of robots] [data0] [data1] ..."
400
        * with tokens separated by spaces and containing no brackets.  
401
        * The [command code]s are predefined values identifying this String as a BOM data
402
        * String, [number of robots] is an integer, and the values that follow are 
403
        * the sensor readings of the robots in order, starting with robot 0.  Only [number of robots]^2
404
        * data entries will be read.  The matrix values are saved locally until the next String is parsed.
405
        * 
406
        *
407
        * @param line the String containing BOM matrix information.
408
        * @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots]^2 data entries in the String
409
        */
410
        public void parseMatrix (String line) {
411
                txtMatrix.setText("");
412
                String [] str = line.split(" ");
413
                int num = Integer.parseInt(str[2]);
414
                for (int i = 0; i < num; i++) {
415
                        for (int j = 0; j < num; j++) {
416
                                String next = str[3 + i*num + j];
417
                                if (next.equals("-1"))
418
                                        txtMatrix.append("-");
419
                                else 
420
                                        txtMatrix.append(next);
421
                                if (j < num - 1) 
422
                                        txtMatrix.append(" ");
423
                        }
424
                        if (i < num - 1) 
425
                                txtMatrix.append("\n");
426
                }
427
                
428
        }
429
        
430
        public void connect () {
431
            webcamLoader = new WebcamLoader(this);
432
                dataUpdater = new DataUpdater();
433
                paintThread = new Thread(this, "paintThread");
434
                csi = new ColonetServerInterface(this);
435
                csi.connect(txtHost.getText(), txtPort.getText());
436
                if (!csi.isReady())
437
                        return;
438
                btnConnect.setEnabled(false);
439
                lblConnectionStatus.setText("Status: Connected");
440
                //paintThread.start();
441
                dataUpdater.start();
442
                webcamLoader.start();
443
        }
444
        
445
        public void disconnect () {
446
            btnConnect.setEnabled(true);
447
            lblConnectionStatus.setText("Status: Disconnected");
448
            try { paintThread.interrupt(); } catch (Exception e) { }
449
                try { indicator.interrupt(); } catch (Exception e) { }
450
                
451
        }
452
        
453
        /**
454
        * Parses a String containing a task queue update.
455
        * Format is currently not specified.
456
        * This method currently does nothing.
457
        *
458
        * @param line the String containing task queue update information.
459
        */
460
        public void parseQueue (String line) {
461
                log.append("Got queue update\n");
462
                //TODO: display new queue data in tasks tab
463
        }
464
        
465
        /**
466
        * Parses a String containing XBee ID values.
467
        * The ColonetServerInterface receives Strings of XBee information.  (For encoding 
468
        * information, see the ColonetServerInterface documentation.)  This method takes
469
        * a string of the form "[command code] [command code] [number of robots] [id0] [id1] ..."
470
        * with tokens separated by spaces and containing no brackets.  
471
        * The [command code]s are predefined values identifying this String as an XBee
472
        * ID String, [number of robots] is an integer, and the values that follow are 
473
        * the IDs of the robots in order, starting with robot 0.  Only [number of robots] 
474
        * will be read.  The ID values are saved locally until the next String is parsed.
475
        * The purpose of having this list is to ensure that robots are properly identified for control purposes.
476
        * This keeps robot identification consistent between sessions and prevents arbitrary assignment. 
477
        *
478
        * @param line the String containing XBee ID information.
479
        * @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots] IDs in the String
480
        * @see ColonetServerInterface#sendXBeeIDRequest()
481
        */
482
        public void parseXBeeIDs (String line) {
483
        
484
                String [] str = line.split(" ");
485
                int num = Integer.parseInt(str[2]);
486
                xbeeID = new int[num];
487
                for (int i = 0; i < num; i++)
488
                        xbeeID[i] = Integer.parseInt(str[i+3]);
489
                
490
                //update the list of robots to control
491
                //but save the old value first
492
                Object oldSelection = cmbRobotNum.getSelectedItem();
493
                cmbRobotNum.removeAllItems();
494
                cmbRobotNum.addItem(new String("   All   "));
495
                for (int i = 0; i < num; i++)
496
                        cmbRobotNum.addItem(new String("" + xbeeID[i]));
497
                cmbRobotNum.setSelectedItem(oldSelection);
498
        }
499
        
500
        /**
501
        * Parses a String containing battery information.
502
        * The ColonetServerInterface receives Strings of battery information.  (For encoding 
503
        * information, see the ColonetServerInterface documentation.)  This method takes
504
        * a string of the form "[command code] [command code] [robot ID] [value]"
505
        * with tokens separated by spaces and containing no brackets.  
506
        * The [command code]s are predefined values identifying this String as a battery
507
        * information String, [robot ID] is an integer, and [value] is a battery measurement.
508
        * This updates the batery information for a single robot.
509
        * 
510
        *
511
        * @param line the String containing battery information.
512
        * @see ColonetServerInterface#sendBatteryRequest(int)
513
        */
514
        public void parseBattery (String line) {
515
                String [] str = line.split(" ");
516
                int botNum = Integer.parseInt(str[2]);
517
                int level = Integer.parseInt(str[3]);
518
                int selected = -1;
519
                try { 
520
                    selected = Integer.parseInt((String)cmbRobotNum.getSelectedItem());
521
                } catch (Exception e) {
522
                }
523
                if (selected == botNum) {
524
                        batteryIcon.setLevel(level);
525
                }
526
        }
527
        
528
        /**
529
        * Parses a String containing visual robot position information along with 
530
        * canonical ID assignments.
531
        */
532
        public void parsePositions (String line) {
533
                String [] str = line.split(" ");
534
                java.util.List <RobotIcon> newList = new ArrayList <RobotIcon> ();
535
                
536
                for (int i = 2; i < str.length; i+=3) {
537
                        int id = Integer.parseInt(str[i]);
538
                        int x = Integer.parseInt(str[i+1]);
539
                        int y = Integer.parseInt(str[i+2]);
540
                        RobotIcon newIcon = new RobotIcon(id, x, y);
541
                        newList.add(newIcon);
542
                }
543
                
544
                robotIcons = newList;
545
        
546
        }
547
        
548
        
549
        //
550
        // MouseListener methods
551
        //
552
        public void mouseExited(MouseEvent e) {
553
        }
554
        public void mouseEntered(MouseEvent e) {
555
        }
556
        public void mouseReleased(MouseEvent e) {
557
        }
558
        public void mouseClicked(MouseEvent e) {
559
        }
560
        public void mousePressed(MouseEvent e) {
561
        
562
            // If we are selecting a waypoint (destination) for a specific bot
563
            if (setWaypoint && setWaypointID  >= 0) {
564
                setWaypoint = false;
565
                panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
566
                if (selectedBot < 0)
567
                    return;
568
                
569
                RobotIcon r = robotIcons.get(selectedBot);
570
                r.destx = e.getX();
571
                r.desty = e.getY();
572
                
573
                if (csi != null)
574
                    csi.sendAbsoluteMove(r.id, r.destx, r.desty);
575
                
576
                return;
577
            }
578
            
579
            // Right-click also means we are moving a robot
580
            if (e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON3) {
581
                if (selectedBot < 0)
582
                    return;
583
                
584
                RobotIcon r = robotIcons.get(selectedBot);
585
                r.destx = e.getX();
586
                r.desty = e.getY();
587
                
588
                if (csi != null)
589
                    csi.sendAbsoluteMove(r.id, r.destx, r.desty);
590
                
591
                return;
592
            }
593
            
594
            // If we are setting all waypoints
595
            if (setWaypoint) {
596
                setWaypoint = false;
597
                panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
598
                for (int i = 0; i < robotIcons.size(); i++) {
599
                    RobotIcon r = robotIcons.get(i);
600
                    r.destx = e.getX();
601
                    r.desty = e.getY();
602
                }
603
                return;
604
            }
605
            
606
            // Otherwise, we are selecting a bot, or doing nothing
607
                for (int i = 0; i < robotIcons.size(); i++) {
608
                    RobotIcon r = robotIcons.get(i);
609
                    if (r.contains(e.getX(), e.getY())) {
610
                        selectedBot = i;
611
                        lblSelected.setText(" " + r.id);
612
                    }
613
                }
614
                repaint();
615
        }
616
        public void mouseDragged(MouseEvent e) {
617
        }
618
        public void mouseMoved(MouseEvent e) {
619
        }
620
        
621
        //
622
        // KeyListener methods
623
        //
624
        public void keyPressed (KeyEvent e) {
625
                int code = e.getKeyCode();
626
                if (code == KeyEvent.VK_UP) {
627
                        vectorController.setMaxForward();
628
                        vectorController.sendToServer();
629
                } else if (code == KeyEvent.VK_DOWN) {
630
                        vectorController.setMaxReverse();
631
                        vectorController.sendToServer();
632
                } else if (code == KeyEvent.VK_LEFT) {
633
                        vectorController.setMaxLeft();
634
                        vectorController.sendToServer();
635
                } else if (code == KeyEvent.VK_RIGHT) {
636
                        vectorController.setMaxRight();
637
                        vectorController.sendToServer();
638
                } else if (code == KeyEvent.VK_S) {
639
                        vectorController.setZero();
640
                        vectorController.sendToServer();
641
                }
642
        }
643
        public void keyReleased (KeyEvent e) {
644
        }
645
        public void keyTyped (KeyEvent e) {
646
        }
647
        
648
        
649
        //
650
        // ActionListener method
651
        //
652
        public void actionPerformed (ActionEvent e) {
653
                Object source = e.getSource();
654
                
655
                // General Actions
656
                if (source == btnConnect) {
657
                        connect();
658
                } else if (source == btnGetXBeeIDs) {
659
                        csi.sendXBeeIDRequest();
660
                } else if (source == btnAssignID) {
661
                    String message;
662
                    if (selectedBot < 0)
663
                        return;
664
                    int curID = robotIcons.get(selectedBot).id;
665
                    if (curID < 0)
666
                        message = "That robot is unidentified. Please specify its ID.";
667
                    else
668
                        message = "That robot has ID " + curID + ". You may reassign it now.";
669
                    String result = JOptionPane.showInputDialog(this, message, "Robot Identification", JOptionPane.QUESTION_MESSAGE);
670
                    if (result == null)
671
                        return;
672
                int newID = -1;
673
                    try {
674
                        newID = Integer.parseInt(result);
675
                    } catch (Exception ex) {
676
                        csi.warn("Invalid ID.");
677
                        return;
678
                    }
679
                    // Assign new ID and update display  
680
                        csi.sendIDAssignment(curID, newID);
681
                    robotIcons.get(selectedBot).id = newID;
682
                    robotIcons.get(selectedBot).color = Color.GREEN;
683
                    lblSelected.setText(" " + newID);
684
                    
685
                        
686
                }
687
                
688
                // Robot Movement Controls
689
                else if (source == btnF) {
690
                        vectorController.setMaxForward();
691
                        vectorController.sendToServer();
692
                } else if (source == btnB) {
693
                        vectorController.setMaxReverse();
694
                        vectorController.sendToServer();
695
                } else if (source == btnL) {
696
                        vectorController.setMaxLeft();
697
                        vectorController.sendToServer();
698
                } else if (source == btnR) {
699
                        vectorController.setMaxRight();
700
                        vectorController.sendToServer();
701
                } else if (source == btnActivate) {
702
                        vectorController.setZero();
703
                        vectorController.sendToServer();
704
                }
705
                // Robot Commands (non-movement)
706
                else if (source == btnCommand_MoveTo) {
707
                    if (selectedBot < 0)
708
                        return;
709
                    panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
710
                    setWaypoint = true;
711
                    setWaypointID = selectedBot;
712
                                    
713
                } else if (source == btnCommand_MoveAll) {
714
                    panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
715
                    setWaypoint = true;
716
                    setWaypointID = -1;
717
                                    
718
                } else if (source == btnCommand_StopTask) {
719
                
720
                } else if (source == btnCommand_ResumeTask) {
721
                
722
                } else if (source == btnCommand_ChargeNow) {
723
                
724
                } else if (source == btnCommand_StopCharging) {
725
                
726
                }
727
                        
728
                // Queue Management
729
                else if (source == btnAddTask) {
730
                        taskAddWindow.prompt();
731
                } else if (source == btnRemoveTask) {
732
                        if (taskList.getSelectedIndex() >= 0);
733
                                csi.sendQueueRemove(taskList.getSelectedIndex());
734
                        csi.sendQueueUpdate();
735
                } else if (source == btnMoveTaskUp) {
736
                        csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() - 1);
737
                        csi.sendQueueUpdate();
738
                } else if (source == btnMoveTaskDown) {
739
                        csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() + 1);
740
                        csi.sendQueueUpdate();
741
                } else if (source == btnUpdateTasks) {
742
                        csi.sendQueueUpdate();
743
                }
744
        }
745
        
746
        /*
747
        *        SelectionIndicator thread.
748
        *        Graphical representation of the selection marker
749
        *
750
        *        step() and draw() are synchronized methods. step() is private and 
751
        *        used to update the position of the crosshairs. draw() is called 
752
        *        externally and should only run if all calculations in step() have
753
        *        been completed.
754
        */
755
        private class SelectionIndicator extends Thread {
756
        
757
                final int INDICATOR_DELAY = 180;
758
                final double DTHETA = 0.4;    //larger values make the marker rotate faster
759
                Graphics2D g;   //canvas to draw on
760
                boolean running;
761
                
762
                int sx, sy;                //center
763
                int r, dr;                //radius and width of marker
764
                double theta;   //current angle
765
                
766
                volatile Polygon poly1, poly2, poly3, poly4;
767
                
768
                int px1, py1;
769
                int rx1, ry1;
770
                int px2, py2;
771
                int rx2, ry2;
772
                int px3, py3;
773
                int rx3, ry3;
774
                int px4, py4;
775
                int rx4, ry4;
776
                
777
                int steps;
778
        
779
                public SelectionIndicator (Graphics2D g) {
780
                        super("SelectionIndicator");
781
                        this.g = g;
782
                        running = false;
783
                        steps = 0;
784
                        
785
                        theta = 0;
786
                        rx1 = 0; ry1 = 0;
787
                        px1 = 0; py1 = 0;
788
                        rx2 = 0; ry2 = 0;
789
                        px2 = 0; py2 = 0;
790
                        rx3 = 0; ry3 = 0;
791
                        px3 = 0; py3 = 0;
792
                        rx4 = 0; ry4 = 0;
793
                        px4 = 0; py4 = 0;
794
                }
795
                
796
                public synchronized void setCenter (int sx, int sy) {
797
                        if (sx == this.sx && sy == this.sy) return;
798
                        this.sx = sx;
799
                        this.sy = sy;
800
                        steps = 0;
801
                }
802
                
803
                public synchronized void setRadius (int r, int dr) {
804
                        this.r = r;
805
                        this.dr = dr;
806
                        steps = 0;
807
                }
808
                
809
                public void run () {
810
                        running = true;
811
                        while (running) {
812
                                step();
813
                                try { 
814
                                        Thread.sleep(INDICATOR_DELAY);
815
                                } catch (InterruptedException e) {
816
                                        running = false;
817
                                        return;
818
                                }
819
                        }
820
                }
821
                
822
                private synchronized void step () {
823
                        Polygon poly1_new = new Polygon();
824
                        Polygon poly2_new = new Polygon();
825
                        Polygon poly3_new = new Polygon();
826
                        Polygon poly4_new = new Polygon();
827
                
828
                        //the step
829
                        theta = (theta + DTHETA/Math.PI) % (Math.PI);
830
                        
831
                        //the calculation
832
                        //let p be the point of the pointy thing toward the center
833
                        //let r be the point at the opposite side
834
                        
835
                        //recalculate radius, if it will look cool, lolz
836
                        int newr = r;
837
                        if (steps < 100)
838
                        newr = (int)( r + 200/(steps+1) );
839
                        
840
                        //precompute values for dx and dy
841
                        int dx_inner = (int)(newr * Math.cos(theta));
842
                        int dy_inner = (int)(newr * Math.sin(theta));
843
                        int dx_outer = (int)((newr+dr) * Math.cos(theta));
844
                        int dy_outer = (int)((newr+dr) * Math.sin(theta));
845
                        
846
                        //calculate polygon constants
847
                        int dy_poly = (int)(dr/2 * Math.cos(theta));
848
                        int dx_poly = (int)(dr/2 * Math.sin(theta));
849
                        
850
                        //determine critical points
851
                        //kansas city shuffle!
852
                        px1 = sx + dx_inner;
853
                        py1 = sy - dy_inner;
854
                        rx1 = sx + dx_outer;
855
                        ry1 = sy - dy_outer;
856
                        px2 = sx - dx_inner;
857
                        py2 = sy + dy_inner;
858
                        rx2 = sx - dx_outer;
859
                        ry2 = sy + dy_outer;
860
                        px3 = sx - dy_inner;
861
                        py3 = sy - dx_inner;
862
                        rx3 = sx - dy_outer;
863
                        ry3 = sy - dx_outer;
864
                        px4 = sx + dy_inner;
865
                        py4 = sy + dx_inner;
866
                        rx4 = sx + dy_outer;
867
                        ry4 = sy + dx_outer;
868
                        
869
                        //create polygons
870
                        poly1_new.addPoint(px1, py1);
871
                        poly1_new.addPoint(rx1+dx_poly, ry1+dy_poly);
872
                        poly1_new.addPoint(rx1-dx_poly, ry1-dy_poly);
873
                        poly2_new.addPoint(px2, py2);
874
                        poly2_new.addPoint(rx2+dx_poly, ry2+dy_poly);
875
                        poly2_new.addPoint(rx2-dx_poly, ry2-dy_poly);
876
                        poly3_new.addPoint(px3, py3);
877
                        poly3_new.addPoint(rx3-dy_poly, ry3+dx_poly);
878
                        poly3_new.addPoint(rx3+dy_poly, ry3-dx_poly);
879
                        poly4_new.addPoint(px4, py4);
880
                        poly4_new.addPoint(rx4-dy_poly, ry4+dx_poly);
881
                        poly4_new.addPoint(rx4+dy_poly, ry4-dx_poly);
882
                        
883
                        //reassign updated polygons
884
                        poly1 = poly1_new;
885
                        poly2 = poly2_new;
886
                        poly3 = poly3_new;
887
                        poly4 = poly4_new;
888
                
889
                        if (steps < 300) steps++;
890
                }
891
                
892
                public synchronized void draw () {
893
                        if (!running) return;
894
                        g.setColor(Color.GRAY);
895
                        //draw polygons
896
                        g.fillPolygon(poly1);
897
                        g.fillPolygon(poly2);
898
                        g.fillPolygon(poly3);
899
                        g.fillPolygon(poly4);
900
                }
901
        
902
        }
903
        
904
        /*
905
        *        DataUpdater thread.
906
        *   The purpose of this thread is to request data from the server at regular intervals.
907
        *
908
        */
909
        class DataUpdater extends Thread {
910
                final int DATAUPDATER_DELAY = 2200;
911
                
912
                public DataUpdater () {
913
                        super("Colonet DataUpdater");
914
                }
915
                
916
                public void run () {
917
                        String line;
918
                        while (true) {
919
                                try {
920
                                        //request more data
921
                                        if (csi != null && csi.isReady()) {
922
                        csi.sendPositionRequest();
923
                                                csi.sendXBeeIDRequest();
924
                                                if (cmbRobotNum.getSelectedIndex() > 0) {
925
                                                    String sel = (String) cmbRobotNum.getSelectedItem();
926
                                                    int num = Integer.parseInt(sel);
927
                                                        csi.sendBatteryRequest(num);
928
                                                }
929
                                        }
930
                                        Thread.sleep(DATAUPDATER_DELAY);
931
                                } catch (InterruptedException e) {
932
                                        return;
933
                                } 
934
                        }
935
                }
936

    
937
        }
938
        
939
        /*
940
        *        GraphicsPanel class
941
        *        An extension of JPanel, designed for holding an image that will be repainted regularly.
942
        */
943
        class GraphicsPanel extends JPanel {
944
                protected Image img;
945
        
946
                public GraphicsPanel (Image img) {
947
                        super();
948
                        this.img = img;
949
                }
950
                
951
                public GraphicsPanel (Image img, boolean isDoubleBuffered) {
952
                        super(isDoubleBuffered);
953
                        this.img = img;
954
                }
955
                
956
                public void paint (Graphics g) {
957
                        // Place the buffered image on the screen, inside the panel
958
                        g.drawImage(img, 0, 0, Color.WHITE, this);
959
                }
960
        
961
        }
962
        
963
        /*
964
        *        WebcamPanel class
965
        *        Enables more efficient image handling in a component-controlled environment
966
        */
967
        class WebcamPanel extends JPanel {
968
                int BORDER = 16;  // this is arbitrary. it makes the image look nice inside a border.
969
                int BOT_RADIUS = 40;
970
                volatile BufferedImage img;
971
        
972
                public WebcamPanel () {
973
                        super();
974
                }
975
                
976
                public void setImage (BufferedImage newimg) {
977
                        if (img != null) {
978
                                img.flush();
979
                        }
980
                        System.gc();
981
                        img = newimg;
982
                }
983
                
984
                                
985
                public void paint (Graphics g) {
986
                        
987
                        if (img == null)
988
                                return;
989
                        // Place the image on the screen, inside the panel
990
                        
991
                        int maxWidth = getWidth() - 2*BORDER;
992
                        int maxHeight = getHeight() - 2*BORDER;
993
                        double widthRatio = 1.0 * maxWidth / img.getWidth();
994
                        double heightRatio = 1.0 * maxHeight / img.getHeight();
995
                        int newWidth = 0;
996
                        int newHeight = 0;
997
                        int x = 0;
998
                        int y = 0;
999
                        
1000
                        if (widthRatio > heightRatio) {  //height is the limiting factor
1001
                            newHeight = maxHeight;
1002
                            newWidth = img.getWidth() * maxHeight / img.getHeight();
1003
                            y = BORDER;
1004
                            x = (maxWidth - newWidth) / 2 + BORDER;
1005
                        } else {  //width is the limiting factor
1006
                            newWidth = maxWidth;
1007
                            newHeight = img.getHeight() * maxWidth / img.getWidth();
1008
                            x = BORDER;
1009
                            y = (maxHeight - newHeight) / 2 + BORDER;
1010
                        }
1011
                        
1012
                        Image imgScaled = img.getScaledInstance(newWidth, newHeight, Image.SCALE_FAST);
1013
                        g.drawImage(imgScaled, x, y, this);
1014
                        
1015
                                                
1016
                        // Draw Identifiers
1017
                        if (robotIcons == null)
1018
                                return;
1019
                        
1020
                        ((Graphics2D)g).setStroke(new BasicStroke(2));
1021
                        for (int i = 0; i < robotIcons.size(); i++) {
1022
                                RobotIcon r = robotIcons.get(i);
1023
                                g.setColor(r.color);
1024
                                if (widthRatio > heightRatio) {
1025
                                    
1026
                                
1027
                                } else {
1028
                                    
1029
                                }
1030
                                g.drawOval(r.x-RADIUS, r.y-RADIUS, 2*r.RADIUS, 2*r.RADIUS);
1031
                                // If the robot has a destination, draw the vector
1032
                                if (r.destx >= 0) {
1033
                                    g.drawLine(r.x, r.y, r.destx, r.desty);
1034
                                }
1035
                        }
1036
                        
1037
                        // Identify currently-selected robot
1038
                        if (selectedBot == -1)
1039
                            return;
1040
                        g.setColor(Color.YELLOW);
1041
                        RobotIcon r = robotIcons.get(selectedBot);
1042
                        g.drawOval(r.x-RADIUS-6, r.y-RADIUS-6, 2*r.RADIUS+12, 2*r.RADIUS+12);
1043
                        
1044
                }
1045
        
1046
        }
1047
        
1048
        /*
1049
        *        WebcamLoader class
1050
        *        Handles the loading of the webcam image.
1051
        */
1052
        class WebcamLoader extends Thread 
1053
        {
1054
                final int WEBCAMLOADER_DELAY = 300;
1055
                final String IMAGE_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet.jpg";
1056
                                
1057
                URL imagePath;
1058
                
1059
                MediaTracker mt;
1060
                BufferedImage image;
1061
                Random rand;
1062
                
1063
                public WebcamLoader (JApplet applet)
1064
                {
1065
                        super("ColonetWebcamLoader");
1066
                        mt = new MediaTracker(applet);
1067
                        ImageIO.setUseCache(false);
1068
                        rand = new Random();
1069
                }
1070
                
1071
                public void run ()
1072
                {
1073
                        while (true) {
1074
                                try {
1075
                                        Thread.sleep(WEBCAMLOADER_DELAY);
1076
                                        if (image != null) 
1077
                                                image.flush();
1078
                                        System.gc();
1079
                                        try {
1080
                                        imagePath = new URL(IMAGE_PATH + "?rand=" + rand.nextInt(50000));
1081
                                } catch (MalformedURLException e) {
1082
                                        System.out.println("Malformed URL: could not form URL from: [" + IMAGE_PATH + "]\n");
1083
                                }
1084
                                        image = ImageIO.read(imagePath);
1085
                                        // The MediaTracker waitForID pauses the thread until the image is loaded.
1086
                                        // We don't want to display a half-downloaded image.
1087
                                        mt.addImage(image, 1);
1088
                                        mt.waitForID(1);
1089
                                        mt.removeImage(image);
1090
                                        // Save
1091
                                        panelWebcam.setImage(image);
1092
                                } catch (InterruptedException e) {
1093
                                        return;
1094
                                } catch (java.security.AccessControlException e) {
1095
                                        csi.warn("Could not load webcam.\n" + e);
1096
                                        return;
1097
                                } catch (IOException e) {
1098
                                        log.append("IOException while trying to load image.");
1099
                                }
1100
                        }
1101
                }
1102
                
1103
        }
1104
        
1105
        /*
1106
        *  RobotIcon class
1107
        *  Provides a means for graphically representing and keeping track of webcam bots.
1108
        */
1109
        class RobotIcon {
1110
                public final int RADIUS = 30;
1111
                public final int CLOSE = 80;
1112
                
1113
                public int x, y;
1114
                public int destx, desty;
1115
                public int id;
1116
                public Color color;
1117
                
1118
                public RobotIcon (int id, int x, int y) {
1119
                        this.color = Color.RED;
1120
                        this.x = x;
1121
                        this.y = y;
1122
                        this.id = id;
1123
                        this.destx = -1;
1124
                        this.desty = -1;
1125
                }
1126
                
1127
                /**
1128
                *  Relocates this RobotIcon to a new coordinate point.
1129
                *
1130
                */
1131
                public void move (int newX, int newY) {
1132
                        this.x = newX;
1133
                        this.y = newY;
1134
                }
1135
                
1136
                /**
1137
                *  Determines if a given point is within a reasonable range of the current location
1138
                *  to be considered the same robot when moving. The threshold is determined by the 
1139
                *  CLOSE value.
1140
                *
1141
                *  @returns Whether or not the given point is reasonably close to the current location.
1142
                *
1143
                */
1144
                public boolean isClose (int nx, int ny) {
1145
                        int dist = (int) Point.distance(this.x, this.y, nx, ny);
1146
                        return (dist < CLOSE);
1147
                }
1148
                
1149
                /**
1150
                *  Determines whether a given point is within the rectangle that circumscribes the
1151
                *  robot's circlular icon. Used for clicking on robots in webcam view.
1152
        *
1153
        */
1154
                public boolean contains (int px, int py) {
1155
                    Rectangle rect = new Rectangle(x-RADIUS, y-RADIUS, 2*RADIUS, 2*RADIUS);
1156
                    return rect.contains(px, py);
1157
                }
1158
                
1159
                public String toString () {
1160
                        String s = "RobotIcon at (" + x + "," + y + "), id " + id;
1161
                        return s;
1162
                }
1163
                
1164
        }
1165

    
1166
        
1167
        /*
1168
        *        VectorController class
1169
        *        Manages robot motion control graphically
1170
        */
1171
        class VectorController extends GraphicsPanel implements MouseListener, MouseMotionListener {
1172
                int x, y, cx, cy;
1173
                int width, height;
1174
                int side;
1175
                
1176
                public VectorController (Image img) {
1177
                        super (img);
1178
                        width = img.getWidth(null);
1179
                        height = img.getHeight(null);
1180
                        cx = img.getWidth(null)/2;
1181
                        cy = img.getHeight(null)/2;
1182
                        x = cx;
1183
                        y = cy;
1184
                        if (width < height)
1185
                                side = width;
1186
                        else
1187
                                side = height;
1188
                        this.addMouseListener(this);
1189
                        this.addMouseMotionListener(this);
1190
                }
1191
                
1192
                public void setPoint (int x, int y) {
1193
                        if (!isValidPoint(x, y))
1194
                                return;
1195
                        this.x = x;
1196
                        this.y = y;
1197
                        repaint();
1198
                }
1199
                
1200
                public boolean isValidPoint (int x, int y) {
1201
                        double xterm = Math.pow(1.0*(x - cx)/(side/2), 2);
1202
                        double yterm = Math.pow(1.0*(y - cy)/(side/2), 2);
1203
                        return (xterm + yterm <= 1);
1204
                }
1205
                
1206
                public void notifyMouseEvent (MouseEvent e, boolean send) {
1207
                        if (!isValidPoint(e.getX(), e.getY()))
1208
                                return;
1209
                        vectorController.setPoint(e.getX(), e.getY());
1210
                        vectorController.repaint();
1211
                        if (send)
1212
                                vectorController.sendToServer();
1213
                }
1214
                
1215
                public void mouseExited(MouseEvent e) {
1216
                }
1217
                public void mouseEntered(MouseEvent e) {
1218
                }
1219
                public void mouseReleased(MouseEvent e) {
1220
                        this.notifyMouseEvent(e, true);
1221
                }
1222
                public void mouseClicked(MouseEvent e) {
1223
                        this.notifyMouseEvent(e, false);
1224
                }
1225
                public void mousePressed(MouseEvent e) {
1226
                }
1227
                public void mouseDragged(MouseEvent e) {
1228
                        vectorController.notifyMouseEvent(e, false);
1229
                }
1230
                public void mouseMoved(MouseEvent e) {
1231
                }
1232
                
1233
                public int getSpeed () {
1234
                        int dx = x - cx;
1235
                        int dy = y - cy;
1236
                        int v = (int) Math.sqrt( Math.pow(dx, 2) + Math.pow(dy, 2) );
1237
                        return v;
1238
                }
1239
                
1240
                /** 
1241
                * Returns the angle of the control vector in positive degrees west of north,
1242
                * or negative degrees east of north, whichever is less than or equal to
1243
                * 180 degrees total.
1244
                */
1245
                public int getAngle () {
1246
                        int dx = x - cx;
1247
                        int dy = cy - y;
1248
                        // find reference angle in radians
1249
                        double theta = Math.atan2(Math.abs(dx), Math.abs(dy));
1250
                        // transform to degrees
1251
                        theta = theta * 180 / Math.PI;
1252
                        // adjust for quadrant
1253
                        if (dx < 0 && dy < 0)
1254
                                theta = 90 + theta;
1255
                        else if (dx < 0 && dy >= 0)
1256
                                theta = 90 - theta;
1257
                        else if (dx >= 0 && dy < 0)
1258
                                theta = -90 - theta;
1259
                        else
1260
                                theta = -90 + theta;
1261
                        return (int) theta;
1262
                }
1263
                
1264
                public void paint (Graphics g) {
1265
                        g.setColor(Color.BLACK);
1266
                        g.fillRect(0, 0, width, height);
1267
                        ((Graphics2D)g).setStroke(new BasicStroke(1));
1268
                        g.setColor(Color.RED);
1269
                        g.drawOval(cx-side/2, cy-side/2, side, side);
1270
                        ((Graphics2D)g).setStroke(new BasicStroke(2));
1271
                        g.setColor(Color.GREEN);
1272
                        g.drawLine(cx, cy, x, y);
1273
                        g.fillOval(x-3, y-3, 6, 6);
1274
                }
1275
                
1276
                public void setMaxForward () {
1277
                        setPoint(cx, cy - (side/2) + 1);
1278
                }
1279
                
1280
                public void setMaxReverse () {
1281
                        setPoint(cx, cy + (side/2) - 1);
1282
                }
1283
                
1284
                public void setMaxLeft () {
1285
                        setPoint(cx - (side/2) + 1, cy);
1286
                }
1287
                
1288
                public void setMaxRight () {
1289
                        setPoint(cx + (side/2) - 1, cy);
1290
                }
1291
                
1292
                public void setZero () {
1293
                        setPoint(cx, cy);
1294
                }
1295
                
1296
                public void sendToServer () {
1297
                        System.out.println("Attempting to send angle = " + getAngle() + ", speed = " + getSpeed() + "");
1298
                        String dest = ColonetServerInterface.GLOBAL_DEST;
1299
                        if (cmbRobotNum != null && cmbRobotNum.getSelectedIndex() > 0) {
1300
                                dest = (String)cmbRobotNum.getSelectedItem();
1301
                        }
1302
                        
1303
                        if (csi != null) {
1304
                                /*
1305
                                csi.sendData(ColonetServerInterface.MOVE + " " + getSpeed() + " " + getAngle(), dest);
1306
                                */
1307
                                
1308
                                //Directional commands
1309
                                if (x > cx && y == cy) {  //move right
1310
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 200", dest);
1311
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 200", dest);
1312
                                } else if (x < cx && y == cy) {  //move left
1313
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 200", dest);
1314
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 200", dest);
1315
                                } else if (x == cx && y > cy) {  //move forward
1316
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 225", dest);
1317
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 225", dest);
1318
                                } else if (x == cx && y < cy) {  //move backward
1319
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 225", dest);
1320
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 225", dest);
1321
                                } else if (x == cx && y == cy) {  //stop!
1322
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 0", dest);
1323
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 0", dest);
1324
                                }
1325
                        }
1326
                }
1327
        
1328
        }
1329
        
1330
        /*
1331
        *        TaskAddWindow class
1332
        *        A window that provides a simple way to add tasks to a task queue.
1333
        */
1334
        class TaskAddWindow extends JFrame implements ActionListener, ListSelectionListener {
1335
                JPanel panelButtons;
1336
                JPanel panelParameters;
1337
                JPanel panelSouth;
1338
                JPanel panelSelection;
1339
                JButton btnSubmit;
1340
                JButton btnCancel;
1341
                DefaultListModel availableListModel;
1342
                JList availableList;
1343
                JScrollPane spAvailableTasks;
1344
                JTextArea txtDescription;
1345
                JTextField txtParameters;
1346
                
1347
                public TaskAddWindow () {
1348
                        super("Add a Task");
1349
                        super.setSize(500,500);
1350
                        super.setLayout(new BorderLayout());
1351
                        
1352
                        // set up buttons
1353
                        btnSubmit = new JButton("Submit");
1354
                        btnCancel = new JButton("Cancel");
1355
                        panelButtons = new JPanel();
1356
                        panelButtons.setLayout(new FlowLayout());
1357
                        panelButtons.add(btnSubmit);
1358
                        panelButtons.add(btnCancel);
1359
                        this.getRootPane().setDefaultButton(btnSubmit);
1360
                        
1361
                        // set up task list
1362
                        availableListModel = new DefaultListModel();
1363
                        availableListModel.addElement("Map the Environment");
1364
                        availableListModel.addElement("Clean Up Chemical Spill");
1365
                        availableListModel.addElement("Grow Plants");
1366
                        availableListModel.addElement("Save the Cheerleader");
1367
                        availableListModel.addElement("Save the World");
1368
                        availableList = new JList(availableListModel);
1369
                        availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
1370
                        availableList.setSelectedIndex(-1);
1371
                        spAvailableTasks = new JScrollPane(availableList);
1372
                        spAvailableTasks.setBorder(BorderFactory.createTitledBorder("Select A Task"));
1373
                        txtDescription = new JTextArea();
1374
                        txtDescription.setEditable(false);
1375
                        txtDescription.setLineWrap(true);
1376
                        txtDescription.setWrapStyleWord(true);
1377
                        txtDescription.setBorder(BorderFactory.createTitledBorder("Description"));
1378
                        
1379
                        //set up parameter area
1380
                        panelParameters = new JPanel();
1381
                        panelParameters.setLayout(new BorderLayout());
1382
                        txtParameters = new JTextField();
1383
                        panelParameters.add(new JLabel("Optional parameters for this task: "), BorderLayout.WEST);
1384
                        panelParameters.add(txtParameters);
1385
                        
1386
                        // assemble objects
1387
                        panelSelection = new JPanel();
1388
                        panelSelection.setLayout(new GridLayout(1,2));
1389
                        panelSelection.add(spAvailableTasks);
1390
                        panelSelection.add(txtDescription);
1391
                        
1392
                        panelSouth = new JPanel();
1393
                        panelSouth.setLayout(new GridLayout(2,1));
1394
                        panelSouth.add(panelParameters);
1395
                        panelSouth.add(panelButtons);
1396
                        
1397
                        this.getContentPane().add(panelSouth, BorderLayout.SOUTH);
1398
                        this.getContentPane().add(panelSelection, BorderLayout.CENTER);
1399
                        this.setLocationRelativeTo(null);
1400
                        
1401
                        // add listeners here
1402
                        availableList.addListSelectionListener(this);
1403
                        btnSubmit.addActionListener(this);
1404
                        btnCancel.addActionListener(this);
1405
                }
1406
                
1407
                public void prompt () {
1408
                        this.setVisible(true);
1409
                }
1410
                
1411
                private String getDescription (int index) {
1412
                        if (index < 0)
1413
                                return "";
1414
                        switch (index) {
1415
                                case 0: return "SLAM and junk";
1416
                                case 1: return "I'm not sure this works";
1417
                                case 2: return "Push them into the light";
1418
                                case 3: return "...";
1419
                                case 4: return "...";
1420
                        
1421
                                default: return "Task not recognized";
1422
                        }
1423
                }
1424
                
1425
                public void actionPerformed (ActionEvent e) {
1426
                        Object source = e.getSource();
1427
                        if (source == btnSubmit) {
1428
                                txtParameters.setText(txtParameters.getText().trim());
1429
                                
1430
                                
1431
                                this.setVisible(false);
1432
                        } else if (source == btnCancel) {
1433
                                this.setVisible(false);
1434
                        }
1435
                }
1436
                
1437
                public void valueChanged (ListSelectionEvent e) {
1438
                        int index = availableList.getSelectedIndex();
1439
                        if (index >= 0)
1440
                                txtDescription.setText(getDescription(index));
1441
                }
1442
        
1443
        }
1444
        
1445
        /*
1446
        *  BatteryIcon class
1447
        *  Graphical representation of battery level
1448
        */
1449
        class BatteryIcon implements Icon {
1450
                private int width;
1451
            private int height;
1452
            private int level;
1453
            
1454
                /** 
1455
                * Constructs a new BatteryIcon with all default parameters.
1456
                * Default width and height are 50.
1457
                * Default level is 100.
1458
                */
1459
            public BatteryIcon(){
1460
                    this(100, 50, 50);
1461
            }
1462
            
1463
                /** 
1464
                * Constructs a new BatteryIcon with default width and height, and with the specified level.
1465
                * Default width and height are 50.
1466
                */
1467
            public BatteryIcon(int startLevel){
1468
                    this(startLevel, 50, 50);
1469
            }
1470
            
1471
                /** 
1472
                * Constructs a new BatteryIcon with the specified level, width, and height.
1473
                */
1474
            public BatteryIcon(int startLevel, int w, int h){
1475
                    level = startLevel;
1476
                    width = w;
1477
                    height = h;
1478
            }
1479
            
1480
            public void paintIcon(Component c, Graphics g, int x, int y) {
1481
                Graphics2D g2d = (Graphics2D) g.create();
1482
                //clear the background
1483
                g2d.setColor(Color.WHITE);
1484
                g2d.fillRect(x + 1, y + 1, width - 2, height - 2);
1485
                //outline
1486
                g2d.setColor(Color.BLACK);
1487
                g2d.drawRect((int)(x + width*.3), y + 2, (int)(width*.4), height - 4);
1488
                //battery life rectangle
1489
                g2d.setColor(Color.GREEN);
1490
                int greenX = (int)(x + 1 + width*.3);
1491
                int greenY = (int)((y+3) + Math.abs(level-100.0)*(height-6)/(100));
1492
                int greenWidth = (int)(width*.4 - 2)+1;
1493
                int greenHeight = 1+(int)(level-0.0)*(height-6)/(100);
1494
                g2d.fillRect(greenX, greenY, greenWidth, greenHeight);
1495
                //text
1496
                g2d.setColor(Color.BLACK);
1497
                g2d.drawString(level + "%", greenX + greenWidth/2 - 10, greenY + greenHeight/2 + 5);
1498
                
1499
                g2d.dispose();
1500
            }
1501
            
1502
                /**
1503
                * Sets the battery level for this BatteryIcon. The level should be given in raw form, i.e. 0-255 directly 
1504
                * from the robot. The value will be converted to a representative percentage automatically.
1505
                *
1506
                * @param newLevel the new battery reading from the robot that this BatteryIcon will display.
1507
                */
1508
            public void setLevel(int newLevel) {
1509
                    level = convert(newLevel);
1510
                    repaint();
1511
                    System.out.println("Updated level to " + level);
1512
            }
1513
                
1514
            public int getIconWidth() {
1515
                return width;
1516
            }
1517
            
1518
            public int getIconHeight() {
1519
                return height;
1520
            }
1521
                
1522
                /**
1523
                * Converts a robot battery reading into representable form.
1524
                * Readings from the robot are returned as raw values, 0-255. This method converts the reading into a value
1525
                * from 0 to 100 so that the practical remaining charge is represented.
1526
                *
1527
                * @param level The battery level as returned by the robot.
1528
                * @returns The representable battery percentage.
1529
                */
1530
                private int convert (int level) {
1531
                        // TODO: make this a forreals conversion.
1532
                        return (int) (100.0 * level / 128);
1533
                }
1534
                
1535
        }
1536

    
1537

    
1538

    
1539
}