from pymavlink import mavutil
import time
def connect_to_drone(ip=‘192.168.2.2’, port=14550):
“”"
Tries to connect to a real drone using UDP with a specific IP and port.
“”"
try:
connection_string = f’udpin:{ip}:{port}’
print(f"Attempting to connect via {connection_string}…")
connection = mavutil.mavlink_connection(connection_string)
print("Waiting for heartbeat...")
connection.wait_heartbeat(timeout=15)
print(f"Heartbeat received from system {connection.target_system}, component {connection.target_component}")
return connection
except Exception as e:
print(f"Connection failed: {e}")
return None
def display_firmware_info(connection):
“”"
Display autopilot firmware and vehicle type from the heartbeat message.
“”"
heartbeat = connection.recv_match(type=‘HEARTBEAT’, blocking=True, timeout=5)
if heartbeat:
autopilot_firmware = mavutil.mavlink.enums[‘MAV_AUTOPILOT’][heartbeat.autopilot].description
vehicle_type = mavutil.mavlink.enums[‘MAV_TYPE’][heartbeat.type].description
print(f"Firmware: {autopilot_firmware}“)
print(f"Vehicle Type: {vehicle_type}”)
else:
print(“No heartbeat received.”)
def get_gps_data(connection):
“”"
Retrieve GPS data from the drone and print it.
“”"
msg = connection.recv_match(type=‘GPS_RAW_INT’, blocking=True, timeout=5)
if msg:
print(f"GPS Data: Lat: {msg.lat / 1e7}, Lon: {msg.lon / 1e7}, Alt: {msg.alt / 1000}m")
else:
print(“No GPS data received.”)
def get_battery_data(connection):
“”"
Retrieve battery status from the drone and print it.
“”"
msg = connection.recv_match(type=‘SYS_STATUS’, blocking=True, timeout=5)
if msg:
voltage = msg.voltage_battery / 1000.0 # convert millivolts to volts
current = msg.current_battery / 100.0 # convert to amperes
print(f"Battery Data: Voltage: {voltage}V, Current: {current}A")
else:
print(“No battery data received.”)
def main():
connection = connect_to_drone()
if connection:
print("Connection successful. Communicating with the drone.")
display_firmware_info(connection)
# Continuously fetch data
for _ in range(10): # Try 10 times
get_gps_data(connection)
get_battery_data(connection)
time.sleep(1) # Wait for 1 second before fetching data again
else:
print("Failed to connect to the drone.")
if name == “main”:
main()
this is the code when i run the above code
Attempting to connect via udpin:192.168.2.2:14550…
Connection failed: [Errno 99] Cannot assign requested address
Failed to connect to the drone.
i am getting the above error. but the ip address and port number are correct i cross checked with mission planner. can any one tell me how to connect to real drone i am able to connect to jmavsim simulation and get the data if i change the ipaddress according to it