Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (38 KB)

1
//
2
//        Colonet.java
3
//
4

    
5
import javax.swing.*;
6
import javax.swing.event.*;
7
import javax.imageio.*;
8
import java.awt.*;
9
import java.awt.image.*;
10
import java.awt.event.*;
11
import java.net.*;
12
import java.io.*;
13
import java.util.*;
14

    
15
/**
16
* The Colonet Graphical User Interface Applet for use locally and over an internet connection.
17
* @author Gregory Tress
18
*
19
* To generate javadoc on this file or other java files, use javadoc *.java -d doc, where doc
20
* is the name of the folder into which the files should be written.
21
*/
22
public class Colonet extends JApplet implements ActionListener, MouseInputListener, KeyListener {
23

    
24
        // Used for images
25
        final int CANVAS_SIZE = 500;        //the applet may be slow if the canvas gets too large
26
        final int BUFFER = 50;
27
        final int RADIUS = 30;
28

    
29
        //Used for the robot controller
30
        final int VECTOR_CONTROLLER_HEIGHT = 220;
31
        final int VECTOR_CONTROLLER_WIDTH = 350;
32

    
33
        // Connection
34
        JTextField txtHost;
35
        JTextField txtPort;
36
        JButton btnConnect;
37
        JButton btnGetXBeeIDs;
38
        JLabel lblConnectionStatus;
39
        JTextArea txtMatrix;
40
        JTextArea txtInfo;
41
        JPanel panelConnect;
42
        JPanel panelServerInterface;
43
        Socket socket;
44
        OutputStreamWriter out;
45
        DataUpdater dataUpdater;
46

    
47
        // South
48
        JPanel panelSouth;
49
        JTextArea log;
50
        JScrollPane spLog;
51

    
52
        // Control
53
        JPanel panelControl;
54
        JTabbedPane tabPaneControl;
55
        JPanel panelRobotControl;
56
        JPanel panelRobotDirection;
57
        JPanel panelRobotDirectionButtons;
58
        JPanel panelRobotCommands;
59
        JButton btnF, btnB, btnL, btnR, btnActivate;
60
        JComboBox cmbRobotNum;
61
        JLabel lblBattery;
62
        JLabel lblSelected;
63
        BatteryIcon batteryIcon;
64
        JPanel panelBattery;
65
        VectorController vectorController;
66
        BufferedImage imageVectorControl;
67
        JButton btnAssignID;
68
        boolean setWaypoint;
69
        int setWaypointID;
70
        JButton btnCommand_MoveTo;
71
        JButton btnCommand_MoveAll;
72
        JButton btnCommand_StopTask;
73
        JButton btnCommand_ResumeTask;
74
        JButton btnCommand_ChargeNow;
75
        JButton btnCommand_StopCharging;
76

    
77
        // Task Manager
78
        JPanel panelTaskManager;
79
        JScrollPane spTaskManager;
80
        JPanel panelTaskManagerControls;
81
        JPanel panelTaskManagerControlsPriority;
82
        DefaultListModel taskListModel;
83
        JList taskList;
84
        JButton btnAddTask;
85
        JButton btnRemoveTask;
86
        JButton btnMoveTaskUp;
87
        JButton btnMoveTaskDown;
88
        JButton btnUpdateTasks;
89
        TaskAddWindow taskAddWindow;
90

    
91
        //Webcam
92
        WebcamPanel panelWebcam;
93
        GraphicsPanel panelGraph;
94
        GraphicsConfiguration gc;
95
        volatile BufferedImage image;
96
        volatile Graphics2D canvas;
97
        int cx, cy;
98
        JTabbedPane tabPaneMain;
99

    
100
        Font botFont;
101
        volatile int numBots;
102
        volatile int selectedBot;         //the user has selected this bot graphically
103
        volatile java.util.Map <Integer, RobotIcon> robotIcons;         //contains boundary shapes around bots for click detection
104
        volatile int[] xbeeID;
105

    
106
        Colonet self = this;
107
        WebcamLoader webcamLoader;
108
        volatile ColonetServerInterface csi;
109

    
110
        public void init () {
111
                // Set the default look and feel - choose one
112
                //String laf = UIManager.getSystemLookAndFeelClassName();
113
                String laf = UIManager.getCrossPlatformLookAndFeelClassName();
114
                //String laf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
115
                try {
116
                        UIManager.setLookAndFeel(laf);
117
                } catch (UnsupportedLookAndFeelException exc) {
118
                        System.err.println ("Warning: UnsupportedLookAndFeel: " + laf);
119
                } catch (Exception exc) {
120
                        System.err.println ("Error loading " + laf + ": " + exc);
121
                }
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

    
130
                try {
131
                        SwingUtilities.invokeAndWait(r);
132
                } catch (InterruptedException e) {
133
                        //Not really sure why we would be in this situation
134
                        System.out.println("InterruptedException in init: " + e);
135
                } catch (java.lang.reflect.InvocationTargetException e) {
136
                        //This could happen for various reasons if there is a problem in createAndShowGUI
137
                        e.printStackTrace();
138
                }
139
        }
140

    
141
        public void destroy () {
142
        }
143

    
144
        private synchronized void createAndShowGUI () {
145
                // init graphical elements
146
                // Get the graphics configuration of the screen to create a buffer
147
                gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
148
                image = gc.createCompatibleImage(CANVAS_SIZE,CANVAS_SIZE);
149
                canvas = image.createGraphics();
150
                canvas.setStroke(new BasicStroke(2));         //set pen width
151
                panelGraph = new GraphicsPanel(image, false);         //set automatic double-buffering to false. we are doing it manually.
152
                panelWebcam = new WebcamPanel();
153
                tabPaneMain = new JTabbedPane();
154
                tabPaneMain.setFont(new Font("arial", Font.PLAIN, 16));
155
                tabPaneMain.add(panelWebcam, "Webcam");
156
                //tabPaneMain.add(panelGraph, "Graph");
157

    
158
                // Calculate center of canvas
159
                cx = image.getWidth() / 2;
160
                cy = image.getHeight() / 2;
161

    
162
                // Set up robots
163
                botFont = new Font("arial", Font.PLAIN, 14);
164
                numBots = 0;
165
                selectedBot = -1;
166
                robotIcons = new HashMap <Integer, RobotIcon> ();
167

    
168
                // Connection area
169
                txtMatrix = new JTextArea();
170
                txtMatrix.setBorder(BorderFactory.createTitledBorder("Info"));
171
                txtInfo = new JTextArea();
172
                txtInfo.setBorder(BorderFactory.createTitledBorder("Info"));
173
                txtInfo.setEditable(false);
174
                txtHost = new JTextField(this.getDocumentBase().getHost());
175
                txtHost.setBorder(BorderFactory.createTitledBorder("Host"));
176
                txtPort = new JTextField("10123");
177
                txtPort.setBorder(BorderFactory.createTitledBorder("Port"));
178
                btnConnect = new JButton("Connect");
179
                btnConnect.setFont(new Font("arial", Font.BOLD, 16));
180
                btnGetXBeeIDs = new JButton("Get XBee IDs");
181
                getRootPane().setDefaultButton(btnConnect);
182
                lblConnectionStatus = new JLabel("Status: Offline");
183
                panelConnect = new JPanel();
184
                panelConnect.setLayout(new GridLayout(6,1));
185
                panelConnect.add(lblConnectionStatus);
186
                panelConnect.add(txtHost);
187
                panelConnect.add(txtPort);
188
                panelConnect.add(btnConnect);
189
                //panelConnect.add(btnGetXBeeIDs);
190
                panelServerInterface = new JPanel();
191
                panelServerInterface.setLayout(new GridLayout(2,1));
192
                panelServerInterface.add(panelConnect);
193
                panelServerInterface.add(txtMatrix);
194

    
195
                // Robot direction panel
196
                panelRobotDirection = new JPanel();
197
                panelRobotDirectionButtons = new JPanel();
198

    
199
                Font f = new Font(null, Font.PLAIN, 18);
200
                btnF = new JButton("\u2191");
201
                btnF.setFont(f);
202
                btnB = new JButton("\u2193");
203
                btnB.setFont(f);
204
                btnL = new JButton("\u2190");
205
                btnL.setFont(f);
206
                btnR = new JButton("\u2192");
207
                btnR.setFont(f);
208
                btnActivate = new JButton("\u25A0");
209
                btnActivate.setFont(new Font(null, Font.BOLD, 36));
210

    
211
                panelRobotDirectionButtons.setLayout(new GridLayout(1,5));
212
                panelRobotDirectionButtons.add(btnActivate);
213
                panelRobotDirectionButtons.add(btnF);
214
                panelRobotDirectionButtons.add(btnB);
215
                panelRobotDirectionButtons.add(btnL);
216
                panelRobotDirectionButtons.add(btnR);
217

    
218
                imageVectorControl = gc.createCompatibleImage(VECTOR_CONTROLLER_WIDTH, VECTOR_CONTROLLER_HEIGHT);
219
                vectorController = new VectorController(imageVectorControl);
220
                panelRobotDirection.setLayout(new BorderLayout());
221
                //panelRobotDirection.add(vectorController, BorderLayout.CENTER);
222
                panelRobotDirection.add(panelRobotDirectionButtons, BorderLayout.SOUTH);
223

    
224
                // Robot Control and Commands
225
                panelRobotCommands = new JPanel();
226
                panelRobotCommands.setLayout(new GridLayout(5,2));
227
                cmbRobotNum = new JComboBox();
228
                // Battery subset
229
                batteryIcon = new BatteryIcon(0);
230
                lblBattery = new JLabel(batteryIcon);
231
                lblSelected = new JLabel("None");
232
                // Command subset
233
                setWaypoint = false;
234
                setWaypointID = -1;
235
                btnAssignID = new JButton("Assign ID");
236
                btnCommand_MoveTo = new JButton("Move to ...");
237
                btnCommand_MoveAll = new JButton("Move all ...");
238
                btnCommand_StopTask = new JButton("Stop Current Task");
239
                btnCommand_ResumeTask = new JButton("Resume Current Task");
240
                btnCommand_ChargeNow = new JButton("Recharge Now");
241
                btnCommand_StopCharging = new JButton("Stop Recharging");
242
                panelRobotCommands.add(new JLabel("Select Robot to Control: "));
243
                panelRobotCommands.add(cmbRobotNum);
244
                panelRobotCommands.add(new JLabel("Battery Level: "));
245
                panelRobotCommands.add(lblBattery);
246
                panelRobotCommands.add(new JLabel("Selected Icon: "));
247
                panelRobotCommands.add(lblSelected);
248
                panelRobotCommands.add(btnAssignID);
249
                panelRobotCommands.add(new JLabel(""));
250
                panelRobotCommands.add(btnCommand_MoveTo);
251
                panelRobotCommands.add(btnCommand_MoveAll);
252
                //panelRobotCommands.add(btnCommand_StopTask);
253
                //panelRobotCommands.add(btnCommand_ResumeTask);
254
                //panelRobotCommands.add(btnCommand_ChargeNow);
255
                //panelRobotCommands.add(btnCommand_StopCharging);
256
                panelRobotControl = new JPanel();
257
                panelRobotControl.setLayout(new GridLayout(2,1));
258
                panelRobotControl.add(panelRobotDirection);
259
                panelRobotControl.add(panelRobotCommands);
260

    
261

    
262
                // Task Manager
263
                panelTaskManager = new JPanel();
264
                panelTaskManager.setLayout(new BorderLayout());
265
                taskListModel = new DefaultListModel();
266
                taskList = new JList(taskListModel);
267
                taskList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
268
                taskList.setSelectedIndex(0);
269
                spTaskManager = new JScrollPane(taskList);
270
                panelTaskManagerControls = new JPanel();
271
                panelTaskManagerControls.setLayout(new GridLayout(1,4));
272
                panelTaskManagerControlsPriority = new JPanel();
273
                panelTaskManagerControlsPriority.setLayout(new GridLayout(1,2));
274
                btnAddTask = new JButton("Add...");
275
                btnRemoveTask = new JButton("Remove");
276
                btnMoveTaskUp = new JButton("^");
277
                btnMoveTaskDown = new JButton("v");
278
                btnUpdateTasks = new JButton("Update");
279
                panelTaskManagerControlsPriority.add(btnMoveTaskUp);
280
                panelTaskManagerControlsPriority.add(btnMoveTaskDown);
281
                panelTaskManagerControls.add(btnAddTask);
282
                panelTaskManagerControls.add(btnRemoveTask);
283
                panelTaskManagerControls.add(btnUpdateTasks);
284
                panelTaskManagerControls.add(panelTaskManagerControlsPriority);
285
                panelTaskManager.add(spTaskManager, BorderLayout.CENTER);
286
                panelTaskManager.add(panelTaskManagerControls, BorderLayout.SOUTH);
287
                panelTaskManager.add(new JLabel("Current Task Queue"), BorderLayout.NORTH);
288
                taskAddWindow = new TaskAddWindow();
289

    
290
                // Message log
291
                log = new JTextArea();
292
                spLog = new JScrollPane(log, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
293
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
294
                spLog.setBorder(BorderFactory.createTitledBorder("Log"));
295
                spLog.setPreferredSize(new Dimension(0, 120));
296
                log.setEditable(false);
297

    
298
                // Main control mechanism
299
                panelControl = new JPanel();
300
                panelControl.setLayout(new GridLayout(1,1));
301
                tabPaneControl = new JTabbedPane(JTabbedPane.TOP);
302
                tabPaneControl.setFont(new Font("arial", Font.PLAIN, 16));
303
                tabPaneControl.setPreferredSize(new Dimension(VECTOR_CONTROLLER_WIDTH, 0));
304
                tabPaneControl.addTab("Connection", panelServerInterface);
305
                tabPaneControl.addTab("Robots", panelRobotControl);
306
                //tabPaneControl.addTab("Tasks", panelTaskManager);
307
                panelControl.add(tabPaneControl);
308

    
309
                // Set up elements in the south
310
                panelSouth = new JPanel();
311
                panelSouth.setLayout(new GridLayout(1,2));
312
                //panelSouth.add(spLog);
313

    
314
                // Put all elements in the ContentPane
315
                this.getContentPane().setLayout(new BorderLayout());
316
                this.getContentPane().add(tabPaneMain, BorderLayout.CENTER);
317
                this.getContentPane().add(panelSouth, BorderLayout.SOUTH);
318
                this.getContentPane().add(panelControl, BorderLayout.EAST);
319
                this.setVisible(true);
320
                
321
                // Disable components before connecting
322
                btnConnect.setText("Connect");
323
        lblConnectionStatus.setText("Status: Disconnected");
324
        btnF.setEnabled(false);
325
        btnB.setEnabled(false);
326
        btnL.setEnabled(false);
327
        btnR.setEnabled(false);
328
        btnActivate.setEnabled(false);
329
        cmbRobotNum.setEnabled(false);
330
        btnAssignID.setEnabled(false);
331
        btnCommand_MoveTo.setEnabled(false);
332
        btnCommand_MoveAll.setEnabled(false);
333

    
334
                /* Add all listeners here */
335
                // Task Management
336
                btnAddTask.addActionListener(this);
337
                btnRemoveTask.addActionListener(this);
338
                btnMoveTaskUp.addActionListener(this);
339
                btnMoveTaskDown.addActionListener(this);
340
                btnUpdateTasks.addActionListener(this);
341
                // Robot Control
342
                btnF.addActionListener(this);
343
                btnB.addActionListener(this);
344
                btnL.addActionListener(this);
345
                btnR.addActionListener(this);
346
                btnF.addKeyListener(this);
347
                btnB.addKeyListener(this);
348
                btnL.addKeyListener(this);
349
                btnR.addKeyListener(this);
350
                btnActivate.addActionListener(this);
351
                btnActivate.addKeyListener(this);
352
                cmbRobotNum.addKeyListener(this);
353
                btnCommand_MoveTo.addActionListener(this);
354
                btnCommand_MoveAll.addActionListener(this);
355
                btnCommand_StopTask.addActionListener(this);
356
                btnCommand_ResumeTask.addActionListener(this);
357
                btnCommand_ChargeNow.addActionListener(this);
358
                btnCommand_StopCharging.addActionListener(this);
359
                // Other
360
                btnConnect.addActionListener(this);
361
                btnGetXBeeIDs.addActionListener(this);
362
                btnAssignID.addActionListener(this);
363
                panelWebcam.addMouseListener(this);
364
        }
365

    
366
        public void paint (Graphics g) {
367
                super.paint(g);
368
        }
369

    
370
        public void update (Graphics g) {
371
                paint(g);
372
        }
373

    
374
        /**
375
        * Gets the JTextArea used for storing the activity log. This method returns a reference to the
376
        * JTextArea that stores the log. The log can contain any activity that is revelant to the use
377
        * of the applet, and may optionally display debugging information.
378
        *
379
        * @return the JTextArea where BOM matrix information is stored.
380
        */
381
        public JTextArea getLog () {
382
                return log;
383
        }
384

    
385
        /**
386
        * Gets the JTextArea used for storing the BOM matrix data. This method returns a reference to the
387
        * JTextArea that stores the BOM matrix. The values in the matrix are stored as integers separated
388
        * by spaces, and the lines should be separated by a newline.
389
        *
390
        * @return the JTextArea where BOM matrix information is stored.
391
        */
392
        public JTextArea getMatrixInput () {
393
                return txtMatrix;
394
        }
395

    
396
        /**
397
        * Parses a String containing BOM matrix information.
398
        * The ColonetServerInterface receives lines of the BOM matrix.        (For encoding
399
        * information, see the ColonetServerInterface documentation.)         The entire matrix is passed
400
        * to the client when requested. This method takes a string of the form
401
        * "[command code] [command code] [number of robots] [data0] [data1] ..."
402
        * with tokens separated by spaces and containing no brackets.
403
        * The [command code]s are predefined values identifying this String as a BOM data
404
        * String, [number of robots] is an integer, and the values that follow are
405
        * the sensor readings of the robots in order, starting with robot 0.        Only [number of robots]^2
406
        * data entries will be read.        The matrix values are saved locally until the next String is parsed.
407
        *
408
        *
409
        * @param line the String containing BOM matrix information.
410
        * @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots]^2 data entries in the String
411
        */
412
        public void parseMatrix (String line) {
413
                txtMatrix.setText("");
414
                String [] str = line.split(" ");
415
                int num = Integer.parseInt(str[2]);
416
                for (int i = 0; i < num; i++) {
417
                        for (int j = 0; j < num; j++) {
418
                                String next = str[3 + i*num + j];
419
                                if (next.equals("-1")) {
420
                                        txtMatrix.append("-");
421
                                } else {
422
                                        txtMatrix.append(next);
423
                                }
424

    
425
                                if (j < num - 1) {
426
                                        txtMatrix.append(" ");
427
                                }
428
                        }
429

    
430
                        if (i < num - 1) {
431
                                txtMatrix.append("\n");
432
                        }
433
                }
434
                repaint();
435
        }
436

    
437
        public void connect () {
438
        if (csi != null)
439
                return;
440
        csi = new ColonetServerInterface(self);
441
        csi.connect(txtHost.getText(), txtPort.getText());
442
        if (!csi.isReady()) {
443
                csi = null;
444
                return;
445
        }
446
        webcamLoader = new WebcamLoader(self);
447
        dataUpdater = new DataUpdater();
448
        dataUpdater.start();
449
        webcamLoader.start();
450
        Runnable r = new Runnable() {
451
                public void run () {
452
                        btnConnect.setText("Disconnect");
453
                        lblConnectionStatus.setText("Status: Connected");
454
                btnF.setEnabled(true);
455
                btnB.setEnabled(true);
456
                btnL.setEnabled(true);
457
                btnR.setEnabled(true);
458
                btnActivate.setEnabled(true);
459
                cmbRobotNum.setEnabled(true);
460
                btnAssignID.setEnabled(true);
461
                btnCommand_MoveTo.setEnabled(true);
462
                btnCommand_MoveAll.setEnabled(true);
463
                    }
464
                };
465
                SwingUtilities.invokeLater(r);
466
        }
467

    
468
        public void disconnect () {
469
        dataUpdater.interrupt();
470
        csi = null;
471
                Runnable r = new Runnable() {
472
                public void run () {
473
                        btnConnect.setText("Connect");
474
                    lblConnectionStatus.setText("Status: Disconnected");
475
                btnF.setEnabled(false);
476
                btnB.setEnabled(false);
477
                btnL.setEnabled(false);
478
                btnR.setEnabled(false);
479
                btnActivate.setEnabled(false);
480
                cmbRobotNum.setEnabled(false);
481
                btnAssignID.setEnabled(false);
482
                btnCommand_MoveTo.setEnabled(false);
483
                btnCommand_MoveAll.setEnabled(false);
484
                    }
485
                };
486
                SwingUtilities.invokeLater(r);
487
        }
488

    
489
        /**
490
        * Parses a String containing a task queue update.
491
        * Format is currently not specified.
492
        * This method currently does nothing.
493
        *
494
        * @param line the String containing task queue update information.
495
        */
496
        public void parseQueue (String line) {
497
                log.append("Got queue update\n");
498
                //TODO: display new queue data in tasks tab
499
        }
500

    
501
        /**
502
        * Parses a String containing XBee ID values.
503
        * The ColonetServerInterface receives Strings of XBee information.        (For encoding
504
        * information, see the ColonetServerInterface documentation.)         This method takes
505
        * a string of the form "[command code] [command code] [number of robots] [id0] [id1] ..."
506
        * with tokens separated by spaces and containing no brackets.
507
        * The [command code]s are predefined values identifying this String as an XBee
508
        * ID String, [number of robots] is an integer, and the values that follow are
509
        * the IDs of the robots in order, starting with robot 0.        Only [number of robots]
510
        * will be read.         The ID values are saved locally until the next String is parsed.
511
        * The purpose of having this list is to ensure that robots are properly identified for control purposes.
512
        * This keeps robot identification consistent between sessions and prevents arbitrary assignment.
513
        *
514
        * @param line the String containing XBee ID information.
515
        * @throws ArrayIndexOutOfBoundsException if there are fewer than [number of robots] IDs in the String
516
        * @see ColonetServerInterface#sendXBeeIDRequest()
517
        */
518
        public void parseXBeeIDs (String line) {
519
                String [] str = line.split(" ");
520
                int num = Integer.parseInt(str[2]);
521
                xbeeID = new int[num];
522
                for (int i = 0; i < num; i++) {
523
                        xbeeID[i] = Integer.parseInt(str[i+3]);
524
                }
525

    
526
                //update the list of robots to control
527
                //but save the old value first
528
                Object oldSelection = cmbRobotNum.getSelectedItem();
529
                cmbRobotNum.removeAllItems();
530
                cmbRobotNum.addItem(new String("         All         "));
531
                for (int i = 0; i < num; i++) {
532
                        cmbRobotNum.addItem(new String("" + xbeeID[i]));
533
                }
534
                cmbRobotNum.setSelectedItem(oldSelection);
535
                repaint();
536
        }
537

    
538
        /**
539
        * Parses a String containing battery information.
540
        * The ColonetServerInterface receives Strings of battery information.         (For encoding
541
        * information, see the ColonetServerInterface documentation.)         This method takes
542
        * a string of the form "[command code] [command code] [robot ID] [value]"
543
        * with tokens separated by spaces and containing no brackets.
544
        * The [command code]s are predefined values identifying this String as a battery
545
        * information String, [robot ID] is an integer, and [value] is a battery measurement.
546
        * This updates the batery information for a single robot.
547
        *
548
        *
549
        * @param line the String containing battery information.
550
        * @see ColonetServerInterface#sendBatteryRequest(int)
551
        */
552
        public void parseBattery (String line) {
553
                String [] str = line.split(" ");
554
                int botNum = Integer.parseInt(str[2]);
555
                int level = Integer.parseInt(str[3]);
556

    
557
                System.out.println("Got battery update:" + line);
558
                RobotIcon r = robotIcons.get(botNum);
559
                if (r != null) {
560
                    r.battery = level;
561
                }
562
                repaint();
563
        }
564

    
565
        /**
566
        * Parses a String containing visual robot position information along with
567
        * canonical ID assignments.
568
        */
569
        public void parsePositions (String line) {
570
                String [] str = line.split(" ");
571
                java.util.Map <Integer, RobotIcon> newMap = new HashMap <Integer, RobotIcon> ();
572

    
573
                for (int i = 2; i < str.length; i+=3) {
574
                        int id = Integer.parseInt(str[i]);
575
                        int x = Integer.parseInt(str[i+1]);
576
                        int y = Integer.parseInt(str[i+2]);
577
                        RobotIcon newIcon = new RobotIcon(id, x, y);
578
                        if (newIcon.id >= 0) {
579
                                newIcon.color = Color.GREEN;
580
                        }
581
                        newMap.put(id, newIcon);
582
                }
583
                robotIcons = newMap;
584
                repaint();
585
        }
586

    
587
        //
588
        // MouseListener methods
589
        //
590
        public void mousePressed(MouseEvent e) {
591
                //Start a new Thread to handle the MouseEvent
592
                (new MouseHandler(e)).start();
593
        }
594
        public void mouseExited(MouseEvent e) {
595
        }
596
        public void mouseEntered(MouseEvent e) {
597
        }
598
        public void mouseReleased(MouseEvent e) {
599
        }
600
        public void mouseClicked(MouseEvent e) {
601
        }
602
        public void mouseDragged(MouseEvent e) {
603
        }
604
        public void mouseMoved(MouseEvent e) {
605
        }
606

    
607
        //
608
        // KeyListener methods
609
        //
610
        public void keyPressed (KeyEvent e) {
611
                //Start a new Thread to handle the KeyEvent
612
                (new KeyHandler(e)).start();
613
        }
614
        public void keyReleased (KeyEvent e) {
615
        }
616
        public void keyTyped (KeyEvent e) {
617
        }
618

    
619
        //
620
        // ActionListener method
621
        //
622
        public void actionPerformed (ActionEvent e) {
623
                // Start a new Thread to handle the ActionEvent
624
                (new ActionHandler(e)).start();
625
        }
626

    
627
        class MouseHandler extends Thread {
628
                MouseEvent e;
629

    
630
                public MouseHandler (MouseEvent event) {
631
                        super("MouseHandler");
632
                        this.e = event;
633
                }
634

    
635
                public void run () {
636
                        Point pt = panelWebcam.convertClick(e);
637

    
638
                        // If we are selecting a waypoint (destination) for a specific bot
639
                        if (setWaypoint && setWaypointID >= 0) {
640
                                setWaypoint = false;
641
                                panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
642
                                if (selectedBot < 0) {
643
                                        return;
644
                                }
645
                                
646
                                RobotIcon r = robotIcons.get(selectedBot);
647
                                if (r != null) {
648
                                        r.destx = pt.x;
649
                                        r.desty = pt.y;
650
                                        if (csi != null) {
651
                                                csi.sendAbsoluteMove(r.id, r.destx, r.desty);
652
                                        }
653
                                }
654

    
655
                                return;
656
                        }
657

    
658
                        // Right-click also means we are moving a robot
659
                        if (e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON3) {
660
                                if (selectedBot < 0) {
661
                                        return;
662
                                }
663

    
664
                                RobotIcon r = robotIcons.get(selectedBot);
665
                                if (r != null) {
666
                                        r.destx = pt.x;
667
                                        r.desty = pt.y;
668
                                        if (csi != null) {
669
                                                csi.sendAbsoluteMove(r.id, r.destx, r.desty);
670
                                        }
671
                                }
672

    
673
                                return;
674
                        }
675

    
676
                        // If we are setting all waypoints
677
                        if (setWaypoint) {
678
                                setWaypoint = false;
679
                                panelWebcam.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
680
                                Iterator <Map.Entry<Integer,RobotIcon>> it = robotIcons.entrySet().iterator();
681
                                while (it.hasNext()) {
682
                                        RobotIcon r = it.next().getValue();
683
                                        r.destx = pt.x;
684
                                        r.desty = pt.y;
685
                                }
686
                                
687
                                return;
688
                        }
689

    
690
                        // Otherwise, we are selecting a bot, or doing nothing
691
                        Iterator <Map.Entry<Integer,RobotIcon>> it = robotIcons.entrySet().iterator();
692
                        while (it.hasNext()) {
693
                                RobotIcon r = it.next().getValue();
694
                                if (r.contains(pt.x, pt.y)) {
695
                                        selectedBot = r.id;
696
                                        lblSelected.setText("" + r.id);
697
                                        // Try to select the clicked bot, if its XBee ID is detected.
698
                                        for (int j = 1; j < cmbRobotNum.getItemCount(); j++) {
699
                                                if (Integer.parseInt(cmbRobotNum.getItemAt(j).toString()) == selectedBot) {
700
                                                        cmbRobotNum.setSelectedIndex(j);
701
                                                }
702
                                        }
703
                                        return;
704
                                }
705
                        }
706

    
707
                        repaint();
708
                }
709
        }
710

    
711
        class KeyHandler extends Thread {
712
                KeyEvent e;
713

    
714
                public KeyHandler (KeyEvent event) {
715
                        super("KeyHandler");
716
                        this.e = event;
717
                }
718

    
719
                public void run () {
720
                        int code = e.getKeyCode();
721
                        if (code == KeyEvent.VK_UP) {
722
                                vectorController.setMaxForward();
723
                                vectorController.sendToServer();
724
                        } else if (code == KeyEvent.VK_DOWN) {
725
                                vectorController.setMaxReverse();
726
                                vectorController.sendToServer();
727
                        } else if (code == KeyEvent.VK_LEFT) {
728
                                vectorController.setMaxLeft();
729
                                vectorController.sendToServer();
730
                        } else if (code == KeyEvent.VK_RIGHT) {
731
                                vectorController.setMaxRight();
732
                                vectorController.sendToServer();
733
                        } else if (code == KeyEvent.VK_S) {
734
                                vectorController.setZero();
735
                                vectorController.sendToServer();
736
                        }
737
                        repaint();
738
                }
739
        }
740

    
741
        class ActionHandler extends Thread {
742
                ActionEvent e;
743

    
744
                public ActionHandler (ActionEvent event) {
745
                        super("ActionHandler");
746
                        this.e = event;
747
                }
748

    
749
                public void run () {
750
                        Object source = e.getSource();
751

    
752
                        // General Actions
753
                        if (source == btnConnect) {
754
                                if (csi == null) {
755
                                        connect();
756
                                } else {
757
                                        disconnect();
758
                                }
759
                        } else if (source == btnGetXBeeIDs) {
760
                                csi.sendXBeeIDRequest();
761
                        } else if (source == btnAssignID) {
762
                                String message;
763
                                if (selectedBot < 0) {
764
                                        message = "That robot is unidentified. Please specify its ID.";
765
                                } else {
766
                                        message = "That robot has ID " + selectedBot + ". You may reassign it now.";
767
                                }
768
                                String result = JOptionPane.showInputDialog(self, message, "Robot Identification", JOptionPane.QUESTION_MESSAGE);
769
                                if (result == null) {
770
                                        return;
771
                                }
772
                                int newID = -1;
773
                                try {
774
                                        newID = Integer.parseInt(result);
775
                                } catch (Exception ex) {
776
                                        csi.warn("Invalid ID.");
777
                                        return;
778
                                }
779
                                // Assign new ID and update display
780
                                if (csi != null) {
781
                                        csi.sendIDAssignment(selectedBot, newID);
782
                                }
783
                                selectedBot = newID;
784
                                lblSelected.setText("" + newID);
785
                        } else if (source == btnF) { // Robot Movement Controls
786
                                vectorController.setMaxForward();
787
                                vectorController.sendToServer();
788
                        } else if (source == btnB) {
789
                                vectorController.setMaxReverse();
790
                                vectorController.sendToServer();
791
                        } else if (source == btnL) {
792
                                vectorController.setMaxLeft();
793
                                vectorController.sendToServer();
794
                        } else if (source == btnR) {
795
                                vectorController.setMaxRight();
796
                                vectorController.sendToServer();
797
                        } else if (source == btnActivate) {
798
                                vectorController.setZero();
799
                                vectorController.sendToServer();
800
                        } else if (source == btnCommand_MoveTo) { // Robot Commands (non-movement)
801
                                if (selectedBot < 0) {
802
                                        return;
803
                                }
804
                                panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
805
                                setWaypoint = true;
806
                                setWaypointID = selectedBot;
807
                        } else if (source == btnCommand_MoveAll) {
808
                                panelWebcam.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
809
                                setWaypoint = true;
810
                                setWaypointID = -1;
811
                        } else if (source == btnCommand_StopTask) {
812

    
813
                        } else if (source == btnCommand_ResumeTask) {
814

    
815
                        } else if (source == btnCommand_ChargeNow) {
816

    
817
                        } else if (source == btnCommand_StopCharging) {
818

    
819
                        } else if (source == btnAddTask) { // Queue Management
820
                                taskAddWindow.prompt();
821
                        } else if (source == btnRemoveTask) {
822
                                if (taskList.getSelectedIndex() >= 0) {
823
                                        csi.sendQueueRemove(taskList.getSelectedIndex());
824
                                }
825
                                csi.sendQueueUpdate();
826
                        } else if (source == btnMoveTaskUp) {
827
                                csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() - 1);
828
                                csi.sendQueueUpdate();
829
                        } else if (source == btnMoveTaskDown) {
830
                                csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() + 1);
831
                                csi.sendQueueUpdate();
832
                        } else if (source == btnUpdateTasks) {
833
                                csi.sendQueueUpdate();
834
                        }
835

    
836
                        repaint();
837
                }
838
        }
839

    
840
        /*
841
        * DataUpdater thread.
842
        *                The purpose of this thread is to request data from the server at regular intervals.
843
        *
844
        */
845
        class DataUpdater extends Thread {
846
                final int DATAUPDATER_DELAY = 250;
847

    
848
                public DataUpdater () {
849
                        super("Colonet DataUpdater");
850
                }
851

    
852
                public void run () {
853
                        String line;
854
                        while (true) {
855
                                try {
856
                                        //request more data
857
                                        if (csi != null && csi.isReady()) {
858
                                                csi.sendPositionRequest();
859
                                                csi.sendXBeeIDRequest();
860
                                                if (selectedBot >= 0) {
861
                                                        csi.sendBatteryRequest(selectedBot);
862
                                                }
863
                                        }
864
                                        Thread.sleep(DATAUPDATER_DELAY);
865
                                } catch (InterruptedException e) {
866
                                        return;
867
                                }
868
                        }
869
                }
870
        }
871

    
872
        /*
873
        * GraphicsPanel class
874
        * An extension of JPanel, designed for holding an image that will be repainted regularly.
875
        */
876
        class GraphicsPanel extends JPanel {
877
                protected Image img;
878

    
879
                public GraphicsPanel (Image img) {
880
                        this(img, true);
881
                }
882

    
883
                public GraphicsPanel (Image img, boolean isDoubleBuffered) {
884
                        super(isDoubleBuffered);
885
                        this.img = img;
886
                }
887

    
888
                public void paint (Graphics g) {
889
                        // Place the buffered image on the screen, inside the panel
890
                        g.drawImage(img, 0, 0, Color.WHITE, this);
891
                }
892
        }
893

    
894
        /*
895
        * WebcamPanel class
896
        * Enables more efficient image handling in a component-controlled environment
897
        */
898
        class WebcamPanel extends JPanel {
899
                final int BORDER = 16;        // this is arbitrary. it makes the image look nice inside a border.
900
                final int BATTERY_WIDTH = 50;
901
                final int BATTERY_HEIGHT = 10;
902
                volatile BufferedImage img;
903
                BufferedImage buffer;
904

    
905
                public WebcamPanel () {
906
                        super(true);
907
                }
908

    
909
                public synchronized void setImage (BufferedImage newimg) {
910
                        if (img != null) {
911
                                img.flush();
912
                        }
913
                        System.gc();
914
                        img = newimg;
915
                        repaint();
916
                }
917

    
918
                public synchronized void paint (Graphics g) {
919
                        if (img == null) {
920
                                return;
921
                        }
922

    
923
                        // Calculate scaling
924
                        int maxWidth = getWidth() - 2*BORDER;
925
                        int maxHeight = getHeight() - 2*BORDER;
926
                        double widthRatio = 1.0 * maxWidth / img.getWidth();
927
                        double heightRatio = 1.0 * maxHeight / img.getHeight();
928
                        double scale = 0;
929
                        int newWidth = 0;
930
                        int newHeight = 0;
931
                        int x = 0;
932
                        int y = 0;
933

    
934
                        if (widthRatio > heightRatio) {         //height is the limiting factor
935
                                scale = heightRatio;
936
                                newHeight = maxHeight;
937
                                newWidth = (int) (img.getWidth() * scale);
938
                                y = BORDER;
939
                                x = (maxWidth - newWidth) / 2 + BORDER;
940
                        } else {        //width is the limiting factor
941
                                scale = widthRatio;
942
                                newWidth = maxWidth;
943
                                newHeight = (int) (img.getHeight() * scale);
944
                                x = BORDER;
945
                                y = (maxHeight - newHeight) / 2 + BORDER;
946
                        }
947

    
948
                        // Draw everything onto the buffer
949
                        buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
950
                        Graphics2D bufferedGraphics = (Graphics2D)buffer.getGraphics();
951
                        bufferedGraphics.setColor(Color.GRAY);
952
                        bufferedGraphics.fillRect(0, 0, this.getWidth(), this.getHeight());
953
                        Image imgScaled = img.getScaledInstance(newWidth, newHeight, Image.SCALE_FAST);
954
                        bufferedGraphics.drawImage(imgScaled, x, y, this);
955

    
956

    
957
                        // Draw Identifiers and battery levels
958
                        if (robotIcons != null) {
959
                                bufferedGraphics.setStroke(new BasicStroke(2));
960
                                Iterator <Map.Entry<Integer,RobotIcon>> it = robotIcons.entrySet().iterator();
961
                                while (it.hasNext()) {
962
                                        RobotIcon r = it.next().getValue();
963
                                        bufferedGraphics.setColor(r.color);
964
                                        // Identifier circle
965
                                        int px = (int) (x + r.x * scale);
966
                                        int py = (int) (y + r.y * scale);
967
                                        bufferedGraphics.drawOval(px-RADIUS, py-RADIUS, 2*r.RADIUS, 2*r.RADIUS);
968
                                        // Battery
969
                                        if (r.battery >= 0) {
970
                                            int pixels = r.battery * BATTERY_WIDTH / 160;
971
                                                bufferedGraphics.setColor(Color.YELLOW);
972
                                                bufferedGraphics.fillRect(px+20, py+20, pixels, BATTERY_HEIGHT);
973
                                                bufferedGraphics.setColor(Color.BLACK);
974
                                                bufferedGraphics.drawRect(px+20, py+20, BATTERY_WIDTH, BATTERY_HEIGHT);
975
                                        }
976
                                        // If the robot has a destination, draw the vector
977
                                        if (r.destx >= 0) {
978
                                                bufferedGraphics.drawLine(px, py, (int)(x + r.destx * scale), (int)(y + r.desty * scale));
979
                                        }
980
                                }
981
                        }
982

    
983
                        // Identify currently-selected robot
984
                        RobotIcon r = robotIcons.get(selectedBot);
985
                        if (r != null) {
986
                                int px = (int) (x + r.x * scale);
987
                                int py = (int) (y + r.y * scale);
988
                                bufferedGraphics.setColor(Color.BLACK);
989
                                bufferedGraphics.drawOval(px-RADIUS-6, py-RADIUS-6, 2*r.RADIUS+12, 2*r.RADIUS+12);
990
                        }
991

    
992
                        //Display buffered content
993
                        g.drawImage(buffer, 0, 0, this);
994
                }
995

    
996
                /*
997
                * Convert a click on the webcam panel to a coordinate that is consistent with the
998
                * original size of the image that the panel contains.
999
                */
1000
                public Point convertClick (MouseEvent e) {
1001
                        if (img == null) {
1002
                                return new Point(e.getX(), e.getY());
1003
                        }
1004

    
1005
                        // Calculate scaling
1006
                        int clickx = e.getX();
1007
                        int clicky = e.getY();
1008
                        int maxWidth = getWidth() - 2*BORDER;
1009
                        int maxHeight = getHeight() - 2*BORDER;
1010
                        double widthRatio = 1.0 * maxWidth / img.getWidth();
1011
                        double heightRatio = 1.0 * maxHeight / img.getHeight();
1012
                        double scale = 0;
1013
                        int newWidth = 0;
1014
                        int newHeight = 0;
1015
                        int px = 0;
1016
                        int py = 0;
1017

    
1018
                        if (widthRatio > heightRatio) {         //height is the limiting factor
1019
                                scale = heightRatio;
1020
                                newHeight = maxHeight;
1021
                                newWidth = (int) (img.getWidth() * scale);
1022
                                py = clicky - BORDER;
1023
                                px = clickx - BORDER - (maxWidth - newWidth) / 2;
1024
                        } else {        //width is the limiting factor
1025
                                scale = widthRatio;
1026
                                newWidth = maxWidth;
1027
                                newHeight = (int) (img.getHeight() * scale);
1028
                                px = clickx - BORDER;
1029
                                py = clicky - BORDER - (maxHeight - newHeight) / 2;
1030
                        }
1031
                        py = (int) (py / scale);
1032
                        px = (int) (px / scale);
1033

    
1034
                        txtMatrix.setText("(" + clickx + "," + clicky + ") => (" + px + "," + py + ")");
1035
                        return new Point(px, py);
1036
                }
1037
        }
1038

    
1039
        /*
1040
        * WebcamLoader class
1041
        * Handles the loading of the webcam image.
1042
        */
1043
        class WebcamLoader extends Thread
1044
        {
1045
                final int WEBCAMLOADER_DELAY = 400;
1046
                final String IMAGE_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet.jpg";
1047

    
1048
                URL imagePath;
1049

    
1050
                MediaTracker mt;
1051
                BufferedImage image;
1052
                Random rand;
1053

    
1054
                public WebcamLoader (JApplet applet)
1055
                {
1056
                        super("ColonetWebcamLoader");
1057
                        mt = new MediaTracker(applet);
1058
                        ImageIO.setUseCache(false);
1059
                        rand = new Random();
1060
                }
1061

    
1062
                public void run ()
1063
                {
1064
                        while (true) {
1065
                                try {
1066
                                        Thread.sleep(WEBCAMLOADER_DELAY);
1067
                                        if (image != null)
1068
                                                image.flush();
1069
                                        System.gc();
1070
                                        try {
1071
                                                imagePath = new URL(IMAGE_PATH + "?rand=" + rand.nextInt(50000));
1072
                                        } catch (MalformedURLException e) {
1073
                                                System.out.println("Malformed URL: could not form URL from: [" + IMAGE_PATH + "]\n");
1074
                                        }
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
                                } catch (InterruptedException e) {
1084
                                        return;
1085
                                } catch (java.security.AccessControlException e) {
1086
                                        csi.warn("Could not load webcam.\n" + e);
1087
                                        return;
1088
                                } catch (IOException e) {
1089
                                        log.append("IOException while trying to load image.");
1090
                                }
1091
                        }
1092
                }
1093
        }
1094

    
1095
        /*
1096
        * VectorController class
1097
        * Manages robot motion control graphically
1098
        */
1099
        class VectorController extends GraphicsPanel implements MouseListener, MouseMotionListener {
1100
                int x, y, cx, cy;
1101
                int width, height;
1102
                int side;
1103

    
1104
                public VectorController (Image img) {
1105
                        super (img);
1106
                        width = img.getWidth(null);
1107
                        height = img.getHeight(null);
1108
                        cx = img.getWidth(null)/2;
1109
                        cy = img.getHeight(null)/2;
1110
                        x = cx;
1111
                        y = cy;
1112
                        if (width < height) {
1113
                                side = width;
1114
                        } else {
1115
                                side = height;
1116
                        }
1117
                        this.addMouseListener(this);
1118
                        this.addMouseMotionListener(this);
1119
                }
1120

    
1121
                public void setPoint (int x, int y) {
1122
                        if (isValidPoint(x, y)) {
1123
                                this.x = x;
1124
                                this.y = y;
1125
                        }
1126
                }
1127

    
1128
                public boolean isValidPoint (int x, int y) {
1129
                        double xterm = Math.pow(1.0*(x - cx)/(side/2), 2);
1130
                        double yterm = Math.pow(1.0*(y - cy)/(side/2), 2);
1131
                        return (xterm + yterm <= 1);
1132
                }
1133

    
1134
                public void notifyMouseEvent (MouseEvent e, boolean send) {
1135
                        if (!isValidPoint(e.getX(), e.getY())) {
1136
                                return;
1137
                        }
1138
                        setPoint(e.getX(), e.getY());
1139
                repaint();
1140
                        if (send) {
1141
                                sendToServer();
1142
                        }
1143
                }
1144

    
1145
                public void mouseExited(MouseEvent e) {
1146
                }
1147
                public void mouseEntered(MouseEvent e) {
1148
                }
1149
                public void mouseReleased(MouseEvent e) {
1150
                        this.notifyMouseEvent(e, true);
1151
                }
1152
                public void mouseClicked(MouseEvent e) {
1153
                        this.notifyMouseEvent(e, false);
1154
                }
1155
                public void mousePressed(MouseEvent e) {
1156
                }
1157
                public void mouseDragged(MouseEvent e) {
1158
                        vectorController.notifyMouseEvent(e, false);
1159
                }
1160
                public void mouseMoved(MouseEvent e) {
1161
                }
1162

    
1163
                public int getSpeed () {
1164
                        int dx = x - cx;
1165
                        int dy = y - cy;
1166
                        int v = (int) Math.sqrt( Math.pow(dx, 2) + Math.pow(dy, 2) );
1167
                        return v;
1168
                }
1169

    
1170
                /**
1171
                * Returns the angle of the control vector in positive degrees west of north,
1172
                * or negative degrees east of north, whichever is less than or equal to
1173
                * 180 degrees total.
1174
                */
1175
                public int getAngle () {
1176
                        int dx = x - cx;
1177
                        int dy = cy - y;
1178
                        // find reference angle in radians
1179
                        double theta = Math.atan2(Math.abs(dx), Math.abs(dy));
1180
                        // transform to degrees
1181
                        theta = theta * 180 / Math.PI;
1182
                        // adjust for quadrant
1183
                        if (dx < 0 && dy < 0)
1184
                                theta = 90 + theta;
1185
                        else if (dx < 0 && dy >= 0)
1186
                                theta = 90 - theta;
1187
                        else if (dx >= 0 && dy < 0)
1188
                                theta = -90 - theta;
1189
                        else
1190
                                theta = -90 + theta;
1191
                        return (int) theta;
1192
                }
1193

    
1194
                public void paint (Graphics g) {
1195
                        g.setColor(Color.BLACK);
1196
                        g.fillRect(0, 0, width, height);
1197
                        ((Graphics2D)g).setStroke(new BasicStroke(1));
1198
                        g.setColor(Color.RED);
1199
                        g.drawOval(cx-side/2, cy-side/2, side, side);
1200
                        ((Graphics2D)g).setStroke(new BasicStroke(2));
1201
                        g.setColor(Color.GREEN);
1202
                        g.drawLine(cx, cy, x, y);
1203
                        g.fillOval(x-3, y-3, 6, 6);
1204
                }
1205

    
1206
                public void setMaxForward () {
1207
                        setPoint(cx, cy - (side/2) + 1);
1208
                }
1209

    
1210
                public void setMaxReverse () {
1211
                        setPoint(cx, cy + (side/2) - 1);
1212
                }
1213

    
1214
                public void setMaxLeft () {
1215
                        setPoint(cx - (side/2) + 1, cy);
1216
                }
1217

    
1218
                public void setMaxRight () {
1219
                        setPoint(cx + (side/2) - 1, cy);
1220
                }
1221

    
1222
                public void setZero () {
1223
                        setPoint(cx, cy);
1224
                }
1225

    
1226
                public void sendToServer () {
1227
                        System.out.println("Attempting to send angle = " + getAngle() + ", speed = " + getSpeed() + "");
1228
                        String dest = ColonetServerInterface.GLOBAL_DEST;
1229
                        if (cmbRobotNum != null && cmbRobotNum.getSelectedIndex() > 0) {
1230
                                dest = (String)cmbRobotNum.getSelectedItem();
1231
                        }
1232

    
1233
                        if (csi != null) {
1234
                                /*
1235
                                csi.sendData(ColonetServerInterface.MOVE + " " + getSpeed() + " " + getAngle(), dest);
1236
                                */
1237

    
1238
                                //Directional commands
1239
                                if (x > cx && y == cy) {        //move right
1240
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 200", dest);
1241
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 200", dest);
1242
                                } else if (x < cx && y == cy) {         //move left
1243
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 200", dest);
1244
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 200", dest);
1245
                                } else if (x == cx && y > cy) {         //move forward
1246
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 225", dest);
1247
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 225", dest);
1248
                                } else if (x == cx && y < cy) {         //move backward
1249
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 225", dest);
1250
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 225", dest);
1251
                                } else if (x == cx && y == cy) {        //stop!
1252
                                        csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 0", dest);
1253
                                        csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 0", dest);
1254
                                }
1255
                        }
1256
                }
1257

    
1258
        }
1259

    
1260

    
1261

    
1262
}