Project

General

Profile

Statistics
| Revision:

root / branches / autonomous_recharging / code / projects / libwireless / lib / wl_token_ring.c @ 883

History | View | Annotate | Download (25.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 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
#define WL_TOKEN_PASS_FRAME        2
66

    
67
/*Function Prototypes*/
68

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

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

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

    
87
/*Global Variables*/
88

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

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

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

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

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

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

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

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

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

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

    
151
        return 0;
152
}
153

    
154
/**
155
 * Causes the robot to leave the token ring. The robot stops
156
 * alerting others of its location, but continues storing the
157
 * locations of other robots.
158
 **/
159
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
160
// it reduces code size or not should be done to be sure.
161
void wl_token_ring_leave()
162
{
163
        ringState = LEAVING;
164
}
165

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

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

    
186
        wl_register_packet_group(&wl_token_ring_handler);
187

    
188
        return 0;
189
}
190

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

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

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

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

    
254
                // we may have been dropped from the ring when this is received
255
                if (ringState == MEMBER) {
256
                        wl_token_pass_token();
257
                }
258
        }
259

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

    
283
        if (deathDelay >= 0) {
284
                deathDelay--;
285
        }
286

    
287
        if (joinDelay >= 0) {
288
                joinDelay--;
289
        }
290

    
291
        if (bom_on_count >= 0) {
292
                bom_on_count++;
293
        }
294
}
295

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

    
310
/**
311
 * Called when we recieve a token ring packet.
312
 * @param type the type of the packet
313
 * @param source the id of the robot who sent the packet
314
 * @param packet the data in the packet
315
 * @param length the length of the packet in bytes
316
 **/
317
static void wl_token_ring_receive_handler(char type, int source, unsigned char* packet, int length)
318
{
319
        switch (type)
320
        {
321
                case WL_TOKEN_PASS:
322
                        usb_puts("Got token.\n\r");
323
                        wl_token_pass_receive(source);
324
                        break;
325
                case WL_TOKEN_SENSOR_MATRIX:
326
                        usb_puts("Got sensor matrix.\n\r");
327
                        wl_token_sensor_matrix_receive(source, packet, length);
328
                        break;
329
                case WL_TOKEN_BOM_ON:
330
                        usb_puts("Got BOM on.\n\r");
331
                        //add the robot to the sensor matrix if it is not already there
332
                        wl_token_bom_on_receive(source);
333
                        break;
334
                case WL_TOKEN_JOIN:
335
                        usb_puts("Got join request.\n\r");
336
                        wl_token_join_receive(source);
337
                        break;
338
                case WL_TOKEN_JOIN_ACCEPT:
339
                        usb_puts("Got join accept.\n\r");
340
                        wl_token_join_accept_receive(source);
341
                        break;
342
                default:
343
                        WL_DEBUG_PRINT("Unimplemented token ring packet received.\r\n");
344
                        break;
345
        }
346
}
347

    
348
/**
349
 * Returns the BOM reading robot source has for robot dest.
350
 *
351
 * @param source the robot that made the BOM reading
352
 * @param dest the robot whose relative location is returned
353
 *
354
 * @return a BOM reading from robot source to robot dest,
355
 * in the range 0-15, or -1 if it is unknown
356
 **/
357
int wl_token_get_sensor_reading(int source, int dest)
358
{
359
        if (wl_token_is_robot_in_ring(dest) &&
360
                        (source == wl_get_xbee_id() || wl_token_is_robot_in_ring(source))) {
361
                return sensor_matrix_get_reading(source, dest);
362
        }
363

    
364
        return -1;
365
}
366

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

    
382

    
383
/**
384
 * Returns the number of robots in the token ring.
385
 *
386
 * @return the number of robots in the token ring
387
 **/
388
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
389
// it reduces code size or not should be done to be sure.
390
int wl_token_get_robots_in_ring(void)
391
{
392
        return sensor_matrix_get_joined();
393
}
394

    
395
/**
396
 * Returns true if the specified robot is in the token ring, false
397
 * otherwise.
398
 *
399
 * @param robot the robot to check for whether it is in the token ring
400
 * @return nonzero if the robot is in the token ring, zero otherwise
401
 **/
402
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
403
// it reduces code size or not should be done to be sure.
404
int wl_token_is_robot_in_ring(int robot)
405
{
406
        return sensor_matrix_get_in_ring(robot);
407
}
408

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

    
425
  //TODO: if you do the above comment, then you can compare this to the variable also
426
        if (i == sensor_matrix_get_size()) {
427
                i = -1;
428
        }
429

    
430
        iteratorCount = i;
431
}
432

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

    
449
/**
450
 * Returns the next robot ID in the token ring.
451
 *
452
 * @return the next robot ID in the token ring, or -1 if none exists
453
 *
454
 * @see wl_token_iterator_begin, wl_token_iterator_has_next
455
 **/
456
int wl_token_iterator_next(void)
457
{
458
        int result = iteratorCount;
459
        if (result < 0) {
460
                return result;
461
        }
462

    
463
  //TODO: the compiler may or may not optimize this such that my comment is useless:
464
  // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
465
  // the overhead of a function call each iteration, call it only once before the loop and store
466
  // the value in a variable and check against that variable in the loop condition
467
        iteratorCount++;
468
        while (!sensor_matrix_get_in_ring(iteratorCount)
469
                && iteratorCount < sensor_matrix_get_size()) {
470
                iteratorCount++;
471
        }
472

    
473
  //TODO: if you do the above comment, then you can compare this to the variable also
474
        if (iteratorCount == sensor_matrix_get_size()) {
475
                iteratorCount = -1;
476
        }
477

    
478
        return result;
479
}
480

    
481
/**
482
 * Returns the number of robots currently in the token ring.
483
 *
484
 * @return the number of robots in the token ring
485
 **/
486
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
487
// it reduces code size or not should be done to be sure.
488
int wl_token_get_num_robots(void)
489
{
490
        return sensor_matrix_get_joined();
491
}
492

    
493
/**
494
 * Returns the number of robots in the sensor matrix.
495
 *
496
 * @return the number of robots in the sensor matrix
497
 **/
498
//TODO: this function is so simple, it *may* be beneficial to inline this function.  testing of if
499
// it reduces code size or not should be done to be sure.
500
int wl_token_get_matrix_size(void)
501
{
502
        return sensor_matrix_get_size();
503
}
504

    
505
/**
506
 * This method is called when we receive a token pass packet.
507
 *
508
 * @param source the robot who passed the token to us.
509
 **/
510
static void wl_token_pass_receive(int source)
511
{
512
        WL_DEBUG_PRINT("Received token from ");
513
        WL_DEBUG_PRINT_INT(source);
514
        WL_DEBUG_PRINT(", expected ");
515
        WL_DEBUG_PRINT_INT(wl_token_next_robot);
516
        WL_DEBUG_PRINT(".\n");
517
        // this prevents two tokens from being passed around at a time (second clause is in case we are joining)
518
        usb_puti(source); usb_putc(' '); usb_puti(wl_token_next_robot); usb_putc(' '); usb_puti(wl_get_xbee_id());
519
        usb_putc(' '); usb_puti(bom_on_count); usb_putc(' '); usb_puti(ringState); usb_putc(' '); usb_puts("\n\r");
520
        if ((source != wl_token_next_robot && wl_get_xbee_id() != wl_token_next_robot) && bom_on_count <= DEATH_DELAY / 2 &&
521
                ringState != ACCEPTED)
522
        {
523
                WL_DEBUG_PRINT("Received token pass when a robot should not have died yet.\n");
524
                WL_DEBUG_PRINT("There are probably two tokens going around, packet ignored.\n");
525
                return;
526
        }
527
        bom_on_count = -1;
528
        deathDelay = -1;
529
        sensor_matrix_set_in_ring(source, 1);
530
        wl_token_get_token();
531
}
532

    
533
/**
534
 * This method is called when we receive a token pass packet.
535
 * @param source is the robot it came from
536
 * @param nextRobot is the robot the token was passed to
537
 * @param sensorData a char with an id followed by a char with the sensor
538
 *                reading for that robot, repeated for sensorDataLength bytes
539
 * @param sensorDataLength the length in bytes of sensorData
540
 */
541
static void wl_token_sensor_matrix_receive(int source, unsigned char* sensorData, int sensorDataLength)
542
{
543
        int i, j;
544
        char nextRobot;
545

    
546
        bom_on_count = -1;
547
        deathDelay = -1;
548
        sensor_matrix_set_in_ring(source, 1);
549

    
550
        //with this packet, we are passed the id of the next robot in the ring
551
        //and the sensor matrix, a list of id and sensor reading pairs (two bytes for both)
552
        j = 0;
553
  //TODO: the compiler may or may not optimize this such that my comment is useless:
554
  // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
555
  // the overhead of a function call each iteration, call it only once before the loop and store
556
  // the value in a variable and check against that variable in the loop condition
557
        for (i = 0; i < sensor_matrix_get_size(); i++)
558
        {
559
                if (i == source) {
560
                        continue;
561
                }
562

    
563
                //set the sensor information we receive
564
                if (j < sensorDataLength / 2 && sensorData[2 * j] == i)
565
                {
566
                        //the robot we were going to accept has already been accepted
567
                        if (accepted == i)
568
                        {
569
                                accepted = -1;
570
                                WL_DEBUG_PRINT("Someone accepted the robot we did.\r\n");
571
                        }
572
                        sensor_matrix_set_reading(source, i,
573
                                                sensorData[2 * j + 1]);
574
                        if (!sensor_matrix_get_in_ring(i))
575
                        {
576
                                WL_DEBUG_PRINT("Robot ");
577
                                WL_DEBUG_PRINT_INT(i);
578
                                WL_DEBUG_PRINT(" has been added to the sensor matrix of robot ");
579
                                WL_DEBUG_PRINT_INT(wl_get_xbee_id());
580
                                WL_DEBUG_PRINT(" due to a packet from robot ");
581
                                WL_DEBUG_PRINT_INT(source);
582
                                WL_DEBUG_PRINT(".\r\n");
583
                        }
584
                        sensor_matrix_set_in_ring(i, 1);
585
                        j++;
586
                }
587
                else
588
                {
589
                        if (sensor_matrix_get_in_ring(i))
590
                        {
591
                                WL_DEBUG_PRINT("Robot ");
592
                                WL_DEBUG_PRINT_INT(i);
593
                                WL_DEBUG_PRINT(" has been removed from the sensor matrix of robot ");
594
                                WL_DEBUG_PRINT_INT(wl_get_xbee_id());
595
                                WL_DEBUG_PRINT(" due to a packet from robot ");
596
                                WL_DEBUG_PRINT_INT(source);
597
                                WL_DEBUG_PRINT(".\r\n");
598
                                sensor_matrix_set_in_ring(i, 0);
599
                        }
600

    
601
                        if (i == wl_get_xbee_id() && ringState == MEMBER)
602
                        {
603
                                ringState = NONMEMBER;
604
                                wl_token_ring_join();
605

    
606
                                WL_DEBUG_PRINT("We have been removed from the ring ");
607
                                WL_DEBUG_PRINT("and are rejoining.\r\n");
608
                        }
609

    
610
                        //the person who accepted us is dead... let's ask again
611
                        if (i == acceptor)
612
                        {
613
                                sensor_matrix_set_in_ring(wl_get_xbee_id(), 0);
614
                                ringState = NONMEMBER;
615
                                acceptor = -1;
616
                                wl_token_ring_join();
617
                        }
618
                }
619
        }
620
        
621
        // get the next robot in the token ring
622
        i = source + 1;
623
        while (1)
624
        {
625
                if (i == sensor_matrix_get_size()) {
626
                        i = 0;
627
                }
628

    
629
                if (sensor_matrix_get_in_ring(i) || i == source)
630
                {
631
                        nextRobot = (char)i;
632
                        break;
633
                }
634

    
635
                i++;
636
        }
637

    
638
        if (nextRobot != wl_get_xbee_id())
639
                wl_token_next_robot = nextRobot;
640

    
641
        deathDelay = get_token_distance(wl_get_xbee_id(), nextRobot) * DEATH_DELAY;
642

    
643
        if (sensor_matrix_get_joined() == 0 && ringState == JOINING)
644
                wl_send_robot_to_robot_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_PASS, NULL, 0, nextRobot, WL_TOKEN_PASS_FRAME);
645
}
646

    
647
/**
648
 * Gets the distance in the token ring between two robots.
649
 *
650
 * @param robot1 the first robot
651
 * @param robot2 the second robot
652
 *
653
 * @return the number of passes before the token is expected
654
 * to reach robot2 from robot1
655
 **/
656
static int get_token_distance(int robot1, int robot2)
657
{
658
        int curr = robot1 + 1;
659
        int count = 1;
660
        while (1)
661
        {
662
    //TODO: the compiler may or may not optimize this such that my comment is useless:
663
    // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
664
    // the overhead of a function call each iteration, call it only once before the loop and store
665
    // the value in a variable and check against that variable in the loop condition
666
                if (curr == sensor_matrix_get_size())
667
                        curr = 0;
668
                if (curr == robot2)
669
                        break;
670
                if (sensor_matrix_get_in_ring(curr))
671
                        count++;
672
                curr++;
673
        }
674
        return count;
675
}
676

    
677
/**
678
 * Passes the token to the next robot in the token ring.
679
 **/
680
static int wl_token_pass_token()
681
{
682
        char nextRobot = 0xFF;
683
        int i = wl_get_xbee_id() + 1;
684
        char buf[2 * sensor_matrix_get_size()];
685
        if (accepted == -1)
686
        {
687
                while (1)
688
                {
689
      //TODO: the compiler may or may not optimize this such that my comment is useless:
690
      // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
691
      // the overhead of a function call each iteration, call it only once before the loop and store
692
      // the value in a variable and check against that variable in the loop condition
693
                        if (i == sensor_matrix_get_size()) {
694
                                i = 0;
695
                        }
696

    
697
                        if (sensor_matrix_get_in_ring(i))
698
                        {
699
                                nextRobot = (char)i;
700
                                break;
701
                        }
702

    
703
                        i++;
704
                }
705
        }
706
        else
707
        {
708
                usb_puts("Accepting.\n\r");
709
                WL_DEBUG_PRINT("Accepting new robot, sending it the token.\r\n");
710
                //add a new robot to the token ring
711
                sensor_matrix_set_in_ring(accepted, 1);
712
                nextRobot = accepted;
713
                accepted = -1;
714
        }
715

    
716
        int j = 0;
717
  //TODO: the compiler may or may not optimize this such that my comment is useless:
718
  // instead of calling sensor_matrix_get_size every iteration of the while loop and incurring
719
  // the overhead of a function call each iteration, call it only once before the loop and store
720
  // the value in a variable and check against that variable in the loop condition
721
        for (i = 0; i < sensor_matrix_get_size(); i++) {
722
                if (sensor_matrix_get_in_ring(i) && i != wl_get_xbee_id())
723
                {
724
                        buf[2*j] = i;
725
                        buf[2*j + 1] = sensor_matrix_get_reading(wl_get_xbee_id(), i);
726
                        j++;
727
                        usb_puti(i);
728
                        usb_puts("\n\r");
729
                }
730
        }
731
        usb_puts("\n\r");
732
        int packetSize = 2 * j * sizeof(char);
733
        WL_DEBUG_PRINT("Passing the token to robot ");
734
        WL_DEBUG_PRINT_INT(nextRobot);
735
        WL_DEBUG_PRINT(".\r\n");
736
        usb_puts("Passing token ");
737
        usb_puti(nextRobot);
738
        usb_puts("\n\r");
739
        if (wl_send_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_SENSOR_MATRIX, buf, packetSize, 0) != 0)
740
                return -1;
741
        if (wl_send_robot_to_robot_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_PASS, NULL, 0, nextRobot, WL_TOKEN_PASS_FRAME))
742
                return -1;
743

    
744
        wl_token_next_robot = nextRobot;
745
        usb_puti(nextRobot);
746
        deathDelay = DEATH_DELAY;
747

    
748
        return 0;
749
}
750

    
751
/**
752
 * Called when a packet is received stating that another robot has turned
753
 * its BOM on. Our BOM is then read, and the data is added to the sensor
754
 * matrix.
755
 *
756
 * @param source the robot whose BOM is on
757
 **/
758
static void wl_token_bom_on_receive(int source)
759
{
760
        WL_DEBUG_PRINT("Robot ");
761
        WL_DEBUG_PRINT_INT(source);
762
        WL_DEBUG_PRINT(" has flashed its bom.\r\n");
763

    
764
        bom_on_count = 0;
765

    
766
        sensor_matrix_set_reading(wl_get_xbee_id(),
767
                source, get_max_bom_function());
768
}
769

    
770
/**
771
 * This method is called when we receive the token. Upon receiving
772
 * the token, we must send a BOM_ON packet, flash the BOM, and send
773
 * the token to the next robot.
774
 *
775
 * If there is a pending request for the token, this is processed first.
776
 **/
777
static void wl_token_get_token()
778
{
779
        WL_DEBUG_PRINT("We have the token.\r\n");
780
        if (ringState == ACCEPTED)
781
        {
782
                sensor_matrix_set_in_ring(wl_get_xbee_id(), 1);
783
                WL_DEBUG_PRINT("Now a member of the token ring.\r\n");
784
                ringState = MEMBER;
785
                joinDelay = -1;
786
        }
787

    
788
        if (ringState == LEAVING || ringState == NONMEMBER)
789
        {
790
                sensor_matrix_set_in_ring(wl_get_xbee_id(), 0);
791
                if (ringState == NONMEMBER)
792
                {
793
                        WL_DEBUG_PRINT("We should have left the token ring, but didn't.\r\n");
794
                }
795
                return;
796
        }
797

    
798
        WL_DEBUG_PRINT("Our BOM has been flashed.\r\n");
799
        wl_send_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_BOM_ON, NULL, 0, 0);
800

    
801
        //bom_on_function();
802
        //#ifdef ROBOT
803
        usb_puts("BOM ON!\n\r");
804
        delay_ms(BOM_DELAY);
805
        usb_puts("BOM OFF!\n\r");
806
        //#endif
807
        //bom_off_function();
808

    
809
        if (!sensor_matrix_get_in_ring(wl_get_xbee_id()))
810
        {
811
                usb_puts("FAIL\n\r");
812
                WL_DEBUG_PRINT("Removed from sensor matrix while flashing BOM.\r\n");
813
                return;
814
        }
815

    
816
        wl_token_pass_token();
817
}
818

    
819
/**
820
 * Called when a request to join the token ring is received.
821
 * If we are the robot preceding the requester in the ring,
822
 * we respond with a JOIN_ACCEPT packet and pass the token to
823
 * this robot when we receive the token.
824
 *
825
 * @param source the robot who requested to join
826
 **/
827
static void wl_token_join_receive(int source)
828
{
829
        WL_DEBUG_PRINT("Received joining request from robot ");
830
        WL_DEBUG_PRINT_INT(source);
831
        WL_DEBUG_PRINT(".\r\n");
832

    
833
        //we cannot accept the request if we are not a member
834
        if (ringState != MEMBER)
835
                return;
836
        //if they didn't get our response, see if we should respond again
837
        if (accepted == source)
838
                accepted = -1;
839
        //we can only accept one request at a time
840
        if (accepted != -1)
841
                return;
842

    
843
        //check if we are the preceding robot in the token ring
844
        int i = source - 1;
845
        while (1)
846
        {
847
                if (i < 0)
848
                        i = sensor_matrix_get_size() - 1;
849

    
850
                //we must send a join acceptance
851
                if (i == wl_get_xbee_id())
852
                        break;
853

    
854
                //another robot will handle it
855
                if (sensor_matrix_get_in_ring(i))
856
                        return;
857

    
858
                i--;
859
        }
860

    
861
        accepted = source;
862
        wl_send_robot_to_robot_global_packet(WL_TOKEN_RING_GROUP, WL_TOKEN_JOIN_ACCEPT,
863
                NULL, 0, source, TOKEN_JOIN_ACCEPT_FRAME);
864

    
865
        WL_DEBUG_PRINT("Accepting robot ");
866
        WL_DEBUG_PRINT_INT(source);
867
        WL_DEBUG_PRINT(" into the token ring.\r\n");
868

    
869
        // the token ring has not started yet
870
        if (sensor_matrix_get_joined() == 1)
871
                wl_token_pass_token();
872
}
873

    
874
/**
875
 * Called when we receive a JOIN_ACCEPT packet in attempting to join
876
 * the token ring.
877
 * Our attempt to join the ring is stopped, and we wait for the token.
878
 *
879
 * @param source the robot who accepted us
880
 **/
881
static void wl_token_join_accept_receive(int source)
882
{
883
        WL_DEBUG_PRINT("Accepted into the token ring by robot ");
884
        WL_DEBUG_PRINT_INT(source);
885
        WL_DEBUG_PRINT(".\r\n");
886
        joinDelay = JOIN_DELAY;
887
        ringState = ACCEPTED;
888
        acceptor = source;
889

    
890
        //add ourselves to the token ring
891
        sensor_matrix_set_in_ring(wl_get_xbee_id(), 1);
892
}