## 3. State Machine & Feature Additions for `OVMS/vehicle_vwegolf_bat_ctrl.h` & `.cpp`
*(Consolidated from `OCU_BAP_and_Window_Heating_Findings.md`, `framework.odex`, and `baphandler`)*

### 3.1 How the OCU Runs Cabin Climate (Sequence 1), Window Heating (Sequence 2), and Both Simultaneously

In `RemotePreTripClimatisationImpl.java` (`lines 23–39, 103–147`) and `VehicleAbstractionLayerImpl` (`framework.odex`), the OCU **never** sets `clima = true` and `whFront/whRear = true` in the same Profile 0 write:
* In `framework.odex` (`VehicleAbstractionLayerImpl.climaSettingsDbusToVAL` at `4641856` and `climaSettingsVALtoDbusChange` at `4641964`), `SetClimatisationSettings` ignores `windowHeatingFront`/`windowHeatingRear` completely (hardcoding them to `Boolean.FALSE` on read and leaving Profile 0's `j`/`k` fields untouched on write).
* In `RemoteDepartureTimeProgrammingImpl.java:464`, departure profiles also force `profile.getOperation().setWindowHeating(Boolean.FALSE)`.
* When `PO_CLIMATE` (`0x02`) and `PO2_WINDOW_HEATER_FRONT` (`0x01`) are combined in one Profile 0 write, the car treats `PO2_WINDOW_HEATER_FRONT` as an *automatic* climate sub-option that the HVAC module declines unless ambient temperature is `< 4 °C` (`OVMS/vehicle_vwegolf.cpp:665–668`).

Instead, the OCU holds **two parallel sub-state machines** in `StateJunction`—`"Clima"` (tracking `ClimateState` `0x12` byte `[5]` **high nibble** `cs.state`) and `"WindowHeating"` (tracking `ClimateState` `0x12` byte `[5]` **low nibble** `cs.heaterState` and byte `[6]` `cs.heaters`)—fed by a single FIFO `ConditionalWorkQueueImpl`. To run **both** Cabin Climate and Window Heating at the same time, the OCU runs **Sequence 1** and **Sequence 2** sequentially:

#### Sequence 1: `StartClimatisation` / `StopClimatisation` (`BC_CLIMATE`)
1. **Queue / In-Flight Guard**: Enqueued in `ConditionalWorkQueueImpl` so it cannot clobber an in-flight BAP transaction.
2. **Pre-Wake & Post-Wake Checks**: Rejects if `KL15` (`TERMINAL_15`) is ON, or if `PO_ALLOW_BATTERY == 0` while unplugged/unlocked/no supply. After wake, if `cs.state` is already `CS_RUNNING` (on start) or `CS_IDLE` (on stop), finishes immediately without writing Profile 0.
3. **Arm Profile 0 Exclusively for Cabin Climate (`setOperation(false, true, false, false)`)**:
   * Writes Profile 0 (`RA0`) on `0x19` (`29 59 <asgTxn> 00 00 01 <RA0>`) with:
     * `operation  = 0x06` (`PO_CLIMATE | PO_ALLOW_BATTERY`, `PO_CHARGING = 0`, preserving seat heater / autoDefrost bits `0xF8`)
     * **`operation2 = 0x00` (`PO2_WINDOW_HEATER_FRONT = 0`, `PO2_WINDOW_HEATER_REAR = 0`)**
4. **Verify `49 59` Write Echo (`notifyOperationChange()`)**:
   * Decodes Profile 0 from `49 59` and checks `if (charge || !clima || whFront || whRear)` (`RemotePreTripClimatisationStateStarting.java:260`). If `whFront` or `whRear` is still set, it **aborts with `App_RPC_StartClimaFailedLMError`** and does not fire `0x18`.
5. **Trigger `0x18` (`startClimatisation()` / `stopClimatisation()`)**:
   * Sends `29 58 00 01` (start) or `29 58 00 00` (stop) on `0x17332501`.
6. **Confirm via `49 58` + `ClimateState` (`0x12`) High Nibble (`cs.state`)**:
   * `49 58` cancels repetitive CAN wakeups; `ClimateState` (`0x12`) byte `[5]` high nibble (`cs.state == CS_RUNNING` on start, `CS_IDLE` / `CS_COMPLETED` on stop) confirms the state change.

#### Sequence 2: `StartWindowHeating` / `StopWindowHeating` (`BC_WINDOW_HEAT`)
1. **Queue / In-Flight Guard**: Runs either standalone **or** immediately after Sequence 1 finishes (while Cabin Climate is already `CS_RUNNING`).
2. **Pre-Wake & Post-Wake Checks**: Rejects if `KL15` is ON, or if `PO_ALLOW_BATTERY == 0` while unplugged. After wake, checks `ClimateState` (`0x12`) byte `[5]` **low nibble (`cs.heaterState`)**: if already `CS_RUNNING` (on start) or `!= CS_RUNNING` (on stop), finishes immediately.
3. **Arm Profile 0 Exclusively for Window Heating (`setOperation(false, false, true, true)`)**:
   * Writes Profile 0 (`RA0`) on `0x19` (`29 59 <asgTxn> 00 00 01 <RA0>`) with:
     * **`operation  = 0x04` (`PO_CLIMATE = 0`, `PO_CHARGING = 0`, `PO_ALLOW_BATTERY = 1`)**
     * **`operation2 = 0x03` (`PO2_WINDOW_HEATER_FRONT | PO2_WINDOW_HEATER_REAR`)**
4. **Verify `49 59` Write Echo (`notifyOperationChange()`)**:
   * Decodes Profile 0 from `49 59` and checks `if (charge || clima || !whFront || !whRear)` (`RemotePreTripClimatisationWHStateStarting.java:214`). If `clima` is set or `whFront`/`whRear` is not set, it **aborts with `App_RPC_StartWindowHeatingFailedLMError`**.
5. **Trigger `0x18` (`startWindowHeating()` / `stopWindowHeating()`)**:
   * Sends `29 58 00 01` (start) or `29 58 00 00` (stop) on `0x17332501`.
   * **Why this does not stop a running Cabin Climate session**: Profile 0 acts as the target selector for `0x18`. Sending `29 58 00 01` (`START`) with `op = 0x04, op2 = 0x03` starts the BCU's `seatheaterWindowState` (`cs.heaterState`) state machine while leaving the already-running Cabin Climate (`cs.state`) session active. Likewise, to stop only one while both are running, arming that subsystem's bits in Profile 0 and sending `29 58 00 00` (`STOP`) stops only that subsystem.
6. **Confirm via `49 58` + `ClimateState` (`0x12`) Low Nibble (`cs.heaterState`) & Byte `[6]` (`cs.heaters`)**:
   * Confirms when `cs.heaterState == CS_RUNNING` (`12`) and `cs.heaters` has `CH_WINDOW_FRONT` (`0x10`) / `CH_WINDOW_REAR` (`0x20`) set (or `cs.heaterState == CS_IDLE | CS_COMPLETED` on stop).

---

### 3.2 Is Sequence 1 (`BC_CLIMATE`) Already Implemented the Same Way in OVMS? (Gap Analysis)

**Not completely.** While `OVMS/vehicle_vwegolf_bat_ctrl.cpp` already implements the core `Wake -> Handshake -> GET Profile 0 -> RA0 Write -> 49 59 Echo -> 29 58 Trigger` flow for `BC_CLIMATE`, there are **4 specific differences** between current OVMS and the OCU's Sequence 1 that need to be updated:

| Step in Sequence 1 (`BC_CLIMATE`) | OCU Implementation (`RemotePreTripClimatisationState*` + `VAL`) | Current OVMS Implementation (`OVMS/vehicle_vwegolf_bat_ctrl.cpp`) | Required Change in OVMS for Sequence 1 |
| :--- | :--- | :--- | :--- |
| **1. In-Flight Command Guard (`Climate()`, `Charge()`, `SetChargeCurrent()`)** | Serialized via `ConditionalWorkQueueImpl` — never overwrites an in-flight command. | `ListProfiles()`, `SetProfile()`, and `Timer` ops check `if (m_phase != CP_IDLE) return false;`, **but `Climate()` (`line 48`), `Charge()` (`line 50`), and `SetChargeCurrent()` (`line 63`) do NOT check `m_phase != CP_IDLE`!** | Add `if (m_phase != CP_IDLE)` guard to `Climate()`, `Charge()`, and `SetChargeCurrent()` (or inside `Begin()`) so a second command cannot clobber an in-flight sequence. |
| **2. Clearing `operation2` Window Heater Bits in `SendArm()` (`lines 1071–1088`)** | `setOperation(false, true, false, false)` sets `op = 0x06` **and clears `whFront` & `whRear` in `operation2` (`op2 &= ~0x03`)**. Same for `Charge` (`op = 0x01, op2 &= ~0x03`). | `SendArm()` sets `p.operation = (p.operation \| 0x06) & ~0x01` for `BC_CLIMATE` (and `0x01` for `BC_CHARGE`), **but leaves `p.operation2` untouched!** If `op2` had `0x01`/`0x03` set from `SetProfile` or a prior `WindowHeat` run, `BC_CLIMATE` sends `op = 0x06, op2 = 0x03` instead of `op = 0x06, op2 = 0x00`. | In `SendArm()`, clear `PO2_WINDOW_HEATER_FRONT \| PO2_WINDOW_HEATER_REAR` (`~0x03`) in `p.operation2` for both `BC_CLIMATE` and `BC_CHARGE`. |
| **3. Checking `p.operation2` in `m_arm_skipped` (`line 1119`)** | Always writes Profile 0 if any of `(charge, clima, whFront, whRear)` differ. | `m_arm_skipped` (`line 1119`) only checks `p.operation == m_profile0.operation && p.maxCurrent == m_profile0.maxCurrent` — **it ignores `p.operation2`!** | Add `&& p.operation2 == m_profile0.operation2` to the `m_arm_skipped` condition at `line 1119`. |
| **4. Verifying Echoed Profile 0 Bits on `49 59` (`lines 546–552`)** | `notifyOperationChange()` decodes Profile 0 from the `49 59` write echo and verifies `!charge && clima && !whFront && !whRear` before calling `startClimatisation()`. | Checks `if (lead & 0x80)` on `49 59` and immediately calls `SendTrigger(m_enable)` without verifying the echoed Profile 0 record in `el.body`. | In `IncomingBapStatus()` on `lead & 0x80` (`CP_ARM_WAIT`), decode `el.body` with `decodeProfileArray()` (including `RA6`) and verify `(charge, clima, whFront, whRear)` match `m_op` before calling `SendTrigger(m_enable)`. |

---

### 3.3 `[NEW FEATURE]` Implementing Sequence 2 (`BC_WINDOW_HEAT` / `WindowHeat`) & Testing Seat Heaters via the Same Mechanism
* **Current State in `OVMS/`**:
  `ProfileEdit` supports editing `F_FRONT_WINDOW`, `F_REAR_WINDOW`, and `F_SEATS` on Profile 0 (`vehicle_vwegolf_bat_ctrl.h:130–132`), and `HandleClimateState()` exposes `m_ms_front_window` (`xvg.v.env.heated_front_window`), but `VWeGolfBatteryControl` does not yet have a standalone `WindowHeat` (`BC_WINDOW_HEAT`) command or `m_ms_rear_window` (`xvg.v.env.heated_rear_window`) metric.
* **Can the Same Mechanism Apply to the Seat Heater Bits (`PO_SEAT_FL = 0x10`, `PO_SEAT_FR = 0x20`)?**
  * **Protocol Evidence (`baphandler` `FUN_0002a000` at `0x2a000`, `ev_e43f75aca938bab5422cfcc4c45848dd48a83b7fb4df63acbcf3d23e56c4d070`)**:
    * In `ClimateState` (`0x12`), the BCU does **not** have separate state machines for seat heaters and window heaters—they share a **single** state nibble and bitmap:
      * Byte `[5]` low nibble (`cs.heaterState`): `seat_window_heater_state` (`seatheaterWindowState`)
      * Byte `[6]` (`cs.heaters`, masked to `& 0x3F`): `seat_window_heater_mode` (`0x01` = `CH_SEAT_FL`, `0x02` = `CH_SEAT_FR`, `0x04` = `CH_SEAT_RL`, `0x08` = `CH_SEAT_RR`, `0x10` = `CH_WINDOW_FRONT`, `0x20` = `CH_WINDOW_REAR`).
    * In `operationVALtoDbusChange` (`framework.odex` offset `4657548`), `setOperation(charge, clima, whFront, whRear)` overwrites `b` (`charge`), `c` (`clima`), `j` (`whFront`), and `k` (`whRear`), while **preserving `f..i` (`PO_SEAT_FL..RR`, `operation` bits `4..7`)**.
  * **How to Support & Test Both in OVMS**:
    * For `BC_CLIMATE` and `BC_CHARGE`, `SendArm()` should also clear `PO_SEAT_MASK` (`0xF0`) if we want a pure climate/charge arm, **or** preserve `PO_SEAT_MASK` when desired; and for `BC_WINDOW_HEAT` (or a combined `WindowAndSeatHeat`), we can allow setting `PO_SEAT_FL | PO_SEAT_FR` (`0x30`) alongside `PO_ALLOW_BATTERY` (`0x04`) with `PO_CLIMATE = 0`:
      * **Windows only (exact OCU)**: `op = 0x04, op2 = 0x03` + `29 58 00 01`
      * **Windows + Front Seats**: `op = 0x34, op2 = 0x03` + `29 58 00 01`
      * **Front Seats only**: `op = 0x34, op2 = 0x00` + `29 58 00 01`
    * **On-Car Verification**: Watch `ClimateState` (`0x12`) byte `[5]` low nibble (`cs.heaterState == 12`) and byte `[6]` (`cs.heaters & 0x03`) to see if the e-Golf's BCU/Climatronic honors `PO_SEAT_FL`/`PO_SEAT_FR` when unoccupied or if hardware occupancy/safety rules gate the physical seat relays.
* **Changes to Make**:
  1. Add `bool WindowHeat(bool enable, uint8_t seatMask = 0);` and `BC_WINDOW_HEAT` to `VWeGolfBatteryControl` (`vehicle_vwegolf_bat_ctrl.h`), plus a CLI command in `vehicle_vwegolf.cpp`.
  2. In `SendArm()`, for `BC_WINDOW_HEAT`:
     ```cpp
     case BC_WINDOW_HEAT:
         p.operation = (uint8_t)(((p.operation & ~bap::egolf::PO_SEAT_MASK) |
                                  (m_seat_mask & bap::egolf::PO_SEAT_MASK) |
                                  bap::egolf::PO_ALLOW_BATTERY)
                                 & ~(bap::egolf::PO_CHARGING | bap::egolf::PO_CLIMATE));
         p.operation2 |= (bap::egolf::PO2_WINDOW_HEATER_FRONT |
                          bap::egolf::PO2_WINDOW_HEATER_REAR);
         break;
     ```
  3. Add `OvmsMetricBool* m_ms_rear_window` (`xvg.v.env.heated_rear_window`) and `uint8_t m_hs_state = 0xFF` (last `cs.heaterState`) to track window/seat heating state and emit abort alerts when `cs.heaterState` transitions to an abort value (`CS_ABORT_DEVICE_ERROR`, `CS_ABORT_BATTERY_CONDITION`, `CS_ABORT_BATTERY_LOW`).

### 3.4 `[NEW FEATURE]` Remote Charge Port Lock / Unlock (`LSG 0x25`, Function `0x10` `FUNC_PLUG_STATE`)
* **Source**: `bap_batterycontrol_fsg_plug_statemachine` (`0x28f60`, `ev_e76703c9fc32e0603b11640d8d89d58deb061ae87c8206a9e22e269bb7863f45`) and `bap_batterycontrol_actuator_test_statemachine` (`0x28cec`, `ev_0f68f943b8f688af5dd21c22240c774c6a8bb8e3fc7db0ae47cd1bd528956b5e`).
* **How It Works**:
  * Sending a 2-byte `OP_SET_GET` (`29 50 <lockSetup<<4> 00`) on `0x17332501` (`kCanIdCommand`) commands the BCU to unlock (`0x00, 0x00`) or lock (`0x10, 0x00`) the charge port plug:
    ```cpp
    inline bap::SendResult sendPlugLockSetup(Sink&& sink, bool lock) {
      uint8_t body[2] = { (uint8_t)(lock ? 0x10 : 0x00), 0x00 };
      return bap::sendElement(sink, bap::OP_SET_GET, kLsg, FUNC_PLUG_STATE, body, 2);
    }
    ```

---