forked from nRF24/RF24Network
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRF24Network.cpp
744 lines (577 loc) · 18.9 KB
/
RF24Network.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
/*
Copyright (C) 2011 James Coliz, Jr. <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
*/
#include "RF24Network_config.h"
#include "RF24.h"
#include "RF24Network.h"
#include <avr/sleep.h>
#if defined (ENABLE_SLEEP_MODE)
#include <avr/sleep.h>
#include <avr/power.h>
volatile byte sleep_cycles_remaining;
#endif
uint16_t RF24NetworkHeader::next_id = 1;
uint64_t pipe_address( uint16_t node, uint8_t pipe );
bool is_valid_address( uint16_t node );
/********************************************************************
*
* sleepHandler ISR
*
********************************************************************/
void sleepHandler()
{
sleep_disable(); //disable sleep
noInterrupts (); // same as cli();
// detachInterrupt(interupt) // will be better, but we do not have interupt
}
/******************************************************************/
#if !defined (DUAL_HEAD_RADIO)
RF24Network::RF24Network( RF24& _radio ): radio(_radio), next_frame(frame_queue)
{
}
#else
RF24Network::RF24Network( RF24& _radio, RF24& _radio1 ): radio(_radio), radio1(_radio1), next_frame(frame_queue)
{
}
#endif
/******************************************************************/
void RF24Network::begin(uint8_t _channel, uint16_t _node_address )
{
begin(_channel, _node_address ,NULL,NULL);
return;
}
void RF24Network::begin(uint8_t _channel, uint16_t _node_address ,uint8_t* _key, uint8_t* _iv)
{
if (! is_valid_address(_node_address) )
return;
node_address = _node_address;
key = _key;
iv = _iv;
if ( ! radio.isValid() ){
return;
}
// Set up the radio the way we want it to look
radio.setChannel(_channel);
radio.setDataRate(RF24_1MBPS);
radio.setCRCLength(RF24_CRC_16);
// Use different retry periods to reduce data collisions
uint8_t retryVar = (node_address % 7) + 5;
radio.setRetries(retryVar, 15);
txTimeout = retryVar * 17;
#if defined (DUAL_HEAD_RADIO)
radio1.setChannel(_channel);
radio1.setDataRate(RF24_1MBPS);
radio1.setCRCLength(RF24_CRC_16);
#endif
// Setup our address helper cache
setup_address();
// Open up all listening pipes
int i = 6;
while (i--)
radio.openReadingPipe(i,pipe_address(_node_address,i));
radio.startListening();
// Spew debugging state about the radio
//radio.printDetails();
}
/******************************************************************/
void RF24Network::update(void)
{
// if there is data ready
uint8_t pipe_num;
while ( radio.isValid() && radio.available(&pipe_num) )
{
// Dump the payloads until we've gotten everything
//boolean done = false;
while (radio.available())
{
// Fetch the payload, and see if this was the last one.
radio.read( frame_buffer, sizeof(frame_buffer) );
if (key)
{
IF_SERIAL_DEBUG(printf_P(PSTR("decode\n\r")));
aes128_cbc_dec(key, iv, frame_buffer, sizeof(frame_buffer));
}
// Read the beginning of the frame as the header
const RF24NetworkHeader& header = * reinterpret_cast<RF24NetworkHeader*>(frame_buffer);
//Serial.println(header.toString());
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Received on %u %s\n\r"),millis(),pipe_num,header.toString()));
IF_SERIAL_DEBUG(const uint16_t* i = reinterpret_cast<const uint16_t*>(frame_buffer + sizeof(RF24NetworkHeader));printf_P(PSTR("%lu: NET message %04x\n\r"),millis(),*i));
// Throw it away if it's not a valid address
if ( !is_valid_address(header.to_node) ){
continue;
}
// Is this for us?
if ( header.to_node == node_address ){
// Add it to the buffer of frames for us
enqueue();
}else{
// Relay it
write(header.to_node);
}
// NOT NEEDED anymore. Now all reading pipes are open to start.
#if 0
// If this was for us, from one of our children, but on our listening
// pipe, it could mean that we are not listening to them. If so, open up
// and listen to their talking pipe
if ( header.to_node == node_address && pipe_num == 0 && is_descendant(header.from_node) )
{
uint8_t pipe = pipe_to_descendant(header.from_node);
radio.openReadingPipe(pipe,pipe_address(node_address,pipe));
// Also need to open pipe 1 so the system can get the full 5-byte address of the pipe.
radio.openReadingPipe(1,pipe_address(node_address,1));
}
#endif
}
}
}
/******************************************************************/
bool RF24Network::enqueue(void)
{
bool result = false;
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Enqueue @%x "),millis(),next_frame-frame_queue));
// Copy the current frame into the frame queue
if ( next_frame < frame_queue + sizeof(frame_queue) )
{
memcpy(next_frame,frame_buffer, frame_size );
next_frame += frame_size;
result = true;
IF_SERIAL_DEBUG(printf_P(PSTR("ok\n\r")));
}
else
{
IF_SERIAL_DEBUG(printf_P(PSTR("failed\n\r")));
}
return result;
}
/******************************************************************/
bool RF24Network::availablefifo(void)
{
// Are there frames on the queue for us?
return (next_framefifo < next_frame);
}
bool RF24Network::available(void)
{
// Are there frames on the queue for us?
return (next_frame > frame_queue);
}
/******************************************************************/
uint16_t RF24Network::parent() const
{
if ( node_address == 0 )
return -1;
else
return parent_node;
}
/******************************************************************/
void RF24Network::peekfifo(RF24NetworkHeader& header)
{
if ( available() )
{
// Copy the next available frame from the queue into the provided buffer
memcpy(&header,next_framefifo,sizeof(RF24NetworkHeader));
}
}
void RF24Network::peek(RF24NetworkHeader& header)
{
if ( available() )
{
// Copy the next available frame from the queue into the provided buffer
memcpy(&header,next_frame-frame_size,sizeof(RF24NetworkHeader));
}
}
/******************************************************************/
size_t RF24Network::readmulti(RF24NetworkHeader& header,void* message, size_t maxlen)
{
size_t lentot=0;
const unsigned long timeout = 500; //ms to wait for timeout
uint16_t myid=0;
int npacket;
int nextpacket;
unsigned long start_at = millis();
// Is there anything ready for us?
while ( ( millis() - start_at) < timeout ){
next_framefifo = frame_queue;
while ( availablefifo() ){
start_at = millis();
//Serial.println(start_at);
peekfifo(header);
//Serial.print(">"); Serial.println(header.toString());
if (header.type == 100) {
myid=header.id;
npacket=header.reserved;
nextpacket=npacket;
}
if ((myid >0) && (header.id == myid) && (nextpacket == header.reserved) && (header.type == 100 || header.type == 101)){
char* from = (char*)message+( (npacket-header.reserved )*PAYLOAD_SIZE);
// How much buffer size should we actually copy?
int bufsize = max(min(maxlen-(npacket-header.reserved )*PAYLOAD_SIZE,PAYLOAD_SIZE),0);
lentot += readfifo(header,from,bufsize);
if (!availablefifo()) next_frame = frame_queue;
if (nextpacket == 0) return lentot;
nextpacket -= 1;
}
else{
// skip packet
readfifo(header,NULL ,0);
}
}
update();
}
return 0;
}
size_t RF24Network::readfifo(RF24NetworkHeader& header,void* message, size_t maxlen)
{
size_t bufsize = 0;
if ( available() )
{
uint8_t* frame = next_framefifo;
memcpy(&header,frame,sizeof(RF24NetworkHeader));
if (maxlen > 0)
{
// How much buffer size should we actually copy?
bufsize = min(maxlen,frame_size-sizeof(RF24NetworkHeader));
// Copy the next available frame from the queue into the provided buffer
memcpy(message,frame+sizeof(RF24NetworkHeader),bufsize);
}
// Move the pointer forward one in the queue
next_framefifo += frame_size;
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Received %s\n\r"),millis(),header.toString()));
}
return bufsize;
}
size_t RF24Network::read(RF24NetworkHeader& header,void* message, size_t maxlen)
{
size_t bufsize = 0;
if ( available() )
{
// Move the pointer back one in the queue
next_frame -= frame_size;
uint8_t* frame = next_frame;
memcpy(&header,frame,sizeof(RF24NetworkHeader));
if (maxlen > 0)
{
// How much buffer size should we actually copy?
bufsize = min(maxlen,frame_size-sizeof(RF24NetworkHeader));
// Copy the next available frame from the queue into the provided buffer
memcpy(message,frame+sizeof(RF24NetworkHeader),bufsize);
}
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Received %s\n\r"),millis(),header.toString()));
}
return bufsize;
}
/******************************************************************/
bool RF24Network::writemulti(RF24NetworkHeader& header, const void* message, size_t len)
{
int numpack=len/PAYLOAD_SIZE;
if ((len % PAYLOAD_SIZE) > 0) numpack ++;
int npack=0;
while (npack < numpack)
{
int lenlen;
if (npack == numpack-1)
{
lenlen= len % PAYLOAD_SIZE;
}else
{
lenlen=PAYLOAD_SIZE;
}
if (lenlen == 0) lenlen=PAYLOAD_SIZE;
if (npack == 0 )
{
header.type = 100;
}
else
{
header.type = 101;
}
header.reserved=numpack-npack-1;
//Serial.println(header.toString());
//Serial.println((char*)message+(npack*PAYLOAD_SIZE));
//Serial.println(lenlen);
bool status = write(header,(char*)message+(npack*PAYLOAD_SIZE),lenlen);
if (!status) return status;
npack++;
}
return true;
}
bool RF24Network::write(RF24NetworkHeader& header,const void* message, size_t len)
{
// Fill out the header
header.from_node = node_address;
// Build the full frame to send
memcpy(frame_buffer,&header,sizeof(RF24NetworkHeader));
if (len)
memcpy(frame_buffer + sizeof(RF24NetworkHeader),message,min(frame_size-sizeof(RF24NetworkHeader),len));
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Sending %s\n\r"),millis(),header.toString()));
if (len)
{
IF_SERIAL_DEBUG(const uint16_t* i = reinterpret_cast<const uint16_t*>(message);printf_P(PSTR("%lu: NET message %04x\n\r"),millis(),*i));
}
// If the user is trying to send it to himself
if ( header.to_node == node_address )
// Just queue it in the received queue
return enqueue();
else
// Otherwise send it out over the air
return write(header.to_node);
}
/******************************************************************/
bool RF24Network::write(uint16_t to_node)
{
bool ok = false;
// Throw it away if it's not a valid address
if ( !is_valid_address(to_node) )
return false;
// First, stop listening so we can talk.
//radio.stopListening();
// Where do we send this? By default, to our parent
uint16_t send_node = parent_node;
// On which pipe
uint8_t send_pipe = parent_pipe;
// If the node is a direct child,
if ( is_direct_child(to_node) )
{
// Send directly
send_node = to_node;
// To its listening pipe
send_pipe = 0;
}
// If the node is a child of a child
// talk on our child's listening pipe,
// and let the direct child relay it.
else if ( is_descendant(to_node) )
{
send_node = direct_child_route_to(to_node);
send_pipe = 0;
}
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Sending to 0%o via 0%o on pipe %x\n\r"),millis(),to_node,send_node,send_pipe));
#if !defined (DUAL_HEAD_RADIO)
// First, stop listening so we can talk
radio.stopListening();
#endif
ok = write_to_pipe( send_node, send_pipe );
// NOT NEEDED anymore. Now all reading pipes are open to start.
#if 0
// If we are talking on our talking pipe, it's possible that no one is listening.
// If this fails, try sending it on our parent's listening pipe. That will wake
// it up, and next time it will listen to us.
if ( !ok && send_node == parent_node )
ok = write_to_pipe( parent_node, 0 );
#endif
#if !defined (DUAL_HEAD_RADIO)
// Now, continue listening
radio.startListening();
#endif
return ok;
}
/******************************************************************/
bool RF24Network::write_to_pipe( uint16_t node, uint8_t pipe )
{
bool ok = false;
uint64_t out_pipe = pipe_address( node, pipe );
if (key)
{
IF_SERIAL_DEBUG(printf_P(PSTR("encode\n\r")));
aes128_cbc_enc(key, iv, frame_buffer, sizeof(frame_buffer));
}
#if !defined (DUAL_HEAD_RADIO)
// Open the correct pipe for writing.
radio.openWritingPipe(out_pipe);
radio.writeFast(frame_buffer, frame_size);
ok = radio.txStandBy(txTimeout);
#else
radio1.openWritingPipe(out_pipe);
radio1.writeFast(frame_buffer, frame_size);
ok = radio1.txStandBy(txTimeout);
// // Retry a few times
// short attempts = 5;
// do
// {
// ok = radio.write( frame_buffer, frame_size );
// }
// while ( !ok && --attempts );
#endif
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Sent on %lx %S\n\r"),millis(),(uint32_t)out_pipe,ok?PSTR("ok"):PSTR("failed")));
return ok;
}
/******************************************************************/
const char* RF24NetworkHeader::toString(void) const
{
static char buffer[45];
snprintf_P(buffer,sizeof(buffer),PSTR("id %04x from 0%o to 0%o type %d reserved %d"),id,from_node,to_node,type,reserved);
return buffer;
}
/******************************************************************/
bool RF24Network::is_direct_child( uint16_t node )
{
bool result = false;
// A direct child of ours has the same low numbers as us, and only
// one higher number.
//
// e.g. node 0234 is a direct child of 034, and node 01234 is a
// descendant but not a direct child
// First, is it even a descendant?
if ( is_descendant(node) )
{
// Does it only have ONE more level than us?
uint16_t child_node_mask = ( ~ node_mask ) << 3;
result = ( node & child_node_mask ) == 0 ;
}
return result;
}
/******************************************************************/
bool RF24Network::is_descendant( uint16_t node )
{
return ( node & node_mask ) == node_address;
}
/******************************************************************/
void RF24Network::setup_address(void)
{
// First, establish the node_mask
uint16_t node_mask_check = 0xFFFF;
while ( node_address & node_mask_check )
node_mask_check <<= 3;
node_mask = ~ node_mask_check;
// parent mask is the next level down
uint16_t parent_mask = node_mask >> 3;
// parent node is the part IN the mask
parent_node = node_address & parent_mask;
// parent pipe is the part OUT of the mask
uint16_t i = node_address;
uint16_t m = parent_mask;
while (m)
{
i >>= 3;
m >>= 3;
}
parent_pipe = i;
#ifdef SERIAL_DEBUG
printf_P(PSTR("setup_address node=0%o mask=0%o parent=0%o pipe=0%o\n\r"),node_address,node_mask,parent_node,parent_pipe);
#endif
}
/******************************************************************/
uint16_t RF24Network::direct_child_route_to( uint16_t node )
{
// Presumes that this is in fact a child!!
uint16_t child_mask = ( node_mask << 3 ) | 0B111;
return node & child_mask ;
}
/******************************************************************/
uint8_t RF24Network::pipe_to_descendant( uint16_t node )
{
uint16_t i = node;
uint16_t m = node_mask;
while (m)
{
i >>= 3;
m >>= 3;
}
return i & 0B111;
}
/******************************************************************/
bool is_valid_address( uint16_t node )
{
bool result = true;
while(node)
{
uint8_t digit = node & 0B111;
if (digit < 1 || digit > 5)
{
result = false;
printf_P(PSTR("*** WARNING *** Invalid address 0%o\n\r"),node);
break;
}
node >>= 3;
}
return result;
}
/******************************************************************/
uint64_t pipe_address( uint16_t node, uint8_t pipe )
{
static uint8_t pipe_segment[] = { 0x3c, 0x5a, 0x69, 0x96, 0xa5, 0xc3 };
uint64_t result;
uint8_t* out = reinterpret_cast<uint8_t*>(&result);
out[0] = pipe_segment[pipe];
uint8_t w;
short i = 4;
short shift = 12;
while(i--)
{
w = ( node >> shift ) & 0xF ;
w |= ~w << 4;
out[i+1] = w;
shift -= 4;
}
IF_SERIAL_DEBUG(uint32_t* top = reinterpret_cast<uint32_t*>(out+1);printf_P(PSTR("%lu: NET Pipe %i on node 0%o has address %lx%x\n\r"),millis(),pipe,node,*top,*out));
return result;
}
/************************ Sleep Mode ******************************************/
void RF24Network::sleep(int interrupt,int mode,int sleepMode) {
// if(mode == FALLING || mode == LOW)
// {
// //int pin = interrupt + 2; //will fail on the mega
// pinMode (pin, INPUT);
// digitalWrite (pin, HIGH);
// }
set_sleep_mode(sleepMode);
sleep_enable();
// Do not interrupt before we go to sleep, or the
// ISR will detach interrupts and we won't wake.
noInterrupts (); // same as cli();
attachInterrupt(interrupt,sleepHandler,mode);
//sleep_bod_disable(); // do not use for mega2560
// We are guaranteed that the sleep_cpu call will be done
// as the processor executes the next instruction after
// interrupts are turned on.
interrupts (); // one cycle // same as sei();
sleep_cpu (); // one cycle
//----------------------------- ZZZZZZ sleeping here----------------------
sleep_disable();
detachInterrupt(interrupt);
interrupts (); // one cycle // same as sei();
}
#if defined ENABLE_SLEEP_MODE
#if !defined( __AVR_ATtiny85__ ) && !defined( __AVR_ATtiny84__) && !defined(__arm__)
RF24NetworkHeader sleepHeader(/*to node*/ 00, /*type*/ 'S' /*Sleep*/);
//bool awoke = 0;
void wakeUp(){
//detachInterrupt(0);
sleep_disable();
sleep_cycles_remaining = 0;
//awoke = 1;
}
ISR(WDT_vect){
--sleep_cycles_remaining;
}
void RF24Network::sleepNode( unsigned int cycles, int interruptPin ){
sleep_cycles_remaining = cycles;
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
sleep_enable();
if(interruptPin != 255){
attachInterrupt(interruptPin,wakeUp, LOW);
}
WDTCSR |= _BV(WDIE);
while(sleep_cycles_remaining){
//uint8_t junk = 23;
//write(&junk,1);
sleep_mode(); // System sleeps here
} // The WDT_vect interrupt wakes the MCU from here
sleep_disable(); // System continues execution here when watchdog timed out
//if(awoke){ update(); awoke = 0; }
detachInterrupt(interruptPin);
WDTCSR &= ~_BV(WDIE);
//radio.startListening();
}
void RF24Network::setup_watchdog(uint8_t prescalar){
uint8_t wdtcsr = prescalar & 7;
if ( prescalar & 8 )
wdtcsr |= _BV(WDP3);
MCUSR &= ~_BV(WDRF); // Clear the WD System Reset Flag
WDTCSR = _BV(WDCE) | _BV(WDE); // Write the WD Change enable bit to enable changing the prescaler and enable system reset
WDTCSR = _BV(WDCE) | wdtcsr | _BV(WDIE); // Write the prescalar bits (how long to sleep, enable the interrupt to wake the MCU
}
#endif // not ATTiny
#endif // Enable sleep mode