Project

General

Profile

Statistics
| Revision:

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

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

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

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

    
1475

    
1476
}