# Architecture Documentation

## System Architecture Overview

The Agriculture Robot Control System is built with a modern, scalable architecture that separates concerns between frontend, backend, and communication layers.

## Architecture Principles

1. **Modularity**: Each component is self-contained and can be developed/tested independently
2. **Scalability**: Designed to handle multiple robots and concurrent users
3. **Real-time Communication**: WebSocket for low-latency bidirectional communication
4. **Type Safety**: Full TypeScript implementation for reliability
5. **Extensibility**: Easy to add new features and integrate with external systems

## Component Architecture

### Frontend Architecture

```
┌─────────────────────────────────────────────────────┐
│                    React Application                 │
├─────────────────────────────────────────────────────┤
│                                                       │
│  ┌──────────────────────────────────────────────┐   │
│  │           Routing Layer (React Router)         │   │
│  └──────────────────────────────────────────────┘   │
│                       ↓                               │
│  ┌──────────────────────────────────────────────┐   │
│  │         Page Components (Views)               │   │
│  │  - Dashboard  - RobotControl  - FieldMap     │   │
│  │  - Sensors    - Camera       - Diagnostics  │   │
│  └──────────────────────────────────────────────┘   │
│                       ↓                               │
│  ┌──────────────────────────────────────────────┐   │
│  │      Context Layer (State Management)         │   │
│  │  - WebSocketContext (Real-time data)         │   │
│  └──────────────────────────────────────────────┘   │
│                       ↓                               │
│  ┌──────────────────────────────────────────────┐   │
│  │      Communication Layer                        │   │
│  │  - REST API Client  - WebSocket Client         │   │
│  └──────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────┘
```

### Backend Architecture

```
┌─────────────────────────────────────────────────────┐
│              Express Server (Node.js)                  │
├─────────────────────────────────────────────────────┤
│                                                       │
│  ┌──────────────────────────────────────────────┐   │
│  │            HTTP Server Layer                  │   │
│  │  - REST API Endpoints  - Middleware          │   │
│  └──────────────────────────────────────────────┘   │
│                       ↓                               │
│  ┌──────────────────────────────────────────────┐   │
│  │            Route Handlers                     │   │
│  │  - /api/robot  - /api/sensors                │   │
│  │  - /api/field - /api/diagnostics             │   │
│  └──────────────────────────────────────────────┘   │
│                       ↓                               │
│  ┌──────────────────────────────────────────────┐   │
│  │            Service Layer                      │   │
│  │  - RobotSimulator  - WebSocketManager        │   │
│  │  - SensorService  - FieldService             │   │
│  └──────────────────────────────────────────────┘   │
│                       ↓                               │
│  ┌──────────────────────────────────────────────┐   │
│  │         Communication Layer                    │   │
│  │  - WebSocket Server  - MQTT Client (ready)  │   │
│  │  - REST API         - Hardware Interface    │   │
│  └──────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────┘
```

## Data Flow

### Robot Control Flow

```
User Action (Frontend)
    ↓
React Component
    ↓
WebSocket/REST API Call
    ↓
Backend Route Handler
    ↓
Robot Simulator Service
    ↓
State Update
    ↓
WebSocket Broadcast
    ↓
Frontend Update (Real-time)
```

### Sensor Data Flow

```
Robot Hardware/Simulator
    ↓
Sensor Service
    ↓
Data Processing
    ↓
WebSocket Broadcast
    ↓
Frontend WebSocket Context
    ↓
React Component Update
    ↓
UI Rendering (Charts, Cards)
```

## Communication Protocols

### REST API

**Purpose**: Standard HTTP requests for operations that don't require real-time updates.

**Use Cases**:
- Initial data loading
- Configuration changes
- Historical data retrieval
- One-time commands

**Example**:
```typescript
POST /api/robot/move
{
  "direction": "forward",
  "speed": 50
}
```

### WebSocket

**Purpose**: Real-time bidirectional communication for live updates.

**Use Cases**:
- Robot state updates
- Sensor data streaming
- Live position tracking
- Alert notifications

**Message Format**:
```typescript
{
  type: 'robot_state',
  payload: { ... },
  timestamp: '2024-01-01T12:00:00Z'
}
```

### MQTT (Ready for Integration)

**Purpose**: IoT device communication and edge computing integration.

**Implementation**: Structure is ready, requires MQTT broker setup.

## State Management

### Frontend State

1. **Component State**: Local component state using React hooks
2. **Context State**: Global state via WebSocketContext
3. **Server State**: Data fetched from API endpoints

### Backend State

1. **Robot State**: Managed by RobotSimulator service
2. **Field Data**: In-memory storage (can be migrated to database)
3. **Diagnostics Log**: In-memory array (can be migrated to database)

## Scalability Considerations

### Horizontal Scaling

- **Stateless Backend**: Backend services are stateless, allowing multiple instances
- **Load Balancing**: Can use load balancer for multiple backend instances
- **Database**: Ready for database integration (PostgreSQL, MongoDB, etc.)

### Vertical Scaling

- **WebSocket Connections**: Can handle thousands of concurrent connections
- **API Throughput**: Express server optimized for high throughput
- **Frontend**: React application optimized with code splitting

### Multi-Robot Support

The architecture supports multiple robots through:
- Robot ID in state management
- Separate WebSocket channels per robot
- Database schema ready for multi-robot data

## Security Considerations

### Current Implementation
- CORS configuration
- Input validation
- Error handling

### Production Recommendations
- JWT authentication
- HTTPS/WSS encryption
- Rate limiting
- API key management
- Role-based access control

## Database Integration (Future)

### Recommended Schema

```sql
-- Robots table
CREATE TABLE robots (
  id UUID PRIMARY KEY,
  name VARCHAR(255),
  status VARCHAR(50),
  mode VARCHAR(50),
  position JSONB,
  created_at TIMESTAMP
);

-- Sensor readings table
CREATE TABLE sensor_readings (
  id UUID PRIMARY KEY,
  robot_id UUID REFERENCES robots(id),
  sensor_type VARCHAR(50),
  value DECIMAL,
  timestamp TIMESTAMP
);

-- Field data table
CREATE TABLE fields (
  id UUID PRIMARY KEY,
  name VARCHAR(255),
  boundaries JSONB,
  waypoints JSONB,
  created_at TIMESTAMP
);

-- Diagnostics log table
CREATE TABLE diagnostics_log (
  id UUID PRIMARY KEY,
  robot_id UUID REFERENCES robots(id),
  type VARCHAR(50),
  message TEXT,
  component VARCHAR(100),
  resolved BOOLEAN,
  timestamp TIMESTAMP
);
```

## Integration Points

### Hardware Integration

Replace `RobotSimulator` with actual hardware communication:

```typescript
// Example: Replace simulator with hardware interface
class RobotHardwareInterface {
  async sendCommand(command: RobotCommand) {
    // Send to actual robot via serial, TCP, or other protocol
  }
  
  async getSensorData() {
    // Read from actual sensors
  }
}
```

### MQTT Integration

```typescript
// MQTT client setup
import mqtt from 'mqtt';

const mqttClient = mqtt.connect(process.env.MQTT_BROKER_URL);

mqttClient.on('connect', () => {
  mqttClient.subscribe(`${process.env.MQTT_TOPIC_PREFIX}/+/sensors`);
  mqttClient.subscribe(`${process.env.MQTT_TOPIC_PREFIX}/+/status`);
});

mqttClient.on('message', (topic, message) => {
  // Process MQTT messages
  const data = JSON.parse(message.toString());
  // Broadcast to WebSocket clients
});
```

### OpenCV Integration

```typescript
// Frontend: OpenCV.js integration
import cv from 'opencv-js';

function processFrame(video: HTMLVideoElement, canvas: HTMLCanvasElement) {
  const src = cv.imread(video);
  const dst = new cv.Mat();
  
  // Apply computer vision processing
  cv.cvtColor(src, dst, cv.COLOR_RGBA2GRAY);
  cv.Canny(dst, dst, 50, 100);
  
  cv.imshow(canvas, dst);
  src.delete();
  dst.delete();
}
```

## Performance Optimization

### Frontend
- Code splitting with React.lazy()
- Memoization for expensive computations
- Virtual scrolling for large lists
- Image optimization

### Backend
- Connection pooling for database
- Caching for frequently accessed data
- Compression for API responses
- WebSocket message batching

## Monitoring & Logging

### Recommended Tools
- **Application Monitoring**: New Relic, Datadog
- **Error Tracking**: Sentry
- **Logging**: Winston, Pino
- **Metrics**: Prometheus, Grafana

### Logging Strategy
```typescript
// Structured logging
logger.info('Robot command executed', {
  robotId: 'robot-001',
  command: 'move',
  direction: 'forward',
  timestamp: new Date().toISOString()
});
```

## Deployment Architecture

### Development
- Local development servers
- Hot reload for both frontend and backend

### Production
- Frontend: Static hosting (Vercel, Netlify, AWS S3)
- Backend: Containerized deployment (Docker, Kubernetes)
- Database: Managed database service
- WebSocket: WebSocket server or API Gateway

## Future Architecture Enhancements

1. **Microservices**: Split into separate services (robot-service, sensor-service, etc.)
2. **Message Queue**: Add Redis/RabbitMQ for async processing
3. **Caching Layer**: Redis for frequently accessed data
4. **CDN**: Content delivery network for static assets
5. **Edge Computing**: Process data closer to robots for lower latency

