-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathesp32_simulation.py
More file actions
290 lines (243 loc) Β· 12.1 KB
/
esp32_simulation.py
File metadata and controls
290 lines (243 loc) Β· 12.1 KB
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
#!/usr/bin/env python3
"""
ESP32 Fall Detection Simulation Script
======================================
This script simulates an ESP32 wearable device sending accelerometer and gyroscope data
to the Fall Detection System backend. It can simulate:
1. Normal daily activities
2. Fall detection events
3. Continuous monitoring scenarios
Usage:
python esp32_simulation.py --mode [normal|fall|continuous]
Requirements:
pip install requests
"""
import requests
import json
import time
import random
import argparse
import datetime
from typing import Dict, Any
class ESP32Simulator:
def __init__(self, backend_url: str = "https://fall-detect-system.onrender.com",
device_id: str = "ESP32_WRISTBAND_001"):
self.backend_url = backend_url
self.device_id = device_id
self.session = requests.Session()
self.session.headers.update({'Content-Type': 'application/json'})
def generate_normal_activity_data(self) -> Dict[str, Any]:
"""Generate sensor data for normal daily activities"""
return {
"device_id": self.device_id,
"accelX": random.uniform(-0.8, 0.8), # Normal walking range
"accelY": random.uniform(-0.8, 0.8), # Side-to-side movement
"accelZ": random.uniform(9.2, 10.4), # Gravity + slight movement
"gyroX": random.uniform(-0.5, 0.5), # Minimal rotation
"gyroY": random.uniform(-0.5, 0.5), # Normal hand movement
"gyroZ": random.uniform(-0.5, 0.5) # Slight wrist rotation
}
def generate_fall_event_data(self) -> Dict[str, Any]:
"""Generate sensor data simulating a fall event"""
fall_scenarios = [
{ # Forward fall
"accelX": random.uniform(12.0, 18.0),
"accelY": random.uniform(-4.0, 4.0),
"accelZ": random.uniform(-2.0, 4.0),
"gyroX": random.uniform(150.0, 200.0),
"gyroY": random.uniform(-50.0, 50.0),
"gyroZ": random.uniform(-100.0, 100.0)
},
{ # Backward fall
"accelX": random.uniform(-18.0, -12.0),
"accelY": random.uniform(-4.0, 4.0),
"accelZ": random.uniform(-2.0, 4.0),
"gyroX": random.uniform(-200.0, -150.0),
"gyroY": random.uniform(-50.0, 50.0),
"gyroZ": random.uniform(-100.0, 100.0)
},
{ # Side fall
"accelX": random.uniform(-4.0, 4.0),
"accelY": random.uniform(12.0, 18.0),
"accelZ": random.uniform(-2.0, 4.0),
"gyroX": random.uniform(-50.0, 50.0),
"gyroY": random.uniform(150.0, 200.0),
"gyroZ": random.uniform(-100.0, 100.0)
}
]
scenario = random.choice(fall_scenarios)
return {
"device_id": self.device_id,
**scenario
}
def send_sensor_data(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""Send sensor data to the backend API"""
try:
response = self.session.post(f"{self.backend_url}/predict", json=data)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
return {"error": str(e), "success": False}
def check_backend_health(self) -> Dict[str, Any]:
"""Check if the backend is healthy and ready"""
try:
response = self.session.get(f"{self.backend_url}/health")
response.raise_for_status()
return response.json()
except requests.RequestException as e:
return {"error": str(e), "success": False}
def simulate_normal_activity(self, duration_minutes: int = 5):
"""Simulate normal daily activity for specified duration"""
print(f"πΆ Starting normal activity simulation for {duration_minutes} minutes...")
print(f"π‘ Device ID: {self.device_id}")
print(f"π― Backend: {self.backend_url}")
print("-" * 60)
start_time = time.time()
end_time = start_time + (duration_minutes * 60)
reading_count = 0
fall_alerts = 0
while time.time() < end_time:
data = self.generate_normal_activity_data()
result = self.send_sensor_data(data)
reading_count += 1
if result.get('success', True): # Assuming success if no error field
fall_detected = result.get('fall_detected', False)
confidence = result.get('confidence', 0.0)
status = "π¨ FALL ALERT!" if fall_detected else "β
Normal"
if fall_detected:
fall_alerts += 1
print(f"Reading #{reading_count:3d}: {status} "
f"(Confidence: {confidence*100:.1f}%) "
f"Accel: ({data['accelX']:.2f}, {data['accelY']:.2f}, {data['accelZ']:.2f})")
else:
print(f"β Error sending data: {result.get('error', 'Unknown error')}")
time.sleep(2) # Send data every 2 seconds
print("\n" + "="*60)
print(f"π Normal Activity Simulation Complete!")
print(f"β±οΈ Duration: {duration_minutes} minutes")
print(f"π Total readings: {reading_count}")
print(f"π¨ False alarms: {fall_alerts}")
print(f"β
Accuracy: {((reading_count - fall_alerts) / reading_count * 100):.1f}%")
def simulate_fall_event(self):
"""Simulate a single fall event"""
print("π¨ Simulating FALL EVENT...")
print(f"π‘ Device ID: {self.device_id}")
print(f"π― Backend: {self.backend_url}")
print("-" * 60)
# Send a few normal readings first
print("π Sending baseline normal activity...")
for i in range(3):
data = self.generate_normal_activity_data()
result = self.send_sensor_data(data)
print(f"Baseline {i+1}: Normal activity sent")
time.sleep(1)
# Send fall event
print("\nπ₯ FALL EVENT OCCURRING NOW!")
fall_data = self.generate_fall_event_data()
result = self.send_sensor_data(fall_data)
if result.get('success', True):
fall_detected = result.get('fall_detected', False)
confidence = result.get('confidence', 0.0)
event_id = result.get('event_id', 'N/A')
timestamp = result.get('timestamp', datetime.datetime.now().isoformat())
print(f"\nπ₯ FALL DETECTION RESULT:")
print(f" Fall Detected: {'β
YES' if fall_detected else 'β NO'}")
print(f" Confidence: {confidence*100:.1f}%")
print(f" Event ID: {event_id}")
print(f" Timestamp: {timestamp}")
print(f" Sensor Data:")
print(f" Accel: ({fall_data['accelX']:.2f}, {fall_data['accelY']:.2f}, {fall_data['accelZ']:.2f})")
print(f" Gyro: ({fall_data['gyroX']:.2f}, {fall_data['gyroY']:.2f}, {fall_data['gyroZ']:.2f})")
if fall_detected:
print("\nπ± Push notification should be sent to registered devices!")
print("π₯ Emergency contacts should be alerted!")
else:
print("\nβ οΈ Warning: Fall not detected by ML model!")
else:
print(f"β Error: {result.get('error', 'Unknown error')}")
def simulate_continuous_monitoring(self, duration_minutes: int = 10, fall_probability: float = 0.02):
"""Simulate continuous monitoring with occasional fall events"""
print(f"π Starting continuous monitoring for {duration_minutes} minutes...")
print(f"π‘ Device ID: {self.device_id}")
print(f"π― Backend: {self.backend_url}")
print(f"π² Fall probability: {fall_probability*100:.1f}% per reading")
print("-" * 60)
start_time = time.time()
end_time = start_time + (duration_minutes * 60)
reading_count = 0
total_falls = 0
detected_falls = 0
while time.time() < end_time:
reading_count += 1
# Randomly decide if this should be a fall event
is_fall_event = random.random() < fall_probability
if is_fall_event:
data = self.generate_fall_event_data()
total_falls += 1
event_type = "π¨ FALL EVENT"
else:
data = self.generate_normal_activity_data()
event_type = "π Normal"
result = self.send_sensor_data(data)
if result.get('success', True):
fall_detected = result.get('fall_detected', False)
confidence = result.get('confidence', 0.0)
if fall_detected:
detected_falls += 1
status = "π₯ DETECTED"
else:
status = "β
Normal"
print(f"Reading #{reading_count:3d}: {event_type} -> {status} "
f"(Confidence: {confidence*100:.1f}%)")
if is_fall_event and fall_detected:
print(" β
True positive: Fall correctly detected!")
elif is_fall_event and not fall_detected:
print(" β False negative: Fall missed!")
elif not is_fall_event and fall_detected:
print(" β οΈ False positive: Normal activity flagged as fall!")
else:
print(f"β Error: {result.get('error', 'Unknown error')}")
time.sleep(2)
print("\n" + "="*60)
print(f"π Continuous Monitoring Complete!")
print(f"β±οΈ Duration: {duration_minutes} minutes")
print(f"π Total readings: {reading_count}")
print(f"π¨ Actual falls: {total_falls}")
print(f"π₯ Detected falls: {detected_falls}")
if total_falls > 0:
print(f"π― Detection rate: {(detected_falls / total_falls * 100):.1f}%")
def main():
parser = argparse.ArgumentParser(description='ESP32 Fall Detection Simulator')
parser.add_argument('--mode', choices=['normal', 'fall', 'continuous'],
default='fall', help='Simulation mode')
parser.add_argument('--duration', type=int, default=5,
help='Duration in minutes (for normal/continuous modes)')
parser.add_argument('--device-id', default='ESP32_WRISTBAND_001',
help='Device ID for simulation')
parser.add_argument('--backend-url', default='https://fall-detect-system.onrender.com',
help='Backend API URL')
parser.add_argument('--fall-probability', type=float, default=0.02,
help='Fall probability per reading (continuous mode)')
args = parser.parse_args()
simulator = ESP32Simulator(args.backend_url, args.device_id)
# Check backend health first
print("π₯ Checking backend health...")
health = simulator.check_backend_health()
if health.get('error'):
print(f"β Backend health check failed: {health['error']}")
print("β οΈ Simulation may fail. Please check your backend URL and connection.")
else:
print("β
Backend is healthy and ready!")
print(f" Status: {health.get('status', 'unknown')}")
print(f" Firebase: {'β
' if health.get('firebase_connected') else 'β'}")
print(f" ML Model: {'β
' if health.get('model_loaded') else 'β'}")
print("\n" + "="*60)
# Run simulation based on mode
if args.mode == 'normal':
simulator.simulate_normal_activity(args.duration)
elif args.mode == 'fall':
simulator.simulate_fall_event()
elif args.mode == 'continuous':
simulator.simulate_continuous_monitoring(args.duration, args.fall_probability)
if __name__ == "__main__":
main()