通信定义
无人机信息:
uint8 消息类型=1
uint8 飞机id id
uint8 飞机类型 aircraftType
double x x
double y y
double z z
double 偏转角 yaw
double 俯仰角 pitch
double 滚动角 roll
子弹信息:
uint8 消息类型=2
uint8 子弹id id
uint8 子弹类型 missileType
uint8 子弹状态 missileState
double x x
double y y
double z z
点击查看代码
import socket
import struct
import time
import math
# 定义要发送的数据格式
def create_packet(msg_type, aircraft_id, aircraft_type, x, y, z, yaw, pitch, roll):
packet_format = 'BBBddd3d'
packet = struct.pack(packet_format, msg_type, aircraft_id, aircraft_type, x, y, z, yaw, pitch, roll)
return packet
# 配置UDP目标地址和端口
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 圆心位置
center_x = 0.0
center_y = 0.0
center_z = 500.0
# 圆的半径
radius = 100.0
# 初始角度
angle = 0.0
# 每次移动的角度(10度)
angle_increment = 10.0
# 设置发送间隔(秒)
send_interval = 1.0
try:
while True:
# 计算当前位置
radian = math.radians(angle)
x = center_x + radius * math.cos(radian)
y = center_y + radius * math.sin(radian)
z = center_z
# Yaw角对应当前角度,其他角度保持为0
yaw = angle
pitch = 0.0
roll = 0.0
# 生成数据包
msg_type = 1
aircraft_id = 1
aircraft_type = 1
packet = create_packet(msg_type, aircraft_id, aircraft_type, x, y, z, yaw, pitch, roll)
# 发送数据包
sock.sendto(packet, (UDP_IP, UDP_PORT))
print(f"Packet sent: Type={msg_type}, ID={aircraft_id}, Type={aircraft_type}, X={x}, Y={y}, Z={z}, Yaw={yaw}, Pitch={pitch}, Roll={roll}")
# 更新角度
angle = (angle + angle_increment) % 360
# 等待下一个发送时间
time.sleep(send_interval)
except KeyboardInterrupt:
print("UDP packet sending stopped.")
finally:
sock.close()
import struct
def hex_to_decimal(hex_string):
# 将16进制字符串转换为字节对象
byte_data = bytes.fromhex(hex_string)
# 使用struct模块解码字节数据,假设是大端序
# 这里的格式符号 '>' 表示大端序,'Q' 表示无符号长整型(8字节)
# 根据实际字节数调整格式符号
# 你可以根据需要使用不同的格式符号,如 'B'(1字节), 'H'(2字节), 'I'(4字节)
# 或者 'Q'(8字节)来匹配你的数据
try:
# 解析为大端序的无符号长整型
decimal_value = struct.unpack('>Q', byte_data)[0]
except struct.error:
# 处理字节长度不匹配的情况
raise ValueError("字节长度与指定格式不匹配")
return decimal_value
# 示例
hex_string = '0102030405060708' # 16进制字符串
decimal_value = hex_to_decimal(hex_string)
print(f'十进制值: {decimal_value}')
010101405900000000000040690000000000004072c00000000000000000000000000040240000000000004034000000000000
import struct
# 使用小端格式来解包数据
data = bytes.fromhex('4059000000000000')
value = struct.unpack('<d', data)[0] # 小端格式
print(value) # 应该输出 100.0
点击查看代码
import socket
import struct
import math
import time
# 定义要发送的数据格式
def create_packet(msg_type, aircraft_id, aircraft_type, x, y, z, yaw, pitch, roll):
packet_format = 'BBBddd3d'
packet = struct.pack(packet_format, msg_type, aircraft_id, aircraft_type, x, y, z, yaw, pitch, roll)
return packet
# 配置UDP目标地址和端口
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 圆的半径
radius = 2000.0
# 初始角度
angle = 0.0
# 每次移动的角度(10度)
angle_increment = 10.0
# 设置发送间隔(秒)
send_interval = 1.0
try:
while True:
# 计算当前位置
radian = math.radians(angle)
# 计算8字形轨迹的x, y坐标
x = radius * math.sin(radian)
y = radius * math.sin(2 * radian) / 2.0
z = 500.0
# Yaw角对应当前角度,其他角度保持为0
yaw = math.degrees(math.atan2(2 * math.cos(radian), -2 * math.sin(radian)))
pitch = 0.0
roll = 0.0
# 生成数据包
msg_type = 1
aircraft_id = 1
aircraft_type = 1
packet = create_packet(msg_type, aircraft_id, aircraft_type, x, y, z, yaw, pitch, roll)
# 发送数据包
sock.sendto(packet, (UDP_IP, UDP_PORT))
print(f"Packet sent: Type={msg_type}, ID={aircraft_id}, Type={aircraft_type}, X={x}, Y={y}, Z={z}, Yaw={yaw}, Pitch={pitch}, Roll={roll}")
# 更新角度
angle = (angle + angle_increment) % 360
# 等待下一个发送时间
time.sleep(send_interval)
except KeyboardInterrupt:
print("UDP packet sending stopped.")
finally:
sock.close()
点击查看代码
import socket
from pymavlink.dialects.v20.your_custom_dialect import MAVLink, MAVLink_search_mission_message, MAVLink_area_target_message_1, MAVLink_area_target_message_2, MAVLink_send_interference_area, MAVLink_send_interference_area_polygon
# 组播地址和端口
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
# 创建UDP组播套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
# 创建MAVLink对象
mav = MAVLink(None) # 将None传递给MAVLink,因为我们不需要文件输出
def send_search_mission_message(uav_id, mission_type, zone_node_num, zone_longitudes, zone_latitudes):
# 构建消息
msg = MAVLink_search_mission_message(
uav_id=uav_id,
mission_type=mission_type,
zone_node_num=zone_node_num,
zone_longitudes=zone_longitudes,
zone_latitudes=zone_latitudes
)
# 打包并发送消息
packet = msg.pack(mav)
sock.sendto(packet, (MCAST_GRP, MCAST_PORT))
def send_area_target_message_1(uav_id, area_node_num, area_node_longitudes, area_node_latitudes):
# 构建消息
msg = MAVLink_area_target_message_1(
uav_id=uav_id,
area_node_num=area_node_num,
area_node_longitudes=area_node_longitudes,
area_node_latitudes=area_node_latitudes
)
# 打包并发送消息
packet = msg.pack(mav)
sock.sendto(packet, (MCAST_GRP, MCAST_PORT))
def send_area_target_message_2(uav_id, target_longitudes, target_latitudes, target_type):
# 构建消息
msg = MAVLink_area_target_message_2(
uav_id=uav_id,
target_longitudes=target_longitudes,
target_latitudes=target_latitudes,
target_type=target_type
)
# 打包并发送消息
packet = msg.pack(mav)
sock.sendto(packet, (MCAST_GRP, MCAST_PORT))
def send_interference_area(id, isvalid, itemtype, noisetype, noisemean, noisevariance, connecttime, radius, longitude, latitude):
# 构建消息
msg = MAVLink_send_interference_area(
id=id,
isvalid=isvalid,
itemtype=itemtype,
noisetype=noisetype,
noisemean=noisemean,
noisevariance=noisevariance,
connecttime=connecttime,
radius=radius,
longitude=longitude,
latitude=latitude
)
# 打包并发送消息
packet = msg.pack(mav)
sock.sendto(packet, (MCAST_GRP, MCAST_PORT))
def send_interference_area_polygon(id, isvalid, itemtype, count, longitudes, latitudes):
# 构建消息
msg = MAVLink_send_interference_area_polygon(
id=id,
isvalid=isvalid,
itemtype=itemtype,
count=count,
longitudes=longitudes,
latitudes=latitudes
)
# 打包并发送消息
packet = msg.pack(mav)
sock.sendto(packet, (MCAST_GRP, MCAST_PORT))
# 示例调用
# 发送一条search_mission_message
send_search_mission_message(
uav_id=1,
mission_type=2,
zone_node_num=4,
zone_longitudes=[10.0] * 24,
zone_latitudes=[20.0] * 24
)
点击查看代码
import socket
import time
from pymavlink.dialects.v20.your_custom_dialect import MAVLink, MAVLink_search_mission_message_message, MAVLink_area_target_message_1_message, MAVLink_area_target_message_2_message, MAVLink_send_interference_area_message, MAVLink_send_interference_area_polygon_message
# 组播地址和端口
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
# 创建UDP组播套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
# 创建MAVLink对象
mav = MAVLink(None) # None传递给MAVLink,因为我们不需要文件输出
def send_message(msg):
"""发送MAVLink消息"""
packet = msg.pack(mav)
sock.sendto(packet, (MCAST_GRP, MCAST_PORT))
# 构建每种消息的函数,接受外部输入
def create_search_mission_message(uav_id, mission_type, zone_node_num, zone_longitudes, zone_latitudes):
"""构建search_mission_message"""
return MAVLink_search_mission_message_message(
uav_id=uav_id,
mission_type=mission_type,
zone_node_num=zone_node_num,
zone_longitudes=zone_longitudes,
zone_latitudes=zone_latitudes
)
def create_area_target_message_1(uav_id, area_node_num, area_node_longitudes, area_node_latitudes):
"""构建area_target_message_1"""
return MAVLink_area_target_message_1_message(
uav_id=uav_id,
area_node_num=area_node_num,
area_node_longitudes=area_node_longitudes,
area_node_latitudes=area_node_latitudes
)
def create_area_target_message_2(uav_id, target_longitudes, target_latitudes, target_type):
"""构建area_target_message_2"""
return MAVLink_area_target_message_2_message(
uav_id=uav_id,
target_longitudes=target_longitudes,
target_latitudes=target_latitudes,
target_type=target_type
)
def create_send_interference_area(id, isvalid, itemtype, noisetype, noisemean, noisevariance, connecttime, radius, longitude, latitude):
"""构建send_interference_area"""
return MAVLink_send_interference_area_message(
id=id,
isvalid=isvalid,
itemtype=itemtype,
noisetype=noisetype,
noisemean=noisemean,
noisevariance=noisevariance,
connecttime=connecttime,
radius=radius,
longitude=longitude,
latitude=latitude
)
def create_send_interference_area_polygon(id, isvalid, itemtype, count, longitudes, latitudes):
"""构建send_interference_area_polygon"""
return MAVLink_send_interference_area_polygon_message(
id=id,
isvalid=isvalid,
itemtype=itemtype,
count=count,
longitudes=longitudes,
latitudes=latitudes
)
def main():
# 构建一个正方形的search_mission_message
square_side = 0.01
zone_longitudes = [120.0, 120.0 + square_side, 120.0 + square_side, 120.0] + [0.0] * 20
zone_latitudes = [30.0, 30.0, 30.0 + square_side, 30.0 + square_side] + [0.0] * 20
search_msg = create_search_mission_message(
uav_id=1,
mission_type=2,
zone_node_num=4,
zone_longitudes=zone_longitudes,
zone_latitudes=zone_latitudes
)
print("Sending search_mission_message:", search_msg)
send_message(search_msg)
time.sleep(2) # 等待2秒
# 构建4个正方形的area_target_message_1
for i in range(4):
longitudes = [120.0 + i * 0.02, 120.01 + i * 0.02, 120.01 + i * 0.02, 120.0 + i * 0.02] + [0.0] * 20
latitudes = [30.0 + i * 0.02, 30.0 + i * 0.02, 30.01 + i * 0.02, 30.01 + i * 0.02] + [0.0] * 20
area_target_1_msg = create_area_target_message_1(
uav_id=1,
area_node_num=4,
area_node_longitudes=longitudes,
area_node_latitudes=latitudes
)
print(f"Sending area_target_message_1 [{i + 1}]:", area_target_1_msg)
send_message(area_target_1_msg)
time.sleep(0.5) # 发送消息间隔
# 构建4个area_target_message_2,点在对应的area_target_message_1的区域内
for i in range(4):
longitudes = [120.0 + i * 0.02 + 0.002 * j for j in range(25)]
latitudes = [30.0 + i * 0.02 + 0.002 * j for j in range(25)]
area_target_2_msg = create_area_target_message_2(
uav_id=1,
target_longitudes=longitudes,
target_latitudes=latitudes,
target_type=[1] * 25
)
print(f"Sending area_target_message_2 [{i + 1}]:", area_target_2_msg)
send_message(area_target_2_msg)
time.sleep(0.5) # 发送消息间隔
# 构建一个圆形的send_interference_area
interference_area_msg = create_send_interference_area(
id=123,
isvalid=1,
itemtype=2,
noisetype=3,
noisemean=0.1,
noisevariance=0.01,
connecttime=100.0,
radius=500.0,
longitude=120.0,
latitude=30.0
)
print("Sending send_interference_area:", interference_area_msg)
send_message(interference_area_msg)
time.sleep(1) # 等待1秒
# 构建一个六边形的send_interference_area_polygon
hex_side = 0.01
hex_longitudes = [
120.0,
120.0 + hex_side,
120.0 + 1.5 * hex_side,
120.0 + hex_side,
120.0,
120.0 - 0.5 * hex_side
] + [0.0] * 14
hex_latitudes = [
30.0,
30.0,
30.0 + hex_side,
30.0 + 2 * hex_side,
30.0 + 2 * hex_side,
30.0 + hex_side
] + [0.0] * 14
interference_polygon_msg = create_send_interference_area_polygon(
id=456,
isvalid=1,
itemtype=2,
count=6,
longitudes=hex_longitudes,
latitudes=hex_latitudes
)
print("Sending send_interference_area_polygon:", interference_polygon_msg)
send_message(interference_polygon_msg)
if __name__ == "__main__":
main()
# 初始化UDP组播套接字
def init_multicast_socket(multicast_address="239.255.145.50", multicast_port=14552):
# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# 设置套接字选项允许组播
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) # 设置TTL
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许地址重用
# 将组播地址绑定到套接字上
sock.bind(('', multicast_port)) # 绑定本地端口
# 加入组播组
mreq = struct.pack("4sl", socket.inet_aton(multicast_address), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
return sock
for i in range(4):
# 区域的边界
min_longitude = 120.0
max_longitude = 120.05
min_latitude = 30.0 + i * 0.1
max_latitude = 30.05 + i * 0.1
# 计算每个子网格的步长
longitude_step = (max_longitude - min_longitude) / 4
latitude_step = (max_latitude - min_latitude) / 4
# 生成目标位置,形成5x5的方阵
longitudes = [min_longitude + longitude_step * (j % 5) for j in range(25)]
latitudes = [min_latitude + latitude_step * (j // 5) for j in range(25)]
area_target_2_msg = create_area_target_message_2(
uav_id=i+3,
target_longitudes=longitudes,
target_latitudes=latitudes,
target_type=[1] * 25
)
print(f"Sending area_target_message_2 [{i + 1}]:", area_target_2_msg)
send_message(area_target_2_msg)
time.sleep(0.5) # 发送消息间隔
点击查看代码
import socket
import struct
import math
import time
# UDP 目标 IP 和端口
TARGET_IP = '127.0.0.1'
TARGET_PORT = 12345
# 创建 UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 参数设置
aircraft_id = 1
aircraft_type = 1
missile1_id = 1
missile2_id = 2
missile_type = 0
missile1_state = 1
missile2_state = 1
# 轨迹参数
time_interval = 0.1 # 时间间隔
radius = 2000 # 半径
speed = 100 # 速度
missile2_start = (5000, 5000, 1000)
missile2_end = (10000, 10000, 1000)
# 当前状态
missile2_position = list(missile2_start)
missile2_reached = False
def send_aircraft_data():
t = time.time()
# 生成飞机 8 字运动轨迹 (利用参数方程)
x = radius * math.sin(t * speed / radius)
y = radius * math.sin(2 * t * speed / radius) # figure-8 的另一半
z = 1000 # 高度保持不变
yaw = 0.0
pitch = 0.0
roll = 0.0
# 打包数据
data = struct.pack('=BBBdddddd', 1, aircraft_id, aircraft_type, x, y, z, yaw, pitch, roll)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def send_missile1_data():
t = time.time()
# 生成导弹 1 圆周运动轨迹
x = radius * math.cos(t * speed / radius)
y = radius * math.sin(t * speed / radius)
z = 500 # 高度保持不变
# 打包数据
data = struct.pack('=BBBBddd', 2, missile1_id, missile_type, missile1_state, x, y, z)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def send_missile2_data():
global missile2_state, missile2_reached, missile2_position
if missile2_reached:
return
# 计算导弹 2 直线前往目标点
step = 50 # 每次移动的距离
direction = [(missile2_end[i] - missile2_position[i]) for i in range(3)]
distance = math.sqrt(sum(d ** 2 for d in direction))
if distance < step:
# 到达终点
missile2_position = list(missile2_end)
missile2_state = 2 # 命中状态
missile2_reached = True
else:
# 沿方向移动
norm_dir = [d / distance for d in direction]
missile2_position = [missile2_position[i] + norm_dir[i] * step for i in range(3)]
# 打包数据
data = struct.pack('=BBBBddd', 2, missile2_id, missile_type, missile2_state, *missile2_position)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def main():
while True:
send_aircraft_data()
send_missile1_data()
send_missile2_data()
time.sleep(time_interval)
if __name__ == "__main__":
main()
点击查看代码
import socket
import struct
import math
import time
from threading import Timer
# UDP 目标 IP 和端口
TARGET_IP = '127.0.0.1'
TARGET_PORT = 12345
# 创建 UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 配置部分
config = {
'aircrafts': [
{'id': 2, 'type': 1, 'formation': 'line', 'position': (-100, 0), 'speed': 50}, # 左
{'id': 3, 'type': 1, 'formation': 'line', 'position': (0, 0), 'speed': 50}, # 中
{'id': 4, 'type': 1, 'formation': 'line', 'position': (100, 0), 'speed': 50}, # 右
{'id': 1, 'type': 1, 'movement': 'circle', 'radius': 500, 'speed': 100}, # 无人机转圈
],
'missiles': [
{'id': 1, 'movement': 'straight', 'speed': 200},
{'id': 2, 'movement': 'circle', 'radius': 300, 'speed': 150},
{'id': 3, 'movement': 'straight_descend', 'speed': 200, 'descend_rate': 5, 'explode_after': 5},
],
'delays': {
'missile_spawn': 3 # 导弹生成延迟时间(秒)
}
}
def send_aircraft_data(aircraft, t):
if aircraft.get('formation') == 'line':
# 三架飞机并排飞行,按照初始位置线性运动
x = aircraft['position'][0] + t * aircraft['speed']
y = aircraft['position'][1]
z = 1000 # 高度保持不变
yaw = 0.0
elif aircraft.get('movement') == 'circle':
# 无人机转圈飞行
x = aircraft['radius'] * math.cos(t * aircraft['speed'] / aircraft['radius'])
y = aircraft['radius'] * math.sin(t * aircraft['speed'] / aircraft['radius'])
z = 1000 # 高度保持不变
yaw = math.degrees(math.atan2(y, x))
else:
return # 未知运动方式
pitch = 0.0
roll = 0.0
# 打包数据
data = struct.pack('=BBBdddddd', 1, aircraft['id'], aircraft['type'], x, y, z, yaw, pitch, roll)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def send_missile_data(missile, t):
if missile['movement'] == 'straight':
x = t * missile['speed']
y = 0
z = 500
elif missile['movement'] == 'circle':
x = missile['radius'] * math.cos(t * missile['speed'] / missile['radius'])
y = missile['radius'] * math.sin(t * missile['speed'] / missile['radius'])
z = 500
elif missile['movement'] == 'straight_descend':
x = t * missile['speed']
y = 0
z = 500 - missile['descend_rate'] * t
if t >= missile['explode_after']:
missile['state'] = 2 # 爆炸状态
else:
return # 未知运动方式
state = missile.get('state', 1)
# 打包数据
data = struct.pack('=BBBBddd', 2, missile['id'], 0, state, x, y, z)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def main():
start_time = time.time()
def spawn_missiles():
missile_timers = []
while True:
t = time.time() - (start_time + config['delays']['missile_spawn'])
if t >= 0:
for missile in config['missiles']:
send_missile_data(missile, t)
time.sleep(0.1)
# 启动导弹生成计时器
missile_timer = Timer(config['delays']['missile_spawn'], spawn_missiles)
missile_timer.start()
while True:
t = time.time() - start_time
for aircraft in config['aircrafts']:
send_aircraft_data(aircraft, t)
time.sleep(0.1)
if __name__ == "__main__":
main()
飞机导弹
import socket
import struct
import math
import time
from threading import Timer
# UDP 目标 IP 和端口
TARGET_IP = "192.168.1.103"
TARGET_PORT = 12345
# 创建 UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 配置部分
config = {
'aircrafts': [
{'id': 2, 'type': 1, 'formation': 'line', 'position': (643550, -385070, -451000), 'speed': 500}, # 左
{'id': 3, 'type': 1, 'formation': 'line', 'position': (645550, -385070, -451000), 'speed': 500}, # 中
{'id': 4, 'type': 1, 'formation': 'line', 'position': (647550, -385070, -451000), 'speed': 500}, # 右
{'id': 1, 'type': 1, 'movement': 'circle', 'center': (650550, -385070), 'radius': 1500, 'speed': 500, 'altitude': -451000}, # 无人机转圈
],
'missiles': [
{'id': 1, 'valid':1,'movement': 'straight','center': (643550, -385070), 'speed': 500, 'start_altitude': -452000},
{'id': 2, 'valid':1,'movement': 'circle', 'center': (648550, -385070), 'radius': 1000, 'speed': 500, 'altitude':-452000},
{'id': 3, 'valid':1,'movement': 'straight_descend', 'center': (645550, -385070),'speed': 500, 'descend_rate': 100, 'start_altitude': -452000, 'explode_after': 10},
],
'delays': {
'missile_spawn': 3 # 导弹生成延迟时间(秒)
}
}
# 保存先前位置,用于计算偏航角
previous_positions = {ac['id']: (0, 0) for ac in config['aircrafts']}
def calculate_yaw(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
return math.degrees(math.atan2(dy, dx))
def send_aircraft_data(aircraft, t):
global previous_positions
if aircraft.get('formation') == 'line':
# 三架飞机并排飞行,按照初始位置线性运动
x = aircraft['position'][0]
y = aircraft['position'][1] + t * aircraft['speed']
z = aircraft['position'][2] # 高度保持可配置
elif aircraft.get('movement') == 'circle':
# 无人机转圈飞行
center_x, center_y = aircraft['center']
x = center_x + aircraft['radius'] * math.sin(t * aircraft['speed'] / aircraft['radius'])
y = center_y + aircraft['radius'] * math.cos(t * aircraft['speed'] / aircraft['radius'])
z = aircraft['altitude'] # 高度保持可配置
else:
return # 未知运动方式
# 计算偏航角
pre_x, pre_y = previous_positions[aircraft['id']]
yaw = calculate_yaw(pre_x, pre_y, x, y)
pitch = 0.0
roll = 0.0
# 更新先前位置
previous_positions[aircraft['id']] = (x, y)
# 打包数据
data = struct.pack('=BBBdddddd', 1, aircraft['id'], aircraft['type'], x, y, z, yaw, pitch, roll)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def send_missile_data(missile, t):
if missile['movement'] == 'straight':
center_x, center_y = missile['center']
x = center_x + 0
y = center_y + t * missile['speed']
z = missile['start_altitude'] # 初始高度可配置
state = 1 # 状态为发射中
elif missile['movement'] == 'circle':
center_x, center_y = missile['center']
x = center_x + missile['radius'] * math.cos(t * missile['speed'] / missile['radius'])
y = center_y + missile['radius'] * math.sin(t * missile['speed'] / missile['radius'])
z = missile['altitude'] # 高度保持可配置
state = 1 # 状态为发射中
elif missile['movement'] == 'straight_descend':
center_x, center_y = missile['center']
x = center_x + 0
y = center_y + t * missile['speed']
z = missile['start_altitude'] - missile['descend_rate'] * t /2 # 高度随时间下降
if t >= missile['explode_after']:
state = 2 # 爆炸状态
else:
state = 1 # 发射中
else:
return # 未知运动方式
# 仅向前下方飞的导弹(ID 3)可以爆炸
if missile['id'] != 3 :
state = 1
# 打包数据
if missile['valid']==1:
if state == 2:
missile['valid']=0
data = struct.pack('=BBBBddd', 2, missile['id'], 0, state, x, y, z)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def main():
start_time = time.time()
def spawn_missiles():
missile_timers = []
while True:
t = time.time() - (start_time + config['delays']['missile_spawn'])
if t >= 0:
for missile in config['missiles']:
send_missile_data(missile, t)
time.sleep(0.1)
# 启动导弹生成计时器
missile_timer = Timer(config['delays']['missile_spawn'], spawn_missiles)
missile_timer.start()
while True:
t = time.time() - start_time
for aircraft in config['aircrafts']:
send_aircraft_data(aircraft, t)
time.sleep(0.1)
if __name__ == "__main__":
main()
目标区域
import socket
import time
from pymavlink import MAVLink, MAVLink_search_mission_message_message, \
MAVLink_area_target_message_1_message, MAVLink_area_target_message_2_message, \
MAVLink_send_interference_area_message, MAVLink_send_interference_area_polygon_message
import struct
# 组播地址和端口
MCAST_GRP = '239.255.145.50'
MCAST_PORT = 14551
# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# 设置套接字选项允许组播
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) # 设置TTL
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许地址重用
# 将组播地址绑定到套接字上
sock.bind(('192.168.1.102', MCAST_PORT)) # 绑定本地端口
# 加入组播组
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
# 创建MAVLink对象
mav = MAVLink(None) # None传递给MAVLink,因为我们不需要文件输出
ori_x = 125.78108156
ori_y = 26.59832155
def send_message(msg):
"""发送MAVLink消息"""
packet = msg.pack(mav)
sock.sendto(packet, (MCAST_GRP, MCAST_PORT))
# 构建每种消息的函数,接受外部输入
def create_search_mission_message(uav_id, mission_type, zone_node_num, zone_longitudes, zone_latitudes):
"""构建search_mission_message"""
return MAVLink_search_mission_message_message(
uav_id=uav_id,
mission_type=mission_type,
zone_node_num=zone_node_num,
zone_longitudes=zone_longitudes,
zone_latitudes=zone_latitudes
)
def create_area_target_message_1(uav_id, area_node_num, area_node_longitudes, area_node_latitudes):
"""构建area_target_message_1"""
return MAVLink_area_target_message_1_message(
uav_id=uav_id,
area_node_num=area_node_num,
area_node_longitudes=area_node_longitudes,
area_node_latitudes=area_node_latitudes
)
def create_area_target_message_2(uav_id, target_longitudes, target_latitudes, target_type):
"""构建area_target_message_2"""
return MAVLink_area_target_message_2_message(
uav_id=uav_id,
target_longitudes=target_longitudes,
target_latitudes=target_latitudes,
target_type=target_type
)
def create_send_interference_area(id, isvalid, itemtype, noisetype, noisemean, noisevariance, connecttime, radius,
longitude, latitude):
"""构建send_interference_area"""
return MAVLink_send_interference_area_message(
id=id,
isvalid=isvalid,
itemtype=itemtype,
noisetype=noisetype,
noisemean=noisemean,
noisevariance=noisevariance,
connecttime=connecttime,
radius=radius,
longitude=longitude,
latitude=latitude
)
def create_send_interference_area_polygon(id, isvalid, itemtype, count, longitudes, latitudes):
"""构建send_interference_area_polygon"""
return MAVLink_send_interference_area_polygon_message(
id=id,
isvalid=isvalid,
itemtype=itemtype,
count=count,
longitudes=longitudes,
latitudes=latitudes
)
def main():
# 构建一个正方形的search_mission_message
square_side = 0.2
subsquare_side = 0.1
zone_longitudes = [ori_x,ori_x+ square_side, ori_x+ square_side, ori_x] + [0.0] * 20
zone_latitudes = [ori_y - 0.2 , ori_y - 0.2, ori_y - 0.2 + square_side, ori_y - 0.2 + square_side] + [0.0] * 20
search_msg = create_search_mission_message(
uav_id=1,
mission_type=2,
zone_node_num=4,
zone_longitudes=zone_longitudes,
zone_latitudes=zone_latitudes
)
print("Sending search_mission_message:", search_msg)
send_message(search_msg)
time.sleep(2) # 等待2秒
# 构建4个正方形的area_target_message_1
for i in range(4):
longitudes = [ori_x-0.2,ori_x-0.2+ subsquare_side, ori_x-0.2+ subsquare_side, ori_x-0.2] + [0.0] * 20
latitudes = [ori_y + i * 0.15, ori_y + i * 0.15, ori_y + subsquare_side + i * 0.15, ori_y + subsquare_side + i * 0.15] + [0.0] * 20
area_target_1_msg = create_area_target_message_1(
uav_id=i+3,
area_node_num=4,
area_node_longitudes=longitudes,
area_node_latitudes=latitudes
)
print(f"Sending area_target_message_1 [{i + 1}]:", area_target_1_msg)
send_message(area_target_1_msg)
time.sleep(0.5) # 发送消息间隔
# 构建4个area_target_message_2,点在对应的area_target_message_1的区域内
for i in range(4):
# 区域的边界
min_longitude = ori_x-0.2+0.01
max_longitude = ori_x-0.2+ subsquare_side-0.01
min_latitude = ori_y + i * 0.15
max_latitude = ori_y + subsquare_side+ i * 0.15
# 计算每个子网格的步长
longitude_step = (max_longitude - min_longitude) / 4
latitude_step = (max_latitude - min_latitude) / 4
# 生成目标位置,形成5x5的方阵
longitudes = [min_longitude + longitude_step * (j % 5) for j in range(25)]
latitudes = [min_latitude + latitude_step * (j // 5) for j in range(25)]
area_target_2_msg = create_area_target_message_2(
uav_id=i + 3,
target_longitudes=longitudes,
target_latitudes=latitudes,
target_type=[1] * 25
)
print(f"Sending area_target_message_2 [{i + 1}]:", area_target_2_msg)
send_message(area_target_2_msg)
time.sleep(0.5) # 发送消息间隔
# 构建一个圆形的send_interference_area
interference_area_msg = create_send_interference_area(
id=123,
isvalid=1,
itemtype=1,
noisetype=3,
noisemean=0.1,
noisevariance=0.01,
connecttime=100.0,
radius=300.0,
longitude=ori_x-0.2,
latitude=ori_y-0.6
)
print("Sending send_interference_area:", interference_area_msg)
send_message(interference_area_msg)
time.sleep(0.5) # 等待1秒
# 构建一个六边形的send_interference_area_polygon
hex_side = 0.15
hex_longitudes = [
ori_x+0.3,
ori_x +0.3+ hex_side,
ori_x +0.3+ 1.5 * hex_side,
ori_x +0.3+ hex_side,
ori_x+0.3,
ori_x+0.3 - 0.5 * hex_side
] + [0.0] * 14
hex_latitudes = [
ori_y-0.5,
ori_y-0.5,
ori_y-0.5 + hex_side,
ori_y-0.5 + 2 * hex_side,
ori_y-0.5 + 2 * hex_side,
ori_y-0.5 + hex_side
] + [0.0] * 14
interference_polygon_msg = create_send_interference_area_polygon(
id=456,
isvalid=1,
itemtype=2,
count=6,
longitudes=hex_longitudes,
latitudes=hex_latitudes
)
print("Sending send_interference_area_polygon:", interference_polygon_msg)
send_message(interference_polygon_msg)
if __name__ == "__main__":
main()
点击查看代码
import socket
import struct
import math
import time
from threading import Timer
# UDP 目标 IP 和端口
TARGET_IP = "192.168.1.104"
TARGET_PORT = 12345
# 创建 UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 配置部分
config = {
'aircrafts': [
{'id': 2, 'type': 1, 'formation': 'line', 'position': (643550, -385070, -451000), 'speed': 500}, # 左
{'id': 3, 'type': 1, 'formation': 'line', 'position': (645550, -385070, -451000), 'speed': 500}, # 中
{'id': 4, 'type': 1, 'formation': 'line', 'position': (647550, -385070, -451000), 'speed': 500}, # 右
{'id': 1, 'type': 1, 'movement': 'circle', 'center': (650550, -385070), 'radius': 1500, 'speed': 500, 'altitude': -451000}, # 无人机转圈
],
'missiles': [
{'id': 1, 'valid':1,'movement': 'straight','center': (643550, -385070), 'speed': 500, 'start_altitude': -452000},
{'id': 2, 'valid':1,'movement': 'circle', 'center': (648550, -385070), 'radius': 1000, 'speed': 500, 'altitude':-452000},
{'id': 3, 'valid':1,'movement': 'straight_descend', 'center': (645550, -385070),'speed': 500, 'descend_rate': 100, 'start_altitude': -452000, 'explode_after': 10},
],
'delays': {
'missile_spawn': 3 # 导弹生成延迟时间(秒)
}
}
# 保存先前位置,用于计算偏航角
previous_positions = {ac['id']: (0, 0) for ac in config['aircrafts']}
def calculate_yaw(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
return math.degrees(math.atan2(dy, dx))
def send_aircraft_data(aircraft, t):
global previous_positions
if aircraft.get('formation') == 'line':
# 三架飞机并排飞行,按照初始位置线性运动
x = aircraft['position'][0]
y = aircraft['position'][1] + t * aircraft['speed']
z = aircraft['position'][2] # 高度保持可配置
elif aircraft.get('movement') == 'circle':
# 无人机转圈飞行
center_x, center_y = aircraft['center']
x = center_x + aircraft['radius'] * math.sin(t * aircraft['speed'] / aircraft['radius'])
y = center_y + aircraft['radius'] * math.cos(t * aircraft['speed'] / aircraft['radius'])
z = aircraft['altitude'] # 高度保持可配置
else:
return # 未知运动方式
# 计算偏航角
pre_x, pre_y = previous_positions[aircraft['id']]
yaw = calculate_yaw(pre_x, pre_y, x, y)
pitch = 0.0
roll = 0.0
# 更新先前位置
previous_positions[aircraft['id']] = (x, y)
# 打包数据
data = struct.pack('=BBBdddddd', 1, aircraft['id'], aircraft['type'], x, y, z, yaw, pitch, roll)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def send_missile_data(missile, t):
if missile['movement'] == 'straight':
center_x, center_y = missile['center']
x = center_x + 0
y = center_y + t * missile['speed']
z = missile['start_altitude'] # 初始高度可配置
state = 1 # 状态为发射中
elif missile['movement'] == 'circle':
center_x, center_y = missile['center']
x = center_x + missile['radius'] * math.cos(t * missile['speed'] / missile['radius'])
y = center_y + missile['radius'] * math.sin(t * missile['speed'] / missile['radius'])
z = missile['altitude'] # 高度保持可配置
state = 1 # 状态为发射中
elif missile['movement'] == 'straight_descend':
center_x, center_y = missile['center']
x = center_x + 0
y = center_y + t * missile['speed']
z = missile['start_altitude'] - missile['descend_rate'] * t /2 # 高度随时间下降
if t >= missile['explode_after']:
state = 2 # 爆炸状态
else:
state = 1 # 发射中
else:
return # 未知运动方式
# 仅向前下方飞的导弹(ID 3)可以爆炸
if missile['id'] != 3 :
state = 1
# 打包数据
if missile['valid']==1:
if state == 2:
missile['valid']=0
data = struct.pack('=BBBBddd', 2, missile['id'], 0, state, x, y, z)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def main():
start_time = time.time()
def spawn_missiles():
missile_timers = []
while True:
t = time.time() - (start_time + config['delays']['missile_spawn'])
if t >= 0:
for missile in config['missiles']:
send_missile_data(missile, t)
time.sleep(0.1)
# 启动导弹生成计时器
missile_timer = Timer(config['delays']['missile_spawn'], spawn_missiles)
missile_timer.start()
while True:
t = time.time() - start_time
for aircraft in config['aircrafts']:
send_aircraft_data(aircraft, t)
time.sleep(0.1)
if __name__ == "__main__":
main()
点击查看代码
import socket
import time
from pymavlink import MAVLink, MAVLink_search_mission_message_message, \
MAVLink_area_target_message_1_message, MAVLink_area_target_message_2_message, \
MAVLink_send_interference_area_message, MAVLink_send_interference_area_polygon_message
import struct
# 组播地址和端口
MCAST_GRP = '239.255.145.50'
MCAST_PORT = 14551
# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# 设置套接字选项允许组播
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) # 设置TTL
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许地址重用
# 将组播地址绑定到套接字上
sock.bind(('192.168.1.113', MCAST_PORT)) # 绑定本地端口
# 加入组播组
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
# 创建MAVLink对象
mav = MAVLink(None) # None传递给MAVLink,因为我们不需要文件输出
ori_x = 125.78108156
ori_y = 26.59832155
def send_message(msg):
"""发送MAVLink消息"""
packet = msg.pack(mav)
sock.sendto(packet, (MCAST_GRP, MCAST_PORT))
# 构建每种消息的函数,接受外部输入
def create_search_mission_message(uav_id, mission_type, zone_node_num, zone_longitudes, zone_latitudes):
"""构建search_mission_message"""
return MAVLink_search_mission_message_message(
uav_id=uav_id,
mission_type=mission_type,
zone_node_num=zone_node_num,
zone_longitudes=zone_longitudes,
zone_latitudes=zone_latitudes
)
def create_area_target_message_1(uav_id, area_node_num, area_node_longitudes, area_node_latitudes):
"""构建area_target_message_1"""
return MAVLink_area_target_message_1_message(
uav_id=uav_id,
area_node_num=area_node_num,
area_node_longitudes=area_node_longitudes,
area_node_latitudes=area_node_latitudes
)
def create_area_target_message_2(uav_id, target_longitudes, target_latitudes, target_type):
"""构建area_target_message_2"""
return MAVLink_area_target_message_2_message(
uav_id=uav_id,
target_longitudes=target_longitudes,
target_latitudes=target_latitudes,
target_type=target_type
)
def create_send_interference_area(id, isvalid, itemtype, noisetype, noisemean, noisevariance, connecttime, radius,
longitude, latitude):
"""构建send_interference_area"""
return MAVLink_send_interference_area_message(
id=id,
isvalid=isvalid,
itemtype=itemtype,
noisetype=noisetype,
noisemean=noisemean,
noisevariance=noisevariance,
connecttime=connecttime,
radius=radius,
longitude=longitude,
latitude=latitude
)
def create_send_interference_area_polygon(id, isvalid, itemtype, count, longitudes, latitudes):
"""构建send_interference_area_polygon"""
return MAVLink_send_interference_area_polygon_message(
id=id,
isvalid=isvalid,
itemtype=itemtype,
count=count,
longitudes=longitudes,
latitudes=latitudes
)
def main():
# 构建一个正方形的search_mission_message
square_side = 0.2
subsquare_side = 0.1
zone_longitudes = [ori_x,ori_x+ square_side, ori_x+ square_side, ori_x] + [0.0] * 20
zone_latitudes = [ori_y - 0.2 , ori_y - 0.2, ori_y - 0.2 + square_side, ori_y - 0.2 + square_side] + [0.0] * 20
search_msg = create_search_mission_message(
uav_id=1,
mission_type=2,
zone_node_num=4,
zone_longitudes=zone_longitudes,
zone_latitudes=zone_latitudes
)
print("Sending search_mission_message:", search_msg)
send_message(search_msg)
time.sleep(2) # 等待2秒
# 构建4个正方形的area_target_message_1
for i in range(4):
longitudes = [ori_x-0.2,ori_x-0.2+ subsquare_side, ori_x-0.2+ subsquare_side, ori_x-0.2] + [0.0] * 20
latitudes = [ori_y + i * 0.15, ori_y + i * 0.15, ori_y + subsquare_side + i * 0.15, ori_y + subsquare_side + i * 0.15] + [0.0] * 20
area_target_1_msg = create_area_target_message_1(
uav_id=i+3,
area_node_num=4,
area_node_longitudes=longitudes,
area_node_latitudes=latitudes
)
print(f"Sending area_target_message_1 [{i + 1}]:", area_target_1_msg)
send_message(area_target_1_msg)
time.sleep(0.5) # 发送消息间隔
# 构建4个area_target_message_2,点在对应的area_target_message_1的区域内
for i in range(4):
# 区域的边界
min_longitude = ori_x-0.2+0.01
max_longitude = ori_x-0.2+ subsquare_side-0.01
min_latitude = ori_y + i * 0.15
max_latitude = ori_y + subsquare_side+ i * 0.15
# 计算每个子网格的步长
longitude_step = (max_longitude - min_longitude) / 4
latitude_step = (max_latitude - min_latitude) / 4
# 生成目标位置,形成5x5的方阵
longitudes = [min_longitude + longitude_step * (j % 5) for j in range(25)]
latitudes = [min_latitude + latitude_step * (j // 5) for j in range(25)]
area_target_2_msg = create_area_target_message_2(
uav_id=i + 3,
target_longitudes=longitudes,
target_latitudes=latitudes,
target_type=[1] * 25
)
print(f"Sending area_target_message_2 [{i + 1}]:", area_target_2_msg)
send_message(area_target_2_msg)
time.sleep(0.5) # 发送消息间隔
# 构建一个圆形的send_interference_area
interference_area_msg = create_send_interference_area(
id=123,
isvalid=1,
itemtype=1,
noisetype=3,
noisemean=0.1,
noisevariance=0.01,
connecttime=100.0,
radius=300.0,
longitude=ori_x-0.2,
latitude=ori_y-0.6
)
print("Sending send_interference_area:", interference_area_msg)
send_message(interference_area_msg)
time.sleep(0.5) # 等待1秒
# 构建一个六边形的send_interference_area_polygon
hex_side = 0.15
hex_longitudes = [
ori_x+0.3,
ori_x +0.3+ hex_side,
ori_x +0.3+ 1.5 * hex_side,
ori_x +0.3+ hex_side,
ori_x+0.3,
ori_x+0.3 - 0.5 * hex_side
] + [0.0] * 14
hex_latitudes = [
ori_y-0.5,
ori_y-0.5,
ori_y-0.5 + hex_side,
ori_y-0.5 + 2 * hex_side,
ori_y-0.5 + 2 * hex_side,
ori_y-0.5 + hex_side
] + [0.0] * 14
interference_polygon_msg = create_send_interference_area_polygon(
id=456,
isvalid=1,
itemtype=2,
count=6,
longitudes=hex_longitudes,
latitudes=hex_latitudes
)
print("Sending send_interference_area_polygon:", interference_polygon_msg)
send_message(interference_polygon_msg)
if __name__ == "__main__":
main()
点击查看代码
import socket
import struct
import math
import time
from threading import Timer
# UDP 目标 IP 和端口
TARGET_IP = "192.168.1.105"
TARGET_PORT = 12345
# 创建 UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 配置部分
config = {
'aircrafts': [
{'id': 1, 'type': 1, 'formation': 'line', 'position': (0, 0, 2000), 'speed': 1000}, # 左
{'id': 2, 'type': 1, 'formation': 'line', 'position': (200, 0, 2000), 'speed': 1000}, # 中
{'id': 3, 'type': 1, 'formation': 'line', 'position': (400, 0, 2000), 'speed': 1000}, # 右
{'id': 4, 'type': 1, 'movement': 'circle', 'center': (1600, -1000), 'radius': 1000, 'speed': 1000, 'altitude': 2500}, # 无人机转圈
],
'missiles': [
{'id': 1, 'valid':1,'movement': 'straight','center': (0, 1500), 'speed': 2000, 'start_altitude': 1500},
{'id': 2, 'valid':1,'movement': 'circle', 'center': (400, 500), 'radius': 2000, 'speed': 1000, 'altitude':1500},
{'id': 3, 'valid':1,'movement': 'straight_descend', 'center': (200, 1500),'speed': 2000, 'descend_rate': 200, 'start_altitude': 1500, 'explode_after': 7},
],
'delays': {
'missile_spawn':3 # 导弹生成延迟时间(秒)
}
}
# 保存先前位置,用于计算偏航角
previous_positions = {ac['id']: (0, 0) for ac in config['aircrafts']}
def calculate_yaw(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
return math.degrees(math.atan2(dy, dx))
def send_aircraft_data(aircraft, t):
global previous_positions
if aircraft.get('formation') == 'line':
# 三架飞机并排飞行,按照初始位置线性运动
x = aircraft['position'][0]
y = aircraft['position'][1] + t * aircraft['speed']
z = aircraft['position'][2] # 高度保持可配置
elif aircraft.get('movement') == 'circle':
# 无人机转圈飞行
center_x, center_y = aircraft['center']
x = center_x + aircraft['radius'] * math.sin(t * aircraft['speed'] / aircraft['radius'])
y = center_y + aircraft['radius'] * math.cos(t * aircraft['speed'] / aircraft['radius'])
z = aircraft['altitude'] # 高度保持可配置
else:
return # 未知运动方式
# 计算偏航角
pre_x, pre_y = previous_positions[aircraft['id']]
yaw = calculate_yaw(pre_x, pre_y, x, y)
pitch = 0.0
roll = 0.0
# 更新先前位置
previous_positions[aircraft['id']] = (x, y)
# 打包数据
data = struct.pack('=BBBdddddd', 1, aircraft['id'], aircraft['type'], x, y, z, yaw, pitch, roll)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def send_missile_data(missile, t):
if missile['movement'] == 'straight':
center_x, center_y = missile['center']
x = center_x + 0
y = center_y + t * missile['speed']
z = missile['start_altitude'] # 初始高度可配置
state = 1 # 状态为发射中
elif missile['movement'] == 'circle':
center_x, center_y = missile['center']
x = center_x + missile['radius'] * math.cos(t * missile['speed'] / missile['radius'])
y = center_y + missile['radius'] * math.sin(t * missile['speed'] / missile['radius'])
z = missile['altitude'] # 高度保持可配置
state = 1 # 状态为发射中
elif missile['movement'] == 'straight_descend':
center_x, center_y = missile['center']
x = center_x + 0
y = center_y + t * missile['speed']
z = missile['start_altitude'] - missile['descend_rate'] * t /2 # 高度随时间下降
if t >= missile['explode_after']:
state = 2 # 爆炸状态
else:
state = 1 # 发射中
else:
return # 未知运动方式
# 仅向前下方飞的导弹(ID 3)可以爆炸
if missile['id'] != 3 :
state = 1
# 打包数据
if missile['valid']==1:
if state == 2:
missile['valid']=0
data = struct.pack('=BBBBddd', 2, missile['id'], 0, state, x, y, z)
# 发送数据
sock.sendto(data, (TARGET_IP, TARGET_PORT))
def main():
start_time = time.time()
def spawn_missiles():
missile_timers = []
while True:
t = time.time() - (start_time + config['delays']['missile_spawn'])
if t >= 0:
for missile in config['missiles']:
send_missile_data(missile, t)
time.sleep(0.1)
# 启动导弹生成计时器
missile_timer = Timer(config['delays']['missile_spawn'], spawn_missiles)
missile_timer.start()
while True:
t = time.time() - start_time
for aircraft in config['aircrafts']:
send_aircraft_data(aircraft, t)
time.sleep(0.1)
if __name__ == "__main__":
main()