Project

General

Profile

Statistics
| Revision:

root / trunk / code / projects / colonet / client / ColonetServerInterface.java @ 549

History | View | Annotate | Download (19 KB)

1
/*
2
* ColonetServerInterface.java
3
* Gregory Tress
4
*/
5

    
6
import java.net.*;
7
import java.io.*;
8
import javax.swing.JOptionPane;
9
import javax.swing.JTextArea;
10

    
11
/**
12
* The Colonet server interface class. This class handles direct communication with the Colonet server. The general
13
* contract is that this class will encapsulate the process of sending commands and requests to the server and
14
* receiving responses. This class should provide methods to send specific commands and requests so that the
15
* Colonet can easily communicate with the server. When data is received from the server, the ColonetServerInterface
16
* decides how to handle it and in many cases this means simply passing it to the Colonet.
17
* <p>
18
* The motivation is that any number of Colonet-type classes could be designed for different purposes if needed, with
19
* this class being used by each one for communication.
20
* For instance, if an application is designed which only monitors sensor data, or that only has access to
21
* the task queue, etc., the application could easily plug in to this interface.
22
* The Colonet should generally not contain communication-specific code or Strings of command and request data.
23
* If additional commands and requests are needed for permanent implementation, it is suggested that convenience
24
* classes be created in the ColonetServerInterface and called from the Colonet.
25
*
26
* @author Gregory Tress
27
*/
28
public class ColonetServerInterface
29
{
30
/*        Old packet structure:
31

32
                COMMAND PACKET STRUCTURE
33
        1:        SEND_TO_ROBOT
34
        2:        # of robot, or GLOBAL_DEST
35
        3:        COLONET_COMMMAND
36
        4:        message code (i.e. ORB_SET)
37
        5:        any data, as many that fit in the packet
38

39
        REQUEST PACKET STRUCTURE
40
        1:        REQUEST_FROM_SERVER
41
        2:        # of robot
42
        3:        COLONET_REQUEST
43
        4:        ???
44

45
        9/12/07 New server interface structure
46
                Client will no longer send full robot packets to the server.
47
                Commands will be defined as necessary.
48
        */
49

    
50
        //General Colonet Interface
51
        public static final String SEND_TO_ROBOT = "0";
52
        public static final String REQUEST_FROM_SERVER = "1";
53
        public static final String RESPONSE_TO_CLIENT_REQUEST = "2";
54
        public static final String REQUEST_BOM_MATRIX = "144";
55
        public static final String REQUEST_XBEE_IDS = "145";
56

    
57
        public static final String COLONET_COMMAND = "13"; //0x0D
58
        public static final String COLONET_REQUEST = "14"; //0x0E
59
        public static final String CORONET_RESPONSE = "15"; //0x0F
60
        public static final String GLOBAL_DEST = "200";
61
        public static final String CLIENT_REQUEST_ROBOT_POSITIONS = "86";
62
        public static final String CLIENT_ASSIGN_ROBOT_ID = "87";
63
        public static final String MOVE_TO_ABSOLUTE_POSITION = "83"; //0x53
64

    
65
        //Queue instructions
66
        public static final String COLONET_QUEUE = "100";
67
        public static final String QUEUE_UPDATE = "101";
68
        public static final String QUEUE_ADD = "102";
69
        public static final String QUEUE_REMOVE = "103";
70
        public static final String QUEUE_REORDER = "104";
71

    
72
        //Use BATTERY to request battery level
73
        public static final String BATTERY = "56"; //0x38
74

    
75
        //MOTORS
76
        public static final String MOTORS_INIT = "23"; //0x17
77
        public static final String MOTOR1_SET = "24"; //0x18
78
        public static final String MOTOR2_SET = "25"; //0x19
79
        public static final String MOTORS_OFF = "26"; //0x1A
80
        public static final String MOVE = "27"; //0x1B
81
        public static final String MOVE_AVOID = "28"; //0x1C
82

    
83
        //BUZZER
84
        public static final String BUZZER_INIT = "0"; //0x00
85
        public static final String BUZZER_SET_VAL = "1"; //0x01
86
        public static final String BUZZER_SET_FREQ = "2"; //0x02
87
        public static final String BUZZER_CHIRP = "3"; //0x03
88
        public static final String BUZZER_OFF = "4"; //0x04
89

    
90
        //ORB
91
        public static final String ORB_INIT = "12"; //0x0C
92
        public static final String ORB_SET = "13"; //0x0D
93
        public static final String ORB_SET_COLOR = "14"; //0x0E
94
        public static final String ORB_DISABLE = "15"; //0x0F
95
        public static final String ORB_ENABLE = "16"; //0x10
96
        public static final String ORB_SET_DIO = "17"; //0x11
97
        public static final String LED_INIT = "18"; //0x12
98
        public static final String LED_USER = "19"; //0x13
99
        public static final String ORB_SET_NUM_NS = "20"; //0x14
100
        public static final String ORB_SET_NUM = "21"; //0x15
101
        public static final String ORB_SEND = "22"; //0x16
102

    
103
        Colonet colonet;        //save reference to the entire applet locally
104
        Socket socket;
105
        OutputStreamWriter out;
106
        BufferedReader reader;
107
        DataListener dataListener;
108
        JTextArea log, txtMatrix;
109

    
110
        /*
111
        * FUNCTION IMPLEMENTATIONS
112
        */
113

    
114
        /**
115
        * Constructs a new ColonetServerInterface. When constructing a ColonetServerInterface, a valid Colonet object
116
        * reference must be provided to ensure that data is routed correctly.
117
        *
118
        * @param colonet The Colonet object to save locally. This reference cannot be changed once the
119
        *                ColonetSreverInterface has been contsructed.
120
        * @throws NullPointerException if colonet is null
121
        *
122
        */
123
        public ColonetServerInterface (Colonet colonet) {
124
                this.colonet = colonet;
125
                this.log = colonet.getLog();
126
                this.txtMatrix = colonet.getMatrixInput();
127
                dataListener = new DataListener();
128
        }
129

    
130
        public Socket getSocket () {
131
                return socket;
132
        }
133

    
134
        public OutputStreamWriter getOutputStreamWriter () {
135
                return out;
136
        }
137

    
138
        public BufferedReader getBufferedReader () {
139
                return reader;
140
        }
141

    
142
        public boolean isReady () {
143
                if (socket == null || out == null || reader == null)
144
                        return false;
145
                if (!socket.isConnected() || socket.isClosed() || socket.isInputShutdown() || socket.isOutputShutdown())
146
                        return false;
147
                return true;
148
        }
149

    
150
        public boolean isInputReady () {
151
                try {
152
                        if (reader.ready()) return true;
153
                } catch (Exception e) {
154
                        return false;
155
                }
156
                return false;
157
        }
158

    
159
        public String getLine () throws IOException {
160
                return reader.readLine();
161
        }
162

    
163
        /**
164
         * Create socket connection to Colonet server.
165
         * If successful, start thread for listening for incoming data.
166
         */
167
        public void connect (String strHost, String strPort) {
168
                //make sure hostname and port are valid
169
                if (strHost.equals("") || strPort.equals("")) {
170
                        err("Please enter a hostname and port.");
171
                        return;
172
                }
173
                int port = 0;
174
                try {
175
                        port = Integer.parseInt(strPort);
176
                } catch (Exception e) {
177
                        err("Invalid port");
178
                        return;
179
                }
180

    
181
                //make sure we aren't already connected.
182
                if (socket != null && socket.isConnected()) {
183
                        return;
184
                }
185

    
186
                try {
187
                        socket = new Socket(strHost, port);
188
                        socket.setKeepAlive(true);
189
                } catch (UnknownHostException e) {
190
                        log.append("Unknown host exception.\n");
191
                        err("Unknown Host Exception");
192
                        return;
193
                } catch (IOException e) {
194
                        log.append("IO Exception.\n");
195
                        err("Failed to connect to " + strHost + ".\n");
196
                        return;
197
                } catch (java.security.AccessControlException e) {
198
                        log.append("Access Control Exception.\n");
199
                        err("Permission denied by java.security.AccessControlException.\n\n"
200
                                + "You may only connect to the server from which this applet was loaded.");
201
                        return;
202
                }
203

    
204
                if (socket == null || !socket.isConnected()) {
205
                        log.append("Connection is not ready. Try connecting again.\n");
206
                        return;
207
                }
208
                try {
209
                        out = new OutputStreamWriter(socket.getOutputStream());
210
                        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
211
                } catch (IOException e) {
212
                        warn("Could not get transfer streams from socket connection.");
213
                }
214

    
215
                dataListener.start();
216
        }
217

    
218
        public void disconnect () {
219
                try {
220
                        if (reader != null) {
221
                                reader.close();
222
                        }
223
                        if (out != null) {
224
                                out.close();
225
                        }
226
                        colonet.disconnect();
227
                } catch (IOException e) {
228
                }
229
        }
230

    
231
        /*
232
        * Send a general String to the OutputStream.
233
        */
234
        private void sendString (String s) {
235
                //make sure we can send
236
                if (!this.isReady()) {
237
                        log.append("Could not send data.\n");
238
                        return;
239
                }
240
                //send packet
241
                try {
242
                        Thread.sleep(50);         //pause to be safe
243
                        out.write(s);
244
                        out.flush();
245
                        //log.append("Sent: " + s + "\n");
246
                } catch (IOException e) {
247
                        log.setText("Could not send data.\n");
248
                } catch (InterruptedException e) {
249
                        log.setText("Thread InterruptedException in sendData\n");
250
                }
251
        }
252

    
253
        /**
254
        * General send-to-server method. This method is used by other command methods, which are usually convenience
255
        * methods that simply specify arguments to this method. A command consists of a String which holds integers
256
        * separated by spaces. This method should not be used directly unless you know the format of the particular
257
        * command you are sending. If implementing a particular command for permanent use, it is recommended that
258
        * you create a new wrapper method specific to that command in the ColonetServerInterface file.
259
        *
260
        * Note that no checking is performed in this method to ensure the correct formatting of the String arguments.
261
        * If malformed commands or robot numbers are specified, the behavior of the request at the server will be
262
        * undefined and could result in server failure.
263
        *
264
        * @param s The command String in its correct format. The format of a command String is ultimately specified
265
        * by the Colonet server application and may change.
266
        * @param robotNumber The number of the robot that is the subject of the command, if any. The robot number
267
        * is specified as a single integer in a String. If the command does not have a single robot subject, this
268
        * argument can be null or an empty String, whichever is convenient.
269
        */
270
        public void sendData (String s, String robotNumber) {
271
                //create packet
272
                String packet = "";
273
                packet += ColonetServerInterface.SEND_TO_ROBOT;
274
                if (robotNumber != null)
275
                        packet += " " + robotNumber;
276
                packet += " " + ColonetServerInterface.COLONET_COMMAND;
277
                packet += " " + s;        //add         the command code here
278
                packet += "\n";
279
                sendString(packet);
280
                //txtMatrix.append("S:" + packet);
281
        }
282

    
283
        /**
284
        * General request-from-server method. This method is used by other request methods, which are usually convenience
285
        * methods that simply specify arguments to this method. A request consists of a String which holds integers
286
        * separated by spaces. This method should not be used directly unless you know the format of the particular
287
        * request you are making. If implementing a particular request, it is recommended that you create a new method
288
        * specific to that request in the ColonetServerInterface file.
289
        *
290
        */
291
        private void sendRequest (String s, String robotNumber) {
292
                //create packet
293
                String packet = "";
294
                packet += ColonetServerInterface.REQUEST_FROM_SERVER;
295
                packet += " " + robotNumber;
296
                packet += " " + s;        //add         the command code here
297
                packet += "\n";
298
                sendString(packet);
299
        }
300

    
301
        /**
302
        * Sends a request to the server to report the entire BOM sensor matrix. The server will reply at its convenience.
303
        * No guarantee is made (end-to-end or otherwise) that the server will respond in a timely manner or at all
304
        * to any individual request.
305
        */
306
        public void sendSensorDataRequest () {
307
                sendRequest(ColonetServerInterface.REQUEST_BOM_MATRIX, "");
308
        }
309

    
310
        /**
311
        * Sends a request to the server to report a list of XBee IDs. The server will reply at its convenience.
312
        * The purpose of having this list is to ensure that robots are properly identified for control purposes.
313
        * This keeps robot identification consistent between sessions and prevents arbitrary assignment.
314
        * No guarantee is made (end-to-end or otherwise) that the server will respond in a timely manner or at all
315
        * to any individual request.
316
        *
317
        * @see Colonet#parseXBeeIDs(String)
318
        */
319
        public void sendXBeeIDRequest () {
320
                sendRequest(ColonetServerInterface.REQUEST_XBEE_IDS, "");
321
        }
322

    
323
        /**
324
        * Sends a battery request for a specific robot to the server. The server will reply at its convenience.
325
        * Behavior is undefined if an invalid robot number is specified. The server will probably not respond in
326
        * this case.
327
        * No guarantee is made (end-to-end or otherwise) that the server will respond in a timely manner or at all
328
        * to any individual request.
329
        *
330
        * @param robotNum The number of the robot for which we are requesting the battery. Note that this value
331
        * is sent as-is to the server. No mapping to or from XBee IDs is performed. The contract for this is
332
        * currently undefined.
333
        * @see Colonet#parseBattery(String)
334
        */
335
        public void sendBatteryRequest (int robotNum) {
336
                //create packet
337
                String packet = "";
338
                packet += ColonetServerInterface.SEND_TO_ROBOT;
339
                packet += " " + robotNum;
340
                packet += " " + ColonetServerInterface.COLONET_REQUEST;
341
                packet += " " + ColonetServerInterface.BATTERY;         //add        the command code here
342
                packet += "\n";
343
                sendString(packet);
344
        }
345

    
346
        /**
347
        * Requests a list of all robot positions and correspondind robot IDs.
348
        */
349
        public void sendPositionRequest () {
350
                sendRequest(ColonetServerInterface.CLIENT_REQUEST_ROBOT_POSITIONS, "");
351
        }
352

    
353
        /**
354
        * Send a robot ID assignment update to store on the server.
355
        */
356
        public void sendIDAssignment (int oldID, int newID) {
357
                String packet = "";
358
                packet += ColonetServerInterface.REQUEST_FROM_SERVER;
359
                packet += " " + CLIENT_ASSIGN_ROBOT_ID;
360
                packet += " " + oldID + " " + newID;
361
                packet += "\n";
362
                sendString(packet);
363
        }
364

    
365
        /**
366
        * Order a robot to move to an absolute coordinate point.
367
        */
368
        public void sendAbsoluteMove (int id, int x, int y) {
369
                        sendData(MOVE_TO_ABSOLUTE_POSITION + " " + x + " " + y, "" + id);
370
        }
371

    
372
        /*
373
        * Queue management
374
        */
375
        private void sendQueueInstruction (String inst) {
376
                String packet = "";
377
                packet += ColonetServerInterface.COLONET_QUEUE;
378
                packet += " " + inst;
379
                packet += "\n";
380
                sendString(packet);
381
        }
382

    
383
        /**
384
        * Notifies the Colonet server to add a task to the current task queue. The Colonet server holds the canonical
385
        * task queue. Any applet can send tasks to add to the queue. Local copies of the queue in the applet are for
386
        * display purposes only, and are not authoritative when adding tasks. All clients send additions asynchronously,
387
        * and as a result no guarantee is made that a task will be added in the specificed location in the queue or at
388
        * all. If an invalid position is specified, the task will probably not be added to the queue and may cause
389
        * server failure. Due to the asynchronous nature of the queue, we cannot easily account for concurrent
390
        * modification failures on the client side.
391
        *
392
        * @param pos The position in the queue at which we would like the task to be placed. Note that this is not
393
        * guaranteed. Invalid positions may cause the task to be discarded at the server.
394
        * @param data The String containing the command code(s) for the task and any arguments necessary to fully
395
        * define the behavior of the task. This format is currently not specified. In the future, the canonical format
396
        * of the data String will ultimately be defined by the Colonet server.
397
        * @param description A String that contains a description of the task. This will be the message displayed to
398
        * the user when information about the task is requested.
399
        */
400
        public void sendQueueAdd (int pos, String data, String description) {
401
                String packet = "";
402
                packet += ColonetServerInterface.QUEUE_ADD;
403
                packet += " " + pos;
404
                packet += " " + data;
405
                packet += " [" + description + "]";
406
                packet += "\n";
407
                sendQueueInstruction(packet);
408
        }
409

    
410
        /**
411
        * Notifies the Colonet server to remove a task from the current task queue. The Colonet server holds the canonical
412
        * task queue. Any applet can remove a task from the queue. Local copies of the queue in the applet are for
413
        * display purposes only, and are not authoritative when removing tasks. All clients remove tasks asynchronously,
414
        * and as a result no guarantee is made that the correct task will actually be removed.
415
        * If an invalid position is specified, the state of the queue is undefined and server failure may result.
416
        * Due to the asynchronous nature of the queue, we cannot easily account for concurrent
417
        * modification failures on the client side.
418
        *
419
        * @param pos The position in the queue at which we would like the task to be removed. Note that this is not
420
        * guaranteed. Invalid positions may result in a corrupted queue.
421
        */
422
        public void sendQueueRemove (int pos) {
423
                String packet = "";
424
                packet += ColonetServerInterface.QUEUE_REMOVE;
425
                packet += " " + pos;
426
                packet += "\n";
427
                sendQueueInstruction(packet);
428
        }
429

    
430
        /**
431
        * Notifies the Colonet server to reorder tasks in the current task queue. The Colonet server holds the canonical
432
        * task queue. Any applet can reorder tasks in the queue. Local copies of the queue in the applet are for
433
        * display purposes only, and are not authoritative when reordering tasks. All clients reorder tasks asynchronously,
434
        * and as a result no guarantee is made that the correct tasks will actually be reordered.
435
        * If an invalid position is specified, the state of the queue is undefined and server failure may result.
436
        * Due to the asynchronous nature of the queue, we cannot easily account for concurrent
437
        * modification failures on the client side.
438
        *
439
        * @param pos1 The queue position of a task which we would like to reorder.
440
        * @param pos2 The queue position of a task which we would like to reorder.
441
        */
442
        public void sendQueueReorder (int pos1, int pos2) {
443
                String packet = "";
444
                packet += ColonetServerInterface.QUEUE_REORDER;
445
                packet += " " + pos1;
446
                packet += " " + pos2;
447
                packet += "\n";
448
                sendQueueInstruction(packet);
449
        }
450

    
451
        public void sendQueueUpdate () {
452
                sendQueueInstruction(ColonetServerInterface.QUEUE_UPDATE);
453
        }
454

    
455
        /**
456
         * Display informational message box on the screen. Used for casual communicaton to the user.
457
         * @param text Text to display
458
         */
459
        public void msg (String text) {
460
                JOptionPane.showMessageDialog(colonet, text, "Colonet", JOptionPane.INFORMATION_MESSAGE);
461
        }
462

    
463
        /**
464
         * Display warning message box on the screen. Used for minor alerts or exceptions.
465
         * @param text Text to display
466
         */
467
        public void warn (String text) {
468
                JOptionPane.showMessageDialog(colonet, text, "Colonet", JOptionPane.WARNING_MESSAGE);
469
        }
470

    
471
        /**
472
         * Display error message box on the screen. Used for major errors or exceptions in the program.
473
         * @param text Text to display
474
         */
475
        public void err (String text) {
476
                JOptionPane.showMessageDialog(colonet, text, "Colonet", JOptionPane.ERROR_MESSAGE);
477
        }
478

    
479

    
480
        /*
481
        * DataListener thread.
482
        *
483
        */
484
        class DataListener extends Thread {
485
                final int DATALISTENER_DELAY = 122;
486

    
487
                public DataListener () {
488
                        super("Colonet DataListener");
489
                }
490

    
491
                public void run () {
492
                        String line;
493
                        while (true) {
494
                                try {
495
                                        line = reader.readLine();
496
                                        if (line == null) {
497
                                                throw new IOException();
498
                                        }
499
                                        parseData(line);
500
                                        Thread.sleep(DATALISTENER_DELAY);
501
                                } catch (InterruptedException e) {
502
                                        return;
503
                                } catch (IOException e) {
504
                                        disconnect();
505
                                        return;
506
                                }
507
                        }
508
                }
509

    
510
                public void parseData (String line) {
511
                        // Sensor Matrix
512
                        if (line.startsWith(ColonetServerInterface.RESPONSE_TO_CLIENT_REQUEST + " " +
513
                                ColonetServerInterface.REQUEST_BOM_MATRIX))
514
                                colonet.parseMatrix(line);
515
                        // Task Queue
516
                        else if (line.startsWith(ColonetServerInterface.COLONET_QUEUE))
517
                                colonet.parseQueue(line);
518
                        // XBee IDs
519
                        else if (line.startsWith(ColonetServerInterface.RESPONSE_TO_CLIENT_REQUEST + " " +
520
                                ColonetServerInterface.REQUEST_XBEE_IDS))
521
                                colonet.parseXBeeIDs(line);
522
                        // Battery
523
                        else if (line.startsWith(ColonetServerInterface.RESPONSE_TO_CLIENT_REQUEST + " " +
524
                                ColonetServerInterface.BATTERY))
525
                                colonet.parseBattery(line);
526
                        // Robot Positions
527
                        else if (line.startsWith(ColonetServerInterface.RESPONSE_TO_CLIENT_REQUEST + " " +
528
                                ColonetServerInterface.CLIENT_REQUEST_ROBOT_POSITIONS))
529
                                colonet.parsePositions(line);
530
                        // Unknown type
531
                        else {
532
                                //txtMatrix.setText("Got unknown data: " + line + "\n");
533
                        }
534
                }
535

    
536
        }
537

    
538
}