# Overspeed Algorithm Documentation

## Overview
The Overspeed Generation system works by aggregating data from two sources:
1.  **Calculated Overspeed**: Analyzes raw GPS positions to detect sustained speeding.
2.  **Explicit Events**: Captures "hard" alarms sent directly by the device hardware.

The final count for a trip is the combination of these detections.

---

## 1. Calculated Overspeed
**Location**: `App\Services\EcoDrivingService::calculateOverspeed`

This method iterates through the sequence of GPS positions for a trip.

### Configuration
*   **Speed Limit**: Currently set to **127** (Raw Values).
*   **Duration Threshold**: **30 Seconds**.

### Logic Flow
1.  **Iterate Points**: The system loops through every GPS point in the trip.
    > *Note*: The system uses the **RAW** speed value from the database. No conversion (Knots to Km/h) is applied, based on legacy data compatibility requirements.

2.  **Check Speed**:
    *   `IF row->speed > SpeedLimit (127)`:
        *   If this is the *start* of a violation, mark the **Start Time**.
        *   Continue tracking as long as subsequent points remain above the limit.

3.  **End Event**:
    *   When speed drops below the limit (or the trip ends), the event is closed.

4.  **Duration Check (The 30-Second Rule)**:
    *   Calculates `Duration = End Time - Start Time`.
    *   `IF Duration > 30 seconds`: **+1 Event Count**.
    *   `IF Duration <= 30 seconds`: **Ignored** (considered a short burst or GPS noise).

---

## 2. Explicit Events
**Location**: `App\Services\TripsProcessingService`

Since the calculated logic strictly requires a 30-second duration, it might miss short but critical violations detected by the hardware itself. To cover this:

### Logic Flow
1.  **Inspect Payload**: The system checks the `other` column (XML data) of the trip points.
2.  **Match Tags**: It searches for:
    *   `<io253>` (Common tag for driving behavior alarms).
    *   The explicit string `"overspeed"`.
3.  **Action**: If found, these are counted as valid events **regardless of duration**.

---

## 3. Final Aggregation
The `TripsProcessingService` compares the results:
*   It takes the events found by the **Explicit** check.
*   It adds events from the **Calculated** check (if not redundant).
*   The final sum is stored in the `device_trips_summary` table under the `overspeed` column.

## 4. Validated Test Results (2026-01-30)

The algorithm was tested against the following devices using **Raw Speed** (no conversion) and a **Limit of 127**.

### Test Case A: Device 8900
*   **Date**: 2026-01-10
*   **Max Speed (Raw)**: 116
*   **Result**: 0 Events.
*   **Explanation**: The raw speed (116) never exceeded the limit (127). No explicit alarms were found.

### Test Case B: Device 8937
*   **Date**: 2026-01-01
*   **Result**: 0 Events.
*   **Explanation**: Raw speed remained below the limit (previously converted speed triggered events, confirming limit logic).

