File size: 8,395 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
---
title: Water Quality Monitor
emoji: πŸ’§
colorFrom: blue
colorTo: green
sdk: docker
app_port: 3000
---

# 1Water Quality Monitoring System

A full-stack Next.js application for monitoring and visualizing water quality measurements from geographically distributed sensors worldwide.

## 🌟 Features

- **Real-time Monitoring**: MQTT-based ingestion of sensor data
- **Interactive Global Map**: Visualize sensor locations with Leaflet.js
- **Historical Analysis**: Time-series charts for water quality metrics
- **Responsive Dashboard**: Detailed sensor views with customizable time ranges
- **Scalable Architecture**: MongoDB storage with efficient indexing
- **RESTful APIs**: Backend endpoints for data retrieval

## πŸ“Š Water Quality Metrics

- **pH**: Acidity or alkalinity of water (0-14)
- **Turbidity**: Water clarity measurement (NTU)
- **Temperature**: Water temperature (Β°C)
- **Hardness**: Mineral concentration in water (mg/L)

## πŸ› οΈ Tech Stack

- **Frontend**: Next.js 14, React, TypeScript, Tailwind CSS
- **Backend**: Next.js API Routes, Node.js
- **Database**: MongoDB
- **Mapping**: Leaflet.js, React-Leaflet
- **Charts**: Recharts
- **Messaging**: MQTT (HiveMQ)

## πŸ“‹ Prerequisites

- Node.js 18+ and npm
- MongoDB (local or cloud instance)
- MQTT Broker (HiveMQ public broker by default)

## πŸš€ Installation

1. **Clone the repository**
   ```bash
   cd water-quality-monitoring
   ```

2. **Install dependencies**
   ```bash
   npm install
   ```

3. **Configure environment variables**
   
   Edit `.env.local` with your configuration:
   ```env
   MONGODB_URI=mongodb://localhost:27017/water_quality
   MQTT_BROKER=mqtt://broker.hivemq.com:1883
   MQTT_TOPIC=sensors/water-quality/#
   ```

4. **Start MongoDB**
   
   If running locally:
   ```bash
   # macOS with Homebrew
   brew services start mongodb-community
   
   # Linux
   sudo systemctl start mongod
   
   # Windows
   net start MongoDB
   ```

5. **Seed the database with sample data**
   ```bash
   node scripts/seedDatabase.js
   ```

## πŸƒ Running the Application

### Development Mode

Start the Next.js development server:
```bash
npm run dev
```

The application will be available at `http://localhost:3000`

### MQTT Ingestion Service

In a separate terminal, start the MQTT ingestion service:
```bash
npm run mqtt:start
```

This service subscribes to MQTT topics and stores incoming sensor readings in MongoDB.

### Sensor Simulator (Optional)

To simulate sensor data for testing:
```bash
node scripts/simulateSensors.js
```

This will publish random sensor readings to the MQTT broker.

## πŸ“ Project Structure

```
water-quality-monitoring/
β”œβ”€β”€ app/                      # Next.js app directory
β”‚   β”œβ”€β”€ api/                  # API routes
β”‚   β”‚   β”œβ”€β”€ sensors/          # Sensor endpoints
β”‚   β”‚   └── readings/         # Readings endpoints
β”‚   β”œβ”€β”€ sensor/               # Dynamic sensor routes
β”‚   β”‚   └── [sensorId]/       # Individual sensor pages
β”‚   β”‚       β”œβ”€β”€ page.tsx      # Sensor detail page
β”‚   β”‚       └── not-found.tsx # 404 page
β”‚   β”œβ”€β”€ globals.css           # Global styles
β”‚   β”œβ”€β”€ layout.tsx            # Root layout
β”‚   └── page.tsx              # Home page (map view)
β”œβ”€β”€ components/               # React components
β”‚   β”œβ”€β”€ SensorMap.tsx         # Main map interface
β”‚   β”œβ”€β”€ MapView.tsx           # Leaflet map component
β”‚   β”œβ”€β”€ SensorDashboard.tsx   # Charts and statistics
β”‚   β”œβ”€β”€ SensorDetailPage.tsx  # Full sensor page
β”‚   └── MiniMap.tsx           # Small location map
β”œβ”€β”€ lib/                      # Utilities and types
β”‚   β”œβ”€β”€ mongodb.ts            # Database connection
β”‚   └── types.ts              # TypeScript types
β”œβ”€β”€ services/                 # Background services
β”‚   └── mqttIngestion.js      # MQTT subscriber
β”œβ”€β”€ scripts/                  # Utility scripts
β”‚   β”œβ”€β”€ seedDatabase.js       # Database seeding
β”‚   └── simulateSensors.js    # Sensor simulation
β”œβ”€β”€ .env.local                # Environment variables
β”œβ”€β”€ package.json              # Dependencies
β”œβ”€β”€ tsconfig.json             # TypeScript config
└── next.config.js            # Next.js config
```

## πŸ”Œ API Endpoints

### Get All Sensors
```
GET /api/sensors
```
Returns all sensors with their latest readings.

### Create Sensor
```
POST /api/sensors
Content-Type: application/json

{
  "sensorId": "SENSOR_XXX_001",
  "latitude": 40.7128,
  "longitude": -74.0060,
  "locationName": "Location Name"
}
```

### Get Sensor Readings
```
GET /api/readings?sensorId=SENSOR_XXX_001&timeRange=1d
```

Query Parameters:
- `sensorId` (required): Sensor identifier
- `timeRange`: `1h`, `1d`, `1w`, `1m`
- `startDate`: ISO date string (for custom range)
- `endDate`: ISO date string (for custom range)

## πŸ“Š Database Schema

### Sensors Collection
```javascript
{
  sensorId: String,      // Unique identifier
  latitude: Number,      // Geographic latitude
  longitude: Number,     // Geographic longitude
  locationName: String,  // Optional location name
  installedAt: Date      // Installation timestamp
}
```

### Readings Collection
```javascript
{
  sensorId: String,      // Reference to sensor
  timestamp: Date,       // Reading timestamp
  pH: Number,           // pH level (0-14)
  turbidity: Number,    // Turbidity (NTU)
  temperature: Number,  // Temperature (Β°C)
  hardness: Number      // Hardness (mg/L)
}
```

## 🎯 Usage

### Routes

- **`/`** - Main map view with all sensors
- **`/sensor/[sensorId]`** - Individual sensor dashboard page
  - Example: `/sensor/SENSOR_NYC_001`
  - Direct link to specific sensor with full dashboard
  - Bookmarkable and shareable URLs

### Navigation

1. **View All Sensors**: Visit the home page to see the interactive map
2. **Quick Preview**: Hover over any sensor marker for current readings
3. **Overlay Dashboard**: Click a sensor marker to open side panel with charts
4. **Full Dashboard**: Click "Open Full Dashboard" or visit `/sensor/[sensorId]` directly
5. **Return to Map**: Click the back arrow on any sensor page

### Features by View

**Map View (`/`):**
- Interactive global map
- All sensors displayed
- Quick hover previews
- Click for overlay dashboard

**Sensor Detail Page (`/sensor/[sensorId]`):**
- Dedicated page for each sensor
- Current readings with icons
- Mini location map
- Full historical charts
- Auto-refresh every 30 seconds
- Shareable URL

## πŸ”’ Data Validation

The MQTT ingestion service validates all incoming readings:
- All required fields must be present
- pH: 0-14 range
- Turbidity: Non-negative
- Temperature: -50Β°C to 100Β°C
- Hardness: Non-negative

Invalid messages are logged and rejected.

## πŸ“ˆ Performance Optimizations

- **Database Indexes**: Optimized queries with compound indexes
- **Caching**: Connection pooling for MongoDB
- **Efficient Querying**: Time-based filtering with indexed timestamps
- **Lazy Loading**: Dynamic imports for map components

## 🚧 Future Enhancements

- Water quality safety alerts
- Sensor offline detection
- Data export functionality (CSV, PDF)
- Predictive analytics using historical trends
- Real-time WebSocket streaming
- User authentication and access control
- Mobile app integration
- Alert notifications via email/SMS

## πŸ› Troubleshooting

### MongoDB Connection Issues
```bash
# Check MongoDB status
mongosh --eval "db.runCommand({ ping: 1 })"
```

### MQTT Connection Issues
- Verify broker URL is correct
- Check network connectivity
- Ensure no firewall blocking port 1883

### Port Already in Use
```bash
# Kill process on port 3000
lsof -ti:3000 | xargs kill -9
```

## πŸ“ Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `MONGODB_URI` | MongoDB connection string | `mongodb://localhost:27017/water_quality` |
| `MQTT_BROKER` | MQTT broker URL | `mqtt://broker.hivemq.com:1883` |
| `MQTT_TOPIC` | MQTT topic pattern | `sensors/water-quality/#` |

## πŸ“„ License

This project is licensed under the MIT License.

## 🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## πŸ“§ Support

For issues and questions, please open an issue on the repository.

---

Built with ❀️ using Next.js and MongoDB