From 31ac7dbd495f1ba57c91b602886f3baf5fa0735c Mon Sep 17 00:00:00 2001
From: chen <15335560115@163.com>
Date: 星期三, 09 七月 2025 16:59:15 +0800
Subject: [PATCH] 修改搬运tagid为2字节,修改55aaaoa包体内容和上传时机,增加距离和角度判断区域显示报文输出逻辑

---
 keil/uwb_app.c |  657 +++++++++++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 561 insertions(+), 96 deletions(-)

diff --git a/keil/uwb_app.c b/keil/uwb_app.c
index 7d8709c..7f46dc1 100644
--- a/keil/uwb_app.c
+++ b/keil/uwb_app.c
@@ -10,18 +10,25 @@
 #include "global_param.h"
 #include "board.h"
 #include "lib_aoa.h"
-
+#include "lib_kf.h"
+#include "MK8000_kf_top.h"
+#if PDOA_3D_EN
+#include "lib_pdoa_3d.h"
+#endif
 extern int simple_main(void);
 extern int temp_main(void);
 void Calibration_Time(void);
 void TagListUpdate(void);
 void TagListUpdate_person_num(void);
+void buffer_message_send(void);
+void buffer_485_send(uint8_t* show_buffer);
 void Uwb_init(void);
 void OpenUWB(void);
 void CloseUWB(void);
 int Anchor_App(void);
 extern void IO_LED_control_change(uint8_t data);
 extern void IO_control_init(void);
+extern uint8_t loc_kf_filter(float data_meas, enum KF_DATA_TYPE_T data_type, uint8_t *mac_addr, float *data_post);
 
 extern void updata_led_power_state(void);
 /*receive buffer*/
@@ -33,12 +40,16 @@
 //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];
+uint8_t show_location[TAG_NUM_IN_SYS];
+void buffer_485_construct(uint8_t* show_buffer);
 static int16_t rec_ancdistlist[TAG_NUM_IN_SYS];
+void update_show_buffer(void);
 extern uint8_t group_id;
-static uint16_t anc_id_recv,tag_id_recv;
+static uint16_t anc_id_recv;
+static uint16_t tag_id_recv;
 static int16_t rec_antdelay;
 extern uint32_t dev_id;
-static uint16_t taglist_pos,tmp_time;
+static uint32_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;
@@ -48,6 +59,11 @@
 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];
+uint8_t tag_seq[TAG_NUM_IN_SYS];
+uint16_t angle_azimuth[TAG_NUM_IN_SYS];
+uint16_t angle_elevation[TAG_NUM_IN_SYS];
+uint16_t angle_num;
+uint32_t fliter_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];
@@ -67,6 +83,7 @@
 extern uint8_t recev_error_num;
 uint8_t uwb_rx_flag;
 extern Operation_step UWB_work_state;
+void find_in_tag_id_authorization_list(uint32_t authorization_list_num);
 extern int16_t first_search_flag;
 typedef enum 
 {
@@ -147,7 +164,9 @@
     .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                       */
+    .phy_cfg.rx_main_ant = UWB_RX_ANT_3,             /* UWB RX main antenna port                  */
+    .phy_cfg.rx_ant_mode = RX_ANT_PORTS_COMBINATION, /* UWB RX antenna mode                       */
+    .phy_cfg.pulse_shape = 0x2,                      /* 0x0: CCC pulse, 0x2: FiRa pulse           */
 };
 #elif defined STS_MODE
 static struct mk_uwb_configure config = {
@@ -163,7 +182,9 @@
     .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                       */
+     .phy_cfg.rx_main_ant = UWB_RX_ANT_3,             /* UWB RX main antenna port                  */
+    .phy_cfg.rx_ant_mode = RX_ANT_PORTS_COMBINATION, /* UWB RX antenna mode                       */
+    .phy_cfg.pulse_shape = 0x2,                      /* 0x0: CCC pulse, 0x2: FiRa pulse           */
 };
 /* Use the default key and IV specified in the IEEE 802.15.4z attachment */
 static struct UWB_STS_KEY_CONFIG_T sts_iv_key = {
@@ -190,10 +211,40 @@
     .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                       */
+    .phy_cfg.rx_main_ant = UWB_RX_ANT_3,             /* UWB RX main antenna port                  */
+    .phy_cfg.rx_ant_mode = RX_ANT_PORTS_COMBINATION, /* UWB RX antenna mode                       */
+    .phy_cfg.pulse_shape = 0x2,                      /* 0x0: CCC pulse, 0x2: FiRa pulse           */
+};
+#elif defined STS_MODE_SQUARE
+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_main_ant = UWB_RX_ANT_3,             /* UWB RX main antenna port                  */
+    .phy_cfg.rx_ant_mode = RX_ANT_PORTS_COMBINATION, /* UWB RX antenna mode                       */
+    .phy_cfg.pulse_shape = 0x2,                      /* 0x0: CCC pulse, 0x2: FiRa pulse           */
+};
+/* 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,
 };
 #endif
-
 static struct anchor_id_car{
  uint16_t anchor_new_id;
  uint16_t change_num;
@@ -256,7 +307,7 @@
     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;
+    tx_timestamp += ranging_ant_delays_get(config.phy_cfg.rx_main_ant) / 2;
 
     return tx_timestamp;
 }
@@ -272,7 +323,7 @@
     int64_t rx_timestamp = ranging_rx_time(ind);
 
     // correct antenna delay
-    rx_timestamp -= ranging_ant_delays_get(config.phy_cfg.rx_ant_id) / 2;
+    rx_timestamp -= ranging_ant_delays_get(config.phy_cfg.rx_main_ant) / 2;
 
     return rx_timestamp;
 }
@@ -282,14 +333,59 @@
 uint32_t range_timeout_us = 2000000;//yuan5000
 uint8_t flag_temp2,flag_temp1;
 uint16_t uwb_losttimer;
+uint8_t mac_error;
+uint8_t allow_flag;
+uint8_t resp_tx_flag,poll_rx_error_num;
+uint8_t tag_rssi[TAG_NUM_IN_SYS];
+uint8_t tag_show_location[TAG_NUM_IN_SYS];
+void construct_show_buffer(uint8_t*tag_show_location,uint32_t tag_pos)
+{
+//if(angle_azimuth[tag_pos])
+//{
+//	
+//}elseif(angle_azimuth[tag_pos])
+//{
+
+//}elseif(angle_azimuth[tag_pos])
+//{
+
+//}elseif(angle_azimuth[tag_pos])
+//{
+
+//}
+}
+float temp1,temp2;
+static void angle_result_filter(uint8_t *mac_addr, int16_t *angle, uint8_t type)
+{
+    if (angle == NULL)
+    {
+        return;
+    }
+
+    float post_angle;
+    float angle_meas = mk_q7_to_f32(*angle);
+		temp1=angle_meas;
+		
+    // call filter
+    loc_kf_filter(angle_meas, (enum KF_DATA_TYPE_T)type, mac_addr, &post_angle);
+		temp2=post_angle;
+    // update angle
+    *angle = mk_f32_to_q7(post_angle);
+		temp1=*angle;
+    // LOG_INFO(TRACE_MODULE_APP, "Peer %X, $%d %d;\r\n", READ_SHORT(mac_addr), (int16_t)angle_meas,(int16_t)post_angle);
+}
 static void rx_int_callback(struct MAC_HW_REPORT_T *rx_report)
 {		uint8_t valid_sts=0;
     // Power off radio
     power_off_radio();
-
+		sts_lsp_store_stop();
     /** 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);
+
         /* Received data does not contain FCS */
         rx_length = rx_report->pkt_len;
         memcpy(rx_buf, rx_report->pkt_data, rx_length);
@@ -300,23 +396,54 @@
         poll_rx_ts_i64 = ranging_rx_time_correct(&rx_rpt);
         poll_rx_num++;
         rssi = rx_report->rssi;
-        receive_flag=1;
+        //receive_flag=1;
 				Anchor_App();
-			#ifdef STS_MODE
-				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();
+			//    // PDoA caculation
+			if (sts_valid_check())//为了避免影响时序放到了回包后进行操作
+     {
+			pdoa_3d_calculate(0, &elevation, &azimuth);
+			pdoa_fom_get(NULL, &fom);
+			if(allow_flag)
+			{
+			tag_rssi[taglist_pos]=rssi;
+					uint8_t mac_addr=0;
+				 angle_result_filter(&mac_addr,&azimuth, KF_DATA_TYPE_AZIMUTH);
+       angle_result_filter(&mac_addr,&elevation, KF_DATA_TYPE_ELEVATION);
+			angle_azimuth[taglist_pos]=(uint16_t)mk_q7_to_s16(azimuth);
+			angle_elevation[taglist_pos]=(uint16_t)mk_q7_to_s16(elevation);
+			//buffer_message_send();
+				//int16_t  azimth=mk_q7_to_s16(azimuth),elevate=mk_q7_to_s16(elevation);
+			
+//				 // filter process
+      
+			 LOG_INFO(TRACE_MODULE_APP, "PDoA 0x%04x Azimuth %d Elevation %d FoM %u\r\n",tag_id_recv, mk_q7_to_s16(azimuth),
+                                 mk_q7_to_s16(elevation), fom);
+				allow_flag=0;
 			}
-			#endif
+		}
+			if(resp_tx_flag==0)
+			{
+			  OpenUWB();
+			}
+//				}else{
+//					poll_rx_error_num++;
+//				rx_report->err_code |= UWB_STS_ERR;
+//				}
+//			#ifdef STS_MODE
+//				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();
+//			}
+//			#endif
     }
     else
     {
@@ -329,9 +456,9 @@
 			        temp_count= phy_timer_count_get();
         memcpy(&rx_rpt, rx_report, sizeof(struct MAC_HW_REPORT_T));
         rx_length = 0;
-			//	OpenUWB();//再次开启UWB接收
+				OpenUWB();//再次开启UWB接收
     }
-	OpenUWB();//再次开启UWB接收
+	//OpenUWB();//再次开启UWB接收
 }
 
 /* TX done process handler. */
@@ -346,9 +473,12 @@
         temp_count= phy_timer_count_get();
         temp_internal=temp_count;
         resp_tx_num++;
-		//		OpenUWB();//再次开启UWB接收
+				resp_tx_flag=0;
+				OpenUWB();//再次开启UWB接收
         //LOG_INFO(TRACE_MODULE_APP, "poll_rx_num is %d,resp_tx_num is %d\r\n",poll_rx_num,resp_tx_num);
-    }
+    }else{
+		mac_error=1;
+		}
 }
 uint32_t start_receive_count,end_receive_count,poll_timeout,current_count,temp_resp;
  uint16_t anchordata_id[TAG_NUM_IN_SYS],anchordata_dist[TAG_NUM_IN_SYS];
@@ -356,6 +486,9 @@
 static uint8_t anchordata_bat[TAG_NUM_IN_SYS];
 uint8_t anchordata_num = 0;
 static int32_t tagdist_list[TAG_NUM_IN_SYS];
+uint8_t rssi_quality[TAG_NUM_IN_SYS];
+uint16_t state_button[TAG_NUM_IN_SYS];
+uint16_t pressure[TAG_NUM_IN_SYS];
 uint16_t random_time;
 //anchor
 int32_t hist_dist;
@@ -447,7 +580,7 @@
         ts2 >>= 8;
     }
 }
-
+uint8_t tt5=0;
 //void TagListUpdate(void)
 //{
 //    uint8_t i,j=0;
@@ -461,6 +594,63 @@
 //    }
 //    anchordata_num=j;
 //}
+uint8_t find_flag;
+uint16_t bind_distance,button_determinate_distance,change_by_frequency_distance;
+uint8_t tag_near_frequency;
+uint8_t tag_authorized_List[TAG_NUM_IN_SYS];
+extern uint32_t tag_id_authorization_list_num;
+void sort_tag_lists(void)
+{
+	if (taglist_num <= 1) {
+        return; // 无需排序
+    }
+// 使用冒泡排序(稳定排序,实现简单)
+    for (size_t i = 0; i < taglist_num - 1; i++) {
+        for (size_t j = 0; j < taglist_num - i - 1; j++) {
+            if (tagdist_list[j] > tagdist_list[j + 1]) {
+                // 交换距离值
+                uint16_t temp_dist = tagdist_list[j];
+                tagdist_list[j] = tagdist_list[j + 1];
+                tagdist_list[j + 1] = temp_dist;
+
+                // 同步交换标签ID
+                uint32_t temp_id = tagid_list[j];
+                tagid_list[j] = tagid_list[j + 1];
+                tagid_list[j + 1] = temp_id;
+							
+							//同步交换电量是否授权表和在线时间
+							 uint32_t temp_bat = anchordata_bat[j];
+							anchordata_bat[j]=anchordata_bat[j+1];//电量随之更新
+            anchordata_bat[j+1]=temp_bat;
+							
+							//同步交换在线时间
+								uint32_t temp_tag_offlinetime = tagofflinetime[j];
+							tagofflinetime[j]=tagofflinetime[j+1];//电量随之更新
+            tagofflinetime[j+1]=temp_tag_offlinetime;
+							
+//							//同步交换授权表
+//								uint8_t temp_tag_authorized = tag_authorized_List[j];
+//							tag_authorized_List[j]=tag_authorized_List[j+1];//电量随之更新
+//            tag_authorized_List[j+1]=temp_tag_authorized;
+            }
+        }
+    }
+}
+
+void change_button_state(void)
+{
+	if(tag_authorized_List[0]==1&&taglist_num>=1)//只有在有效判定范围内有授权的标签才会开启,否则都是关闭
+	{
+		if(tagdist_list[0]<button_determinate_distance)
+		{
+			gpio_pin_set(BUTTON_PIN);
+		}else{
+			gpio_pin_clr(BUTTON_PIN);
+		}
+	}else{
+			gpio_pin_clr(BUTTON_PIN);
+		}
+}
 void TagListUpdate(void)
 {
 uint16_t i,j=0,k=0;
@@ -475,6 +665,11 @@
         }
 		}
 		 taglist_num=j;
+		sort_tag_lists();//增加距离小的排到前面逻辑
+		buffer_message_send();//发送测距报文信息
+		update_show_buffer();//根据角度和距离判断区域位置
+		//delay_ms(10);
+		buffer_485_send(show_location);//发送显示信息
 }
 
 uint8_t position;
@@ -484,7 +679,7 @@
 
     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
+    memcpy(&send_buffer[TAG_ID_IDX],&tag_id_recv,4);//接受者id
     send_buffer[MESSAGE_TYPE_IDX]=MBX_RESPONSE;
 
 //    if(rec_nearbase_num == ancrec_nearbasepos)//抢占模式自己为新基站
@@ -506,10 +701,19 @@
     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相当于还原了
+		if(tagdist_list[ancrec_nearbasepos]<=change_by_frequency_distance&&tag_authorized_List[ancrec_nearbasepos]==1)//授权才改变频率否则不改变
+		{
+			send_buffer[RESP_MSG_TAG_FREQUENCY]=tag_near_frequency;//新加入改变标签测距hz
+		}
+		else{
+				send_buffer[RESP_MSG_TAG_FREQUENCY]=1;//新加入改变标签测距hz
+		}
     temp_resp_i64=resp_tx_ts_i64;
     temp_count3= phy_timer_count_get();
     flag_temp2=uwb_tx(send_buffer, 40,1 ,resp_tx_en_start_u32);//立即发送测试size大小
+		resp_tx_flag=1;//限制重复开启
 		tagofflinetime[taglist_pos] = 0;//更新标签通信
+		//phy_update_sts_iv_counter(0x00, sts_iv_key.sts_vcounter);//重置sts
 //    temp_count1=phy_timer_count_get();
     //while(mac_is_busy());
     //gpio_pin_clr(SCL_PIN);
@@ -644,16 +848,240 @@
 //	}
 	 UWBIdleTask();
 }
+
+extern uint8_t bind_flag;
+void bubble_sort(uint32_t *arr, uint32_t n)
+{
+ if (n <= 1) return;  // 无需排序
+    
+    uint32_t i, j;
+    uint8_t swapped;  // 标记是否发生交换
+    
+    for (i = 0; i < n - 1; i++) {
+        swapped = 0;  // 重置交换标记
+        
+        // 每轮将最大元素"冒泡"到末尾
+        for (j = 0; j < n - i - 1; j++) {
+            if (arr[j] > arr[j + 1]) {
+                // 交换相邻元素
+                uint32_t temp = arr[j];
+                arr[j] = arr[j + 1];
+                arr[j + 1] = temp;
+                swapped = 1;  // 标记发生了交换
+            }
+        }
+        
+        // 优化:如果本轮未发生交换,说明数组已排序
+        if (!swapped) break;
+    }
+}
+uint16_t tag_authorization_list_num_temp;
+void fliter_tag_id_authorization_list(uint16_t*tag_authorization_list_real_num)
+{	
+	uint32_t filtered_count = 0;
+    
+    // 遍历所有标签,将距离小于阈值的ID存入结果数组
+    for (uint32_t i = 0; i < taglist_num; i++) {
+        if (tagdist_list[i] < bind_distance&&tagid_list[i]!=0) {
+            fliter_tagid_list[filtered_count] = tagid_list[i];
+            filtered_count++;
+        }
+//fliter_tagid_list
+		}
+		*tag_authorization_list_real_num=filtered_count;
+}
+void copy_taglist_to_flash(void)
+{
+fliter_tag_id_authorization_list(&tag_authorization_list_num_temp);//过滤调id为0的标签和不满足绑定距离的标签
+memset(tag_id_authorization_list,0,sizeof(tag_id_authorization_list));//清空上一次数组防止重叠
+memcpy(&tag_id_authorization_list,&fliter_tagid_list,tag_authorization_list_num_temp*4);//复制满足条件数组
+bubble_sort(&tag_id_authorization_list,tag_authorization_list_num_temp);//进行排序后存入,为二分法做基础
+save_taglist_map_to_flash();//存入flash
+}
+
+void find_in_tag_id_authorization_list(uint32_t authorization_list_num)
+{
+// for (uint32_t i = 0; i < taglist_num; i++) {
+//        uint32_t target = tagid_list[i];
+//        uint32_t left = 0;
+//        uint32_t right = authorization_list_num - 1;  // 授权列表的最大索引
+//        uint8_t found = 0;
+//        
+//        // 二分查找循环
+//        while (left <= right) {
+//            uint32_t mid = left + ((right - left) >> 1);  // 防止整数溢出
+//            uint32_t mid_val = tag_id_authorization_list[mid];
+//            
+//            if (mid_val == target) {
+//                found = 1;
+//                break;  // 找到目标值,立即退出循环
+//            } else if (mid_val < target) {
+//                left = mid + 1;
+//            } else {
+//                right = mid - 1;
+//            }
+//						 LOG_INFO(TRACE_MODULE_APP, "DEBUG: i=%u, left=%d, right=%d, found=%u\n", i, left, right, found);
+//        }
+////        
+////        // 存储查找结果
+////        tag_authorized_List[i] = found;
+//    }
+{
+    // 如果授权列表为空,直接全部标记为0
+    if (authorization_list_num == 0) {
+        for (int i = 0; i < taglist_num; i++) {
+						
+            tag_authorized_List[i] = 0;
+        }
+        return;
+    }
+
+    // 遍历需要查找的每个ID
+    for (int i = 0; i < taglist_num; i++) {
+			if (tag_authorized_List[i] != 2) {
+            continue; // 跳过不需要查找的项
+        }
+        int key = tagid_list[i];
+        int low = 0;
+        int high = authorization_list_num - 1;
+        int found = 0; // 标记是否找到
+
+        // 在授权列表中执行二分查找
+        while (low <= high) {
+            int mid = low + (high - low) / 2; // 防止整数溢出
+            
+            if (tag_id_authorization_list[mid] == key) {
+                found = 1; // 找到匹配项
+                break;
+            } else if (tag_id_authorization_list[mid] < key) {
+                low = mid + 1; // 在右半部分继续查找
+            } else {
+                high = mid - 1; // 在左半部分继续查找
+            }
+        }
+
+        // 根据查找结果设置输出列表
+        tag_authorized_List[i] = found ? 1 : 0;
+    }
+}
+}
+#define AREA_1 0xa1
+#define AREA_2 0xa2
+#define AREA_3 0xa3
+#define AREA_4 0xa4
+#define AREA_5 0xa5
+#define AREA_6 0xa6
+#define AREA_7 0xa7
+#define AREA_8 0xa8
+uint8_t change_by_distance(uint8_t position,uint16_t distance)
+{
+if(distance<1000){
+	position=position;
+}else if (distance>1000&&distance<2000){
+	position=position+16;
+}else if (distance>2000&&distance<3000){
+	position=position+16;
+}
+return position;
+}
+void update_show_buffer(void)
+{
+	uint8_t location_temp;
+	for(int i=0;i<taglist_num;i++)
+	{
+			if((int16_t)angle_azimuth[i]>=-22.5&&(int16_t)angle_azimuth[i]<=22.5)
+		{
+			location_temp=change_by_distance(AREA_1,tagdist_list[i]);
+		}else if((int16_t)angle_azimuth[i]>=22.5&&(int16_t)angle_azimuth[i]<=67.5){
+			location_temp=change_by_distance(AREA_8,tagdist_list[i]);
+		}else if((int16_t)angle_azimuth[i]>=67.5&&(int16_t)angle_azimuth[i]<=112.5){
+			location_temp=change_by_distance(AREA_7,tagdist_list[i]);
+		}else if((int16_t)angle_azimuth[i]>=112.5&&(int16_t)angle_azimuth[i]<=157.5){
+			location_temp=change_by_distance(AREA_6,tagdist_list[i]);
+		}else if(((int16_t)angle_azimuth[i]>=157.5&&(int16_t)angle_azimuth[i]<=180)||((int16_t)angle_azimuth[i]>=-180&&(int16_t)angle_azimuth[i]<=-157.5)){
+			location_temp=change_by_distance(AREA_5,tagdist_list[i]);
+		}else if((int16_t)angle_azimuth[i]>=-157.5&&(int16_t)angle_azimuth[i]<=-112.5){
+			location_temp=change_by_distance(AREA_4,tagdist_list[i]);
+		}else if((int16_t)angle_azimuth[i]>=-112.5&&(int16_t)angle_azimuth[i]<=-67.5){
+			location_temp=change_by_distance(AREA_3,tagdist_list[i]);
+		}else if((int16_t)angle_azimuth[i]>=-67.5&&(int16_t)angle_azimuth[i]<=-22.5){
+			location_temp=change_by_distance(AREA_2,tagdist_list[i]);
+		}
+			show_location[i]=location_temp;
+	}
+}
+void buffer_485_send(uint8_t* show_buffer)
+{				static uint8_t usart_send[100];
+				uint16_t checksum = 0;
+        usart_send[0] = 0x55;
+        usart_send[1] = 0xAA;
+        usart_send[2] = 0x50;                        
+        usart_send[3] = 9+5*taglist_num;      //length            
+        memcpy(&usart_send[4],&dev_id,2); //anchor_id)
+				usart_send[6]=taglist_num;       //区域数量
+        memcpy(&usart_send[7],show_buffer,taglist_num);//区域位置
+        memcpy(&usart_send[7+taglist_num],&tagid_list,2*taglist_num);//tag_idlist
+        memcpy(&usart_send[7+taglist_num+2*taglist_num],&tagdist_list,2*taglist_num); //tag_distlist
+				usart_send[7+5*taglist_num]=0;//保留4位RESERVE1
+				usart_send[7+5*taglist_num+1]=0;
+				usart_send[7+5*taglist_num+2]=0;
+				usart_send[7+5*taglist_num+3]=0;
+	
+        checksum = Checksum_u16(&usart_send[2],9+5*taglist_num);
+        memcpy(&usart_send[7+5*taglist_num+4], &checksum, 2);
+				while(uart_is_busy(UART_ID0));
+				uart_send(UART_ID0, usart_send,13+5*taglist_num, NULL);
+}
+void buffer_message_send(void)
+{				static uint8_t usart0_send[1024];
+				uint16_t checksum = 0;
+				uint32_t yuliu=0;
+        usart0_send[0] = 0x55;
+        usart0_send[1] = 0xAA;
+        usart0_send[2] = 0x51;                        
+        usart0_send[3] = 8+16*taglist_num;      //length
+        memcpy(&usart0_send[4],&dev_id,2); //anchor_id
+				for(uint8_t i=0;i<taglist_num;i++)
+				{
+				memcpy(&usart0_send[6+i*16],tagid_list[i],2);
+				usart0_send[8+i*20] = tag_seq[i];//包序
+				memcpy(&usart0_send[9+i*16],&tagdist_list[i],2); //distance
+        memcpy(&usart0_send[11+i*16],&angle_azimuth[i],2);//angle_azithum
+        memcpy(&usart0_send[13+i*16],&angle_elevation[i],2);//angle_elevation
+        memcpy(&usart0_send[15+i*16],&tag_rssi[i],1); //信号强度
+				memcpy(&usart0_send[16+i*16],&rssi_quality[i],1); //信号质量预留
+				usart0_send[17+i*20]=anchordata_bat[i];//标签电量
+				memcpy(&usart0_send[18+i*16],&state_button[i],2); //设备状态
+				memcpy(&usart0_send[20+i*16],&pressure[i],2); //气压
+				}
+				memcpy(&usart0_send[6+taglist_num*16],&yuliu,4); //预留位4位
+        checksum = Checksum_u16(&usart0_send[2],8+16*taglist_num);
+        memcpy(&usart0_send[10+16*taglist_num], &checksum, 2);
+				uart_send(UART_ID0, usart0_send,12+16*taglist_num, NULL);
+}
 int Anchor_App(void)
 {
 				uint8_t i;
 				uint16_t tempid;
+				//phy_update_sts_iv_counter(0x01, 0x00);//接受到后更新sts时间
 			if(group_id==rx_buf[GROUP_ID_IDX]&&rx_buf[MESSAGE_TYPE_IDX] == MBX_POLL)//判断是否是和自己是同一组通讯的且为poll包
-        {    flag_recsuccess = 1;
+        {    
+						flag_recsuccess = 1;
 						wltag_state=RANGE;//成功后从search切换为range
 						memcpy(&g_com_receive_id,&rx_buf[TAG_ID_IDX],2);
 					  //temp_count2=phy_timer_count_get();
 						uwb_losttimer=0;//成功测距清0 lost时间
+					
+//					#if AOA_EN
+//                        // AOA caculation
+//                        aoa_calculate(&elevation, &azimuth);
+//                        aoa_fom_get(NULL, &fom);
+//#elif PDOA_3D_EN
+//                        // PDoA caculation
+//                        pdoa_3d_calculate(0, &elevation, &azimuth);
+//                        pdoa_fom_get(NULL, &fom);
+//#endif
+					
             frame_seq_nb2 = rx_buf[SEQUENCE_IDX];//获取包序
             battary = rx_buf[BATTARY_IDX];
             rec_nearbase_num=rx_buf[FZ_NEARBASENUM_INDEX];  //标签传过来的他与基站交互的基站id数目
@@ -661,30 +1089,7 @@
             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)//也是比id如果有就更新没有就抢占
-//                {
-//                    seize_anchor=0;  //非抢占。已存在列表中
-//                    Anchor_RecNearPoll(i);
-//                    break;
-//                }
-//            }
-
-//            if(i==rec_nearbase_num)
-//            {
-//                seize_anchor=1;   //抢占anchor
-//                Anchor_RecNearPoll(i);
-//            }
+							allow_flag=1;
 								taglist_pos=CmpTagInList(tag_id_recv);
                 if(taglist_num>=ANC_MAX_NUM)
 										return 0;
@@ -696,22 +1101,23 @@
 												Anchor_RecNearPoll(i);
 												tagdist_list[taglist_pos]=rec_ancdistlist[i];
 												anchordata_bat[taglist_pos] = battary;//保存该基站电量
+												tag_seq[taglist_pos]=frame_seq_nb2;
 												if(taglist_pos==taglist_num)// taglist_pos==taglist_num 说明这个基站不在当前列表中
 												{   //tempid==dev_id 说明基站下发测距报文有这个标签的信息
 														taglist_num++;          //满足上述两种情况才会添加基站ID进入列表中,否则会出现标签不在基站列表中,标签也不响应的情况
-														tagid_list[taglist_pos] = tag_id_recv;
-														
+														tagid_list[taglist_pos] = tag_id_recv;//新增基站
 												}
 												break;
 										}
 								}
+							
 								 if((i==rec_nearbase_num&&taglist_pos==taglist_num)||(rec_nearbase_num==0&&!ExistInTagList(tag_id_recv)))//当基站不在标签列表中,标签也不在基站列表中时,随机找个时间片回复基站。
-                {
-                       Anchor_RecNearPoll(rec_nearbase_num);
+                {    
+									Anchor_RecNearPoll(rec_nearbase_num);
                 }
 				}
 				
-				
+								
 }
 int UwbRange(void)
 {
@@ -848,53 +1254,112 @@
 			
 			return 0;
 }
-void Uwb_init(void)
+void Uwb_init(void)//uwbinit修改了
 {
 		uwb_open();
-	#ifdef STS_MODE
- // 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);
-	#endif
     // Set calibration parameters
     uwb_calibration_params_set(config.phy_cfg.ch_num);
-	#ifndef STS_MODE
-   // set advanced parameters
-    struct PHY_ADV_CONFIG_T adv_config = {
+
+    // set advanced parameters
+    struct PHY_ADV_CONFIG_T adv_config =
+    {
         .thres_fap_detect = 40,
-        .nth_scale_factor = 4,
+        .nth_scale_factor = 1,
         .ranging_performance_mode = 0,
+#if RX_ANT_PORTS_NUM == 4
+        .skip_weakest_port_en = 1,
+#else
         .skip_weakest_port_en = 0,
+#endif
     };
-	#else
-	 // 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,
-    };
-	#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);
-		#ifdef STS_MODE
-		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);
-		#endif
-		mac_register_process_handler(tx_int_callback, rx_int_callback);//初始化回调
+    ranging_lib_init(config.phy_cfg.sts_pkt_cfg, CE_AUX_CH_PWR_NLOS_FOM);
+
+    // Register rx interrupt callback function
+    mac_register_process_handler(tx_int_callback, rx_int_callback);
+
+    // Reduce inter frame spacing (IFS) for non encrypted packets
+    mac_ifs_set(0, 0);
 }
+#if PDOA_3D_EN
+#define PDOA_3D_SUPPORT_NUM 10
+#define PDOA_3D_TIMEOUT_MS 2000
+static struct PDOA_3D_MAC_ADDR_T mac_addr_cache[PDOA_3D_SUPPORT_NUM];
+static struct PDOA_3D_PDOA_DATA_T pdoa_data_cache[PDOA_3D_SUPPORT_NUM];
+#endif
+#define KF_SUPPORT_NUM 3
+#define KF_TIMEOUT_MS 2000
+static struct KF_MAC_ADDR_T kf_mac_addr_cache[KF_SUPPORT_NUM];
+static struct KF_CHANNEL_CACHE_T kf_channel_cache[KF_SUPPORT_NUM];
+static struct KF_MAT_VALUE_CACHE_T kf_mat_value_cache[KF_SUPPORT_NUM];
+void Anchor_uwb_aoa_square_init(void)
+{
+	  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 = 1,
+        .ranging_performance_mode = 0,
+#if RX_ANT_PORTS_NUM == 4
+        .skip_weakest_port_en = 1,
+#else
+        .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);
+
+    ranging_lib_init(config.phy_cfg.sts_pkt_cfg, CE_AUX_CH_PWR_NLOS_FOM);
+
+    // Register rx interrupt callback function
+    mac_register_process_handler(tx_int_callback, rx_int_callback);
+
+    // Reduce inter frame spacing (IFS) for non encrypted packets
+    mac_ifs_set(0, 0);
+
+#if (ANT_PATTERN == ANT_PATTERN_SQUARE)
+    angle_span_t aoa_span;
+    aoa_span.Ndim = 2;
+    aoa_span.el_low = 90;
+    aoa_span.el_high = 90;
+    aoa_span.el_step = 1;
+    aoa_span.az_low = 0;
+    aoa_span.az_high = 359;
+    aoa_span.az_step = 1;
+    aoa_angle_search_span_set(&aoa_span);
+#endif
+
+#if AOA_EN
+    sts_param_config(config.phy_cfg.sts_pkt_cfg, STS_AUX_ANT_IQ_RSSI_PDOA_AOA_FOM, STS_BUF_NUM, STS_BUF_SIZE);
+    aoa_steering_vector_set((const float *)((uint32_t)((config.phy_cfg.ch_num == 9) ? svec_ch9_ptr : svec_ch5_ptr) | SRAM_BASE));
+#else
+    sts_param_config(config.phy_cfg.sts_pkt_cfg, STS_AUX_ANT_IQ_RSSI, STS_BUF_NUM, STS_BUF_SIZE);
+#endif
+
+#if PDOA_3D_EN
+    pdoa_3d_param_config(ANT_PATTERN, ANT_LAYOUT, PDOA_3D_AMBIGUITY_LEVEL_NONE, mac_addr_cache, pdoa_data_cache, PDOA_3D_SUPPORT_NUM, PDOA_3D_TIMEOUT_MS);
+    // pdoa_angle_reverse_set(1, 0);
+#endif
+
+    // Set STS key and IV
+    phy_sts_key_configure(&sts_iv_key);
+
+    phy_rx_sts_switch_mode_set(config.phy_cfg.sts_pkt_cfg, STS_SWITCH_EVERY_4SYM, 0, 0);
+		//初始化滤波空间
+		loc_post_kf_config(1000, kf_mac_addr_cache, kf_channel_cache, kf_mat_value_cache, KF_SUPPORT_NUM, KF_TIMEOUT_MS);
+}
+
+
 //主函数绑定接受逻辑
 int UwbSearch(void)
 {
@@ -938,8 +1403,8 @@
 		#ifdef STS_MODE
 		ranging_lib_init();
 		#endif
-    ranging_frame_type_set(config.phy_cfg.sts_pkt_cfg);
-		
+    //ranging_frame_type_set(config.phy_cfg.sts_pkt_cfg);//新版本修改
+			ranging_lib_init(config.phy_cfg.sts_pkt_cfg, CE_AUX_CH_PWR_NLOS_FOM);
 		#ifdef STS_MODE
 		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));

--
Gitblit v1.9.3