forked from ArduPilot/MethodicConfigurator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend_flightcontroller.py
More file actions
1446 lines (1228 loc) · 61.6 KB
/
Copy pathbackend_flightcontroller.py
File metadata and controls
1446 lines (1228 loc) · 61.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Flight controller interface.
This file is part of ArduPilot Methodic Configurator. https://github.com/ArduPilot/MethodicConfigurator
SPDX-FileCopyrightText: 2024-2025 Amilcar do Carmo Lucas <amilcar.lucas@iav.de>
SPDX-License-Identifier: GPL-3.0-or-later
"""
import os
from argparse import ArgumentParser
from logging import debug as logging_debug
from logging import error as logging_error
from logging import info as logging_info
from logging import warning as logging_warning
from os import name as os_name
from os import path as os_path
from os import readlink as os_readlink
from pathlib import Path
from time import sleep as time_sleep
from time import time as time_time
from typing import Callable, NoReturn, Optional, Union
import serial.tools.list_ports
import serial.tools.list_ports_common
from pymavlink import mavutil
from pymavlink.dialects.v20.ardupilotmega import MAVLink_autopilot_version_message
from serial.serialutil import SerialException
from ardupilot_methodic_configurator import _
from ardupilot_methodic_configurator.argparse_check_range import CheckRange
from ardupilot_methodic_configurator.backend_flightcontroller_info import BackendFlightcontrollerInfo
from ardupilot_methodic_configurator.backend_mavftp import MAVFTP
from ardupilot_methodic_configurator.data_model_par_dict import ParDict
# pylint: disable=too-many-lines
class FakeSerialForTests:
"""
A mock serial class for unit testing purposes.
This class simulates the behavior of a serial connection for testing purposes,
allowing for the testing of serial communication without needing a physical
serial device. It includes methods for reading, writing, and checking the
number of bytes in the input buffer, as well as closing the connection.
"""
def __init__(self, device: str) -> None:
self.device = device
def read(self, _len) -> str: # noqa: ANN001
return ""
def write(self, _buf) -> NoReturn: # noqa: ANN001
msg = "write always fails"
raise Exception(msg) # pylint: disable=broad-exception-raised
def inWaiting(self) -> int: # noqa: N802, pylint: disable=invalid-name
return 0
def close(self) -> None:
pass
DEFAULT_BAUDRATE: int = 115200
DEFAULT_REBOOT_TIME: int = 7
# https://github.com/ArduPilot/ardupilot/blob/master/libraries/AP_SerialManager/AP_SerialManager.cpp#L741C1-L757C32
SUPPORTED_BAUDRATES: list[str] = [
"1200",
"2400",
"4800",
"9600",
"19200",
"38400",
"57600",
"100000",
"111100",
"115200",
"230400",
"256000",
"460800",
"500000",
"921600",
"1500000",
"2000000",
]
class FlightController: # pylint: disable=too-many-public-methods,too-many-instance-attributes
"""
A class to manage the connection and parameters of a flight controller.
Attributes:
device (str): The connection string to the flight controller.
master (mavutil.mavlink_connection): The MAVLink connection object.
fc_parameters (dict[str, float]): A dictionary of flight controller parameters.
"""
def __init__(self, reboot_time: int = DEFAULT_REBOOT_TIME, baudrate: int = DEFAULT_BAUDRATE) -> None:
"""Initialize the FlightController communication object."""
# warn people about ModemManager which interferes badly with ArduPilot
if os_path.exists("/usr/sbin/ModemManager"):
logging_warning(_("You should uninstall ModemManager as it conflicts with ArduPilot"))
self.__reboot_time = reboot_time
self.__baudrate = baudrate
self.__connection_tuples: list[tuple[str, str]] = []
self.discover_connections()
self.master: Union[mavutil.mavlink_connection, None] = None # pyright: ignore[reportGeneralTypeIssues]
self.comport: Union[mavutil.SerialPort, None] = None
self.fc_parameters: dict[str, float] = {}
self.info = BackendFlightcontrollerInfo()
# Battery status tracking
self._last_battery_message_time: float = 0.0
self._last_battery_status: Union[tuple[float, float], None] = None
def discover_connections(self) -> None:
comports = FlightController.__list_serial_ports()
netports = FlightController.__list_network_ports()
# list of tuples with the first element being the port name and the second element being the port description
self.__connection_tuples = [(port.device, port.description) for port in comports] + [(port, port) for port in netports]
logging_info(_("Available connection ports are:"))
for port in self.__connection_tuples:
logging_info("%s - %s", port[0], port[1])
# now that it is logged, add the 'Add another' tuple
self.__connection_tuples += [(_("Add another"), _("Add another"))]
def disconnect(self) -> None:
"""Close the connection to the flight controller."""
if self.master is not None:
self.master.close()
self.master = None
self.fc_parameters = {}
self.info = BackendFlightcontrollerInfo()
def add_connection(self, connection_string: str) -> bool:
"""Add a new connection to the list of available connections."""
if connection_string:
# Check if connection_string is not the first element of any tuple in self.other_connection_tuples
if all(connection_string != t[0] for t in self.__connection_tuples):
self.__connection_tuples.insert(-1, (connection_string, connection_string))
logging_debug(_("Added connection %s"), connection_string)
return True
logging_debug(_("Did not add duplicated connection %s"), connection_string)
else:
logging_debug(_("Did not add empty connection"))
return False
def _register_and_try_connect(
self,
comport: mavutil.SerialPort,
progress_callback: Union[None, Callable[[int, int], None]],
baudrate: int,
log_errors: bool,
) -> str:
"""
Register a device in the connection list (if missing) and attempt connection.
Returns:
str: empty string on success, or error message.
"""
# set comport for subsequent calls
self.comport = comport
# Add the detected port to the list of available connections if it is not there
if self.comport and self.comport.device not in [t[0] for t in self.__connection_tuples]:
self.__connection_tuples.insert(-1, (self.comport.device, getattr(self.comport, "description", "")))
# Try to connect
return self.__create_connection_with_retry(
progress_callback=progress_callback, baudrate=baudrate, log_errors=log_errors, timeout=2
)
def connect(
self,
device: str,
progress_callback: Union[None, Callable[[int, int], None]] = None,
log_errors: bool = True,
baudrate: Optional[int] = None,
) -> str:
"""
Establishes a connection to the FlightController using a specified device.
This method attempts to connect to the FlightController using the provided device
connection string. If no device is specified, it attempts to auto-detect a serial
port that matches the preferred ports list. If no serial device is found it tries
the "standard" ArduPilot UDP and TCP connections. If a device is specified as 'test',
it sets some test parameters for debugging purposes.
Args:
device (str): The connection string to the flight controller. If an empty string
is provided, the method attempts to auto-detect a serial port.
progress_callback (callable, optional): A callback function to report the progress
of the connection attempt. Default is None.
log_errors: log errors
baudrate (int, optional): The baudrate to use for the connection. If None,
uses the default baudrate from initialization.
Returns:
str: An error message if the connection fails, otherwise an empty string indicating
a successful connection.
"""
connection_baudrate = baudrate
if connection_baudrate is None:
connection_baudrate = self.__baudrate
if device:
if device == "none":
return ""
self.add_connection(device)
self.comport = mavutil.SerialPort(device=device, description=device)
return self.__create_connection_with_retry(
progress_callback=progress_callback, baudrate=connection_baudrate, log_errors=log_errors
)
# Try to autodetect serial ports
autodetect_serial = self.__auto_detect_serial()
if autodetect_serial:
# Resolve the soft link if it's a Linux system
if os_name == "posix":
try:
dev = autodetect_serial[0].device
logging_debug(_("Auto-detected device %s"), dev)
# Get the directory part of the soft link
softlink_dir = os_path.dirname(dev)
# Resolve the soft link and join it with the directory part
resolved_path = os_path.abspath(os_path.join(softlink_dir, os_readlink(dev)))
autodetect_serial[0].device = resolved_path
logging_debug(_("Resolved soft link %s to %s"), dev, resolved_path)
except OSError:
pass # Not a soft link, proceed with the original device path
err = self._register_and_try_connect(
comport=autodetect_serial[-1],
progress_callback=progress_callback,
baudrate=connection_baudrate,
log_errors=False,
)
if err == "":
return ""
# Try to autodetect network ports
netports = FlightController.__list_network_ports()
for port in netports:
# try to connect to each "standard" ArduPilot UDP and TCP ports
logging_debug(_("Trying network port %s"), port)
err = self._register_and_try_connect(
comport=mavutil.SerialPort(device=port, description=port),
progress_callback=progress_callback,
baudrate=self.__baudrate,
log_errors=False,
)
if err == "":
return ""
return _("No auto-detected ports responded. Please connect a flight controller and try again.")
def __request_banner(self) -> None:
"""Request banner information from the flight controller."""
# https://mavlink.io/en/messages/ardupilotmega.html#MAV_CMD_DO_SEND_BANNER
if self.master is not None:
# Note: Don't wait for ACK here as banner requests are fire-and-forget
# and we handle the response via STATUS_TEXT messages
self.master.mav.command_long_send(
self.master.target_system,
self.master.target_component,
mavutil.mavlink.MAV_CMD_DO_SEND_BANNER,
0,
0,
0,
0,
0,
0,
0,
0,
)
def __receive_banner_text(self) -> list[str]:
"""Starts listening for STATUS_TEXT MAVLink messages."""
start_time = time_time()
banner_msgs: list[str] = []
while self.master:
msg = self.master.recv_match(type="STATUSTEXT", blocking=False)
if msg:
if banner_msgs:
banner_msgs.append(msg.text)
else:
banner_msgs = [msg.text]
time_sleep(0.1) # Sleep briefly to reduce CPU usage
if time_time() - start_time > 1: # Check if 1 seconds have passed since the start of the loop
break # Exit the loop if 1 seconds have elapsed
return banner_msgs
def __request_message(self, message_id: int) -> None:
"""Request a specific message from the flight controller."""
if self.master is not None:
# Note: Don't wait for ACK here as this is used internally for autopilot version requests
# and the response comes as the requested message itself
self.master.mav.command_long_send(
self.info.system_id,
self.info.component_id,
mavutil.mavlink.MAV_CMD_REQUEST_MESSAGE,
0, # confirmation
message_id,
0,
0,
0,
0,
0,
0,
)
def _send_command_and_wait_ack( # pylint: disable=too-many-arguments,too-many-positional-arguments, too-many-locals
self,
command: int,
param1: float = 0,
param2: float = 0,
param3: float = 0,
param4: float = 0,
param5: float = 0,
param6: float = 0,
param7: float = 0,
timeout: float = 5.0,
) -> tuple[bool, str]:
"""
Send a MAVLink command and wait for acknowledgment.
Args:
command: The MAVLink command ID
param1: Command parameter 1
param2: Command parameter 2
param3: Command parameter 3
param4: Command parameter 4
param5: Command parameter 5
param6: Command parameter 6
param7: Command parameter 7
timeout: Timeout in seconds to wait for acknowledgment
Returns:
tuple[bool, str]: (success, error_message) - success is True if command was acknowledged successfully,
error_message is empty string on success or contains error description on failure
"""
if self.master is None:
error_msg = _("No flight controller connection available for command")
logging_error(error_msg)
return False, error_msg
try:
# Send the command
self.master.mav.command_long_send(
self.master.target_system,
self.master.target_component,
command,
0, # confirmation
param1,
param2,
param3,
param4,
param5,
param6,
param7,
)
# Wait for acknowledgment
start_time = time_time()
while time_time() - start_time < timeout:
msg = self.master.recv_match(type="COMMAND_ACK", blocking=False)
if msg and msg.command == command:
# Map result codes to error messages
result_messages = {
mavutil.mavlink.MAV_RESULT_ACCEPTED: ("", True),
mavutil.mavlink.MAV_RESULT_TEMPORARILY_REJECTED: (_("Command temporarily rejected"), False),
mavutil.mavlink.MAV_RESULT_DENIED: (_("Command denied"), False),
mavutil.mavlink.MAV_RESULT_UNSUPPORTED: (_("Command unsupported"), False),
mavutil.mavlink.MAV_RESULT_FAILED: (_("Command failed"), False),
}
if msg.result in result_messages:
error_msg, success = result_messages[msg.result]
if not success:
logging_error(error_msg)
return success, error_msg
if msg.result == mavutil.mavlink.MAV_RESULT_IN_PROGRESS:
# Command is still in progress, continue waiting
if msg.progress is not None and msg.progress > 0:
logging_debug(_("Command in progress: %(progress)d%%"), {"progress": msg.progress})
continue
# Unknown result code
error_msg = _("Command acknowledgment with unknown result: %(result)d") % {"result": msg.result}
logging_error(error_msg)
return False, error_msg
time_sleep(0.1) # Sleep briefly to reduce CPU usage
# Timeout occurred
error_msg = _("Command acknowledgment timeout after %(timeout).1f seconds") % {"timeout": timeout}
logging_error(error_msg)
return False, error_msg
except Exception as e: # pylint: disable=broad-exception-caught
error_msg = _("Failed to send command: %(error)s") % {"error": str(e)}
logging_error(error_msg)
return False, error_msg
def __create_connection_with_retry( # pylint: disable=too-many-arguments, too-many-positional-arguments, too-many-locals, too-many-branches
self,
progress_callback: Union[None, Callable[[int, int], None]],
retries: int = 3,
timeout: int = 5,
baudrate: int = DEFAULT_BAUDRATE,
log_errors: bool = True,
) -> str:
"""
Attempts to create a connection to the flight controller with retries.
This method attempts to establish a connection to the flight controller using the
provided device connection string. It will retry the connection attempt up to the
specified number of retries if the initial attempt fails. The method also supports
a progress callback to report the progress of the connection attempt.
Args:
progress_callback (callable, optional): A callback function to report the progress
of the connection attempt. Default is None.
retries (int, optional): The number of retries before giving up. Default is 3.
timeout (int, optional): The timeout in seconds for each connection attempt. Default is 5.
baudrate (int, optional): The baud rate for the connection. Default is DEFAULT_BAUDRATE.
log_errors (bool): log errors.
Returns:
str: An error message if the connection fails after all retries, otherwise an empty string
indicating a successful connection.
"""
if self.comport is None or self.comport.device == "test": # FIXME for testing only pylint: disable=fixme
return ""
if self.comport.device.startswith("udp") or self.comport.device.startswith("tcp"):
logging_info(_("Will connect to %s"), self.comport.device)
else:
logging_info(_("Will connect to %s @ %u baud"), self.comport.device, baudrate)
try:
# Create the connection
self.master = mavutil.mavlink_connection(
device=self.comport.device,
baud=baudrate,
timeout=timeout,
retries=retries,
progress_callback=progress_callback,
)
logging_debug(_("Waiting for MAVLink heartbeats..."))
if not self.master:
msg = f"Failed to create mavlink connect to {self.comport.device}"
raise ConnectionError(msg)
# --- NEW: collect all vehicles detected within timeout ---
start_time = time_time()
detected_vehicles = {} # (sysid, compid) -> last HEARTBEAT
while time_time() - start_time < timeout:
m = self.master.recv_match(type="HEARTBEAT", blocking=False)
if m is None:
time_sleep(0.1)
continue
sysid = m.get_srcSystem()
compid = m.get_srcComponent()
detected_vehicles[(sysid, compid)] = m
logging_debug(_("Detected vehicle %u:%u (autopilot=%u, type=%u)"), sysid, compid, m.autopilot, m.type)
if not detected_vehicles:
return _("No MAVLink heartbeat received, connection failed.")
for (sysid, compid), m in detected_vehicles.items():
self.info.set_system_id_and_component_id(sysid, compid)
logging_debug(
_("Connection established with systemID %d, componentID %d."), self.info.system_id, self.info.component_id
)
self.info.set_autopilot(m.autopilot)
if self.info.is_supported:
msg = _("Autopilot type {self.info.autopilot}")
logging_info(msg.format(**locals()))
self.info.set_type(m.type)
msg = _("Vehicle type: {self.info.mav_type} running {self.info.vehicle_type} firmware")
logging_info(msg.format(**locals()))
break
msg = _("Unsupported autopilot type {self.info.autopilot}")
logging_info(msg.format(**locals()))
if not self.info.is_supported:
return _("No supported autopilots found")
self.__request_banner()
banner_msgs = self.__receive_banner_text()
self.__request_message(mavutil.mavlink.MAVLINK_MSG_ID_AUTOPILOT_VERSION)
m = self.master.recv_match(type="AUTOPILOT_VERSION", blocking=True, timeout=timeout)
return self.__process_autopilot_version(m, banner_msgs)
except (ConnectionError, SerialException, PermissionError, ConnectionRefusedError) as e:
if log_errors:
logging_warning(_("Connection failed: %s"), e)
logging_error(_("Failed to connect after %d attempts."), retries)
error_message = str(e)
guidance = self.__get_connection_error_guidance(e, self.comport.device if self.comport else "")
if guidance:
error_message = f"{error_message}\n\n{guidance}"
return error_message
def __get_connection_error_guidance(self, error: Exception, device: str) -> str:
"""
Provides guidance based on the type of connection error.
Args:
error (Exception): The exception that occurred during connection.
device (str): The device path or connection string.
Returns:
str: Guidance message specific to the error type, or empty string if no specific guidance.
"""
# Check for permission denied errors on Linux
if isinstance(error, PermissionError) and os_name == "posix" and "/dev/" in device:
return _(
"Permission denied accessing the serial port. This is common on Linux systems.\n"
"To fix this issue, add your user to the 'dialout' group with the following command:\n"
" sudo adduser $USER dialout\n"
"Then log out and log back in for the changes to take effect."
)
# Add more specific guidance for other error types as needed
return ""
def __process_autopilot_version(self, m: MAVLink_autopilot_version_message, banner_msgs: list[str]) -> str:
if m is None:
return _(
"No AUTOPILOT_VERSION MAVLink message received, connection failed.\n"
"Only ArduPilot versions newer than 4.3.8 are supported.\n"
"Make sure parameter SERIAL0_PROTOCOL is set to 2"
)
self.info.set_capabilities(m.capabilities)
self.info.set_flight_sw_version(m.flight_sw_version)
self.info.set_usb_vendor_and_product_ids(m.vendor_id, m.product_id) # must be done before set_board_version()
self.info.set_board_version(m.board_version)
self.info.set_flight_custom_version(m.flight_custom_version)
self.info.set_os_custom_version(m.os_custom_version)
os_custom_version = ""
os_custom_version_index = None
for i, msg in enumerate(banner_msgs):
if "ChibiOS:" in msg:
os_custom_version = msg.split(" ")[1].strip()
hash_len1 = max(7, len(os_custom_version) - 1)
hash_len2 = max(7, len(self.info.os_custom_version) - 1)
hash_len = min(hash_len1, hash_len2)
if os_custom_version[:hash_len] != self.info.os_custom_version[:hash_len]:
logging_warning(
_("ChibiOS version mismatch: %s (BANNER) != % s (AUTOPILOT_VERSION)"),
os_custom_version,
self.info.os_custom_version,
)
os_custom_version_index = i
continue
logging_debug("FC banner %s", msg)
# the banner message after the ChibiOS one contains the FC type
firmware_type = ""
if os_custom_version_index is not None and os_custom_version_index + 1 < len(banner_msgs):
firmware_type_banner_substrings = banner_msgs[os_custom_version_index + 1].split(" ")
if len(firmware_type_banner_substrings) >= 3:
firmware_type = firmware_type_banner_substrings[0]
if firmware_type and firmware_type != self.info.firmware_type:
logging_debug(
_("FC firmware type mismatch: %s (BANNER) != %s (AUTOPILOT_VERSION)"), firmware_type, self.info.firmware_type
)
self.info.firmware_type = firmware_type # force the one from the banner because it is more reliable
return ""
def download_params(
self,
progress_callback: Union[None, Callable[[int, int], None]] = None,
parameter_values_filename: Optional[Path] = None,
parameter_defaults_filename: Optional[Path] = None,
) -> tuple[dict[str, float], ParDict]:
"""
Requests all flight controller parameters from a MAVLink connection.
Args:
progress_callback (Union[None, Callable[[int, int], None]]): A callback function to report download progress.
parameter_values_filename (Optional[Path]): The filename to save the parameter values.
parameter_defaults_filename (Optional[Path]): The filename to save the parameter defaults.
Returns:
dict[str, float]: A dictionary of flight controller parameters.
ParDict: A dictionary of flight controller default parameters.
"""
# FIXME this entire if statement is for testing only, remove it later pylint: disable=fixme
if self.master is None and self.comport is not None and self.comport.device == "test":
filename = "params.param"
logging_warning(_("Testing active, will load all parameters from the %s file"), filename)
par_dict_with_comments = ParDict.from_file(filename)
return {k: v.value for k, v in par_dict_with_comments.items()}, ParDict()
if self.master is None:
return {}, ParDict()
# Check if MAVFTP is supported
comport_device = getattr(self.comport, "device", "")
if self.info.is_mavftp_supported:
logging_info(_("MAVFTP is supported by the %s flight controller"), comport_device)
param_dict, default_param_dict = self._download_params_via_mavftp(
progress_callback, parameter_values_filename, parameter_defaults_filename
)
if param_dict:
return param_dict, default_param_dict
logging_info(_("MAVFTP is not supported by the %s flight controller, fallback to MAVLink"), comport_device)
return self._download_params_via_mavlink(progress_callback), ParDict()
def _download_params_via_mavlink(
self, progress_callback: Union[None, Callable[[int, int], None]] = None
) -> dict[str, float]:
"""
Requests all flight controller parameters from a MAVLink connection.
Gets parameters via PARAM_REQUEST_LIST and PARAM_VALUE messages
Args:
progress_callback (Union[None, Callable[[int, int], None]]): A callback function to report download progress.
Returns:
dict[str, float]: A dictionary of flight controller parameters.
ParDict: A dictionary of flight controller default parameters.
"""
comport_device = getattr(self.comport, "device", "")
logging_debug(_("Will fetch all parameters from the %s flight controller"), comport_device)
# Dictionary to store parameters
parameters: dict[str, float] = {}
# Request all parameters
if self.master is None:
return parameters
self.master.mav.param_request_list_send(self.master.target_system, self.master.target_component)
# Loop to receive all parameters
while True:
try:
m = self.master.recv_match(type="PARAM_VALUE", blocking=True, timeout=10)
if m is None:
break
message = m.to_dict()
param_id = message["param_id"] # .decode("utf-8")
param_value = message["param_value"]
parameters[param_id] = param_value
logging_debug(_("Received parameter: %s = %s"), param_id, param_value)
# Call the progress callback with the current progress
if progress_callback:
progress_callback(len(parameters), m.param_count)
if m.param_count == len(parameters):
logging_debug(
_("Fetched %d parameter values from the %s flight controller"), m.param_count, comport_device
)
break
except Exception as error: # pylint: disable=broad-except
logging_error(_("Error: %s"), error)
break
return parameters
def _download_params_via_mavftp(
self,
progress_callback: Union[None, Callable[[int, int], None]] = None,
parameter_values_filename: Optional[Path] = None,
parameter_defaults_filename: Optional[Path] = None,
) -> tuple[dict[str, float], ParDict]:
"""
Requests all flight controller parameters from a MAVLink connection.
Gets parameters via MAVFTP protocol
Args:
progress_callback (Union[None, Callable[[int, int], None]]): A callback function to report download progress.
parameter_values_filename (Optional[Path]): The filename to save the parameter values.
parameter_defaults_filename (Optional[Path]): The filename to save the parameter defaults.
Returns:
dict[str, float]: A dictionary of flight controller parameters.
ParDict: A dictionary of flight controller default parameters.
"""
if self.master is None:
return {}, ParDict()
mavftp = MAVFTP(self.master, target_system=self.master.target_system, target_component=self.master.target_component)
def get_params_progress_callback(completion: float) -> None:
if progress_callback is not None and completion is not None:
progress_callback(int(completion * 100), 100)
complete_param_filename = str(parameter_values_filename) if parameter_values_filename else "complete.param"
default_param_filename = str(parameter_defaults_filename) if parameter_defaults_filename else "00_default.param"
mavftp.cmd_getparams([complete_param_filename, default_param_filename], progress_callback=get_params_progress_callback)
ret = mavftp.process_ftp_reply("getparams", timeout=40) # on slow links it might take a long time
pdict: dict[str, float] = {}
defdict: ParDict = ParDict()
# add a file sync operation to ensure the file is completely written
time_sleep(0.3)
if ret.error_code == 0:
# load the parameters from the file
par_dict = ParDict.from_file(complete_param_filename)
pdict = {name: data.value for name, data in par_dict.items()}
defdict = ParDict.from_file(default_param_filename)
else:
ret.display_message()
return pdict, defdict
def set_param(self, param_name: str, param_value: float) -> None:
"""
Set a parameter on the flight controller.
Args:
param_name (str): The name of the parameter to set.
param_value (float): The value to set the parameter to.
"""
if self.master is None: # FIXME for testing only pylint: disable=fixme
return
self.master.param_set_send(param_name, param_value)
def fetch_param(self, param_name: str, timeout: int = 5) -> Optional[float]:
"""
Fetch a parameter from the flight controller using MAVLink PARAM_REQUEST_READ message.
Args:
param_name (str): The name of the parameter to fetch.
timeout (int): Timeout in seconds to wait for the response. Default is 5.
Returns:
float: The value of the parameter, or None if not found or timeout occurred.
"""
if self.master is None: # FIXME for testing only pylint: disable=fixme
return None
# Send PARAM_REQUEST_READ message
self.master.mav.param_request_read_send(
self.master.target_system,
self.master.target_component,
param_name.encode("utf-8"),
-1, # param_index: -1 means use param_id instead
)
# Wait for PARAM_VALUE response
start_time = time_time()
while time_time() - start_time < timeout:
msg = self.master.recv_match(type="PARAM_VALUE", blocking=False)
if msg is not None:
# Check if this is the parameter we requested
received_param_name = msg.param_id.rstrip("\x00")
if received_param_name == param_name:
logging_debug(_("Received parameter: %s = %s"), param_name, msg.param_value)
return float(msg.param_value)
time_sleep(0.01) # Small sleep to prevent busy waiting
raise TimeoutError(_("Timeout waiting for parameter %s") % param_name)
def reset_all_parameters_to_default(self) -> tuple[bool, str]:
"""
Reset all parameters to their factory default values.
This function sends a MAV_CMD_PREFLIGHT_STORAGE command to reset all parameters
to their factory defaults and waits for acknowledgment from the flight controller.
The flight controller will need to be rebooted after this operation to apply the changes.
Returns:
tuple[bool, str]: (success, error_message) - success is True if command was acknowledged successfully,
error_message is empty string on success or contains error description on failure
Note:
After calling this method, the flight controller should be rebooted to
apply the parameter reset. The reset operation will take effect only
after the reboot.
"""
if self.master is None:
error_msg = _("No flight controller connection available for parameter reset")
logging_warning(error_msg)
return False, error_msg
# MAV_CMD_PREFLIGHT_STORAGE command
# https://mavlink.io/en/messages/common.html#MAV_CMD_PREFLIGHT_STORAGE
# param1 = 2: Erase all parameters
success, error_msg = self._send_command_and_wait_ack(
mavutil.mavlink.MAV_CMD_PREFLIGHT_STORAGE,
param1=2, # Storage action (2 = erase all parameters)
param2=0, # Parameter reset (0 = No parameter reset)
param3=0, # Mission reset (not used)
param4=0, # unused
param5=0, # unused
param6=0, # unused
param7=0, # unused
timeout=10.0, # Give more time for parameter reset
)
if success:
logging_info(_("Parameter reset to defaults command confirmed by flight controller"))
else:
error_msg = _("Parameter reset command failed: %(error)s") % {"error": error_msg}
logging_error(error_msg)
return success, error_msg
def reset_and_reconnect(
self,
reset_progress_callback: Union[None, Callable[[int, int], None]] = None,
connection_progress_callback: Union[None, Callable[[int, int], None]] = None,
extra_sleep_time: Optional[int] = None,
) -> str:
"""
Reset the flight controller and reconnect.
Args:
reset_progress_callback: reset callback function
connection_progress_callback: connection callback function
extra_sleep_time (int, optional): The time in seconds to wait before reconnecting.
"""
if self.master is None: # FIXME for testing only pylint: disable=fixme
return ""
# Issue a reset
self.master.reboot_autopilot()
logging_info(_("Reset command sent to ArduPilot."))
time_sleep(0.3)
self.disconnect()
current_step = 0
if extra_sleep_time is None or extra_sleep_time < 0:
extra_sleep_time = 0
sleep_time = self.__reboot_time + extra_sleep_time
while current_step != sleep_time:
# Call the progress callback with the current progress
if reset_progress_callback:
reset_progress_callback(current_step, sleep_time)
# Wait for sleep_time seconds
time_sleep(1)
current_step += 1
# Call the progress callback with the current progress
if reset_progress_callback:
reset_progress_callback(current_step, sleep_time)
# Reconnect to the flight controller
return self.__create_connection_with_retry(connection_progress_callback, baudrate=self.__baudrate)
@staticmethod
def __list_serial_ports() -> list[serial.tools.list_ports_common.ListPortInfo]:
"""List all available serial ports."""
comports = serial.tools.list_ports.comports()
for port in comports:
logging_debug("ComPort - %s, Description: %s", port.device, port.description)
return comports # type: ignore[no-any-return]
# Motor Test Functionality
def test_motor( # pylint: disable=too-many-arguments, too-many-positional-arguments
self, test_sequence_nr: int, motor_letters: str, motor_output_nr: int, throttle_percent: int, timeout_seconds: int
) -> tuple[bool, str]:
"""
Test a specific motor.
Args:
test_sequence_nr: Motor test number, this is not the same as the output number!
motor_letters: Motor letters (for logging purposes only)
motor_output_nr: Motor output number (for logging purposes only)
throttle_percent: Throttle percentage (0-100)
timeout_seconds: Test duration in seconds
Returns:
tuple[bool, str]: (success, error_message) - success is True if command was acknowledged successfully,
error_message is empty string on success or contains error description on failure
"""
if self.master is None:
error_msg = _("No flight controller connection available for motor test")
logging_error(error_msg)
return False, error_msg
# MAV_CMD_DO_MOTOR_TEST command
# https://mavlink.io/en/messages/common.html#MAV_CMD_DO_MOTOR_TEST
success, error_msg = self._send_command_and_wait_ack(
mavutil.mavlink.MAV_CMD_DO_MOTOR_TEST,
param1=test_sequence_nr + 1, # motor test number, this is not the same as the output number!
param2=mavutil.mavlink.MOTOR_TEST_THROTTLE_PERCENT, # throttle type
param3=throttle_percent, # throttle value
param4=timeout_seconds, # timeout
param5=0, # motor count (0=test just the motor specified in param1)
param6=0, # test order (0=default/board order)
param7=0, # unused
)
if success:
logging_info(
_(
"Motor test command acknowledged: Motor %(seq)s on output %(output)d at %(throttle)d%% thrust"
" for %(duration)d seconds"
),
{
"seq": motor_letters,
"output": motor_output_nr,
"throttle": throttle_percent,
"duration": timeout_seconds,
},
)
else:
error_msg = _("Motor test command failed: %(error)s") % {"error": error_msg}
logging_error(error_msg)
return success, error_msg
def test_all_motors(self, nr_of_motors: int, throttle_percent: int, timeout_seconds: int) -> tuple[bool, str]:
"""
Test all motors simultaneously.
Args:
nr_of_motors: Number of motors to test
throttle_percent: Throttle percentage (0-100)
timeout_seconds: Test duration in seconds
Returns:
tuple[bool, str]: (success, error_message) - success is True if command was acknowledged successfully,
error_message is empty string on success or contains error description on failure
"""
if self.master is None:
error_msg = _("No flight controller connection available for motor test")
logging_error(error_msg)
return False, error_msg
for i in range(nr_of_motors):
# MAV_CMD_DO_MOTOR_TEST command for all motors
self.master.mav.command_long_send(
self.master.target_system,
self.master.target_component,
mavutil.mavlink.MAV_CMD_DO_MOTOR_TEST,
0, # confirmation
param1=i + 1, # motor number (1-based)
param2=mavutil.mavlink.MOTOR_TEST_THROTTLE_PERCENT, # throttle type
param3=throttle_percent, # throttle value
param4=timeout_seconds, # timeout
param5=0, # motor count (0=all motors when param1=0)
param6=0, # test order (0=default/board order)
param7=0, # unused
)
time_sleep(0.01) # to let the FC parse each command individually
return True, ""
def test_motors_in_sequence(
self, start_motor: int, motor_count: int, throttle_percent: int, timeout_seconds: int
) -> tuple[bool, str]:
"""
Test motors in sequence (A, B, C, D, etc.).
Args:
start_motor: The first motor to test (1-based index)
motor_count: Number of motors to test in sequence
throttle_percent: Throttle percentage (1-100)
timeout_seconds: Test duration per motor in seconds
Returns:
tuple[bool, str]: (success, error_message) - success is True if command was acknowledged successfully,
error_message is empty string on success or contains error description on failure
"""
if self.master is None:
error_msg = _("No flight controller connection available for motor test")
logging_error(error_msg)
return False, error_msg
# MAV_CMD_DO_MOTOR_TEST command for sequence test
success, error_msg = self._send_command_and_wait_ack(
mavutil.mavlink.MAV_CMD_DO_MOTOR_TEST,
param1=start_motor, # starting motor number (1-based)
param2=mavutil.mavlink.MOTOR_TEST_THROTTLE_PERCENT, # throttle type
param3=throttle_percent, # throttle value
param4=timeout_seconds, # timeout per motor
param5=motor_count, # number of motors to test in sequence