# App Class Documentation

## Overview

The `App` class is the main controller for an injection molding system that manages plunger movement, speed control, and safety features.

## Class Structure

```mermaid
classDiagram
    class App {
        +DirectionSwitch* dirSwitch
        +VFD* vfd
        +MotorLoad* mLoad
        +ProximitySensor* plungerHome
        +short plungeState
        +setup() short
        +loop() short
        +plunge(short value) short
        +home(short value) short
        +stop(short value) short
        -loopManual() ushort
    }
    App --|> Addon
    App --* DirectionSwitch
    App --* VFD
    App --* MotorLoad
    App --* ProximitySensor
```

## State Machine

```mermaid
stateDiagram-v2
    [*] --> IDLE
    IDLE --> PLUNGING: plunge()
    IDLE --> HOMING: home()
    PLUNGING --> JAMMED: overload
    HOMING --> JAMMED: overload
    JAMMED --> IDLE: reset
    PLUNGING --> IDLE: stop()
    HOMING --> IDLE: stop()
    AUTO --> IDLE: abort
```

## Key Components

### State Management
```cpp
enum PLUNGE_STATE {
    IDLE = 0,
    PLUNGING = 5,
    HOMING = 5,
    JAMMED = 11,
    AUTO = 12
};
```

### Safety Features
- Overload detection via MotorLoad class
- End position detection via ProximitySensor
- Direction change protection with minimum delay
- Emergency stop capabilities

### Speed Control
- Variable frequency drive (VFD) interface
- Multi-stage speed profile
- Adaptive speed based on load

## Operation Modes

1. **Manual Mode**
   - Direct control via direction switch
   - Immediate response to user input
   - Load-adaptive speed control

2. **Auto Mode**
   - Automated cycle execution
   - Position-based speed adjustment
   - Safety monitoring and fault handling

## Error Handling

- E_OK: Successful operation
- E_MOTOR_DT_OVERLOAD: Motor overload detected
- State transitions to JAMMED on fault conditions

## Code Examples

### Initialization
```cpp
App::App() : Addon("APP", APP, 1 << STATE),
    dirSwitch(new DirectionSwitch()),
    vfd(new VFD(-1, -1)),
    mLoad(new MotorLoad(MOTOR_LOAD_PIN)),
    plungerHome(new ProximitySensor(PLUNGE_HOME_PIN))
{
    // Constructor initialization
}
```

### Main Control Loop
```cpp
short App::loop() {
    loop_addons();
    timer.tick();
    now = millis();
    short result = loopManual();
    delay(LOOP_DELAY);
    return result;
}
```
