Spaces:
Running
Running
File size: 15,536 Bytes
53c9876 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | # System Architecture
## Overview
The Water Quality Monitoring System follows a modern full-stack architecture using Next.js for both frontend and backend, MongoDB for data persistence, and MQTT for real-time sensor data ingestion.
## Architecture Diagram
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PRESENTATION LAYER β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Next.js Frontend (React 18) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β
β β β’ SensorMap Component (Leaflet.js) β β
β β β’ Dashboard with Charts (Recharts) β β
β β β’ Real-time Updates (Polling) β β
β β β’ Responsive UI (Tailwind CSS) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β² β
β β HTTP/REST β
β βΌ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β APPLICATION LAYER β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Next.js API Routes (Node.js) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β
β β GET /api/sensors - List all sensors β β
β β POST /api/sensors - Create new sensor β β
β β GET /api/readings - Get historical readings β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β² β
β β β
β βΌ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DATA LAYER β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β MongoDB Database β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β
β β β’ sensors collection β β
β β - sensorId (indexed) β β
β β - location (2dsphere index) β β
β β β β
β β β’ readings collection β β
β β - sensorId + timestamp (compound index) β β
β β - timestamp (indexed for queries) β β
β β β β
β β Retention: 5 years β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β² β
βββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ
β INGESTION LAYER β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β MQTT Ingestion Service (Node.js) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β
β β β’ Subscribe to MQTT topics β β
β β β’ Validate incoming readings β β
β β β’ Store in MongoDB β β
β β β’ Error handling & logging β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β² β
β β MQTT Protocol β
β β β
βββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ
β SENSOR LAYER β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β Sensor 1 β β Sensor 2 β β Sensor N β β
β βββββββββββββββ€ βββββββββββββββ€ βββββββββββββββ€ β
β β β’ pH β β β’ pH β β β’ pH β β
β β β’ Turbidity β β β’ Turbidity β β β’ Turbidity β β
β β β’ Temp β β β’ Temp β β β’ Temp β β
β β β’ Hardness β β β’ Hardness β β β’ Hardness β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β
β Fixed geographic locations β
β Random transmission intervals β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
## Component Details
### 1. Frontend (React/Next.js)
**Key Components:**
- `SensorMap`: Main container component managing state
- `MapView`: Leaflet.js integration for interactive mapping
- `SensorDashboard`: Charts and statistics display
**Features:**
- Interactive global map with zoomable interface
- Marker clustering for performance
- Real-time data updates (30-second polling)
- Responsive design for mobile/desktop
- Time-series visualization with Recharts
**State Management:**
- React hooks (useState, useEffect)
- Local component state
- No Redux/Context needed (simple state)
### 2. API Layer (Next.js API Routes)
**Endpoints:**
```typescript
GET /api/sensors
Response: SensorWithLatestReading[]
- Returns all sensors with their most recent reading
- Efficient aggregation using MongoDB pipelines
GET /api/readings?sensorId=XXX&timeRange=1d
Response: Reading[]
- Time-filtered readings for a specific sensor
- Supports: 1h, 1d, 1w, 1m, custom ranges
- Optimized queries with indexed timestamps
POST /api/sensors
Request: { sensorId, latitude, longitude, locationName? }
Response: Sensor
- Create new sensor record
- Auto-generates installedAt timestamp
```
**Features:**
- RESTful design
- Input validation
- Error handling with proper status codes
- Connection pooling for MongoDB
### 3. MQTT Ingestion Service
**Responsibilities:**
- Subscribe to MQTT broker topics
- Parse and validate incoming JSON messages
- Store validated readings in MongoDB
- Log invalid/malformed messages
- Handle connection failures gracefully
**Data Validation:**
```javascript
{
sensorId: required,
timestamp: required (ISO date),
pH: 0-14,
turbidity: >= 0,
temperature: -50 to 100Β°C,
hardness: >= 0
}
```
**Error Handling:**
- Retry logic for MongoDB failures
- Graceful reconnection to MQTT broker
- Detailed error logging
### 4. Database (MongoDB)
**Collections:**
**sensors:**
```javascript
{
_id: ObjectId,
sensorId: "SENSOR_XXX_001",
latitude: 40.7128,
longitude: -74.0060,
locationName: "New York City",
installedAt: ISODate("2020-01-15")
}
```
Indexes:
- `{ sensorId: 1 }` - Unique index for lookups
- `{ location: "2dsphere" }` - Geospatial queries
**readings:**
```javascript
{
_id: ObjectId,
sensorId: "SENSOR_XXX_001",
timestamp: ISODate("2024-02-16T10:30:00Z"),
pH: 7.2,
turbidity: 3.5,
temperature: 22.1,
hardness: 150.0
}
```
Indexes:
- `{ sensorId: 1, timestamp: -1 }` - Compound index for sensor queries
- `{ timestamp: -1 }` - Time-based filtering
**Retention Policy:**
- TTL index for 5-year retention (future implementation)
- Archive strategy for historical data
## Data Flow
### 1. Sensor Reading Flow
```
Sensor Device
β
β MQTT Publish
βΌ
MQTT Broker (HiveMQ)
β
β Subscribe
βΌ
Ingestion Service
β
β Validate
βΌ
MongoDB (readings)
β
β Query (via API)
βΌ
Next.js Frontend
β
β Render
βΌ
User Browser
```
### 2. User Query Flow
```
User clicks sensor
β
βΌ
Frontend fetches data
β
βΌ
API Route handler
β
βΌ
MongoDB query
β
βΌ
Data aggregation
β
βΌ
JSON response
β
βΌ
Chart rendering
```
## Scalability Considerations
### Current Scale
- 10-100 sensors: Easily handled
- 1 reading/sensor/hour: ~240 readings/day per sensor
- 5 years retention: ~440K readings per sensor
### Scaling Strategies
**Horizontal Scaling:**
- Multiple MQTT ingestion workers
- Load balancer for Next.js instances
- MongoDB replica sets
**Vertical Scaling:**
- Increased server resources
- MongoDB sharding by sensorId
- Redis caching layer
**Optimization:**
- Data aggregation pre-computation
- CDN for static assets
- Query result caching
## Security Considerations
**Current Status (Development):**
- No authentication (as per PRD requirements)
- Public MQTT broker
- Open API endpoints
**Production Recommendations:**
- JWT authentication for APIs
- MQTT broker with TLS/SSL
- Role-based access control
- API rate limiting
- Input sanitization
- Environment variable protection
## Monitoring & Observability
**Recommended Tools:**
- Application logs (Winston/Pino)
- MongoDB Atlas monitoring
- MQTT broker metrics
- Error tracking (Sentry)
- Performance monitoring (New Relic)
**Key Metrics:**
- Sensor uptime
- Reading ingestion rate
- API response times
- Database query performance
- Error rates
## Technology Choices Rationale
| Technology | Reason |
|-----------|--------|
| Next.js | Full-stack framework, API routes, SSR/SSG |
| MongoDB | Flexible schema, time-series data, geospatial queries |
| MQTT | Lightweight, efficient for IoT, publish-subscribe |
| Leaflet | Open-source, customizable mapping |
| Recharts | React-friendly, responsive charts |
| TypeScript | Type safety, better developer experience |
## Future Enhancements
1. **Real-time Updates**: WebSocket integration
2. **Advanced Analytics**: ML-based anomaly detection
3. **Alerting System**: Email/SMS notifications
4. **Data Export**: CSV/PDF generation
5. **Mobile App**: React Native implementation
6. **Admin Panel**: Sensor management interface
7. **Authentication**: User accounts and permissions
8. **Caching Layer**: Redis for frequently accessed data
---
This architecture supports the current requirements while providing a foundation for future enhancements and scale.
|