Project

General

Profile

Statistics
| Revision:

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

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
                csi.disconnect();
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().getDefaultScreenDevice().getDefaultConfiguration();
149
                image = gc.createCompatibleImage(CANVAS_SIZE,CANVAS_SIZE);
150
                canvas = image.createGraphics();
151
                canvas.setStroke(new BasicStroke(2));         //set pen width
152
                panelGraph = new GraphicsPanel(image, false);         //set automatic double-buffering to false. we are doing it manually.
153
                panelWebcam = new WebcamPanel();
154
                tabPaneMain = new JTabbedPane();
155
                tabPaneMain.setFont(new Font("arial", Font.PLAIN, 16));
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
                // Set up robots
164
                botFont = new Font("arial", Font.PLAIN, 14);
165
                numBots = 0;
166
                selectedBot = -1;
167
                robotIcons = new HashMap <Integer, RobotIcon> ();
168

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

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

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

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

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

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

    
262

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
628
        class MouseHandler extends Thread {
629
                MouseEvent e;
630

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

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

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

    
656
                                return;
657
                        }
658

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

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

    
674
                                return;
675
                        }
676

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

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

    
708
                        repaint();
709
                }
710
        }
711

    
712
        class KeyHandler extends Thread {
713
                KeyEvent e;
714

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

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

    
742
        class ActionHandler extends Thread {
743
                ActionEvent e;
744

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

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

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

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

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

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

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

    
837
                        repaint();
838
                }
839
        }
840

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
957

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

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

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

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

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

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

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

    
1040
        /*
1041
        * WebcamLoader class
1042
        * Handles the loading of the webcam image.
1043
        */
1044
        class WebcamLoader extends Thread
1045
        {
1046
                final int WEBCAMLOADER_DELAY = 250;
1047
                final String IMAGE_PATH = "http://128.2.99.176/colonet.jpg";
1048

    
1049
                URL imagePath;
1050

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

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

    
1063
                public void run ()
1064
                {
1065
                        while (true) {
1066
                                try {
1067
                                        Thread.sleep(WEBCAMLOADER_DELAY);
1068
                                        if (image != null)
1069
                                                image.flush();
1070
                                        System.gc();
1071
                                        try {
1072
                                                imagePath = new URL(IMAGE_PATH + "?rand=" + rand.nextInt(100000));
1073
                                        } catch (MalformedURLException e) {
1074
                                                System.out.println("Malformed URL: could not form URL from: [" + IMAGE_PATH + "]\n");
1075
                                        }
1076
                                        image = ImageIO.read(imagePath);
1077
                                        // The MediaTracker waitForID pauses the thread until the image is loaded.
1078
                                        // We don't want to display a half-downloaded image.
1079
                                        mt.addImage(image, 1);
1080
                                        mt.waitForID(1);
1081
                                        mt.removeImage(image);
1082
                                        // Save
1083
                                        panelWebcam.setImage(image);
1084
                                } catch (InterruptedException e) {
1085
                                        return;
1086
                                } catch (java.security.AccessControlException e) {
1087
                                        csi.warn("Could not load webcam.\n" + e);
1088
                                        return;
1089
                                } catch (IOException e) {
1090
                                        log.append("IOException while trying to load image.");
1091
                                }
1092
                        }
1093
                }
1094
        }
1095

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1259
        }
1260

    
1261

    
1262

    
1263
}