Project

General

Profile

Statistics
| Revision:

root / trunk / code / projects / libwireless / lib / xbee.c @ 1430

History | View | Annotate | Download (21.2 KB)

1
/**
2
 * Copyright (c) 2007 Colony Project
3
 *
4
 * Permission is hereby granted, free of charge, to any person
5
 * obtaining a copy of this software and associated documentation
6
 * files (the "Software"), to deal in the Software without
7
 * restriction, including without limitation the rights to use,
8
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following
11
 * conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be
14
 * included in all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 * OTHER DEALINGS IN THE SOFTWARE.
24
 **/
25

    
26
/**
27
 * @file xbee.c
28
 * @brief XBee Interface
29
 *
30
 * Implementation of low level communication with the XBee in API mode.
31
 *
32
 * @author Brian Coltin, Colony Project, CMU Robotics Club
33
 **/
34

    
35
#include "xbee.h"
36
#include "wl_defs.h"
37

    
38
#ifndef ROBOT
39

    
40
#include <fcntl.h>
41
#include <unistd.h>
42
#include <pthread.h>
43
#include <errno.h>
44
#include <termios.h>
45

    
46
#else
47

    
48
#include <serial.h>
49
#include <avr/interrupt.h>
50

    
51
#endif
52

    
53
#include <stdio.h>
54
#include <stdlib.h>
55
#include <string.h>
56

    
57
#define XBEE_FRAME_START 0x7E
58
#define XBEE_GET_PACKET_TIMEOUT 1000
59

    
60
/*Frame Types*/
61
#define XBEE_FRAME_STATUS 0x8A
62
#define XBEE_FRAME_AT_COMMAND 0x08
63
#define XBEE_FRAME_AT_COMMAND_RESPONSE 0x88
64
#define XBEE_FRAME_TX_REQUEST_64 0x00
65
#define XBEE_FRAME_TX_REQUEST_16 0x01
66
#define XBEE_FRAME_TX_STATUS XBEE_TX_STATUS
67
#define XBEE_FRAME_RX_64 0x80
68
#define XBEE_FRAME_RX_16 XBEE_RX
69

    
70
/*Internal Function Prototypes*/
71

    
72
/*I/O Functions*/
73
static int xbee_send(char* buf, int size);
74
static int xbee_send_string(char* c);
75

    
76
#ifndef ROBOT
77
static int xbee_read(char* buf, int size);
78
#endif
79

    
80
/*Command Mode Functions
81
 * Called during initialization.
82
 */
83
static int xbee_enter_command_mode(void);
84
static int xbee_exit_command_mode(void);
85
static int xbee_enter_api_mode(void);
86
static int xbee_wait_for_string(char* s, int len);
87
static int xbee_wait_for_ok(void);
88

    
89
/*API Mode Functions*/
90

    
91
static int xbee_handle_packet(char* packet, int len);
92
static void xbee_handle_at_command_response(char* command, char result, char* extra, int extraLen);
93
static void xbee_handle_status(char status);
94
static int xbee_verify_checksum(char* packet, int len);
95
static char xbee_compute_checksum(char* packet, int len);
96
static int xbee_send_frame(char* buf, int len);
97
static int xbee_send_read_at_command(char* command);
98
static int xbee_send_modify_at_command(char* command, char* value);
99

    
100
/*Global Variables*/
101

    
102
#ifndef ROBOT
103
static char* xbee_com_port = XBEE_PORT_DEFAULT;
104
static int xbee_stream;
105
static pthread_t* xbee_listen_thread;
106
#endif
107

    
108
// TODO: is this a good size?
109
#define XBEE_BUFFER_SIZE        128
110
#define PACKET_BUFFER_SIZE        108
111
// a buffer for data received from the XBee
112
char arrival_buf[XBEE_BUFFER_SIZE];
113
// location of last unread byte in buffer
114
volatile int buffer_last = 0;
115
// first unread byte in buffer
116
volatile int buffer_first = 0;
117

    
118

    
119
//used to store packets as they are read
120
static char xbee_buf[PACKET_BUFFER_SIZE];
121
static int currentBufPos = 0;
122

    
123
//XBee status
124
static unsigned int xbee_panID = XBEE_PAN_DEFAULT;
125
static unsigned int xbee_pending_panID = XBEE_PAN_DEFAULT;
126
static int xbee_channel = XBEE_CHANNEL_DEFAULT;
127
static int xbee_pending_channel = XBEE_CHANNEL_DEFAULT;
128
static volatile unsigned int xbee_address = 0;
129

    
130
/*Function Implementations*/
131

    
132
#ifdef ROBOT
133

    
134
/**
135
 * Interrupt for the robot. Adds bytes received from the xbee
136
 * to the buffer.
137
 **/
138
#ifndef FIREFLY
139
ISR(USART1_RX_vect)
140
{
141
        char c = UDR1;
142
        arrival_buf[buffer_last] = c;
143
        int t = buffer_last + 1;
144
        if (t == XBEE_BUFFER_SIZE)
145
                t = 0;
146
        if (t == buffer_first)
147
        {
148
                WL_DEBUG_PRINT("\nOut of space in buffer.\n");
149
        }
150
        buffer_last = t;
151
}
152
#else
153
SIGNAL(SIG_USART0_RECV)
154
{
155
        char c = UDR0;
156
        arrival_buf[buffer_last] = c;
157
        int t = buffer_last + 1;
158
        if (t == XBEE_BUFFER_SIZE)
159
                t = 0;
160
        if (t == buffer_first)
161
        {
162
                WL_DEBUG_PRINT("Out of space in buffer.\n");
163
        }
164
        buffer_last = t;
165
}
166
#endif
167

    
168
#else
169

    
170
// Computer code
171

    
172
/**
173
 * Thread that listens to the xbee.
174
 **/
175
static void* listen_to_xbee(void* x)
176
{
177
        char c;
178
        while (1)
179
        {
180
                if (xbee_read(&c, 1) != 0) {
181
                        WL_DEBUG_PRINT("xbee_read failed.\n");
182
                        return NULL;
183
                }
184

    
185
                arrival_buf[buffer_last] = c;
186
                int t = buffer_last + 1;
187
                if (t == XBEE_BUFFER_SIZE)
188
                        t = 0;
189
                if (t == buffer_first)
190
                {
191
                        WL_DEBUG_PRINT("Out of space in buffer.\n");
192
                }
193
                buffer_last = t;
194

    
195
                usleep(1000);
196
        }
197

    
198
        return NULL;
199
}
200

    
201
#endif
202

    
203
/**
204
 * Initializes the XBee library so that other functions may be used.
205
 **/
206
int xbee_lib_init()
207
{
208
        WL_DEBUG_PRINT("in xbee_init\n");
209
#ifdef ROBOT
210

    
211
        //enable the receiving interrupt
212
#ifdef FIREFLY
213
        UCSR0B |= _BV(RXCIE) | _BV(RXEN);
214
#else
215
#ifdef BAYBOARD
216
        UCSR1B |= _BV(RXCIE1);
217
#else
218
        UCSR1B |= _BV(RXCIE);
219
#endif
220
#endif
221
        sei();
222
#else
223
        xbee_stream = open(xbee_com_port, O_RDWR);
224
        if (xbee_stream == -1/* || lockf(xbee_stream, F_TEST, 0) != 0*/)
225
        {
226
                WL_DEBUG_PRINT("Failed to open connection to XBee on port ");
227
                WL_DEBUG_PRINT_INT(xbee_com_port);
228
                WL_DEBUG_PRINT(".\n");
229
                return -1;
230
        } else {
231
          WL_DEBUG_PRINT("Successfully opened connection to XBee on port ");
232
                WL_DEBUG_PRINT_INT(xbee_com_port);
233
                WL_DEBUG_PRINT(".\n");
234
        }
235

    
236
        // set baud rate, etc. correctly
237
        struct termios options;
238

    
239
        tcgetattr(xbee_stream, &options);
240
        cfsetispeed(&options, B9600);
241
        cfsetospeed(&options, B9600);
242
        options.c_iflag &= ~ICRNL;
243
        options.c_oflag &= ~OCRNL;
244
        options.c_cflag |= (CLOCAL | CREAD);
245
        options.c_cflag &= ~PARENB;
246
        options.c_cflag &= ~CSTOPB;
247
        options.c_cflag &= ~CSIZE;
248
        options.c_cflag |= CS8;
249
        options.c_lflag &= ~ICANON;
250
        options.c_cc[VMIN] = 1;
251
        options.c_cc[VTIME] = 50;
252

    
253
        if (tcsetattr(xbee_stream, TCSANOW, &options))
254
        {
255
                WL_DEBUG_PRINT("Error setting attributes.\n");
256
                return -1;
257
        }
258

    
259
        xbee_listen_thread = (pthread_t*)malloc(sizeof(pthread_t));
260
        if (xbee_listen_thread == NULL)
261
        {
262
                WL_DEBUG_PRINT("Malloc failed.\n");
263
                return -1;
264
        }
265

    
266
        int ret = pthread_create(xbee_listen_thread, NULL, listen_to_xbee, NULL);
267
        if (ret)
268
        {
269
                WL_DEBUG_PRINT("Failed to create listener thread.\n");
270
                return -1;
271
        }
272
#endif
273

    
274
        WL_DEBUG_PRINT("Entering command mode.\n");
275

    
276
        if (xbee_enter_command_mode() != 0) {
277
                return -1;
278
        }
279

    
280
        WL_DEBUG_PRINT("Entered command mode.\n");
281

    
282
        if (xbee_enter_api_mode() != 0) {
283
                return -1;
284
        }
285

    
286
        WL_DEBUG_PRINT("Entered api mode.\n");
287

    
288
        if (xbee_exit_command_mode() != 0) {
289
             return -1;
290
        }
291
        
292
        WL_DEBUG_PRINT("Left command mode.\n");
293

    
294
        if (xbee_send_read_at_command("MY")) {
295
                return -1;
296
        }
297
        WL_DEBUG_PRINT("Getting ATMY address.\n");
298

    
299
#ifndef ROBOT
300
        int i;
301
        for (i = 0; xbee_address == 0 && i < XBEE_GET_PACKET_TIMEOUT; i++) {
302
          ret = xbee_get_packet(NULL);
303

    
304
          usleep(1000);
305
          
306
/*           if (ret == -1) { */
307
/*             WL_DEBUG_PRINT("xbee_get_packet(NULL) failed.\n"); */
308
/*             return -1; */
309
/*           } */
310
        }
311
#else
312
        //wait to return until the address is set
313
  //TODO: this shouldn't wait indefinitely.  There should be some sort of reasonable timeout
314
  // so if the address is never set right, an error can be returned instead of having the
315
  // robot hang forever
316
        while (xbee_address == 0) {
317
          xbee_get_packet(NULL);
318
        }
319
#endif
320
        WL_DEBUG_PRINT("Got ATMY address.\n");
321

    
322
#ifndef ROBOT
323
        if (i == XBEE_GET_PACKET_TIMEOUT) { // We timed-out.
324

    
325
          WL_DEBUG_PRINT("xbee_get_packet timed out.\n");
326
          return -1;
327
        } else {
328
          return 0;
329
        }
330
#else
331
        return 0;
332
#endif
333
}
334

    
335
/**
336
 * Call when finished using the XBee library. This releases
337
 * all sued resources.
338
 **/
339
void xbee_terminate()
340
{
341
        #ifndef ROBOT
342
        pthread_cancel(*xbee_listen_thread);
343
    pthread_join(*xbee_listen_thread, NULL);
344
        free(xbee_listen_thread);
345
        lockf(xbee_stream, F_ULOCK, 0);
346
        close(xbee_stream);
347
        #endif
348
}
349

    
350
/**
351
 * Send a buffer buf of size bytes to the XBee.
352
 *
353
 * @param buf the buffer of data to send
354
 * @param size the number of bytes to send
355
 **/
356
static int xbee_send(char* buf, int size)
357
{
358
#ifdef ROBOT
359
        int i;
360
        for (i = 0; i < size; i++) {
361
                xbee_putc(buf[i]);
362
        }
363

    
364
        return 0;
365

    
366
#else
367

    
368
        int ret = write(xbee_stream, buf, size);
369
        //success
370
        if (ret == size)
371
                return 0;
372
        if (ret == -1)
373
        {
374
                //interrupted by system signal, probably timer interrupt.
375
                //just try again
376
                if (errno == 4)
377
                {
378
                        return xbee_send(buf, size);
379
                }
380
                WL_DEBUG_PRINT("Failed to write to xbee\r\n");
381
                return -1;
382
        }
383

    
384
        //write was interrupted after writing ret bytes
385
        return xbee_send(buf + ret, size - ret);
386
#endif
387
}
388

    
389
/**
390
 * Sends a string to the XBee.
391
 *
392
 * @param c the string to send to the XBEE
393
 **/
394
static int xbee_send_string(char* c)
395
{
396
        return xbee_send(c, strlen(c));
397
}
398

    
399
#ifndef ROBOT
400
static int xbee_read(char* buf, int size)
401
{
402
        if (read(xbee_stream, buf, size) == -1) {
403
                WL_DEBUG_PRINT("Failed to read from xbee.\r\n");
404
                return -1;
405
        }
406

    
407
        return 0;
408
}
409
#endif
410

    
411
/**
412
 * Enter into command mode.
413
 **/
414
static int xbee_enter_command_mode()
415
{
416
        if (xbee_send_string("+++") != 0) {
417
                return -1;
418
        }
419

    
420
        if (xbee_wait_for_ok() != 0) {
421
          return -1;
422
        }
423
          return 0;
424
}
425

    
426
/**
427
 * Exit from command mode.
428
 **/
429
static int xbee_exit_command_mode()
430
{
431
        if (xbee_send_string("ATCN\r") != 0) {
432
                return -1;
433
        }
434

    
435
        xbee_wait_for_ok();
436

    
437
        return 0;
438
}
439

    
440
/**
441
 * Enter API mode.
442
 **/
443
static int xbee_enter_api_mode()
444
{
445
        if (xbee_send_string("ATAP 1\r") != 0) {
446
                return -1;
447
        }
448
        xbee_wait_for_ok();
449

    
450
        return 0;
451
}
452

    
453
/**
454
 * Wait until the string "OK\r" is received from the XBee.
455
 **/
456
static int xbee_wait_for_ok()
457
{
458
        return xbee_wait_for_string("OK\r", 3);
459
}
460

    
461
/**
462
 * Delay until the specified string is received from
463
 * the XBee. Discards all other XBee data.
464
 *
465
 * @param s the string to receive
466
 * @param len the length of the string
467
 **/
468
static int xbee_wait_for_string(char* s, int len)
469
{
470
        char* curr = s;
471
        while (curr - s < len) {
472
                // check if buffer is empty
473
                if (buffer_last != buffer_first) {
474
                        char c = arrival_buf[buffer_first++];
475
                        if (buffer_first == XBEE_BUFFER_SIZE) {
476
                                buffer_first = 0;
477
                        }
478

    
479
                        if (c == *curr) {
480
                                curr++;
481
                        } else {
482
#ifndef ROBOT
483
                          //return -1; // Computer is less forgiving.
484
                          curr = s;
485
#else
486
                          curr = s;
487
#endif
488
                        }
489
                } // else buffer is empty.
490

    
491
#ifndef ROBOT
492
                usleep(100);
493
#endif
494
        }
495

    
496
        return 0;
497
}
498

    
499
/**
500
 * Verifies that the packets checksum is correct.
501
 * (If the checksum is correct, the sum of the bytes
502
 * is 0xFF.)
503
 *
504
 * @param packet the packet received. This includes the first
505
 * three bytes, which are header information from the XBee.
506
 *
507
 * @param len The length of the packet received from the XBee
508
 *
509
 * @return 0 if the checksum is incorrect, nonzero
510
 * otherwise
511
 **/
512
int xbee_verify_checksum(char* packet, int len)
513
{
514
        unsigned char sum = 0;
515
        int i;
516
        for (i = 3; i < len; i++)
517
                sum += (unsigned char)packet[i];
518
        return sum == 0xFF;
519
}
520

    
521
/**
522
 * Returns the checksum of the given packet.
523
 *
524
 * @param buf the data for the packet to send
525
 * @param len the length of the packet in bytes
526
 *
527
 * @return the checksum of the packet, which will
528
 * become the last byte sent in the packet
529
 **/
530
char xbee_compute_checksum(char* buf, int len)
531
{
532
        int i;
533
        unsigned char sum = 0;
534
        for (i = 0; i < len; i++)
535
                sum += (unsigned char)buf[i];
536
        return 0xFF - sum;
537
}
538

    
539
/**
540
 * Adds header information and checksum to the given
541
 * packet and sends it. Header information includes
542
 * XBEE_FRAME_START and the packet length, as two bytes.
543
 *
544
 * @param buf the packet data
545
 * @param len the size in bytes of the packet data
546
 *
547
 **/
548
static int xbee_send_frame(char* buf, int len)
549
{
550
        char prefix[3];
551
        prefix[0] = XBEE_FRAME_START;
552
        prefix[1] = (len & 0xFF00) >> 8;
553
        prefix[2] = len & 0xFF;
554
        char checksum = xbee_compute_checksum(buf, len);
555

    
556
        if (xbee_send(prefix, 3) != 0) {
557
                return -1;
558
        }
559

    
560
        if (xbee_send(buf, len) != 0) {
561
                return -1;
562
        }
563

    
564
        if (xbee_send(&checksum, 1) != 0) {
565
                return -1;
566
        }
567

    
568
        return 0;
569
}
570

    
571
/**
572
 * Sends an AT command to read a parameter.
573
 *
574
 * @param command the AT command to send. For exmaple,
575
 * use ID to read the PAN ID and MY to return the XBee ID.
576
 * See the XBee reference guide for a complete listing.
577
 **/
578
static int xbee_send_read_at_command(char* command)
579
{
580
        return xbee_send_modify_at_command(command, NULL);
581
}
582

    
583
/**
584
 * Sends the given AT command.
585
 *
586
 * @param command the AT command to send (e.g., MY, ID)
587
 * @param value the value to pass as a parameter
588
 * (or NULL if there is no parameter)
589
 **/
590
static int xbee_send_modify_at_command(char* command, char* value)
591
{
592
        char buf[16];
593
        int i;
594

    
595
        buf[0] = XBEE_FRAME_AT_COMMAND;
596
        buf[1] = 1;
597
        buf[2] = command[0];
598
        buf[3] = command[1];
599
        int valueLen = 0;
600
        if (value != NULL)
601
        {
602
                valueLen = strlen(value);
603
                if (valueLen > 8)
604
                {
605
                        WL_DEBUG_PRINT("AT Command too large.\r\n");
606
                        return -1;
607
                }
608

    
609
                for (i = 0; i < valueLen; i++) {
610
                        buf[4 + i] = value[i];
611
                }
612
        }
613

    
614
        return xbee_send_frame(buf, 4 + valueLen);
615
}
616

    
617
/**
618
 * Send the specified packet.
619
 *
620
 * @param packet the packet data to send
621
 * @param len the number of bytes in the packet
622
 *
623
 * @param dest the ID of the XBee to send the packet to,
624
 * or XBEE_BROADCAST to send the message to all robots
625
 * in the PAN.
626
 *
627
 * @param options a combination of the flags
628
 * XBEE_OPTIONS_NONE, XBEE_OPTIONS_DISABLE_RESPONSE and
629
 * XBEE_OPTIONS_BROADCAST_ALL_PANS
630
 *
631
 * @param frame the frame number to associate this packet
632
 * with. This will be used to identify the response when
633
 * the XBee alerts us as to whether or not our message
634
 * was received.
635
 **/
636
int xbee_send_packet(char* packet, int len, int dest, char options, char frame)
637
{
638
        char buf[5];
639
        char prefix[3];
640
        int i;
641
        unsigned char checksum = 0;
642

    
643
        if (len > 100)
644
        {
645
                WL_DEBUG_PRINT("Packet is too large.\r\n");
646
                return -1;
647
        }
648

    
649
        //data for sending request
650
        buf[0] = XBEE_FRAME_TX_REQUEST_16;
651
        buf[1] = frame;
652
        buf[2] = (dest >> 8) & 0xFF;
653
        buf[3] = dest & 0xFF;
654
        buf[4] = options;
655

    
656
        //packet prefix, do this here so we don't need an extra buffer
657
        prefix[0] = XBEE_FRAME_START;
658
        prefix[1] = ((5 + len) & 0xFF00) >> 8;
659
        prefix[2] = (5 + len) & 0xFF;
660

    
661
        for (i = 0; i < 5; i++)
662
                checksum += (unsigned char)buf[i];
663
        for (i = 0; i < len; i++)
664
                checksum += (unsigned char)packet[i];
665
        checksum = 0xFF - checksum;
666

    
667
        if (xbee_send(prefix, 3) != 0) {
668
                return -1;
669
        }
670

    
671
        if (xbee_send(buf, 5) != 0) {
672
                return -1;
673
        }
674

    
675
        if (xbee_send(packet, len) != 0) {
676
                return -1;
677
        }
678

    
679
        if (xbee_send((char*)&checksum, 1) != 0) {
680
                return -1;
681
        }
682

    
683
        return 0;
684
}
685

    
686
/**
687
 * Reads a packet received from the XBee. This function
688
 * is non-blocking. The resulting packet is stored in dest.
689
 * Only returns transmission response packets and
690
 * received packets. The returned packet does not include
691
 * header information or the checksum. This method also
692
 * handles special packets dealt with by the XBee library,
693
 * and so should be called frequently while the XBee is in
694
 * use.<br><br>
695
 *
696
 * The first byte of the packet will be either
697
 * XBEE_TX_STATUS or XBEE_RX to indicated
698
 * a response to a sent message or a received message,
699
 * respectively.<br><br>
700
 *
701
 * For a status response packet:<br>
702
 * The first byte will be XBEE_TX_STATUS.<br>
703
 * The second byte will be the frame number.<br>
704
 * The third byte will be the result. 0 indicates success,
705
 * and nonzero indicates that an error ocurred in
706
 * transmitting the packet.<br><br>
707
 *
708
 * For a received packet:<br>
709
 * The first byte will be XBEE_RX.<br>
710
 * The second and third bytes will be the 16-bit
711
 * address of the packet's sender.<br>
712
 * The fourth byte is the signal strength.<br>
713
 * The fifth byte is 1 if the packet were sent to
714
 * a specific address, and 2 if it is a broadcast packet.<br><br>
715
 *
716
 * @param dest set to the packet data
717
 * @return the length of the packet, or -1 if no packet
718
 * is available
719
 **/
720
int xbee_get_packet(unsigned char* dest)
721
{
722
     int ret;
723
        //start reading a packet with XBEE_FRAME_START
724
        if (currentBufPos == 0)
725
        {
726
                do
727
                {
728
                        if (buffer_first == XBEE_BUFFER_SIZE)
729
                                buffer_first = 0;
730
                        // check if buffer is empty
731
                        if (buffer_first == buffer_last) {
732
                                return -1;
733
                        }
734
                } while (arrival_buf[buffer_first++] != XBEE_FRAME_START);
735

    
736
                if (buffer_first == XBEE_BUFFER_SIZE) {
737
                        buffer_first = 0;
738
                }
739
                xbee_buf[0] = XBEE_FRAME_START;
740
                currentBufPos++;
741
        }
742

    
743
        int len = -1;
744
        if (currentBufPos >= 3) {
745
                len = (int)xbee_buf[2] + ((int)xbee_buf[1] << 8);
746
        }
747

    
748
        while (len == -1 //packet length has not been read yet
749
                || currentBufPos < len + 4)
750
        {
751
                if (currentBufPos == 3)
752
                {
753
                        len = (int)xbee_buf[2] + ((int)xbee_buf[1] << 8);
754
                        if (len > 120)
755
                        {
756
                                WL_DEBUG_PRINT("Packet too large. Probably error in XBee transmission.\n");
757
                                currentBufPos = 0;
758
                                return -1;
759
                        }
760
                }
761

    
762
                // check if buffer is empty
763
                if (buffer_first == buffer_last) {
764
                        return -1;
765
                }
766
                xbee_buf[currentBufPos++] = arrival_buf[buffer_first++];
767
                if (buffer_first == XBEE_BUFFER_SIZE) {
768
                        buffer_first = 0;
769
                }
770
        }
771

    
772
        currentBufPos = 0;
773

    
774
        if (!xbee_verify_checksum(xbee_buf, len + 4))
775
        {
776
                WL_DEBUG_PRINT("XBee checksum failed.\r\n");
777
                return -1;
778
        }
779

    
780
        //we will take care of the packet
781
        
782
        ret = xbee_handle_packet(xbee_buf+3, len);
783
        if (ret == 1) {
784
                return 3;
785
        }
786
        
787
        if (dest == NULL) {
788
                return -1;
789
        }
790

    
791
        int i;
792
        for (i = 3; i < len + 3; i++) {
793
                dest[i - 3] = xbee_buf[i];
794
        }
795
        return len;
796
}
797

    
798
/**
799
 * Handles modem status packets.
800
 *
801
 * @param status the type of status packet received.
802
 **/
803
void xbee_handle_status(char status)
804
{
805
        switch (status)
806
        {
807
                case 0:
808
                        WL_DEBUG_PRINT("XBee hardware reset.\r\n");
809
                        break;
810
                case 1:
811
                        WL_DEBUG_PRINT("Watchdog timer reset.\r\n");
812
                        break;
813
                case 2:
814
                        WL_DEBUG_PRINT("Associated.\r\n");
815
                        break;
816
                case 3:
817
                        WL_DEBUG_PRINT("Disassociated.\r\n");
818
                        break;
819
                case 4:
820
                        WL_DEBUG_PRINT("Synchronization lost.\r\n");
821
                        break;
822
                case 5:
823
                        WL_DEBUG_PRINT("Coordinator realignment.\r\n");
824
                        break;
825
                case 6:
826
                        WL_DEBUG_PRINT("Coordinator started.\r\n");
827
                        break;
828
        }
829
}
830

    
831
/**
832
 * Handles AT command response packets.
833
 * @param command the two character AT command, e.g. MY or ID
834
 * @param result 0 for success, 1 for an error
835
 * @param extra the hex value of the requested register
836
 * @param extraLen the length in bytes of extra
837
 **/
838
static void xbee_handle_at_command_response(char* command, char result, char* extra, int extraLen)
839
{
840
        if (result == 1)
841
        {
842
                WL_DEBUG_PRINT("Error with AT");
843
                WL_DEBUG_PRINT(command);
844
                WL_DEBUG_PRINT(" packet.\r\n");
845
        }
846
        WL_DEBUG_PRINT("AT");
847
        WL_DEBUG_PRINT(command);
848
        WL_DEBUG_PRINT(" command was successful.\r\n");
849

    
850
        if (command[0] == 'I' && command[1] == 'D')
851
        {
852
                xbee_panID = xbee_pending_panID;
853
                WL_DEBUG_PRINT("PAN ID set to ");
854
                WL_DEBUG_PRINT_INT(xbee_panID);
855
                WL_DEBUG_PRINT(".\r\n");
856
                return;
857
        }
858

    
859
        if (command[0] == 'C' && command[1] == 'H')
860
        {
861
                xbee_channel = xbee_pending_channel;
862
                WL_DEBUG_PRINT("Channel set to ");
863
                WL_DEBUG_PRINT_INT(xbee_channel);
864
                WL_DEBUG_PRINT(".\r\n");
865
                return;
866
        }
867

    
868
        if (command[0] == 'M' && command[1] == 'Y' && extraLen != 0)
869
        {
870
                xbee_address = 0;
871
                int i;
872
                for (i = 0; i < extraLen; i++) {
873
                        xbee_address = (xbee_address << 8) + extra[i];
874
                }
875

    
876
                WL_DEBUG_PRINT("XBee address is ");
877
                WL_DEBUG_PRINT_INT(xbee_address);
878
                WL_DEBUG_PRINT(".\r\n");
879

    
880
                if (xbee_address == 0)
881
                {
882
                        WL_DEBUG_PRINT("XBee 16-bit address must be set using ATMY.\r\n");
883
                        #ifndef ROBOT
884
                        exit(0);
885
                        #endif
886
                }
887
        }
888
}
889

    
890
/**
891
 * Attempts to handle the packet if it is dealt with
892
 * by the library.
893
 * We will handle the following packet types:
894
 *    Modem Status
895
 *    AT Command Response
896
 *
897
 * @param packet the packet to handle
898
 * @param len the length of the packet
899
 *
900
 * @return 1 if we have handled the packet, 0 otherwise
901
 */
902
static int xbee_handle_packet(char* packet, int len)
903
{
904

    
905
        char command[3] = {1, 2, 3};
906
        if (len <= 0) //this should not happend
907
        {
908
                WL_DEBUG_PRINT("Non-positive packet length.\r\n");
909
                return 0;
910
        }
911

    
912
        switch ((unsigned char)packet[0]) //packet type
913
        {
914
                case XBEE_FRAME_STATUS:
915
                        xbee_handle_status(packet[1]);
916
                        return 1;
917
                case XBEE_FRAME_AT_COMMAND_RESPONSE:
918
                        command[0] = packet[2];
919
                        command[1] = packet[3];
920
                        command[2] = 0;
921
                        xbee_handle_at_command_response(command, packet[4], packet + 5, len - 5);
922
                        return 1;
923
        }
924
        return 0;
925
}
926

    
927
/**
928
 * Sets the personal area network id.
929
 *
930
 * @param id the new personal area network (PAN) id
931
 **/
932
int xbee_set_pan_id(int id)
933
{
934
        char s[3];
935
        s[0] = (id >> 8) & 0xFF;
936
        s[1] = id & 0xFF;
937
        s[2] = 0;
938
        xbee_pending_panID = id;
939
        return xbee_send_modify_at_command("ID", s);
940
}
941

    
942
/**
943
 * Get the PAN ID for the XBee.
944
 *
945
 * @return the personal area network id, or
946
 * XBEE_PAN_DEFAULT if it has not yet been set.
947
 **/
948
unsigned int xbee_get_pan_id()
949
{
950
        return xbee_panID;
951
}
952

    
953
/**
954
 * Set the channel the XBee is using.
955
 *
956
 * @param channel the channel the XBee will not use,
957
 * between 0x0B and 0x1A
958
 *
959
 * @see xbee_get_channel
960
 **/
961
int xbee_set_channel(int channel)
962
{
963
        if (channel < 0x0B || channel > 0x1A)
964
        {
965
                WL_DEBUG_PRINT("Channel out of range.\r\n");
966
                return -1;
967
        }
968

    
969
        char s[3];
970
        s[0] = channel & 0xFF;
971
        s[1] = 0;
972
        xbee_pending_channel = channel;
973

    
974
        return xbee_send_modify_at_command("CH", s);
975
}
976

    
977
/**
978
 * Returns the channel which the XBee is currently using.
979
 *
980
 * @return the channel the XBee is using
981
 *
982
 * @see xbee_set_channel
983
 **/
984
int xbee_get_channel(void)
985
{
986
        return xbee_channel;
987
}
988

    
989
/**
990
 * Get the 16-bit address of the XBee.
991
 * This is used to specify who to send messages to
992
 * and who messages are from.
993
 *
994
 * @return the 16-bit address of the XBee.
995
 **/
996
unsigned int xbee_get_address()
997
{
998
        return xbee_address;
999
}
1000

    
1001
#ifndef ROBOT
1002
void xbee_set_com_port(char* port)
1003
{
1004
        xbee_com_port = port;
1005
}
1006
#endif