开始相机的持续光学变焦

MAV_DJI_CMD_START_OPT_ZOOM

参数:
参数 类型 说明
zoomDirection E_DjiCameraZoomDirection 变焦方向
zoomSpeed E_DjiCameraZoomSpeed 变焦速度

zoomDirection

名称 枚举值 说明
DJI_CAMERA_ZOOM_DIRECTION_OUT 0 缩小变焦(Zoom Out),降低变焦倍率
DJI_CAMERA_ZOOM_DIRECTION_IN 1 放大变焦(Zoom In),提高变焦倍率

zoomSpeed

名称 枚举值 说明
DJI_CAMERA_ZOOM_SPEED_SLOWEST 72 最慢变焦速度
DJI_CAMERA_ZOOM_SPEED_SLOW 73 慢速变焦
DJI_CAMERA_ZOOM_SPEED_MODERATELY_SLOW 74 略慢于正常速度
DJI_CAMERA_ZOOM_SPEED_NORMAL 75 正常变焦速度
DJI_CAMERA_ZOOM_SPEED_MODERATELY_FAST 76 略快于正常速度
DJI_CAMERA_ZOOM_SPEED_FAST 77 快速变焦
DJI_CAMERA_ZOOM_SPEED_FASTEST 78 最快变焦速度
示例
### 模板
import time
from pymavlink import mavutil
from enum import IntEnum

# MAV_CMD 执行结果映射
MAV_RESULT_NAMES = {
    mavutil.mavlink.MAV_RESULT_ACCEPTED: "ACCEPTED",
    mavutil.mavlink.MAV_RESULT_TEMPORARILY_REJECTED: "TEMPORARILY_REJECTED",
    mavutil.mavlink.MAV_RESULT_DENIED: "DENIED",
    mavutil.mavlink.MAV_RESULT_UNSUPPORTED: "UNSUPPORTED",
    mavutil.mavlink.MAV_RESULT_FAILED: "FAILED",
    mavutil.mavlink.MAV_RESULT_IN_PROGRESS: "IN_PROGRESS",
}


def recv_command_ack(timeout=5):
    """接收并显示 command_ack 消息

    Args:
        timeout: 超时时间(秒)

    Returns:
        ack 消息对象,None 表示超时
    """
    print(f"等待 command_ack 响应 (超时 {timeout}s)...")

    ack = master.recv_match(type='COMMAND_ACK', blocking=True, timeout=timeout)

    if ack is None:
        print("错误: 命令响应超时")
        return None

    # 获取命令名称
    cmd_name = getattr(ack, 'command_name', None)
    if not cmd_name:
        # 尝试通过枚举查找命令名称
        try:
            cmd_name = mavutil.mavlink.enums.get('MAV_CMD', {}).get(ack.command, {}).name
        except:
            cmd_name = str(ack.command)

    # 获取结果名称
    result_name = MAV_RESULT_NAMES.get(ack.result, f"UNKNOWN({ack.result})")

    print("=" * 50)
    print(f"命令: {cmd_name} ({ack.command})")
    print(f"结果: {result_name}")
    print(f"进度: {ack.progress * 100:.0f}%" if ack.progress > 0 else "")
    # print(f"参数2: {ack.result_param2}")
    print(f"系统ID: {ack.target_system}")
    print(f"组件ID: {ack.target_component}")
    print("=" * 50)

    return ack


class MavDjiCmd(IntEnum):
    MAV_CMD_NAV_LAND = 21
    MAV_DJI_CMD_TRIGGER_FFC=40
    MAV_DJI_CMD_START_RECORD_POINT_CLOUD=41
    MAV_DJI_CMD_STOP_RECORD_POINT_CLOUD=42
    MAV_DJI_CMD_RESTORE_FACTORY_SETTINGS=43
    MAV_DJI_CMD_APPLY_HIGH_POWER_SYNC=44
    MAV_DJI_CMD_APPLY_HIGH_POWER_SYNCV2=45
    MAV_DJI_CMD_START_CONFIRM_LANDING=46
    MAV_DJI_CMD_START_FORCE_LANDING=47
    MAV_DJI_CMD_EXECUTE_EMERGENCY_BRAKE_ACTION=48
    MAV_DJI_CMD_CANCEL_EMERGENCY_BRAKE_ACTION=49
    MAV_DJI_CMD_START_SLOW_ROTATE_MOTOR=50
    MAV_DJI_CMD_STOP_SLOW_ROTATE_MOTOR=51
    MAV_DJI_CMD_ARREST_FLYING=52
    MAV_DJI_CMD_CANCEL_ARREST_FLYING=53
    MAV_DJI_CMD_OUTPUT_HIGH_POWER=54
    TUNNEL_PROTOCOL_ID_INJECT_HMS_ERROR=32770

timestamp = int(time.time() * 1000)
millis = int(time.time() * 1000)

master = mavutil.mavlink_connection('udpin:0.0.0.0:14550')
print("waiting for heartbeat")
master.wait_heartbeat()
print("heartbeat received")
boot_time = time.time()

def send_command(command, param1=0, param2=0, param3=0, param4=0, param5=0, param6=0, param7=0, wait_ack=True, timeout=5):
    """发送 command_long 并可选接收 command_ack

    Args:
        command: 命令ID (如 MavDjiCmd.TRIGGER_FFC)
        param1~param7: 命令参数
        wait_ack: 是否等待并显示 ACK
        timeout: ACK 超时时间(秒)

    Returns:
        ack 消息对象,None 表示超时或未等待
    """
    print(f"发送命令: {command} ({int(command)})")
    master.mav.command_long_send(
        master.target_system,
        master.target_component,
        int(command),
        0,  # confirmation
        param1, param2, param3, param4, param5, param6, param7
    )

    if wait_ack:
        return recv_command_ack(timeout=timeout)
    return None


def ready():
    send_command(55,0,1)

ready()
示例使用说明

运行后,成功建立连接并发送指令

停止相机的持续光学变焦

MAV_DJI_CMD_STOP_OPT_ZOOM

示例
### 模板
import time
from pymavlink import mavutil
from enum import IntEnum

# MAV_CMD 执行结果映射
MAV_RESULT_NAMES = {
    mavutil.mavlink.MAV_RESULT_ACCEPTED: "ACCEPTED",
    mavutil.mavlink.MAV_RESULT_TEMPORARILY_REJECTED: "TEMPORARILY_REJECTED",
    mavutil.mavlink.MAV_RESULT_DENIED: "DENIED",
    mavutil.mavlink.MAV_RESULT_UNSUPPORTED: "UNSUPPORTED",
    mavutil.mavlink.MAV_RESULT_FAILED: "FAILED",
    mavutil.mavlink.MAV_RESULT_IN_PROGRESS: "IN_PROGRESS",
}


def recv_command_ack(timeout=5):
    """接收并显示 command_ack 消息

    Args:
        timeout: 超时时间(秒)

    Returns:
        ack 消息对象,None 表示超时
    """
    print(f"等待 command_ack 响应 (超时 {timeout}s)...")

    ack = master.recv_match(type='COMMAND_ACK', blocking=True, timeout=timeout)

    if ack is None:
        print("错误: 命令响应超时")
        return None

    # 获取命令名称
    cmd_name = getattr(ack, 'command_name', None)
    if not cmd_name:
        # 尝试通过枚举查找命令名称
        try:
            cmd_name = mavutil.mavlink.enums.get('MAV_CMD', {}).get(ack.command, {}).name
        except:
            cmd_name = str(ack.command)

    # 获取结果名称
    result_name = MAV_RESULT_NAMES.get(ack.result, f"UNKNOWN({ack.result})")

    print("=" * 50)
    print(f"命令: {cmd_name} ({ack.command})")
    print(f"结果: {result_name}")
    print(f"进度: {ack.progress * 100:.0f}%" if ack.progress > 0 else "")
    # print(f"参数2: {ack.result_param2}")
    print(f"系统ID: {ack.target_system}")
    print(f"组件ID: {ack.target_component}")
    print("=" * 50)

    return ack


class MavDjiCmd(IntEnum):
    MAV_CMD_NAV_LAND = 21
    MAV_DJI_CMD_TRIGGER_FFC=40
    MAV_DJI_CMD_START_RECORD_POINT_CLOUD=41
    MAV_DJI_CMD_STOP_RECORD_POINT_CLOUD=42
    MAV_DJI_CMD_RESTORE_FACTORY_SETTINGS=43
    MAV_DJI_CMD_APPLY_HIGH_POWER_SYNC=44
    MAV_DJI_CMD_APPLY_HIGH_POWER_SYNCV2=45
    MAV_DJI_CMD_START_CONFIRM_LANDING=46
    MAV_DJI_CMD_START_FORCE_LANDING=47
    MAV_DJI_CMD_EXECUTE_EMERGENCY_BRAKE_ACTION=48
    MAV_DJI_CMD_CANCEL_EMERGENCY_BRAKE_ACTION=49
    MAV_DJI_CMD_START_SLOW_ROTATE_MOTOR=50
    MAV_DJI_CMD_STOP_SLOW_ROTATE_MOTOR=51
    MAV_DJI_CMD_ARREST_FLYING=52
    MAV_DJI_CMD_CANCEL_ARREST_FLYING=53
    MAV_DJI_CMD_OUTPUT_HIGH_POWER=54
    TUNNEL_PROTOCOL_ID_INJECT_HMS_ERROR=32770

timestamp = int(time.time() * 1000)
millis = int(time.time() * 1000)

master = mavutil.mavlink_connection('udpin:0.0.0.0:14550')
print("waiting for heartbeat")
master.wait_heartbeat()
print("heartbeat received")
boot_time = time.time()

def send_command(command, param1=0, param2=0, param3=0, param4=0, param5=0, param6=0, param7=0, wait_ack=True, timeout=5):
    """发送 command_long 并可选接收 command_ack

    Args:
        command: 命令ID (如 MavDjiCmd.TRIGGER_FFC)
        param1~param7: 命令参数
        wait_ack: 是否等待并显示 ACK
        timeout: ACK 超时时间(秒)

    Returns:
        ack 消息对象,None 表示超时或未等待
    """
    print(f"发送命令: {command} ({int(command)})")
    master.mav.command_long_send(
        master.target_system,
        master.target_component,
        int(command),
        0,  # confirmation
        param1, param2, param3, param4, param5, param6, param7
    )

    if wait_ack:
        return recv_command_ack(timeout=timeout)
    return None


def ready():
    send_command(56,0,1)

ready()
示例使用说明

运行后,成功建立连接并发送指令

启用或禁用相机的点击变焦功能

TAP_ZOOM_ENABLED

设置

mavlink消息:

接收PARAM_SET
发送PARAM_VALUE

获取

mavlink消息

接收PARAM_REQUEST_READ
发送PARAM_VALUE

参数:
类型 枚举值 说明
bool 0 禁用 Tap-Zoom 功能
bool 1 启用 Tap-Zoom 功能
示例
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”选择读取参数

输入对应参数“TAP_ZOOM_ENABLED”

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

设置

运行后,成功建立连接

输入“1”选择设置参数

输入对应参数“TAP_ZOOM_ENABLED”

输入要设置的数值

选择参数类型“1”

成功返回设置值

点击变焦倍数

TAP_ZOOM_MULT

设置

mavlink消息:

接收PARAM_SET
发送PARAM_VALUE

获取

mavlink消息

接收PARAM_REQUEST_READ
发送PARAM_VALUE

参数:
参数 类型 取值范围 说明
tapZoomMultiplier uint8_t [1, 5] Tap-Zoom倍率系数。最终变焦倍率 = 当前Zoom Scale × 该系数;当值为1时,Tap-Zoom不改变变焦倍率
示例
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”选择读取参数

输入对应参数“TAP_ZOOM_MULT”

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

设置

运行后,成功建立连接

输入“1”选择设置参数

输入对应参数“TAP_ZOOM_MULT”

输入要设置的数值

选择参数类型“1”

成功返回设置值

获取相机焦距环的值范围

FOC_RING_RNG

设置

mavlink消息:

接收PARAM_EXT_SET
发送PARAM_EXT_ACK

获取

mavlink消息:

接收PARAM_EXT_REQUEST_READ
发送PARAM_EXT_VALUE

参数:
字段 类型 说明
size uint8_t 有效数组长度(最大16)
value union 可选取值集合(同一时刻仅使用其中一种类型)
minValue uint32_t 数值范围最小值(适用于数值型参数)
maxValue uint32_t 数值范围最大值(适用于数值型参数)

value(联合体说明)

该字段为联合体,同一时间仅有一个数组有效:

成员 类型 说明
photoStorageFormat E_DjiCameraManagerPhotoStorageFormat[16] 照片存储格式枚举列表
videoStorageFormat E_DjiCameraManagerVideoStorageFormat[16] 视频存储格式枚举列表
photoRatioFormat E_DjiCameraManagerPhotoRatio[16] 照片比例列表
streamSource E_DjiCameraManagerStreamSource[16] 视频流源列表
streamStorage E_DjiCameraManagerStreamStorage[16] 视频存储介质列表
nightSceneMode E_DjiCameraManagerNightSceneMode[16] 夜景模式列表
meteringMode E_DjiCameraManagerMeteringMode[16] 测光模式列表
示例
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”选择设置参数

输入对应参数“FOC_RING_RNG”

成功返回完整消息

相机焦距环

FOCUS_RING_VALUE

设置

mavlink消息:

接收PARAM_SET
发送PARAM_VALUE

获取

mavlink消息

接收PARAM_REQUEST_READ
发送PARAM_VALUE

参数:
字段 类型 说明
value uint16_t 对焦环数值
示例
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”选择读取参数

输入对应参数“FOCUS_RING_VALUE”

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

设置

运行后,成功建立连接

输入“1”选择设置参数

输入对应参数“FOCUS_RING_VALUE”

输入要设置的数值

选择参数类型“1”

成功返回设置值

mavlink id 260 CAMERA_SETTINGS

返回字段名称
类型
单位
描述
zoomLevel
float

变焦倍数

结果(使用QGC查看)

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