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
#include "mk_trace.h"
#include "mk_uwb.h"
#include "mk_phy.h"
#include "mk_misc.h"
#include "mk_wdt.h"
#include "mk_power.h"
#include "mk_sleep_timer.h"
#include "lib_ranging.h"
#include "dw_app.h"
#include "board.h"
#include "mk_calib.h"
#include "stdlib.h"
#include "mk_flash.h"
#include "global_param.h"
#if defined(MK_SS_TWR_DW_INIT)
 
extern int TagRange(void);
void Tag_uwb_init(void);
void TagListUpdate(void);
/* Ranging period: 1s */
#define RANGING_PERIOD_MS (10000)
 
/* This is the delay from the end of the poll frame transmission to the enable of the receiver */
#define POLL_TX_TO_RESP_RX_DLY_US 1000U  //yuan400
 
#define RESP_RX_TO_FINAL_TX_DLY_US 550U
 
/* Poll delay: 1s */
#define POLL_DELAY  100U //yuan100U
 
/* Receive response timeout */
#define RESP_RX_TIMEOUT_US_DEFAULT 1100U //Yuan500 10mssuccess 300jixian
#define RESP_RX_TIMEOUT_US 2000000
/* Field index in frame */
#define MSG_SEQ_NUM_IDX 2
#define FINAL_MSG_POLL_TX_TS_IDX 10
#define FINAL_MSG_RESP_RX_TS_IDX 14
#define FINAL_MSG_FINAL_TX_TS_IDX 18
#define DELAY_DEFAULT 50000
#define DELAY_BETWEEN_TWO_FRAME_UUS 400  //yuan1400
#define HALF_SECOND_TIME 62400000
 
uint16_t CmpTagInList(uint16_t tagid);
uint16_t AddNewTagIntoList(uint16_t tagid);
void AnchorListUpdate(void);
void Rank_ANchor_list_by_dis(void);
struct mk_uwb_configure
{
    uint8_t phy_work_mode; /* PHY_TX / PHY_RX / PHT_TX|PHY_RX */
    struct UWB_CONFIG_T phy_cfg;
};
uint32_t dev_id;
uint8_t group_id;
 
#ifdef DW1000
/* Default communication configuration. */
static struct mk_uwb_configure config = {//yuan
    .phy_work_mode = (uint8_t)(PHY_TX | PHY_RX),
    .phy_cfg.ch_num = UWB_CH_NUM,             /* Channel number.                           */
    .phy_cfg.code_index = 9,                  /* TRX preamble code                         */
    .phy_cfg.mean_prf = MEAN_PRF_64M,         /* Mean prf 64/128/256M                      */
    .phy_cfg.data_bit_rate = DATA_BR_6M8,     /* Data rate 6.8M                            */
    .phy_cfg.sync_sym = PREAM_LEN_64,        /* Preamble duration, length of preamble 128 */
    .phy_cfg.sfd_sym = NON_STD_NSFD5_8,          /* Identifier for SFD sequence               */
    .phy_cfg.ranging_bit = 1,                 /* ranging bit set 1                         */
    .phy_cfg.trx_mode = TRX_MODE_15_4A,  /* IEEE802.15.4z - BPRF mode                 */
    .phy_cfg.sts_pkt_cfg = STS_PKT_CFG_0,     /* SP0 Frame                                 */
    .phy_cfg.sts_segnum = STS_SEGNUM_BPRF_1,  /* Number of STS segments in the frame       */
    .phy_cfg.sts_seglen = STS_SEGLEN_BPRF_64, /* Number of symbols in an STS segment       */
    .phy_cfg.rx_ant_id = UWB_RX_ANT_3,    /* UWB RX antenna port                       */
};
#elif defined STS_MODE
static struct mk_uwb_configure config = {
    .phy_work_mode = (uint8_t)(PHY_TX | PHY_RX),
    .phy_cfg.ch_num = 5,                      /* Channel number.                           */
    .phy_cfg.code_index = 9,                  /* TRX preamble code                         */
    .phy_cfg.mean_prf = MEAN_PRF_64M,         /* Mean prf 64/128/256M                      */
    .phy_cfg.data_bit_rate = DATA_BR_6M8,     /* Data rate 6.8M                            */
    .phy_cfg.sync_sym = PREAM_LEN_128,        /* Preamble duration, length of preamble 128 */
    .phy_cfg.sfd_sym = BPRF_NSFD2_8,          /* Identifier for SFD sequence               */
    .phy_cfg.ranging_bit = 1,                 /* ranging bit set 1                         */
    .phy_cfg.trx_mode = TRX_MODE_15_4Z_BPRF,  /* IEEE802.15.4z - BPRF mode                 */
    .phy_cfg.sts_pkt_cfg = STS_PKT_CFG_1,     /* SP1 Frame                                 */
    .phy_cfg.sts_segnum = STS_SEGNUM_BPRF_1,  /* Number of STS segments in the frame       */
    .phy_cfg.sts_seglen = STS_SEGLEN_BPRF_64, /* Number of symbols in an STS segment       */
    .phy_cfg.rx_ant_id = UWB_RX_ANT_3,        /* UWB RX antenna port                       */
};
/* Use the default key and IV specified in the IEEE 802.15.4z attachment */
static struct UWB_STS_KEY_CONFIG_T sts_iv_key = {
    .sts_vcounter = 0x1F9A3DE4,
    .sts_vupper0 = 0xD37EC3CA,
    .sts_vupper1 = 0xC44FA8FB,
    .sts_vupper2 = 0x362EEB34,
    .sts_key0 = 0x14EB220F,
    .sts_key1 = 0xF86050A8,
    .sts_key2 = 0xD1D336AA,
    .sts_key3 = 0x14148674,
};
#else //MKmode
/* Default communication configuration. */
static struct mk_uwb_configure config = {
    .phy_work_mode = (uint8_t)(PHY_TX | PHY_RX),
    .phy_cfg.ch_num = 9,                      /* Channel number.                           */
    .phy_cfg.code_index = 9,                  /* TX preamble code.                         */
    .phy_cfg.mean_prf = MEAN_PRF_64M,         /* Data rate 6.8M                            */
    .phy_cfg.data_bit_rate = DATA_BR_6M8,     /* data rate 6.8M.                           */
    .phy_cfg.sync_sym = PREAM_LEN_128,        /* Preamble duration, length of preamble 128 */
    .phy_cfg.sfd_sym = BPRF_NSFD2_8,          /* Identifier for SFD sequence               */
    .phy_cfg.ranging_bit = 1,                 /* ranging bit set.                          */
    .phy_cfg.trx_mode = TRX_MODE_15_4Z_BPRF,  /* IEEE802.15.4z - BPRF mode                 */
    .phy_cfg.sts_pkt_cfg = STS_PKT_CFG_0,     /* SP0 Frame                                 */
    .phy_cfg.sts_segnum = STS_SEGNUM_BPRF_1,  /* Number of STS segments in the frame       */
    .phy_cfg.sts_seglen = STS_SEGLEN_BPRF_64, /* Number of symbols in an STS segment       */
    .phy_cfg.rx_ant_id = UWB_RX_ANT_3,        /* UWB RX antenna port                       */
};
#endif
///* Default communication configuration. */
//static struct mk_uwb_configure config = {
//    .phy_work_mode = (uint8_t)(PHY_TX | PHY_RX),
//    .phy_cfg.ch_num = 5,                      /* Channel number.                           */
//    .phy_cfg.code_index = 3,                  /* TX preamble code.                         */
//    .phy_cfg.mean_prf = MEAN_PRF_16M,         /* Data rate 6.8M                            */
//    .phy_cfg.data_bit_rate = DATA_BR_110K,     /* data rate 6.8M.                           */
//    .phy_cfg.sync_sym = PREAM_LEN_1024,        /* Preamble duration, length of preamble 128 */
//    .phy_cfg.sfd_sym = NSFD_64,          /* Identifier for SFD sequence               */
//    .phy_cfg.ranging_bit = 1,                 /* ranging bit set.                          */
//    .phy_cfg.trx_mode = TRX_MODE_15_4A,  /* IEEE802.15.4z - BPRF mode                 */
//    .phy_cfg.sts_pkt_cfg = STS_PKT_CFG_0,     /* SP0 Frame                                 */
//    .phy_cfg.sts_segnum = STS_SEGNUM_BPRF_1,  /* Number of STS segments in the frame       */
//    .phy_cfg.sts_seglen = STS_SEGLEN_BPRF_64, /* Number of symbols in an STS segment       */
//    .phy_cfg.rx_ant_id = UWB_RX_ANT_3,    /* UWB RX antenna port                       */
//};
/* Buffer to store received frame */
static uint8_t rx_buf[150];
static uint8_t uwb_sendbuffer[150];
/*     Frames used in the ranging process
 *     Poll message:
 *     - byte 0 - 1: 0x8841 to indicate a data frame using 16-bit addressing.
 *     - byte 2: sequence number, incremented for each new frame.
 *     - byte 3 - 4: PAN Id 0x4B4d
 *     - byte 5 - 6: Destination address
 *     - byte 7 - 8: Source address
 *     - byte 9: Message type (0x02 RANGING_POLL / 0x03 RANGING_RESPONSE / 0x04 RANGING_FINAL)
 *     Response message:
 *     - byte 10: activity code (0x07 to tell the initiator to go on with the ranging exchange)
 *     Final message:
 *     - byte 10 - 13: poll message transmission timestamp.
 *     - byte 14 - 17: response message reception timestamp.
 *     - byte 18 - 21: final message transmission timestamp.
 */
static uint8_t tx_poll_msg[] = {0x41, 0x88, 0, 0x4D, 0x4B, 0x53, 0x45, 0x4D, 0x49, 0x02};
static uint8_t rx_resp_msg[] = {0x41, 0x88, 0, 0x4D, 0x4B, 0x4D, 0x49, 0x53, 0x45, 0x03, 0x07};
static uint8_t tx_final_msg[] = {0x41, 0x88, 0, 0x4D, 0x4B, 0x53, 0x45, 0x4D, 0x49, 0x04, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
 
/* Count value of phy counter when transmitting and receiving frames */
static uint32_t poll_tx_en_start_u32;
static uint32_t resp_rx_en_start_u32;
static uint32_t final_tx_en_start_u32;
 
/* 41 bits timestamps of frames transmission/reception. */
static int64_t poll_tx_ts_i64;
static int64_t resp_rx_ts_i64;
static int64_t final_tx_ts_i64;
 
/* Frame sequence number, incremented after each transmission. */
static uint8_t frame_seq_nb = 0;
 
static volatile uint16_t rx_state;
static volatile uint16_t rx_state1;
static volatile uint16_t rx_length;
//DW
uint16_t rec_nearbaseid;
uint8_t temp_tag_num;
int32_t test2;
static uint8_t receive_flag=0;
static uint8_t rec_tag_index,tag_num_tosend;
uint16_t  taglist_total_num,taglist_current_index;  //µ±Ç°Áбí×ÜÊýÁ¿
 
uint32_t start_receive_count,end_receive_count,poll_timeout,current_count,temp_resp;
uint8_t  taglist_keeptime[MAX_TAG_LIST_NUM]; //ÿ¸ö±êÇ©´æ»îʱ¼ä
uint16_t taglist_id[MAX_TAG_LIST_NUM],taglist_dist[MAX_TAG_LIST_NUM],temp_index; //±êÇ©¾àÀëºÍ±êÇ©µÄID
 
int32_t mainbase_dist,nearbase_distlist[MAX_NEARBASE_NUM],true_nearbase_distlist[MAX_NEARBASE_NUM],true_exsistbase_list[MAX_NEARBASE_NUM],ancsync_time,nextpoll_delaytime,offsettimeus;
uint8_t anclost_times=0 , mainbase_lost_count=0,exsistbase_list[MAX_NEARBASE_NUM],get_newbase=0,nearbase_num,last_nearbase_num,next_nearbase_num;
uint16_t nearbaseid_list[MAX_NEARBASE_NUM],mainbase_id,true_nearbase_idlist[MAX_NEARBASE_NUM],rec_nearbaseid,rec_nearbasepos;
uint16_t u16_nearbase_distlist[MAX_NEARBASE_NUM];
uint32_t temp_count1=0;
uint32_t temp_count2=0;
uint32_t temp_count3=0;
uint32_t temp_count4=0;
uint32_t tempflag=0;
int32_t freq_offset,freq_offset_filter; 
int temp_flag,poll_tx_num,resp_rx_num;
extern double distance;
extern uint8_t bat_percent;
uint32_t count1,count2;
extern uint32_t reboot_num;
enum SIMPLE_FSM_T
{
    SIMPLE_IDLE = 0,
    SIMPLE_POLL = 1,
    SIMPLE_RESPONSE = 2,
    SIMPLE_FINAL = 3,
};
void uwb_poll_buffer_construct(void)
{
//    for(uint8_t i=0;i<nearbase_num;i++)   //±êÇ©¾àÀë32λת³É16λ
//{
//    u16_nearbase_distlist[i] = nearbase_distlist[i];
//}
    
     tag_num_tosend = taglist_total_num-taglist_current_index;
    if(tag_num_tosend>SEND_GROUP_MAX_NUM)  //Õâ´Î·¢µÄÊýÁ¿
    {
        tag_num_tosend = SEND_GROUP_MAX_NUM;
    }
    memcpy(&uwb_sendbuffer[7],&g_com_map[VERSION],2);
        uwb_sendbuffer[GROUP_ID_IDX] = group_id;
        memcpy(&uwb_sendbuffer[TAG_ID_IDX],&dev_id,2);
        uwb_sendbuffer[BATTARY_IDX] = bat_percent;
    uwb_sendbuffer[SEQUENCE_IDX] = frame_seq_nb++;
        uwb_sendbuffer[NEARBASENUM_INDEX] = tag_num_tosend;
        memcpy(&uwb_sendbuffer[NEARBASEID_INDEX],&taglist_id[taglist_current_index],tag_num_tosend*2);//»ùÕ¾id
    memcpy(&uwb_sendbuffer[NEARBASEID_INDEX+tag_num_tosend*2],&taglist_dist[taglist_current_index],tag_num_tosend*2);
        uwb_sendbuffer[MESSAGE_TYPE_IDX] = MBX_POLL;    
        memcpy(&uwb_sendbuffer[ANCHOR_ID_IDX],&mainbase_id,2);
    
}
 
static enum SIMPLE_FSM_T state = SIMPLE_IDLE;
 
/**
 * @brief Correct TX timestamp of the ranging frame.
 *
 * @param[in] timestamp    PHY timer count of TX
 * @return TX timestamp (unit: 15.65ps)
 */
static int64_t ranging_tx_time_correct(uint32_t timestamp)
{
    int64_t tx_timestamp = ranging_tx_time(timestamp);
 
    // correct antenna delay (TX using the same antenna as RX)
    tx_timestamp += ranging_ant_delays_get(config.phy_cfg.rx_ant_id) / 2;
 
    return tx_timestamp;
}
 
/**
 * @brief Correct RX timestamp of the ranging frame.
 *
 * @param[in] ind    MAC RX report
 * @return RX timestamp (unit: 15.65ps)
 */
static int64_t ranging_rx_time_correct(const struct MAC_HW_REPORT_T *ind)
{
    int64_t rx_timestamp = ranging_rx_time(ind);
 
    // correct antenna delay
    rx_timestamp -= ranging_ant_delays_get(config.phy_cfg.rx_ant_id) / 2;
 
    return rx_timestamp;
}
uint32_t temp_rx_first_stamp,temp_rx_second_stamp;
uint16_t temp_rx_first_id,temp_rx_second_id;
/* RX done process handler. */
static void rx_int_callback(struct MAC_HW_REPORT_T *rx_report)
{
    // Power off radio
    power_off_radio();
        //tempflag=uwb_rx(0, 0, RESP_RX_TIMEOUT_US);
    rx_state = rx_report->err_code;
 
    /** UWB RX success */
    if (rx_state == UWB_RX_OK)
    {
        /* Received data does not contain FCS */
        rx_length = rx_report->pkt_len;
        memcpy(rx_buf, rx_report->pkt_data, rx_length);
        /* Calculate rx timestamp */
        resp_rx_ts_i64 = ranging_rx_time_correct(rx_report);
//            if(temp_rx_first_stamp==0)
//            {
//            temp_rx_first_stamp=(uint32_t)resp_rx_ts_i64;
//            memcpy(&temp_rx_first_id,&rx_buf[1],2);
//            }else{
//            memcpy(&temp_rx_second_id,&rx_buf[1],2);
//            temp_rx_second_stamp=(uint32_t)resp_rx_ts_i64;
//            }
                temp_count1=phy_timer_count_get();
                    //»ñÈ¡·¢Éä¶ËʱÖÓÆ«²î
            resp_rx_num++;
            freq_offset=phy_freq_offset_get();
            
        //    freq_offset_filter=average_filter(freq_offset);//»ñȡƵƫ
            //int32_t ppm = freq_offset_filter / (int32_t)(ch_center_freq_map[UWB_CH_NUM] * 1e-6);
            //calib_xtal38m4_load_cap_auto_tune(ppm);//ÀûÓõçÈݵ÷Õû¾§ÕñÊÊÅäÆµÆ«Ó¦ÔÚÍêÕûµÄÒ»°üÖ®ºóµ÷Õû£¬ÐèÒª¹Ø±ÕXTAL_AUTO_TUNE_EN ºê¶¨Òå±ÜÃâÊÕ°üÖÐ;У׼µ¼Ö²â¾à´íÎó
            //LOG_INFO(TRACE_MODULE_APP, "poll_tx_num is %d,resp_rx_num is %d,distance is %lf\r\n",poll_tx_num,resp_rx_num,distance);    
            receive_flag=1;
            
    }
    else
    {
        /* UWB_PLD_ERR     payload error             */
        /* UWB_PHR_ERR     PHR error                 */
        /* UWB_SFD_ERR     Sfd error                 */
        /* UWB_BD_ERR      Preamble detection error  */
        /* UWB_TO_ERR      Receive timeout           */
        /* UWB_STS_ERR     STS error                 */
                rx_state1=rx_report->err_code;    
        rx_length = 0;
                receive_flag=2;
            temp_count2=phy_timer_count_get();
            
    }
        //tempflag=uwb_rx(0, 0, RESP_RX_TIMEOUT_US);//Á¢¼´¿ªÆô½ÓÊܲ¢ÉèÖÃ0³¬Ê±
}
 
/* TX done process handler. */
static void tx_int_callback(struct MAC_HW_REPORT_T *tx_report)
{
    // Power off radio
    power_off_radio();
 
    /** UWB TX success */
    if (tx_report->err_code == UWB_TX_OK)
    {
            poll_tx_num++;
            temp_count4=phy_timer_count_get();//²âÊÔ
            if(temp_flag){
                count2=phy_timer_count_get();
                temp_flag=0;
                return;
            }
            count1=temp_count1;
                temp_flag=1;
    }
}
 
 
 
//×¢Ò⣺ÒòΪÐÂ×¢²áµÄ±êÇ©²¢²»ÖªµÀ»ùÕ¾ÒѾ­ÊÕµ½ÁË£¬ËùÒÔÒªÔÚÏÂÒ»°üÁ¢¿Ì½«ÐµıêÇ©ID·¢³ö£¬·ñÔò±êÇ©»áÒ»Ö±ÇÀÕ¼»ùÕ¾µÄpoll°ü¡£
//·½·¨Êǽ«ÐÂ×¢²áµÄ±êÇ©Ìí¼Óµ½Ï´η¢Ë͵ıêÇ©ÁбíÍ·²¿£¬ÆäËû±êÇ©ÒÀ´ÎÏòºóŲ¶¯¡£
uint16_t AddNewTagIntoList(uint16_t tagid)  
{                                       
     uint16_t newindex_cal = taglist_current_index+SEND_GROUP_MAX_NUM;//µ±Ç°Ë÷Òý+25£¬ÎªÏ´ÎË÷ÒýÒª·¢³öµÄÖµµÄ×î´óÖµ£¬Èç¹û×ÜÊýСÓÚÕâ¸öÖµ£¬¼´¿É·Åµ½×îºóÃæ¡£
      if(newindex_cal>=taglist_total_num) //Èç¹ûµ±Ç°Ë÷ÒýÊÇ×îºóÒ»°ü£¬ÄÇô¾Í¼Óµ½×ÜË÷ÒýµÄºóÃæ£¬Èç¹û²»ÊǾͼӵ½ÏÂÒ»´ÎÆðʼË÷ÒýλÖá£
      {
        newindex_cal = taglist_total_num;
          
      }else{           
         for(uint16_t i=taglist_total_num;i>newindex_cal;i--)  //´ÓºóÍùǰŲµØ·½??¾ÍÊDzåÈë
            {
                taglist_id[i]=taglist_id[i-1];
                taglist_dist[i]=taglist_dist[i-1];
                taglist_keeptime[i]=taglist_keeptime[i-1];
            }          
      }
      taglist_total_num++;
      taglist_id[newindex_cal] = tagid;
      taglist_dist[newindex_cal] = 0;
      taglist_keeptime[newindex_cal] = KEEP_TIMES;
      return newindex_cal;
}
uint8_t FindNearBasePos(uint16_t baseid)//ѰÕÒµ±Ç°ÁбíÖеĻùÕ¾·µ»ØË÷Òý
{
    uint8_t i;
    for(i=0;i<nearbase_num;i++)
    {
        if(baseid==nearbaseid_list[i])
            return i;
    }
    if(i==nearbase_num)
        return nearbase_num;
}
 
void AnchorListUpdate(void)
{
    next_nearbase_num = 0;
            int j=0;
            for(int i=0;i<nearbase_num;i++)
            {
                if(exsistbase_list[i]>0)
                {    
          exsistbase_list[i]--;    
                    next_nearbase_num++;
                    true_exsistbase_list[j]=exsistbase_list[i];
                    true_nearbase_idlist[j]=nearbaseid_list[i];            
                    true_nearbase_distlist[j++]=nearbase_distlist[i];
                    
                }
            }
            nearbase_num = next_nearbase_num;//¸üÐÂÏÖ´æ»ùÕ¾Êý
            last_nearbase_num = next_nearbase_num;//¸üе±Ç°»ùÕ¾Êý
}
int temp_j;
void TagListUpdate(void)
{
    uint16_t i,j=0,temp[TAG_NUM_IN_SYS];
    for(i=0;i<taglist_total_num;i++)
    {
        if(taglist_keeptime[i]-->0)
        {
            taglist_id[j]=taglist_id[i];
            taglist_keeptime[j++]=taglist_keeptime[i];//×Ô¶¯¸²¸Ç£¬¼´´ÓǰÍùºóѰÕÒ´æ»îʱ¼äΪ0µÄ±êÇ©£¬²¢°ÑËüÓúóÃæÀëµÃ×î½üµÄµÚÒ»¸öÓÐЧ´æ»îµÄ±êÇ©¸²¸Ç£¬ÄÇô×îºójµÄÖµ¾ÍÊǵ±Ç°ÓÐЧ¸öÊý
        }
    }
    temp_j=j;
    taglist_total_num=j;
}
void Rank_ANchor_list_by_dis(void)//°´ÕÕĿǰµÄ»ùÕ¾¾àÀë½øÐÐðÅÝÅÅÐòÓÃÁÙʱÊý×鷽ʽ½«×î½üµÄ·Åµ½×îÇ°Ãæ£¬×îÔ¶µÄ·Åµ½×îºóÃæ
{
for(int i=0;i<last_nearbase_num-1;i++)
            {
                for(int j=0;j<last_nearbase_num-1;j++)
                {
                    if(true_nearbase_distlist[j]>true_nearbase_distlist[j+1])
                    {
                        uint32_t temp_dist,temp_id,temp_exsis;
                        temp_dist=true_nearbase_distlist[j];
                        temp_id = true_nearbase_idlist[j];
                        temp_exsis=true_exsistbase_list[i];
                        true_nearbase_distlist[j]=true_nearbase_distlist[j+1];
                        true_nearbase_idlist[j]=true_nearbase_idlist[j+1];
                        true_exsistbase_list[j]=true_exsistbase_list[j+1];
                        
                        true_nearbase_distlist[j+1]=temp_dist;
                        true_nearbase_idlist[j+1]=temp_id;
                        true_exsistbase_list[j+1]=temp_exsis;
                    }            
                }
            }
            for (int i=0;i<last_nearbase_num;i++)
            {
                nearbaseid_list[i]=true_nearbase_idlist[i];
                nearbase_distlist[i]=true_nearbase_distlist[i];
                exsistbase_list[i] = true_exsistbase_list[i];
            }
}
uint16_t CmpTagInList(uint16_t tagid)//ÕÒÕâ¸öÐÂÒ»°üµÄ»ùÕ¾ÔÚ²»ÔÚÏÖ´æµÄtaglistÖÐÔڵϰ¶ÔӦλÖøüдæ»îʱ¼ä£¬²»ÔÚ¾ÍÔö¼Ó£¨È·±£ÓÐЧÊýÁ¿Ð¡ÓÚ×î´óÉèÖÃÊý£©
{
    uint16_t temp;
    for(uint8_t i=0;i<taglist_total_num;i++)
    {
        if(memcmp(&tagid,&taglist_id[i],2)==0)
        {
            taglist_keeptime[i] = KEEP_TIMES;
            return i;
        }
    }
    if(taglist_total_num<MAX_TAG_LIST_NUM)
    temp = AddNewTagIntoList(tagid);
    return temp;
}
uint32_t count_index;
int tt=1;
float freqlost_count;
void Tag_uwb_init(void)
{
 // The following peripherals will be initialized in the uwb_open function
    // phy/mac/aes/lsp/phy timers initialized
            uwb_open();
#ifdef STS_MODE
       // Set STS key and IV
    phy_sts_key_configure(&sts_iv_key);
#endif
    // Set calibration parameters
    uwb_calibration_params_set(config.phy_cfg.ch_num);
#ifdef STS_MODE
    
     // set advanced parameters
    struct PHY_ADV_CONFIG_T adv_config = {
        .thres_fap_detect = 40,
        .nth_scale_factor = 4,
        .ranging_performance_mode = 3,
        .skip_weakest_port_en = 0,
    };
#else
    // set advanced parameters
     struct PHY_ADV_CONFIG_T adv_config = {
        .thres_fap_detect = 40,
        .nth_scale_factor = 4,
        .ranging_performance_mode = 0,
        .skip_weakest_port_en = 0,
    };
#endif
    phy_adv_params_configure(&adv_config);
 
    // uwb configure
    uwb_configure(config.phy_work_mode, board_param.tx_power_fcc[CALIB_CH(config.phy_cfg.ch_num)], &config.phy_cfg);
#if (defined STS_MODE) || (defined MK_MODE)
        ranging_lib_init();
#endif
    ranging_frame_type_set(config.phy_cfg.sts_pkt_cfg);
 
}
int sleep_time_step=SLEEP_COUNT;
int rand_temp;
static uint16_t source_id;
uint8_t rec_index,rec_secdelay;
uint16_t rec_value;
uint8_t readgcom_flag;
uint16_t wg_report_id;
uint16_t rec_wenjian_daxiao;
uint16_t wangguan_up_id;
uint8_t shengji_flag,time=5;
uint8_t LoraUp_flag;
extern uint16_t final_bag_num;
uint16_t checksum1;
void Uwb_Update(void)
{
                                            
                    checksum1=Checksum_u16(rx_buf,rx_length-2);
                    if(!memcmp(&checksum1,&rx_buf[rx_length-2],2))
                    if(!memcmp(&dev_id,&rx_buf[DEST_ID_IDX],2))
                    {
                       memcpy(&source_id,&rx_buf[SOURCE_ID_IDX],2); 
//                        if(wg_state==WG_Lost)
//                        {
//                            wg_state = WG_Connected;
                            wg_report_id = source_id;
//                        }
//                        if(!memcmp(&wg_report_id,&rx_buf[SOURCE_ID_IDX],2))
//                        {
//                            wg_lost_count = 0;
//                            loraled=GREEN;
                            switch(rx_buf[PWTAG_RW_FLAG_IDX])
                            {
                                case WGRSP_RWTAG_READ:
                                    readgcom_flag = 1;
//                                    LoraSendComMap(WGRSP_RWTAG_READ);
                                    break;
                                case WGRSP_RWTAG_WRITE:
                                    rec_index = rx_buf[PWTAG_WRITE_IDX_IDX];
                                    if(rec_index<=DEV_ID)
                                    {break;}
                                    memcpy(&rec_value,&rx_buf[PWTAG_WRITE_VALUE_IDX],2);
                                    if(g_com_map[rec_index/2]==rec_value)
                                    {break;}
                                    g_com_map[rec_index/2] = rec_value;
                                    save_com_map_to_flash();
                                    delay_us(60000);
                                    NVIC_SystemReset();
                                    break; 
                                case WGRSP_RWTAG_UPDATE:
                                rec_index = rx_buf[PWTAG_WRITE_IDX_IDX];
                                switch(rec_index)
                                {
                                    case 0xaa:  //Éý¼¶Ï·¢
                                    memcpy(&rec_wenjian_daxiao,&rx_buf[11],2);//Îļþ´óС
                                    if(rec_wenjian_daxiao>APP_SIZE||rec_wenjian_daxiao==0)
                                    {}//Îļþ¹ý´ó£¬³¬³ö·¶Î§
                                    else
                                    {
                                    final_bag_num=(rec_wenjian_daxiao/ONE_BAG_DAXIAO)+1;    
                                    memcpy(&wangguan_up_id,&rx_buf[SOURCE_ID_IDX],2);//Íø¹ØID Õ¼ÓÃ2¸ö×Ö½Ú
                                    shengji_flag=1;
                                    LoraUp_flag=1;    
                                    LOG_INFO(TRACE_MODULE_APP, "½øÈëÉý¼¶Ä£Ê½,½ÓÊÕÎļþ´óС%d\r\n",rec_wenjian_daxiao); 
                                    }
                                        break;                        
                                }
                                    break; 
                            }
//                        }
                    }
}
int TagRange(void)
{        
    if(readgcom_flag)
  {
    readgcom_flag=0;
    phy_timer_open(1, IRQ_PRIORITY_HIGH);
    mac_register_process_handler(tx_int_callback, rx_int_callback); 
    uint8_t data_length = 0x50;
    uint16_t checksum = 0;
    uwb_sendbuffer[MSG_TYPE_IDX] = LORA_MSGTYPE_READPARARESP;
    uwb_sendbuffer[MSG_LENGTH] = data_length+11;
    memcpy(&uwb_sendbuffer[SOURCE_ID_IDX],&g_com_map[DEV_ID],2);
    memcpy(&uwb_sendbuffer[DEST_ID_IDX],&wg_report_id,2);
    uwb_sendbuffer[RP_CMD_IDX] = WGRSP_RWTAG_READ;
    uwb_sendbuffer[RP_INDEX_IDX] = 2;
    uwb_sendbuffer[RP_LEN_IDX] = data_length;
    memcpy(&uwb_sendbuffer[9], &g_com_map[1], data_length);
    checksum = Checksum_u16(uwb_sendbuffer,11+data_length);
    memcpy(&uwb_sendbuffer[11+data_length],&checksum,2);
//    Radio.Send(uwb_sendbuffer,data_length+13);
  //  Delay_Ms(100);
    poll_tx_en_start_u32 = phy_timer_count_get()+US_TO_PHY_TIMER_COUNT(POLL_DELAY);//·¢ËͱØÐëÒªÑÓʱ·¢ËͲſÉÒÔÓÃÓÚ²â¾à·ñÔòÁ¢¼´·¢ËÍ»á»ñȡʱ¼ä´Á²»¶Ô£¬ÐèÒª¼ÆËã³ÌÐòÔËÐÐʱ¼ä£¬±ÜÃâÉèÖùýȥʱ¼ä
    tempflag=uwb_tx(uwb_sendbuffer,data_length+13,1,poll_tx_en_start_u32);//Á¢¼´·¢ËÍ  
    poll_tx_ts_i64 = ranging_tx_time_correct(poll_tx_en_start_u32 + phy_shr_duration());//ÐÞÕýʱ¼ä´Á
    temp_count1=phy_timer_count_get();
    while(mac_is_busy());//µÈ´ý·¢ËÍÍê³É    
    }else{
            phy_timer_open(1, IRQ_PRIORITY_HIGH);
    // Register rx interrupt callback function
    mac_register_process_handler(tx_int_callback, rx_int_callback);
        //taglist_total_num=50;//²âÊÔ
 
        uwb_poll_buffer_construct();
        temp_tag_num=0;//ÁÙʱÊýÁ¿Îª0
        poll_tx_en_start_u32 = phy_timer_count_get()+US_TO_PHY_TIMER_COUNT(POLL_DELAY);//·¢ËͱØÐëÒªÑÓʱ·¢ËͲſÉÒÔÓÃÓÚ²â¾à·ñÔòÁ¢¼´·¢ËÍ»á»ñȡʱ¼ä´Á²»¶Ô£¬ÐèÒª¼ÆËã³ÌÐòÔËÐÐʱ¼ä£¬±ÜÃâÉèÖùýȥʱ¼ä
        tempflag=uwb_tx(uwb_sendbuffer,13+4*tag_num_tosend,1,poll_tx_en_start_u32);//Á¢¼´·¢ËÍ
        #ifdef BOXING
        gpio_pin_set(IO_PIN_5);//²âÊÔ
        #endif
        //LOG_INFO(TRACE_MODULE_APP, "½øÈë²â¾à",poll_tx_num,resp_rx_num,distance);    
        poll_tx_ts_i64 = ranging_tx_time_correct(poll_tx_en_start_u32 + phy_shr_duration());//ÐÞÕýʱ¼ä´Á
        temp_count1=phy_timer_count_get();
        while(mac_is_busy());//µÈ´ý·¢ËÍÍê³É
    #ifdef BOXING
        gpio_pin_clr(IO_PIN_5);//²âÊÔ
        gpio_pin_set(IO_PIN_5);//²âÊÔ
    #endif    
    temp_count2=phy_timer_count_get();
        resp_rx_en_start_u32 =  poll_tx_en_start_u32+ US_TO_PHY_TIMER_COUNT(POLL_TX_TO_RESP_RX_DLY_US);//ÉèÖ÷¢ËͶàÉÙsºó½ÓÊÕ°´target¶ÀÁ¢Ê±¼äÆðµãËã+ US_TO_PHY_TIMER_COUNT(POLL_TX_TO_RESP_RX_DLY_USΪ·¢ËͺóÒª¶à¾Ã¿ªÆô½ÓÊÕʱ¼ä
        temp_resp=resp_rx_en_start_u32;
    //tempflag=uwb_rx(1, resp_rx_en_start_u32, RESP_RX_TIMEOUT_US);//¿ªÆô½ÓÊܲ¢ÉèÖýÓÊÕ³¬Ê±
    tempflag=uwb_rx(1,resp_rx_en_start_u32, RESP_RX_TIMEOUT_US);
    
    
    start_receive_count=phy_timer_count_get();
    //poll_timeout=nearbase_num*US_TO_PHY_TIMER_COUNT(DELAY_BETWEEN_TWO_FRAME_UUS)+US_TO_PHY_TIMER_COUNT(RESP_RX_TIMEOUT_US);//¶àÒ»¸ö¶à0.4msĬÈÏ0.4ms¼ÆËãΪ0.125*4*100000,ĬÈÏ¿ªÆô1mss
    poll_timeout=US_TO_PHY_TIMER_COUNT(RESP_RX_TIMEOUT_US_DEFAULT)+tag_num_tosend*US_TO_PHY_TIMER_COUNT(DELAY_BETWEEN_TWO_FRAME_UUS);
    end_receive_count=start_receive_count+poll_timeout;
    
    if(end_receive_count>=UINT32_MAX)
    {end_receive_count-=UINT32_MAX;}
    current_count=phy_timer_count_get();        
    count_index=end_receive_count+HALF_SECOND_TIME;
//    if(tt){
    while(current_count<end_receive_count||current_count>end_receive_count+HALF_SECOND_TIME)//Ñ­»·½ÓÊܰüÌå,ÈôΪ124.8KÔòÊÇ+62400000
        {
        
        current_count=phy_timer_count_get();//²»¶Ïˢе±Ç°¼ÆÊýÆ÷Öµ
        temp_count2=phy_timer_count_get();
        while(mac_is_busy())//µÈ´ý½ÓÊÕÍê³É
        {
                        IdleTask();
            current_count=phy_timer_count_get();
            if(current_count>end_receive_count&&current_count<end_receive_count+HALF_SECOND_TIME)
            {
                    break;
            }
        }
        
        temp_count3=phy_timer_count_get();
        if(receive_flag==1)//³É¹¦½ÓÊÕÊý¾Ý
        {
            receive_flag=0;
            tempflag=uwb_rx(0, 0, RESP_RX_TIMEOUT_US);//Á¢¼´¿ªÆô½ÓÊܲ¢ÉèÖÃ0³¬Ê±
            //½ÓÊճɹ¦ÔòÅжÏÊÇ·ñΪͬһ×é
                if(rx_buf[MESSAGE_TYPE_IDX] == MBX_POLL)//ÊÕµ½ÊÇÆäËûµÄ»ùÕ¾µÄPOLL°ü
                {
                rand_temp=rand()%10;
                sleep_timer_start(__MS_TO_32K_CNT(SLEEP_COUNT-rand_temp));//²âÊÔ
                }else if (rx_buf[MESSAGE_TYPE_IDX] == MBX_RESPONSE&&!memcmp(&rx_buf[TAG_ID_IDX],&dev_id,2)&&rx_buf[GROUP_ID_IDX]==group_id) //ÅжϽÓÊÕµ½µÄÊý¾ÝÊÇ·ñÊÇresponseÊý¾Ý
                            {    
                                reboot_num=0;//Çå0¸´Î»¼à²âÊýÖµ
                                    memcpy(&rec_nearbaseid,&rx_buf[ANCHOR_ID_IDX],2);
                                rec_tag_index = CmpTagInList(rec_nearbaseid);//µ±Ç°ÐÂÀ´µÄÕâ°üÊý¾Ý²åÈ뵱ǰ±íÖеÄλÖÃË÷Òý
                                    //rec_nearbasepos=FindNearBasePos(rec_nearbaseid);
                                    freqlost_count = 0;
                                    temp_index =rec_tag_index -taglist_current_index;
                                    SetANCTimestap(temp_index,&rx_buf[RESP_MSG_POLL_RX_TS_IDX],&rx_buf[RESP_MSG_RESP_TX_TS_IDX],(uint32_t)resp_rx_ts_i64,&rx_buf[RESP_MSG_ANC_DISTOFFSET],test2,(uint32_t)poll_tx_ts_i64);
//                                    if(rec_nearbasepos>=nearbase_num)          //·¢ÏÖеĻùÕ¾
//                                    {
//                                        //get_newbase=1;
//                                        nearbase_num++;
//                                        nearbaseid_list[rec_nearbasepos] = rec_nearbaseid;
//                                    }
//                                    exsistbase_list[rec_nearbasepos]=KEEP_TIMES;//¸üдæ»îʱ¼ä
              
                            memset(rx_buf, 0, sizeof(rx_buf));//Çå¿Õ½ÓÊÕµ½µÄÓÃÍêµÄÊý×é
                            rx_length=0;//Çå0³¤¶È
                            //uwb_rx(0, 0, RESP_RX_TIMEOUT_US);//Á¢¼´¿ªÆô½ÓÊܲ¢ÉèÖÃ0³¬Ê±
//                            while(mac_is_busy());
                            //break;//³É¹¦½ÓÊÕ¾ÍÍ˳ö
                    }else if(rx_buf[MSG_TYPE_IDX]==LORA_MSGTYPE_WGRESPTAG){
                            Uwb_Update();
          } 
        
//                #ifdef BOXING 
//        gpio_pin_clr(IO_PIN_5);//²âÊÔ
//            #endif
        }else if(receive_flag==2){//½ÓÊÕ³ö´í
        receive_flag=0;
        tempflag=uwb_rx(0, 0, RESP_RX_TIMEOUT_US);//Á¢¼´¿ªÆô½ÓÊܲ¢ÉèÖÃ0³¬Ê±
//        sleep_timer_start(__MS_TO_32K_CNT(SLEEP_COUNT-phy_timer_count_get()%30));//²âÊÔ
//            sleep_time_step=SLEEP_COUNT-phy_timer_count_get()%10;
        //tempflag=uwb_rx(0, 0, RESP_RX_TIMEOUT_US);//Á¢¼´¿ªÆô½ÓÊܲ¢ÉèÖÃ0³¬Ê±
        temp_count3=phy_timer_count_get();
//        while(mac_is_busy());
        temp_count1=phy_timer_count_get();
        }
    #ifdef BOXING 
        gpio_pin_clr(IO_PIN_5);//²âÊÔ
        gpio_pin_set(IO_PIN_5);//²âÊÔ
        #endif
        }
//    }
        #ifdef BOXING 
        gpio_pin_clr(IO_PIN_5);//²âÊÔ
        #endif
        delay_us(1);
        uwb_rx_force_off(1);
        //dwt_forecetrxoff();
         CalculateDists(poll_tx_ts_i64); //¼ÆËã¾àÀë²¢¸üоàÀë±í
            
         //Calculate_battery_percent();
        
        //LOG_INFO(TRACE_MODULE_APP,"ÏÖ´æ²â¾àÊý %d id1:%04x dist:%d .\r\n",taglist_total_num,taglist_id[0],(int16_t)taglist_dist[0]);
         //AnchorListUpdate();//¸üдæ»î»ùÕ¾Áбí
         TagListUpdate();
         taglist_current_index+=tag_num_tosend;
        if(taglist_current_index>=taglist_total_num||taglist_total_num<=SEND_GROUP_MAX_NUM) //Èç¹û±êÇ©µ±Ç°index´óÓÚ×Üindex£¬»òÕß×Ü»ùÕ¾ÊýÁ¿Ð¡ÓÚµÈÓÚ25£¬Ôò´Ó0¿ªÊ¼index¡£Ò»¸öÊÇÒѾ­·¢ÍêÒ»ÂÖÁË£¬Ò»¸öÊDz»¹»×î´ó·¢ËÍÊý
     taglist_current_index = 0;
         //Rank_ANchor_list_by_dis();//ðÅÝÅÅÐòÖØÐ°´¾àÀëÖØÐÂÅÅÁлùÕ¾Áбí×îС¾àÀë´æ»õ»ùÕ¾·Åµ½×îÇ°Ãæ
    }
}
#endif
uint16_t UpdateCRC16(uint16_t crcIn, uint8_t byte)
{
  uint32_t crc = crcIn;
  uint32_t in = byte|0x100;
 
  do
  {
    crc <<= 1;
    in <<= 1;
 
    if(in&0x100)
    {
      ++crc;
    }
    
    if(crc&0x10000)
    {
      crc ^= 0x1021;
    }
 } while(!(in&0x10000));
 
 return (crc&0xffffu);
}
 
/**
  * @brief  Cal CRC16 for YModem Packet
  * @param  data
  * @param  length
  * @retval CRC value
  */
uint16_t Cal_CRC16(const uint8_t* data, uint32_t size)
{
  uint32_t crc = 0;
  const uint8_t* dataEnd = data+size;
  
  while(data<dataEnd)
  {
    crc = UpdateCRC16(crc,*data++);
  }
  crc = UpdateCRC16(crc,0);
  crc = UpdateCRC16(crc,0);
 
  return (crc&0xffffu);
}
void delay_ms(uint32_t nTimer)  
{  
    uint32_t i=1000*nTimer;  
    delay_us(i);  
}  
uint8_t send_lora_data[250];
uint16_t muqiandeshengjibao;
static uint16_t current_count1,target_count1,end_count1,start_count1;
uint8_t huifushengjibaoerror_num;
uint16_t final_bag_num;
uint16_t testflag;
uint32_t Zhongjian_data[60];
uint8_t shengji_flag;
uint16_t wangguan_up_id;
uint8_t huifushengjibao_flag;
uint8_t LoraUp_flag;
uint16_t rec_wenjian_daxiao;
uint8_t lora_up_rec_flag;
uint16_t flash_shuju;
static uint32_t status_reg;
static uint32_t frame_len;
void LoraUp_Poll(void)
{    uint16_t  result ;
    uint16_t crc16;
    uint8_t jindu;
    if(shengji_flag)
    {
    uwb_rx_force_off(1);
    Tag_uwb_init();
    phy_timer_open(1, IRQ_PRIORITY_HIGH);
    mac_register_process_handler(tx_int_callback, rx_int_callback);
        
    send_lora_data[MSG_TYPE_IDX]=LORA_MSGTYPE_UPDATE_CONFIRM;
    memcpy(&send_lora_data[SOURCE_ID_IDX],&dev_id,2);//Íø¹ØID Õ¼ÓÃ2¸ö×Ö½Ú
    memcpy(&send_lora_data[DEST_ID_IDX],&wangguan_up_id,2);//±êÇ©»òÕß»ùÕ¾µÄÉ豸ID 2¸ö×Ö½Ú
//    send_lora_data[MUQIAN_BAG]=0xFF;
    crc16=Checksum_u16(send_lora_data,6);
    memcpy(&send_lora_data[6],&crc16,2);
    huifushengjibao_flag=0;
    LoraUp_flag=1;
         
    poll_tx_en_start_u32 = phy_timer_count_get()+US_TO_PHY_TIMER_COUNT(POLL_DELAY);//·¢ËͱØÐëÒªÑÓʱ·¢ËͲſÉÒÔÓÃÓÚ²â¾à·ñÔòÁ¢¼´·¢ËÍ»á»ñȡʱ¼ä´Á²»¶Ô£¬ÐèÒª¼ÆËã³ÌÐòÔËÐÐʱ¼ä£¬±ÜÃâÉèÖùýȥʱ¼ä
    tempflag=uwb_tx(send_lora_data,8+2,1,poll_tx_en_start_u32);//Á¢¼´·¢ËÍ  
    poll_tx_ts_i64 = ranging_tx_time_correct(poll_tx_en_start_u32 + phy_shr_duration());//ÐÞÕýʱ¼ä´Á
    temp_count1=phy_timer_count_get();
    while(mac_is_busy());//µÈ´ý·¢ËÍÍê³É        
 
    __disable_irq();
    result=flash_open(FLASH_ID0,NULL);
    flash_read(FLASH_ID0, APP2_ADRESS, (uint8_t*)&flash_shuju, 2);
    if(flash_shuju!=0xffff/*&&flash_shuju!=0x0000*/)
    {
            while(1)
        {
            flash_erase(FLASH_ID0,APP2_ADRESS,APP_SIZE);      
            delay_ms(500);
            flash_read(FLASH_ID0, APP2_ADRESS, (uint8_t*)&flash_shuju, 2);
            if(flash_shuju==0xffff/*&&flash_shuju!=0x0000*/)
            {break;}
        }
    }
    __enable_irq();
            while(1)
            {
                uwb_rx_force_off(1);
                send_lora_data[MSG_TYPE_IDX]=LORA_MSGTYPE_UPDATEFILE_REQUEST;
                memcpy(&send_lora_data[SOURCE_ID_IDX],&dev_id,2);//Íø¹ØID Õ¼ÓÃ2¸ö×Ö½Ú
                memcpy(&send_lora_data[DEST_ID_IDX],&wangguan_up_id,2);//±êÇ©»òÕß»ùÕ¾µÄÉ豸ID 2¸ö×Ö½Ú
//                send_lora_data[MUQIAN_BAG]=muqiandeshengjibao;
                memcpy(&send_lora_data[MUQIAN_BAG],&muqiandeshengjibao,2);
                crc16=Checksum_u16(send_lora_data,8);
                memcpy(&send_lora_data[8],&crc16,2);
                lora_up_rec_flag=0;    
//                LOG_INFO(TRACE_MODULE_APP, "ÕýÔÚÇëÇóµÚ%d°ü\r\n",muqiandeshengjibao);
                jindu=(muqiandeshengjibao*100)/final_bag_num;
                LOG_INFO(TRACE_MODULE_APP, "Éý¼¶½ø¶È%d\r\n",jindu);
                wdt_ping(WDT_ID0);//ι¹·
                poll_tx_en_start_u32 = phy_timer_count_get()+US_TO_PHY_TIMER_COUNT(POLL_DELAY);//·¢ËͱØÐëÒªÑÓʱ·¢ËͲſÉÒÔÓÃÓÚ²â¾à·ñÔòÁ¢¼´·¢ËÍ»á»ñȡʱ¼ä´Á²»¶Ô£¬ÐèÒª¼ÆËã³ÌÐòÔËÐÐʱ¼ä£¬±ÜÃâÉèÖùýȥʱ¼ä
                tempflag=uwb_tx(send_lora_data,10+2,1,poll_tx_en_start_u32);//Á¢¼´·¢ËÍ
                poll_tx_ts_i64 = ranging_tx_time_correct(poll_tx_en_start_u32 + phy_shr_duration());//ÐÞÕýʱ¼ä´Á
                temp_count1=phy_timer_count_get();
                while(mac_is_busy());//µÈ´ý·¢ËÍÍê³É
                temp_count2=phy_timer_count_get();
                resp_rx_en_start_u32 =  poll_tx_en_start_u32+ US_TO_PHY_TIMER_COUNT(POLL_TX_TO_RESP_RX_DLY_US);//ÉèÖ÷¢ËͶàÉÙsºó½ÓÊÕ°´target¶ÀÁ¢Ê±¼äÆðµãËã+ US_TO_PHY_TIMER_COUNT(POLL_TX_TO_RESP_RX_DLY_USΪ·¢ËͺóÒª¶à¾Ã¿ªÆô½ÓÊÕʱ¼ä
                temp_resp=resp_rx_en_start_u32;
                tempflag=uwb_rx(0,0, 50000);
                
                while(mac_is_busy())
                {}
                if(receive_flag==1)//³É¹¦½ÓÊÕÊý¾Ý
                {   uint16_t result12;
                     
                     __disable_irq();
                     crc16=Cal_CRC16(rx_buf,DATA_IDX+ONE_BAG_DAXIAO);
 
                     if(!memcmp(&muqiandeshengjibao,&rx_buf[MUQIAN_BAG],2)&&!memcmp(&crc16,&rx_buf[DATA_IDX+ONE_BAG_DAXIAO],2)&&!memcmp(&dev_id,&rx_buf[DEST_ID_IDX],2)&& !memcmp(&wangguan_up_id,&rx_buf[SOURCE_ID_IDX],2))
                     {
                     result=flash_open(FLASH_ID0,NULL);
                     memcpy(Zhongjian_data,&rx_buf[DATA_IDX],ONE_BAG_DAXIAO);
                     result12=flash_write_nbytes(FLASH_ID0, APP2_ADRESS+ONE_BAG_DAXIAO*muqiandeshengjibao, (uint8_t*)Zhongjian_data, ONE_BAG_DAXIAO);
                     while(!result12==0)
                     {
                     result12=flash_write_nbytes(FLASH_ID0, APP2_ADRESS+ONE_BAG_DAXIAO*muqiandeshengjibao, (uint8_t*)Zhongjian_data, ONE_BAG_DAXIAO);
                     delay_ms(10);    
                     }                         
                     if(result12==0)
                     {
//                         if(muqiandeshengjibao==650)
//                         {
//                         delay_ms(10);   
//                         }
                     muqiandeshengjibao++;   
                     huifushengjibaoerror_num=0;
                     delay_ms(10);       
                     }
                     }
                     __enable_irq();
                }
                else
                {
                    delay_ms(500);
                    huifushengjibaoerror_num++;
                    if(huifushengjibaoerror_num>=20)
                    {
                    huifushengjibaoerror_num=0;    
                    muqiandeshengjibao=0;
                    delay_ms(500);
                    NVIC_SystemReset();    
                    break;
                    }   
                    uwb_rx_force_off(1);
                }
                if(muqiandeshengjibao==final_bag_num)
                {
                send_lora_data[MSG_TYPE_IDX]=0x99;
                memcpy(&send_lora_data[SOURCE_ID_IDX],&dev_id,2);//Íø¹ØID Õ¼ÓÃ2¸ö×Ö½Ú
                memcpy(&send_lora_data[DEST_ID_IDX],&wangguan_up_id,2);//±êÇ©»òÕß»ùÕ¾µÄÉ豸ID 2¸ö×Ö½Ú
                crc16=Checksum_u16(send_lora_data,6);
                memcpy(&send_lora_data[6],&crc16,2);
                huifushengjibao_flag=0;
                LoraUp_flag=1;    
                LOG_INFO(TRACE_MODULE_APP, "ÕýÔÚ·¢ËÍ×îºóÒ»°ü\r\n");    
                poll_tx_en_start_u32 = phy_timer_count_get()+US_TO_PHY_TIMER_COUNT(POLL_DELAY);//·¢ËͱØÐëÒªÑÓʱ·¢ËͲſÉÒÔÓÃÓÚ²â¾à·ñÔòÁ¢¼´·¢ËÍ»á»ñȡʱ¼ä´Á²»¶Ô£¬ÐèÒª¼ÆËã³ÌÐòÔËÐÐʱ¼ä£¬±ÜÃâÉèÖùýȥʱ¼ä
                tempflag=uwb_tx(send_lora_data,8+2,1,poll_tx_en_start_u32);//Á¢¼´·¢ËÍ  
                poll_tx_ts_i64 = ranging_tx_time_correct(poll_tx_en_start_u32 + phy_shr_duration());//ÐÞÕýʱ¼ä´Á
                temp_count1=phy_timer_count_get();
                while(mac_is_busy());//µÈ´ý·¢ËÍÍê³É        
                
                uint16_t tmp11 ,result11;
                tmp11=0XDDDD;
                result=flash_open(FLASH_ID0,NULL); 
                result11=flash_erase(FLASH_ID0,APP_1OR2_ADRESS,0x1000);
                if(result11==0)
                flash_write_nbytes(FLASH_ID0, APP_1OR2_ADRESS, (uint8_t*)&tmp11, 2);
                __disable_irq();       
                delay_ms(500);
                NVIC_SystemReset(); 
                }
            }
   uwb_rx_force_off(1);
  }
}