NMEA position and heading
This page includes example Python scripts for forwarding the drone's position and heading to NMEA receivers, and for sending an external positioning system's fixes to the drone. Each script is shown below with its filename linked to a copy bundled with this documentation version. These links also work in the SDK's installed, offline documentation.
Download all examples and extract the archive, or save the individual example and the shared nmea_utils.py helper shown at the end of this page in the same directory. Use the SDK version that matches these docs. If you need the example dependencies, install "blueye.sdk[examples]==<version>", replacing <version> with that SDK version. This keeps the SDK pinned while adding the dependencies.
The scripts use NMEA 0183 sentences with an XOR checksum (*hh) and a CRLF terminator. Coordinates are decimal degrees in Python and unsigned degrees/minutes plus hemisphere letters in the sentences.
Forwarding the drone's position
The nmea_publisher.py example below subscribes to PositionEstimateTel as an observer and sends GPGLL sentences to a chart plotter or other UDP receiver. It carries the position estimate's validity flag as A (valid) or V (invalid). Non-finite or out-of-range coordinates are skipped.
The default destination is the surface-unit subnet's broadcast address, 192.168.1.255, on port 10111. Change it to your receiver's address and port. Do not broadcast these estimates to port 10110: that is the drone's position input, and feeding its output back into that input creates a feedback loop. If a chart plotter requires port 10110, send directly to the plotter's IP address.
"""Forward the drone's position estimate to an NMEA UDP receiver."""
import socket
import time
import blueye.protocol as bp
from blueye.sdk import Drone
from nmea_utils import nmea_gll
# Broadcast within the surface-unit subnet. Change this to your receiver's IP if needed.
UDP_IP = "192.168.1.255"
# Do not broadcast to 10110: the drone would consume its own position output as input.
UDP_PORT = 10111
def callback_position_estimate(
msg_type: str, msg: bp.PositionEstimateTel, udp_socket: socket.socket
):
"""Forward each position estimate, including its validity flag."""
position = msg.position_estimate
try:
sentence = nmea_gll(
position.global_position.latitude,
position.global_position.longitude,
position.is_valid,
)
except ValueError:
return # No usable coordinates in this sample.
udp_socket.sendto(sentence.encode("ascii"), (UDP_IP, UDP_PORT))
print(f"Sent: {sentence.rstrip()}")
def main():
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp_socket:
udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
with Drone(connect_as_observer=True) as drone:
drone.telemetry.add_msg_callback(
[bp.PositionEstimateTel], callback_position_estimate, udp_socket=udp_socket
)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
Forwarding heading to a serial port
The nmea_heading_publisher.py example below sends the latest yaw as HDT at up to 10 Hz. Set COM_PORT and BAUD_RATE for your receiver. It connects as an observer without changing the drone-wide attitude publishing rate. It waits for an attitude message, skips non-finite values, and stops sending if no attitude has arrived for one second. Heading is wrapped and rounded to 0.0–359.9 degrees.
examples/nmea_heading_publisher.py
"""Forward the drone's yaw as NMEA HDT to a serial port.
Install the example dependencies with: pip install 'blueye.sdk[examples]'
"""
import math
import time
import blueye.protocol as bp
import serial
from blueye.sdk import Drone
from nmea_utils import nmea_hdt
COM_PORT = "COM2" # Change to your serial port.
BAUD_RATE = 9600
heading = math.nan
last_attitude_time = None
def callback_attitude(msg_type: str, msg: bp.AttitudeTel):
"""Keep the latest yaw and its arrival time."""
global heading, last_attitude_time
heading = msg.attitude.yaw
last_attitude_time = time.monotonic()
def main():
global heading, last_attitude_time
heading, last_attitude_time = math.nan, None
try:
with serial.Serial(COM_PORT, BAUD_RATE, timeout=1) as port:
with Drone(connect_as_observer=True) as drone:
drone.telemetry.add_msg_callback([bp.AttitudeTel], callback_attitude)
# Read the existing telemetry stream; do not change the rate for other clients.
while True:
if last_attitude_time is not None and time.monotonic() - last_attitude_time < 1:
sentence = nmea_hdt(heading)
if sentence is not None:
port.write(sentence.encode("ascii"))
print(f"Sent: {sentence.rstrip()}")
time.sleep(0.1)
except serial.SerialException as exc:
print(f"Serial error: {exc}")
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
Feeding an external position to the drone
The drone listens on UDP port 10110 for its own position, such as fixes from a topside USBL system. This is separate from the pilot's position. Send the ROV's measured latitude and longitude, not the boat's GPS coordinates and not the drone's own position estimate.
Blunux 4.2.6 and newer pass GNGGA, GPGLL, PBLPLL and PSONLLD sentences to the position estimator, and Blunux 5.1 adds GPGGA and GNGLL. Other sentence types are ignored. The example sends GPGLL, which all of these versions accept.
Send one checksummed, CRLF-terminated sentence per UDP datagram to the drone's IP address, normally 192.168.1.101. Supply fresh fixes at 1 Hz or faster. The NMEA navigation source expires after about three seconds without a valid fix. Mark unusable fixes invalid rather than repeatedly sending the last valid position with a new timestamp.
Position reset
The first valid NMEA fix resets the drone's local position frame and odometer. Do not inject test coordinates during a dive or a running mission.
The nmea_position_input.py example below reads latitude longitude A|V lines from standard input and unicasts a GPGLL sentence for each line. It needs no SDK connection or control of the drone. Connect it to an adapter for your positioning system that emits fresh fixes without buffering, for example:
python -u positioning_adapter.py | python examples/nmea_position_input.py --ip 192.168.1.101
positioning_adapter.py is your own adapter, not a supplied example. If it already produces NMEA, send those sentences directly instead. The supplied script does not repeat old fixes if its input stops.
examples/nmea_position_input.py
"""Send fresh external ROV positions from stdin to the drone's NMEA UDP input.
Each line must contain: latitude longitude A|V
Coordinates are decimal degrees; A means a valid fix and V means invalid.
Supply fresh measurements at least once per second. This script sends each line
once and does not repeat old coordinates when the source stops.
Example usage with your own positioning adapter:
python positioning_adapter.py | python examples/nmea_position_input.py --ip 192.168.1.101
The first valid fix resets the drone's local position frame and odometer.
Do not feed the boat's GPS position or the drone's own telemetry back into this input.
"""
import argparse
import socket
import sys
from nmea_utils import nmea_gll
NMEA_INPUT_PORT = 10110
def forward_positions(lines, udp_socket: socket.socket, ip: str):
"""Convert one fresh fix per line into a unicast GPGLL datagram."""
for line_number, line in enumerate(lines, start=1):
try:
latitude, longitude, status = line.split()
if status not in ("A", "V"):
raise ValueError("Status must be A or V")
sentence = nmea_gll(float(latitude), float(longitude), status == "A")
except ValueError as exc:
print(f"Skipping line {line_number}: {exc}", file=sys.stderr)
continue
udp_socket.sendto(sentence.encode("ascii"), (ip, NMEA_INPUT_PORT))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ip", default="192.168.1.101", help="Drone IPv4 address")
args = parser.parse_args()
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp_socket:
forward_positions(sys.stdin, udp_socket, args.ip)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
Checking that the drone receives the fixes
Inspect the NMEA entry in PositionEstimateTel.position_estimate.navigation_sensors. The overall estimate's is_valid flag alone does not tell you whether the NMEA source is valid.
import time
import blueye.protocol as bp
from blueye.sdk import Drone
def show_nmea(msg_type, msg):
for sensor in msg.position_estimate.navigation_sensors:
if sensor.sensor_id == bp.NavigationSensorID.NAVIGATION_SENSOR_ID_NMEA:
print(sensor.is_valid, sensor.global_position)
with Drone(connect_as_observer=True) as drone:
drone.telemetry.add_msg_callback([bp.PositionEstimateTel], show_nmea)
time.sleep(10)
Older firmware may not report the per-source status. The resulting global estimate can also incorporate other sensors, so it need not equal each incoming fix exactly.
NMEA position input does not enable station keeping. See station keeping requirements and waypoint missions for supported control modes. Waypoint mission legs are limited to 300 m.
Shared sentence formatting
Both position scripts and the heading publisher use this helper:
"""NMEA sentence formatting shared by the examples in this directory."""
import datetime
import math
def nmea_sentence(body: str) -> str:
"""Add the XOR checksum and CRLF to a sentence body without delimiters."""
checksum = 0
for byte in body.encode("ascii"):
checksum ^= byte
return f"${body}*{checksum:02X}\r\n"
def _coordinate(value: float, degree_digits: int) -> str:
# Round before splitting so 59.99996 minutes carries into the next degree.
units = round(abs(value) * 60 * 10000)
degrees, minute_units = divmod(units, 60 * 10000)
minutes, fraction = divmod(minute_units, 10000)
return f"{degrees:0{degree_digits}d}{minutes:02d}.{fraction:04d}"
def nmea_gll(lat: float, lon: float, valid: bool) -> str:
"""Format decimal-degree coordinates as GPGLL with the current UTC time.
Raises:
ValueError: If a coordinate is non-finite or outside its geographic range.
"""
if not math.isfinite(lat) or not -90 <= lat <= 90:
raise ValueError("Latitude must be finite and between -90 and 90 degrees")
if not math.isfinite(lon) or not -180 <= lon <= 180:
raise ValueError("Longitude must be finite and between -180 and 180 degrees")
now = datetime.datetime.now(datetime.timezone.utc)
utc_time = now.strftime("%H%M%S") + f".{now.microsecond // 10000:02d}"
return nmea_sentence(
f"GPGLL,{_coordinate(lat, 2)},{'N' if lat >= 0 else 'S'},"
f"{_coordinate(lon, 3)},{'E' if lon >= 0 else 'W'},"
f"{utc_time},{'A' if valid else 'V'}"
)
def nmea_hdt(heading: float) -> str | None:
"""Format heading in degrees as HDT, or skip a non-finite heading."""
if not math.isfinite(heading):
return None
# Wrap again after rounding: 359.99 must not be sent as 360.0.
heading = round(heading % 360, 1) % 360
return nmea_sentence(f"IIHDT,{heading:.1f},T")