Project

General

Profile

Statistics
| Revision:

root / branches / autonomous_recharging / code / projects / libwireless / lib / xbee.c @ 726

History | View | Annotate | Download (24.4 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
#include <ctype.h>
52

    
53
#endif
54

    
55
#include <stdio.h>
56
#include <stdlib.h>
57
#include <string.h>
58

    
59
#define XBEE_FRAME_START 0x7E
60
#define XBEE_GET_PACKET_TIMEOUT 1000
61

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

    
72
/*Internal Function Prototypes*/
73

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

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

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

    
92
/*API Mode Functions*/
93

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

    
103
/*Global Variables*/
104
#define MAX_XBEE_FRAME_SIZE 32
105

    
106

    
107
#ifndef ROBOT
108
static char* xbee_com_port = XBEE_PORT_DEFAULT;
109
static int xbee_stream;
110
static pthread_t* xbee_listen_thread;
111
#endif
112

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

    
122

    
123
//used to store packets as they are read
124
static char xbee_buf[MAX_XBEE_FRAME_SIZE];
125
static int currentBufPos = 0;
126

    
127
//XBee status
128
static unsigned int xbee_panID = XBEE_PAN_DEFAULT;
129
static unsigned int xbee_pending_panID = XBEE_PAN_DEFAULT;
130
static int xbee_channel = XBEE_CHANNEL_DEFAULT;
131
static int xbee_pending_channel = XBEE_CHANNEL_DEFAULT;
132
static volatile unsigned int xbee_address = 0;
133

    
134
#ifndef ROBOT
135
void printHex(char * s, int len) {
136
  int i;
137
  for (i = 0; i < len; i++) {
138
    printf("0x%x ", (int)(s[i]));
139
  }
140
  printf("\n");
141
}
142
#endif
143

    
144

    
145
/*Function Implementations*/
146

    
147
#ifdef ROBOT
148

    
149
/**
150
 * Interrupt for the robot. Adds bytes received from the xbee
151
 * to the buffer.
152
 **/
153
#ifdef FIREFLY
154
SIGNAL(SIG_USART0_RECV)
155
{
156
  usb_puts("In USART0 interrupt\n");
157
        char c = UDR0;
158
        arrival_buf[buffer_last] = c;
159
        int t = buffer_last + 1;
160
        if (t == XBEE_BUFFER_SIZE)
161
                t = 0;
162
        if (t == buffer_first)
163
    {
164
      WL_DEBUG_PRINT("Out of space in buffer.\n");
165
    }
166
        buffer_last = t;
167
}
168
#else
169
#ifdef BAYBOARD
170
ISR(USART1_RX_vect)
171
{
172
        char c = UDR1;
173

    
174
        /*
175
    char buf[30];
176
    char buf2[5];
177
          buf2[0] = '\\';
178
          if (c == '\b') {
179
    buf2[1] = 'b';
180
    buf2[2] = '\0';
181
          }
182
          else if (c == '\n') {
183
    buf2[1] = 'n';
184
    buf2[2] = '\0';
185
          }
186
          else if (c == '\r') {
187
    buf2[1] = 'r';
188
    buf2[2] = '\0';
189
          }
190
          else if (c == '\t') {
191
    buf2[1] = 't';
192
    buf2[2] = '\0';
193
          }
194
          else if (!isprint(c)) {
195
    sprintf(buf2, "0x%.2x", c);
196
          }
197
          else {
198
    buf2[0] = c;
199
    buf2[1] = '\0';
200
          }
201
    sprintf(buf, "In USART1 interrupt [%s]\n", buf2);
202
    usb_puts(buf);
203
        */
204

    
205
        arrival_buf[buffer_last] = c;
206
        int t = buffer_last + 1;
207
        if (t == XBEE_BUFFER_SIZE)
208
                t = 0;
209
        if (t == buffer_first)
210
    {
211
      WL_DEBUG_PRINT("Out of space in buffer.\n");
212
    }
213
        buffer_last = t;
214
}
215
#else
216
ISR(USART1_RX_vect)
217
{
218
        char c = UDR1;
219
        arrival_buf[buffer_last] = c;
220
        int t = buffer_last + 1;
221
        if (t == XBEE_BUFFER_SIZE)
222
                t = 0;
223
        if (t == buffer_first)
224
    {
225
      WL_DEBUG_PRINT("Out of space in buffer.\n");
226
    }
227
        buffer_last = t;
228
}
229
#endif
230
#endif
231

    
232
#else
233

    
234
// Computer code
235

    
236
/**
237
 * Thread that listens to the xbee.
238
 **/
239
static void* listen_to_xbee(void* x)
240
{
241
        char c;
242
        while (1)
243
    {
244
      if (xbee_read(&c, 1) != 0) {
245
        fprintf(stderr, "xbee_read failed.\n");
246
        return NULL;
247
      }
248

    
249
      //DEBUGGING PRINT
250
      //printf("interrupt: %c (%d)\n", c, (int)c);
251
      arrival_buf[buffer_last] = c;
252
      int t = buffer_last + 1;
253
      if (t == XBEE_BUFFER_SIZE)
254
        t = 0;
255
      if (t == buffer_first)
256
        {
257
          WL_DEBUG_PRINT("Out of space in buffer.\n");
258
        }
259
      buffer_last = t;
260

    
261
      usleep(1000);
262
    }
263

    
264
        return NULL;
265
}
266

    
267
#endif
268

    
269
/**
270
 * Initializes the XBee library so that other functions may be used.
271
 **/
272
int xbee_lib_init()
273
{
274
        arrival_buf[0] = 'A';
275
        arrival_buf[1] = 'A';
276
        arrival_buf[2] = 'A';
277
#ifdef ROBOT
278

    
279
        //enable the receiving interrupt
280
#ifdef FIREFLY
281
        UCSR0B |= _BV(RXCIE) | _BV(RXEN);
282
#else
283
#ifdef BAYBOARD
284
        UCSR1B |= _BV(RXCIE0);
285
#else
286
        UCSR1B |= _BV(RXCIE);
287
#endif
288
#endif
289
        sei();
290
#else
291
        printf("Connecting to port %s.\n", xbee_com_port);
292
        xbee_stream = open(xbee_com_port, O_RDWR);
293
        if (xbee_stream == -1/* || lockf(xbee_stream, F_TEST, 0) != 0*/)
294
    {
295
      printf("Failed to open connection to XBee on port %s\r\n", xbee_com_port);
296
      return -1;
297
    } else {
298
          printf("Successfully opened connection to XBee on port %s\r\n", xbee_com_port);
299
        }
300

    
301
        // set baud rate, etc. correctly
302
        struct termios options;
303

    
304
        tcgetattr(xbee_stream, &options);
305
        cfsetispeed(&options, B9600);
306
        cfsetospeed(&options, B9600);
307
        options.c_iflag &= ~ICRNL;
308
        options.c_oflag &= ~OCRNL;
309
        options.c_cflag |= (CLOCAL | CREAD);
310
        options.c_cflag &= ~PARENB;
311
        options.c_cflag &= ~CSTOPB;
312
        options.c_cflag &= ~CSIZE;
313
        options.c_cflag |= CS8;
314
        options.c_lflag &= ~ICANON;
315
        options.c_cc[VMIN] = 1;
316
        options.c_cc[VTIME] = 50;
317

    
318
        if (tcsetattr(xbee_stream, TCSANOW, &options))
319
    {
320
      fprintf(stderr, "Error setting attributes.\n");
321
      return -1;
322
    } else {
323
          //printf("Successfully set termios attributes.\n");
324
        }
325

    
326
        //lockf(xbee_stream, F_LOCK, 0);
327

    
328
        xbee_listen_thread = (pthread_t*)malloc(sizeof(pthread_t));
329
        if (xbee_listen_thread == NULL)
330
    {
331
      fprintf(stderr, "%s: Malloc failed.\n", __FUNCTION__);
332
      return -1;
333
    }
334

    
335
        int ret = pthread_create(xbee_listen_thread, NULL, listen_to_xbee, NULL);
336
        if (ret)
337
    {
338
      fprintf(stderr, "Failed to create listener thread.\r\n");
339
      return -1;
340
    } else {
341
          //printf("Successfully created listener thread.\n");
342
        }
343
#endif
344

    
345
        //DEBUGGING PRINT
346
        //printf("about to call xbee_enter_command_mode\n");
347

    
348
        if (xbee_enter_command_mode() != 0) {
349
#ifndef ROBOT
350
          printf("Error returned from xbee_enter_command_mode\n");
351
#endif
352
                return -1;
353
        }
354

    
355
        //DEBUGGING PRINT
356
        //printf("about to call xbee_enter_api_mode\n");
357

    
358
        if (xbee_enter_api_mode() != 0) {
359
#ifndef ROBOT
360
          printf("Error returned from xbee_enter_api_mode\n");
361
#endif
362
                return -1;
363
        }
364

    
365
        //DEBUGGING PRINT
366
        //printf("about to call xbee_exit_command_mode\n");
367

    
368
        if (xbee_exit_command_mode() != 0) {
369
#ifndef ROBOT
370
          printf("Error returned from xbee_exit_command_mode\n");
371
#endif
372
                return -1;
373
        }
374

    
375
        //DEBUGGING PRINT
376
        //printf("about to call xbee_send_read_at_command\n");
377

    
378
        if (xbee_send_read_at_command("MY")) {
379
#ifndef ROBOT
380
          printf("Error returned from xbee_send_read_at_command\n");
381
#endif
382
                return -1;
383
        }
384

    
385
#ifndef ROBOT
386
        //printf("About to enter while loop to get xbee_address.\n");
387
        int i;
388
        for (i = 0; xbee_address == 0 && i < XBEE_GET_PACKET_TIMEOUT; i++) {
389
          ret = xbee_get_packet(NULL);
390

    
391
          usleep(1000);
392

    
393
          if (ret == -1) {
394
      //printf("xbee_get_packet(NULL) failed.\n");
395
      return -1;
396
          }
397
        }
398

    
399
        //        printf("After exiting while loop to get xbee_address.\n");
400
#else
401
        //wait to return until the address is set
402
        while (xbee_address == 0) {
403
          xbee_get_packet(NULL);
404
        }
405
#endif
406

    
407
#ifndef ROBOT
408
        if (i == XBEE_GET_PACKET_TIMEOUT) { // We timed-out.
409

    
410
          printf("xbee_get_packet timed out.\n");
411
          return -1;
412
        } else {
413
          return 0;
414
        }
415
#else
416
        return 0;
417
#endif
418
}
419

    
420
/**
421
 * Call when finished using the XBee library. This releases
422
 * all sued resources.
423
 **/
424
void xbee_terminate()
425
{
426
#ifndef ROBOT
427
        pthread_cancel(*xbee_listen_thread);
428
        free(xbee_listen_thread);
429
        lockf(xbee_stream, F_ULOCK, 0);
430
        close(xbee_stream);
431
#endif
432
}
433

    
434
/**
435
 * Send a buffer buf of size bytes to the XBee.
436
 *
437
 * @param buf the buffer of data to send
438
 * @param size the number of bytes to send
439
 **/
440
static int xbee_send(char* buf, int size)
441
{
442
#ifdef ROBOT
443
        int i;
444
        for (i = 0; i < size; i++) {
445
                xbee_putc(buf[i]);
446
        }
447

    
448
        return 0;
449

    
450
#else
451
        //DEBUGGING PRINT
452
        //printf("in xbee_send ");
453
        //printHex(buf, size);
454

    
455
        int ret = write(xbee_stream, buf, size);
456
        //success
457
        if (ret == size)
458
                return 0;
459
        if (ret == -1)
460
    {
461
      //interrupted by system signal, probably timer interrupt.
462
      //just try again
463
      if (errno == 4)
464
        {
465
          return xbee_send(buf, size);
466
        }
467
      printf("Failed to write to xbee, error %i.\r\n", errno);
468
      return -1;
469
    }
470

    
471
        //write was interrupted after writing ret bytes
472
        return xbee_send(buf + ret, size - ret);
473
#endif
474
}
475

    
476
/**
477
 * Sends a string to the XBee.
478
 *
479
 * @param c the string to send to the XBEE
480
 **/
481
static int xbee_send_string(char* c)
482
{
483
        return xbee_send(c, strlen(c));
484
}
485

    
486
#ifndef ROBOT
487
static int xbee_read(char* buf, int size)
488
{
489
        if (read(xbee_stream, buf, size) == -1) {
490
                printf("Failed to read from xbee.\r\n");
491
                return -1;
492
        }
493

    
494
        return 0;
495
}
496
#endif
497

    
498
/**
499
 * Enter into command mode.
500
 **/
501
static int xbee_enter_command_mode()
502
{
503
        if (xbee_send_string("+++") != 0) {
504
                return -1;
505
        }
506

    
507
#ifndef ROBOT
508
        //        printf("In xbee_enter_command_mode about to call xbee_wait_for_ok()\n");
509
#endif
510

    
511
        if (xbee_wait_for_ok() != 0) {
512
#ifndef ROBOT
513
          printf("xbee_wait_for_ok failed.\n");
514
#endif
515
          return -1;
516
        } else {
517
          return 0;
518
        }
519
}
520

    
521
/**
522
 * Exit from command mode.
523
 **/
524
static int xbee_exit_command_mode()
525
{
526
        if (xbee_send_string("ATCN\r") != 0) {
527
                return -1;
528
        }
529

    
530
        xbee_wait_for_ok();
531

    
532
        return 0;
533
}
534

    
535
/**
536
 * Enter API mode.
537
 **/
538
static int xbee_enter_api_mode()
539
{
540
        if (xbee_send_string("ATAP 1\r") != 0) {
541
                return -1;
542
        }
543
        xbee_wait_for_ok();
544

    
545
        return 0;
546
}
547

    
548
/**
549
 * Exit API mode. (warning - does not check for response)
550
 **/
551
static int xbee_exit_api_mode()
552
{
553
        return xbee_send_string("ATAP 0\r");
554
}
555

    
556
/**
557
 * Wait until the string "OK\r" is received from the XBee.
558
 **/
559
static int xbee_wait_for_ok()
560
{
561
  //DEBUGGING PRINT
562
  //printf("\tin xbee_wait_for_ok\n");
563
        return xbee_wait_for_string("OK\r", 3);
564
}
565

    
566
/**
567
 * Delay until the specified string is received from
568
 * the XBee. Discards all other XBee data.
569
 *
570
 * @param s the string to receive
571
 * @param len the length of the string
572
 **/
573
static int xbee_wait_for_string(char* s, int len)
574
{
575
  //DEBUGGING PRINT
576
  //printf("\t in xbee_wait_for_string\n");
577

    
578
#ifndef ROBOT
579
  //printf("In xbee_wait_for_string.\n");
580
#endif
581

    
582
        char* curr = s;
583
        while (curr - s < len) {
584
                // check if buffer is empty
585
                if (buffer_last != buffer_first) {
586
                  cli();
587
                        char c = arrival_buf[buffer_first++];
588
                        if (buffer_first == XBEE_BUFFER_SIZE) {
589
                                buffer_first = 0;
590
                        }
591
                        sei();
592

    
593
                        //DEBUGGING PRINT
594
                        //printf("\t\t c is %c (%d)\n", c, (int)c);
595

    
596
                        if (c == *curr) {
597
                                curr++;
598
                        } else {
599
#ifndef ROBOT
600
                          //return -1; // Computer is less forgiving.
601
                          curr = s;
602
#else
603
                          curr = s;
604
#endif
605
                        }
606
                } // else buffer is empty.
607

    
608
#ifndef ROBOT
609
                usleep(100);
610
#endif
611
        }
612

    
613
        return 0;
614
}
615

    
616
/**
617
 * Verifies that the packets checksum is correct.
618
 * (If the checksum is correct, the sum of the bytes
619
 * is 0xFF.)
620
 *
621
 * @param packet the packet received. This includes the first
622
 * three bytes, which are header information from the XBee.
623
 *
624
 * @param len The length of the packet received from the XBee
625
 *
626
 * @return 0 if the checksum is incorrect, nonzero
627
 * otherwise
628
 **/
629
int xbee_verify_checksum(char* packet, int len)
630
{
631
        unsigned char sum = 0;
632
        int i;
633
        for (i = 3; i < len; i++)
634
                sum += (unsigned char)packet[i];
635
        return sum == 0xFF;
636
}
637

    
638
/**
639
 * Returns the checksum of the given packet.
640
 *
641
 * @param buf the data for the packet to send
642
 * @param len the length of the packet in bytes
643
 *
644
 * @return the checksum of the packet, which will
645
 * become the last byte sent in the packet
646
 **/
647
char xbee_compute_checksum(char* buf, int len)
648
{
649
        int i;
650
        unsigned char sum = 0;
651
        for (i = 0; i < len; i++)
652
                sum += (unsigned char)buf[i];
653
        return 0xFF - sum;
654
}
655

    
656
/**
657
 * Adds header information and checksum to the given
658
 * packet and sends it. Header information includes
659
 * XBEE_FRAME_START and the packet length, as two bytes.
660
 *
661
 * @param buf the packet data
662
 * @param len the size in bytes of the packet data
663
 *
664
 **/
665
static int xbee_send_frame(char* buf, int len)
666
{
667
        //printf("in %s and len is %d\n", __FUNCTION__, len);
668

    
669
        char prefix[3];
670
        prefix[0] = XBEE_FRAME_START;
671
        prefix[1] = (len & 0xFF00) >> 8;
672
        prefix[2] = len & 0xFF;
673
        char checksum = xbee_compute_checksum(buf, len);
674

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

    
679
        if (xbee_send(buf, len) != 0) {
680
                return -1;
681
        }
682

    
683
        if (xbee_send(&checksum, 1) != 0) {
684
                return -1;
685
        }
686

    
687
        return 0;
688
}
689

    
690
/**
691
 * Sends an AT command to read a parameter.
692
 *
693
 * @param command the AT command to send. For exmaple,
694
 * use ID to read the PAN ID and MY to return the XBee ID.
695
 * See the XBee reference guide for a complete listing.
696
 **/
697
static int xbee_send_read_at_command(char* command)
698
{
699
        return xbee_send_modify_at_command(command, NULL);
700
}
701

    
702
/**
703
 * Sends the given AT command.
704
 *
705
 * @param command the AT command to send (e.g., MY, ID)
706
 * @param value the value to pass as a parameter
707
 * (or NULL if there is no parameter)
708
 **/
709
static int xbee_send_modify_at_command(char* command, char* value)
710
{
711
        //printf("in %s with command %s and value %s\n", __FUNCTION__, command, value);
712

    
713
        char buf[16];
714
        int i;
715

    
716
        buf[0] = XBEE_FRAME_AT_COMMAND;
717
        buf[1] = 1;
718
        buf[2] = command[0];
719
        buf[3] = command[1];
720
        int valueLen = 0;
721
        if (value != NULL)
722
    {
723
      valueLen = strlen(value);
724
      if (valueLen > 8)
725
        {
726
          WL_DEBUG_PRINT("AT Command too large.\r\n");
727
          return -1;
728
        }
729

    
730
      for (i = 0; i < valueLen; i++) {
731
        buf[4 + i] = value[i];
732
      }
733
    }
734

    
735
        return xbee_send_frame(buf, 4 + valueLen);
736
}
737

    
738
/**
739
 * Send the specified packet.
740
 *
741
 * @param packet the packet data to send
742
 * @param len the number of bytes in the packet
743
 *
744
 * @param dest the ID of the XBee to send the packet to,
745
 * or XBEE_BROADCAST to send the message to all robots
746
 * in the PAN.
747
 *
748
 * @param options a combination of the flags
749
 * XBEE_OPTIONS_NONE, XBEE_OPTIONS_DISABLE_RESPONSE and
750
 * XBEE_OPTIONS_BROADCAST_ALL_PANS
751
 *
752
 * @param frame the frame number to associate this packet
753
 * with. This will be used to identify the response when
754
 * the XBee alerts us as to whether or not our message
755
 * was received.
756
 **/
757
int xbee_send_packet(char* packet, int len, int dest, char options, char frame)
758
{
759
        char buf[5];
760
        char prefix[3];
761
        int i;
762
        unsigned char checksum = 0;
763

    
764
        if (len > 100)
765
    {
766
      WL_DEBUG_PRINT("Packet is too large.\r\n");
767
      return -1;
768
    }
769

    
770
        //data for sending request
771
        buf[0] = XBEE_FRAME_TX_REQUEST_16;
772
        buf[1] = frame;
773
        buf[2] = (dest >> 8) & 0xFF;
774
        buf[3] = dest & 0xFF;
775
        buf[4] = options;
776

    
777
        //packet prefix, do this here so we don't need an extra buffer
778
        prefix[0] = XBEE_FRAME_START;
779
        prefix[1] = ((5 + len) & 0xFF00) >> 8;
780
        prefix[2] = (5 + len) & 0xFF;
781

    
782
        for (i = 0; i < 5; i++)
783
                checksum += (unsigned char)buf[i];
784
        for (i = 0; i < len; i++)
785
                checksum += (unsigned char)packet[i];
786
        checksum = 0xFF - checksum;
787

    
788
        if (xbee_send(prefix, 3) != 0) {
789
                return -1;
790
        }
791

    
792
        if (xbee_send(buf, 5) != 0) {
793
                return -1;
794
        }
795

    
796
        if (xbee_send(packet, len) != 0) {
797
                return -1;
798
        }
799

    
800
        if (xbee_send((char*)&checksum, 1) != 0) {
801
                return -1;
802
        }
803

    
804
        return 0;
805
}
806

    
807
/**
808
 * Reads a packet received from the XBee. This function
809
 * is non-blocking. The resulting packet is stored in dest.
810
 * Only returns transmission response packets and
811
 * received packets. The returned packet does not include
812
 * header information or the checksum. This method also
813
 * handles special packets dealt with by the XBee library,
814
 * and so should be called frequently while the XBee is in
815
 * use.<br><br>
816
 *
817
 * The first byte of the packet will be either
818
 * XBEE_TX_STATUS or XBEE_RX to indicated
819
 * a response to a sent message or a received message,
820
 * respectively.<br><br>
821
 *
822
 * For a status response packet:<br>
823
 * The first byte will be XBEE_TX_STATUS.<br>
824
 * The second byte will be the frame number.<br>
825
 * The third byte will be the result. 0 indicates success,
826
 * and nonzero indicates that an error ocurred in
827
 * transmitting the packet.<br><br>
828
 *
829
 * For a received packet:<br>
830
 * The first byte will be XBEE_RX.<br>
831
 * The second and third bytes will be the 16-bit
832
 * address of the packet's sender.<br>
833
 * The fourth byte is the signal strength.<br>
834
 * The fifth byte is 1 if the packet were sent to
835
 * a specific address, and 2 if it is a broadcast packet.<br><br>
836
 *
837
 * @param dest set to the packet data
838
 * @return the length of the packet, or -1 if no packet
839
 * is available
840
 **/
841
int xbee_get_packet(unsigned char* dest)
842
{
843
        //start reading a packet with XBEE_FRAME_START
844
        if (currentBufPos == 0)
845
    {
846
      cli();
847
      do
848
        {
849
          if (buffer_first == XBEE_BUFFER_SIZE)
850
            buffer_first = 0;
851
          // check if buffer is empty
852
          if (buffer_first == buffer_last) {
853
            sei();
854
            return 0;
855
          }
856
        } while (arrival_buf[buffer_first++] != XBEE_FRAME_START);
857

    
858
      if (buffer_first == XBEE_BUFFER_SIZE) {
859
        buffer_first = 0;
860
      }
861
      sei();
862

    
863
      xbee_buf[0] = XBEE_FRAME_START;
864
      currentBufPos++;
865
    }
866

    
867
        int len = -1;
868
        if (currentBufPos >= 3) {
869
                len = (int)xbee_buf[2] + ((int)xbee_buf[1] << 8);
870
        }
871

    
872
        while (len == -1 //packet length has not been read yet
873
         || currentBufPos < len + 4)
874
    {
875
      if (currentBufPos == 3)
876
        {
877
          len = (int)xbee_buf[2] + ((int)xbee_buf[1] << 8);
878
          if (len > 120)
879
            {
880
              WL_DEBUG_PRINT("Packet too large. Probably error in XBee transmission.\n");
881
              currentBufPos = 0;
882
              return -1;
883
            }
884
        }
885

    
886
      // check if buffer is empty
887
      if (buffer_first == buffer_last) {
888
        return 0;
889
      }
890
      xbee_buf[currentBufPos++] = arrival_buf[buffer_first++];
891
      if (buffer_first == XBEE_BUFFER_SIZE) {
892
        buffer_first = 0;
893
      }
894
    }
895

    
896
        currentBufPos = 0;
897

    
898
        if (!xbee_verify_checksum(xbee_buf, len + 4))
899
    {
900
      WL_DEBUG_PRINT("XBee checksum failed.\r\n");
901
      return -1;
902
    }
903

    
904
        //we will take care of the packet
905
        if (xbee_handle_packet(xbee_buf + 3, len) != 0) {
906
                return 0;
907
        }
908

    
909
        if (dest == NULL) {
910
                return 0;
911
        }
912

    
913
        int i;
914
        for (i = 3; i < len + 3; i++) {
915
                dest[i - 3] = xbee_buf[i];
916
        }
917

    
918
        return len;
919
}
920

    
921
/**
922
 * Handles modem status packets.
923
 *
924
 * @param status the type of status packet received.
925
 **/
926
void xbee_handle_status(char status)
927
{
928
        switch (status)
929
    {
930
                case 0:
931
                        WL_DEBUG_PRINT("XBee hardware reset.\r\n");
932
                        break;
933
                case 1:
934
                        WL_DEBUG_PRINT("Watchdog timer reset.\r\n");
935
                        break;
936
                case 2:
937
                        WL_DEBUG_PRINT("Associated.\r\n");
938
                        break;
939
                case 3:
940
                        WL_DEBUG_PRINT("Disassociated.\r\n");
941
                        break;
942
                case 4:
943
                        WL_DEBUG_PRINT("Synchronization lost.\r\n");
944
                        break;
945
                case 5:
946
                        WL_DEBUG_PRINT("Coordinator realignment.\r\n");
947
                        break;
948
                case 6:
949
                        WL_DEBUG_PRINT("Coordinator started.\r\n");
950
                        break;
951
    }
952
}
953

    
954
/**
955
 * Handles AT command response packets.
956
 * @param command the two character AT command, e.g. MY or ID
957
 * @param result 0 for success, 1 for an error
958
 * @param extra the hex value of the requested register
959
 * @param extraLen the length in bytes of extra
960
 **/
961
static void xbee_handle_at_command_response(char* command, char result, char* extra, int extraLen)
962
{
963
        if (result == 1)
964
    {
965
      WL_DEBUG_PRINT("Error with AT");
966
      WL_DEBUG_PRINT(command);
967
      WL_DEBUG_PRINT(" packet.\r\n");
968
    }
969
        WL_DEBUG_PRINT("AT");
970
        WL_DEBUG_PRINT(command);
971
        WL_DEBUG_PRINT(" command was successful.\r\n");
972

    
973
        if (command[0] == 'I' && command[1] == 'D')
974
    {
975
      xbee_panID = xbee_pending_panID;
976
      WL_DEBUG_PRINT("PAN ID set to ");
977
      WL_DEBUG_PRINT_INT(xbee_panID);
978
      WL_DEBUG_PRINT(".\r\n");
979
      return;
980
    }
981

    
982
        if (command[0] == 'C' && command[1] == 'H')
983
    {
984
      xbee_channel = xbee_pending_channel;
985
      WL_DEBUG_PRINT("Channel set to ");
986
      WL_DEBUG_PRINT_INT(xbee_channel);
987
      WL_DEBUG_PRINT(".\r\n");
988
      return;
989
    }
990

    
991
        if (command[0] == 'M' && command[1] == 'Y' && extraLen != 0)
992
    {
993
      //                                                        printf("reading xbee_address\n");
994

    
995
      xbee_address = 0;
996
      int i;
997
      for (i = 0; i < extraLen; i++) {
998
        xbee_address = (xbee_address << 8) + extra[i];
999
      }
1000
      //                                                        printf("xbee address is: %d\n", xbee_address);
1001

    
1002
      WL_DEBUG_PRINT("XBee address is ");
1003
      WL_DEBUG_PRINT_INT(xbee_address);
1004
      WL_DEBUG_PRINT(".\r\n");
1005

    
1006
      if (xbee_address == 0)
1007
        {
1008
          printf("XBee 16-bit address must be set using ATMY.\r\n");
1009
          WL_DEBUG_PRINT("XBee 16-bit address must be set using ATMY.\r\n");
1010
          exit(0);
1011
        }
1012
    }
1013
}
1014

    
1015
/**
1016
 * Attempts to handle the packet if it is dealt with
1017
 * by the library.
1018
 * We will handle the following packet types:
1019
 *    Modem Status
1020
 *    AT Command Response
1021
 *
1022
 * @param packet the packet to handle
1023
 * @param len the length of the packet
1024
 *
1025
 * @return 1 if we have handled the packet, 0 otherwise
1026
 */
1027
static int xbee_handle_packet(char* packet, int len)
1028
{
1029
  //DEBUGGING PRINT
1030
  //printf("xbee_handle_packet: ");
1031
  //printHex(packet, len);
1032

    
1033
        char command[3] = {1, 2, 3};
1034
        if (len <= 0) //this should not happend
1035
    {
1036
      WL_DEBUG_PRINT("Non-positive packet length.\r\n");
1037
      return 0;
1038
    }
1039

    
1040
        switch ((unsigned char)packet[0]) //packet type
1041
    {
1042
                case XBEE_FRAME_STATUS:
1043
                        xbee_handle_status(packet[1]);
1044
                        return 1;
1045
                case XBEE_FRAME_AT_COMMAND_RESPONSE:
1046
                        //printf("in XBEE_FRAME_AT_COMMAND_RESPONSE case\n");
1047
                        command[0] = packet[2];
1048
                        command[1] = packet[3];
1049
                        command[2] = 0;
1050
                        xbee_handle_at_command_response(command, packet[4], packet + 5, len - 5);
1051
                        return 1;
1052
    }
1053
        return 0;
1054
}
1055

    
1056
/**
1057
 * Sets the personal area network id.
1058
 *
1059
 * @param id the new personal area network (PAN) id
1060
 **/
1061
int xbee_set_pan_id(int id)
1062
{
1063
        char s[3];
1064
        s[0] = (id >> 8) & 0xFF;
1065
        s[1] = id & 0xFF;
1066
        s[2] = 0;
1067
        xbee_pending_panID = id;
1068
        return xbee_send_modify_at_command("ID", s);
1069
}
1070

    
1071
/**
1072
 * Get the PAN ID for the XBee.
1073
 *
1074
 * @return the personal area network id, or
1075
 * XBEE_PAN_DEFAULT if it has not yet been set.
1076
 **/
1077
unsigned int xbee_get_pan_id()
1078
{
1079
        return xbee_panID;
1080
}
1081

    
1082
/**
1083
 * Set the channel the XBee is using.
1084
 *
1085
 * @param channel the channel the XBee will not use,
1086
 * between 0x0B and 0x1A
1087
 *
1088
 * @see xbee_get_channel
1089
 **/
1090
int xbee_set_channel(int channel)
1091
{
1092
        if (channel < 0x0B || channel > 0x1A)
1093
    {
1094
      WL_DEBUG_PRINT("Channel out of range.\r\n");
1095
      return -1;
1096
    }
1097

    
1098
        char s[3];
1099
        s[0] = channel & 0xFF;
1100
        s[1] = 0;
1101
        xbee_pending_channel = channel;
1102

    
1103
        return xbee_send_modify_at_command("CH", s);
1104
}
1105

    
1106
/**
1107
 * Returns the channel which the XBee is currently using.
1108
 *
1109
 * @return the channel the XBee is using
1110
 *
1111
 * @see xbee_set_channel
1112
 **/
1113
int xbee_get_channel(void)
1114
{
1115
        return xbee_channel;
1116
}
1117

    
1118
/**
1119
 * Get the 16-bit address of the XBee.
1120
 * This is used to specify who to send messages to
1121
 * and who messages are from.
1122
 *
1123
 * @return the 16-bit address of the XBee.
1124
 **/
1125
unsigned int xbee_get_address()
1126
{
1127
        return xbee_address;
1128
}
1129

    
1130
#ifndef ROBOT
1131
void xbee_set_com_port(char* port)
1132
{
1133
        xbee_com_port = port;
1134
}
1135
#endif