# Vertical Farm Integration Guide

How to integrate your vertical farm with LocalGreenChain.

## Integration Overview

```
┌─────────────────────────────────────────────────────────────────┐
│              INTEGRATION ARCHITECTURE                            │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  YOUR VERTICAL FARM              LOCALGREENCHAIN                │
│  ─────────────────               ──────────────────              │
│                                                                  │
│  ┌──────────────┐               ┌──────────────────┐           │
│  │ Control      │───Register───→│ /api/vertical-   │           │
│  │ System       │               │    farm/register │           │
│  └──────────────┘               └──────────────────┘           │
│         │                                │                       │
│         │                                ▼                       │
│  ┌──────────────┐               ┌──────────────────┐           │
│  │ Sensors      │───Readings───→│ /api/vertical-   │           │
│  │              │               │    farm/batch/   │           │
│  │              │               │    {id}/environ  │           │
│  └──────────────┘               └──────────────────┘           │
│         │                                │                       │
│         │                                ▼                       │
│  ┌──────────────┐               ┌──────────────────┐           │
│  │ Harvest      │───Complete───→│ Transport Chain  │           │
│  │ Station      │               │ (Blockchain)     │           │
│  └──────────────┘               └──────────────────┘           │
│                                          │                       │
│                                          ▼                       │
│                                 ┌──────────────────┐           │
│                                 │ Consumer QR      │           │
│                                 │ Scan → History   │           │
│                                 └──────────────────┘           │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

## Step 1: Register Your Farm

### API Call

```typescript
POST /api/vertical-farm/register

{
  "name": "Your Farm Name",
  "ownerId": "your-user-id",

  "location": {
    "latitude": 40.7128,
    "longitude": -74.0060,
    "address": "123 Main Street",
    "city": "Brooklyn",
    "country": "USA",
    "timezone": "America/New_York"
  },

  "specs": {
    "totalAreaSqm": 500,
    "growingAreaSqm": 400,
    "numberOfLevels": 4,
    "ceilingHeightM": 4,
    "totalGrowingPositions": 5000,
    "powerCapacityKw": 150,
    "waterStorageL": 10000,
    "certifications": ["gap"],
    "buildingType": "warehouse"
  },

  "automationLevel": "semi_automated"
}
```

### Response

```json
{
  "success": true,
  "data": {
    "id": "farm-abc123",
    "name": "Your Farm Name",
    "status": "operational",
    "apiKey": "vf_key_xxxxx"  // For automation
  }
}
```

## Step 2: Configure Zones

### Create Zones

```typescript
POST /api/vertical-farm/{farmId}/zones

{
  "name": "Zone A - Lettuce",
  "level": 1,
  "areaSqm": 100,
  "growingMethod": "NFT",
  "plantPositions": 1200,
  "environmentTargets": {
    "temperatureC": { "min": 18, "max": 24, "target": 21 },
    "humidityPercent": { "min": 55, "max": 75, "target": 65 },
    "co2Ppm": { "min": 800, "max": 1400, "target": 1000 },
    "lightPpfd": { "min": 200, "max": 400, "target": 300 },
    "lightHours": 16,
    "nutrientEc": { "min": 1.2, "max": 1.8, "target": 1.5 },
    "nutrientPh": { "min": 5.5, "max": 6.5, "target": 6.0 },
    "waterTempC": { "min": 18, "max": 22, "target": 20 }
  }
}
```

## Step 3: Integrate Sensors

### Environment Reporting

Set up your control system to report environment data:

```typescript
// Every 5 minutes, send readings
async function reportEnvironment(batchId: string): Promise<void> {
  const readings = await collectSensorData();

  await fetch(`/api/vertical-farm/batch/${batchId}/environment`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${API_KEY}`
    },
    body: JSON.stringify({
      timestamp: new Date().toISOString(),
      temperatureC: readings.temperature,
      humidityPercent: readings.humidity,
      co2Ppm: readings.co2,
      ppfd: readings.light,
      dli: readings.dli,
      waterTempC: readings.waterTemp,
      ec: readings.ec,
      ph: readings.ph,
      dissolvedOxygenPpm: readings.do,
      airflowMs: readings.airflow
    })
  });
}

// Schedule reporting
setInterval(() => reportEnvironment(currentBatchId), 5 * 60 * 1000);
```

### Handle Alerts

Process alerts returned from the API:

```typescript
const response = await reportEnvironment(batchId);
const { alerts } = await response.json();

for (const alert of alerts) {
  if (alert.type.includes('critical')) {
    // Trigger immediate action
    handleCriticalAlert(alert);
  } else {
    // Log and notify
    logAlert(alert);
    notifyOperator(alert);
  }
}
```

## Step 4: Manage Crop Batches

### Start a Batch

When planting a new crop:

```typescript
POST /api/vertical-farm/batch/start

{
  "farmId": "farm-abc123",
  "zoneId": "zone-xyz789",
  "recipeId": "recipe-lettuce-butterhead",
  "seedBatchId": "seeds-lettuce-2024-001",  // Links to transport chain
  "plantCount": 200
}
```

This creates:
1. A new batch record
2. Links to the seed source (transport chain)
3. Generates plant IDs for tracking
4. Sets initial stage and targets

### Track Progress

The system automatically tracks:
- Current day and stage
- Health score based on environment
- Expected vs actual timeline

```typescript
GET /api/vertical-farm/batch/{batchId}

// Response
{
  "id": "batch-abc123",
  "currentDay": 15,
  "currentStage": "Vegetative Growth",
  "healthScore": 95,
  "status": "growing",
  "expectedHarvestDate": "2024-07-06",
  "alerts": []
}
```

### Complete Harvest

When harvesting:

```typescript
POST /api/vertical-farm/batch/{batchId}/harvest

{
  "actualYieldKg": 38.5,
  "qualityGrade": "A",
  "notes": "Excellent crop"
}
```

This automatically:
1. Records harvest in transport chain
2. Updates batch status
3. Frees zone for next batch
4. Links to distribution

## Step 5: Connect to Demand

### Check Demand Signals

```typescript
GET /api/demand/signal?lat=40.7128&lon=-74.0060&radius=25&season=summer

// Response shows gaps you can fill
{
  "demandItems": [
    {
      "produceType": "lettuce",
      "gapKg": 120,
      "urgency": "this_week"
    }
  ]
}
```

### Commit Supply

```typescript
POST /api/demand/supply

{
  "produceType": "lettuce",
  "variety": "butterhead",
  "committedQuantityKg": 50,
  "availableFrom": "2024-07-06",
  "pricePerKg": 5.00,
  "certifications": ["local_food_safety"],
  "deliveryRadiusKm": 25
}
```

## Integration Patterns

### Pattern 1: Periodic Reporting

Simple integration for basic operations:

```
Every 5 min:  Report environment
Every 1 hour: Check for alerts
Daily:        Update batch progress
On harvest:   Report completion
```

### Pattern 2: Event-Driven

Real-time integration for advanced operations:

```
On sensor change:    Report if significant
On alert trigger:    Immediate notification
On stage change:     Update setpoints
On harvest complete: Full chain update
```

### Pattern 3: Full Automation

Complete integration with automated response:

```
LocalGreenChain ←→ Control System ←→ Equipment

Demand signal  →  Start batch automatically
Recipe stage   →  Update setpoints automatically
Alert          →  Automated response
Harvest ready  →  Schedule harvest automation
```

## Webhook Integration

### Register Webhooks

Receive real-time events:

```typescript
POST /api/webhooks

{
  "url": "https://your-farm.com/webhook",
  "events": [
    "batch.stage_changed",
    "batch.alert_triggered",
    "demand.signal_generated"
  ],
  "secret": "your-webhook-secret"
}
```

### Handle Webhooks

```typescript
app.post('/webhook', (req, res) => {
  // Verify signature
  const signature = req.headers['x-lgc-signature'];
  if (!verifySignature(req.body, signature)) {
    return res.status(401).send('Invalid signature');
  }

  const { event, data } = req.body;

  switch (event) {
    case 'batch.stage_changed':
      updateControllerSetpoints(data.zoneId, data.newStage);
      break;

    case 'batch.alert_triggered':
      handleAlert(data.alert);
      break;

    case 'demand.signal_generated':
      evaluateOpportunity(data.signal);
      break;
  }

  res.status(200).send('OK');
});
```

## Data Flow Example

### Complete Cycle

```
1. SEED ACQUISITION
   - Source seeds → Record transport event
   - seedBatchId: "seeds-001"

2. START BATCH
   - Create batch with seedBatchId
   - System links to seed origin

3. GROWING
   - Report environment every 5 min
   - System tracks against recipe
   - Alerts if out of range

4. STAGE TRANSITIONS
   - System detects day changes
   - Updates stage, setpoints
   - Webhook notifies control system

5. HARVEST
   - Complete harvest API call
   - Creates transport event
   - Links to seed origin (full chain)

6. DISTRIBUTION
   - Record distribution transport
   - Generate QR code
   - Consumer can scan for full history
```

## Testing Integration

### Test Checklist

1. [ ] Farm registration successful
2. [ ] Zone creation successful
3. [ ] Environment reporting working
4. [ ] Alerts generated correctly
5. [ ] Batch creation working
6. [ ] Harvest recording working
7. [ ] Transport chain links correct
8. [ ] QR code shows full history
9. [ ] Webhooks received
10. [ ] Analytics accurate

### Test Environment

```bash
# Use development API
API_BASE=http://localhost:3001/api

# Test registration
curl -X POST $API_BASE/vertical-farm/register \
  -H "Content-Type: application/json" \
  -d '{"name": "Test Farm", ...}'
```

## Troubleshooting

### Common Issues

| Issue | Cause | Solution |
|-------|-------|----------|
| 401 Unauthorized | Invalid API key | Check API key |
| Missing alerts | Readings within range | Check thresholds |
| Wrong stage | Day calculation | Check planting date |
| No transport link | Missing seedBatchId | Include in batch start |

### Debug Mode

```typescript
// Enable detailed logging
const response = await fetch(url, {
  headers: {
    'X-Debug': 'true'
  }
});

// Response includes debug info
const { data, _debug } = await response.json();
console.log(_debug);
```

## Best Practices

1. **Consistent reporting** - Don't skip readings
2. **Accurate timestamps** - Use server time or sync
3. **Complete data** - Include all sensor values
4. **Handle errors** - Retry on failure
5. **Monitor health** - Track batch health scores
6. **Link everything** - Use seedBatchId to connect chains
