mavlink id 0 HEARTBEAT


返回字段名称

类型

单位

描述

custom_mode

uint32_t

PX4 custom_mode 编码格式

无人机飞行模式

type

uint8_t

MAV_TYPE 见下表

飞控类型

autopilot

uint8_t

MAV_AUTOPILOT 见下表

无人机型号

base_mode

uint8_t

MAV_MODE_FLAG 见下表

无人机基本状态位图

system_status

uint8_t

MAV_STATE 见下表

无人机状态

mavlink_version

uint8_t



mavlink协议版本


PX4 custom_mode

低16位保留,16~24位为主模式,24~32位为子模式

飞行模式



POSCTL

0x00030000

TAKEOFF

0x02040000

HOLD

0x03040000

MISSION

0x04040000

RTL

0x05040000

LAND

0x06040000

MAV_TYPE

MAVLINK 组件类型在 HEARTBEAT 消息中报告。飞控必须报告所安装飞行器的类型。

Value

Field Name

Description

0

MAV_TYPE_GENERIC

通用微型飞行器

1

MAV_TYPE_FIXED_WING

固定翼

2

MAV_TYPE_QUADROTOR

四旋翼

3

MAV_TYPE_COAXIAL

共轴直升机

4

MAV_TYPE_HELICOPTER

带尾桨的普通直升机

5

MAV_TYPE_ANTENNA_TRACKER

地面天线跟踪站

6

MAV_TYPE_GCS

操作员控制单元/地面站

MAV_AUTOPILOT

微型飞行器/自动驾驶仪类型。标志着各个模型的具体特征。

Value

Field Name

Description

0

MAV_AUTOPILOT_GENERIC

通用自动驾驶,支持所有内容。

1

MAV_AUTOPILOT_RESERVED

预留给未来使用。

12

MAV_AUTOPILOT_PX4

PX4 自动驾驶仪 - http://px4.io/

MAV_MODE_FLAG

无人机基础状态的位掩码。

Value

Field Name

Description

0b00000001

MAV_MODE_FLAG_CUSTOM_MODE_ENABLED

系统特定自定义模式已启用。使用该标志启用自定义模式时,其他所有标志都应忽略。

0b00000100

MAV_MODE_FLAG_AUTO_ENABLED

启用自动模式后,无人机自行定位目标位置。

0b00010000

MAV_MODE_FLAG_STABILIZE_ENABLED

飞控自动稳定姿态和位置,但需要接收控制输入来移动。

0b00100000

MAV_MODE_FLAG_HIL_ENABLED

硬件进入仿真环境。所有电机都被停用了,但内部软件完全正常工作。

0b01000000

MAV_MODE_FLAG_MANUAL_INPUT_ENABLED

遥控输入已启用。

0b10000000

MAV_MODE_FLAG_SAFETY_ARMED

MAV 安全设置为已启动。电机已启用。

MAV_STATE

Value

Field Name

Description

3

MAV_STATE_STANDBY

当无人机处于地面时发出此状态

4

MAV_STATE_ACTIVE

当无人机处于空中时发出此状态

mavlink id 1 SYS_STATUS

返回字段名称

类型

单位

描述

voltage_battery

uint16_t

mV

电池电压

current_battery

int16_t

mA

电池电量毫安

battery_remaining

int8_t

%

电池电量百分比

onboard_control_sensors_enabled_extended

uint32_t



避障状态 0 不正常 1 正常

结果(使用QGC查看)

获取移动设备App的基础信息

MOBILE_APP_INFO

mavlink消息:

接收PARAM_EXT_REQUEST_READ
发送PARAM_EXT_VALUE
参数:
T_DjiMobileAppInfo

字段 类型 说明
appLanguage E_DjiMobileAppLanguage APP 系统语言
appScreenType E_DjiMobileAppScreenType APP 屏幕尺寸类型
APP 系统语言类型

E_DjiMobileAppLanguage

名称 数值 说明
DJI_MOBILE_APP_LANGUAGE_UNKNOWN 255 未知语言
DJI_MOBILE_APP_LANGUAGE_ENGLISH 0 英语
DJI_MOBILE_APP_LANGUAGE_CHINESE 1 中文
DJI_MOBILE_APP_LANGUAGE_JAPANESE 2 日语
DJI_MOBILE_APP_LANGUAGE_FRENCH 3 法语
移动 APP 屏幕尺寸类型

E_DjiMobileAppScreenType

名称 数值 说明
DJI_MOBILE_APP_SCREEN_TYPE_UNKNOWN 255 未知屏幕类型
DJI_MOBILE_APP_SCREEN_TYPE_BIG_SCREEN 0 大屏设备(屏幕尺寸 ≥ 6 英寸)
DJI_MOBILE_APP_SCREEN_TYPE_LITTLE_SCREEN 1 小屏设备(屏幕尺寸 < 6 英寸)
示例
import time
import sys
import struct
import ctypes
from pymavlink import mavutil

def connect_to_vehicle():
    """建立 UDP 监听连接(默认监听所有接口的 14550 端口)"""
    connection_string = "udpin:0.0.0.0:14550"
    print(f"Listening for MAVLink on: {connection_string}")
    vehicle = mavutil.mavlink_connection(connection_string)
    print("Waiting for HEARTBEAT (timeout: 10s)...")
    try:
        vehicle.wait_heartbeat(timeout=10)
        print(f"✅ Heartbeat received from system {vehicle.target_system}, component {vehicle.target_component}")
        return vehicle
    except Exception as e:
        print(f"❌ Connection failed: {str(e)}")
        print("Ensure your vehicle is sending MAVLink messages to 14550 port")
        print("Example QGroundControl setup: Settings > General > MAVLink > Listening Port = 14550")
        sys.exit(1)

def format_param_id(param_id):
    """格式化16字节参数ID(符合MAVLink协议要求)"""
    if len(param_id) > 16:
        raise ValueError("param_id cannot exceed 16 characters")

    param_id_bytes = bytearray(16)
    for i in range(min(len(param_id), 16)):
        param_id_bytes[i] = ord(param_id[i])

    # 长度<16时添加NULL终止符
    if len(param_id) < 16:
        param_id_bytes[len(param_id)] = 0

    return param_id_bytes

# ============ 结构体打包函数 ============

def pack_uint8_xy(x, y):
    """打包 {uint8_t x; uint8_t y} 结构体 (2字节)"""
    return struct.pack('<BB', x, y)

def pack_float32_xy(x, y):
    """打包 {float32 x; float32 y} 结构体 (8字节)"""
    return struct.pack('<ff', x, y)

def pack_float32_lxlyrxry(LX, LY, RX, RY):
    """打包 {float32 LX; float32 LY; float32 RX; float32 RY;} 结构体 (16字节)"""
    return struct.pack('<ffff', LX, LY, RX, RY)

def pack_ering_mode(size, eringMode, minValue, maxValue):
    """打包 {uint8_t size; uint8_t eringMode[16]; uint32_t minValue; uint32_t maxValue;} 结构体 (25字节)

    Args:
        size: uint8_t, eringMode数组的有效长度
        eringMode: list of int (0-255), 16个uint8_t值
        minValue: uint32_t, 最小值
        maxValue: uint32_t, 最大值

    Returns:
        bytes: 打包后的二进制数据
    """
    # 确保eringMode是16字节
    eringMode_bytes = bytearray(16)
    for i in range(min(len(eringMode), 16)):
        eringMode_bytes[i] = eringMode[i] & 0xFF

    return struct.pack('<B16sII', size, eringMode_bytes, minValue, maxValue)

def format_param_value(param_value):
    """格式化128字节参数值(接受二进制输入)"""
    if isinstance(param_value, str):
        # 如果是十六进制字符串(如 "48656c6c6f"),先转换为字节
        if param_value.startswith('0x') or all(c in '0123456789abcdefABCDEF' for c in param_value.replace(' ', '')):
            hex_str = param_value.replace('0x', '').replace(' ', '')
            if len(hex_str) % 2 == 0:
                param_value = bytes.fromhex(hex_str)
            else:
                raise ValueError("Invalid hex string: must have even number of characters")
        else:
            # 普通字符串转字节
            param_value = param_value.encode('utf-8')

    if len(param_value) > 128:
        raise ValueError("param_value cannot exceed 128 bytes")

    param_value_bytes = bytearray(128)
    param_value_bytes[:len(param_value)] = param_value

    return param_value_bytes

def hex_dump(data, bytes_per_line=16):
    """格式化二进制数据为 hex + ASCII 展示(类 hexdump 风格)

    Returns:
        str: 格式化后的多行字符串
    """
    lines = []
    for i in range(0, len(data), bytes_per_line):
        chunk = data[i:i + bytes_per_line]
        hex_part = ' '.join(f'{b:02X}' for b in chunk)
        ascii_part = ''.join(chr(b) if 32 <= b < 127 else '.' for b in chunk)
        lines.append(f"  {i:04X}  {hex_part:<{bytes_per_line*3}}  {ascii_part}")
    return '\n'.join(lines)

def send_param_ext_request_read(vehicle, param_id=None, param_index=-1):
    """发送参数读取请求"""
    param_id_bytes = format_param_id(param_id) if param_id else bytearray(16)

    vehicle.mav.param_ext_request_read_send(
        vehicle.target_system,
        vehicle.target_component,
        param_id_bytes,
        param_index
    )

    target = f"index {param_index}" if param_index >= 0 else f"ID '{param_id}'"
    print(f"📤 Sent PARAM_EXT_REQUEST_READ for {target}")

def send_param_ext_request_list(vehicle):
    """发送请求所有参数列表"""
    vehicle.mav.param_ext_request_list_send(
        vehicle.target_system,
        vehicle.target_component
    )
    print(f"📤 Sent PARAM_EXT_REQUEST_LIST to system {vehicle.target_system}, component {vehicle.target_component}")

def send_param_ext_set(vehicle, param_id, param_value, param_type):
    """发送参数设置请求"""
    vehicle.mav.param_ext_set_send(
        vehicle.target_system,
        vehicle.target_component,
        format_param_id(param_id),
        format_param_value(param_value),
        param_type
    )
    print(f"📤 Sent PARAM_EXT_SET for '{param_id}' = '{param_value}' (type: {param_type})")

def receive_param_ext_value(vehicle, timeout=5.0):
    """接收参数值响应"""
    print(f"⏳ Waiting for PARAM_EXT_VALUE ({timeout}s timeout)...")
    msg = vehicle.recv_match(type='PARAM_EXT_VALUE', blocking=True, timeout=timeout)

    if not msg:
        print("❌ Timeout: No PARAM_EXT_VALUE received")
        return None

    # 解析参数ID
    param_id = msg.param_id

    # 解析参数值(直接获取128字节原始数据)
    param_value_raw = msg.param_value
    # byte_pointer = (ctypes.c_ubyte * 128).from_buffer_copy(msg.param_value)
    if isinstance(param_value_raw, (bytes, bytearray)):
        param_value_bytes = bytes(param_value_raw)
    # param_value_bytes = bytes(byte_pointer)
    elif isinstance(param_value_raw, str):
        # 替换无法编码的字符(如 \ufffd)为 0x00,还原为128字节
        param_value_bytes = param_value_raw.encode('latin1', errors='replace')
    else:
        param_value_bytes = bytes(param_value_raw)

    # 参数类型映射
    type_names = {
        0: "INT8", 1: "UINT8", 2: "INT16", 3: "UINT16", 4: "INT32",
        5: "UINT32", 6: "INT64", 7: "UINT64", 8: "FLOAT", 9: "FLOAT",
        10: "CHAR", 11: "CHAR", 12: "UINT8_ENUM", 13: "STRING"
    }
    param_type = type_names.get(msg.param_type, f"UNKNOWN({msg.param_type})")

    print("\n📥 Received PARAM_EXT_VALUE:")
    print(f"  🆔 ID: {param_id}")
    print(f"  🧾 Type: {param_type}  |  Data: {len(param_value_bytes)} bytes")
    print(f"  📊 Index/Total: {msg.param_index}/{msg.param_count}")
    print(hex_dump(param_value_bytes))

    return {
        'id': param_id,
        'value': param_value_bytes,
        'type': param_type,
        'index': msg.param_index,
        'count': msg.param_count
    }


def receive_all_param_ext_values(vehicle, timeout=10.0):
    """接收所有参数值,直到收到 param_count 条消息后退出循环"""
    received_params = []
    expected_count = None
    print(f"⏳ Waiting for all PARAM_EXT_VALUE messages...")

    while True:
        msg = vehicle.recv_match(type='PARAM_EXT_VALUE', blocking=True, timeout=timeout)

        if not msg:
            print(f"❌ Timeout: Received {len(received_params)} parameters (expected {expected_count if expected_count else 'unknown'})")
            break

        param_id = msg.param_id
        param_value_raw = msg.param_value

        # 直接获取128字节原始数据
        if isinstance(param_value_raw, (bytes, bytearray)):
            param_value_bytes = bytes(param_value_raw)
        elif isinstance(param_value_raw, str):
            # 替换无法编码的字符(如 \ufffd)为 0x00
            param_value_bytes = param_value_raw.encode('latin1', errors='replace')
        else:
            param_value_bytes = bytes(param_value_raw)

        # 参数类型映射
        type_names = {
            0: "INT8", 1: "UINT8", 2: "INT16", 3: "UINT16", 4: "INT32",
            5: "UINT32", 6: "INT64", 7: "UINT64", 8: "FLOAT", 9: "DOUBLE",
            10: "CHAR", 11: "BOOL", 12: "UINT8_ENUM", 13: "STRING"
        }
        param_type = type_names.get(msg.param_type, f"UNKNOWN({msg.param_type})")

        # 首次收到消息时记录总参数数量
        if expected_count is None:
            expected_count = msg.param_count
            print(f"📊 Total parameters to receive: {expected_count}")

        print(f"  [{msg.param_index}/{expected_count}] {param_id}  [{param_type}][{len(param_value_bytes)}B]")
        print(hex_dump(param_value_bytes))

        received_params.append({
            'id': param_id,
            'value': param_value_bytes,
            'type': param_type,
            'index': msg.param_index,
            'count': msg.param_count
        })

        # 当已接收数量达到预期总数时退出循环
        if len(received_params) >= expected_count:
            print(f"\n✅ Successfully received all {expected_count} parameters")
            break

    return received_params

def receive_param_ext_ack(vehicle, timeout=5.0):
    """接收参数设置确认"""
    print(f"⏳ Waiting for PARAM_EXT_ACK ({timeout}s timeout)...")
    msg = vehicle.recv_match(type='PARAM_EXT_ACK', blocking=True, timeout=timeout)

    if not msg:
        print("❌ Timeout: No PARAM_EXT_ACK received")
        return None

    param_id = msg.param_id
    param_value = msg.param_value

    # 结果代码映射
    result_codes = {
        0: "✅ PARAM_ACK_ACCEPTED",
        1: "⚠️ PARAM_ACK_VALUE_UNSUPPORTED",
        2: "❌ PARAM_ACK_FAILED",
        3: "🔄 PARAM_ACK_IN_PROGRESS"
    }
    result = result_codes.get(msg.param_result, f"❓ UNKNOWN({msg.param_result})")

    print("\n📥 Received PARAM_EXT_ACK:")
    print(f"  🆔 ID: {param_id}")
    print(f"  🔢 Value: {param_value}")
    print(f"  📌 Result: {result}")

    return {
        'id': param_id,
        'value': param_value,
        'result': result,
        'result_code': msg.param_result
    }

def main():
    print("🚀 Starting MAVLink PARAM_EXT Tool (UDP Listening Mode)")
    print("-----------------------------------------------------")
    print("This script listens for MAVLink on ALL interfaces:14550")
    print("Ensure your vehicle is configured to send to this port")
    print("-----------------------------------------------------\n")

    vehicle = connect_to_vehicle()

    # 操作选择
    print("\nAvailable operations:")
    print("1. Read parameter value (by ID or index)")
    print("2. Set parameter value (raw/hex/string)")
    print("3. Request all parameters (PARAM_EXT_REQUEST_LIST)")
    print("4. Set struct: uint8_xy {x, y}")
    print("5. Set struct: float32_xy {x, y}")
    print("6. Set struct: float32_lxlyrxry {LX, LY, RX, RY}")
    print("7. Set struct: ering_mode {size, eringMode[16], minValue, maxValue}")
    choice = input("\nSelect operation [1-7]: ").strip()

    if choice == '1':
        # mode = input("Read by [id/index]: ").lower()
        mode = 'id'
        if mode == 'id':
            param_id = input("Enter parameter ID: ").strip()
            send_param_ext_request_read(vehicle, param_id=param_id)
            receive_param_ext_value(vehicle)
        elif mode == 'index':
            param_index = int(input("Enter parameter index: "))
            send_param_ext_request_read(vehicle, param_index=param_index)
            receive_param_ext_value(vehicle)
        else:
            print("Invalid mode. Use 'id' or 'index'")

    elif choice == '2':
        param_id = input("Enter parameter ID to set: ").strip()

        print("\nEnter parameter value (supports):")
        print("  - Plain string (e.g., hello)")
        print("  - Hex string (e.g., 48656c6c6f or 0x48656c6c6f)")
        print("  - Raw bytes (e.g., b'\\x48\\x65\\x6c\\x6c\\x6f')")
        param_value_input = input("Enter value: ").strip()

        # 解析输入值
        if param_value_input.startswith("b'") or param_value_input.startswith('b"'):
            # Python字节字面量格式
            param_value = eval(param_value_input)
        elif param_value_input.startswith('0x') or all(c in '0123456789abcdefABCDEF ' for c in param_value_input):
            # 十六进制格式
            hex_str = param_value_input.replace('0x', '').replace(' ', '')
            try:
                param_value = bytes.fromhex(hex_str)
            except ValueError:
                param_value = param_value_input.encode('utf-8')
        else:
            # 默认作为字符串处理
            param_value = param_value_input.encode('utf-8')

        print("\nParameter types:")
        print("  8 = FLOAT (most common)")
        print("  13 = STRING")
        print("  10 = CHAR (raw bytes)")
        print("  Other types require specific binary formats")
        param_type = int(input("Enter type number [8]: ") or 8)

        send_param_ext_set(vehicle, param_id, param_value, param_type)
        receive_param_ext_ack(vehicle)

    elif choice == '4':
        """设置 uint8_xy 结构体 {uint8_t x; uint8_t y}"""
        param_id = input("Enter parameter ID: ").strip()
        x = int(input("Enter x (0-255): "))
        y = int(input("Enter y (0-255): "))
        param_value = pack_uint8_xy(x, y)
        print(f"  Packed: {param_value.hex()} ({len(param_value)} bytes)")
        send_param_ext_set(vehicle, param_id, param_value, 10)  # CHAR type
        receive_param_ext_ack(vehicle)

    elif choice == '5':
        """设置 float32_xy 结构体 {float32 x; float32 y}"""
        param_id = input("Enter parameter ID: ").strip()
        x = float(input("Enter x: "))
        y = float(input("Enter y: "))
        param_value = pack_float32_xy(x, y)
        print(f"  Packed: {param_value.hex()} ({len(param_value)} bytes)")
        send_param_ext_set(vehicle, param_id, param_value, 10)  # CHAR type
        receive_param_ext_ack(vehicle)

    elif choice == '6':
        """设置 float32_lxlyrxry 结构体 {float32 LX; float32 LY; float32 RX; float32 RY;}"""
        param_id = input("Enter parameter ID: ").strip()
        LX = float(input("Enter LX: "))
        LY = float(input("Enter LY: "))
        RX = float(input("Enter RX: "))
        RY = float(input("Enter RY: "))
        param_value = pack_float32_lxlyrxry(LX, LY, RX, RY)
        print(f"  Packed: {param_value.hex()} ({len(param_value)} bytes)")
        send_param_ext_set(vehicle, param_id, param_value, 10)  # CHAR type
        receive_param_ext_ack(vehicle)

    elif choice == '7':
        """设置 ering_mode 结构体 {uint8_t size; uint8_t eringMode[16]; uint32_t minValue; uint32_t maxValue;}"""
        param_id = input("Enter parameter ID: ").strip()
        size = int(input("Enter size (0-16): "))
        eringMode = []
        print("Enter 16 eringMode values (0-255), one per line:")
        for i in range(16):
            val = int(input(f"  eringMode[{i}]: "))
            eringMode.append(val)
        minValue = int(input("Enter minValue: "))
        maxValue = int(input("Enter maxValue: "))
        param_value = pack_ering_mode(size, eringMode, minValue, maxValue)
        print(f"  Packed: {param_value.hex()} ({len(param_value)} bytes)")
        send_param_ext_set(vehicle, param_id, param_value, 10)  # CHAR type
        receive_param_ext_ack(vehicle)

    elif choice == '3':
        print("\n📤 Requesting all parameters...")
        send_param_ext_request_list(vehicle)
        all_params = receive_all_param_ext_values(vehicle)
        print(f"\n📋 Total parameters received: {len(all_params)}")

    else:
        print("Invalid choice. Select 1, 2, or 3.")


if __name__ == "__main__":
    main()
示例使用说明

运行后,成功建立连接

输入“1”选择设置参数

输入对应参数“MOBILE_APP_INFO”

成功返回完整消息

获取移动 App 图传设置中的“增强传输”状态

ENH_TRANS_STATE

mavlink消息:

接收PARAM_REQUEST_READ
发送PARAM_VALUE

参数:E_DjiEnhancedTransmissionState

名称 枚举值 说明
DJI_ENHANCEED_TRANSMISSION_STATE_DISABLED 0 Mobile app 图传设置:关闭增强图传(Enhanced transmission disabled)
DJI_ENHANCEED_TRANSMISSION_STATE_ENABLED 3 Mobile app 图传设置:开启增强图传(Enhanced transmission enabled)
示例
import time
import sys
from pymavlink import mavutil

def connect_to_vehicle():
    """建立 UDP 监听连接(默认监听所有接口的 14550 端口)"""
    connection_string = "udpin:0.0.0.0:14550"
    print(f"Listening for MAVLink on: {connection_string}")
    vehicle = mavutil.mavlink_connection(connection_string)
    print("Waiting for HEARTBEAT (timeout: 10s)...")
    try:
        vehicle.wait_heartbeat(timeout=10)
        print(f"✅ Heartbeat received from system {vehicle.target_system}, component {vehicle.target_component}")
        return vehicle
    except Exception as e:
        print(f"❌ Connection failed: {str(e)}")
        print("Ensure your vehicle is sending MAVLink messages to 14550 port")
        print("Example QGroundControl setup: Settings > General > MAVLink > Listening Port = 14550")
        sys.exit(1)

def format_param_id(param_id):
    """格式化16字节参数ID(符合MAVLink协议要求)"""
    if len(param_id) > 16:
        raise ValueError("param_id cannot exceed 16 characters")

    param_id_bytes = bytearray(16)
    for i in range(min(len(param_id), 16)):
        param_id_bytes[i] = ord(param_id[i])

    # 长度<16时添加NULL终止符
    if len(param_id) < 16:
        param_id_bytes[len(param_id)] = 0

    return param_id_bytes

def send_param_set(vehicle, param_id, param_value, param_type):
    """发送参数设置请求"""
    vehicle.mav.param_set_send(
        vehicle.target_system,
        vehicle.target_component,
        format_param_id(param_id),
        param_value,
        param_type
    )
    print(f"📤 Sent PARAM_SET for '{param_id}' = {param_value} (type: {param_type})")

def send_param_request_read(vehicle, param_id=None, param_index=-1):
    """发送参数读取请求"""
    param_id_bytes = format_param_id(param_id) if param_id else bytearray(16)

    vehicle.mav.param_request_read_send(
        vehicle.target_system,
        vehicle.target_component,
        param_id_bytes,
        param_index
    )

    target = f"index {param_index}" if param_index >= 0 else f"ID '{param_id}'"
    print(f"📤 Sent PARAM_REQUEST_READ for {target}")

def send_param_request_list(vehicle):
    """发送请求所有参数列表"""
    vehicle.mav.param_request_list_send(
        vehicle.target_system,
        vehicle.target_component
    )
    print(f"📤 Sent PARAM_REQUEST_LIST to system {vehicle.target_system}, component {vehicle.target_component}")

def receive_param_value(vehicle, timeout=5.0):
    """接收参数值响应"""
    print(f"⏳ Waiting for PARAM_VALUE ({timeout}s timeout)...")
    msg = vehicle.recv_match(type='PARAM_VALUE', blocking=True, timeout=timeout)

    if not msg:
        print("❌ Timeout: No PARAM_VALUE received")
        return None

    # 解析参数ID
    param_id = msg.param_id

    # 解析参数值
    param_value = msg.param_value

    # 参数类型映射
    type_names = {
        0: "INT8", 1: "UINT8", 2: "INT16", 3: "UINT16", 4: "INT32",
        5: "UINT32", 6: "INT64", 7: "UINT64", 8: "FLOAT", 9: "DOUBLE"
    }
    param_type = type_names.get(msg.param_type, f"UNKNOWN({msg.param_type})")

    print("\n📥 Received PARAM_VALUE:")
    print(f"  🆔 ID: {param_id}")
    print(f"  🔢 Value: {param_value}")
    print(f"  🧾 Type: {param_type}")
    print(f"  📊 Index/Total: {msg.param_index}/{msg.param_count}")

    return {
        'id': param_id,
        'value': param_value,
        'type': param_type,
        'index': msg.param_index,
        'count': msg.param_count
    }

def receive_all_param_values(vehicle, timeout=10.0):
    """接收所有参数值,直到收到 param_count 条消息后退出循环"""
    received_params = []
    expected_count = None
    print(f"⏳ Waiting for all PARAM_VALUE messages...")

    while True:
        msg = vehicle.recv_match(type='PARAM_VALUE', blocking=True, timeout=timeout)

        if not msg:
            print(f"❌ Timeout: Received {len(received_params)} parameters (expected {expected_count if expected_count else 'unknown'})")
            break

        param_id = msg.param_id
        param_value = msg.param_value

        # 参数类型映射
        type_names = {
            0: "INT8", 1: "UINT8", 2: "INT16", 3: "UINT16", 4: "INT32",
            5: "UINT32", 6: "INT64", 7: "UINT64", 8: "FLOAT", 9: "DOUBLE"
        }
        param_type = type_names.get(msg.param_type, f"UNKNOWN({msg.param_type})")

        # 首次收到消息时记录总参数数量
        if expected_count is None:
            expected_count = msg.param_count
            print(f"📊 Total parameters to receive: {expected_count}")

        print(f"  [{msg.param_index}/{expected_count}] {param_id} = {param_value} ({param_type})")

        received_params.append({
            'id': param_id,
            'value': param_value,
            'type': param_type,
            'index': msg.param_index,
            'count': msg.param_count
        })

        # 当已接收数量达到预期总数时退出循环
        if len(received_params) >= expected_count:
            print(f"\n✅ Successfully received all {expected_count} parameters")
            break

    return received_params

def main():
    print("🚀 Starting MAVLink PARAM_SET Tool (UDP Listening Mode)")
    print("-----------------------------------------------------")
    print("This script listens for MAVLink on ALL interfaces:14550")
    print("Ensure your vehicle is configured to send to this port")
    print("-----------------------------------------------------\n")

    vehicle = connect_to_vehicle()

    # 操作选择
    print("\nAvailable operations:")
    print("1. Set parameter value")
    print("2. Read parameter value (by ID or index)")
    print("3. Request all parameters (PARAM_REQUEST_LIST)")
    choice = input("\nSelect operation [1-3]: ").strip()

    if choice == '1':
        param_id = input("Enter parameter ID to set: ").strip()
        param_value = float(input("Enter new value: ").strip())

        print("\nParameter types:")
        print("  8 = FLOAT (most common)")
        print("  9 = DOUBLE")
        print("  4 = INT32")
        print("  1 = UINT8")
        param_type = int(input("Enter type number [8]: ").strip() or 8)

        send_param_set(vehicle, param_id, param_value, param_type)
        receive_param_value(vehicle)

    elif choice == '2':
        # mode = input("Read by [id/index]: ").lower()
        mode = 'id'
        if mode == 'id':
            param_id = input("Enter parameter ID: ").strip()
            send_param_request_read(vehicle, param_id=param_id)
            receive_param_value(vehicle)
        elif mode == 'index':
            param_index = int(input("Enter parameter index: "))
            send_param_request_read(vehicle, param_index=param_index)
            receive_param_value(vehicle)
        else:
            print("Invalid mode. Use 'id' or 'index'")

    elif choice == '3':
        print("\n📤 Requesting all parameters...")
        send_param_request_list(vehicle)
        all_params = receive_all_param_values(vehicle)
        print(f"\n📋 Total parameters received: {len(all_params)}")

    else:
        print("Invalid choice. Select 1, 2, or 3.")


if __name__ == "__main__":
    main()
示例使用说明

运行后,成功建立连接

输入“2”选择读取参数

输入对应参数“ENH_TRANS_STATE”

成功返回该参数对应的数值

作者:孙渝泓  创建时间:2026-06-15 16:12
最后编辑:孙渝泓  更新时间:2026-06-18 18:17