Project

General

Profile

Statistics
| Revision:

root / branches / wireless / code / projects / libwireless / xbee.c @ 1576

History | View | Annotate | Download (25.7 KB)

1
/**
2
 * Copyright (c) 2009 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 Colony Project, CMU Robotics Club
33
 **/
34

    
35
#include "xbee.h"
36
#include "wl_defs.h"
37
#include <time.h>
38

    
39
// TODO: separate robot and computer code into two xbee.c files
40

    
41
#ifndef ROBOT
42

    
43
#include <fcntl.h>
44
#include <unistd.h>
45
#include <pthread.h>
46
#include <errno.h>
47
#include <termios.h>
48

    
49
#else
50

    
51
#include <serial.h> // TODO: integrate serial xbee functions into this file
52
#include <avr/interrupt.h>
53

    
54
#endif
55

    
56
// TODO: do we really need stdio and stdlib in the robot code?
57
#include <stdio.h>
58
#include <stdlib.h>
59
#include <string.h>
60

    
61
/**
62
 * The port to use the XBee from on the computer.
63
 * Also, a backup port if the other is used.
64
 **/
65
#ifndef ROBOT
66
#define XBEE_PORT_DEFAULT "/dev/ttyUSB1"
67
#endif
68

    
69
/* start definitions of xbee constants */
70

    
71
/**@brief Unset PAN, uses XBee default **/
72
#define XBEE_PAN_DEFAULT 0xFFFF
73
/**@brief Unset channel, uses XBee default **/
74
#define XBEE_CHANNEL_DEFAULT 0
75
/**@brief Broadcast to all robots in the PAN **/
76
#define XBEE_BROADCAST 0xFFFF
77
/**@brief No special options **/
78
#define XBEE_OPTIONS_NONE 0x00
79
/**@brief Do not receive a TX_STATUS message from this packet **/
80
#define XBEE_OPTIONS_DISABLE_RESPONSE 0x01
81
/**@brief Send the packet to all PANS **/
82
#define XBEE_OPTIONS_BROADCAST_ALL_PANS 0x04
83
/**@brief A transmit status packet **/
84
#define XBEE_TX_STATUS 0x89
85
/**@brief A packet received from another XBee **/
86
#define XBEE_RX 0x81
87

    
88
// TODO: add comments for all of these definitions
89
#define XBEE_FRAME_START 0x7E
90
#define XBEE_GET_PACKET_TIMEOUT 1000
91

    
92
/*Frame Types*/
93
#define XBEE_FRAME_STATUS 0x8A
94
#define XBEE_FRAME_AT_COMMAND 0x08
95
#define XBEE_FRAME_AT_COMMAND_RESPONSE 0x88
96
#define XBEE_FRAME_TX_REQUEST_64 0x00
97
#define XBEE_FRAME_TX_REQUEST_16 0x01
98
#define XBEE_FRAME_TX_STATUS XBEE_TX_STATUS
99
#define XBEE_FRAME_RX_64 0x80
100
#define XBEE_FRAME_RX_16 XBEE_RX
101

    
102
/*Internal Function Prototypes*/
103

    
104
// TODO: convert all int references to int16_t syntax (see stdint.h)
105

    
106
/*I/O Functions*/
107
static int xbee_send(char* buf, int size);
108
static int xbee_send_string(char* c);
109

    
110
#ifndef ROBOT
111
static int xbee_read(char* buf, int size);
112
#endif
113

    
114
/*Command Mode Functions
115
 * Called during initialization.
116
 */
117
static int xbee_enter_command_mode(void);
118
static int xbee_exit_command_mode(void);
119
static int xbee_enter_api_mode(void);
120
static int xbee_exit_api_mode(void);
121
static int xbee_wait_for_string(char* s, int len);
122
static int xbee_wait_for_ok(void);
123

    
124
/*API Mode Functions*/
125

    
126
static int xbee_handle_packet(char* packet, int len);
127
static int xbee_handle_at_command_response(char* command, char result, char* extra, int extraLen);
128
static void xbee_handle_status(char status);
129
static int xbee_verify_checksum(char* packet, int len);
130
static char xbee_compute_checksum(char* packet, int len);
131
static int xbee_send_frame(char* buf, int len);
132
int xbee_send_read_at_command(char* command);
133
static int xbee_send_modify_at_command(char* command, char* value);
134

    
135
/*Global Variables*/
136

    
137
#ifndef ROBOT
138
static char* xbee_com_port = XBEE_PORT_DEFAULT;
139
static int xbee_stream;
140
static pthread_t* xbee_listen_thread;
141
#endif
142

    
143
// TODO: clarify buffers, what they're used for, etc
144

    
145
// TODO: is this a good size?
146
#define XBEE_BUFFER_SIZE        128
147
#define PACKET_BUFFER_SIZE        108
148
// a buffer for data received from the XBee
149
char arrival_buf[XBEE_BUFFER_SIZE];
150
// location of last unread byte in buffer
151
volatile int buffer_last = 0;
152
// first unread byte in buffer
153
volatile int buffer_first = 0;
154

    
155

    
156
//used to store packets as they are read
157
static char xbee_buf[PACKET_BUFFER_SIZE];
158
static int currentBufPos = 0;
159

    
160
//XBee status
161
static unsigned int xbee_panID = XBEE_PAN_DEFAULT;
162
static unsigned int xbee_pending_panID = XBEE_PAN_DEFAULT;
163
static int xbee_channel = XBEE_CHANNEL_DEFAULT;
164
static int xbee_pending_channel = XBEE_CHANNEL_DEFAULT;
165
static volatile unsigned int xbee_address = 0;
166

    
167

    
168
/*Function Implementations*/
169

    
170
#ifdef ROBOT
171

    
172
/**
173
 * Interrupt for the robot. Adds bytes received from the xbee
174
 * to the buffer.
175
 **/
176
#ifndef FIREFLY
177
ISR(USART1_RX_vect)
178
{
179
        char c = UDR1;
180
        arrival_buf[buffer_last] = c;
181
        int t = buffer_last + 1;
182
        if (t == XBEE_BUFFER_SIZE)
183
                t = 0;
184
        if (t == buffer_first)
185
        {
186
                WL_DEBUG_PRINT("\nOut of space in buffer.\n");
187
        }
188
        buffer_last = t;
189
}
190
#else
191
SIGNAL(SIG_USART0_RECV)
192
{
193
        char c = UDR0;
194
        arrival_buf[buffer_last] = c;
195
        int t = buffer_last + 1;
196
        if (t == XBEE_BUFFER_SIZE)
197
                t = 0;
198
        if (t == buffer_first)
199
        {
200
                WL_DEBUG_PRINT("Out of space in buffer.\n");
201
        }
202
        buffer_last = t;
203
}
204
#endif
205

    
206
#else
207

    
208
// Computer code
209

    
210
/**
211
 * Thread that listens to the xbee.
212
 **/
213
static void* listen_to_xbee(void* x)
214
{
215
        char c;
216
        while (1)
217
        {
218
                if (xbee_read(&c, 1) != 0) {
219
                        WL_DEBUG_PRINT("xbee_read failed.\n");
220
                        return NULL;
221
                }
222

    
223
                arrival_buf[buffer_last] = c;
224
                int t = buffer_last + 1;
225
                if (t == XBEE_BUFFER_SIZE)
226
                        t = 0;
227
                if (t == buffer_first)
228
                {
229
                        WL_DEBUG_PRINT("Out of space in buffer.\n");
230
                }
231
                buffer_last = t;
232

    
233
                usleep(1000);
234
        }
235

    
236
        return NULL;
237
}
238

    
239
#endif
240

    
241
/**
242
 * Initializes the XBee library so that other functions may be used.
243
 **/
244
int xbee_lib_init()
245
{
246
  if (xbee_init() != 0) {
247
    usb_puts("xbee_init error");
248
    return -1;
249
  }
250

    
251
        WL_DEBUG_PRINT("in xbee_init\n");
252
#ifdef ROBOT
253

    
254
        //enable the receiving interrupt
255
#ifdef FIREFLY
256
        UCSR0B |= _BV(RXCIE) | _BV(RXEN);
257
#else
258
#ifdef BAYBOARD
259
        UCSR1B |= _BV(RXCIE1);
260
#else
261
        UCSR1B |= _BV(RXCIE);
262
#endif
263
#endif
264
        sei();
265
#else
266
        xbee_stream = open(xbee_com_port, O_RDWR);
267
        if (xbee_stream == -1/* || lockf(xbee_stream, F_TEST, 0) != 0*/)
268
        {
269
                WL_DEBUG_PRINT("Failed to open connection to XBee on port ");
270
                WL_DEBUG_PRINT_INT(xbee_com_port);
271
                WL_DEBUG_PRINT(".\n");
272
                return -1;
273
        } else {
274
          WL_DEBUG_PRINT("Successfully opened connection to XBee on port ");
275
                WL_DEBUG_PRINT_INT(xbee_com_port);
276
                WL_DEBUG_PRINT(".\n");
277
        }
278

    
279
        // set baud rate, etc. correctly
280
        struct termios options;
281

    
282
        tcgetattr(xbee_stream, &options);
283
        cfsetispeed(&options, B9600);
284
        cfsetospeed(&options, B9600);
285
        options.c_iflag &= ~ICRNL;
286
        options.c_oflag &= ~OCRNL;
287
        options.c_cflag |= (CLOCAL | CREAD);
288
        options.c_cflag &= ~PARENB;
289
        options.c_cflag &= ~CSTOPB;
290
        options.c_cflag &= ~CSIZE;
291
        options.c_cflag |= CS8;
292
        options.c_lflag &= ~ICANON;
293
        options.c_cc[VMIN] = 1;
294
        options.c_cc[VTIME] = 50;
295

    
296
        if (tcsetattr(xbee_stream, TCSANOW, &options))
297
        {
298
                WL_DEBUG_PRINT("Error setting attributes.\n");
299
                return -1;
300
        }
301

    
302
        xbee_listen_thread = (pthread_t*)malloc(sizeof(pthread_t));
303
        if (xbee_listen_thread == NULL)
304
        {
305
                WL_DEBUG_PRINT("Malloc failed.\n");
306
                return -1;
307
        }
308

    
309
        int ret = pthread_create(xbee_listen_thread, NULL, listen_to_xbee, NULL);
310
        if (ret)
311
        {
312
                WL_DEBUG_PRINT("Failed to create listener thread.\n");
313
                return -1;
314
        }
315
#endif
316

    
317
        WL_DEBUG_PRINT("Entering command mode.\r\n");
318

    
319
        if (xbee_enter_command_mode() != 0) {
320
    usb_puts("error entering command mode\r\n");
321
                return -1;
322
        }
323

    
324
        WL_DEBUG_PRINT("Entered command mode.\r\n");
325

    
326
  // reset baud rate
327
  WL_DEBUG_PRINT("Resetting Baud to ");
328
  WL_DEBUG_PRINT(XBEE_BAUD_STR);
329
  WL_DEBUG_PRINT("\r\n");
330
  
331
  // set baud on xbee
332
//#if (XBEE_BAUD == 250000)
333
#if (XBEE_BAUD == 115200)
334
  xbee_send_string("ATBD7\r\n");
335
#elif (XBEE_BAUD == 57600)
336
  xbee_send_string("ATBD6\r\n");
337
#elif (XBEE_BAUD == 38400)
338
  xbee_send_string("ATBD5\r\n");
339
#elif (XBEE_BAUD == 19200)
340
  xbee_send_string("ATBD4\r\n");
341
#elif (XBEE_BAUD == 9600)
342
  // already at this baud rate
343
  //xbee_send_string("ATBD3\r\n");
344
#else
345
  WL_DEBUG_PRINT("undefined baud rate\r\n");
346
#endif  
347
  // exit command mode
348
  xbee_wait_for_ok();
349
  WL_DEBUG_PRINT("got ok from baud reset\r\n");
350
  xbee_send_string("ATCN\r\n");
351
  xbee_wait_for_ok();
352
  WL_DEBUG_PRINT("got ok from exiting command mode\r\n");
353
  
354
  // set UART baud
355
#if (XBEE_BAUD == 250000)
356
  UBRR1H = 0x00;
357
  UBRR1L = 3;
358
  UCSR1A |= _BV(U2X1);
359
#elif (XBEE_BAUD == 115200)
360
  UBRR1H = 0x00;
361
  UBRR1L = 8;
362
  UCSR1A |= _BV(U2X1);
363
#elif (XBEE_BAUD == 57600)
364
  UBRR1H = 0x00;
365
  UBRR1L = 16;
366
  UCSR1A |= _BV(U2X1);
367
#elif (XBEE_BAUD == 38400)
368
  UBRR1H = 0x00;
369
  UBRR1L = 25;
370
  UCSR1A |= _BV(U2X1);
371
#elif (XBEE_BAUD == 19200)
372
  UBRR1H = 0x00;
373
  UBRR1L = 51;
374
  UCSR1A |= _BV(U2X1);
375
#elif (XBEE_BAUD == 9600)
376
  /* this is the default baud rate, so do nothing
377
  UBRR1H = 0x00;
378
  UBRR1L = 103;
379
  UCSR1A |= _BV(U2X1);*/
380
#else //Baud rate is defined in the header file, we should not get here
381
  return 0;
382
#endif
383
  delay_ms(50);
384

    
385
  // enter command mode
386
  WL_DEBUG_PRINT("entering command mode 2\r\n");
387
  xbee_send_string("+++");
388
  xbee_wait_for_ok();
389
  WL_DEBUG_PRINT("entered command mode 2\r\n");
390
  
391
  if (xbee_enter_api_mode() != 0) {
392
    WL_DEBUG_PRINT("can't enter api mode\r\n");
393
                return -1;
394
        }
395

    
396
        WL_DEBUG_PRINT("Entered api mode.\r\n");
397

    
398
        if (xbee_exit_command_mode() != 0) {
399
    WL_DEBUG_PRINT("can't exit command mode\r\n");
400
          return -1;
401
        }
402
        
403
        WL_DEBUG_PRINT("Left command mode.\r\n");
404
  
405
  // get MY address
406
        if (xbee_send_read_at_command("BD")) {
407
    WL_DEBUG_PRINT("can't send BD command\r\n");
408
                return -1;
409
        }
410
        WL_DEBUG_PRINT("Getting ATBD rate.\n");
411
  
412
  // get MY address
413
        if (xbee_send_read_at_command("MY")) {
414
    WL_DEBUG_PRINT("can't send my command\r\n");
415
                return -1;
416
        }
417
        WL_DEBUG_PRINT("Getting ATMY address.\n");
418

    
419
#ifndef ROBOT
420
        int i;
421
        for (i = 0; xbee_address == 0 && i < XBEE_GET_PACKET_TIMEOUT; i++) {
422
          ret = xbee_get_packet(NULL);
423

    
424
          usleep(1000);
425
          
426
/*           if (ret == -1) { */
427
/*             WL_DEBUG_PRINT("xbee_get_packet(NULL) failed.\n"); */
428
/*             return -1; */
429
/*           } */
430
        }
431
#else
432
        //wait to return until the address is set
433
  //TODO: this shouldn't wait indefinitely.  There should be some sort of reasonable timeout
434
  // so if the address is never set right, an error can be returned instead of having the
435
  // robot hang forever
436
        while (xbee_address == 0) {
437
          xbee_get_packet(NULL);
438
        }
439
#endif
440
        WL_DEBUG_PRINT("Got ATMY address.\n");
441

    
442
#ifndef ROBOT
443
        if (i == XBEE_GET_PACKET_TIMEOUT) { // We timed-out.
444

    
445
          WL_DEBUG_PRINT("xbee_get_packet timed out.\n");
446
          return -1;
447
        } else {
448
          return 0;
449
        }
450
#else
451
        return 0;
452
#endif
453
}
454

    
455
/**
456
 * Call when finished using the XBee library. This releases
457
 * all sued resources.
458
 **/
459
void xbee_terminate()
460
{
461
        #ifndef ROBOT
462
        pthread_cancel(*xbee_listen_thread);
463
    pthread_join(*xbee_listen_thread, NULL);
464
        free(xbee_listen_thread);
465
        lockf(xbee_stream, F_ULOCK, 0);
466
        close(xbee_stream);
467
  #else
468
  xbee_exit_api_mode();
469
        #endif
470
}
471

    
472
/**
473
 * Send a buffer buf of size bytes to the XBee.
474
 *
475
 * @param buf the buffer of data to send
476
 * @param size the number of bytes to send
477
 **/
478
static int xbee_send(char* buf, int size)
479
{
480
#ifdef ROBOT
481
        int i;
482
        for (i = 0; i < size; i++) {
483
                xbee_putc(buf[i]);
484
        }
485

    
486
        return 0;
487

    
488
#else
489

    
490
        int ret = write(xbee_stream, buf, size);
491
        //success
492
        if (ret == size)
493
                return 0;
494
        if (ret == -1)
495
        {
496
                //interrupted by system signal, probably timer interrupt.
497
                //just try again
498
                if (errno == 4)
499
                {
500
                        return xbee_send(buf, size);
501
                }
502
                WL_DEBUG_PRINT("Failed to write to xbee\r\n");
503
                return -1;
504
        }
505

    
506
        //write was interrupted after writing ret bytes
507
        return xbee_send(buf + ret, size - ret);
508
#endif
509
}
510

    
511
/**
512
 * Sends a string to the XBee.
513
 *
514
 * @param c the string to send to the XBEE
515
 **/
516
static int xbee_send_string(char* c)
517
{
518
        return xbee_send(c, strlen(c));
519
}
520

    
521
#ifndef ROBOT
522
static int xbee_read(char* buf, int size)
523
{
524
        if (read(xbee_stream, buf, size) == -1) {
525
                WL_DEBUG_PRINT("Failed to read from xbee.\r\n");
526
                return -1;
527
        }
528

    
529
        return 0;
530
}
531
#endif
532

    
533
/**
534
 * Enter into command mode.
535
 **/
536
static int xbee_enter_command_mode()
537
{
538
        if (xbee_send_string("+++") != 0) {
539
                return -1;
540
        }
541

    
542
        if (xbee_wait_for_ok() != 0) {
543
          return -1;
544
        }
545
          return 0;
546
}
547

    
548
/**
549
 * Exit from command mode.
550
 **/
551
static int xbee_exit_command_mode()
552
{
553
        if (xbee_send_string("ATCN\r") != 0) {
554
                return -1;
555
        }
556

    
557
        xbee_wait_for_ok();
558

    
559
        return 0;
560
}
561

    
562
/**
563
 * Enter API mode.
564
 **/
565
static int xbee_enter_api_mode()
566
{
567
        if (xbee_send_string("ATAP 1\r") != 0) {
568
                return -1;
569
        }
570
        xbee_wait_for_ok();
571

    
572
        return 0;
573
}
574

    
575
/**
576
 * Exit API mode.
577
 **/
578
static int xbee_exit_api_mode()
579
{
580
        if (xbee_send_modify_at_command("AP","0") != 0) {
581
                return -1;
582
        }
583

    
584
        return 0;
585
}
586

    
587
/**
588
 * Wait until the string "OK\r" is received from the XBee.
589
 **/
590
static int xbee_wait_for_ok()
591
{
592
        return xbee_wait_for_string("OK\r", 3);
593
}
594

    
595
/**
596
 * Delay until the specified string is received from
597
 * the XBee. Discards all other XBee data.
598
 *
599
 * ********* Robot often hangs here ****************
600
 *
601
 * @param s the string to receive
602
 * @param len the length of the string
603
 **/
604
static int xbee_wait_for_string(char* s, int len)
605
{
606
        char* curr = s;
607
  unsigned int i=0;
608
        while (curr - s < len) {
609
    WL_DEBUG_PRINT("waiting for string\r\n");
610
                // check if buffer is empty
611
                if (buffer_last != buffer_first) {
612
                        char c = arrival_buf[buffer_first++];
613
                        if (buffer_first == XBEE_BUFFER_SIZE) {
614
                                buffer_first = 0;
615
                        }
616
      WL_DEBUG_PRINT("buffer char|");
617
      WL_DEBUG_PRINT_CHAR(c);
618
      WL_DEBUG_PRINT("|\r\n");
619

    
620
                        if (c == *curr) {
621
                                curr++;
622
                        } else {
623
#ifndef ROBOT
624
                          //return -1; // Computer is less forgiving.
625
                          curr = s;
626
#else
627
                          curr = s;
628
#endif
629
                        }
630
                } // else buffer is empty.
631

    
632
#ifndef ROBOT
633
                usleep(100);
634
#endif
635
        }
636
  if (i >= 10000)
637
    return -1;
638

    
639
        return 0;
640
}
641

    
642
/**
643
 * Verifies that the packets checksum is correct.
644
 * (If the checksum is correct, the sum of the bytes
645
 * is 0xFF.)
646
 *
647
 * @param packet the packet received. This includes the first
648
 * three bytes, which are header information from the XBee.
649
 *
650
 * @param len The length of the packet received from the XBee
651
 *
652
 * @return 0 if the checksum is incorrect, nonzero
653
 * otherwise
654
 **/
655
int xbee_verify_checksum(char* packet, int len)
656
{
657
        unsigned char sum = 0;
658
        int i;
659
        for (i = 3; i < len; i++)
660
                sum += (unsigned char)packet[i];
661
        return sum == 0xFF;
662
}
663

    
664
/**
665
 * Returns the checksum of the given packet.
666
 *
667
 * @param buf the data for the packet to send
668
 * @param len the length of the packet in bytes
669
 *
670
 * @return the checksum of the packet, which will
671
 * become the last byte sent in the packet
672
 **/
673
char xbee_compute_checksum(char* buf, int len)
674
{
675
        int i;
676
        unsigned char sum = 0;
677
        for (i = 0; i < len; i++)
678
                sum += (unsigned char)buf[i];
679
        return 0xFF - sum;
680
}
681

    
682
/**
683
 * Adds header information and checksum to the given
684
 * packet and sends it. Header information includes
685
 * XBEE_FRAME_START and the packet length, as two bytes.
686
 *
687
 * @param buf the packet data
688
 * @param len the size in bytes of the packet data
689
 *
690
 **/
691
static int xbee_send_frame(char* buf, int len)
692
{
693
        char prefix[3];
694
        prefix[0] = XBEE_FRAME_START;
695
        prefix[1] = (len & 0xFF00) >> 8;
696
        prefix[2] = len & 0xFF;
697
        char checksum = xbee_compute_checksum(buf, len);
698

    
699
        if (xbee_send(prefix, 3) != 0) {
700
                return -1;
701
        }
702

    
703
        if (xbee_send(buf, len) != 0) {
704
                return -1;
705
        }
706

    
707
        if (xbee_send(&checksum, 1) != 0) {
708
                return -1;
709
        }
710

    
711
        return 0;
712
}
713

    
714
/**
715
 * Sends an AT command to read a parameter.
716
 *
717
 * @param command the AT command to send. For exmaple,
718
 * use ID to read the PAN ID and MY to return the XBee ID.
719
 * See the XBee reference guide for a complete listing.
720
 **/
721
int xbee_send_read_at_command(char* command)
722
{
723
        return xbee_send_modify_at_command(command, NULL);
724
}
725

    
726
/**
727
 * Sends the given AT command.
728
 *
729
 * @param command the AT command to send (e.g., MY, ID)
730
 * @param value the value to pass as a parameter
731
 * (or NULL if there is no parameter)
732
 **/
733
static int xbee_send_modify_at_command(char* command, char* value)
734
{
735
        char buf[16];
736
        int i;
737

    
738
        buf[0] = XBEE_FRAME_AT_COMMAND;
739
        buf[1] = 1;
740
        buf[2] = command[0];
741
        buf[3] = command[1];
742
        int valueLen = 0;
743
        if (value != NULL)
744
        {
745
                valueLen = strlen(value);
746
                if (valueLen > 8)
747
                {
748
                        WL_DEBUG_PRINT("AT Command too large.\r\n");
749
                        return -1;
750
                }
751

    
752
                for (i = 0; i < valueLen; i++) {
753
                        buf[4 + i] = value[i];
754
                }
755
        }
756

    
757
        return xbee_send_frame(buf, 4 + valueLen);
758
}
759

    
760
/**
761
 * Send the specified packet.
762
 *
763
 * @param packet the packet data to send
764
 * @param len the number of bytes in the packet
765
 *
766
 * @param dest the ID of the XBee to send the packet to,
767
 * or XBEE_BROADCAST to send the message to all robots
768
 * in the PAN.
769
 *
770
 * @param options a combination of the flags
771
 * XBEE_OPTIONS_NONE, XBEE_OPTIONS_DISABLE_RESPONSE and
772
 * XBEE_OPTIONS_BROADCAST_ALL_PANS
773
 *
774
 * @param frame the frame number to associate this packet
775
 * with. This will be used to identify the response when
776
 * the XBee alerts us as to whether or not our message
777
 * was received.
778
 **/
779
int xbee_send_packet(char* packet, int len, int dest, char options, char frame)
780
{
781
        char buf[5];
782
        char prefix[3];
783
        int i;
784
        unsigned char checksum = 0;
785

    
786
        if (len > 100)
787
        {
788
                WL_DEBUG_PRINT("Packet is too large.\r\n");
789
                return -1;
790
        }
791

    
792
        //data for sending request
793
        buf[0] = XBEE_FRAME_TX_REQUEST_16;
794
        buf[1] = frame;
795
        buf[2] = (dest >> 8) & 0xFF;
796
        buf[3] = dest & 0xFF;
797
        buf[4] = options;
798

    
799
        //packet prefix, do this here so we don't need an extra buffer
800
        prefix[0] = XBEE_FRAME_START;
801
        prefix[1] = ((5 + len) & 0xFF00) >> 8;
802
        prefix[2] = (5 + len) & 0xFF;
803

    
804
        for (i = 0; i < 5; i++)
805
                checksum += (unsigned char)buf[i];
806
        for (i = 0; i < len; i++)
807
                checksum += (unsigned char)packet[i];
808
        checksum = 0xFF - checksum;
809

    
810
        if (xbee_send(prefix, 3) != 0) {
811
                return -1;
812
        }
813

    
814
        if (xbee_send(buf, 5) != 0) {
815
                return -1;
816
        }
817

    
818
        if (xbee_send(packet, len) != 0) {
819
                return -1;
820
        }
821

    
822
        if (xbee_send((char*)&checksum, 1) != 0) {
823
                return -1;
824
        }
825

    
826
        return 0;
827
}
828

    
829
/**
830
 * Reads a packet received from the XBee. This function
831
 * is non-blocking. The resulting packet is stored in dest.
832
 * Only returns transmission response packets and
833
 * received packets. The returned packet does not include
834
 * header information or the checksum. This method also
835
 * handles special packets dealt with by the XBee library,
836
 * and so should be called frequently while the XBee is in
837
 * use.<br><br>
838
 *
839
 * The first byte of the packet will be either
840
 * XBEE_TX_STATUS or XBEE_RX to indicated
841
 * a response to a sent message or a received message,
842
 * respectively.<br><br>
843
 *
844
 * For a status response packet:<br>
845
 * The first byte will be XBEE_TX_STATUS.<br>
846
 * The second byte will be the frame number.<br>
847
 * The third byte will be the result. 0 indicates success,
848
 * and nonzero indicates that an error ocurred in
849
 * transmitting the packet.<br><br>
850
 *
851
 * For a received packet:<br>
852
 * The first byte will be XBEE_RX.<br>
853
 * The second and third bytes will be the 16-bit
854
 * address of the packet's sender.<br>
855
 * The fourth byte is the signal strength.<br>
856
 * The fifth byte is 1 if the packet were sent to
857
 * a specific address, and 2 if it is a broadcast packet.<br><br>
858
 *
859
 * @param dest set to the packet data
860
 * @return the length of the packet, or -1 if no packet
861
 * is available
862
 **/
863
int xbee_get_packet(unsigned char* dest)
864
{
865
     int ret;
866
        //start reading a packet with XBEE_FRAME_START
867
        if (currentBufPos == 0)
868
        {
869
                do
870
                {
871
                        if (buffer_first == XBEE_BUFFER_SIZE)
872
                                buffer_first = 0;
873
                        // check if buffer is empty
874
                        if (buffer_first == buffer_last) {
875
        WL_DEBUG_PRINT("buffer empty\r\n");
876
                                return -1;
877
                        }
878
                } while (arrival_buf[buffer_first++] != XBEE_FRAME_START);
879

    
880
                if (buffer_first == XBEE_BUFFER_SIZE) {
881
                        buffer_first = 0;
882
                }
883
                xbee_buf[0] = XBEE_FRAME_START;
884
                currentBufPos++;
885
        }
886

    
887
        int len = -1;
888
        if (currentBufPos >= 3) {
889
                len = (int)xbee_buf[2] + ((int)xbee_buf[1] << 8);
890
        }
891

    
892
        while (len == -1 //packet length has not been read yet
893
                || currentBufPos < len + 4)
894
        {
895
                if (currentBufPos == 3)
896
                {
897
                        len = (int)xbee_buf[2] + ((int)xbee_buf[1] << 8);
898
                        if (len > 120)
899
                        {
900
                                WL_DEBUG_PRINT("Packet too large. Probably error in XBee transmission.\r\n");
901
                                currentBufPos = 0;
902
                                return -1;
903
                        }
904
                }
905

    
906
                // check if buffer is empty
907
                if (buffer_first == buffer_last) {
908
      WL_DEBUG_PRINT("Buffer empty 2\r\n");
909
                        return -1;
910
                }
911
                xbee_buf[currentBufPos++] = arrival_buf[buffer_first++];
912
                if (buffer_first == XBEE_BUFFER_SIZE) {
913
                        buffer_first = 0;
914
                }
915
        }
916

    
917
        currentBufPos = 0;
918

    
919
        if (!xbee_verify_checksum(xbee_buf, len + 4))
920
        {
921
                WL_DEBUG_PRINT("XBee checksum failed.\r\n");
922
                return -1;
923
        }
924

    
925
        //we will take care of the packet
926
        
927
        ret = xbee_handle_packet(xbee_buf+3, len);
928
        if (ret == 1) {
929
                return 3;
930
        } else if (ret == -1) {
931
    WL_DEBUG_PRINT("xbee_handle_packet returned -1\r\n");
932
    return -2;
933
  }
934
        
935
        if (dest == NULL) {
936
    WL_DEBUG_PRINT("dest buffer is null\r\n");
937
                return -1;
938
        }
939

    
940
        int i;
941
        for (i = 3; i < len + 3; i++) {
942
                dest[i - 3] = xbee_buf[i];
943
        }
944
        return len;
945
}
946

    
947
/**
948
 * Handles modem status packets.
949
 *
950
 * @param status the type of status packet received.
951
 **/
952
void xbee_handle_status(char status)
953
{
954
        switch (status)
955
        {
956
                case 0:
957
                        WL_DEBUG_PRINT("XBee hardware reset.\r\n");
958
                        break;
959
                case 1:
960
                        WL_DEBUG_PRINT("Watchdog timer reset.\r\n");
961
                        break;
962
                case 2:
963
                        WL_DEBUG_PRINT("Associated.\r\n");
964
                        break;
965
                case 3:
966
                        WL_DEBUG_PRINT("Disassociated.\r\n");
967
                        break;
968
                case 4:
969
                        WL_DEBUG_PRINT("Synchronization lost.\r\n");
970
                        break;
971
                case 5:
972
                        WL_DEBUG_PRINT("Coordinator realignment.\r\n");
973
                        break;
974
                case 6:
975
                        WL_DEBUG_PRINT("Coordinator started.\r\n");
976
                        break;
977
        }
978
}
979

    
980
/**
981
 * Handles AT command response packets.
982
 * @param command the two character AT command, e.g. MY or ID
983
 * @param result 0 for success, 1 for an error
984
 * @param extra the hex value of the requested register
985
 * @param extraLen the length in bytes of extra
986
 **/
987
static int xbee_handle_at_command_response(char* command, char result, char* extra, int extraLen)
988
{
989
        if (result == 1)
990
        {
991
                WL_DEBUG_PRINT("Error with AT");
992
                WL_DEBUG_PRINT(command);
993
                WL_DEBUG_PRINT(" packet. Result = ");
994
    switch(result) {
995
    case 1:
996
      WL_DEBUG_PRINT("ERROR\r\n");
997
      break;
998
    case 2:
999
      WL_DEBUG_PRINT("Invalid Command\r\n");
1000
      break;
1001
    case 3:
1002
      WL_DEBUG_PRINT("Invalid Parameter\r\n");
1003
      break;
1004
    }
1005
    return -1;
1006
        }
1007
        WL_DEBUG_PRINT("AT");
1008
        WL_DEBUG_PRINT(command);
1009
        WL_DEBUG_PRINT(" command was successful.\r\n");
1010

    
1011
        if (command[0] == 'I' && command[1] == 'D')
1012
        {
1013
                xbee_panID = xbee_pending_panID;
1014
                WL_DEBUG_PRINT("PAN ID set to ");
1015
                WL_DEBUG_PRINT_INT(xbee_panID);
1016
                WL_DEBUG_PRINT(".\r\n");
1017
                return 0;
1018
        }
1019

    
1020
        if (command[0] == 'C' && command[1] == 'H')
1021
        {
1022
                xbee_channel = xbee_pending_channel;
1023
                WL_DEBUG_PRINT("Channel set to ");
1024
                WL_DEBUG_PRINT_INT(xbee_channel);
1025
                WL_DEBUG_PRINT(".\r\n");
1026
                return 0;
1027
        }
1028
  
1029
  if (command[0] == 'N' && command[1] == 'D')
1030
        {
1031
                WL_DEBUG_PRINT("ND - extra=");
1032
    WL_DEBUG_PRINT(extra);
1033
                WL_DEBUG_PRINT("\r\n");
1034
                return 0;
1035
        }
1036
  
1037
   if (command[0] == 'B' && command[1] == 'D')
1038
        {
1039
                WL_DEBUG_PRINT("BD - extra=");
1040
    WL_DEBUG_PRINT(extra);
1041
                WL_DEBUG_PRINT("\r\n");
1042
                return 0;
1043
        }
1044

    
1045
        if (command[0] == 'M' && command[1] == 'Y' && extraLen != 0)
1046
        {
1047
                xbee_address = 0;
1048
                int i;
1049
                for (i = 0; i < extraLen; i++) {
1050
                        xbee_address = (xbee_address << 8) + extra[i];
1051
                }
1052

    
1053
                WL_DEBUG_PRINT("XBee address is ");
1054
                WL_DEBUG_PRINT_INT(xbee_address);
1055
                WL_DEBUG_PRINT(".\r\n");
1056

    
1057
                if (xbee_address == 0)
1058
                {
1059
                        WL_DEBUG_PRINT("XBee 16-bit address must be set using ATMY.\r\n");
1060
                        #ifndef ROBOT
1061
                        exit(0);
1062
                        #endif
1063
                }
1064
        }
1065
  return 0;
1066
}
1067

    
1068
/**
1069
 * Attempts to handle the packet if it is dealt with
1070
 * by the library.
1071
 * We will handle the following packet types:
1072
 *    Modem Status
1073
 *    AT Command Response
1074
 *
1075
 * @param packet the packet to handle
1076
 * @param len the length of the packet
1077
 *
1078
 * @return 1 if we have handled the packet, 0 otherwise
1079
 */
1080
static int xbee_handle_packet(char* packet, int len)
1081
{
1082

    
1083
        char command[3] = {1, 2, 3};
1084
        if (len <= 0) //this should not happend
1085
        {
1086
                WL_DEBUG_PRINT("Non-positive packet length.\r\n");
1087
                return 0;
1088
        }
1089

    
1090
        switch ((unsigned char)packet[0]) //packet type
1091
        {
1092
                case XBEE_FRAME_STATUS:
1093
                        xbee_handle_status(packet[1]);
1094
                        return 1;
1095
                case XBEE_FRAME_AT_COMMAND_RESPONSE:
1096
                        command[0] = packet[2];
1097
                        command[1] = packet[3];
1098
                        command[2] = 0;
1099
                        if (xbee_handle_at_command_response(command, packet[4], packet + 5, len - 5) != 0)
1100
        return -1;
1101
      else
1102
        return 1;
1103
        }
1104
        return 0;
1105
}
1106

    
1107
/**
1108
 * Sets the personal area network id.
1109
 *
1110
 * @param id the new personal area network (PAN) id
1111
 **/
1112
int xbee_set_pan_id(int id)
1113
{
1114
        char s[3];
1115
        s[0] = (id >> 8) & 0xFF;
1116
        s[1] = id & 0xFF;
1117
        s[2] = 0;
1118
        xbee_pending_panID = id;
1119
        return xbee_send_modify_at_command("ID", s);
1120
}
1121

    
1122
/**
1123
 * Get the PAN ID for the XBee.
1124
 *
1125
 * @return the personal area network id, or
1126
 * XBEE_PAN_DEFAULT if it has not yet been set.
1127
 **/
1128
unsigned int xbee_get_pan_id()
1129
{
1130
        return xbee_panID;
1131
}
1132

    
1133
/**
1134
 * Set the channel the XBee is using.
1135
 *
1136
 * @param channel the channel the XBee will not use,
1137
 * between 0x0B and 0x1A
1138
 *
1139
 * @see xbee_get_channel
1140
 **/
1141
int xbee_set_channel(int channel)
1142
{
1143
        if (channel < 0x0B || channel > 0x1A)
1144
        {
1145
                WL_DEBUG_PRINT("Channel out of range.\r\n");
1146
                return -1;
1147
        }
1148

    
1149
        char s[3];
1150
        s[0] = channel & 0xFF;
1151
        s[1] = 0;
1152
        xbee_pending_channel = channel;
1153

    
1154
        return xbee_send_modify_at_command("CH", s);
1155
}
1156

    
1157
/**
1158
 * Returns the channel which the XBee is currently using.
1159
 *
1160
 * @return the channel the XBee is using
1161
 *
1162
 * @see xbee_set_channel
1163
 **/
1164
int xbee_get_channel(void)
1165
{
1166
        return xbee_channel;
1167
}
1168

    
1169
/**
1170
 * Get the 16-bit address of the XBee.
1171
 * This is used to specify who to send messages to
1172
 * and who messages are from.
1173
 *
1174
 * @return the 16-bit address of the XBee.
1175
 **/
1176
unsigned int xbee_get_address()
1177
{
1178
        return xbee_address;
1179
}
1180

    
1181
#ifndef ROBOT
1182
void xbee_set_com_port(char* port)
1183
{
1184
        xbee_com_port = port;
1185
}
1186
#endif