Metadata-Version: 2.4
Name: blackbox-parser
Version: 0.1.0
Summary: A modular parser and analysis toolkit for MAVLink (.tlog) and ArduPilot DataFlash (.bin) flight logs.
Author-email: Punit Kumar <punitkumar.pothuraju2007@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/Punit-154/BlackBox-Parser
Project-URL: Documentation, https://github.com/Punit-154/BlackBox-Parser#readme
Project-URL: Repository, https://github.com/Punit-154/BlackBox-Parser.git
Project-URL: Issues, https://github.com/Punit-154/BlackBox-Parser/issues
Keywords: drone,uav,mavlink,ardupilot,telemetry,flight-log,blackbox,tlog,dataflash
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pymavlink>=2.4.41
Requires-Dist: pandas>=2.0.0
Requires-Dist: matplotlib>=3.7.0
Requires-Dist: PyYAML>=6.0
Requires-Dist: fpdf2>=2.7.0
Requires-Dist: folium>=0.14.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Dynamic: license-file

# BlackBox-Parser

[![PyPI version](https://img.shields.io/pypi/v/blackbox-parser.svg)](https://pypi.org/project/blackbox-parser/)
[![Python versions](https://img.shields.io/pypi/pyversions/blackbox-parser.svg)](https://pypi.org/project/blackbox-parser/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A modular parser and telemetry analysis toolkit for drone flight logs.
It fully supports both:
- **MAVLink telemetry logs** (`.tlog`)
- **ArduPilot DataFlash binary logs** (`.bin`)

Use it as a **command-line tool** or as an **importable Python library**.

---

## Features
- **Format Auto-Detection**: Automatically parses `.tlog` and `.bin` logs into a unified internal data schema.
- **Summary**: Generates an overview of flight duration, speed, max altitude, battery usage, cumulative distance, displacement, climb/descent rates, and a chronological flight events timeline.
- **CSV Export**: Extracts telemetry into `output/csv/` for GPS, Attitude, Altitude, and Battery data.
- **Graphs**: Generates PNG visualizations in `output/graphs/` for Altitude, Battery, Speed, Power, and Attitude vs. Time.
- **PDF Report**: Generates a self-contained PDF report with summary, embedded graphs, and warnings in `output/flight_report.pdf`.
- **Flight Track Map**: Generates an interactive HTML map with color-coded flight path (green=slow, red=fast).
- **Anomalies**: Detects critical warnings (low battery, altitude drop, excessive roll/pitch angles).
- **Batch Mode**: Analyze multiple logs at once and compare them in a side-by-side table.
- **Interactive Mode**: Menu-driven interface for users who prefer not to memorize CLI flags.

---

## Installation

### From PyPI
```bash
pip install blackbox-parser
```

### From Source (Development)
```bash
git clone https://github.com/Punit-154/BlackBox-Parser.git
cd BlackBox-Parser

python -m venv venv
venv\Scripts\activate      # On Windows
# source venv/bin/activate # On macOS/Linux

pip install -e .
```

---

## Usage

### 1. Command-Line Interface (CLI)

Once installed, use either `blackbox-parser` or the shortcut `bbparser`:

```bash
# View help
blackbox-parser --help

# Run specific analyses on a .tlog or .bin file
blackbox-parser logs/sample.tlog --summary
blackbox-parser logs/sample.bin --export --graphs

# Run all analysis steps at once (summary, export, graphs, warnings)
blackbox-parser logs/sample.tlog --all

# Generate a self-contained PDF report
blackbox-parser logs/sample.tlog --report

# Generate an interactive flight track map
blackbox-parser logs/sample.tlog --map

# Batch analyze all logs in a folder
blackbox-parser --batch logs/

# Interactive mode (menu-driven)
blackbox-parser --interactive
```

*(You can also continue using `python analyzer.py [args]` from the root directory).*

---

### 2. Python Library SDK

You can also import `blackbox_parser` directly into your Python scripts or Jupyter Notebooks:

```python
import blackbox_parser as bbp

# 1. Parse a log file (.tlog or .bin)
data = bbp.parse_log("logs/flight.tlog")

# 2. Generate summary metrics
stats = bbp.generate_summary(data)
print(f"Flight Duration : {stats['duration_formatted']}")
print(f"Max Altitude    : {stats['max_altitude']} m")
print(f"Total Distance  : {stats['total_distance']} m")

# 3. Detect anomalies and warnings
warnings = bbp.run_all_checks(data)
bbp.print_warnings(warnings)

# 4. Export telemetry data to CSV files
bbp.export_all(data, output_dir="output/csv")

# 5. Generate Matplotlib graphs
bbp.generate_all_graphs(data, output_dir="output/graphs")

# 6. Generate a PDF report and interactive HTML track map
bbp.generate_report(data, output_dir="output")
bbp.generate_track_map(data, output_dir="output")
```

---

## Architecture Notes
The project is built on a "schema normalization" approach:
- `parser.py` maps the different raw messages from `.tlog` (`GPS_RAW_INT`, `ATTITUDE`, etc.) and `.bin` (`GPS`, `ATT`, etc.) into a **common internal data structure** using human-readable units (meters, degrees, m/s, volts).
- Missing data fields in `.bin` files (such as `battery_remaining`, `vx`, `vy`, `vz`, `relative_alt`) are safely filtered out, handled as `None`, or skipped in downstream modules (`summary.py`, `graphs.py`, `anomalies.py`, `exporter.py`) to prevent errors and ensure backward compatibility.
- **Interactive mode** runs an event loop that dispatches user menu selections to the same standalone functions used by the flag-based CLI.

---

## Understanding the Metrics & Technical Background

### Cumulative Flight Distance & Max Displacement
- **What it is**: 
  - **Cumulative Distance**: The total ground distance traveled by the drone over the entire flight.
  - **Max Displacement**: The furthest straight-line distance the drone flew away from its original takeoff point.
- **Why it exists**: Useful for verifying that a flight stayed within required geofence limits (Displacement) and estimating total motor/propulsion work done (Distance).
- **Technical Background**: Calculated using the **Haversine formula**. Because the Earth is a sphere, we cannot use simple 2D Cartesian math (`sqrt(x^2 + y^2)`) for GPS coordinates. The Haversine formula accounts for the curvature of the Earth to accurately measure the great-circle distance between two (Latitude, Longitude) points. 

### Peak Climb & Descent Rates
- **What it is**: The maximum vertical velocity (in m/s) at which the drone gained or lost altitude.
- **Why it exists**: Critical for safety analysis. Rapid descents can cause a drone to enter its own prop-wash (Vortex Ring State), leading to a crash.
- **Technical Background**: Calculated using the discrete derivative of altitude with respect to time (`dz / dt`). By comparing the `relative_alt` at two consecutive timestamps, we can compute the vertical speed.

### Flight Events Timeline
- **What it is**: A chronologically ordered timeline of significant flight events (e.g., "Armed", "Takeoff", "Mode AUTO") printed directly in the terminal summary.
- **Why it exists**: It provides critical context to understand the progression of the flight without needing to open external graphing tools. Knowing when the drone armed or changed flight modes is essential for diagnosing issues.
- **Technical Background**: MAVLink (`.tlog`) and DataFlash (`.bin`) logs contain distinct text strings and event IDs. The analyzer parses `STATUSTEXT`, `MSG`, `MODE`, and `EV` packets, filters for keywords like "arm", "takeoff", or "mode", and formats them into a human-readable chronological timeline.

---

## License
This project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.
