### Install Linux Dependencies Source: https://github.com/ardupilot/pymavlink/blob/master/README.md Installs necessary development headers for lxml on Debian-based systems. Also shows how to install optional numpy and pytest packages. ```bash sudo apt-get install libxml2-dev libxslt-dev ``` ```bash sudo apt-get install python3-numpy python3-pytest ``` -------------------------------- ### QGC WPL 110 Waypoint Example Source: https://github.com/ardupilot/pymavlink/blob/master/tests/rally-110.txt This is an example of a QGC WPL 110 waypoint file. Each line represents a waypoint with specific parameters. ```text 0 0 0 5100 8.000000 0.000000 0.000000 0.000000 40.071766 -105.230202 0.000000 0 ``` ```text 1 0 0 5100 8.000000 0.000000 0.000000 0.000000 40.071014 -105.230247 0.000000 0 ``` -------------------------------- ### Install Pymavlink with Pip Source: https://github.com/ardupilot/pymavlink/blob/master/README.md Installs the Pymavlink library and its dependencies using pip. This is the recommended method for users. ```bash sudo python3 -m pip install --upgrade lxml ``` ```bash sudo python3 -m pip install --upgrade pymavlink ``` -------------------------------- ### Install Pymavlink for Developers Source: https://github.com/ardupilot/pymavlink/blob/master/README.md Installs Pymavlink from a local source directory, allowing for development. Requires setting the MDEF environment variable to point to message definitions. ```bash MDEF=PATH_TO_message_definitions python3 -m pip install . -v ``` ```bash python3 -m pip install . ``` -------------------------------- ### Copy and Install MAVLink Implementation Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/README.md Copies the MAVLink protocol version to your project's node_modules folder and installs its dependencies. This prepares the MAVLink module for use in your Node.js application. ```bash cp -R javascript/implementations/mavlink_ardupilotmega_v1.0 /path/to/my/project/node_modules/ cd /path/to/my/project/node_modules/mavlink_ardupilotmega_v1.0 && npm install ``` -------------------------------- ### Install Node.js MAVLink Dependencies Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/README.md Installs the necessary Node.js dependencies for the MAVLink implementation. This is a prerequisite for building the Javascript modules. ```bash npm install ``` ```bash make ``` -------------------------------- ### Install MAVLink Swift Library with Swift Package Manager Source: https://github.com/ardupilot/pymavlink/blob/master/generator/swift/README.md Use Swift Package Manager to install the MAVLink Swift Library by adding the specified URL to your Package.swift file. ```swift import PackageDescription let package = Package( name: "GCS", dependencies: [.Package(url: "https://github.com/modnovolyk/MAVLinkSwift", majorVersion: 0)] ) ``` -------------------------------- ### Build Long.js Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/local_modules/long/README.md Install dependencies and build the UMD bundle for Long.js. ```bash npm install npm run build ``` -------------------------------- ### Generate MAVLink libraries using mavgen.py (CLI) Source: https://context7.com/ardupilot/pymavlink/llms.txt These commands demonstrate how to use `mavgen.py` from the command line to generate MAVLink libraries in various languages. It shows examples for generating C headers and Python dialect modules, specifying protocol version and output directories. ```Bash # Generate C headers for MAVLink 2.0 using the ardupilotmega dialect python3 -m pymavlink.tools.mavgen \ --lang C \ --wire-protocol 2.0 \ --output /tmp/mavlink_c \ /path/to/mavlink/message_definitions/v1.0/ardupilotmega.xml # Generate Python dialect module python3 -m pymavlink.tools.mavgen \ --lang Python \ --wire-protocol 2.0 \ --output /tmp/dialects \ ardupilotmega.xml # Generate JavaScript (stable) generator/gen_js.stable.sh # Supported --lang values: # C, C++11, Python, Java, JavaScript, JavaScript_Stable, # TypeScript, CS (C#), Swift, Lua, WLua, ObjC, Ada, Spin ``` -------------------------------- ### Log live MAVLink connection to file Source: https://context7.com/ardupilot/pymavlink/llms.txt This code sets up logging for a live MAVLink connection. It shows how to log messages in the `.tlog` format with timestamps or as raw bytes without timestamps. Messages received after setup are written to the specified file. ```Python from pymavlink import mavutil master = mavutil.mavlink_connection('udpin:0.0.0.0:14550') master.wait_heartbeat() # Start logging with timestamps (tlog format) master.setup_logfile('mission_2024.tlog') # Or log raw bytes without timestamps master.setup_logfile_raw('mission_raw.bin') # Messages received from here are written to both the live connection and the file while True: msg = master.recv_match(blocking=True, timeout=1) if msg is None: break if msg.get_type() == 'VFR_HUD': print(f"Alt={msg.alt:.1f}m Airspeed={msg.airspeed:.1f}m/s " f"Groundspeed={msg.groundspeed:.1f}m/s " f"Heading={msg.heading}° Throttle={msg.throttle}%") ``` -------------------------------- ### Run MAVLink JavaScript Unit Tests Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/README.md Execute the unit tests for the MAVLink JavaScript library using npm. Ensure you have mocha installed. ```bash npm test ``` -------------------------------- ### Custom Ardupilot Mode Mapping JSON Source: https://github.com/ardupilot/pymavlink/blob/master/README.md Example JSON structure for customizing Ardupilot mode names and numbers. This file should be named 'custom_mode_map.json' and placed in the '.pymavlink' directory in the user's home folder. ```json { "1": { "0": "MANUAL", "1": "CIRCLE", "2": "STABILIZE", "3": "TRAINING", "4": "ACRO", "5": "FBWA", "6": "FBWB", "7": "CRUISE", "8": "AUTOTUNE", "10": "AUTO", "11": "RTL", "12": "LOITER", "13": "TAKEOFF", "14": "AVOID_ADSB", "15": "GUIDED", "16": "INITIALISING", "17": "QSTABILIZE", "18": "QHOVER", "19": "QLOITER", "20": "QLAND", "21": "QRTL", "22": "QAUTOTUNE", "23": "QACRO", "24": "THERMAL" "25": "LOITERALTQLAND", "26": "AUTOLAND" } } ``` -------------------------------- ### Parse MAVLink Data in Swift Source: https://github.com/ardupilot/pymavlink/blob/master/generator/swift/README.md Example of parsing MAVLink data using the MAVLink Swift library. This snippet demonstrates how to initialize the MAVLink parser and process incoming data, printing the decoded message. ```swift import Foundation import MAVLink let data = Data(bytes: [0xFE, 0x1C, 0x00, 0x01, 0x01, 0x1E, 0x7E, 0x19, 0x01, 0x00, 0x64, 0x6A, 0x8E, 0xBD, 0xB2, 0x0D, 0xDF, 0x3C, 0x5B, 0xD7, 0x8E, 0x3F, 0xEA, 0xC2, 0xAA, 0xBC, 0x56, 0x96, 0x15, 0x3C, 0x51, 0x30, 0xDA, 0x3A, 0x12, 0xAB]) let mavLink = MAVLink() mavLink.parse(data: data, channel: 0) { message, _ in print(message.debugDescription) } ``` -------------------------------- ### Create a serial tunnel via MAVLink SERIAL_CONTROL Source: https://context7.com/ardupilot/pymavlink/llms.txt This example demonstrates how to use `MavlinkSerialPort` to create a serial tunnel. It exposes a Pixhawk's GPS port (UART 2) as a local TCP server, allowing tools like u-Center to connect. The code shows basic read/write operations on this virtual serial port. ```Python from pymavlink import mavutil # Expose GPS port (UART 2) of a Pixhawk as a local TCP server on port 2001 mav_serialport = mavutil.MavlinkSerialPort( portname='/dev/ttyACM0', baudrate=115200, devnum=2, # FC UART number (2 = GPS port on PX4) devbaud=115200, # GPS baud rate debug=0 ) # Read and write bytes as if it were a real serial port data = mav_serialport.read(128) mav_serialport.write(b'\xb5\x62\x06\x00...') # send UBX config frame mav_serialport.flushInput() ``` -------------------------------- ### Implement fixed-frequency event scheduler Source: https://context7.com/ardupilot/pymavlink/llms.txt This example uses the `periodic_event` utility class to run tasks at a controlled rate within a polling loop, avoiding the need for `time.sleep()`. It's useful for managing tasks like sending heartbeats or printing status updates at specific frequencies. ```Python from pymavlink import mavutil from pymavlink.mavutil import periodic_event master = mavutil.mavlink_connection('udpin:0.0.0.0:14550') master.wait_heartbeat() hb_event = periodic_event(1) # 1 Hz heartbeat status_event = periodic_event(4) # 4 Hz status print while True: master.recv_msg() # pump the receive buffer if hb_event.trigger(): master.mav.heartbeat_send( mavutil.mavlink.MAV_TYPE_GCS, mavutil.mavlink.MAV_AUTOPILOT_INVALID, 0, 0, 0 ) if status_event.trigger(): alt = master.field('GLOBAL_POSITION_INT', 'relative_alt', 0) * 0.001 mode = master.flightmode armed = master.motors_armed() print(f"mode={mode} alt={alt:.1f}m armed={armed} " f"loss={master.packet_loss():.1f}%") ``` -------------------------------- ### Unpack(fmt, a, p) Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/local_modules/jspack/README.md Unpacks values from an octet array according to a format string. It returns an array of unpacked values. If there are fewer octets than required, it returns undefined. The optional 'p' argument specifies the starting position in the array. ```APIDOC ## Unpack(fmt, a, p) ### Description Returns an array containing values unpacked from the octet array `a`, beginning at position `p`, according to the supplied format string `fmt`. ### Parameters - **fmt** (string) - The format string describing the structure. - **a** (Array) - The octet array (array of numbers 0-255) to unpack from. - **p** (number, optional) - The starting position in the octet array `a`. Defaults to 0. ### Returns - (Array) An array of unpacked values, or undefined if there are fewer octets than required by the format string. ``` -------------------------------- ### Open MAVLink Connections with mavlink_connection() Source: https://context7.com/ardupilot/pymavlink/llms.txt Demonstrates various ways to establish MAVLink connections using mavlink_connection(). Supports serial, UDP, TCP, WebSockets, and log files. Optional parameters allow for customization of connection behavior. ```python from pymavlink import mavutil # --- Serial port --- master = mavutil.mavlink_connection('/dev/ttyACM0', baud=115200) # --- UDP server (listen for incoming packets) --- master = mavutil.mavlink_connection('udpin:0.0.0.0:14550') # --- UDP client (send to a host) --- master = mavutil.mavlink_connection('udpout:192.168.1.100:14550') # --- TCP client --- master = mavutil.mavlink_connection('tcp:127.0.0.1:5760') # --- TCP server (listen for one client) --- master = mavutil.mavlink_connection('tcpin:0.0.0.0:5760') # --- WebSocket server --- master = mavutil.mavlink_connection('wsserver:0.0.0.0:5770') # --- WebSocket client (TLS) --- master = mavutil.mavlink_connection('wss:my-drone-host:443') # --- Read a DataFlash binary log --- log = mavutil.mavlink_connection('flight.bin') # --- Read a telemetry log --- log = mavutil.mavlink_connection('flight.tlog') # Common optional parameters master = mavutil.mavlink_connection( '/dev/ttyUSB0', baud=57600, source_system=255, # GCS system ID source_component=0, dialect='ardupilotmega', # pre-select dialect autoreconnect=True, # reconnect serial on drop force_connected=True, # don't raise if port missing at start zero_time_base=False, robust_parsing=True, ) ``` -------------------------------- ### Load and Push Parameters Source: https://context7.com/ardupilot/pymavlink/llms.txt Loads parameters from a file and pushes changed values to a live vehicle. Ensure the parameter file is correctly formatted. ```python pdict2 = MAVParmDict() pdict2.load('my_copter.param', mav=master, check=True) ``` -------------------------------- ### Generate CI-Friendly Output with Make Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/README.md Use the makefile to generate Jenkins-friendly output for continuous integration pipelines. ```bash make ci ``` -------------------------------- ### Constructor Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/local_modules/long/README.md Constructs a 64 bit two's-complement integer using its low and high 32 bit values. ```APIDOC ## new Long(low: number, high: number, unsigned?: boolean) ### Description Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. See the from* functions below for more convenient ways of constructing Longs. ### Parameters * **low** (number) - The low 32 bits as a signed integer. * **high** (number) - The high 32 bits as a signed integer. * **unsigned** (boolean) - Optional. Whether the integer should be treated as unsigned. ``` -------------------------------- ### Instantiate Long with High and Low Bits Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/local_modules/long/README.md Demonstrates how to create a Long instance by providing the high and low 32-bit values. This is useful when the 64-bit integer is already represented in this split format. ```javascript var Long = require("long"); var longVal = new Long(0xFFFFFFFF, 0x7FFFFFFF); console.log(longVal.toString()); ... ``` -------------------------------- ### Generate MAVLink Classes and Enums for Swift Source: https://github.com/ardupilot/pymavlink/blob/master/generator/swift/Tests/README.md Use this script to generate Swift files for MAVLink definitions from XML files. It also generates C headers for compatibility checks. Ensure generated Swift files are added to the project. ```bash ./ardugen.sh ``` -------------------------------- ### MAVParmDict for Parameter File Management Source: https://context7.com/ardupilot/pymavlink/llms.txt Use `MAVParmDict` to load, save, and diff parameter files in the ArduPilot text format. It can also interact with live MAVLink connections. ```python from pymavlink.mavparm import MAVParmDict from pymavlink import mavutil # --- Load parameters from file (no device connection needed) --- params = MAVParmDict() params.load('my_copter.param') print(params.get('ATC_RAT_RLL_P')) # e.g. 0.135 # --- Save all currently-known params to file --- master = mavutil.mavlink_connection('udpin:0.0.0.0:14550') master.wait_heartbeat() master.param_fetch_all() import time; time.sleep(3) pdict = MAVParmDict(master.params) pdict.save('backup.param', verbose=True) # Saved 487 parameters to backup.param # --- Diff two parameter files --- pdict.diff('other_copter.param') ``` -------------------------------- ### MAVParmDict — Save/load/diff parameter files Source: https://context7.com/ardupilot/pymavlink/llms.txt A `dict` subclass that handles parameter file I/O and live device push. Files use the ArduPilot `NAME VALUE` text format. ```APIDOC ## `MAVParmDict` — Save/load/diff parameter files A `dict` subclass that handles parameter file I/O and live device push. Files use the ArduPilot `NAME VALUE` text format. ### Methods * **load(filename: str)**: Loads parameters from a file. * **save(filename: str, verbose: bool = False)**: Saves all currently-known parameters to a file. * **diff(other_filename: str)**: Diffs the current parameters with those from another file. * **get(param_id: str, default: any = None)**: Retrieves a parameter value. ### Example ```python from pymavlink.mavparm import MAVParmDict from pymavlink import mavutil # --- Load parameters from file (no device connection needed) --- params = MAVParmDict() params.load('my_copter.param') print(params.get('ATC_RAT_RLL_P')) # e.g. 0.135 # --- Save all currently-known params to file --- master = mavutil.mavlink_connection('udpin:0.0.0.0:14550') master.wait_heartbeat() master.param_fetch_all() import time; time.sleep(3) pdict = MAVParmDict(master.params) pdict.save('backup.param', verbose=True) # Saved 487 parameters to backup.param # --- Diff two parameter files --- pdict.diff('other_copter.param') ``` ``` -------------------------------- ### Pack(fmt, values) Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/local_modules/jspack/README.md Packs values into a new octet array according to a format string. It returns the new octet array on success, or false if there are fewer values than specified. ```APIDOC ## Pack(fmt, values) ### Description Returns an octet array containing the packed `values` according to the format string `fmt`. ### Parameters - **fmt** (string) - The format string describing the structure. - **values** (Array) - The values to pack. ### Returns - (Array | false) An octet array containing the packed values, or `false` if there are fewer values supplied than specified. ``` -------------------------------- ### DFReader - Parse ArduPilot DataFlash Logs Source: https://context7.com/ardupilot/pymavlink/llms.txt Parses .bin and .log files produced by ArduPilot, allowing log analysis code to be identical to live-connection code. ```APIDOC ## DFReader — Parse ArduPilot DataFlash logs ### Description `DFReader_binary` and `DFReader_text` parse `.bin` and `.log` files produced by ArduPilot. The same `recv_match()` interface is used, making log analysis code identical to live-connection code. ### Usage ```python from pymavlink import mavutil # Open a DataFlash binary log (auto-detected by .bin extension) log = mavutil.mavlink_connection('2024-01-15.bin', zero_time_base=True) # Extract all GPS messages while True: msg = log.recv_match(type='GPS', blocking=False) if msg is None: break if msg.get_type() == 'BAD_DATA': continue print(f"t={msg._timestamp:.2f} " f"lat={msg.Lat:.6f} lon={msg.Lng:.6f} " f"alt={msg.Alt:.1f}m spd={msg.Spd:.1f}m/s") # Use mavmmaplog for fast multi-type filtering (memory-mapped, read-only) from pymavlink.mavutil import mavmmaplog mlog = mavmmaplog('2024-01-15.bin') # List flight modes in the log for mode, t0, t1 in mlog.flightmode_list(): duration = (t1 - t0) if t1 else 0 print(f" {mode:<20} {t0:.1f}s – {t1 or '?'}s ({duration:.1f}s)") # STABILIZE 0.0s – 42.3s (42.3s) # LOITER 42.3s – 180.1s (137.8s) # AUTO 180.1s – 542.0s (361.9s) # Read ATT (attitude) with a field condition mlog.rewind() while True: msg = mlog.recv_match(type='ATT', condition='ATT.Roll > 45 or ATT.Roll < -45', blocking=False) if msg is None: break print(f"Large roll at t={msg._timestamp:.2f}: {msg.Roll:.1f}°") ``` ``` -------------------------------- ### Parse ArduPilot DataFlash Logs Source: https://context7.com/ardupilot/pymavlink/llms.txt Parses ArduPilot DataFlash logs (.bin or .log files) using DFReader. The same interface as live connections can be used for log analysis. Supports memory-mapped reading for fast filtering. ```python from pymavlink import mavutil # Open a DataFlash binary log (auto-detected by .bin extension) log = mavutil.mavlink_connection('2024-01-15.bin', zero_time_base=True) ``` ```python # Extract all GPS messages while True: msg = log.recv_match(type='GPS', blocking=False) if msg is None: break if msg.get_type() == 'BAD_DATA': continue print(f"t={msg._timestamp:.2f} " f"lat={msg.Lat:.6f} lon={msg.Lng:.6f} " f"alt={msg.Alt:.1f}m spd={msg.Spd:.1f}m/s") ``` ```python # Use mavmmaplog for fast multi-type filtering (memory-mapped, read-only) from pymavlink.mavutil import mavmmaplog mlog = mavmmaplog('2024-01-15.bin') ``` ```python # List flight modes in the log for mode, t0, t1 in mlog.flightmode_list(): duration = (t1 - t0) if t1 else 0 print(f" {mode:<20} {t0:.1f}s – {t1 or '?'}s ({duration:.1f}s)") # STABILIZE 0.0s – 42.3s (42.3s) # LOITER 42.3s – 180.1s (137.8s) # AUTO 180.1s – 542.0s (361.9s) ``` ```python # Read ATT (attitude) with a field condition mlog.rewind() while True: msg = mlog.recv_match(type='ATT', condition='ATT.Roll > 45 or ATT.Roll < -45', blocking=False) if msg is None: break print(f"Large roll at t={msg._timestamp:.2f}: {msg.Roll:.1f}°") ``` -------------------------------- ### Fast Indexed Log Search with mavmmaplog Source: https://context7.com/ardupilot/pymavlink/llms.txt Utilizes mavmmaplog for efficient log searching by building an in-memory index. This allows direct jumping to message instances, significantly speeding up data extraction from large logs. ```python from pymavlink.mavutil import mavmmaplog, mavlink_connection def progress(pct): print(f"\rIndexing: {pct}%", end='', flush=True) log = mavmmaplog('big_flight.bin', progress_callback=progress) print() ``` -------------------------------- ### Manage Parameters with pymavlink Source: https://context7.com/ardupilot/pymavlink/llms.txt Fetch parameters using `param_fetch_all()` or `param_fetch_one()`, and set parameters with `param_set_send()`. Fetched parameters are cached in `master.params`. Use `master.param()` for convenient access to cached values. ```python from pymavlink import mavutil import time master = mavutil.mavlink_connection('udpin:0.0.0.0:14550') master.wait_heartbeat() # Fetch all parameters master.param_fetch_all() time.sleep(3) # allow PARAM_VALUE stream to fill up # Read cached parameters print("ARMING_CHECK =", master.param('ARMING_CHECK', default='N/A')) print("PILOT_SPEED_UP =", master.param('PILOT_SPEED_UP')) # Fetch a single parameter by name master.param_fetch_one('FS_THR_ENABLE') ack = master.recv_match(type='PARAM_VALUE', blocking=True, timeout=5) if ack and ack.param_id.strip('\x00') == 'FS_THR_ENABLE': print(f"FS_THR_ENABLE = {ack.param_value}") # e.g. 1.0 # Set a parameter master.param_set_send('PILOT_SPEED_UP', 250.0) ack = master.recv_match(type='PARAM_VALUE', blocking=True, timeout=5) if ack: print(f"Set {ack.param_id.strip(chr(0))} = {ack.param_value}") # Set PILOT_SPEED_UP = 250.0 # Convenient field accessor with default alt = master.field('GLOBAL_POSITION_INT', 'relative_alt', 0) * 0.001 print(f"Current altitude: {alt:.2f} m") ``` -------------------------------- ### mavmmaplog.recv_match() - Fast Indexed Log Search Source: https://context7.com/ardupilot/pymavlink/llms.txt Builds an in-memory offset index at open time and uses it to jump directly to the next instance of requested message types, making selective extraction from large logs very fast. ```APIDOC ## mavmmaplog.recv_match() — Fast indexed log search ### Description `mavmmaplog` builds an in-memory offset index at open time and uses it to jump directly to the next instance of requested message types, making selective extraction from large logs very fast. ### Usage ```python from pymavlink.mavutil import mavmmaplog, mavlink_connection def progress(pct): print(f"\rIndexing: {pct}%", end='', flush=True) log = mavmmaplog('big_flight.bin', progress_callback=progress) print() ``` ``` -------------------------------- ### Select MAVLink Dialect with set_dialect() Source: https://context7.com/ardupilot/pymavlink/llms.txt Load a MAVLink dialect module using `set_dialect()`. The dialect determines available message IDs and enumerations. Environment variables `MAVLINK20` or `MAVLINK09` control the wire protocol version. ```python import os from pymavlink import mavutil # Use MAVLink 2.0 with the ArduPilot dialect os.environ['MAVLINK20'] = '1' mavutil.set_dialect('ardupilotmega') # Use the minimal common dialect with MAVLink 1.0 mavutil.set_dialect('common') # Access dialect enumerations after loading from pymavlink import mavutil as mav print(mav.mavlink.MAV_TYPE_QUADROTOR) # 2 print(mav.mavlink.MAV_CMD_COMPONENT_ARM_DISARM) # 400 print(mav.mavlink.WIRE_PROTOCOL_VERSION) # '2.0' ``` -------------------------------- ### Utility Methods Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/local_modules/long/README.md Static utility methods for creating and checking Long objects. ```APIDOC ## Long.isLong(obj: *): boolean ### Description Tests if the specified object is a Long. ### Parameters * **obj** (*) - The object to test. ### Returns `boolean` - True if the object is a Long, false otherwise. ## Long.fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long ### Description Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. ### Parameters * **lowBits** (number) - The low 32 bits. * **highBits** (number) - The high 32 bits. * **unsigned** (boolean) - Optional. Whether the Long should be unsigned. ### Returns `Long` - The constructed Long object. ## Long.fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long ### Description Creates a Long from its byte representation. ### Parameters * **bytes** (number[]) - An array of bytes. * **unsigned** (boolean) - Optional. Whether the Long should be unsigned. * **le** (boolean) - Optional. True for little-endian, false for big-endian. ### Returns `Long` - The constructed Long object. ## Long.fromBytesLE(bytes: number[], unsigned?: boolean): Long ### Description Creates a Long from its little-endian byte representation. ### Parameters * **bytes** (number[]) - An array of bytes in little-endian order. * **unsigned** (boolean) - Optional. Whether the Long should be unsigned. ### Returns `Long` - The constructed Long object. ## Long.fromBytesBE(bytes: number[], unsigned?: boolean): Long ### Description Creates a Long from its big-endian byte representation. ### Parameters * **bytes** (number[]) - An array of bytes in big-endian order. * **unsigned** (boolean) - Optional. Whether the Long should be unsigned. ### Returns `Long` - The constructed Long object. ## Long.fromInt(value: number, unsigned?: boolean): Long ### Description Returns a Long representing the given 32-bit integer value. ### Parameters * **value** (number) - The 32-bit integer value. * **unsigned** (boolean) - Optional. Whether the Long should be unsigned. ### Returns `Long` - The constructed Long object. ## Long.fromNumber(value: number, unsigned?: boolean): Long ### Description Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. ### Parameters * **value** (number) - The number to convert. * **unsigned** (boolean) - Optional. Whether the Long should be unsigned. ### Returns `Long` - The constructed Long object. ## Long.fromString(str: string, unsigned?: boolean, radix?: number) ## Long.fromString(str: string, radix: number): Long ### Description Returns a Long representation of the given string, written using the specified radix. ### Parameters * **str** (string) - The string to convert. * **unsigned** (boolean) - Optional. Whether the Long should be unsigned. * **radix** (number) - Optional. The radix (base) of the string representation. ### Returns `Long` - The constructed Long object. ## Long.fromValue(val: *, unsigned?: boolean): Long ### Description Converts the specified value to a Long using the appropriate from* function for its type. ### Parameters * **val** (*) - The value to convert. Can be a number, string, or another Long. * **unsigned** (boolean) - Optional. Whether the Long should be unsigned. ### Returns `Long` - The constructed Long object. ``` -------------------------------- ### PackTo(fmt, a, p, values) Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/local_modules/jspack/README.md Packs values into a specified octet array at a given position. It returns the modified octet array on success, or false if there are fewer values than specified or insufficient space in the target array. ```APIDOC ## PackTo(fmt, a, p, values) ### Description Packs and stores the `values` into the supplied octet array `a`, beginning at position `p`, according to the format string `fmt`. ### Parameters - **fmt** (string) - The format string describing the structure. - **a** (Array) - The target octet array to pack into. - **p** (number) - The starting position in the octet array `a`. - **values** (Array) - The values to pack. ### Returns - (Array | false) The modified octet array `a` on success, or `false` if there are fewer values supplied than specified, or if there is insufficient space in `a`. ``` -------------------------------- ### mavlink_connection() — Open any MAVLink connection Source: https://context7.com/ardupilot/pymavlink/llms.txt The primary entry point for all connectivity. Automatically selects the right transport class based on the device string prefix. Supports various connection types including serial, UDP, TCP, WebSockets, and log files. ```APIDOC ## mavlink_connection() — Open any MAVLink connection ### Description The primary entry point for all connectivity. Automatically selects the right transport class (`mavserial`, `mavudp`, `mavtcp`, `mavmmaplog`, `DFReader`, etc.) based on the device string prefix. Supports serial ports, UDP server/client/broadcast, TCP client/server, WebSocket server and client (ws/wss), DataFlash binary (`.bin`/`.px4log`), DataFlash text (`.log`), MAVLink telemetry logs (`.tlog`/`.mavlink`), CSV logs, and child-process executables. ### Method `mavutil.mavlink_connection(device, ...)` ### Parameters - **device** (string) - The connection string specifying the transport and address. - **baud** (int, optional) - Baud rate for serial connections. - **source_system** (int, optional) - GCS system ID. - **source_component** (int, optional) - GCS component ID. - **dialect** (string, optional) - Pre-select MAVLink dialect. - **autoreconnect** (bool, optional) - Reconnect serial on drop. - **force_connected** (bool, optional) - Don't raise if port missing at start. - **zero_time_base** (bool, optional) - Whether to zero the time base. - **robust_parsing** (bool, optional) - Enable robust message parsing. ### Request Example ```python from pymavlink import mavutil # Serial port master = mavutil.mavlink_connection('/dev/ttyACM0', baud=115200) # UDP server master = mavutil.mavlink_connection('udpin:0.0.0.0:14550') # UDP client master = mavutil.mavlink_connection('udpout:192.168.1.100:14550') # TCP client master = mavutil.mavlink_connection('tcp:127.0.0.1:5760') # TCP server master = mavutil.mavlink_connection('tcpin:0.0.0.0:5760') # WebSocket server master = mavutil.mavlink_connection('wsserver:0.0.0.0:5770') # WebSocket client (TLS) master = mavutil.mavlink_connection('wss:my-drone-host:443') # Read a DataFlash binary log log = mavutil.mavlink_connection('flight.bin') # Read a telemetry log log = mavutil.mavlink_connection('flight.tlog') # Common optional parameters master = mavutil.mavlink_connection( '/dev/ttyUSB0', baud=57600, source_system=255, source_component=0, dialect='ardupilotmega', autoreconnect=True, force_connected=True, zero_time_base=False, robust_parsing=True, ) ``` ``` -------------------------------- ### CalcLength(fmt) Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/local_modules/jspack/README.md Calculates the number of octets required to store data described by a given format string. ```APIDOC ## CalcLength(fmt) ### Description Returns the number of octets required to store the given format string `fmt`. ### Parameters - **fmt** (string) - The format string. ### Returns - (number) The number of octets required. ``` -------------------------------- ### Send MAVLink Message in JavaScript Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/README.md Instantiate a MAVLink message, populate its fields, pack it into a buffer, and send it over a connection. Note that the MAVLink parser does not manage connection state, requiring manual population of certain fields. ```javascript mavlink.messages.request_data_stream = function(target_system, target_component, req_stream_id, req_message_rate, start_stop) //... ``` ```javascript request = new mavlink.messages.request_data_stream(1, 1, mavlink.MAV_DATA_STREAM_ALL, 1, 1); // Create a buffer consisting of the packed message, and send it across the wire. // You need to pass a MAVLink instance to pack. It will then take care of setting sequence number, system and component id. // Hack alert: the MAVLink connection could/should encapsulate this. p = new Buffer(request.pack(mavlinkParser)); connection.write(p); ``` -------------------------------- ### Fields Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/local_modules/long/README.md Access the internal representation of the 64-bit integer. ```APIDOC ## Long#low ### Description The low 32 bits of the 64-bit integer as a signed value. ### Type `number` ## Long#high ### Description The high 32 bits of the 64-bit integer as a signed value. ### Type `number` ## Long#unsigned ### Description A boolean indicating whether the Long is treated as unsigned. ### Type `boolean` ``` -------------------------------- ### Initialize MAVLink Parser in Node.js Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/README.md Initializes the MAVLink parser and sets up a network connection to receive MAVLink data. It binds the connection's 'data' event to the parser's parseBuffer method. ```javascript // requires Underscore.js and jspack // can use Winston for logging // see package.json for dependencies for the implementation var mavlink = require('mavlink_ardupilotmega_v1.0'), net = require('net'); // Instantiate the parser // logger: pass a Winston logger or null if not used // 1: source system id // 50: source component id mavlinkParser = new MAVLink(logger, 1, 50); // Create a connection -- can be anything that can receive/send binary connection = net.createConnection(5760, '127.0.0.1'); // When the connection issues a "got data" event, try and parse it connection.on('data', function(data) { mavlinkParser.parseBuffer(data); }); ``` -------------------------------- ### Constants Source: https://github.com/ardupilot/pymavlink/blob/master/generator/javascript/local_modules/long/README.md Predefined Long values for common scenarios. ```APIDOC ## Long.ZERO ### Description Represents signed zero. ### Type `Long` ## Long.ONE ### Description Represents signed one. ### Type `Long` ## Long.NEG_ONE ### Description Represents signed negative one. ### Type `Long` ## Long.UZERO ### Description Represents unsigned zero. ### Type `Long` ## Long.UONE ### Description Represents unsigned one. ### Type `Long` ## Long.MAX_VALUE ### Description Represents the maximum signed value. ### Type `Long` ## Long.MIN_VALUE ### Description Represents the minimum signed value. ### Type `Long` ## Long.MAX_UNSIGNED_VALUE ### Description Represents the maximum unsigned value. ### Type `Long` ``` -------------------------------- ### Auto-Detect Autopilot USB Serial Ports Source: https://context7.com/ardupilot/pymavlink/llms.txt Scans the system's serial ports and returns a list of SerialPort objects. Accepts a preferred-list of fnmatch patterns to prioritise known autopilot vendor strings. Use this to automatically find and connect to autopilots. ```python from pymavlink import mavutil # Find any port matching common autopilot signatures ports = mavutil.auto_detect_serial( preferred_list=['*FTDI*', '*Arduino_Mega_2560*', '*3D_Robotics*', '*USB_to_UART*', '*PX4*', '*FMU*'] ) for port in ports: print(port) # e.g. /dev/ttyUSB0 : FT232R USB UART : USB VID:PID=0403:6001 if ports: master = mavutil.mavlink_connection(ports[0].device, baud=115200) master.wait_heartbeat() print("Connected to", ports[0]) ``` -------------------------------- ### param_fetch_all() / param_fetch_one() / param_set_send() — Parameter management Source: https://context7.com/ardupilot/pymavlink/llms.txt Requests vehicle parameters over MAVLink. `param_fetch_all()` sends a PARAM_REQUEST_LIST; received PARAM_VALUE messages are cached in `master.params`. `param_set_send()` pushes a single value. ```APIDOC ## `param_fetch_all()` / `param_fetch_one()` / `param_set_send()` — Parameter management Requests vehicle parameters over MAVLink. `param_fetch_all()` sends a PARAM_REQUEST_LIST; received PARAM_VALUE messages are cached in `master.params`. `param_set_send()` pushes a single value. ### Methods * **param_fetch_all()**: Sends a PARAM_REQUEST_LIST to fetch all parameters. * **param_fetch_one(param_id: str)**: Sends a PARAM_REQUEST_יוחד to fetch a single parameter by its ID. * **param_set_send(param_id: str, value: float, type: int = mavutil.mavlink.MAV_PARAM_TYPE_REAL32)**: Sends a PARAM_SET message to set a parameter's value. * **param(param_id: str, default: any = None)**: Retrieves a cached parameter by its ID. Returns `default` if not found. * **field(message_name: str, field_name: str, default: any = None)**: Retrieves a field from the last received message of a given type. Returns `default` if the message or field is not found. ### Example ```python from pymavlink import mavutil import time master = mavutil.mavlink_connection('udpin:0.0.0.0:14550') master.wait_heartbeat() # Fetch all parameters master.param_fetch_all() time.sleep(3) # allow PARAM_VALUE stream to fill up # Read cached parameters print("ARMING_CHECK =", master.param('ARMING_CHECK', default='N/A')) print("PILOT_SPEED_UP =", master.param('PILOT_SPEED_UP')) # Fetch a single parameter by name master.param_fetch_one('FS_THR_ENABLE') ack = master.recv_match(type='PARAM_VALUE', blocking=True, timeout=5) if ack and ack.param_id.strip('\x00') == 'FS_THR_ENABLE': print(f"FS_THR_ENABLE = {ack.param_value}") # e.g. 1.0 # Set a parameter master.param_set_send('PILOT_SPEED_UP', 250.0) ack = master.recv_match(type='PARAM_VALUE', blocking=True, timeout=5) if ack: print(f"Set {ack.param_id.strip(chr(0))} = {ack.param_value}") # Set PILOT_SPEED_UP = 250.0 # Convenient field accessor with default alt = master.field('GLOBAL_POSITION_INT', 'relative_alt', 0) * 0.001 print(f"Current altitude: {alt:.2f} m") ``` ``` -------------------------------- ### Generate MAVLink dialect programmatically (Python API) Source: https://context7.com/ardupilot/pymavlink/llms.txt This Python code snippet shows how to programmatically generate and import a MAVLink dialect using `mavgen_python_dialect`. It demonstrates auto-generating the 'common' dialect for protocol version 2.0 and then importing and using a constant from the generated module. ```Python # Programmatic generation from pymavlink.generator.mavgen import mavgen_python_dialect from pymavlink.generator import mavparse # Auto-generate and import a dialect by name mavgen_python_dialect('common', mavparse.PROTOCOL_2_0) import importlib mod = importlib.import_module('pymavlink.dialects.v20.common') print(mod.WIRE_PROTOCOL_VERSION) # '2.0' print(mod.MAV_TYPE_QUADROTOR) # 2 ``` -------------------------------- ### Set Flight Mode with set_mode() Source: https://context7.com/ardupilot/pymavlink/llms.txt Change the vehicle's flight mode using `set_mode()` by specifying the mode name. The mode is resolved against the vehicle-type-specific mode map. Verify the change by inspecting the HEARTBEAT message or `master.flightmode`. ```python from pymavlink import mavutil master = mavutil.mavlink_connection('udpin:0.0.0.0:14550') master.wait_heartbeat() # ArduCopter modes master.set_mode('LOITER') master.set_mode('RTL') master.set_mode('GUIDED') master.set_mode('LAND') # ArduPlane modes master.set_mode('AUTO') master.set_mode('FBWA') # Verify the mode change via heartbeat hb = master.recv_match(type='HEARTBEAT', blocking=True, timeout=3) if hb: print("Current mode:", master.flightmode) # e.g. "GUIDED" # Inspect available modes for this vehicle mode_map = master.mode_mapping() # dict: name -> number print(sorted(mode_map.keys())) # ['ACRO', 'ALT_HOLD', 'AUTO', 'BRAKE', 'CIRCLE', 'FLIP', 'GUIDED', ...] ``` -------------------------------- ### Encode and Decode Raw MAVLink Messages Source: https://context7.com/ardupilot/pymavlink/llms.txt Demonstrates encoding and decoding MAVLink messages using dialect imports for offline processing. Signing can be enabled on the MAVLink codec object. ```python from pymavlink.dialects.v20 import ardupilotmega as mav2 from pymavlink.dialects.v10 import ardupilotmega as mav1 # Simple FIFO buffer for testing encode/decode offline class FIFO: def __init__(self): self.buf = [] def write(self, data): self.buf += data; return len(data) def read(self): return self.buf.pop(0) f = FIFO() mav = mav2.MAVLink(f) ``` ```python # Enable signing mav.signing.secret_key = bytearray(b'A' * 32) mav.signing.sign_outgoing = True mav.signing.timestamp = 0 ``` ```python # Encode a PARAM_SET message mav.param_set_send( target_system=1, target_component=1, param_id=b'WP_RADIUS', param_value=10.0, param_type=mav2.MAV_PARAM_TYPE_REAL32 ) ``` ```python # Alternatively produce a message object without sending msg = mav.param_set_encode(1, 1, b'ATC_RAT_RLL_P', 0.135, mav2.MAV_PARAM_TYPE_REAL32) msg.pack(mav) raw_bytes = msg.get_msgbuf() print("Encoded bytes:", list(raw_bytes)) ``` ```python # Decode it back decoded = mav.decode(raw_bytes) print(f"type={decoded.get_type()} " f"param_id={decoded.param_id} " f"param_value={decoded.param_value}") # type=PARAM_SET param_id=ATC_RAT_RLL_P param_value=0.135 print(f"fields: {decoded.get_fieldnames()}") ```