chen
2024-11-21 34f575a6cb201ca70e142de59f1e9750b863d7f2
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
#include "mk_trace.h"
#include "mk_uwb.h"
#include "mk_phy.h"
#include "mk_misc.h"
#include "mk_power.h"
#include "mk_sleep_timer.h"
#include "lib_ranging.h"
#include "lib_aoa.h"
#include "dw_app_anchor.h"
#include "global_param.h"
#include "board.h"
#include "lib_aoa.h"
 
extern int simple_main(void);
extern int temp_main(void);
void Calibration_Time(void);
void TagListUpdate(void);
extern void IO_LED_control_change(uint8_t data);
extern void IO_control_init(void);
 
extern void updata_led_power_state(void);
/*receive buffer*/
static uint8_t rx_buf[150];
static uint8_t uwb_sendbuffer[150];
static volatile uint16_t rx_state;
static volatile uint16_t rx_length;
 
//resp±äÁ¿
static uint8_t frame_seq_nb2,battary,button,rec_nearbase_num,ancidlist_num;
static uint16_t ancidlist_rec[TAG_NUM_IN_SYS],ancidlist_send[TAG_NUM_IN_SYS],rec_ancidlist[TAG_NUM_IN_SYS];
static int16_t rec_ancdistlist[TAG_NUM_IN_SYS];
extern uint8_t group_id;
static uint16_t anc_id_recv,tag_id_recv;
static int16_t rec_antdelay;
extern uint32_t dev_id;
static uint16_t taglist_pos,tmp_time;
extern uint16_t tag_frequency;
extern uint16_t disoffset;
static uint8_t frame_len,recpoll_len,current_syncid,new_tagid,seize_anchor,result,g_start_sync_flag;
extern uint8_t gps_power_state,motor_power_state,uwb_state,air780_power_state,gps_success_state,red_charge_state,green_charge_state,air780_success_state;
int poll_rx_num,resp_tx_num;
//respº¯Êý
void PushAnchorDataArray(uint16_t ancid,int16_t dist,uint8_t battary);//ÕÒµ½×Ô¼ºµÄidÐÅÏ¢¶ÔӦλÖøüÐÂ×Ô¼ºµÄ½»»¥ÐÅÏ¢
static void resp_msg_set_ts(uint8_t *ts_field, int64_t ts);//ÓÃÀ´¶ÔӦλÖ÷ÅÈëʱ¼ä´Á
static uint16_t tagid_list[TAG_NUM_IN_SYS];
uint16_t CmpTagInList(uint16_t tagid);
uint8_t Anchor_RecNearPoll(uint8_t ancrec_nearbasepos);
static uint8_t send_buffer[100];
static uint8_t tagofflinetime[TAG_NUM_IN_SYS];
uint32_t temp_count=0;
uint32_t temp_count1=0;
uint32_t temp_count2=0;
uint32_t temp_count3=0;
uint32_t temp_internal=0;
int16_t elevation = 0;
int16_t azimuth = 0;
uint8_t fom = 0;
int32_t distance;
uint8_t taglist_num;
float *sts_rssi=NULL;
extern uint8_t recev_error_num;
 
extern Operation_step UWB_work_state;
extern int16_t first_search_flag;
/* Ranging period */
#define RANGING_PERIOD_MS (1000)
 
/* This is the delay from Frame RX POLL frame to send RESP Frame */
#define POLL_RX_TO_RESP_TX_DLY_US 1000U //yuan670 with urt 3000success
 
#define RESP_TX_TO_FINAL_RX_DLY_US 500U
 
/* RX sync window size 50 ms*/
#define RX_SYNC_WIN_US 5000U //yuan1000  7000success
 
/* RX sync window size 50 ms*/
#define RX_SYNC_WIN_US_TEMP 2000000U //yuan1000  7000success
 
/* Receive poll timeout 500us*/
#define POLL_RX_TIMEOUT_US 500
 
/* Receive final timeout 500us */
#define FINAL_RX_TIMEOUT_US 500
 
/* RX window open in advance */
#define RX_WIN_IN_ADVANCE_US (150)
 
#define DELAY_BETWEEN_TWO_FRAME_UUS 600 //yuan1400
 
/* 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 1000
#define HALF_SECOND_TIME 624000000
/* Length of the common part of the message */
#define MSG_COMMON_LEN 10
 
#define UWB_DELAY_TIME_US 496
static uint8_t receive_flag=0;
struct mk_uwb_configure
{
    uint8_t phy_work_mode; /* PHY_TX / PHY_RX / PHT_TX|PHY_RX */
    struct UWB_CONFIG_T phy_cfg;
};
 
///* Default communication configuration. */
//static struct mk_uwb_configure config = {//Ô­À´µÄ»ùÕ¾·Ç110k´úÂë
//    .phy_work_mode = (uint8_t)(PHY_TX | PHY_RX),
//    .phy_cfg.ch_num = 5,                      /* 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                       */
//};
#ifndef 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 = 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                       */
};
#else
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                       */
};
#endif
/* 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,
};
/* Buffer to store received frame */
 
/*     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 rx_poll_msg[] = {0x41, 0x88, 0, 0x4D, 0x4B, 0x53, 0x45, 0x4D, 0x49, 0x02};
static uint8_t tx_resp_msg[] = {0x41, 0x88, 0, 0x4D, 0x4B, 0x4D, 0x49, 0x53, 0x45, 0x03, 0x07};
static uint8_t rx_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_rx_en_start_u32;
static uint32_t resp_tx_en_start_u32;
static uint32_t resp_tx_timeout;
int64_t temp_resp_i64;
/* 41 bits timestamps of frames transmission/reception. */
int64_t poll_rx_ts_i64;
int64_t resp_tx_ts_i64;
int64_t final_rx_ts_i64;
 
/* Frame sequence number, incremented after each transmission. */
static uint8_t frame_seq_nb = 0;
 
/* MAC report data structure */
static struct MAC_HW_REPORT_T rx_rpt;
 
enum SIMPLE_FSM_T
{
    SIMPLE_IDLE = 0,
    SIMPLE_POLL = 1,
    SIMPLE_RESPONSE = 2,
    SIMPLE_FINAL = 3,
};
 
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;
}
 
/* RX done process handler. */
int8_t rssi;
static void rx_int_callback(struct MAC_HW_REPORT_T *rx_report)
{        uint8_t valid_sts=0;
    // Power off radio
    power_off_radio();
 
    /** UWB RX success */
    if (rx_report->err_code == UWB_RX_OK)
    {
        /* Received data does not contain FCS */
        rx_length = rx_report->pkt_len;
        memcpy(rx_buf, rx_report->pkt_data, rx_length);
        memcpy(&rx_rpt, rx_report, sizeof(struct MAC_HW_REPORT_T));
        /* Calculate rx timestamp */
        temp_count= phy_timer_count_get();
        poll_rx_en_start_u32 = rx_rpt.timestamp - phy_shr_duration();
        poll_rx_ts_i64 = ranging_rx_time_correct(&rx_rpt);
        poll_rx_num++;
        rssi = rx_report->rssi;
        receive_flag=1;
                valid_sts= sts_valid_check();
      if (valid_sts)
      {
                aoa_calculate(&elevation, &azimuth);
                aoa_fom_get(NULL, &fom);
//                float pdoa[3];
//                pdoa[0] = pdoa_select_get(0, 3);
//                pdoa[1] = pdoa_select_get(1, 3);
//                pdoa[2] = pdoa_select_get(2, 3);
//                LOG_INFO(TRACE_MODULE_APP, "PDOA: %f %f %f\r\n", pdoa[0], pdoa[1], pdoa[2]);
 
                    sts_rssi = sts_rssi_output_get();
            }
    }
    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                 */
                    temp_count= phy_timer_count_get();
        memcpy(&rx_rpt, rx_report, sizeof(struct MAC_HW_REPORT_T));
        rx_length = 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)
    {
        temp_count= phy_timer_count_get();
        temp_internal=temp_count;
        resp_tx_num++;
        //LOG_INFO(TRACE_MODULE_APP, "poll_rx_num is %d,resp_tx_num is %d\r\n",poll_rx_num,resp_tx_num);
    }
}
uint32_t start_receive_count,end_receive_count,poll_timeout,current_count,temp_resp;
static uint16_t anchordata_id[TAG_NUM_IN_SYS],anchordata_dist[TAG_NUM_IN_SYS];
static uint8_t anchordata_bat[TAG_NUM_IN_SYS];
uint8_t anchordata_num = 0;
static int32_t tagdist_list[TAG_NUM_IN_SYS];
uint16_t random_time;
//anchor
int32_t hist_dist;
int16_t temp_recdist_before_offset;
int16_t dist_temp;
void PushAnchorDataArray(uint16_t ancid,int16_t dist,uint8_t battary)
{
    uint8_t i;
    for(i=0; i<anchordata_num; i++)
    {
        if(anchordata_id[i] == ancid)//²éѯ±êÇ©ÊÇ·ñÔÚ×Ô¼ºÒÑͨѶÁбíÖÐ
        {
 
            break;
        }
    }
    if(i==anchordata_num)
    {
        if(anchordata_num<TAG_NUM_IN_SYS-1)
            anchordata_num++;
    }
    anchordata_id[i] = ancid;//Óë֮ͨÐŵıêÇ©id´æÈ뵱ǰ±íÖÐ
    anchordata_dist[i] = dist;
    anchordata_bat[i] = battary;
    tagofflinetime[i]=0;//²»¶Ï¸üе±Ç°TAG¶ÔÓ¦ÀëÏßʱ¼ä
        dist_temp=dist;
//    if(dist>0)
        if(temp_recdist_before_offset!=0&&distance!=0x1ffff)
        {
    distance=dist*0.5+distance*0.5;
        }else{
            distance=dist;
        }
}
uint16_t CmpTagInList(uint16_t tagid)
{   uint16_t i;
    for(i=0; i<taglist_num; i++)
    {
        if(memcmp(&tagid,&anchordata_id[i],2)==0)
            break;
    }
    if(i==taglist_num)
        return taglist_num;
    //tagofflinetime[i] = 0;
    return i;
}
 
static void resp_msg_set_ts(uint8_t *ts_field, int64_t ts)
{
    int i,ts2;
    ts2=(int32_t)ts;
    for (i = 0; i < 4; i++)
    {
        ts_field[i] = (uint8_t)ts2;
        ts2 >>= 8;
    }
}
 
void TagListUpdate(void)
{
    uint8_t i,j=0;
    for(i=0; i<anchordata_num; i++)
    {
        if(tagofflinetime[i]++<QUIT_SLOT_TIME)
        {
            anchordata_id[j]=anchordata_id[i];
            tagofflinetime[j++]=tagofflinetime[i];
        }
    }
    anchordata_num=j;
}
uint8_t Anchor_RecNearPoll(uint8_t ancrec_nearbasepos)//¸ù¾Ý×Ô¼ºÊÇ·ñΪлùÕ¾¶¨ÖÆÏûϢȥ·¢ËÍ£¬¸ù¾ÝÊÇ·ñÇÀÕ¼ÅжÏ
{
    temp_count2=poll_rx_en_start_u32;
 
    memcpy(&send_buffer[GROUP_ID_IDX],&group_id,1);//×éid
    memcpy(&send_buffer[ANCHOR_ID_IDX],&dev_id,2);//×ÔÉíid
    memcpy(&send_buffer[TAG_ID_IDX],&tag_id_recv,2);//½ÓÊÜÕßid
    send_buffer[MESSAGE_TYPE_IDX]=MBX_RESPONSE;
 
    if(rec_nearbase_num == ancrec_nearbasepos)//ÇÀռģʽ×Ô¼ºÎªÐ»ùÕ¾
    {
        random_time = (phy_timer_count_get()%100);//¶à»ùÕ¾ÇÀÕ¼Ò»¸öλÖÃʱ±ÜÃâÒ»¸öÒ²ÊÕ²»µ½µÄÇé¿ö¾Íÿһ¸öËæ»ú´í¿ª¼¸Ê®uS
        //resp_tx_time = (poll_rx_ts+((random_time+rec_nearbase_num*20 + POLL_RX_TO_RESP_TX_DLY_UUS+ancrec_nearbasepos*DELAY_BETWEEN_TWO_FRAME_UUS) * UUS_TO_DWT_TIME)) >> 8;//¼ÆËãResponse·¢ËÍʱ¼äT3¡£
        // (resp_tx_en_start_u32) is the moment when TX enable
        resp_tx_en_start_u32 = poll_rx_en_start_u32+US_TO_PHY_TIMER_COUNT(20*rec_nearbase_num+POLL_RX_TO_RESP_TX_DLY_US+rec_nearbase_num*DELAY_BETWEEN_TWO_FRAME_UUS);//ºóÃæµÄÐèÒª¸ù¾ÝÒÑÓлùÕ¾ÊýÁ¿½øÐиü¸Ä£¬Èç¹ûÊÇÇÀÕ¼×Ô¼º×îºóÒ»¸ö»Ø¸´£¬ÒªÓе×Êý
                
        } else {
        //resp_tx_time = (poll_rx_ts + ((rec_nearbase_num*20+POLL_RX_TO_RESP_TX_DLY_UUS+ancrec_nearbasepos*DELAY_BETWEEN_TWO_FRAME_UUS) * UUS_TO_DWT_TIME)) >> 8;//¼ÆËãResponse·¢ËÍʱ¼äT3¡£
       resp_tx_en_start_u32 = poll_rx_en_start_u32+US_TO_PHY_TIMER_COUNT(20*rec_nearbase_num+POLL_RX_TO_RESP_TX_DLY_US+rec_nearbase_num*DELAY_BETWEEN_TWO_FRAME_UUS);//ºóÃæµÄÐèÒª¸ù¾ÝÒÑÓлùÕ¾ÊýÁ¿½øÐиü¸Ä£¬Èç¹ûÊÇÇÀÕ¼×Ô¼º×îºóÒ»¸ö»Ø¸´£¬ÒªÓе×Êý
                //ÕâÀïÓ¦¸ÃÓÐÎÊÌâÎÊÒ»ÏÂÖÓ¹¤
        }//´Ë´¦ÉèÖþø¶Ôʱ¼ä½«poll u32¸ÄΪphy_timer_count_get()
 
    resp_tx_ts_i64 = ranging_tx_time_correct(resp_tx_en_start_u32 + phy_shr_duration());//ÐÞÕýʱ¼ä´Á
    /* Write all timestamps in the final message. See NOTE 8 below. */
    resp_msg_set_ts(&send_buffer[RESP_MSG_POLL_RX_TS_IDX], poll_rx_ts_i64);
    resp_msg_set_ts(&send_buffer[RESP_MSG_RESP_TX_TS_IDX], resp_tx_ts_i64);//´Ë´¦Ê±¼ä´Áint64Ö±½Óת»»Îªuint64²»ÖªµÀ»á²»»áÓдíÎó
    memcpy(&send_buffer[RESP_MSG_ANC_DISTOFFSET],&disoffset,2);//²î¸öÐÞÕýoffset,ÐÞÕýÓзûºÅµ«ÊÇÕâ¸öcom±íΪÎÞ·ûºÅµÄ,´«¹ýÈ¥Ö±½Ó¸³¸øInt16_tÏ൱ÓÚ»¹Ô­ÁË
    temp_resp_i64=resp_tx_ts_i64;
    temp_count3= phy_timer_count_get();
    uwb_tx(send_buffer, 40,1 ,resp_tx_en_start_u32);//Á¢¼´·¢ËͲâÊÔsize´óС
    temp_count1=phy_timer_count_get();
    while(mac_is_busy());
    gpio_pin_clr(SCL_PIN);
}
uint32_t range_timeout_us = 1000000;//yuan5000
uint16_t uwb_searchcount;
uint8_t flag_recsuccess;
uint8_t flag_temp2,flag_temp1;
uint32_t start_receive_count_calibration;
uint32_t current_count_calibration;
uint8_t secondtask_search_count,secondtask_search_flag;
extern uint8_t g_start_send_flag,search_open_flag = 1,link_success_flag,flag_secondtask;
void Calibration_Time(void)
{    
    current_count_calibration=phy_timer_count_get();
    if((current_count_calibration-start_receive_count_calibration>=MS_TO_PHY_TIMER_COUNT(500)||current_count_calibration+(UINT32_MAX-start_receive_count_calibration)>=MS_TO_PHY_TIMER_COUNT(500))
        &&!((end_receive_count-current_count_calibration<=MS_TO_PHY_TIMER_COUNT(200))||(end_receive_count+(UINT32_MAX-current_count_calibration)<=MS_TO_PHY_TIMER_COUNT(200))))
    {
        start_receive_count_calibration=current_count_calibration;//¸üпªÊ¼Ê±¼ä
//        MotorPoll();
        
        if(secondtask_search_count++%2==0)
    {
        secondtask_search_flag = 1;
    }else{
        secondtask_search_flag = 0;
    }
        if(secondtask_search_flag)//¸üÐÂSʱ¼äTICK
        {
        HIDO_TimerTick();
        TagListUpdate();
//    GPS_Poll();
//        if(nomove_count<=g_com_map[NOMOVESLEEP_TIME])//·ÀÖ¹Òç³ö
//    nomove_count++;
//        else{
//        nomove_count=g_com_map[NOMOVESLEEP_TIME]+1;
//        }
        }
//        update_led_power_state();//¸üеÈ״̬·ÀÖ¹Õ𶯿¨ËÀÔÚËÑË÷
    }
}
 
int UwbRange(void)
{
    uint8_t i;
    uint16_t tempid;
    // The following peripherals will be initialized in the uwb_open function
    // phy/mac/aes/lsp/phy timers initialized
    uwb_open();
 
//    // Set calibration parameters
//    uwb_calibration_params_set(config.phy_cfg.ch_num);
 
//    // 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,
//    };
//    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);
 
//    ranging_frame_type_set(config.phy_cfg.sts_pkt_cfg);
 
    // Register rx interrupt callback function
    mac_register_process_handler(tx_int_callback, rx_int_callback);
 
    receive_flag = 0;
        flag_recsuccess = 0;
    temp_count3=phy_timer_count_get();
    gpio_pin_set(SCL_PIN);
        sts_lsp_store();
    flag_temp1=uwb_rx(0, 0, range_timeout_us);//¿ªÆô½ÓÊÕ
    
   // while(mac_is_busy());
  //  temp_count2=phy_timer_count_get();
        start_receive_count=phy_timer_count_get();
    poll_timeout=US_TO_PHY_TIMER_COUNT(range_timeout_us);//¶àÒ»¸ö¶à0.4msĬÈÏ0.4ms¼ÆËãΪ0.125*4*100000,ĬÈÏ¿ªÆô1mss
    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();
        while(current_count<end_receive_count||current_count>end_receive_count+HALF_SECOND_TIME)//Ñ­»·½ÓÊܰüÌå,ÈôΪ124.8KÔòÊÇ+62400000
        {
            current_count=phy_timer_count_get();
            while(mac_is_busy())
        {
                        Calibration_Time();
            IdleTask();
            current_count=phy_timer_count_get();
            if(current_count>end_receive_count&&current_count<end_receive_count+HALF_SECOND_TIME)
            {
                    break;
            }
        }
            sts_lsp_store_stop();
            
            
    if(receive_flag==1)//³É¹¦½ÓÊÕ
    {
 
        if(group_id==rx_buf[GROUP_ID_IDX]&&rx_buf[MESSAGE_TYPE_IDX] == MBX_POLL&&!memcmp(&rx_buf[TAG_ID_IDX],&g_com_map[BIND_DEV_ID],2))//ÅжÏÊÇ·ñÊǺÍ×Ô¼ºÊÇͬһ×éͨѶµÄÇÒΪpoll°ü
        {    flag_recsuccess = 1;
                     sleep_timer_start(__MS_TO_32K_CNT(UWB_DELAY_TIME_US));//²âÊÔ
                      temp_count2=phy_timer_count_get();
            frame_seq_nb2 = rx_buf[SEQUENCE_IDX];//»ñÈ¡°üÐò
            battary = rx_buf[BATTARY_IDX];
            rec_nearbase_num=rx_buf[FZ_NEARBASENUM_INDEX];  //±êÇ©´«¹ýÀ´µÄËûÓë»ùÕ¾½»»¥µÄ»ùÕ¾idÊýÄ¿
            memcpy(&tag_id_recv,&rx_buf[TAG_ID_IDX],2);
            memcpy(rec_ancidlist,&rx_buf[FZ_NEARBASEID_INDEX],2*rec_nearbase_num);
            memcpy(rec_ancdistlist,&rx_buf[FZ_NEARBASEID_INDEX+2*rec_nearbase_num],2*rec_nearbase_num);
            memcpy(&rec_antdelay,&rx_buf[FZ_NEARBASEID_INDEX+rec_nearbase_num*4],2);
            for(i=0; i<rec_nearbase_num; i++)
            {
                if(rec_ancidlist[i] == dev_id)
                {        temp_recdist_before_offset=rec_ancdistlist[i];
                    rec_ancdistlist[i]+=(int16_t)g_com_map[DIST_OFFSET];
                    PushAnchorDataArray(tag_id_recv,rec_ancdistlist[i],battary);
                }
            }
            for(i=0; i<rec_nearbase_num; i++)
            {
                memcpy(&tempid,&rx_buf[FZ_NEARBASEID_INDEX+i*2],2);
                if(tempid==dev_id)//Ò²ÊDZÈidÈç¹ûÓо͸üÐÂûÓоÍÇÀÕ¼
                {
                    seize_anchor=0;  //·ÇÇÀÕ¼¡£ÒÑ´æÔÚÁбíÖÐ
                    Anchor_RecNearPoll(i);
                    break;
                }
            }
 
            if(i==rec_nearbase_num)
            {
                seize_anchor=1;   //ÇÀÕ¼anchor
                Anchor_RecNearPoll(i);
            }
                        recev_error_num=0;
               range_timeout_us=5000;//»Ö¸´Îª5000½øÈërangeºó
           LOG_INFO(TRACE_MODULE_APP,"±êÇ©ID£º%X,¾àÀë: %d ÐźÅÇ¿¶ÈANT0: %f,ÐźÅÇ¿¶ÈANT2: %f\r\n",g_com_map[BIND_DEV_ID],distance,sts_rssi[0],sts_rssi[2]);
                        gpio_pin_clr(SCL_PIN);
        break;
                }
    } 
            sts_lsp_store();
        //ʧ°Ü»òÕß½ÓÊܱ»¸ß·¢Éä»ú´ò¶Ï¶¼»áÔٴοªÆô½ÓÊÕ
            flag_temp1=uwb_rx(0, 0, range_timeout_us);
    }
        delay_us(1);
        uwb_rx_force_off(1);
        if(!flag_recsuccess)
        {
            sleep_timer_start(__MS_TO_32K_CNT(UWB_DELAY_TIME_US-3));//²âÊÔ
        LOG_INFO(TRACE_MODULE_APP,"²â¾àʧ°Ü£¬¼ÆÊý£º%d\r\n",recev_error_num);
        if(recev_error_num++>5)
        {
            recev_error_num=0;
            UWB_work_state=SEARCH_DEV;
            uwb_searchcount = 0;
            search_open_flag = 1;
        }
            }
 
   
            
            return 0;
}
 
 
//Ö÷º¯Êý°ó¶¨½ÓÊÜÂß¼­
int UwbSearch(void)
{
    uint8_t i;
    uint16_t tempid;
    // The following peripherals will be initialized in the uwb_open function
    // phy/mac/aes/lsp/phy timers initialized
    uwb_open();
  // Set STS key and IV
    phy_sts_key_configure(&sts_iv_key);
    
    // which RX ports will be used for AoA/PDoA
    phy_rx_ant_mode_set(RX_ANT_PORTS_COMBINATION);
 
    // Set calibration parameters
    uwb_calibration_params_set(config.phy_cfg.ch_num);
 
   // 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,
    };
    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);
        
        ranging_lib_init();
    ranging_frame_type_set(config.phy_cfg.sts_pkt_cfg);
        
        aoa_aux_info_set(AOA_AUX_ANT_IQ_RSSI_PDOA_AOA_FOM);
    aoa_steering_vector_set((const float *)((uint32_t)((config.phy_cfg.ch_num == 9) ? svec_ch9_ptr : svec_ch5_ptr) | SRAM_BASE));
 
    aoa_param_config();
        
        phy_rx_sts_switch_mode_set(config.phy_cfg.sts_pkt_cfg, STS_SWITCH_EVERY_4SYM, 0, 0);
    // Register rx interrupt callback function
    mac_register_process_handler(tx_int_callback, rx_int_callback);
        
    receive_flag = 0;
    temp_count3=phy_timer_count_get();
    gpio_pin_set(SCL_PIN);
        sts_lsp_store();
    flag_temp2=uwb_rx(0, 0, RX_SYNC_WIN_US_TEMP);//¿ªÆô½ÓÊÕ
    start_receive_count=phy_timer_count_get();
    poll_timeout=US_TO_PHY_TIMER_COUNT(2000000);//¶àÒ»¸ö¶à0.4msĬÈÏ0.4ms¼ÆËãΪ0.125*4*100000,ĬÈÏ¿ªÆô1mss
    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();
    while(current_count<end_receive_count||current_count>end_receive_count+HALF_SECOND_TIME)//Ñ­»·½ÓÊܰüÌå,ÈôΪ124.8KÔòÊÇ+62400000
    {
        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;
            }
        }
                sts_lsp_store_stop();
                
                
        temp_count2=phy_timer_count_get();
        if(receive_flag==1)//³É¹¦½ÓÊÕ
        {
            if(group_id==rx_buf[GROUP_ID_IDX]&&rx_buf[MESSAGE_TYPE_IDX] == MBX_POLL&&!memcmp(&rx_buf[TAG_ID_IDX],&g_com_map[BIND_DEV_ID],2))//ÅжÏÊÇ·ñÊǺÍ×Ô¼ºÊÇͬһ×éͨѶµÄÇÒΪpoll°ü
            {   
                              sleep_timer_start(__MS_TO_32K_CNT(UWB_DELAY_TIME_US-13));//²âÊÔ
                                range_timeout_us=20000;//½«Ï´Îrange¿ªÆôºó³¬Ê±Ê±¼äÉèΪ20msÖ®ºóÔÙrangeÀï»Ö¸´
                                temp_count2=phy_timer_count_get();
                frame_seq_nb2 = rx_buf[SEQUENCE_IDX];//»ñÈ¡°üÐò
                battary = rx_buf[BATTARY_IDX];
                rec_nearbase_num=rx_buf[FZ_NEARBASENUM_INDEX];  //±êÇ©´«¹ýÀ´µÄËûÓë»ùÕ¾½»»¥µÄ»ùÕ¾idÊýÄ¿
                memcpy(&tag_id_recv,&rx_buf[TAG_ID_IDX],2);
                memcpy(rec_ancidlist,&rx_buf[FZ_NEARBASEID_INDEX],2*rec_nearbase_num);
                memcpy(rec_ancdistlist,&rx_buf[FZ_NEARBASEID_INDEX+2*rec_nearbase_num],2*rec_nearbase_num);
                memcpy(&rec_antdelay,&rx_buf[FZ_NEARBASEID_INDEX+rec_nearbase_num*4],2);
                for(i=0; i<rec_nearbase_num; i++)
                {
                    if(rec_ancidlist[i] == dev_id)
                    {
                                                temp_recdist_before_offset=rec_ancdistlist[i];
                                                rec_ancdistlist[i]+=(int16_t)g_com_map[DIST_OFFSET];
                        PushAnchorDataArray(tag_id_recv,rec_ancdistlist[i],battary);
                    }
                }
                for(i=0; i<rec_nearbase_num; i++)
                {
                    memcpy(&tempid,&rx_buf[FZ_NEARBASEID_INDEX+i*2],2);
                    if(tempid==dev_id)//Ò²ÊDZÈidÈç¹ûÓо͸üÐÂûÓоÍÇÀÕ¼
                    {
                        seize_anchor=0;  //·ÇÇÀÕ¼¡£ÒÑ´æÔÚÁбíÖÐ
                        Anchor_RecNearPoll(i);
                        break;
                    }
                }
 
                if(i==rec_nearbase_num)
                {
                    seize_anchor=1;   //ÇÀÕ¼anchor
                    Anchor_RecNearPoll(i);
                }
                
                gpio_pin_clr(SCL_PIN);//²âÊÔ
                                LOG_INFO(TRACE_MODULE_APP,"±êÇ©ID£º%X,¾àÀë: %d ÐźÅÇ¿¶ÈANT0:%f,ÐźÅÇ¿¶ÈANT2: %f\r\n",g_com_map[BIND_DEV_ID],distance,sts_rssi[0],sts_rssi[2]);
                return 1;//·µ»Ø·¢Ëͳɹ¦±êÖ¾
            }
 
        }
                temp_count3=phy_timer_count_get();
                sts_lsp_store();
        flag_temp2=uwb_rx(0, 0, RX_SYNC_WIN_US_TEMP);//ÔٴοªÆô½ÓÊÕ
    }
        delay_us(2);
        sts_lsp_store_stop();
        uwb_rx_force_off(1);
    // LOG_INFO(TRACE_MODULE_APP,"³¬Ê±¶¨Ê±Æ÷£º%x,%x,%x\r\n",start_receive_count,end_receive_count,current_count);
    gpio_pin_clr(SCL_PIN);//²âÊÔ
    return 0;//·µ»Ø°ó¶¨Ê§°Ü±êÖ¾
}
//}
 
#define SEARCH_TIMESTEMP 20
void UWBPoll(void)
{
    switch(UWB_work_state)
    {
    case LINK_SUCCESS:
    {   //Á¬½Ó³É¹¦½øÐÐÂÖѯ²â¾à
 
        uwb_led_on();
        UwbRange();
        uwb_led_off();
 
    }
    break;
    case SEARCH_DEV:
    {   //½Ó°ü²»³É¹¦»òÕßͨѶʧ°Ü½øÈëËÑË÷ģʽ
        if(search_open_flag)
        {
            LOG_INFO(TRACE_MODULE_APP,"¿ªÆôËÑË÷\r\n");
            search_open_flag=0;
            uwb_led_on();
            link_success_flag=UwbSearch();//µÚÒ»´Î¿ªÆô½ÓÊÕ2s°ó¶¨Ê§°ÜºóÔò½øÐÐÏÂÃæ1·ÖÖÓºóÖØÐ¿ªÆô2s°ó¶¨Á÷³Ì
            uwb_led_off();
            if(link_success_flag)
                UWB_work_state=LINK_SUCCESS;
        }else{
            LOG_INFO(TRACE_MODULE_APP,"µÈ´ý½øÈëËÑË÷ģʽ£º%d\r\n",SEARCH_TIMESTEMP-uwb_searchcount);
        }
 
    }
    break;
    case UN_BIND:
    {
        uwb_led_off();//¹Ø±ÕuwbָʾµÆ
    }
    break;
    }
    if(UWB_work_state==LINK_SUCCESS)
    {   //³É¹¦Ê±Çå0´íÎó¼ÆÊý
        uwb_searchcount=0;
    }
    if(UWB_work_state==SEARCH_DEV)
    {
        if(!search_open_flag)
        {
            if(uwb_searchcount++>SEARCH_TIMESTEMP)
            {
                uwb_searchcount=0;
                search_open_flag=1;
            }
        }
        //link_error_count+=g_com_map[COM_INTERVAL];
        //if(link_error_count>=g_com_map[4G_INTERNAL])
        //link_error_count=0;
       // update_led_power_state();//¸üеÆ×´Ì¬
    }
     LOG_INFO(TRACE_MODULE_APP,"UWB״̬£º%d\r\n",UWB_work_state);
}
 
uint8_t GetUWBBindState(void)
{
    if(UWB_work_state == UN_BIND)
    {
        return 0;
    }
    return 1;
}