Project

General

Profile

Statistics
| Revision:

root / trunk / code / projects / colonet / ColonetGUI / Colonet.java @ 420

History | View | Annotate | Download (45 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.Random;
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 the robot graph
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
        
46
        // South
47
        JPanel panelSouth;
48
        JTextArea log;
49
        JScrollPane spLog;
50
        
51
        // Control
52
        JPanel panelControl;
53
        JTabbedPane tabPaneControl;
54
        JPanel panelRobotControl;
55
        JPanel panelRobotDirection;
56
        JPanel panelRobotDirectionButtons;
57
        JPanel panelRobotCommands;
58
        JButton btnF, btnB, btnL, btnR, btnActivate;
59
        JComboBox cmbRobotNum;
60
        JLabel lblBattery;
61
        BatteryIcon batteryIcon;
62
        JPanel panelBattery;
63
        VectorController vectorController;
64
        BufferedImage imageVectorControl;
65
        JButton btnCommand_StopTask;
66
        JButton btnCommand_ResumeTask;
67
        JButton btnCommand_ChargeNow;
68
        JButton btnCommand_StopCharging;
69
        
70
        // Task Manager
71
        JPanel panelTaskManager;
72
        JScrollPane spTaskManager;
73
        JPanel panelTaskManagerControls;
74
        JPanel panelTaskManagerControlsPriority;
75
        DefaultListModel taskListModel;
76
        JList taskList;
77
        JButton btnAddTask;
78
        JButton btnRemoveTask;
79
        JButton btnMoveTaskUp;
80
        JButton btnMoveTaskDown;
81
        JButton btnUpdateTasks;
82
        TaskAddWindow taskAddWindow;
83
        
84
        //Webcam and Graph
85
        WebcamPanel panelWebcam;
86
        GraphicsPanel panelGraph;
87
        GraphicsConfiguration gc;
88
        volatile BufferedImage image;
89
        volatile Graphics2D canvas;
90
        int cx, cy;
91
        JTabbedPane tabPaneMain;
92
        
93
        
94
        Socket socket;                                        
95
        OutputStreamWriter out;
96
        DataUpdater dataUpdater;  
97
        
98
        Font botFont;
99
        volatile int tokenLoc;  //the token is currently here
100
        volatile int numBots;
101
        volatile int selectedBot;  //the user has selected this bot
102
        volatile Rectangle[] botRect;  //contains boundary shapes around bots for click detection
103
        volatile int[] xbeeID;
104
        
105
        Thread drawThread;
106
        SelectionIndicator indicator;
107
        WebcamLoader webcamLoader;
108
        ColonetServerInterface csi;
109

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

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

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

    
949
        }
950
        
951
        /*
952
        *        GraphicsPanel class
953
        *        An extension of JPanel, designed for holding an image that will be repainted regularly.
954
        */
955
        class GraphicsPanel extends JPanel {
956
                protected Image img;
957
        
958
                public GraphicsPanel (Image img) {
959
                        super();
960
                        this.img = img;
961
                }
962
                
963
                public GraphicsPanel (Image img, boolean isDoubleBuffered) {
964
                        super(isDoubleBuffered);
965
                        this.img = img;
966
                }
967
                
968
                public void paint (Graphics g) {
969
                        // Place the buffered image on the screen, inside the panel
970
                        g.drawImage(img, 0, 0, Color.WHITE, this);
971
                }
972
        
973
        }
974
        
975
        /*
976
        *        WebcamPanel class
977
        *        Enables more efficient image handling in a component-controlled environment
978
        */
979
        class WebcamPanel extends JPanel {
980
                int BORDER = 16;  // this is arbitrary. it makes the image look nice inside a border.
981
                int BOT_RADIUS = 40;
982
                volatile BufferedImage img;
983
                volatile Point [] points;
984
        
985
                public WebcamPanel () {
986
                        super();
987
                }
988
                
989
                public synchronized void setImage (BufferedImage newimg) {
990
                        if (img != null) {
991
                                img.flush();
992
                                img = null;
993
                                img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
994
                        }
995
                        System.gc();
996
                        img = newimg;
997
                }
998
                
999
                public synchronized void setPoints (Point [] newpoints) {
1000
                        this.points = newpoints;
1001
                }
1002
                
1003
                public synchronized void paint (Graphics g) {
1004
                        
1005
                        if (img == null)
1006
                                return;
1007
                        // Place the image on the screen, inside the panel
1008
                        g.drawImage(img, 
1009
                                                BORDER,        //dx1 - the x coordinate of the first corner of the destination rectangle.
1010
                                                BORDER,        //dy1 - the y coordinate of the first corner of the destination rectangle.
1011
                                                this.getWidth() - BORDER,         //dx2 - the x coordinate of the second corner of the destination rectangle.
1012
                                                this.getHeight() - BORDER,        //dy2 - the y coordinate of the second corner of the destination rectangle.
1013
                                                0,        //sx1 - the x coordinate of the first corner of the source rectangle.
1014
                                                0,        //sy1 - the y coordinate of the first corner of the source rectangle.
1015
                                                image.getWidth(),        //sx2 - the x coordinate of the second corner of the source rectangle.
1016
                                                image.getHeight(),        //sy2 - the y coordinate of the second corner of the source rectangle.
1017
                                                null        //observer - object to be notified as more of the image is scaled and converted.
1018
                                                );
1019
                                                
1020
                        // Draw Identifiers
1021
                        if (points == null)
1022
                                return;
1023
                        g.setColor(Color.RED);
1024
                        ((Graphics2D)g).setStroke(new BasicStroke(2));
1025
                        for (int i = 0; i < points.length; i++) {
1026
                                g.drawOval(points[i].x - BOT_RADIUS, points[i].y - BOT_RADIUS, 2*BOT_RADIUS, 2*BOT_RADIUS);
1027
                        }
1028
                        
1029
                }
1030
        
1031
        }
1032
        
1033
        /*
1034
        *        WebcamLoader class
1035
        *        Handles the loading of the webcam image.
1036
        */
1037
        class WebcamLoader extends Thread 
1038
        {
1039
                final int WEBCAMLOADER_DELAY = 1000;
1040
                final String IMAGE_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet.jpg";
1041
                final String LOCATIONS_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet/locations.txt";
1042
                
1043
                URL imagePath;
1044
                URI locationsPath;
1045
                
1046
                MediaTracker mt;
1047
                BufferedImage image;
1048
                
1049
                public WebcamLoader (JApplet applet)
1050
                {
1051
                        super("ColonetWebcamLoader");
1052
                        mt = new MediaTracker(applet);
1053
                        ImageIO.setUseCache(false);
1054
                        try {
1055
                                imagePath = new URL(IMAGE_PATH);
1056
                        } catch (MalformedURLException e) {
1057
                                System.out.println("Malformed URL: could not form URL from: [" + IMAGE_PATH + "]\n");
1058
                        }
1059
                        try {
1060
                                locationsPath = new URI(LOCATIONS_PATH);
1061
                        } catch (URISyntaxException x) {
1062
                                System.out.println("Malformed URI: could not form URI from: [" + LOCATIONS_PATH + "]\n");
1063
                        }
1064
                        
1065
                }
1066
                
1067
                public synchronized void run ()
1068
                {
1069
                        while (true) {
1070
                                try {
1071
                                        Thread.sleep(WEBCAMLOADER_DELAY);
1072
                                        if (image != null) 
1073
                                                image.flush();
1074
                                        System.gc();
1075
                                        image = ImageIO.read(imagePath);
1076
                                        // The MediaTracker waitForID pauses the thread until the image is loaded.
1077
                                        // We don't want to display a half-downloaded image.
1078
                                        mt.addImage(image, 1);
1079
                                        mt.waitForID(1);
1080
                                        mt.removeImage(image);
1081
                                        // Save
1082
                                        panelWebcam.setImage(image);
1083
                                        parseLocations(locationsPath.toURL());
1084
                                } catch (InterruptedException e) {
1085
                                        return;
1086
                                } catch (java.security.AccessControlException e) {
1087
                                        csi.warn("Could not load webcam.\n" + e);
1088
                                        return;
1089
                                } catch (IOException e) {
1090
                                        log.append("IOException while trying to load image.");
1091
                                }
1092
                        }
1093
                }
1094
                
1095
                private void parseLocations (URL url) {
1096
                        URLConnection conn = null;
1097
                        DataInputStream data = null;
1098
                        String line;
1099
                        String [] lines = new String[30];
1100
                        StringBuffer buf = new StringBuffer();
1101
                        int i = 0;
1102
                
1103
                        try {
1104
                                conn = url.openConnection();
1105
                                conn.connect();
1106
                                data = new DataInputStream(new BufferedInputStream(conn.getInputStream()));
1107
                                while ((line = data.readLine()) != null) {
1108
                                        buf.append(line + ";");
1109
                                        lines[i] = line;
1110
                                        i++;
1111
                                }
1112
                                data.close();
1113
                        } catch (IOException e) {
1114
                                System.out.println("IOException:" + e.getMessage());
1115
                        }
1116
                        //log.append("Got robot locations: " + buf + "\n");
1117
                        
1118
                        // Get Point values from strings
1119
                        Point [] points = new Point[i];
1120
                        for (int j = 0; j < i; j++) {
1121
                                String [] parts = lines[j].split(",");
1122
                                int xval = Integer.parseInt(parts[0]);
1123
                                int yval = Integer.parseInt(parts[1]);
1124
                                Point p = new Point(xval, yval);
1125
                                points[j] = p;
1126
                        }
1127
                        if (points.length != 0)
1128
                                panelWebcam.setPoints(points);
1129
                        
1130
                }
1131
        }
1132

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

    
1478

    
1479
}