# Reading Mavlink packets from pymavlink (only heartbeat)

**URL:** <https://discuss.bluerobotics.com/t/reading-mavlink-packets-from-pymavlink-only-heartbeat/11403>\
**Category:** ArduSub\
**Tags:** pymavlink\
**Created:** [January 23, 2022, 7:02pm UTC](https://discuss.bluerobotics.com/t/reading-mavlink-packets-from-pymavlink-only-heartbeat/11403 "2022-01-23T19:02:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Efe](https://avatars.discourse-cdn.com/v4/letter/e/5fc32e/32.png) [@Efe](https://discuss.bluerobotics.com/u/Efe)\
**Post date:** [January 23, 2022, 7:02pm UTC](https://discuss.bluerobotics.com/t/reading-mavlink-packets-from-pymavlink-only-heartbeat/11403/1 "2022-01-23T19:02:29Z")

</div>

We are trying to make our own gui for a competition. When we connect pixhawk via USB port and try to get telemetry values with pymavlink, the pixhawk only sends heartbeat messages and the occasional TIMESYNC message. We are using the exact same code as the one on the ardusub documentation. We can display the values on QGroundControl but pymavlink only receives the heartbeat messages for some reason. After opening and closing QGC, we get correct packets for a few seconds but after rerunning the code a few seconds later we again receive only heartbeat messages. We also tried to send heartbeat with this code:

```auto
"""
Example of how to connect pymavlink to an autopilot via an UDP connection
"""

# Disable "Bare exception" warning
# pylint: disable=W0702

import time
# Import mavutil
from pymavlink import mavutil
import threading
mavlink = mavutil.mavlink
![aaa|690x187](upload://gbw8Y52tb6aslSMZ3hjdCJ9o2fQ.png)

class WriteLockedFile(object):
    # A file with thread-locked writing. 
    def __init__ (self, file):
        self._base_file = file
        self._write_lock = threading.Lock()
        
    def write(self, *args, **kwargs):
        with self._write_lock:
            self._base_file.write(*args, **kwargs)
    
    def __getattr__ (self, name):
        return getattr(self._base_file, name)
    
    def __dir__ (self):
        return dir(self._base_file) + ["_base_file", "_write_lock"]

class mavactive(object):
    """ A class for managing an active mavlink connection. """
    def __init__ (self, connection, type_=mavlink.MAV_TYPE_GENERIC, autopilot=mavlink.MAV_AUTOPILOT_INVALID, base_mode=0, custom_mode=0,
                 mavlink_version=0, heartbeat_period=0.95):
        """ Initialises the program state and starts the heartbeat thread. """
        self.connection = connection
        self.type = type_
        self.autopilot = autopilot
        self.base_mode = base_mode
        self.custom_mode = custom_mode
        self.mavlink_version = mavlink_version
        self.heartbeat_period = heartbeat_period
        
        # replace internal file with a thread-safe one
        self.connection.mav.file = WriteLockedFile(self.connection.mav.file)
        # set up the kill event and initialise the heartbeat thread
        self._kill = threading.Event()
        self._birth()

    def _birth(self):
        """ Creates and starts the heartbeat thread. """
        self._kill.clear()
        self.heartbeat_thread = threading.Thread(target=self.heartbeat_repeat)
        self.heartbeat_thread.start()

    @property
    def is_alive(self):
        return not self._kill.is_set()

    def heartbeat_repeat(self):
        """ Sends a heartbeat to 'self.connection' with 'self.heartbeat_period'. """
        while self.is_alive:
            #print("Heartbeat")
            self.connection.mav.heartbeat_send(
                self.type,
                self.autopilot,
                self.base_mode,
                self.custom_mode,
                self.mavlink_version
            )
            time.sleep(self.heartbeat_period)

    def kill(self):
        """ Stops the heartbeat, if not already dead. """
        if not self.is_alive:
            return # already dead

        self._kill.set()
        self.heartbeat_thread.join()
        del self.heartbeat_thread

    def revive(self):
        """ Starts the heartbeat, if not already alive. """
        if self.is_alive:
            return # already alive

        self._birth()

    def __del__ (self):
        """ End the thread cleanly on program end. """
        self.kill()
# Create the connection
# If using a companion computer
# the default connection is available
# at ip 192.168.2.1 and the port 14550
# Note: The connection is done with 'udpin' and not 'udpout'.
# You can check in http:192.168.2.2:2770/mavproxy that the communication made for 14550
# uses a 'udpbcast' (client) and not 'udpin' (server).
# If you want to use QGroundControl in parallel with your python script,
# it's possible to add a new output port in http:192.168.2.2:2770/mavproxy as a new line.
# E.g: --out udpbcast:192.168.2.255:yourport
master = mavutil.mavlink_connection("/dev/ttyACM0", baud=115200)

# Make sure the connection is valid
master.wait_heartbeat()

heartbeatPulser = mavactive(master)
# Get some information !
while True:
    try:
        rcvpacket = master.recv_match().to_dict()
        print(rcvpacket)
        if rcvpacket["mavpackettype"] == "AHRS2":
            print("AHRS2 Value")
    except:
        pass
    time.sleep(0.1)

# Output:
# {'mavpackettype': 'AHRS2', 'roll': -0.11364290863275528, 'pitch': -0.02841472253203392, 'yaw': 2.0993032455444336, 'altitude': 0.0, 'lat': 0, 'lng': 0}
# {'mavpackettype': 'AHRS3', 'roll': 0.025831475853919983, 'pitch': 0.006112074479460716, 'yaw': 2.1514968872070312, 'altitude': 0.0, 'lat': 0, 'lng': 0, 'v1': 0.0, 'v2': 0.0, 'v3': 0.0, 'v4': 0.0}
# {'mavpackettype': 'VFR_HUD', 'airspeed': 0.0, 'groundspeed': 0.0, 'heading': 123, 'throttle': 0, 'alt': 3.129999876022339, 'climb': 3.2699999809265137}
# {'mavpackettype': 'AHRS', 'omegaIx': 0.0014122836291790009, 'omegaIy': -0.022567369043827057, 'omegaIz': 0.02394154854118824, 'accel_weight': 0.0, 'renorm_val': 0.0, 'error_rp': 0.08894175291061401, 'error_yaw': 0.0990816056728363}

```

 ![aaa](https://us1.discourse-cdn.com/flex019/uploads/bluerobotics/original/2X/7/71701bac976a418cf57cc0e36e7ccbe2cafc880e.png)

---

<div class="post-metadata">

**Author:** ![EliotBR](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.bluerobotics.com/eliotbr/32/6937_2.png) [@EliotBR](https://discuss.bluerobotics.com/u/EliotBR)\
**Post date:** [January 24, 2022, 12:13am UTC](https://discuss.bluerobotics.com/t/reading-mavlink-packets-from-pymavlink-only-heartbeat/11403/2 "2022-01-24T00:13:00Z")

</div>

Hi @Efe,

Please see this post:

> [@Accessing real-time MAVLink messages via pymavlink](https://discuss.bluerobotics.com/t/accessing-real-time-mavlink-messages-via-pymavlink/11355/2):
>
> Hi @toosat, welcome to the forum slight_smile The Pixhawk will send a small set of vital messages by default, but other messages you’re interested in need to be requested. QGC requests a large set of messages automatically, whereas if you’re connecting directly to the Pixhawk with Pymavlink you’ll need to request those messages yourself. You can request a message to be sent regularly using [MAV\_CMD\_SET\_MESSAGE\_INTERVAL](https://mavlink.io/en/messages/common.html#MAV_CMD_SET_MESSAGE_INTERVAL), which we have a Pymavlink example for [here](https://www.ardusub.com/developers/pymavlink.html#request-message-interval) slight_smile There’s an alte…
