ardupilot-log-reader 0.3.3__tar.gz → 0.4.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.
Files changed (36) hide show
  1. ardupilot_log_reader-0.4.1/.github/workflows/publish_pypi.yml +47 -0
  2. ardupilot_log_reader-0.4.1/.vscode/settings.json +9 -0
  3. ardupilot_log_reader-0.4.1/PKG-INFO +48 -0
  4. ardupilot_log_reader-0.4.1/README.md +36 -0
  5. ardupilot_log_reader-0.4.1/pyproject.toml +27 -0
  6. ardupilot_log_reader-0.4.1/src/ardupilot_log_reader/reader.py +325 -0
  7. ardupilot_log_reader-0.4.1/tests/test_ardupilot.py +162 -0
  8. ardupilot_log_reader-0.4.1/tests/test_reader_contracts.py +131 -0
  9. ardupilot_log_reader-0.4.1/uv.lock +454 -0
  10. ardupilot_log_reader-0.3.3/.github/workflows/publish_pypi.yml +0 -53
  11. ardupilot_log_reader-0.3.3/.vscode/launch.json +0 -16
  12. ardupilot_log_reader-0.3.3/.vscode/settings.json +0 -8
  13. ardupilot_log_reader-0.3.3/PKG-INFO +0 -30
  14. ardupilot_log_reader-0.3.3/ReadMe.md +0 -17
  15. ardupilot_log_reader-0.3.3/ardupilot_log_reader/reader.py +0 -128
  16. ardupilot_log_reader-0.3.3/ardupilot_log_reader.egg-info/PKG-INFO +0 -30
  17. ardupilot_log_reader-0.3.3/ardupilot_log_reader.egg-info/SOURCES.txt +0 -25
  18. ardupilot_log_reader-0.3.3/ardupilot_log_reader.egg-info/dependency_links.txt +0 -1
  19. ardupilot_log_reader-0.3.3/ardupilot_log_reader.egg-info/requires.txt +0 -3
  20. ardupilot_log_reader-0.3.3/ardupilot_log_reader.egg-info/top_level.txt +0 -1
  21. ardupilot_log_reader-0.3.3/bld.bat +0 -2
  22. ardupilot_log_reader-0.3.3/build.sh +0 -1
  23. ardupilot_log_reader-0.3.3/meta.yaml +0 -28
  24. ardupilot_log_reader-0.3.3/pyproject.toml +0 -21
  25. ardupilot_log_reader-0.3.3/requirements.txt +0 -3
  26. ardupilot_log_reader-0.3.3/setup.cfg +0 -4
  27. ardupilot_log_reader-0.3.3/tests/test_ardupilot.py +0 -35
  28. ardupilot_log_reader-0.3.3/tests/test_inputs/00000002.BIN +0 -0
  29. ardupilot_log_reader-0.3.3/tests/test_inputs/00000054.BIN +0 -0
  30. ardupilot_log_reader-0.3.3/tests/test_inputs/00000129.BIN +0 -4
  31. ardupilot_log_reader-0.3.3/tests/test_inputs/2023-07-20 17-52-06.bin +0 -4
  32. ardupilot_log_reader-0.3.3/tests/test_inputs/manual_Generic_Generic_23_05_01_00000129.json +0 -402665
  33. ardupilot_log_reader-0.3.3/tests/test_inputs/test_log_00000052.BIN +0 -0
  34. {ardupilot_log_reader-0.3.3 → ardupilot_log_reader-0.4.1}/.gitignore +0 -0
  35. {ardupilot_log_reader-0.3.3 → ardupilot_log_reader-0.4.1/src}/ardupilot_log_reader/__init__.py +0 -0
  36. /ardupilot_log_reader-0.3.3/tests/__init__.py → /ardupilot_log_reader-0.4.1/src/ardupilot_log_reader/py.typed +0 -0
@@ -0,0 +1,47 @@
1
+ name: Publish to PyPI and GitHub
2
+ # Pushing a tag v<version> publishes that version. The tag must match the
3
+ # version in pyproject.toml; tag the commit that the release deploys.
4
+ on:
5
+ push:
6
+ tags:
7
+ - 'v*'
8
+ permissions:
9
+ contents: write
10
+ jobs:
11
+ publish:
12
+ name: Build, publish to PyPI and create a GitHub release
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - name: Checkout repo
16
+ uses: actions/checkout@v4
17
+
18
+ - name: Install uv
19
+ uses: astral-sh/setup-uv@v3
20
+
21
+ - name: Set up Python
22
+ run: uv python install 3.12
23
+
24
+ - name: Check the tag matches the package version
25
+ id: version
26
+ run: |
27
+ version=$(python3 -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])")
28
+ if [ "${GITHUB_REF_NAME}" != "v${version}" ]; then
29
+ echo "Tag ${GITHUB_REF_NAME} does not match pyproject version ${version}" >&2
30
+ exit 1
31
+ fi
32
+ echo "version=${version}" >> "$GITHUB_OUTPUT"
33
+
34
+ - name: Build
35
+ run: uv build
36
+
37
+ - name: Publish to PyPI
38
+ run: uv publish -t ${{ secrets.PYPI_TOKEN }}
39
+
40
+ - name: Create GitHub release
41
+ env:
42
+ GH_TOKEN: ${{ github.token }}
43
+ VERSION: ${{ steps.version.outputs.version }}
44
+ run: |
45
+ flags=""
46
+ if echo "${VERSION}" | grep -q '[a-z]'; then flags="--prerelease"; fi
47
+ gh release create "${GITHUB_REF_NAME}" dist/* --title "${GITHUB_REF_NAME}" --generate-notes --verify-tag ${flags}
@@ -0,0 +1,9 @@
1
+ {
2
+ "python.testing.pytestArgs": [
3
+ "tests"
4
+ ],
5
+ "python.testing.unittestEnabled": false,
6
+ "python.testing.pytestEnabled": true,
7
+ "python-envs.defaultEnvManager": "ms-python.python:conda",
8
+ "python-envs.defaultPackageManager": "ms-python.python:conda"
9
+ }
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.5
2
+ Name: ardupilot_log_reader
3
+ Version: 0.4.1
4
+ Summary: module to read ardupilot binary logs to memory
5
+ Author-email: Thomas David <thomasdavid0@gmail.com>
6
+ Requires-Python: >=3.12
7
+ Requires-Dist: numpy>=2.1.3
8
+ Requires-Dist: pandas>=2.2.3
9
+ Provides-Extra: pymavlink
10
+ Requires-Dist: pymavlink>=2.4.42; extra == 'pymavlink'
11
+ Description-Content-Type: text/markdown
12
+
13
+ # Ardupilot Log Reader
14
+
15
+ This package is a bit like mavlogdump in pymavlink. It reads an ardupilot log to a pandas dataframe.
16
+
17
+ ## usage
18
+
19
+ Set up script
20
+ ```
21
+ from ardupilot_log_reader import Ardupilot
22
+ import sys
23
+
24
+ def read_bin_file(file_path):
25
+ # Create a parser instance with specific message types we want to read
26
+ types = ['ATT', 'BAT', 'AHR2', 'CTUN', 'CTRL', 'ESC', 'IMU', 'RCIN', 'VIBE']
27
+ parser = Ardupilot.parse(file_path, types=types)
28
+
29
+ # Print available message types and their columns
30
+ print("\nAvailable message types and their columns:")
31
+ for msg_type, df in parser.dfs.items():
32
+ print(f"\n{msg_type} columns:")
33
+ for col in df.columns:
34
+ print(f" - {col}")
35
+
36
+ if __name__ == "__main__":
37
+ if len(sys.argv) != 2:
38
+ print("Usage: python test_log_reader.py <path_to_bin_file>")
39
+ sys.exit(1)
40
+
41
+ bin_file_path = sys.argv[1]
42
+ read_bin_file(bin_file_path)
43
+ ```
44
+
45
+ Run script:
46
+ ```
47
+ python <script-name>.py <path-to-bin-file>
48
+ ```
@@ -0,0 +1,36 @@
1
+ # Ardupilot Log Reader
2
+
3
+ This package is a bit like mavlogdump in pymavlink. It reads an ardupilot log to a pandas dataframe.
4
+
5
+ ## usage
6
+
7
+ Set up script
8
+ ```
9
+ from ardupilot_log_reader import Ardupilot
10
+ import sys
11
+
12
+ def read_bin_file(file_path):
13
+ # Create a parser instance with specific message types we want to read
14
+ types = ['ATT', 'BAT', 'AHR2', 'CTUN', 'CTRL', 'ESC', 'IMU', 'RCIN', 'VIBE']
15
+ parser = Ardupilot.parse(file_path, types=types)
16
+
17
+ # Print available message types and their columns
18
+ print("\nAvailable message types and their columns:")
19
+ for msg_type, df in parser.dfs.items():
20
+ print(f"\n{msg_type} columns:")
21
+ for col in df.columns:
22
+ print(f" - {col}")
23
+
24
+ if __name__ == "__main__":
25
+ if len(sys.argv) != 2:
26
+ print("Usage: python test_log_reader.py <path_to_bin_file>")
27
+ sys.exit(1)
28
+
29
+ bin_file_path = sys.argv[1]
30
+ read_bin_file(bin_file_path)
31
+ ```
32
+
33
+ Run script:
34
+ ```
35
+ python <script-name>.py <path-to-bin-file>
36
+ ```
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "ardupilot_log_reader"
3
+ version = "0.4.1"
4
+ description = "module to read ardupilot binary logs to memory"
5
+ readme = "README.md"
6
+ authors = [{ name = "Thomas David", email = "thomasdavid0@gmail.com" }]
7
+ requires-python = ">=3.12"
8
+ dependencies = [
9
+ "numpy>=2.1.3",
10
+ "pandas>=2.2.3",
11
+ ]
12
+
13
+
14
+ [project.optional-dependencies]
15
+ pymavlink = ["pymavlink>=2.4.42"]
16
+
17
+ [build-system]
18
+ requires = ["hatchling"]
19
+ build-backend = "hatchling.build"
20
+
21
+ [dependency-groups]
22
+ dev = ["pytest>=8.3.3"]
23
+ lint = ["ruff>=0.7.3"]
24
+
25
+ [tool.hatch.build.targets.sdist]
26
+ # The test logs and the pymavlink field dump are well over PyPI's 100 MB file limit.
27
+ exclude = ["tests/test_inputs", "pymavlink_bin_fields.json"]
@@ -0,0 +1,325 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import fnmatch
5
+ import logging
6
+ import os
7
+ from dataclasses import dataclass
8
+ from json import dump, load
9
+ from pathlib import Path
10
+ from typing import Literal
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+ try:
16
+ from pymavlink.DFReader import DFReader_binary
17
+
18
+ HAS_PYMAVLINK = True
19
+ except ImportError:
20
+ type DFReader_binary = None
21
+ HAS_PYMAVLINK = False
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ try:
27
+ import schemas as s
28
+ HAS_SCHEMAS = True
29
+ except ImportError:
30
+ HAS_SCHEMAS = False
31
+
32
+ @dataclass
33
+ class Ardupilot:
34
+ filename: str
35
+ dfs: dict[str, pd.DataFrame]
36
+ source: Literal["bin_file", "web_compressed", "web_array", "web_legacy"]
37
+
38
+ def __getattr__(self, name):
39
+ if name in self.dfs:
40
+ return self.dfs[name]
41
+ raise AttributeError(f"No such attribute: {name}")
42
+
43
+ @staticmethod
44
+ def process_patterns(
45
+ available: list[str],
46
+ patterns: list[str] | None = None,
47
+ exclude_patterns: list[str] | None = None,
48
+ ):
49
+ def match_type(mtype, patterns):
50
+ for p in patterns:
51
+ if fnmatch.fnmatch(mtype, p):
52
+ return True
53
+ return False
54
+
55
+ patterns = available if patterns is None else patterns
56
+ exclude_patterns = [] if exclude_patterns is None else exclude_patterns
57
+ return [
58
+ k
59
+ for k in available
60
+ if match_type(k, patterns) and not match_type(k, exclude_patterns)
61
+ ]
62
+
63
+ @staticmethod
64
+ def parse(
65
+ bin_file,
66
+ types=None,
67
+ nottypes=None,
68
+ zero_time_base=False,
69
+ source_system=None,
70
+ source_component=None,
71
+ link=None,
72
+ mav10=False,
73
+ cache_file: str | Path | bool = False,
74
+ ) -> Ardupilot:
75
+ """
76
+ Parses a binary file into an Ardupilot object.
77
+
78
+ Parameters:
79
+ bin_file (str): The binary file to parse.
80
+ types (list[str], optional): List of types or patterns to include in the parsing. Defaults to None.
81
+ nottypes (list[str], optional): List of types or patterns to exclude from the parsing. Defaults to None.
82
+ zero_time_base (bool, optional): If True, sets the time base to zero. Defaults to False.
83
+ source_system (int, optional): The source system ID to filter messages by. Defaults to None (all systems in log).
84
+ source_component (int, optional): The source component ID to filter messages by. Defaults to None (all components in log).
85
+ link (int, optional): The link to filter messages by. Defaults to None.
86
+ mav10 (bool, optional): If True, uses MAVLink 1.0. Defaults to False.
87
+
88
+ Returns:
89
+ Ardupilot: The parsed Ardupilot object.
90
+ """
91
+ if types is None:
92
+ types = [
93
+ "POS",
94
+ "ATT",
95
+ "IMU",
96
+ "XKF1",
97
+ "XKF2",
98
+ "ERR",
99
+ "GPS",
100
+ "ORGN",
101
+ "RCOU",
102
+ "RCIN",
103
+ ]
104
+ if cache_file:
105
+ cache_file = (
106
+ Path(bin_file).with_suffix(".json")
107
+ if cache_file is True
108
+ else Path(cache_file)
109
+ )
110
+ if cache_file.exists():
111
+ with open(cache_file, "r") as f:
112
+ data = load(f)
113
+ return Ardupilot.from_dict(data)
114
+
115
+ if not HAS_PYMAVLINK:
116
+ raise ImportError(
117
+ "pymavlink is required to parse Ardupilot logs. Please install it."
118
+ )
119
+ if not mav10:
120
+ os.environ["MAVLINK20"] = "1"
121
+
122
+ mlog: DFReader_binary = DFReader_binary(
123
+ str(bin_file), zero_time_base=zero_time_base
124
+ )
125
+
126
+ try:
127
+ match_types = Ardupilot.process_patterns(
128
+ list(mlog.name_to_id.keys()), list(set(types + ["PARM"])), nottypes
129
+ )
130
+ log = Ardupilot._parse(mlog, match_types, source_system, source_component, link)
131
+ finally:
132
+ mlog.filehandle.close()
133
+
134
+ if cache_file:
135
+ with open(cache_file, "w") as f:
136
+ dump(log.to_dict(), f, indent=4)
137
+
138
+ return log
139
+
140
+ @staticmethod
141
+ def _parse(
142
+ mlog: DFReader_binary,
143
+ cols: list[str],
144
+ src_system=None,
145
+ src_component=None,
146
+ link=None,
147
+ ):
148
+ dfs_dicts = {}
149
+
150
+ while True:
151
+ m = mlog.recv_match(blocking=False, type=cols)
152
+ if m is None:
153
+ break
154
+ if src_system is not None and src_system != m.get_srcSystem():
155
+ continue
156
+ if src_component is not None and src_component != m.get_srcComponent():
157
+ continue
158
+ if link is not None and link != m._link:
159
+ continue
160
+
161
+ key = m.get_type()
162
+ if key == "POS":
163
+ pass
164
+ if key not in dfs_dicts:
165
+ if key == "BAD_DATA":
166
+ continue
167
+ dfs_dicts[key] = {}
168
+ dfs_dicts[key]["timestamp"] = []
169
+ for field in m.get_fieldnames():
170
+ dfs_dicts[key][field] = []
171
+
172
+ dfs_dicts[key]["timestamp"].append(getattr(m, "_timestamp", 0.0))
173
+
174
+ for field in m.get_fieldnames():
175
+ dfs_dicts[key][field].append(getattr(m, field))
176
+
177
+ return Ardupilot(
178
+ mlog.filehandle.name,
179
+ {k: pd.DataFrame(v) for k, v in dfs_dicts.items()},
180
+ "bin_file",
181
+ )._correct_timestamps()
182
+
183
+ def parameters(self) -> dict[str, pd.DataFrame]:
184
+ gb = self.PARM.groupby("Name")
185
+
186
+ parms = {}
187
+ for gn in gb.groups:
188
+ gr = gb.get_group(gn)
189
+ parms[gn] = gr.loc[
190
+ abs(gr.Value.diff().fillna(1)) > 0, ["timestamp", "TimeUS", "Value"]
191
+ ].set_index("timestamp")
192
+ return parms
193
+
194
+ def to_dict(self, **kwargs) -> dict[str, dict[str, list]]:
195
+ return {
196
+ "filename": self.filename,
197
+ "data": {k: Ardupilot.write_df(v, **kwargs) for k, v in self.dfs.items()},
198
+ "source": self.source,
199
+ }
200
+
201
+ @staticmethod
202
+ def write_df(df: pd.DataFrame, **kwargs) -> dict[str, list | str]:
203
+ return {k: Ardupilot.write_column(v, **kwargs) for k, v in df.items()}
204
+
205
+ @staticmethod
206
+ def write_column(
207
+ data: pd.Series, mode: Literal["list", "base64", "records"] = "base64"
208
+ ) -> str | list | dict:
209
+ if mode == "records":
210
+ return data.to_dict()
211
+ elif mode == "list":
212
+ return data.tolist()
213
+ elif mode == "base64":
214
+ if data.dtype == np.float64:
215
+ return base64.b64encode(data.to_numpy().tobytes()).decode("utf-8")
216
+ else:
217
+ return data.tolist()
218
+
219
+ @staticmethod
220
+ def from_dict(data: dict[str, dict[str, list]]) -> Ardupilot:
221
+ return Ardupilot(
222
+ data.get("filename", "unknown"),
223
+ Ardupilot._process_dict(data.get("data", data)),
224
+ source=data.get("source", "web_legacy"),
225
+ )._correct_timestamps()
226
+
227
+ @staticmethod
228
+ def parse_schema(data) -> Ardupilot:
229
+ if not HAS_SCHEMAS:
230
+ raise ImportError("Schemas not available")
231
+ _d: s.NewBinData | s.LegacyBinData = data
232
+
233
+ return Ardupilot.from_dict(_d.model_dump())
234
+
235
+ @staticmethod
236
+ def _process_dict(bindata: dict[str, dict[str, list]]) -> dict[str, pd.DataFrame]:
237
+ # dfs = {k: pd.DataFrame(v) for k,v in bindata.items()}
238
+
239
+ dfs: dict[str, pd.DataFrame] = {}
240
+ groups = {}
241
+ for k, v in bindata.items():
242
+ new_df = Ardupilot.parse_df(v)
243
+ if new_df is not None:
244
+ if "[" not in k:
245
+ dfs[k] = new_df
246
+ else:
247
+ nk = k.split("[")[0]
248
+ if nk not in groups:
249
+ groups[nk] = []
250
+ groups[nk].append(new_df)
251
+
252
+ for k, v in groups.items():
253
+ dfs[k] = pd.concat(v)
254
+
255
+ def process_df(df: pd.DataFrame) -> pd.DataFrame:
256
+ if "TimeUS" not in df.columns:
257
+ df.insert(0, "TimeUS", np.floor(df.time_boot_s * 1e6).astype(int))
258
+ if "timestamp" not in df.columns:
259
+ df.insert(0, "timestamp", df.TimeUS / 1e6)
260
+
261
+ df = df.drop(columns="time_boot_s", errors="ignore").reset_index(drop=True)
262
+
263
+ colsort = ["TimeUS" if "TimeUS" in df.columns else "time_boot_s"]
264
+ for core_col in ["I", "C"]:
265
+ if core_col in df.columns:
266
+ colsort.append(core_col)
267
+ break
268
+ df = df.sort_values(colsort)
269
+ return df
270
+
271
+ dfs = {k: process_df(v) for k, v in dfs.items() if not v.empty}
272
+
273
+ return dfs
274
+
275
+ def _correct_timestamps(self):
276
+
277
+ if "GPS" in self.dfs:
278
+ gps = self.dfs["GPS"]
279
+
280
+ start_time = (
281
+ Ardupilot._gpsTimeToTime(
282
+ gps.GWk.iloc[0],
283
+ gps.GMS.iloc[0],
284
+ )
285
+ - (gps.TimeUS / 1e6).iloc[0]
286
+ )
287
+ else:
288
+ start_time = 0
289
+
290
+ return Ardupilot(
291
+ self.filename,
292
+ {
293
+ k: v.assign(timestamp=v.timestamp + start_time)
294
+ if v.timestamp[0] < start_time
295
+ else v
296
+ for k, v in self.dfs.items()
297
+ },
298
+ self.source
299
+ )
300
+
301
+ @staticmethod
302
+ def _gpsTimeToTime(week, msec):
303
+ """convert GPS week and TOW to a time in seconds since 1970"""
304
+ epoch = 86400 * (10 * 365 + int((1980 - 1969) / 4) + 1 + 6 - 2)
305
+ return epoch + 86400 * 7 * week + msec * 0.001 - 18
306
+
307
+ @staticmethod
308
+ def parse_df(data: dict[str, list | str], **kwargs) -> pd.DataFrame:
309
+ df = pd.DataFrame(
310
+ {k: Ardupilot.process_column(k, v) for k, v in data.items()}, **kwargs
311
+ )
312
+
313
+ return df
314
+
315
+ @staticmethod
316
+ def process_column(name: str, data: str | list | dict) -> pd.Series:
317
+ if isinstance(data, str):
318
+ _data = np.frombuffer(base64.b64decode(data), dtype=np.float64)
319
+ return pd.Series(_data, name=name)
320
+ elif isinstance(data, list):
321
+ return pd.Series(data, name=name)
322
+ elif isinstance(data, dict):
323
+ return pd.Series(data, name=name).reset_index(drop=True)
324
+ else:
325
+ raise TypeError(f"Unsupported data type for column {name}: {type(data)}")
@@ -0,0 +1,162 @@
1
+ """
2
+ This program is free software: you can redistribute it and/or modify it under
3
+ the terms of the GNU General Public License as published by the Free Software
4
+ Foundation, either version 3 of the License, or (at your option) any later
5
+ version.
6
+ This program is distributed in the hope that it will be useful, but WITHOUT
7
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8
+ FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
9
+ You should have received a copy of the GNU General Public License along with
10
+ this program. If not, see <http://www.gnu.org/licenses/>.
11
+ """
12
+
13
+ import base64
14
+ import struct
15
+ from json import load
16
+ from pathlib import Path
17
+
18
+ from pytest import fixture, mark, raises
19
+
20
+ from ardupilot_log_reader.reader import Ardupilot
21
+ import numpy as np
22
+ import pandas as pd
23
+
24
+ TEST_INPUTS = Path(__file__).parent / "test_inputs"
25
+
26
+
27
+ @fixture(scope="session")
28
+ def type_request():
29
+ return [
30
+ "XKF1",
31
+ "XKQ1",
32
+ "ARSP",
33
+ "GPS",
34
+ "RCIN",
35
+ "RCOU",
36
+ "IMU",
37
+ "BARO",
38
+ "MODE",
39
+ "RPM",
40
+ "MAG",
41
+ ]
42
+
43
+
44
+ @fixture(scope="session")
45
+ def log(type_request):
46
+ return Ardupilot.parse(
47
+ Path(__file__).parent / "test_inputs/test_log_00000052.BIN",
48
+ types=type_request,
49
+ zero_time_base=True,
50
+ )
51
+
52
+
53
+ @fixture(scope="session")
54
+ def log2(type_request):
55
+ return Ardupilot.parse(
56
+ Path(__file__).parent / "test_inputs/00000129.BIN",
57
+ types=type_request,
58
+ zero_time_base=True,
59
+ )
60
+
61
+
62
+ def test_dfs(type_request, log):
63
+ assert set(log.dfs.keys()) == set(type_request + ["PARM"])
64
+
65
+
66
+ @fixture(scope="session")
67
+ def old_web_bin():
68
+ with (TEST_INPUTS / "old_web_bin.json").open("r") as f:
69
+ return Ardupilot.from_dict(load(f))
70
+
71
+
72
+ @fixture(scope="session")
73
+ def new_web_bin():
74
+ with (TEST_INPUTS / "new_web_bin.json").open("r") as f:
75
+ return Ardupilot.from_dict(load(f))
76
+
77
+ @fixture(scope="session")
78
+ def raw_bin():
79
+ return Ardupilot.parse(
80
+ TEST_INPUTS / "raw_web_bin.BIN",
81
+ types=["POS", "ATT", "XKF1", "XKF2", "IMU", "GPS", "ERR"],
82
+ zero_time_base=True,
83
+ )
84
+
85
+
86
+ def assert_dfs_match(bin1: Ardupilot, bin2: Ardupilot):
87
+ matches = {}
88
+ throw = False
89
+ for k in bin1.dfs:
90
+ try:
91
+ pd.testing.assert_frame_equal(
92
+ bin1.dfs[k].reset_index(drop=True),
93
+ bin2.dfs[k].reset_index(drop=True),
94
+ check_dtype=False,
95
+ rtol=0.1,
96
+ )
97
+ matches[k] = True
98
+ except AssertionError as e:
99
+ matches[k] = f"DataFrames for {k} are not equal: {e}"
100
+ throw = True
101
+ if throw:
102
+ match_summary = "\n".join(
103
+ [f"\n{v}" for v in matches.values() if v is not True]
104
+ )
105
+ raise AssertionError(f"DataFrames {','.join(m for m in matches if matches[m] is not True)} do not match:\n{match_summary}")
106
+
107
+
108
+ def test_old_web_bin_matches_raw_bin(raw_bin: Ardupilot, old_web_bin: Ardupilot):
109
+ assert_dfs_match(raw_bin, old_web_bin)
110
+
111
+ def test_new_web_bin_matches_raw_bin(
112
+ raw_bin: Ardupilot, new_web_bin: Ardupilot
113
+ ):
114
+ assert_dfs_match(raw_bin, new_web_bin)
115
+
116
+
117
+ @mark.xfail(
118
+ raises=TypeError,
119
+ strict=True,
120
+ reason="D04/coordinator review by 2026-11-26: CompressedBinColumn decoding pending",
121
+ )
122
+ def test_schema_compressed_web_bin_matches_raw_bin(raw_bin: Ardupilot):
123
+ """Keep the identified compressed counterpart visible until decoding exists."""
124
+ with (Path(__file__).parent / "test_inputs/new_web_bin_compressed.json").open() as f:
125
+ compressed_web_bin = Ardupilot.from_dict(load(f))
126
+ assert_dfs_match(raw_bin, compressed_web_bin)
127
+
128
+
129
+ def test_base64_web_bin_columns_match_checked_in_array_data():
130
+ """The reader's base64 form is native float64 bytes, encoded as base64."""
131
+ with (Path(__file__).parent / "test_inputs/new_web_bin.json").open() as f:
132
+ array_data = load(f)
133
+
134
+ columns = ("TimeUS", "Lat", "Lng", "Alt")
135
+ expected = {
136
+ name: array_data["POS"][name][:5]
137
+ for name in columns
138
+ }
139
+ encoded = {
140
+ name: base64.b64encode(
141
+ struct.pack("=" + "d" * len(values), *values)
142
+ ).decode("ascii")
143
+ for name, values in expected.items()
144
+ }
145
+
146
+ parsed = Ardupilot.from_dict(
147
+ {"filename": "small-web-bin", "source": "web_compressed", "data": {"POS": encoded}}
148
+ )
149
+
150
+ frame = parsed.dfs["POS"]
151
+ assert list(parsed.dfs) == ["POS"]
152
+ assert frame.shape == (5, 5) # four supplied columns plus derived timestamp
153
+ assert frame.TimeUS.tolist() == expected["TimeUS"]
154
+ for name in ("Lat", "Lng", "Alt"):
155
+ assert frame[name].tolist() == expected[name]
156
+ assert frame.timestamp.tolist() == [value / 1e6 for value in expected["TimeUS"]]
157
+
158
+
159
+ def test_base64_web_bin_column_rejects_incomplete_float64_bytes():
160
+ incomplete_double = base64.b64encode(b"\x00").decode("ascii")
161
+ with raises(ValueError):
162
+ Ardupilot.process_column("Alt", incomplete_double)