Project

General

Profile

Statistics
| Revision:

root / trunk / code / projects / libwireless / lib / wl_token_ring.c @ 717

History | View | Annotate | Download (24.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 <wl_token_ring.h>
36

    
37
#include <stdlib.h>
38
#include <stdio.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
//TODO: why is this in both this file and sensor_matrix.c?  If it is needed in both places,
52
// put it in sensor_matrix.h.  This file already includes sensor_matrix.h
53
#define DEFAULT_SENSOR_MATRIX_SIZE 20
54

    
55
/*Ring States*/
56

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

    
63
/*Frame Types*/
64
#define TOKEN_JOIN_ACCEPT_FRAME 1
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, char nextRobot, unsigned char* sensorData, int sensorDataLength);
81
static void wl_token_bom_on_receive(int source);
82
static void wl_token_join_receive(int source);
83
static void wl_token_join_accept_receive(int source);
84

    
85
/*Global Variables*/
86

    
87
//the sensor matrix
88
static SensorMatrix* sensorMatrix;
89

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

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

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

    
105
//current robot to check in the iterator
106
static int iteratorCount = 0;
107

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

    
111
static void do_nothing(void) {}
112
static int get_nothing(void) {return -1;}
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
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
159
// it reduces code size or not should be done to be sure.
160
void wl_token_ring_leave()
161
{
162
        ringState = LEAVING;
163
}
164

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

    
181
        sensorMatrix = sensor_matrix_create();
182
        //add ourselves to the sensor matrix
183
        sensor_matrix_set_in_ring(sensorMatrix, wl_get_xbee_id(), 0);
184

    
185
        wl_register_packet_group(&wl_token_ring_handler);
186

    
187
        return 0;
188
}
189

    
190
/**
191
 * Removes the packet group from the wireless library.
192
 **/
193
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
194
// it reduces code size or not should be done to be sure.
195
void wl_token_ring_unregister()
196
{
197
        wl_unregister_packet_group(&wl_token_ring_handler);
198
}
199

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

    
220
/**
221
 * Called to cleanup the token ring packet group.
222
 **/
223
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
224
// it reduces code size or not should be done to be sure.
225
static void wl_token_ring_cleanup()
226
{
227
        sensor_matrix_destroy(sensorMatrix);
228
}
229

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

    
250
                // we may have been dropped from the ring when this is received
251
                if (ringState == MEMBER) {
252
                        wl_token_pass_token();
253
                }
254
        }
255

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

    
278
        if (deathDelay >= 0) {
279
                deathDelay--;
280
        }
281

    
282
        if (joinDelay >= 0) {
283
                joinDelay--;
284
        }
285

    
286
        if (bom_on_count >= 0) {
287
                bom_on_count++;
288
        }
289
}
290

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

    
305
/**
306
 * Called when we recieve a token ring packet.
307
 * @param type the type of the packet
308
 * @param source the id of the robot who sent the packet
309
 * @param packet the data in the packet
310
 * @param length the length of the packet in bytes
311
 **/
312
static void wl_token_ring_receive_handler(char type, int source, unsigned char* packet, int length)
313
{
314
        switch (type)
315
        {
316
                case WL_TOKEN_PASS:
317
                        if (length < 1)
318
                        {
319
                                WL_DEBUG_PRINT("Malformed Token Pass packet received.\r\n");
320
                                return;
321
                        }
322
                        wl_token_pass_receive(source, packet[0], packet + 1, length - 1);
323
                        break;
324
                case WL_TOKEN_BOM_ON:
325
                        //add the robot to the sensor matrix if it is not already there
326
                        wl_token_bom_on_receive(source);
327
                        break;
328
                case WL_TOKEN_JOIN:
329
                        wl_token_join_receive(source);
330
                        break;
331
                case WL_TOKEN_JOIN_ACCEPT:
332
                        wl_token_join_accept_receive(source);
333
                        break;
334
                default:
335
                        WL_DEBUG_PRINT("Unimplemented token ring packet received.\r\n");
336
                        break;
337
        }
338
}
339

    
340
/**
341
 * Returns the BOM reading robot source has for robot dest.
342
 *
343
 * @param source the robot that made the BOM reading
344
 * @param dest the robot whose relative location is returned
345
 *
346
 * @return a BOM reading from robot source to robot dest,
347
 * in the range 0-15, or -1 if it is unknown
348
 **/
349
int wl_token_get_sensor_reading(int source, int dest)
350
{
351
        if (wl_token_is_robot_in_ring(dest) &&
352
                        (source == wl_get_xbee_id() || wl_token_is_robot_in_ring(source))) {
353
                return sensor_matrix_get_reading(sensorMatrix, source, dest);
354
        }
355

    
356
        return -1;
357
}
358

    
359
/**
360
 * Returns the BOM reading we have for robot dest.
361
 *
362
 * @param dest the robot whose relative location is returned
363
 *
364
 * @return a BOM reading from us to robot dest, in the range
365
 * 0-15, or -1 if it is unkown
366
 **/
367
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
368
// it reduces code size or not should be done to be sure.
369
int wl_token_get_my_sensor_reading(int dest)
370
{
371
        return wl_token_get_sensor_reading(wl_get_xbee_id(), dest);
372
}
373

    
374

    
375
/**
376
 * Returns the number of robots in the token ring.
377
 *
378
 * @return the number of robots in the token ring
379
 **/
380
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
381
// it reduces code size or not should be done to be sure.
382
int wl_token_get_robots_in_ring(void)
383
{
384
        return sensor_matrix_get_joined(sensorMatrix);
385
}
386

    
387
/**
388
 * Returns true if the specified robot is in the token ring, false
389
 * otherwise.
390
 *
391
 * @param robot the robot to check for whether it is in the token ring
392
 * @return nonzero if the robot is in the token ring, zero otherwise
393
 **/
394
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
395
// it reduces code size or not should be done to be sure.
396
int wl_token_is_robot_in_ring(int robot)
397
{
398
        return sensor_matrix_get_in_ring(sensorMatrix, robot);
399
}
400

    
401
/**
402
 * Begins iterating through the robots in the token ring.
403
 *
404
 * @see wl_token_iterator_has_next, wl_token_iterator_next
405
 **/
406
void wl_token_iterator_begin(void)
407
{
408
        int i = 0;
409
  //TODO: the compiler may or may not optimize this such that my comment is useless:
410
  // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
411
  // the overhead of a function call each iteration, call it only once before the loop and store
412
  // the value in a variable and check against that variable in the loop condition
413
        while (!sensor_matrix_get_in_ring(sensorMatrix, i) && i < sensor_matrix_get_size(sensorMatrix)) {
414
                i++;
415
        }
416

    
417
  //TODO: if you do the above comment, then you can compare this to the variable also
418
        if (i == sensor_matrix_get_size(sensorMatrix)) {
419
                i = -1;
420
        }
421

    
422
        iteratorCount = i;
423
}
424

    
425
/**
426
 * Returns true if there are more robots in the token ring
427
 * to iterate through, and false otherwise.
428
 *
429
 * @return nonzero if there are more robots to iterate through,
430
 * zero otherwise
431
 *
432
 * @see wl_token_iterator_begin, wl_token_iterator_next
433
 **/
434
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
435
// it reduces code size or not should be done to be sure.
436
int wl_token_iterator_has_next(void)
437
{
438
        return iteratorCount != -1;
439
}
440

    
441
/**
442
 * Returns the next robot ID in the token ring.
443
 *
444
 * @return the next robot ID in the token ring, or -1 if none exists
445
 *
446
 * @see wl_token_iterator_begin, wl_token_iterator_has_next
447
 **/
448
int wl_token_iterator_next(void)
449
{
450
        int result = iteratorCount;
451
        if (result < 0) {
452
                return result;
453
        }
454

    
455
  //TODO: the compiler may or may not optimize this such that my comment is useless:
456
  // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
457
  // the overhead of a function call each iteration, call it only once before the loop and store
458
  // the value in a variable and check against that variable in the loop condition
459
        iteratorCount++;
460
        while (!sensor_matrix_get_in_ring(sensorMatrix, iteratorCount)
461
                && iteratorCount < sensor_matrix_get_size(sensorMatrix)) {
462
                iteratorCount++;
463
        }
464

    
465
  //TODO: if you do the above comment, then you can compare this to the variable also
466
        if (iteratorCount == sensor_matrix_get_size(sensorMatrix)) {
467
                iteratorCount = -1;
468
        }
469

    
470
        return result;
471
}
472

    
473
/**
474
 * Returns the number of robots currently in the token ring.
475
 *
476
 * @return the number of robots in the token ring
477
 **/
478
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
479
// it reduces code size or not should be done to be sure.
480
int wl_token_get_num_robots(void)
481
{
482
        return sensor_matrix_get_joined(sensorMatrix);
483
}
484

    
485
/**
486
 * Returns the number of robots in the sensor matrix.
487
 *
488
 * @return the number of robots in the sensor matrix
489
 **/
490
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
491
// it reduces code size or not should be done to be sure.
492
int wl_token_get_matrix_size(void)
493
{
494
        return sensor_matrix_get_size(sensorMatrix);
495
}
496

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

    
509
        // this prevents two tokens from being passed around at a time (second clause is in case we are joining)
510
        if (source != wl_token_next_robot && bom_on_count <= DEATH_DELAY / 2 &&
511
                ringState != ACCEPTED)
512
        {
513
                WL_DEBUG_PRINT("Received token pass when a robot should not have died yet.\n");
514
                WL_DEBUG_PRINT("There are probably two tokens going around, packet ignored.\n");
515
                return;
516
        }
517

    
518
        bom_on_count = -1;
519
        deathDelay = -1;
520
        WL_DEBUG_PRINT("Received the token from robot");
521
        WL_DEBUG_PRINT_INT(source);
522
        WL_DEBUG_PRINT(", next robot is ");
523
        WL_DEBUG_PRINT_INT((int)nextRobot);
524
        WL_DEBUG_PRINT(" \r\n");
525
        sensor_matrix_set_in_ring(sensorMatrix, source, 1);
526

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

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

    
568
                        if (i == wl_get_xbee_id() && ringState == MEMBER)
569
                        {
570
                                ringState = NONMEMBER;
571
                                wl_token_ring_join();
572

    
573
                                WL_DEBUG_PRINT("We have been removed from the ring ");
574
                                WL_DEBUG_PRINT("and are rejoining.\r\n");
575
                        }
576

    
577
                        //the person who accepted us is dead... let's ask again
578
                        if (i == acceptor)
579
                        {
580
                                sensor_matrix_set_in_ring(sensorMatrix,
581
                                                wl_get_xbee_id(), 1);
582
                                ringState = NONMEMBER;
583
                                acceptor = -1;
584
                                wl_token_ring_join();
585
                        }
586
                }
587
        }
588

    
589
        wl_token_next_robot = nextRobot;
590

    
591
        deathDelay = get_token_distance(wl_get_xbee_id(), nextRobot) * DEATH_DELAY;
592

    
593
        //we have the token
594
        if (wl_token_next_robot == wl_get_xbee_id()) {
595
                wl_token_get_token();
596
        }
597
}
598

    
599
/**
600
 * Gets the distance in the token ring between two robots.
601
 *
602
 * @param robot1 the first robot
603
 * @param robot2 the second robot
604
 *
605
 * @return the number of passes before the token is expected
606
 * to reach robot2 from robot1
607
 **/
608
static int get_token_distance(int robot1, int robot2)
609
{
610
        int curr = robot1 + 1;
611
        int count = 1;
612
        while (1)
613
        {
614
    //TODO: the compiler may or may not optimize this such that my comment is useless:
615
    // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
616
    // the overhead of a function call each iteration, call it only once before the loop and store
617
    // the value in a variable and check against that variable in the loop condition
618
                if (curr == sensor_matrix_get_size(sensorMatrix))
619
                        curr = 0;
620
                if (curr == robot2)
621
                        break;
622
                if (sensor_matrix_get_in_ring(sensorMatrix, curr))
623
                        count++;
624
                curr++;
625
        }
626
        return count;
627
}
628

    
629
/**
630
 * Passes the token to the next robot in the token ring.
631
 **/
632
static int wl_token_pass_token()
633
{
634
        char nextRobot;
635
        int i = wl_get_xbee_id() + 1;
636
        if (accepted == -1)
637
        {
638
                while (1)
639
                {
640
      //TODO: the compiler may or may not optimize this such that my comment is useless:
641
      // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
642
      // the overhead of a function call each iteration, call it only once before the loop and store
643
      // the value in a variable and check against that variable in the loop condition
644
                        if (i == sensor_matrix_get_size(sensorMatrix)) {
645
                                i = 0;
646
                        }
647

    
648
                        if (sensor_matrix_get_in_ring(sensorMatrix, i))
649
                        {
650
                                nextRobot = (char)i;
651
                                break;
652
                        }
653

    
654
                        i++;
655
                }
656
        }
657
        else
658
        {
659
                WL_DEBUG_PRINT("Accepting new robot, sending it the token.\r\n");
660
                //add a new robot to the token ring
661
                sensor_matrix_set_in_ring(sensorMatrix, accepted, 1);
662
                nextRobot = accepted;
663
                accepted = -1;
664
        }
665

    
666
        //we don't include ourself
667
        int packetSize = 1 + 2 * (sensor_matrix_get_joined(sensorMatrix) - 1);
668
        char* buf = (char*)malloc(packetSize * sizeof(char));
669
        if (!buf)
670
        {
671
                WL_DEBUG_PRINT_INT(packetSize);
672
                WL_DEBUG_PRINT("Out of memory - pass token.\r\n");
673
                free(buf);
674
                return -1;
675
        }
676
        buf[0] = nextRobot;
677

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

    
692
        WL_DEBUG_PRINT("Passing the token to robot ");
693
        WL_DEBUG_PRINT_INT(buf[0]);
694
        WL_DEBUG_PRINT(".\r\n");
695
        if (wl_send_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_PASS, buf, packetSize, 3) != 0) {
696
                free(buf);
697
                return -1;
698
        }
699

    
700
        wl_token_next_robot = nextRobot;
701
        deathDelay = DEATH_DELAY;
702
        free(buf);
703

    
704
        return 0;
705
}
706

    
707
/**
708
 * Called when a packet is received stating that another robot has turned
709
 * its BOM on. Our BOM is then read, and the data is added to the sensor
710
 * matrix.
711
 *
712
 * @param source the robot whose BOM is on
713
 **/
714
static void wl_token_bom_on_receive(int source)
715
{
716
        WL_DEBUG_PRINT("Robot ");
717
        WL_DEBUG_PRINT_INT(source);
718
        WL_DEBUG_PRINT(" has flashed its bom.\r\n");
719

    
720
        bom_on_count = 0;
721

    
722
        sensor_matrix_set_reading(sensorMatrix, wl_get_xbee_id(),
723
                source, get_max_bom_function());
724
}
725

    
726
/**
727
 * This method is called when we receive the token. Upon receiving
728
 * the token, we must send a BOM_ON packet, flash the BOM, and send
729
 * the token to the next robot.
730
 *
731
 * If there is a pending request for the token, this is processed first.
732
 **/
733
static void wl_token_get_token()
734
{
735
        WL_DEBUG_PRINT("We have the token.\r\n");
736
        if (ringState == ACCEPTED)
737
        {
738
                sensor_matrix_set_in_ring(sensorMatrix, wl_get_xbee_id(), 1);
739
                WL_DEBUG_PRINT("Now a member of the token ring.\r\n");
740
                ringState = MEMBER;
741
                joinDelay = -1;
742
        }
743

    
744
        if (ringState == LEAVING || ringState == NONMEMBER)
745
        {
746
                sensor_matrix_set_in_ring(sensorMatrix, wl_get_xbee_id(), 0);
747
                if (ringState == NONMEMBER)
748
                {
749
                        WL_DEBUG_PRINT("We should have left the token ring, but didn't.\r\n");
750
                }
751
                return;
752
        }
753

    
754
        WL_DEBUG_PRINT("Our BOM has been flashed.\r\n");
755
        wl_send_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_BOM_ON, NULL, 0, 0);
756

    
757
        bom_on_function();
758
        #ifdef ROBOT
759
        delay_ms(BOM_DELAY);
760
        #endif
761
        bom_off_function();
762

    
763
        if (!sensor_matrix_get_in_ring(sensorMatrix, wl_get_xbee_id()))
764
        {
765
                WL_DEBUG_PRINT("Removed from sensor matrix while flashing BOM.\r\n");
766
                return;
767
        }
768

    
769
        wl_token_pass_token();
770
}
771

    
772
/**
773
 * Called when a request to join the token ring is received.
774
 * If we are the robot preceding the requester in the ring,
775
 * we respond with a JOIN_ACCEPT packet and pass the token to
776
 * this robot when we receive the token.
777
 *
778
 * @param source the robot who requested to join
779
 **/
780
static void wl_token_join_receive(int source)
781
{
782
        WL_DEBUG_PRINT("Received joining request from robot ");
783
        WL_DEBUG_PRINT_INT(source);
784
        WL_DEBUG_PRINT(".\r\n");
785

    
786
        //we cannot accept the request if we are not a member
787
        if (ringState != MEMBER)
788
                return;
789
        //if they didn't get our response, see if we should respond again
790
        if (accepted == source)
791
                accepted = -1;
792
        //we can only accept one request at a time
793
        if (accepted != -1)
794
                return;
795

    
796
        //check if we are the preceding robot in the token ring
797
        int i = source - 1;
798
        while (1)
799
        {
800
                if (i < 0)
801
                        i = sensor_matrix_get_size(sensorMatrix) - 1;
802

    
803
                //we must send a join acceptance
804
                if (i == wl_get_xbee_id())
805
                        break;
806

    
807
                //another robot will handle it
808
                if (sensor_matrix_get_in_ring(sensorMatrix, i))
809
                        return;
810

    
811
                i--;
812
        }
813

    
814
        accepted = source;
815
        wl_send_robot_to_robot_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_JOIN_ACCEPT,
816
                NULL, 0, source, TOKEN_JOIN_ACCEPT_FRAME);
817

    
818
        WL_DEBUG_PRINT("Accepting robot ");
819
        WL_DEBUG_PRINT_INT(source);
820
        WL_DEBUG_PRINT(" into the token ring.\r\n");
821

    
822
        // the token ring has not started yet
823
        if (sensor_matrix_get_joined(sensorMatrix) == 1)
824
                wl_token_pass_token();
825
}
826

    
827
/**
828
 * Called when we receive a JOIN_ACCEPT packet in attempting to join
829
 * the token ring.
830
 * Our attempt to join the ring is stopped, and we wait for the token.
831
 *
832
 * @param source the robot who accepted us
833
 **/
834
static void wl_token_join_accept_receive(int source)
835
{
836
        WL_DEBUG_PRINT("Accepted into the token ring by robot ");
837
        WL_DEBUG_PRINT_INT(source);
838
        WL_DEBUG_PRINT(".\r\n");
839
        joinDelay = JOIN_DELAY;
840
        ringState = ACCEPTED;
841
        acceptor = source;
842

    
843
        //add ourselves to the token ring
844
        sensor_matrix_set_in_ring(sensorMatrix, wl_get_xbee_id(), 1);
845
}