ardupilot-log-reader 0.2.0__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,14 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ardupilot_log_reader
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: module to read ardupilot binary logs to memory
5
5
  Home-page: https://github.com/PyFlightCoach/ardupilot_log_reader
6
6
  Author: Thomas David
7
7
  Author-email: thomasdavid0@gmail.com
8
8
  Description-Content-Type: text/markdown
9
+ Requires-Dist: numpy
10
+ Requires-Dist: pandas
11
+ Requires-Dist: pymavlink
9
12
 
10
13
  # Ardupilot Log Reader
11
14
 
@@ -18,7 +21,6 @@ from ArdupilotLogReader import Ardupilot
18
21
  parser = Ardupilot(
19
22
  log_file, # the log file, .bin
20
23
  types = ['ARSP', 'ATT', 'BARO', 'GPS', 'IMU', 'RCIN', 'RCOU', 'BAT', 'MODE', 'NKF1', 'STAT', 'XKF1'], # fields to read from the log
21
- zero_time_base=True # arguments passed to pymavlink
22
24
  )
23
25
 
24
26
  parser.dfs # a dict containing a dataframes of log data for each field requested.
@@ -9,7 +9,6 @@ from ArdupilotLogReader import Ardupilot
9
9
  parser = Ardupilot(
10
10
  log_file, # the log file, .bin
11
11
  types = ['ARSP', 'ATT', 'BARO', 'GPS', 'IMU', 'RCIN', 'RCOU', 'BAT', 'MODE', 'NKF1', 'STAT', 'XKF1'], # fields to read from the log
12
- zero_time_base=True # arguments passed to pymavlink
13
12
  )
14
13
 
15
14
  parser.dfs # a dict containing a dataframes of log data for each field requested.
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env python
2
+
3
+ '''
4
+ example program that dumps a Mavlink log file. The log file is
5
+ assumed to be in the format that qgroundcontrol uses, which consists
6
+ of a series of MAVLink packets, each with a 64 bit timestamp
7
+ header. The timestamp is in microseconds since 1970 (unix epoch)
8
+
9
+ This program is free software: you can redistribute it and/or modify it under
10
+ the terms of the GNU General Public License as published by the Free Software
11
+ Foundation, either version 3 of the License, or (at your option) any later
12
+ version.
13
+ This program is distributed in the hope that it will be useful, but WITHOUT
14
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15
+ FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16
+ You should have received a copy of the GNU General Public License along with
17
+ this program. If not, see <http://www.gnu.org/licenses/>.
18
+ '''
19
+
20
+ from __future__ import annotations
21
+ import fnmatch
22
+ import os
23
+ import pandas as pd
24
+ from dataclasses import dataclass
25
+ from pymavlink.DFReader import DFReader_binary
26
+
27
+
28
+ @dataclass
29
+ class Ardupilot(object):
30
+ filename: str
31
+ dfs: dict[str, pd.DataFrame]
32
+
33
+ def __getattr__(self, name):
34
+ if name in self.dfs:
35
+ return self.dfs[name]
36
+ raise AttributeError(f"No such attribute: {name}")
37
+
38
+ @staticmethod
39
+ def process_patterns(available: list[str], patterns:list[str] = None, exclude_patterns: list[str]=None):
40
+ def match_type(mtype, patterns):
41
+ for p in patterns:
42
+ if fnmatch.fnmatch(mtype, p):
43
+ return True
44
+ return False
45
+ patterns = available if patterns is None else patterns
46
+ exclude_patterns = [] if exclude_patterns is None else exclude_patterns
47
+ return [k for k in available if match_type(k, patterns) and not match_type(k, exclude_patterns)]
48
+
49
+ @staticmethod
50
+ def parse(
51
+ bin_file, types=None, nottypes=None, zero_time_base=False,
52
+ source_system=None, source_component=None, link=None, mav10=False
53
+ ) -> Ardupilot:
54
+ """
55
+ Parses a binary file into an Ardupilot object.
56
+
57
+ Parameters:
58
+ bin_file (str): The binary file to parse.
59
+ types (list[str], optional): List of types or patterns to include in the parsing. Defaults to None.
60
+ nottypes (list[str], optional): List of types or patterns to exclude from the parsing. Defaults to None.
61
+ zero_time_base (bool, optional): If True, sets the time base to zero. Defaults to False.
62
+ source_system (int, optional): The source system ID to filter messages by. Defaults to None (all systems in log).
63
+ source_component (int, optional): The source component ID to filter messages by. Defaults to None (all components in log).
64
+ link (int, optional): The link to filter messages by. Defaults to None.
65
+ mav10 (bool, optional): If True, uses MAVLink 1.0. Defaults to False.
66
+
67
+ Returns:
68
+ Ardupilot: The parsed Ardupilot object.
69
+ """
70
+ if not mav10:
71
+ os.environ['MAVLINK20'] = '1'
72
+
73
+ mlog: DFReader_binary = DFReader_binary(str(bin_file), zero_time_base=zero_time_base)
74
+
75
+ match_types = Ardupilot.process_patterns(
76
+ list(mlog.name_to_id.keys()),
77
+ list(set(types + ['PARM'])),
78
+ nottypes
79
+ )
80
+
81
+ log = Ardupilot._parse(mlog, match_types, source_system, source_component, link)
82
+
83
+ mlog.filehandle.close()
84
+
85
+ return log
86
+
87
+ @staticmethod
88
+ def _parse(mlog, cols: list[str], src_system=None, src_component=None, link=None):
89
+ dfs_dicts = {}
90
+
91
+ while True:
92
+ m = mlog.recv_match(blocking=False, type=cols)
93
+ if m is None:
94
+ break
95
+ if src_system is not None and src_system != m.get_srcSystem():
96
+ continue
97
+ if src_component is not None and src_component != m.get_srcComponent():
98
+ continue
99
+ if link is not None and link != m._link:
100
+ continue
101
+
102
+ key=m.get_type()
103
+
104
+ if key not in dfs_dicts:
105
+ if key == 'BAD_DATA':
106
+ continue
107
+ dfs_dicts[key] = {}
108
+ dfs_dicts[key]['timestamp'] = []
109
+ for field in m.get_fieldnames():
110
+ dfs_dicts[key][field] = []
111
+
112
+ dfs_dicts[key]['timestamp'].append( getattr(m,'_timestamp', 0.0) )
113
+
114
+ for field in m.get_fieldnames():
115
+ dfs_dicts[key][field].append( getattr(m,field) )
116
+
117
+ return Ardupilot(mlog.filehandle.name, {k: pd.DataFrame(v) for k, v in dfs_dicts.items()})
118
+
119
+ def parameters(self) -> dict[str, pd.DataFrame]:
120
+ gb = self.PARM.groupby('Name')
121
+
122
+ parms = {}
123
+ for gn in gb.groups.keys():
124
+ gr = gb.get_group(gn)
125
+ parms[gn] = gr.loc[abs(gr.Value.diff().fillna(1)) > 0, ["timestamp", "TimeUS", "Value"]].set_index('timestamp')
126
+ return parms
127
+
128
+
@@ -1,11 +1,14 @@
1
1
  Metadata-Version: 2.1
2
- Name: ardupilot-log-reader
3
- Version: 0.2.0
2
+ Name: ardupilot_log_reader
3
+ Version: 0.3.1
4
4
  Summary: module to read ardupilot binary logs to memory
5
5
  Home-page: https://github.com/PyFlightCoach/ardupilot_log_reader
6
6
  Author: Thomas David
7
7
  Author-email: thomasdavid0@gmail.com
8
8
  Description-Content-Type: text/markdown
9
+ Requires-Dist: numpy
10
+ Requires-Dist: pandas
11
+ Requires-Dist: pymavlink
9
12
 
10
13
  # Ardupilot Log Reader
11
14
 
@@ -18,7 +21,6 @@ from ArdupilotLogReader import Ardupilot
18
21
  parser = Ardupilot(
19
22
  log_file, # the log file, .bin
20
23
  types = ['ARSP', 'ATT', 'BARO', 'GPS', 'IMU', 'RCIN', 'RCOU', 'BAT', 'MODE', 'NKF1', 'STAT', 'XKF1'], # fields to read from the log
21
- zero_time_base=True # arguments passed to pymavlink
22
24
  )
23
25
 
24
26
  parser.dfs # a dict containing a dataframes of log data for each field requested.
@@ -5,12 +5,11 @@ author_email = thomasdavid0@gmail.com
5
5
  description = module to read ardupilot binary logs to memory
6
6
  long_description = file: ReadMe.md
7
7
  long_description_content_type = text/markdown
8
- version = 0.2.0
8
+ version = 0.3.1
9
9
  url = https://github.com/PyFlightCoach/ardupilot_log_reader
10
10
 
11
11
  [options]
12
12
  install_requires =
13
- future
14
13
  numpy
15
14
  pandas
16
15
  pymavlink
@@ -10,8 +10,6 @@ You should have received a copy of the GNU General Public License along with
10
10
  this program. If not, see <http://www.gnu.org/licenses/>.
11
11
  """
12
12
  from ardupilot_log_reader.reader import Ardupilot
13
- import numpy as np
14
- import pandas as pd
15
13
 
16
14
  import pytest
17
15
 
@@ -22,30 +20,16 @@ def type_request():
22
20
 
23
21
  @pytest.fixture(scope="session")
24
22
  def log(type_request):
25
- return Ardupilot('tests/test_inputs/test_log_00000052.BIN', types=type_request, zero_time_base=True)
23
+ return Ardupilot.parse('tests/test_inputs/test_log_00000052.BIN', types=type_request, zero_time_base=True)
26
24
 
27
25
  @pytest.fixture(scope="session")
28
26
  def log2(type_request):
29
- return Ardupilot('tests/test_inputs/00000129.BIN', types=type_request, zero_time_base=True)
30
-
27
+ return Ardupilot.parse('tests/test_inputs/00000129.BIN', types=type_request, zero_time_base=True)
31
28
 
32
29
  def test_dfs(type_request, log):
33
30
  assert set(log.dfs.keys()) == set(type_request + ['PARM'])
34
31
 
35
32
 
36
- def test_full_df_frequency(log, type_request):
37
- fulldf = log.join_logs(type_request)
38
- assert len(log.dfs['XKF1']) == len(fulldf)
39
-
40
-
41
- def test_time_epioch(log):
42
- gpsdf = log.dfs['GPS']
43
- assert "GPSTimeUS" in gpsdf.columns
44
-
45
-
46
- def test_time_index(log2):
47
- assert "XKF1" in log2.dfs
48
- assert log2.dfs["XKF1"].timestamp.is_monotonic_increasing
49
33
 
50
34
 
51
35
 
@@ -1,165 +0,0 @@
1
- #!/usr/bin/env python
2
-
3
- '''
4
- example program that dumps a Mavlink log file. The log file is
5
- assumed to be in the format that qgroundcontrol uses, which consists
6
- of a series of MAVLink packets, each with a 64 bit timestamp
7
- header. The timestamp is in microseconds since 1970 (unix epoch)
8
-
9
- This program is free software: you can redistribute it and/or modify it under
10
- the terms of the GNU General Public License as published by the Free Software
11
- Foundation, either version 3 of the License, or (at your option) any later
12
- version.
13
- This program is distributed in the hope that it will be useful, but WITHOUT
14
- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15
- FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16
- You should have received a copy of the GNU General Public License along with
17
- this program. If not, see <http://www.gnu.org/licenses/>.
18
- '''
19
-
20
- from __future__ import print_function
21
-
22
- import array
23
- import fnmatch
24
- import json
25
- import os
26
- import struct
27
- import sys
28
- import time
29
-
30
- import pandas as pd
31
-
32
- try:
33
- from pymavlink.mavextra import *
34
- except:
35
- print("WARNING: Numpy missing, mathematical notation will not be supported..")
36
-
37
- from argparse import ArgumentParser
38
-
39
- import inspect
40
-
41
- from pymavlink import mavutil
42
-
43
-
44
- class Ardupilot(object):
45
-
46
- def __init__(
47
- self,
48
- bin_file,
49
- no_timestamps=False,
50
- planner=False,
51
- robust=False,
52
- condition=None,
53
- types=None,
54
- nottypes=None,
55
- dialect="ardupilotmega",
56
- zero_time_base=False,
57
- source_system=None,
58
- source_component=None,
59
- link=None,
60
- mav10=False
61
- ):
62
- '''
63
- parser.add_argument("--no-timestamps", dest="notimestamps", action='store_true', help="Log doesn't have timestamps")
64
- parser.add_argument("--planner", action='store_true', help="use planner file format")
65
- parser.add_argument("--robust", action='store_true', help="Enable robust parsing (skip over bad data)")
66
- parser.add_argument("--condition", default=None, help="select packets by condition")
67
- parser.add_argument("--types", default=None, help="types of messages (comma separated with wildcard)")
68
- parser.add_argument("--nottypes", default=None, help="types of messages not to include (comma separated with wildcard)")
69
- parser.add_argument("--dialect", default="ardupilotmega", help="MAVLink dialect")
70
- parser.add_argument("--zero-time-base", action='store_true', help="use Z time base for DF logs")
71
- parser.add_argument("--source-system", type=int, default=None, help="filter by source system ID")
72
- parser.add_argument("--source-component", type=int, default=None, help="filter by source component ID")
73
- parser.add_argument("--link", type=int, default=None, help="filter by comms link ID")
74
- parser.add_argument("--mav10", action='store_true', help="parse as MAVLink1")
75
- parser.add_argument("log", metavar="LOG")
76
- '''
77
-
78
- self._parms = None
79
- if not mav10:
80
- os.environ['MAVLINK20'] = '1'
81
-
82
- filename = bin_file
83
- mlog = mavutil.mavlink_connection(filename, planner_format=planner,
84
- notimestamps=no_timestamps,
85
- robust_parsing=robust,
86
- dialect=dialect,
87
- zero_time_base=zero_time_base)
88
-
89
-
90
- types = list(set(types + ['PARM']))
91
-
92
- if nottypes is not None:
93
- nottypes = nottypes.split(',')
94
-
95
- def match_type(mtype, patterns):
96
- '''return True if mtype matches pattern'''
97
- for p in patterns:
98
- if fnmatch.fnmatch(mtype, p):
99
- return True
100
- return False
101
-
102
- # for DF logs pre-calculate types list
103
- match_types=None
104
- if types is not None and hasattr(mlog, 'name_to_id'):
105
- for k in mlog.name_to_id.keys():
106
- if match_type(k, types):
107
- if nottypes is not None and match_type(k, nottypes):
108
- continue
109
- if match_types is None:
110
- match_types = []
111
- match_types.append(k)
112
-
113
- dfs_dicts = {}
114
-
115
- self.read_types = types
116
-
117
- while True:
118
- m = mlog.recv_match(blocking=False, type=match_types)
119
- if m is None:
120
- break
121
-
122
- if not mavutil.evaluate_condition(condition, mlog.messages):
123
- continue
124
- if source_system is not None and source_system != m.get_srcSystem():
125
- continue
126
- if source_component is not None and source_component != m.get_srcComponent():
127
- continue
128
- if link is not None and link != m._link:
129
- continue
130
- if types is not None and m.get_type() != 'BAD_DATA' and not match_type(m.get_type(), types):
131
- continue
132
- if nottypes is not None and match_type(m.get_type(), nottypes):
133
- continue
134
-
135
- # Ignore BAD_DATA messages is the user requested or if they're because of a bad prefix. The
136
- # latter case is normally because of a mismatched MAVLink version.
137
- if m.get_type() == 'BAD_DATA':
138
- continue
139
-
140
- key=m.get_type()
141
-
142
- if not key in dfs_dicts:
143
- dfs_dicts[key] = {}
144
- dfs_dicts[key]['timestamp'] = []
145
- for field in m.get_fieldnames():
146
- dfs_dicts[key][field] = []
147
-
148
- dfs_dicts[key]['timestamp'].append( getattr(m,'_timestamp', 0.0) )
149
-
150
- for field in m.get_fieldnames():
151
- dfs_dicts[key][field].append( getattr(m,field) )
152
-
153
- mlog.filehandle.close()
154
-
155
- self.dfs = {}
156
- for k, v in dfs_dicts.items():
157
- self.dfs[k] = pd.DataFrame(v)
158
- #self.dfs[k].columns = list(v.keys())#[val if val == "timestamp" else k + val for val in v.keys()]
159
- self.parms = self.dfs['PARM'].set_index('Name')['Value'].to_dict()
160
-
161
- def __getattr__(self, name):
162
- if name in self.dfs:
163
- return self.dfs[name]
164
- raise AttributeError(f"No such attribute: {name}")
165
-