- Add guides: quick-start, installation, configuration, grower, consumer, transport, vertical-farm - Add API references: REST, demand, vertical-farming - Add concepts: blockchain, seasonal-planning, carbon-footprint - Add architecture: data-flow, transport-tracking - Add vertical-farming: environmental-control, automation, integration - Add examples: seed-to-harvest, demand-driven-planting, vertical-farm-setup Completes Agent_5 documentation tasks from AGENT_REPORT.md
12 KiB
12 KiB
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
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
{
"success": true,
"data": {
"id": "farm-abc123",
"name": "Your Farm Name",
"status": "operational",
"apiKey": "vf_key_xxxxx" // For automation
}
}
Step 2: Configure Zones
Create Zones
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:
// 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:
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:
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:
- A new batch record
- Links to the seed source (transport chain)
- Generates plant IDs for tracking
- Sets initial stage and targets
Track Progress
The system automatically tracks:
- Current day and stage
- Health score based on environment
- Expected vs actual timeline
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:
POST /api/vertical-farm/batch/{batchId}/harvest
{
"actualYieldKg": 38.5,
"qualityGrade": "A",
"notes": "Excellent crop"
}
This automatically:
- Records harvest in transport chain
- Updates batch status
- Frees zone for next batch
- Links to distribution
Step 5: Connect to Demand
Check Demand Signals
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
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:
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
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
- Farm registration successful
- Zone creation successful
- Environment reporting working
- Alerts generated correctly
- Batch creation working
- Harvest recording working
- Transport chain links correct
- QR code shows full history
- Webhooks received
- Analytics accurate
Test Environment
# 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
// 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
- Consistent reporting - Don't skip readings
- Accurate timestamps - Use server time or sync
- Complete data - Include all sensor values
- Handle errors - Retry on failure
- Monitor health - Track batch health scores
- Link everything - Use seedBatchId to connect chains