forked from prideofisland/arduino-dw1000
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDW1000Ranging.cpp
982 lines (789 loc) · 31.3 KB
/
DW1000Ranging.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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
/*
* Copyright (c) 2015 by Thomas Trojer <thomas@trojer.net> and Leopold Sayous <leosayous@gmail.com>
* Decawave DW1000 library for arduino.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file DW1000Ranging.h
* Arduino global library (source file) working with the DW1000 library
* for the Decawave DW1000 UWB transceiver IC.
*
* @TODO
* - remove or debugmode for Serial.print
* - move strings to flash to reduce ram usage
* - do not safe duplicate of pin settings
* - maybe other object structure
* - use enums instead of preprocessor constants
*/
#include "DW1000Ranging.h"
#include "DW1000Device.h"
DW1000RangingClass DW1000Ranging;
//other devices we are going to communicate with which are on our network:
DW1000Device DW1000RangingClass::_networkDevices[MAX_DEVICES];
byte DW1000RangingClass::_currentAddress[8];
byte DW1000RangingClass::_currentShortAddress[2];
byte DW1000RangingClass::_lastSentToShortAddress[2];
volatile uint8_t DW1000RangingClass::_networkDevicesNumber = 0; // TODO short, 8bit?
int16_t DW1000RangingClass::_lastDistantDevice = 0; // TODO short, 8bit?
DW1000Mac DW1000RangingClass::_globalMac;
//module type (anchor or tag)
int16_t DW1000RangingClass::_type; // TODO enum??
// message flow state
volatile byte DW1000RangingClass::_expectedMsgId;
// range filter
volatile boolean DW1000RangingClass::_useRangeFilter = false;
uint16_t DW1000RangingClass::_rangeFilterValue = 15;
// message sent/received state
volatile boolean DW1000RangingClass::_sentAck = false;
volatile boolean DW1000RangingClass::_receivedAck = false;
// protocol error state
boolean DW1000RangingClass::_protocolFailed = false;
// timestamps to remember
int32_t DW1000RangingClass::timer = 0;
int16_t DW1000RangingClass::counterForBlink = 0; // TODO 8 bit?
// data buffer
byte DW1000RangingClass::data[LEN_DATA];
// reset line to the chip
uint8_t DW1000RangingClass::_RST;
uint8_t DW1000RangingClass::_SS;
// watchdog and reset period
uint32_t DW1000RangingClass::_lastActivity;
uint32_t DW1000RangingClass::_resetPeriod;
// reply times (same on both sides for symm. ranging)
uint16_t DW1000RangingClass::_replyDelayTimeUS;
//timer delay
uint16_t DW1000RangingClass::_timerDelay;
// ranging counter (per second)
uint16_t DW1000RangingClass::_successRangingCount = 0;
uint32_t DW1000RangingClass::_rangingCountPeriod = 0;
//Here our handlers
void (* DW1000RangingClass::_handleNewRange)(void) = 0;
void (* DW1000RangingClass::_handleBlinkDevice)(DW1000Device*) = 0;
void (* DW1000RangingClass::_handleNewDevice)(DW1000Device*) = 0;
void (* DW1000RangingClass::_handleInactiveDevice)(DW1000Device*) = 0;
/* ###########################################################################
* #### Init and end #######################################################
* ######################################################################### */
void DW1000RangingClass::initCommunication(uint8_t myRST, uint8_t mySS, uint8_t myIRQ) {
// reset line to the chip
_RST = myRST;
_SS = mySS;
_resetPeriod = DEFAULT_RESET_PERIOD;
// reply times (same on both sides for symm. ranging)
_replyDelayTimeUS = DEFAULT_REPLY_DELAY_TIME;
//we set our timer delay
_timerDelay = DEFAULT_TIMER_DELAY;
DW1000.begin(myIRQ, myRST);
DW1000.select(mySS);
}
void DW1000RangingClass::configureNetwork(uint16_t deviceAddress, uint16_t networkId, const byte mode[]) {
// general configuration
DW1000.newConfiguration();
DW1000.setDefaults();
DW1000.setDeviceAddress(deviceAddress);
DW1000.setNetworkId(networkId);
DW1000.enableMode(mode);
DW1000.commitConfiguration();
}
void DW1000RangingClass::generalStart() {
// attach callback for (successfully) sent and received messages
DW1000.attachSentHandler(handleSent);
DW1000.attachReceivedHandler(handleReceived);
// anchor starts in receiving mode, awaiting a ranging poll message
if(DEBUG) {
// DEBUG monitoring
Serial.println("DW1000-arduino");
// initialize the driver
Serial.println("configuration..");
// DEBUG chip info and registers pretty printed
char msg[90];
DW1000.getPrintableDeviceIdentifier(msg);
Serial.print("Device ID: ");
Serial.println(msg);
DW1000.getPrintableExtendedUniqueIdentifier(msg);
Serial.print("Unique ID: ");
Serial.print(msg);
char string[6];
sprintf(string, "%02X:%02X", _currentShortAddress[0], _currentShortAddress[1]);
Serial.print(" short: ");
Serial.println(string);
DW1000.getPrintableNetworkIdAndShortAddress(msg);
Serial.print("Network ID & Device Address: ");
Serial.println(msg);
DW1000.getPrintableDeviceMode(msg);
Serial.print("Device mode: ");
Serial.println(msg);
}
// anchor starts in receiving mode, awaiting a ranging poll message
receiver();
// for first time ranging frequency computation
_rangingCountPeriod = millis();
}
void DW1000RangingClass::startAsAnchor(char address[], const byte mode[], const bool randomShortAddress) {
//save the address
DW1000.convertToByte(address, _currentAddress);
//write the address on the DW1000 chip
DW1000.setEUI(address);
Serial.print("device address: ");
Serial.println(address);
if (randomShortAddress) {
//we need to define a random short address:
randomSeed(analogRead(0));
_currentShortAddress[0] = random(0, 256);
_currentShortAddress[1] = random(0, 256);
}
else {
// we use first two bytes in addess for short address
_currentShortAddress[0] = _currentAddress[0];
_currentShortAddress[1] = _currentAddress[1];
}
//we configur the network for mac filtering
//(device Address, network ID, frequency)
DW1000Ranging.configureNetwork(_currentShortAddress[0]*256+_currentShortAddress[1], 0xDECA, mode);
//general start:
generalStart();
//defined type as anchor
_type = ANCHOR;
Serial.println("### ANCHOR ###");
}
void DW1000RangingClass::startAsTag(char address[], const byte mode[], const bool randomShortAddress) {
//save the address
DW1000.convertToByte(address, _currentAddress);
//write the address on the DW1000 chip
DW1000.setEUI(address);
Serial.print("device address: ");
Serial.println(address);
if (randomShortAddress) {
//we need to define a random short address:
randomSeed(analogRead(0));
_currentShortAddress[0] = random(0, 256);
_currentShortAddress[1] = random(0, 256);
}
else {
// we use first two bytes in addess for short address
_currentShortAddress[0] = _currentAddress[0];
_currentShortAddress[1] = _currentAddress[1];
}
//we configur the network for mac filtering
//(device Address, network ID, frequency)
DW1000Ranging.configureNetwork(_currentShortAddress[0]*256+_currentShortAddress[1], 0xDECA, mode);
generalStart();
//defined type as tag
_type = TAG;
Serial.println("### TAG ###");
}
boolean DW1000RangingClass::addNetworkDevices(DW1000Device* device, boolean shortAddress) {
boolean addDevice = true;
//we test our network devices array to check
//we don't already have it
for(uint8_t i = 0; i < _networkDevicesNumber; i++) {
if(_networkDevices[i].isAddressEqual(device) && !shortAddress) {
//the device already exists
addDevice = false;
return false;
}
else if(_networkDevices[i].isShortAddressEqual(device) && shortAddress) {
//the device already exists
addDevice = false;
return false;
}
}
if(addDevice) {
device->setRange(0);
memcpy(&_networkDevices[_networkDevicesNumber], device, sizeof(DW1000Device));
_networkDevices[_networkDevicesNumber].setIndex(_networkDevicesNumber);
_networkDevicesNumber++;
return true;
}
return false;
}
boolean DW1000RangingClass::addNetworkDevices(DW1000Device* device) {
boolean addDevice = true;
//we test our network devices array to check
//we don't already have it
for(uint8_t i = 0; i < _networkDevicesNumber; i++) {
if(_networkDevices[i].isAddressEqual(device) && _networkDevices[i].isShortAddressEqual(device)) {
//the device already exists
addDevice = false;
return false;
}
}
if(addDevice) {
if(_type == ANCHOR) //for now let's start with 1 TAG
{
_networkDevicesNumber = 0;
}
memcpy(&_networkDevices[_networkDevicesNumber], device, sizeof(DW1000Device));
_networkDevices[_networkDevicesNumber].setIndex(_networkDevicesNumber);
_networkDevicesNumber++;
return true;
}
return false;
}
void DW1000RangingClass::removeNetworkDevices(int16_t index) {
//if we have just 1 element
if(_networkDevicesNumber == 1) {
_networkDevicesNumber = 0;
}
else if(index == _networkDevicesNumber-1) //if we delete the last element
{
_networkDevicesNumber--;
}
else {
//we translate all the element wich are after the one we want to delete.
for(int16_t i = index; i < _networkDevicesNumber-1; i++) { // TODO 8bit?
memcpy(&_networkDevices[i], &_networkDevices[i+1], sizeof(DW1000Device));
_networkDevices[i].setIndex(i);
}
_networkDevicesNumber--;
}
}
/* ###########################################################################
* #### Setters and Getters ##################################################
* ######################################################################### */
//setters
void DW1000RangingClass::setReplyTime(uint16_t replyDelayTimeUs) { _replyDelayTimeUS = replyDelayTimeUs; }
void DW1000RangingClass::setResetPeriod(uint32_t resetPeriod) { _resetPeriod = resetPeriod; }
DW1000Device* DW1000RangingClass::searchDistantDevice(byte shortAddress[]) {
//we compare the 2 bytes address with the others
for(uint16_t i = 0; i < _networkDevicesNumber; i++) { // TODO 8bit?
if(memcmp(shortAddress, _networkDevices[i].getByteShortAddress(), 2) == 0) {
//we have found our device !
return &_networkDevices[i];
}
}
return NULL;
}
DW1000Device* DW1000RangingClass::getDistantDevice() {
//we get the device which correspond to the message which was sent (need to be filtered by MAC address)
return &_networkDevices[_lastDistantDevice];
}
/* ###########################################################################
* #### Public methods #######################################################
* ######################################################################### */
void DW1000RangingClass::checkForReset() {
uint32_t curMillis = millis();
if(!_sentAck && !_receivedAck) {
// check if inactive
if(curMillis-_lastActivity > _resetPeriod) {
resetInactive();
}
return; // TODO cc
}
}
void DW1000RangingClass::checkForInactiveDevices() {
for(uint8_t i = 0; i < _networkDevicesNumber; i++) {
if(_networkDevices[i].isInactive()) {
if(_handleInactiveDevice != 0) {
(*_handleInactiveDevice)(&_networkDevices[i]);
}
//we need to delete the device from the array:
removeNetworkDevices(i);
}
}
}
// TODO check return type
int16_t DW1000RangingClass::detectMessageType(byte datas[]) {
if(datas[0] == FC_1_BLINK) {
return BLINK;
}
else if(datas[0] == FC_1 && datas[1] == FC_2) {
//we have a long MAC frame message (ranging init)
return datas[LONG_MAC_LEN];
}
else if(datas[0] == FC_1 && datas[1] == FC_2_SHORT) {
//we have a short mac frame message (poll, range, range report, etc..)
return datas[SHORT_MAC_LEN];
}
}
void DW1000RangingClass::loop() {
//we check if needed to reset !
checkForReset();
uint32_t time = millis(); // TODO other name - too close to "timer"
if(time-timer > _timerDelay) {
timer = time;
timerTick();
}
if(_sentAck) {
_sentAck = false;
// TODO cc
int messageType = detectMessageType(data);
if(messageType != POLL_ACK && messageType != POLL && messageType != RANGE)
return;
//A msg was sent. We launch the ranging protocole when a message was sent
if(_type == ANCHOR) {
if(messageType == POLL_ACK) {
DW1000Device* myDistantDevice = searchDistantDevice(_lastSentToShortAddress);
DW1000.getTransmitTimestamp(myDistantDevice->timePollAckSent);
}
}
else if(_type == TAG) {
if(messageType == POLL) {
DW1000Time timePollSent;
DW1000.getTransmitTimestamp(timePollSent);
//if the last device we send the POLL is broadcast:
if(_lastSentToShortAddress[0] == 0xFF && _lastSentToShortAddress[1] == 0xFF) {
//we save the value for all the devices !
for(uint16_t i = 0; i < _networkDevicesNumber; i++) {
_networkDevices[i].timePollSent = timePollSent;
}
}
else {
//we search the device associated with the last send address
DW1000Device* myDistantDevice = searchDistantDevice(_lastSentToShortAddress);
//we save the value just for one device
myDistantDevice->timePollSent = timePollSent;
}
}
else if(messageType == RANGE) {
DW1000Time timeRangeSent;
DW1000.getTransmitTimestamp(timeRangeSent);
//if the last device we send the POLL is broadcast:
if(_lastSentToShortAddress[0] == 0xFF && _lastSentToShortAddress[1] == 0xFF) {
//we save the value for all the devices !
for(uint16_t i = 0; i < _networkDevicesNumber; i++) {
_networkDevices[i].timeRangeSent = timeRangeSent;
}
}
else {
//we search the device associated with the last send address
DW1000Device* myDistantDevice = searchDistantDevice(_lastSentToShortAddress);
//we save the value just for one device
myDistantDevice->timeRangeSent = timeRangeSent;
}
}
}
}
//check for new received message
if(_receivedAck) {
_receivedAck = false;
//we read the datas from the modules:
// get message and parse
DW1000.getData(data, LEN_DATA);
int messageType = detectMessageType(data);
//we have just received a BLINK message from tag
if(messageType == BLINK && _type == ANCHOR) {
byte address[8];
byte shortAddress[2];
_globalMac.decodeBlinkFrame(data, address, shortAddress);
//we crate a new device with th tag
DW1000Device myTag(address, shortAddress);
if(addNetworkDevices(&myTag)) {
if(_handleBlinkDevice != 0) {
(*_handleBlinkDevice)(&myTag);
}
//we reply by the transmit ranging init message
transmitRangingInit(&myTag);
noteActivity();
}
_expectedMsgId = POLL;
}
else if(messageType == RANGING_INIT && _type == TAG) {
byte address[2];
_globalMac.decodeLongMACFrame(data, address);
//we crate a new device with the anchor
DW1000Device myAnchor(address, true);
if(addNetworkDevices(&myAnchor, true)) {
if(_handleNewDevice != 0) {
(*_handleNewDevice)(&myAnchor);
}
}
noteActivity();
}
else {
//we have a short mac layer frame !
byte address[2];
_globalMac.decodeShortMACFrame(data, address);
//we get the device which correspond to the message which was sent (need to be filtered by MAC address)
DW1000Device* myDistantDevice = searchDistantDevice(address);
if((_networkDevicesNumber != 0) && (myDistantDevice == NULL)) {
Serial.println("Not found");
//we don't have the short address of the device in memory
/*
Serial.print("unknown: ");
Serial.print(address[0], HEX);
Serial.print(":");
Serial.println(address[1], HEX);
*/
return;
}
//then we proceed to range protocole
if(_type == ANCHOR) {
if(messageType != _expectedMsgId) {
// unexpected message, start over again (except if already POLL)
_protocolFailed = true;
}
if(messageType == POLL) {
//we receive a POLL which is a broacast message
//we need to grab info about it
int16_t numberDevices = 0;
memcpy(&numberDevices, data+SHORT_MAC_LEN+1, 1);
for(uint16_t i = 0; i < numberDevices; i++) {
//we need to test if this value is for us:
//we grab the mac address of each devices:
byte shortAddress[2];
memcpy(shortAddress, data+SHORT_MAC_LEN+2+i*4, 2);
//we test if the short address is our address
if(shortAddress[0] == _currentShortAddress[0] && shortAddress[1] == _currentShortAddress[1]) {
//we grab the replytime wich is for us
uint16_t replyTime;
memcpy(&replyTime, data+SHORT_MAC_LEN+2+i*4+2, 2);
//we configure our replyTime;
_replyDelayTimeUS = replyTime;
// on POLL we (re-)start, so no protocol failure
_protocolFailed = false;
DW1000.getReceiveTimestamp(myDistantDevice->timePollReceived);
//we note activity for our device:
myDistantDevice->noteActivity();
//we indicate our next receive message for our ranging protocole
_expectedMsgId = RANGE;
transmitPollAck(myDistantDevice);
noteActivity();
return;
}
}
}
else if(messageType == RANGE) {
//we receive a RANGE which is a broacast message
//we need to grab info about it
uint8_t numberDevices = 0;
memcpy(&numberDevices, data+SHORT_MAC_LEN+1, 1);
for(uint8_t i = 0; i < numberDevices; i++) {
//we need to test if this value is for us:
//we grab the mac address of each devices:
byte shortAddress[2];
memcpy(shortAddress, data+SHORT_MAC_LEN+2+i*17, 2);
//we test if the short address is our address
if(shortAddress[0] == _currentShortAddress[0] && shortAddress[1] == _currentShortAddress[1]) {
//we grab the replytime wich is for us
DW1000.getReceiveTimestamp(myDistantDevice->timeRangeReceived);
noteActivity();
_expectedMsgId = POLL;
if(!_protocolFailed) {
myDistantDevice->timePollSent.setTimestamp(data+SHORT_MAC_LEN+4+17*i);
myDistantDevice->timePollAckReceived.setTimestamp(data+SHORT_MAC_LEN+9+17*i);
myDistantDevice->timeRangeSent.setTimestamp(data+SHORT_MAC_LEN+14+17*i);
// (re-)compute range as two-way ranging is done
DW1000Time myTOF;
computeRangeAsymmetric(myDistantDevice, &myTOF); // CHOSEN RANGING ALGORITHM
float distance = myTOF.getAsMeters();
if (_useRangeFilter) {
//Skip first range
if (myDistantDevice->getRange() != 0.0f) {
distance = filterValue(distance, myDistantDevice->getRange(), _rangeFilterValue);
}
}
myDistantDevice->setRXPower(DW1000.getReceivePower());
myDistantDevice->setRange(distance);
myDistantDevice->setFPPower(DW1000.getFirstPathPower());
myDistantDevice->setQuality(DW1000.getReceiveQuality());
//we send the range to TAG
transmitRangeReport(myDistantDevice);
//we have finished our range computation. We send the corresponding handler
_lastDistantDevice = myDistantDevice->getIndex();
if(_handleNewRange != 0) {
(*_handleNewRange)();
}
}
else {
transmitRangeFailed(myDistantDevice);
}
return;
}
}
}
}
else if(_type == TAG) {
// get message and parse
if(messageType != _expectedMsgId) {
// unexpected message, start over again
//not needed ?
return;
_expectedMsgId = POLL_ACK;
return;
}
if(messageType == POLL_ACK) {
DW1000.getReceiveTimestamp(myDistantDevice->timePollAckReceived);
//we note activity for our device:
myDistantDevice->noteActivity();
//in the case the message come from our last device:
if(myDistantDevice->getIndex() == _networkDevicesNumber-1) {
_expectedMsgId = RANGE_REPORT;
//and transmit the next message (range) of the ranging protocole (in broadcast)
transmitRange(NULL);
}
}
else if(messageType == RANGE_REPORT) {
float curRange;
memcpy(&curRange, data+1+SHORT_MAC_LEN, 4);
float curRXPower;
memcpy(&curRXPower, data+5+SHORT_MAC_LEN, 4);
if (_useRangeFilter) {
//Skip first range
if (myDistantDevice->getRange() != 0.0f) {
curRange = filterValue(curRange, myDistantDevice->getRange(), _rangeFilterValue);
}
}
//we have a new range to save !
myDistantDevice->setRange(curRange);
myDistantDevice->setRXPower(curRXPower);
//We can call our handler !
//we have finished our range computation. We send the corresponding handler
_lastDistantDevice = myDistantDevice->getIndex();
if(_handleNewRange != 0) {
(*_handleNewRange)();
}
}
else if(messageType == RANGE_FAILED) {
//not needed as we have a timer;
return;
_expectedMsgId = POLL_ACK;
}
}
}
}
}
void DW1000RangingClass::useRangeFilter(boolean enabled) {
_useRangeFilter = enabled;
}
void DW1000RangingClass::setRangeFilterValue(uint16_t newValue) {
if (newValue < 2) {
_rangeFilterValue = 2;
}else{
_rangeFilterValue = newValue;
}
}
/* ###########################################################################
* #### Private methods and Handlers for transmit & Receive reply ############
* ######################################################################### */
void DW1000RangingClass::handleSent() {
// status change on sent success
_sentAck = true;
}
void DW1000RangingClass::handleReceived() {
// status change on received success
_receivedAck = true;
}
void DW1000RangingClass::noteActivity() {
// update activity timestamp, so that we do not reach "resetPeriod"
_lastActivity = millis();
}
void DW1000RangingClass::resetInactive() {
//if inactive
if(_type == ANCHOR) {
_expectedMsgId = POLL;
receiver();
}
noteActivity();
}
void DW1000RangingClass::timerTick() {
if(_networkDevicesNumber > 0 && counterForBlink != 0) {
if(_type == TAG) {
_expectedMsgId = POLL_ACK;
//send a prodcast poll
transmitPoll(NULL);
}
}
else if(counterForBlink == 0) {
if(_type == TAG) {
transmitBlink();
}
//check for inactive devices if we are a TAG or ANCHOR
checkForInactiveDevices();
}
counterForBlink++;
if(counterForBlink > 20) {
counterForBlink = 0;
}
}
void DW1000RangingClass::copyShortAddress(byte address1[], byte address2[]) {
*address1 = *address2;
*(address1+1) = *(address2+1);
}
/* ###########################################################################
* #### Methods for ranging protocole ######################################
* ######################################################################### */
void DW1000RangingClass::transmitInit() {
DW1000.newTransmit();
DW1000.setDefaults();
}
void DW1000RangingClass::transmit(byte datas[]) {
DW1000.setData(datas, LEN_DATA);
DW1000.startTransmit();
}
void DW1000RangingClass::transmit(byte datas[], DW1000Time time) {
DW1000.setDelay(time);
DW1000.setData(data, LEN_DATA);
DW1000.startTransmit();
}
void DW1000RangingClass::transmitBlink() {
transmitInit();
_globalMac.generateBlinkFrame(data, _currentAddress, _currentShortAddress);
transmit(data);
}
void DW1000RangingClass::transmitRangingInit(DW1000Device* myDistantDevice) {
transmitInit();
//we generate the mac frame for a ranging init message
_globalMac.generateLongMACFrame(data, _currentShortAddress, myDistantDevice->getByteAddress());
//we define the function code
data[LONG_MAC_LEN] = RANGING_INIT;
copyShortAddress(_lastSentToShortAddress, myDistantDevice->getByteShortAddress());
transmit(data);
}
void DW1000RangingClass::transmitPoll(DW1000Device* myDistantDevice) {
transmitInit();
if(myDistantDevice == NULL) {
//we need to set our timerDelay:
_timerDelay = DEFAULT_TIMER_DELAY+(uint16_t)(_networkDevicesNumber*3*DEFAULT_REPLY_DELAY_TIME/1000);
byte shortBroadcast[2] = {0xFF, 0xFF};
_globalMac.generateShortMACFrame(data, _currentShortAddress, shortBroadcast);
data[SHORT_MAC_LEN] = POLL;
//we enter the number of devices
data[SHORT_MAC_LEN+1] = _networkDevicesNumber;
for(uint8_t i = 0; i < _networkDevicesNumber; i++) {
//each devices have a different reply delay time.
_networkDevices[i].setReplyTime((2*i+1)*DEFAULT_REPLY_DELAY_TIME);
//we write the short address of our device:
memcpy(data+SHORT_MAC_LEN+2+4*i, _networkDevices[i].getByteShortAddress(), 2);
//we add the replyTime
uint16_t replyTime = _networkDevices[i].getReplyTime();
memcpy(data+SHORT_MAC_LEN+2+2+4*i, &replyTime, 2);
}
copyShortAddress(_lastSentToShortAddress, shortBroadcast);
}
else {
//we redefine our default_timer_delay for just 1 device;
_timerDelay = DEFAULT_TIMER_DELAY;
_globalMac.generateShortMACFrame(data, _currentShortAddress, myDistantDevice->getByteShortAddress());
data[SHORT_MAC_LEN] = POLL;
data[SHORT_MAC_LEN+1] = 1;
uint16_t replyTime = myDistantDevice->getReplyTime();
memcpy(data+SHORT_MAC_LEN+2, &replyTime, sizeof(uint16_t)); // todo is code correct?
copyShortAddress(_lastSentToShortAddress, myDistantDevice->getByteShortAddress());
}
transmit(data);
}
void DW1000RangingClass::transmitPollAck(DW1000Device* myDistantDevice) {
transmitInit();
_globalMac.generateShortMACFrame(data, _currentShortAddress, myDistantDevice->getByteShortAddress());
data[SHORT_MAC_LEN] = POLL_ACK;
// delay the same amount as ranging tag
DW1000Time deltaTime = DW1000Time(_replyDelayTimeUS, DW1000Time::MICROSECONDS);
copyShortAddress(_lastSentToShortAddress, myDistantDevice->getByteShortAddress());
transmit(data, deltaTime);
}
void DW1000RangingClass::transmitRange(DW1000Device* myDistantDevice) {
//transmit range need to accept broadcast for multiple anchor
transmitInit();
if(myDistantDevice == NULL) {
//we need to set our timerDelay:
_timerDelay = DEFAULT_TIMER_DELAY+(uint16_t)(_networkDevicesNumber*3*DEFAULT_REPLY_DELAY_TIME/1000);
byte shortBroadcast[2] = {0xFF, 0xFF};
_globalMac.generateShortMACFrame(data, _currentShortAddress, shortBroadcast);
data[SHORT_MAC_LEN] = RANGE;
//we enter the number of devices
data[SHORT_MAC_LEN+1] = _networkDevicesNumber;
// delay sending the message and remember expected future sent timestamp
DW1000Time deltaTime = DW1000Time(DEFAULT_REPLY_DELAY_TIME, DW1000Time::MICROSECONDS);
DW1000Time timeRangeSent = DW1000.setDelay(deltaTime);
for(uint8_t i = 0; i < _networkDevicesNumber; i++) {
//we write the short address of our device:
memcpy(data+SHORT_MAC_LEN+2+17*i, _networkDevices[i].getByteShortAddress(), 2);
//we get the device which correspond to the message which was sent (need to be filtered by MAC address)
_networkDevices[i].timeRangeSent = timeRangeSent;
_networkDevices[i].timePollSent.getTimestamp(data+SHORT_MAC_LEN+4+17*i);
_networkDevices[i].timePollAckReceived.getTimestamp(data+SHORT_MAC_LEN+9+17*i);
_networkDevices[i].timeRangeSent.getTimestamp(data+SHORT_MAC_LEN+14+17*i);
}
copyShortAddress(_lastSentToShortAddress, shortBroadcast);
}
else {
_globalMac.generateShortMACFrame(data, _currentShortAddress, myDistantDevice->getByteShortAddress());
data[SHORT_MAC_LEN] = RANGE;
// delay sending the message and remember expected future sent timestamp
DW1000Time deltaTime = DW1000Time(_replyDelayTimeUS, DW1000Time::MICROSECONDS);
//we get the device which correspond to the message which was sent (need to be filtered by MAC address)
myDistantDevice->timeRangeSent = DW1000.setDelay(deltaTime);
myDistantDevice->timePollSent.getTimestamp(data+1+SHORT_MAC_LEN);
myDistantDevice->timePollAckReceived.getTimestamp(data+6+SHORT_MAC_LEN);
myDistantDevice->timeRangeSent.getTimestamp(data+11+SHORT_MAC_LEN);
copyShortAddress(_lastSentToShortAddress, myDistantDevice->getByteShortAddress());
}
transmit(data);
}
void DW1000RangingClass::transmitRangeReport(DW1000Device* myDistantDevice) {
transmitInit();
_globalMac.generateShortMACFrame(data, _currentShortAddress, myDistantDevice->getByteShortAddress());
data[SHORT_MAC_LEN] = RANGE_REPORT;
// write final ranging result
float curRange = myDistantDevice->getRange();
float curRXPower = myDistantDevice->getRXPower();
//We add the Range and then the RXPower
memcpy(data+1+SHORT_MAC_LEN, &curRange, 4);
memcpy(data+5+SHORT_MAC_LEN, &curRXPower, 4);
copyShortAddress(_lastSentToShortAddress, myDistantDevice->getByteShortAddress());
transmit(data, DW1000Time(_replyDelayTimeUS, DW1000Time::MICROSECONDS));
}
void DW1000RangingClass::transmitRangeFailed(DW1000Device* myDistantDevice) {
transmitInit();
_globalMac.generateShortMACFrame(data, _currentShortAddress, myDistantDevice->getByteShortAddress());
data[SHORT_MAC_LEN] = RANGE_FAILED;
copyShortAddress(_lastSentToShortAddress, myDistantDevice->getByteShortAddress());
transmit(data);
}
void DW1000RangingClass::receiver() {
DW1000.newReceive();
DW1000.setDefaults();
// so we don't need to restart the receiver manually
DW1000.receivePermanently(true);
DW1000.startReceive();
}
/* ###########################################################################
* #### Methods for range computation and corrections #######################
* ######################################################################### */
void DW1000RangingClass::computeRangeAsymmetric(DW1000Device* myDistantDevice, DW1000Time* myTOF) {
// asymmetric two-way ranging (more computation intense, less error prone)
DW1000Time round1 = (myDistantDevice->timePollAckReceived-myDistantDevice->timePollSent).wrap();
DW1000Time reply1 = (myDistantDevice->timePollAckSent-myDistantDevice->timePollReceived).wrap();
DW1000Time round2 = (myDistantDevice->timeRangeReceived-myDistantDevice->timePollAckSent).wrap();
DW1000Time reply2 = (myDistantDevice->timeRangeSent-myDistantDevice->timePollAckReceived).wrap();
myTOF->setTimestamp((round1*round2-reply1*reply2)/(round1+round2+reply1+reply2));
/*
Serial.print("timePollAckReceived ");myDistantDevice->timePollAckReceived.print();
Serial.print("timePollSent ");myDistantDevice->timePollSent.print();
Serial.print("round1 "); Serial.println((long)round1.getTimestamp());
Serial.print("timePollAckSent ");myDistantDevice->timePollAckSent.print();
Serial.print("timePollReceived ");myDistantDevice->timePollReceived.print();
Serial.print("reply1 "); Serial.println((long)reply1.getTimestamp());
Serial.print("timeRangeReceived ");myDistantDevice->timeRangeReceived.print();
Serial.print("timePollAckSent ");myDistantDevice->timePollAckSent.print();
Serial.print("round2 "); Serial.println((long)round2.getTimestamp());
Serial.print("timeRangeSent ");myDistantDevice->timeRangeSent.print();
Serial.print("timePollAckReceived ");myDistantDevice->timePollAckReceived.print();
Serial.print("reply2 "); Serial.println((long)reply2.getTimestamp());
*/
}
/* FOR DEBUGGING*/
void DW1000RangingClass::visualizeDatas(byte datas[]) {
char string[60];
sprintf(string, "%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",
datas[0], datas[1], datas[2], datas[3], datas[4], datas[5], datas[6], datas[7], datas[8], datas[9], datas[10], datas[11], datas[12], datas[13], datas[14], datas[15]);
Serial.println(string);
}
/* ###########################################################################
* #### Utils ###############################################################
* ######################################################################### */
float DW1000RangingClass::filterValue(float value, float previousValue, uint16_t numberOfElements) {
float k = 2.0f / ((float)numberOfElements + 1.0f);
return (value * k) + previousValue * (1.0f - k);
}