# fg1/bleheartratelogger architecture

> Architecture diagram of the GitHub repository fg1/bleheartratelogger, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-13). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/fg1/bleheartratelogger
- Repository: https://github.com/fg1/bleheartratelogger

## Overview

Summary of project type and purpose
- Type: Small single-process CLI utility / data-logger written in Python for Linux.
- Purpose: Connect to a Bluetooth Low-Energy (BLE) heart-rate monitor (HRM) device using system BLE tools (hcitool/gatttool), parse the output, and store heart-rate and RR (heart-rate variability) values into a local sqlite database. It is a device-integration and persistence tool, not a web service or microservice.

##### Top-level architectural analysis (from file tree + README)
- Single main executable script: BLEHeartRateLogger.py — contains the entire runtime logic (device discovery, connection establishment, data parsing, persistence and CLI options).
- Config example: BLEHeartRateLogger.conf.example — runtime settings (likely: MAC override, battery check flag, gatttool path, output filename).
- Packaging metadata: setup.py — indicates it's packaged as a Python script / module.
- External system dependencies: hcitool, gatttool, Python pexpect, BlueZ stack (Linux).
- Persistence: sqlite database file written by the script.
- Execution context: Linux user environment; requires root or capabilities set on hcitool/hciconfig.

##### Main components
- External BLE Device(s): e.g., Polar H7, Zephyr HxM, Wahoo TICKR — emits BLE advertisements and GATT notifications.
- Linux Host OS and BlueZ stack: kernel BLE controller + Bluetooth stack; provides low-level BLE capability to tools.
- System BLE Tools: hcitool and gatttool (executables; used by the script to discover and talk to device).
- BLEHeartRateLogger Process (Python runtime):
- CLI / Argument Parser (presentation layer: -m, -b, -g, -o, -v)
- Discovery & Connection Manager (invokes hcitool lescan / gatttool -I connect)
- BLE Interaction Layer (pexpect wrapper processes talking to gatttool/hcitool)
- Parser / Decoder for HRM GATT notifications (hex -> HR value, RR intervals)
- Persistence Layer (sqlite3): write heart rate + timestamps + RR to DB file
- Logging & Error handling: console/log file output, reconnection logic
- Config loader (reads conf example or CLI args)
- Local sqlite DB file (output: file on disk)
- Operator (user) — invokes the CLI, may ctrl-C to stop
- Optional: systemd/service manager if deployed as background service (mention as extension)

##### Important architectural patterns and design principles
- Integration pattern: External process wrapping — the script integrates with BLE devices indirectly by controlling system tools (hcitool/gatttool) via pexpect. Represent this as "Process Adapter" or "System Tool Adapter".
- Layered separation (recommended representation even if implemented in one file):
- Presentation (CLI + config)
- Integration / Adapter layer (pexpect to gatttool/hcitool)
- Domain logic (parse HRM messages)
- Persistence (sqlite)
- Resilience concerns: reconnection loops, timeouts, error handling — include these as annotations on the connection manager component.
- Security/Permissions: drawing should emphasize host-level capability requirement (root or setcap).
- Single-process vs distributed: this is a single-process local tool — do not show microservices. Keep it simple: one runtime process interacting with external device and DB.

##### Relevant technologies, libs and OS elements to label
- Python runtime (interpreter)
- pexpect (used to script gatttool/hcitool)
- hcitool, gatttool (executables from BlueZ)
- BlueZ (Linux Bluetooth stack / kernel interface)
- sqlite3 (local DB)
- setcap / root privileges (cap_net_raw / cap_net_admin) — permission model
- Optional: packaging via setup.py; config via .conf example

- Error & reconnect flow: a small flowchart showing reconnection attempts and logging on failure.

##### Specific elements to include (explicit checklist
- Discovery: BLEHeartRateLogger → hcitool (lescan) → BLE device
- /subscribe: BLEHeartRateLogger → gatttool (connect, characteristics, subscribe)
- Notifications: BLE device → gatttool → BLEHeartRateLogger (notifications containing HR/ RR)
- Persistence: BLEHeartRateLogger → sqlite DB (INSERT timestamp, HR, RR)
- Logging: BLEHeartRateLogger → console/log
- Permissions: Host OS → hcitool/hciconfig setcap / root privilege
- Pexpect as the mechanism bridging the Python process and the system tools.
- Config file / CLI options feeding into the BLEHeartRateLogger Process.
- User/operator and mention Ctrl-C to stop (signal handling).

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% Top-down layout
    %% User / CLI
    User["Operator / User"]:::user
    CLI["CLI & Config Loader"]:::config
    User -->|start/stop| CLI
    click CLI "https://github.com/fg1/bleheartratelogger/blob/master/BLEHeartRateLogger.conf.example"

    %% Host OS and BlueZ
    subgraph "Linux Host (BlueZ & System Tools)"
        Kernel["Linux Kernel + BlueZ (Bluetooth stack)"]:::bluez
        Tools["System BLE Tools: hcitool / gatttool"]:::tools
        Permissions["Permissions: root or setcap(cap_net_raw/cap_net_admin)"]:::security
        Kernel --> Tools
        Tools -->|requires_permissions| Permissions
    end

    %% Python process (center)
    subgraph "BLEHeartRateLogger Process (single Python runtime)"
        APP["BLEHeartRateLogger.py (Python runtime)"]:::appmain
        CLI_in["ArgumentParser (CLI flags -m,-b,-g,-o,-v)"]:::appcomp
        ConfigLoader["Config Loader (.conf example)"]:::appcomp
        Discovery["Discovery & Connection Manager"]:::appcomp
        Adapter["Integration Adapter (pexpect → hcitool/gatttool)"]:::adapter
        Parser["HRM Parser/Decoder (HR & RR extraction)"]:::appcomp
        Persistence["Persistence Layer (sqlite writes)"]:::dbcomp
        Logger["Logging & Error handling / Reconnect logic / Signal handling (Ctrl-C)"]:::appcomp

        APP --> CLI_in
        APP --> ConfigLoader
        APP --> Discovery
        Discovery --> Adapter
        Adapter --> Parser
        Parser --> Persistence
        APP --> Logger

        click APP "https://github.com/fg1/bleheartratelogger/blob/master/BLEHeartRateLogger.py"
        click CLI_in "https://github.com/fg1/bleheartratelogger/blob/master/BLEHeartRateLogger.py"
        click ConfigLoader "https://github.com/fg1/bleheartratelogger/blob/master/BLEHeartRateLogger.conf.example"
        click Discovery "https://github.com/fg1/bleheartratelogger/blob/master/BLEHeartRateLogger.py"
        click Adapter "https://github.com/fg1/bleheartratelogger/blob/master/BLEHeartRateLogger.py"
        click Parser "https://github.com/fg1/bleheartratelogger/blob/master/BLEHeartRateLogger.py"
        click Persistence "https://github.com/fg1/bleheartratelogger/blob/master/BLEHeartRateLogger.py"
        click Logger "https://github.com/fg1/bleheartratelogger/blob/master/BLEHeartRateLogger.py"
    end

    %% External BLE Devices (right side)
    subgraph "External BLE Devices"
        HRM["BLE Heart-Rate Monitors (Polar H7, Zephyr HxM, Wahoo TICKR)"]:::device
    end

    %% Database on disk
    DB[(sqlite DB file<br/>heart_rate, rr, timestamp)]:::database

    %% Packaging and docs (bottom)
    Docs["Project Docs & Packaging"]:::docs
    README["README.md"]:::docsfile
    SetupPy["setup.py (packaging & deps)"]:::docsfile
    CHANGES["CHANGES"]:::docsfile
    LICENSE["LICENSE"]:::docsfile

    Docs --> README
    Docs --> SetupPy
    Docs --> CHANGES
    Docs --> LICENSE

    click README "https://github.com/fg1/bleheartratelogger/blob/master/README.md"
    click SetupPy "https://github.com/fg1/bleheartratelogger/blob/master/setup.py"
    click CHANGES "https://github.com/fg1/bleheartratelogger/tree/master/CHANGES"
    click LICENSE "https://github.com/fg1/bleheartratelogger/tree/master/LICENSE"

    %% Primary interactions and data flows (arrows labeled without spaces)
    CLI -->|start_with_flags| APP
    ConfigLoader -->|provides_config| APP

    APP -->|invoke_lescan| Tools
    Tools -->|lescan_results| APP
    APP -->|gatttool_connect_subscribe| Tools
    Tools -->|ATT_requests| HRM
    HRM -->|GATT_notifications| Tools
    Tools -->|notification_via_pexpect| Adapter
    Adapter -->|raw_hex_notifications| Parser
    Parser -->|parsed_records| Persistence
    Persistence -->|INSERT_rows| DB
    APP -->|write_logs| Logger
    Logger -->|console_syslog| User

    %% Host permissions dependency
    Permissions -->|enforced_on| Tools
    Permissions -.->|required_by| APP

    %% Reconnect and error handling feedback
    HRM -.->|connection_lost| APP
    APP -->|reconnect_attempt| Discovery
    APP -->|on_error_log_and_retry| Logger

    %% Notes and annotations
    NoteSecurity["Note: Requires BlueZ>=v5 and root or setcap on hcitool/hciconfig"]:::note
    NoteSingleFile["Single-file implementation: consider refactor into modules<br/>(Discovery, Adapter, Parser, Persistence)"]:::note
    APP --> NoteSingleFile
    Permissions --> NoteSecurity

    %% Layout hints to keep diagram vertical: groupings above/below
    User ---|uses CLI| CLI
    APP --- DB
    APP --- Kernel
    HRM --- Tools

    %% Legend
    subgraph "Legend"
        L1["Blue: External/Hardware"]:::bluez
        L2["Green: Host OS & System Tools"]:::tools
        L3["Orange: Application & subcomponents"]:::app
        L4["Grey: Persistence (sqlite)"]:::database
        L5["Red: Security/Permissions"]:::security
    end

    %% Styling
    classDef user fill:#E8F0FE,stroke:#2B66D6,color:#0B2A66;
    classDef config fill:#FFF4E5,stroke:#E09A00,color:#6B3E00;
    classDef host fill:#E8FFF0,stroke:#2E8B57,color:#135D38;
    classDef bluez fill:#D7EEFF,stroke:#1E6FFF,color:#07387A;
    classDef tools fill:#DFF3E6,stroke:#2AA05A,color:#064B20;
    classDef security fill:#FFDDE0,stroke:#D1323A,color:#7A0F1A;
    classDef app fill:#FFF3E6,stroke:#E67A00,color:#5A3400;
    classDef appmain fill:#FFE8D6,stroke:#E65A00,color:#5A2A00;
    classDef appcomp fill:#FFF7ED,stroke:#E6A96A,color:#6B3E00;
    classDef adapter fill:#FFEFD9,stroke:#E6B800,color:#5A3E00;
    classDef dbcomp fill:#F2F2F2,stroke:#7D7D7D,color:#222222;
    classDef database fill:#F5F7FA,stroke:#9AA7B2,color:#222222;
    classDef docs fill:#F3F3FF,stroke:#6B6BE6,color:#1E1E7A;
    classDef docsfile fill:#F7F7FF,stroke:#9A9AF7,color:#1E1E7A;
    classDef devices fill:#E8F6FF,stroke:#1E90FF,color:#003366;
    classDef device fill:#DFF0FF,stroke:#1E90FF,color:#003366;
    classDef note fill:#FFF3F8,stroke:#D66B9A,color:#5A1F3A;
    classDef legend fill:#FFFFFF,stroke:#DDDDDD,color:#333333;
```
