Project

General

Profile

Statistics
| Revision:

root / branches / wireless / code / projects / oldlibwireless / lib / wl_token_ring.c @ 1624

History | View | Annotate | Download (23.3 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 wl_token_ring.c
28
 * @brief Token Ring Implementation
29
 *
30
 * Implementation of the token ring packet group.
31
 *
32
 * @author Brian Coltin, Colony Project, CMU Robotics Club
33
 **/
34

    
35
#include <inttypes.h>
36
#include <wl_token_ring.h>
37

    
38
#include <stdlib.h>
39

    
40
#include <wl_defs.h>
41
#include <wireless.h>
42
#include <sensor_matrix.h>
43

    
44
#ifdef ROBOT
45
#ifndef FIREFLY
46
#include <bom.h>
47
#endif
48
#include <time.h>
49
#endif
50

    
51

    
52
//#define DEFAULT_SENSOR_MATRIX_SIZE 20
53

    
54
/*Ring States*/
55

    
56
#define NONMEMBER 0
57
#define MEMBER 1
58
#define JOINING 2
59
#define ACCEPTED 3
60
#define LEAVING 4
61

    
62
/*Frame Types*/
63
#define TOKEN_JOIN_ACCEPT_FRAME        1
64
#define WL_TOKEN_PASS_FRAME        2
65

    
66
/*Function Prototypes*/
67

    
68
/*Wireless Library Prototypes*/
69
static void wl_token_ring_timeout_handler(void);
70
static void wl_token_ring_response_handler(int frame, int received);
71
static void wl_token_ring_receive_handler(char type, int source, unsigned char* packet, int length);
72
static void wl_token_ring_cleanup(void);
73

    
74
/*Helper Functions*/
75
static int wl_token_pass_token(void);
76
static int get_token_distance(int robot1, int robot2);
77
static void wl_token_get_token(void);
78

    
79
/*Packet Handling Routines*/
80
static void wl_token_pass_receive(int source);
81
static void wl_token_sensor_matrix_receive(int source, unsigned char* sensorData, int sensorDataLength);
82
static void wl_token_bom_on_receive(int source);
83
static void wl_token_join_receive(int source);
84
static void wl_token_join_accept_receive(int source);
85

    
86
/*Global Variables*/
87

    
88
//the robot we are waiting to say it has received the token. -1 if unspecified
89
static int wl_token_next_robot = -1;
90

    
91
//true if the robot should be in the token ring, 0 otherwise
92
static int ringState = NONMEMBER;
93
//the id of the robot who accepted us into the token ring, only used in ACCEPTED state
94
static int acceptor = -1;
95
//id of the robot we are accepting
96
static int accepted = -1;
97

    
98
//the counter for when we assume a robot is dead
99
static int deathDelay = -1;
100
//the counter for joining, before we form our own token ring
101
static int joinDelay = -1;
102

    
103
//current robot to check in the iterator
104
static int iteratorCount = 0;
105

    
106
// the amount of time a robot has had its BOM on for
107
static int bom_on_count = 0;
108

    
109
#ifndef ROBOT
110
static void do_nothing(void) {}
111
static int get_nothing(void) {return -1;}
112
#endif
113

    
114
#ifdef ROBOT
115
#ifndef FIREFLY
116
static void (*bom_on_function) (void) = bom_on;
117
static void (*bom_off_function) (void) = bom_off;
118
static int (*get_max_bom_function) (void) = get_max_bom;
119
#else
120
static void (*bom_on_function) (void) = do_nothing;
121
static void (*bom_off_function) (void) = do_nothing;
122
static int (*get_max_bom_function) (void) = get_nothing;
123
#endif
124
#else
125
static void (*bom_on_function) (void) = do_nothing;
126
static void (*bom_off_function) (void) = do_nothing;
127
static int (*get_max_bom_function) (void) = get_nothing;
128
#endif
129

    
130
static PacketGroupHandler wl_token_ring_handler =
131
        {WL_TOKEN_RING_GROUP, wl_token_ring_timeout_handler,
132
                wl_token_ring_response_handler, wl_token_ring_receive_handler,
133
                wl_token_ring_cleanup};
134

    
135
/**
136
 * Causes the robot to join an existing token ring, or create one
137
 * if no token ring exists. The token ring uses global and robot to robot
138
 * packets, and does not rely on any PAN.
139
 **/
140
int wl_token_ring_join()
141
{
142
        WL_DEBUG_PRINT("Joining the token ring.\r\n");
143

    
144
        ringState = JOINING;
145
        joinDelay = DEATH_DELAY * 2;
146
        if (wl_send_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_JOIN, NULL, 0, 0) != 0) {
147
                return -1;
148
        }
149

    
150
        return 0;
151
}
152

    
153
/**
154
 * Causes the robot to leave the token ring. The robot stops
155
 * alerting others of its location, but continues storing the
156
 * locations of other robots.
157
 **/
158
void wl_token_ring_leave()
159
{
160
        ringState = LEAVING;
161
}
162

    
163
/**
164
 * Initialize the token ring packet group and register it with the
165
 * wireless library. The robot will not join a token ring.
166
 **/
167
int wl_token_ring_register()
168
{
169
        if (wl_get_xbee_id() > 0xFF)
170
        {
171
                //Note: if this becomes an issue (unlikely), we could limit sensor information
172
                //to half a byte and use 12 bits for the id
173
                WL_DEBUG_PRINT("XBee ID must be single byte for token ring, is ");
174
                WL_DEBUG_PRINT_INT(wl_get_xbee_id());
175
                WL_DEBUG_PRINT(".\r\n");
176
                return -1;
177
        }
178

    
179
        sensor_matrix_create();
180
        //add ourselves to the sensor matrix
181
        sensor_matrix_set_in_ring(wl_get_xbee_id(), 0);
182

    
183
        wl_register_packet_group(&wl_token_ring_handler);
184

    
185
        return 0;
186
}
187

    
188
/**
189
 * Removes the packet group from the wireless library.
190
 **/
191
void wl_token_ring_unregister()
192
{
193
        wl_unregister_packet_group(&wl_token_ring_handler);
194
}
195

    
196
/**
197
 * Sets the functions that are called when the BOM ought to be
198
 * turned on or off. This could be used for things such as
199
 * charging stations, which have multiple BOMs.
200
 *
201
 * @param on_function the function to be called when the BOM
202
 * should be turned on
203
 * @param off_function the function to be called when the BOM
204
 * should be turned off
205
 * @param max_bom_function the function to be called when a
206
 * measurement of the maximum BOM reading is needed.
207
 **/
208
void wl_token_ring_set_bom_functions(void (*on_function) (void),
209
        void (*off_function) (void), int (*max_bom_function) (void))
210
{
211
        bom_on_function = on_function;
212
        bom_off_function = off_function;
213
        get_max_bom_function = max_bom_function;
214
}
215

    
216
/**
217
 * Called to cleanup the token ring packet group.
218
 **/
219
static void wl_token_ring_cleanup()
220
{
221
}
222

    
223
/**
224
 * Called approximately every quarter second by the wireless library.
225
 **/
226
static void wl_token_ring_timeout_handler()
227
{
228
        //someone is not responding, assume they are dead
229
        if (deathDelay == 0)
230
        {
231
                //pass the token to the next robot if we think someone has died
232
                //also, declare that person dead, as long as it isn't us
233
                if (wl_token_next_robot != wl_get_xbee_id())
234
                {
235
                        sensor_matrix_set_in_ring(wl_token_next_robot, 0);
236
                        WL_DEBUG_PRINT("Robot ");
237
                        WL_DEBUG_PRINT_INT(wl_token_next_robot);
238
                        WL_DEBUG_PRINT(" has died.\r\n");
239
                        wl_token_next_robot = -1;
240
                        deathDelay = DEATH_DELAY;
241
                }
242

    
243
                // we may have been dropped from the ring when this is received
244
                if (ringState == MEMBER) {
245
                        wl_token_pass_token();
246
                }
247
        }
248

    
249
        //we must start our own token ring, no one is responding to us
250
        if (joinDelay == 0)
251
        {
252
                if (sensor_matrix_get_joined() == 0)
253
                {
254
                        WL_DEBUG_PRINT("Creating our own token ring, no robots seem to exist.\r\n");
255
                        sensor_matrix_set_in_ring(wl_get_xbee_id(), 1);
256
                        ringState = MEMBER;
257
                        //this will make us pass the token to ourself
258
                        //repeatedly, and other robots when they join
259
                        deathDelay = DEATH_DELAY;
260
                        wl_token_next_robot = wl_get_xbee_id();
261
                }
262
                else
263
                {
264
                        WL_DEBUG_PRINT("Attempting to join the token ring again.\r\n");
265
                        //attempt to rejoin with a random delay
266
      //TODO: should we use the constant JOIN_DELAY ?
267
                        wl_token_ring_join();
268
                        joinDelay = rand() / (RAND_MAX / JOIN_DELAY) + 1;
269
                }
270
        }
271

    
272
        if (deathDelay >= 0) {
273
                deathDelay--;
274
        }
275

    
276
        if (joinDelay >= 0) {
277
                joinDelay--;
278
        }
279

    
280
        if (bom_on_count >= 0) {
281
                bom_on_count++;
282
        }
283
}
284

    
285
/**
286
 * Called when the XBee tells us if a packet we sent has been received.
287
 *
288
 * @param frame the frame number assigned when the packet was sent
289
 * @param received 1 if the packet was received, 0 otherwise
290
 **/
291
static void wl_token_ring_response_handler(int frame, int received)
292
{
293
        if (!received)
294
        {
295
                WL_DEBUG_PRINT("FAILED.\r\n");
296
        }
297
}
298

    
299
/**
300
 * Called when we recieve a token ring packet.
301
 * @param type the type of the packet
302
 * @param source the id of the robot who sent the packet
303
 * @param packet the data in the packet
304
 * @param length the length of the packet in bytes
305
 **/
306
static void wl_token_ring_receive_handler(char type, int source, unsigned char* packet, int length)
307
{
308
        switch (type)
309
        {
310
                case WL_TOKEN_PASS:
311
                        wl_token_pass_receive(source);
312
                        break;
313
                case WL_TOKEN_SENSOR_MATRIX:
314
                        wl_token_sensor_matrix_receive(source, packet, length);
315
                        break;
316
                case WL_TOKEN_BOM_ON:
317
                        //add the robot to the sensor matrix if it is not already there
318
                        wl_token_bom_on_receive(source);
319
                        break;
320
                case WL_TOKEN_JOIN:
321
                        wl_token_join_receive(source);
322
                        break;
323
                case WL_TOKEN_JOIN_ACCEPT:
324
                        wl_token_join_accept_receive(source);
325
                        break;
326
                default:
327
                        WL_DEBUG_PRINT("Unimplemented token ring packet received.\r\n");
328
                        break;
329
        }
330
}
331

    
332
/**
333
 * Returns the BOM reading robot source has for robot dest.
334
 *
335
 * @param source the robot that made the BOM reading
336
 * @param dest the robot whose relative location is returned
337
 *
338
 * @return a BOM reading from robot source to robot dest,
339
 * in the range 0-15, or -1 if it is unknown
340
 **/
341
int wl_token_get_sensor_reading(int source, int dest)
342
{
343
        if (wl_token_is_robot_in_ring(dest) &&
344
                        (source == wl_get_xbee_id() || wl_token_is_robot_in_ring(source))) {
345
                return sensor_matrix_get_reading(source, dest);
346
        }
347

    
348
        return -1;
349
}
350

    
351
/**
352
 * Returns the BOM reading we have for robot dest.
353
 *
354
 * @param dest the robot whose relative location is returned
355
 *
356
 * @return a BOM reading from us to robot dest, in the range
357
 * 0-15, or -1 if it is unkown
358
 **/
359
int wl_token_get_my_sensor_reading(int dest)
360
{
361
        return wl_token_get_sensor_reading(wl_get_xbee_id(), dest);
362
}
363

    
364

    
365
/**
366
 * Returns the number of robots in the token ring.
367
 *
368
 * @return the number of robots in the token ring
369
 **/
370
int wl_token_get_robots_in_ring(void)
371
{
372
        return sensor_matrix_get_joined();
373
}
374

    
375
/**
376
 * Returns true if the specified robot is in the token ring, false
377
 * otherwise.
378
 *
379
 * @param robot the robot to check for whether it is in the token ring
380
 * @return nonzero if the robot is in the token ring, zero otherwise
381
 **/
382
int wl_token_is_robot_in_ring(int robot)
383
{
384
        return sensor_matrix_get_in_ring(robot);
385
}
386

    
387
/**
388
 * Begins iterating through the robots in the token ring.
389
 *
390
 * @see wl_token_iterator_has_next, wl_token_iterator_next
391
 **/
392
void wl_token_iterator_begin(void)
393
{
394
        int i = 0;
395
  //TODO: the compiler may or may not optimize this such that my comment is useless:
396
  // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
397
  // the overhead of a function call each iteration, call it only once before the loop and store
398
  // the value in a variable and check against that variable in the loop condition
399
        while (!sensor_matrix_get_in_ring(i) && i < sensor_matrix_get_size()) {
400
                i++;
401
        }
402

    
403
  //TODO: if you do the above comment, then you can compare this to the variable also
404
        if (i == sensor_matrix_get_size()) {
405
                i = -1;
406
        }
407

    
408
        iteratorCount = i;
409
}
410

    
411
/**
412
 * Returns true if there are more robots in the token ring
413
 * to iterate through, and false otherwise.
414
 *
415
 * @return nonzero if there are more robots to iterate through,
416
 * zero otherwise
417
 *
418
 * @see wl_token_iterator_begin, wl_token_iterator_next
419
 **/
420
int wl_token_iterator_has_next(void)
421
{
422
        return iteratorCount != -1;
423
}
424

    
425
/**
426
 * Returns the next robot ID in the token ring.
427
 *
428
 * @return the next robot ID in the token ring, or -1 if none exists
429
 *
430
 * @see wl_token_iterator_begin, wl_token_iterator_has_next
431
 **/
432
int wl_token_iterator_next(void)
433
{
434
        int result = iteratorCount;
435
        if (result < 0) {
436
                return result;
437
        }
438

    
439
  //TODO: the compiler may or may not optimize this such that my comment is useless:
440
  // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
441
  // the overhead of a function call each iteration, call it only once before the loop and store
442
  // the value in a variable and check against that variable in the loop condition
443
        iteratorCount++;
444
        while (!sensor_matrix_get_in_ring(iteratorCount)
445
                && iteratorCount < sensor_matrix_get_size()) {
446
                iteratorCount++;
447
        }
448

    
449
  //TODO: if you do the above comment, then you can compare this to the variable also
450
        if (iteratorCount == sensor_matrix_get_size()) {
451
                iteratorCount = -1;
452
        }
453

    
454
        return result;
455
}
456

    
457
/**
458
 * Returns the number of robots currently in the token ring.
459
 *
460
 * @return the number of robots in the token ring
461
 **/
462
int wl_token_get_num_robots(void)
463
{
464
        return sensor_matrix_get_joined();
465
}
466

    
467
/**
468
 * Returns the number of robots in the sensor matrix.
469
 *
470
 * @return the number of robots in the sensor matrix
471
 **/
472
int wl_token_get_matrix_size(void)
473
{
474
        return sensor_matrix_get_size();
475
}
476

    
477
/**
478
 * This method is called when we receive a token pass packet.
479
 *
480
 * @param source the robot who passed the token to us.
481
 **/
482
static void wl_token_pass_receive(int source)
483
{
484
        WL_DEBUG_PRINT("Received token from ");
485
        WL_DEBUG_PRINT_INT(source);
486
        WL_DEBUG_PRINT(", expected ");
487
        WL_DEBUG_PRINT_INT(wl_token_next_robot);
488
        WL_DEBUG_PRINT(".\n");
489
        // this prevents two tokens from being passed around at a time (second clause is in case we are joining)
490
        if ((source != wl_token_next_robot && wl_get_xbee_id() != wl_token_next_robot) && bom_on_count <= DEATH_DELAY / 2 &&
491
                ringState != ACCEPTED)
492
        {
493
                WL_DEBUG_PRINT("Received token pass when a robot should not have died yet.\n");
494
                WL_DEBUG_PRINT("There are probably two tokens going around, packet ignored.\n");
495
                return;
496
        }
497
        bom_on_count = -1;
498
        deathDelay = -1;
499
        sensor_matrix_set_in_ring(source, 1);
500
        wl_token_get_token();
501
}
502

    
503
/**
504
 * This method is called when we receive a token pass packet.
505
 * @param source is the robot it came from
506
 * @param nextRobot is the robot the token was passed to
507
 * @param sensorData a char with an id followed by a char with the sensor
508
 *                reading for that robot, repeated for sensorDataLength bytes
509
 * @param sensorDataLength the length in bytes of sensorData
510
 */
511
static void wl_token_sensor_matrix_receive(int source, unsigned char* sensorData, int sensorDataLength)
512
{
513
        int i, j;
514
        char nextRobot;
515

    
516
        bom_on_count = -1;
517
        deathDelay = -1;
518
        sensor_matrix_set_in_ring(source, 1);
519

    
520
        //with this packet, we are passed the id of the next robot in the ring
521
        //and the sensor matrix, a list of id and sensor reading pairs (two bytes for both)
522
        j = 0;
523
  //TODO: the compiler may or may not optimize this such that my comment is useless:
524
  // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
525
  // the overhead of a function call each iteration, call it only once before the loop and store
526
  // the value in a variable and check against that variable in the loop condition
527
        for (i = 0; i < sensor_matrix_get_size(); i++)
528
        {
529
                if (i == source) {
530
                        continue;
531
                }
532

    
533
                //set the sensor information we receive
534
                if (j < sensorDataLength / 2 && sensorData[2 * j] == i)
535
                {
536
                        //the robot we were going to accept has already been accepted
537
                        if (accepted == i)
538
                        {
539
                                accepted = -1;
540
                                WL_DEBUG_PRINT("Someone accepted the robot we did.\r\n");
541
                        }
542
                        sensor_matrix_set_reading(source, i,
543
                                                sensorData[2 * j + 1]);
544
                        if (!sensor_matrix_get_in_ring(i))
545
                        {
546
                                WL_DEBUG_PRINT("Robot ");
547
                                WL_DEBUG_PRINT_INT(i);
548
                                WL_DEBUG_PRINT(" has been added to the sensor matrix of robot ");
549
                                WL_DEBUG_PRINT_INT(wl_get_xbee_id());
550
                                WL_DEBUG_PRINT(" due to a packet from robot ");
551
                                WL_DEBUG_PRINT_INT(source);
552
                                WL_DEBUG_PRINT(".\r\n");
553
                        }
554
                        sensor_matrix_set_in_ring(i, 1);
555
                        j++;
556
                }
557
                else
558
                {
559
                        if (sensor_matrix_get_in_ring(i))
560
                        {
561
                                WL_DEBUG_PRINT("Robot ");
562
                                WL_DEBUG_PRINT_INT(i);
563
                                WL_DEBUG_PRINT(" has been removed from the sensor matrix of robot ");
564
                                WL_DEBUG_PRINT_INT(wl_get_xbee_id());
565
                                WL_DEBUG_PRINT(" due to a packet from robot ");
566
                                WL_DEBUG_PRINT_INT(source);
567
                                WL_DEBUG_PRINT(".\r\n");
568
                                sensor_matrix_set_in_ring(i, 0);
569
                        }
570

    
571
                        if (i == wl_get_xbee_id() && ringState == MEMBER)
572
                        {
573
                                ringState = NONMEMBER;
574
                                wl_token_ring_join();
575

    
576
                                WL_DEBUG_PRINT("We have been removed from the ring ");
577
                                WL_DEBUG_PRINT("and are rejoining.\r\n");
578
                        }
579

    
580
                        //the person who accepted us is dead... let's ask again
581
                        if (i == acceptor)
582
                        {
583
                                sensor_matrix_set_in_ring(wl_get_xbee_id(), 0);
584
                                ringState = NONMEMBER;
585
                                acceptor = -1;
586
                                wl_token_ring_join();
587
                        }
588
                }
589
        }
590
        
591
        // get the next robot in the token ring
592
        i = source + 1;
593
        while (1)
594
        {
595
                if (i == sensor_matrix_get_size()) {
596
                        i = 0;
597
                }
598

    
599
                if (sensor_matrix_get_in_ring(i) || i == source)
600
                {
601
                        nextRobot = (char)i;
602
                        break;
603
                }
604

    
605
                i++;
606
        }
607

    
608
        if (nextRobot != wl_get_xbee_id())
609
                wl_token_next_robot = nextRobot;
610

    
611
        deathDelay = get_token_distance(wl_get_xbee_id(), nextRobot) * DEATH_DELAY;
612

    
613
        if (sensor_matrix_get_joined() == 0 && ringState == JOINING)
614
                wl_send_robot_to_robot_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_PASS, NULL, 0, nextRobot, WL_TOKEN_PASS_FRAME);
615
}
616

    
617
/**
618
 * Gets the distance in the token ring between two robots.
619
 *
620
 * @param robot1 the first robot
621
 * @param robot2 the second robot
622
 *
623
 * @return the number of passes before the token is expected
624
 * to reach robot2 from robot1
625
 **/
626
static int get_token_distance(int robot1, int robot2)
627
{
628
        int curr = robot1 + 1;
629
        int count = 1;
630
        while (1)
631
        {
632
    //TODO: the compiler may or may not optimize this such that my comment is useless:
633
    // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
634
    // the overhead of a function call each iteration, call it only once before the loop and store
635
    // the value in a variable and check against that variable in the loop condition
636
                if (curr == sensor_matrix_get_size())
637
                        curr = 0;
638
                if (curr == robot2)
639
                        break;
640
                if (sensor_matrix_get_in_ring(curr))
641
                        count++;
642
                curr++;
643
        }
644
        return count;
645
}
646

    
647
/**
648
 * Passes the token to the next robot in the token ring.
649
 **/
650
static int wl_token_pass_token()
651
{
652
        char nextRobot = 0xFF;
653
        int i = wl_get_xbee_id() + 1;
654
        char buf[2 * sensor_matrix_get_size()];
655
        if (accepted == -1)
656
        {
657
                while (1)
658
                {
659
      //TODO: the compiler may or may not optimize this such that my comment is useless:
660
      // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
661
      // the overhead of a function call each iteration, call it only once before the loop and store
662
      // the value in a variable and check against that variable in the loop condition
663
                        if (i == sensor_matrix_get_size()) {
664
                                i = 0;
665
                        }
666

    
667
                        if (sensor_matrix_get_in_ring(i))
668
                        {
669
                                nextRobot = (char)i;
670
                                break;
671
                        }
672

    
673
                        i++;
674
                }
675
        }
676
        else
677
        {
678
                WL_DEBUG_PRINT("Accepting new robot, sending it the token.\r\n");
679
                //add a new robot to the token ring
680
                sensor_matrix_set_in_ring(accepted, 1);
681
                nextRobot = accepted;
682
                accepted = -1;
683
        }
684

    
685
        int j = 0;
686
  //TODO: the compiler may or may not optimize this such that my comment is useless:
687
  // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
688
  // the overhead of a function call each iteration, call it only once before the loop and store
689
  // the value in a variable and check against that variable in the loop condition
690
        for (i = 0; i < sensor_matrix_get_size(); i++) {
691
                if (sensor_matrix_get_in_ring(i) && i != wl_get_xbee_id())
692
                {
693
                        buf[2*j] = i;
694
                        buf[2*j + 1] = sensor_matrix_get_reading(wl_get_xbee_id(), i);
695
                        j++;
696
                }
697
        }
698

    
699
        int packetSize = 2 * j * sizeof(char);
700
        WL_DEBUG_PRINT("Passing the token to robot ");
701
        WL_DEBUG_PRINT_INT(nextRobot);
702
        WL_DEBUG_PRINT(".\r\n");
703
        if (wl_send_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_SENSOR_MATRIX, buf, packetSize, 0) != 0)
704
                return -1;
705
        if (wl_send_robot_to_robot_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_PASS, NULL, 0, nextRobot, WL_TOKEN_PASS_FRAME))
706
                return -1;
707

    
708
        wl_token_next_robot = nextRobot;
709
        deathDelay = DEATH_DELAY;
710

    
711
        return 0;
712
}
713

    
714
/**
715
 * Called when a packet is received stating that another robot has turned
716
 * its BOM on. Our BOM is then read, and the data is added to the sensor
717
 * matrix.
718
 *
719
 * @param source the robot whose BOM is on
720
 **/
721
static void wl_token_bom_on_receive(int source)
722
{
723
        int max;
724

    
725
        WL_DEBUG_PRINT("Robot ");
726
        WL_DEBUG_PRINT_INT(source);
727
        WL_DEBUG_PRINT(" has flashed its bom.\r\n");
728

    
729
        bom_on_count = 0;
730

    
731
        max = get_max_bom_function();
732
        sensor_matrix_set_reading(wl_get_xbee_id(),
733
                source, max);
734

    
735
        WL_DEBUG_PRINT("Max: ");
736
        WL_DEBUG_PRINT_INT(max);
737
        WL_DEBUG_PRINT("\n\n");
738
}
739

    
740
/**
741
 * This method is called when we receive the token. Upon receiving
742
 * the token, we must send a BOM_ON packet, flash the BOM, and send
743
 * the token to the next robot.
744
 *
745
 * If there is a pending request for the token, this is processed first.
746
 **/
747
static void wl_token_get_token()
748
{
749
        WL_DEBUG_PRINT("We have the token.\r\n");
750
        if (ringState == ACCEPTED)
751
        {
752
                sensor_matrix_set_in_ring(wl_get_xbee_id(), 1);
753
                WL_DEBUG_PRINT("Now a member of the token ring.\r\n");
754
                ringState = MEMBER;
755
                joinDelay = -1;
756
        }
757

    
758
        if (ringState == LEAVING || ringState == NONMEMBER)
759
        {
760
                sensor_matrix_set_in_ring(wl_get_xbee_id(), 0);
761
                if (ringState == NONMEMBER)
762
                {
763
                        WL_DEBUG_PRINT("We should have left the token ring, but didn't.\r\n");
764
                }
765
                return;
766
        }
767

    
768
        WL_DEBUG_PRINT("Our BOM has been flashed.\r\n");
769
        wl_send_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_BOM_ON, NULL, 0, 0);
770

    
771
        bom_on_function();
772
        #ifdef ROBOT
773
        delay_ms(BOM_DELAY);
774
        #endif
775
        bom_off_function();
776

    
777
        if (!sensor_matrix_get_in_ring(wl_get_xbee_id()))
778
        {
779
                WL_DEBUG_PRINT("Removed from sensor matrix while flashing BOM.\r\n");
780
                return;
781
        }
782

    
783
        wl_token_pass_token();
784
}
785

    
786
/**
787
 * Called when a request to join the token ring is received.
788
 * If we are the robot preceding the requester in the ring,
789
 * we respond with a JOIN_ACCEPT packet and pass the token to
790
 * this robot when we receive the token.
791
 *
792
 * @param source the robot who requested to join
793
 **/
794
static void wl_token_join_receive(int source)
795
{
796
        WL_DEBUG_PRINT("Received joining request from robot ");
797
        WL_DEBUG_PRINT_INT(source);
798
        WL_DEBUG_PRINT(".\r\n");
799

    
800
        //we cannot accept the request if we are not a member
801
        if (ringState != MEMBER)
802
                return;
803
        //if they didn't get our response, see if we should respond again
804
        if (accepted == source)
805
                accepted = -1;
806
        //we can only accept one request at a time
807
        if (accepted != -1)
808
                return;
809

    
810
        //check if we are the preceding robot in the token ring
811
        int i = source - 1;
812
        while (1)
813
        {
814
                if (i < 0)
815
                        i = sensor_matrix_get_size() - 1;
816

    
817
                //we must send a join acceptance
818
                if (i == wl_get_xbee_id())
819
                        break;
820

    
821
                //another robot will handle it
822
                if (sensor_matrix_get_in_ring(i))
823
                        return;
824

    
825
                i--;
826
        }
827

    
828
        accepted = source;
829
        wl_send_robot_to_robot_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_JOIN_ACCEPT,
830
                NULL, 0, source, TOKEN_JOIN_ACCEPT_FRAME);
831

    
832
        WL_DEBUG_PRINT("Accepting robot ");
833
        WL_DEBUG_PRINT_INT(source);
834
        WL_DEBUG_PRINT(" into the token ring.\r\n");
835

    
836
        // the token ring has not started yet
837
        if (sensor_matrix_get_joined() == 1)
838
                wl_token_pass_token();
839
}
840

    
841
/**
842
 * Called when we receive a JOIN_ACCEPT packet in attempting to join
843
 * the token ring.
844
 * Our attempt to join the ring is stopped, and we wait for the token.
845
 *
846
 * @param source the robot who accepted us
847
 **/
848
static void wl_token_join_accept_receive(int source)
849
{
850
        WL_DEBUG_PRINT("Accepted into the token ring by robot ");
851
        WL_DEBUG_PRINT_INT(source);
852
        WL_DEBUG_PRINT(".\r\n");
853
        joinDelay = JOIN_DELAY;
854
        ringState = ACCEPTED;
855
        acceptor = source;
856

    
857
        //add ourselves to the token ring
858
        sensor_matrix_set_in_ring(wl_get_xbee_id(), 1);
859
}