# Automation Systems

Automating vertical farm operations for efficiency and consistency.

## Automation Levels

### Manual Operation

```
Human → Observe → Decide → Act → Monitor

Pros: Low cost, flexible
Cons: Labor intensive, inconsistent, human error
Best for: Small hobbyist operations
```

### Semi-Automated

```
Sensors → Alert → Human Decision → Automated Action

Pros: Reduced labor, consistent execution
Cons: Still requires monitoring, delayed response
Best for: Small-medium commercial operations
```

### Fully Automated

```
Sensors → Controller → Algorithm → Action → Verify

Pros: 24/7 operation, optimal control, data-driven
Cons: High upfront cost, requires expertise
Best for: Commercial production facilities
```

## Control System Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                    AUTOMATION ARCHITECTURE                       │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  LAYER 4: BUSINESS INTELLIGENCE                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  Analytics │ Forecasting │ Optimization │ Reporting      │  │
│  └──────────────────────────────────────────────────────────┘  │
│                              │                                   │
│  LAYER 3: SUPERVISORY CONTROL                                   │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  Recipe Management │ Scheduling │ Alarm Management        │  │
│  └──────────────────────────────────────────────────────────┘  │
│                              │                                   │
│  LAYER 2: ZONE CONTROLLERS                                      │
│  ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐  │
│  │  Zone A    │ │  Zone B    │ │  Zone C    │ │  Zone D    │  │
│  │ Controller │ │ Controller │ │ Controller │ │ Controller │  │
│  └────────────┘ └────────────┘ └────────────┘ └────────────┘  │
│                              │                                   │
│  LAYER 1: FIELD DEVICES                                         │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  Sensors │ Actuators │ Valves │ Pumps │ Lights │ HVAC    │  │
│  └──────────────────────────────────────────────────────────┘  │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

## Automated Systems

### Lighting Automation

```typescript
interface LightingAutomation {
  // Photoperiod control
  schedule: {
    onTime: string;   // "06:00"
    offTime: string;  // "22:00"
    rampUp: number;   // minutes to full brightness
    rampDown: number; // minutes to off
  };

  // Intensity control
  intensity: {
    mode: 'fixed' | 'dli_target' | 'adaptive';
    targetDLI?: number;
    maxPPFD: number;
  };

  // Spectrum control (tunable LEDs)
  spectrum: {
    vegetative: { blue: 30, red: 60, farRed: 10 };
    flowering: { blue: 20, red: 70, farRed: 10 };
    auto_switch_day?: number; // Day to switch
  };
}
```

### Irrigation Automation

```typescript
interface IrrigationAutomation {
  // Timing-based
  schedule: {
    intervalsPerDay: number;
    duration: number;  // seconds
    times: string[];   // ["06:00", "12:00", "18:00"]
  };

  // Sensor-based triggers
  triggers: {
    minMoisturePercent?: number;  // Start irrigation below this
    maxMoisturePercent?: number;  // Stop irrigation above this
    ecThreshold?: number;         // Flush if EC too high
  };

  // Flow control
  flowRate: number;  // L/min
  maxDuration: number;  // Safety limit
}
```

### Nutrient Dosing Automation

```typescript
interface DosingAutomation {
  targetEC: number;
  targetPH: number;

  // PID control parameters
  ec_pid: { kp: 0.5, ki: 0.1, kd: 0.05 };
  ph_pid: { kp: 0.3, ki: 0.05, kd: 0.02 };

  // Dosing limits
  maxDoseML: number;      // Per adjustment
  minDoseInterval: number; // Seconds between doses
  mixTime: number;         // Seconds to wait after dosing

  // Stock solution mappings
  ecUp: string[];   // ["nutrient_a", "nutrient_b"]
  ecDown: string[]; // ["fresh_water"]
  phUp: string;     // "ph_up"
  phDown: string;   // "ph_down"
}
```

### Climate Automation

```typescript
interface ClimateAutomation {
  // Temperature control
  cooling: {
    stage1_offset: 1;  // First stage at target + 1°C
    stage2_offset: 2;
    stage3_offset: 3;
  };
  heating: {
    stage1_offset: -1;
    stage2_offset: -2;
  };

  // Humidity control
  humidify_below: number;
  dehumidify_above: number;

  // CO2 control
  co2: {
    inject_below: number;
    stop_above: number;
    only_when_lights_on: boolean;
  };

  // Ventilation
  ventilation: {
    outdoor_temp_min: number;  // Don't vent if too cold
    outdoor_temp_max: number;  // Don't vent if too hot
    humidity_threshold: number;
  };
}
```

## Recipe-Driven Automation

### How Recipes Control Automation

```
Recipe Definition
      │
      ▼
┌─────────────────┐
│ Current Day     │ ─────────→ Stage Lookup
│ of Crop Batch   │
└─────────────────┘
                        │
                        ▼
              ┌─────────────────┐
              │ Stage Settings  │
              │ - Temperature   │
              │ - Humidity      │
              │ - Light PPFD    │
              │ - Light hours   │
              │ - EC target     │
              │ - pH target     │
              │ - CO2 level     │
              └────────┬────────┘
                       │
          ┌────────────┴────────────┐
          ▼                         ▼
  ┌──────────────┐         ┌──────────────┐
  │ Update Zone  │         │ Update Zone  │
  │ Setpoints    │         │ Light Schedule│
  └──────────────┘         └──────────────┘
          │                         │
          ▼                         ▼
  Controllers adjust         Light timers
  to new targets             updated
```

### Stage Transition Automation

```typescript
function updateBatchStage(batch: CropBatch): void {
  const recipe = getRecipe(batch.recipeId);
  const currentDay = calculateDay(batch.plantingDate);

  // Find current stage
  const stage = recipe.stages.find(s =>
    currentDay >= s.daysStart && currentDay <= s.daysEnd
  );

  if (stage && stage.name !== batch.currentStage) {
    // Stage has changed!
    batch.currentStage = stage.name;

    // Update zone setpoints
    updateZoneTargets(batch.zoneId, stage);

    // Trigger any stage actions
    executeStageActions(batch, stage, currentDay);

    // Log transition
    logEvent('stage_transition', batch.id, stage.name);
  }
}
```

## Robotics Integration

### Seeding Automation

```
┌─────────────────────────────────────────────────────────────┐
│                    SEEDING AUTOMATION                        │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  1. Tray Loading                                             │
│     Robot arm places empty trays on conveyor                 │
│                                                              │
│  2. Media Filling                                            │
│     Automated hopper fills trays with growing media          │
│                                                              │
│  3. Seed Placement                                           │
│     Precision seeder places seeds at correct spacing         │
│     Vision system verifies placement                         │
│                                                              │
│  4. Cover/Press                                              │
│     Automated press firms seeds into media                   │
│     Vermiculite cover applied                                │
│                                                              │
│  5. Labeling                                                 │
│     QR code applied linking to blockchain record             │
│                                                              │
│  6. Transport                                                │
│     Automated cart moves to germination zone                 │
│                                                              │
└─────────────────────────────────────────────────────────────┘
```

### Transplanting Automation

```typescript
interface TransplantRobot {
  type: 'robotic_arm' | 'gantry' | 'mobile';

  capabilities: {
    seedlingsPerHour: number;
    success_rate: number;  // 95%+
    plant_spacing_accuracy: number;  // ±2mm
  };

  integration: {
    vision_system: boolean;  // For plant detection
    force_feedback: boolean; // Gentle handling
    api_endpoint: string;    // LocalGreenChain integration
  };
}
```

### Harvesting Automation

| Crop Type | Automation Method | Speed | Accuracy |
|-----------|-------------------|-------|----------|
| Microgreens | Blade cut | Fast | High |
| Lettuce | Root cut + vacuum | Medium | High |
| Basil | Selective picking | Slow | Medium |
| Tomatoes | Vision + gripper | Slow | High |

## Scheduling System

### Batch Scheduling

```typescript
interface BatchScheduler {
  // Calculate optimal start dates
  calculatePlantingDate(
    recipe: GrowingRecipe,
    targetHarvestDate: Date,
    zoneAvailability: ZoneCalendar
  ): Date;

  // Optimize zone utilization
  optimizeZoneAssignment(
    batches: CropBatch[],
    zones: GrowingZone[]
  ): Assignment[];

  // Handle conflicts
  resolveConflicts(
    pending: CropBatch[],
    capacity: number
  ): Resolution;
}
```

### Maintenance Scheduling

```typescript
const maintenanceSchedule = {
  daily: [
    { task: 'sensor_check', duration: 15 },
    { task: 'visual_inspection', duration: 30 }
  ],
  weekly: [
    { task: 'calibrate_ph', duration: 30 },
    { task: 'calibrate_ec', duration: 30 },
    { task: 'filter_check', duration: 15 }
  ],
  monthly: [
    { task: 'deep_clean', duration: 240 },
    { task: 'sensor_calibration', duration: 60 },
    { task: 'equipment_service', duration: 120 }
  ]
};
```

## Data-Driven Optimization

### Machine Learning Integration

```
Historical Data
      │
      ├── Environmental readings
      ├── Crop performance
      ├── Energy usage
      └── Yield data
           │
           ▼
┌─────────────────────┐
│   ML Models         │
│                     │
│ - Yield prediction  │
│ - Recipe optimization│
│ - Anomaly detection │
│ - Energy optimization│
└─────────────────────┘
           │
           ▼
┌─────────────────────┐
│   Recommendations   │
│                     │
│ - Adjust setpoints  │
│ - Modify recipes    │
│ - Predict issues    │
└─────────────────────┘
```

### Optimization Targets

| Metric | Optimization Method |
|--------|---------------------|
| Yield | Adjust PPFD, DLI, nutrients |
| Quality | Fine-tune environment |
| Energy | Shift operations off-peak |
| Water | Optimize irrigation timing |
| Labor | Batch scheduling |

## API Integration

### LocalGreenChain Integration

```typescript
// Automation system reports to LocalGreenChain
async function reportEnvironment(
  batchId: string,
  readings: EnvironmentReading
): Promise<void> {
  await fetch('/api/vertical-farm/batch/{batchId}/environment', {
    method: 'PUT',
    body: JSON.stringify(readings)
  });
}

// Automation receives commands from LocalGreenChain
async function fetchSetpoints(zoneId: string): Promise<Setpoints> {
  const response = await fetch(`/api/vertical-farm/zone/${zoneId}/setpoints`);
  return response.json();
}
```

## Best Practices

### Reliability

1. **Redundancy** - Backup sensors, dual pumps
2. **Fail-safes** - Default to safe state on failure
3. **Monitoring** - 24/7 alerting
4. **Testing** - Regular system tests
5. **Documentation** - Keep procedures updated

### Security

1. **Access control** - Role-based permissions
2. **Audit logging** - Track all changes
3. **Network security** - Segmented OT network
4. **Updates** - Regular firmware patches
5. **Backups** - Configuration backups
