# Operation Modes Documentation

Each operation mode has unique functions and real-time monitoring capabilities connected to microcontrollers.

## Plowing Mode

### Real-time Monitoring
- **Plow Depth**: Current plowing depth in cm (0-30 cm)
- **Speed**: Robot movement speed in m/s
- **Coverage**: Percentage of field covered
- **Area Covered**: Total area plowed in square meters
- **Plow Angle**: Current plow angle in degrees
- **Soil Resistance**: Force measurement in Newtons
- **Power Consumption**: Current power usage in Watts

### Microcontroller Data Format
```json
{
  "deviceId": "arduino-plow-001",
  "mode": "plowing",
  "depth": 15.5,
  "speed": 1.2,
  "coverage": 45.5,
  "areaCovered": 4550,
  "plowAngle": 0,
  "soilResistance": 350,
  "powerConsumption": 2500
}
```

### Arduino Example Code
```cpp
// Plowing mode sensors
float plowDepth = readDepthSensor(); // cm
float speed = readSpeedSensor(); // m/s
float soilResistance = readForceSensor(); // N
float power = readPowerSensor(); // W

// Send data
Serial.print("{\"deviceId\":\"arduino-plow-001\",");
Serial.print("\"mode\":\"plowing\",");
Serial.print("\"depth\":");
Serial.print(plowDepth);
Serial.print(",\"speed\":");
Serial.print(speed);
Serial.print(",\"soilResistance\":");
Serial.print(soilResistance);
Serial.print(",\"powerConsumption\":");
Serial.print(power);
Serial.println("}");
```

## Spraying Mode

### Real-time Monitoring
- **Flow Rate**: Chemical flow rate in L/min
- **Pressure**: Spray pressure in PSI
- **Chemical Level**: Remaining chemical percentage
- **Nozzle Status**: Status of each nozzle (active/inactive)
- **Coverage**: Percentage of area sprayed
- **Area Sprayed**: Total area in square meters
- **Wind Speed**: Current wind speed in m/s (safety)
- **Temperature**: Ambient temperature in Celsius
- **Humidity**: Relative humidity percentage

### Safety Features
- **Wind Speed Alert**: Warns if wind > 5 m/s (unsafe for spraying)
- **Low Chemical Alert**: Warns when chemical level < 20%
- **Pressure Monitoring**: Optimal pressure range 20-40 PSI

### Microcontroller Data Format
```json
{
  "deviceId": "raspberry-spray-001",
  "mode": "spraying",
  "flowRate": 2.5,
  "pressure": 30.0,
  "chemicalLevel": 75.0,
  "nozzleStatus": ["active", "active", "inactive", "active"],
  "coverage": 30.5,
  "areaSprayed": 3050,
  "windSpeed": 3.2,
  "temperature": 25.5,
  "humidity": 60.0
}
```

### Raspberry Pi Example Code
```python
import json
import time
from sense_hat import SenseHat

sense = SenseHat()

def get_spraying_data():
    return {
        "deviceId": "raspberry-spray-001",
        "mode": "spraying",
        "flowRate": read_flow_sensor(),  # L/min
        "pressure": read_pressure_sensor(),  # PSI
        "chemicalLevel": read_level_sensor(),  # %
        "nozzleStatus": check_nozzles(),  # Array
        "windSpeed": read_wind_sensor(),  # m/s
        "temperature": sense.get_temperature(),
        "humidity": sense.get_humidity()
    }

# Send every 2 seconds
while True:
    data = get_spraying_data()
    send_to_server(data)
    time.sleep(2)
```

## Seeding Mode

### Real-time Monitoring
- **Seed Rate**: Seeds per meter
- **Spacing**: Distance between seeds in cm
- **Depth**: Planting depth in cm
- **Coverage**: Percentage of area seeded
- **Area Seeded**: Total area in square meters
- **Seeds Remaining**: Count of remaining seeds
- **Hopper Level**: Hopper fill percentage
- **Seed Type**: Type of seed being planted
- **Germination Rate**: Percentage (from monitoring data)

### Microcontroller Data Format
```json
{
  "deviceId": "arduino-seed-001",
  "mode": "seeding",
  "seedRate": 25.5,
  "spacing": 15.0,
  "depth": 3.0,
  "coverage": 60.0,
  "areaSeeded": 6000,
  "seedsRemaining": 50000,
  "hopperLevel": 80.0,
  "seedType": "Corn"
}
```

### ESP32 Example Code
```cpp
#include <WiFi.h>
#include <HTTPClient.h>

void sendSeedingData() {
  int seedCount = readSeedCounter();
  float spacing = readSpacingSensor();
  float depth = readDepthSensor();
  int hopperLevel = readHopperLevel();
  
  String json = "{";
  json += "\"deviceId\":\"esp32-seed-001\",";
  json += "\"mode\":\"seeding\",";
  json += "\"seedRate\":" + String(seedCount / distance) + ",";
  json += "\"spacing\":" + String(spacing) + ",";
  json += "\"depth\":" + String(depth) + ",";
  json += "\"seedsRemaining\":" + String(totalSeeds - seedCount) + ",";
  json += "\"hopperLevel\":" + String(hopperLevel);
  json += "}";
  
  sendToServer(json);
}
```

## Monitoring Mode

### Real-time Monitoring
- **Crop Health**: Overall health percentage (0-100)
- **Growth Stage**: Current growth stage (e.g., "Seedling", "Vegetative", "Flowering")
- **Plant Count**: Number of plants detected
- **Average Height**: Average plant height in cm
- **Leaf Area Index**: Canopy density measurement
- **Chlorophyll**: SPAD units (leaf greenness)
- **Soil Moisture**: Percentage
- **Soil pH**: Acidity/alkalinity (0-14)
- **Nitrogen (N)**: Parts per million
- **Phosphorus (P)**: Parts per million
- **Potassium (K)**: Parts per million
- **Pest Detection**: Array of detected pests with severity and location
- **Weed Detection**: Array of detected weeds with coverage and location

### Advanced Features
- **Computer Vision**: Pest and weed detection using camera
- **Multi-spectral Analysis**: Crop health assessment
- **Soil Analysis**: NPK nutrient levels
- **Growth Tracking**: Historical growth data

### Microcontroller Data Format
```json
{
  "deviceId": "raspberry-monitor-001",
  "mode": "monitoring",
  "cropHealth": 85.5,
  "growthStage": "Vegetative",
  "plantCount": 1250,
  "averageHeight": 45.2,
  "leafAreaIndex": 2.5,
  "chlorophyll": 35.8,
  "soilMoisture": 55.0,
  "soilPh": 6.8,
  "nitrogen": 150,
  "phosphorus": 25,
  "potassium": 200,
  "pestDetection": [
    {
      "type": "Aphids",
      "severity": 15,
      "location": {"x": 10.5, "y": 20.3}
    }
  ],
  "weedDetection": [
    {
      "type": "Broadleaf",
      "coverage": 5.2,
      "location": {"x": 15.0, "y": 25.0}
    }
  ]
}
```

### Raspberry Pi with Camera Example
```python
import cv2
import numpy as np
from picamera2 import Picamera2

picam2 = Picamera2()
picam2.start()

def analyze_crop_health():
    frame = picam2.capture_array()
    
    # Computer vision analysis
    health_score = analyze_leaf_color(frame)
    plant_count = count_plants(frame)
    pests = detect_pests(frame)
    weeds = detect_weeds(frame)
    
    return {
        "deviceId": "raspberry-monitor-001",
        "mode": "monitoring",
        "cropHealth": health_score,
        "plantCount": plant_count,
        "pestDetection": pests,
        "weedDetection": weeds
    }
```

## API Endpoints

### Set Operation Mode
```
POST /api/operation-modes/set
Content-Type: application/json
Authorization: Bearer <token>

{
  "mode": "plowing",
  "deviceId": "arduino-001"
}
```

### Get Current Mode Data
```
GET /api/operation-modes/current
Authorization: Bearer <token>
```

### Update Mode Data (from microcontroller)
```
POST /api/operation-modes/data
Content-Type: application/json

{
  "deviceId": "arduino-001",
  "data": {
    "depth": 15.5,
    "speed": 1.2,
    ...
  }
}
```

### Start/Stop/Pause Operation
```
POST /api/operation-modes/start
POST /api/operation-modes/stop
POST /api/operation-modes/pause
```

## WebSocket Events

### Server → Client
- `operation_mode_data`: Real-time mode data updates
- `operation_mode_changed`: Mode change notification

### Client → Server
- Send commands via REST API

## Integration with Hardware

The operation modes service automatically processes data from connected hardware devices. When a device sends sensor data:

1. Data is received via `/api/hardware/devices/{id}/sensors`
2. Operation modes service processes it based on current mode
3. Real-time updates broadcast via WebSocket
4. Frontend displays mode-specific information

## Real-time Updates

All mode data updates in real-time:
- **Update Frequency**: Every 2 seconds (configurable)
- **WebSocket**: Instant updates when data changes
- **Fallback**: REST API polling if WebSocket unavailable

## Next Steps

1. Connect your microcontroller to the Hardware page
2. Set the operation mode in Robot Control
3. Start the operation
4. View real-time monitoring data specific to that mode
5. Monitor progress and receive alerts

Each mode provides comprehensive monitoring tailored to the specific agricultural operation!

