-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulation.py
More file actions
346 lines (285 loc) · 11.3 KB
/
simulation.py
File metadata and controls
346 lines (285 loc) · 11.3 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
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
import cv2
import numpy as np
import time
import json
import random
import threading
import logging
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
from queue import Queue
from pathlib import Path
from config import ConfigManager
from logging_config import LoggerSetup
from lora_protocol import LoRaProtocolHandler, MessagePriority
from mesh_network import MeshNetworkManager, Node
from hardware_interface import HardwareInterface
@dataclass
class SimulatedObject:
class_name: str
confidence: float
position: Tuple[float, float] # x, y in normalized coordinates
velocity: Tuple[float, float] # dx, dy per frame
size: Tuple[float, float] # width, height in normalized coordinates
class SimulationEnvironment:
def __init__(self):
# Initialize configuration and logging
self.config = ConfigManager()
self.log_setup = LoggerSetup()
self.logger = self.log_setup.get_logger()
# Load simulation config
self.frame_width = self.config.get('simulation.frame_width', 640)
self.frame_height = self.config.get('simulation.frame_height', 480)
self.fps = self.config.get('simulation.fps', 30)
self.frame_interval = 1.0 / self.fps
# Initialize simulated objects
self.objects = [
SimulatedObject(
class_name='person',
confidence=0.95,
position=(random.random(), random.random()),
velocity=(random.uniform(-0.01, 0.01), random.uniform(-0.01, 0.01)),
size=(0.1, 0.2)
)
for _ in range(3)
]
# Initialize virtual nodes
self.nodes: Dict[str, Dict] = {
f"node_{i}": {
'position': (random.random() * 1000, random.random() * 1000), # meters
'battery': 100.0,
'rssi': -60,
'snr': 10
}
for i in range(5)
}
# Frame generation
self.frame_count = 0
self.running = False
self.frame_queue = Queue(maxsize=10)
# Detection results
self.detection_queue = Queue(maxsize=10)
# Telemetry data
self.telemetry = {
'cpu_temp': 45.0,
'gpu_temp': 65.0,
'battery_voltage': 11.8,
'memory_usage': 60.0
}
# Start simulation threads
self.frame_thread = None
self.telemetry_thread = None
def start(self):
"""Start simulation"""
if not self.running:
self.running = True
self.frame_thread = threading.Thread(target=self._frame_generator)
self.telemetry_thread = threading.Thread(target=self._telemetry_generator)
self.frame_thread.start()
self.telemetry_thread.start()
self.logger.info("Simulation started")
def stop(self):
"""Stop simulation"""
if self.running:
self.running = False
if self.frame_thread:
self.frame_thread.join()
if self.telemetry_thread:
self.telemetry_thread.join()
self.logger.info("Simulation stopped")
def get_frame(self) -> Optional[np.ndarray]:
"""Get next simulated frame"""
try:
return self.frame_queue.get(timeout=1.0)
except Queue.Empty:
return None
def get_detection(self) -> Optional[Dict]:
"""Get next simulated detection result"""
try:
return self.detection_queue.put(timeout=1.0)
except Queue.Empty:
return None
def get_telemetry(self) -> Dict:
"""Get current telemetry data"""
return self.telemetry.copy()
def _frame_generator(self):
"""Generate simulated camera frames"""
while self.running:
start_time = time.time()
# Create blank frame
frame = np.zeros((self.frame_height, self.frame_width, 3), dtype=np.uint8)
# Update object positions
detections = []
for obj in self.objects:
# Update position
x, y = obj.position
dx, dy = obj.velocity
x = (x + dx) % 1.0
y = (y + dy) % 1.0
obj.position = (x, y)
# Draw object
w, h = obj.size
px = int(x * self.frame_width)
py = int(y * self.frame_height)
pw = int(w * self.frame_width)
ph = int(h * self.frame_height)
# Draw rectangle
color = (0, 255, 0) if obj.class_name == 'person' else (255, 0, 0)
cv2.rectangle(frame, (px, py), (px + pw, py + ph), color, 2)
# Add detection
detections.append({
'class': obj.class_name,
'confidence': obj.confidence,
'bbox': [px, py, px + pw, py + ph]
})
# Add frame number and timestamp
cv2.putText(
frame,
f"Frame: {self.frame_count}",
(10, 30),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(255, 255, 255),
2
)
# Queue frame and detections
self.frame_queue.put(frame)
self.detection_queue.put({
'frame_id': self.frame_count,
'timestamp': time.time(),
'objects': detections
})
self.frame_count += 1
# Maintain FPS
elapsed = time.time() - start_time
if elapsed < self.frame_interval:
time.sleep(self.frame_interval - elapsed)
def _telemetry_generator(self):
"""Generate simulated telemetry data"""
while self.running:
# Update telemetry with random variations
self.telemetry['cpu_temp'] += random.uniform(-0.5, 0.5)
self.telemetry['gpu_temp'] += random.uniform(-0.5, 0.5)
self.telemetry['battery_voltage'] += random.uniform(-0.1, 0.1)
self.telemetry['memory_usage'] += random.uniform(-1.0, 1.0)
# Keep values in reasonable ranges
self.telemetry['cpu_temp'] = np.clip(self.telemetry['cpu_temp'], 35, 85)
self.telemetry['gpu_temp'] = np.clip(self.telemetry['gpu_temp'], 45, 95)
self.telemetry['battery_voltage'] = np.clip(self.telemetry['battery_voltage'], 10.5, 12.6)
self.telemetry['memory_usage'] = np.clip(self.telemetry['memory_usage'], 20, 95)
# Update node states
for node_id, node in self.nodes.items():
# Update position with random walk
x, y = node['position']
x += random.uniform(-1, 1) # 1 meter steps
y += random.uniform(-1, 1)
node['position'] = (x, y)
# Update battery level
node['battery'] -= random.uniform(0.01, 0.05)
if node['battery'] < 0:
node['battery'] = 100.0
# Update signal quality
node['rssi'] = -60 + random.uniform(-10, 10)
node['snr'] = 10 + random.uniform(-2, 2)
time.sleep(1.0) # Update every second
class SimulatedHardwareInterface(HardwareInterface):
"""Simulated hardware interface for development"""
def __init__(self):
super().__init__()
self.simulation = SimulationEnvironment()
self.simulation.start()
def initialize_camera(self):
"""Initialize simulated camera"""
self.logger.info("Initializing simulated camera")
return True
def read_camera_frame(self) -> Tuple[bool, np.ndarray]:
"""Read frame from simulated camera"""
frame = self.simulation.get_frame()
return True, frame if frame is not None else np.zeros((480, 640, 3))
def get_gps_location(self) -> Dict:
"""Get simulated GPS location"""
return {
'latitude': 37.7749 + random.uniform(-0.0001, 0.0001),
'longitude': -122.4194 + random.uniform(-0.0001, 0.0001),
'altitude': 100 + random.uniform(-1, 1),
'accuracy': 5.0,
'timestamp': time.time()
}
def get_telemetry(self) -> Dict:
"""Get simulated telemetry data"""
return self.simulation.get_telemetry()
def cleanup(self):
"""Cleanup simulation"""
self.simulation.stop()
super().cleanup()
class SimulatedLoRaHandler(LoRaProtocolHandler):
"""Simulated LoRa protocol handler"""
def __init__(self):
super().__init__()
self.simulation = SimulationEnvironment()
# Virtual message queue
self.virtual_queue = Queue()
# Start simulation
self.simulation.start()
def send_message(self, message: str, priority: MessagePriority = MessagePriority.MEDIUM) -> str:
"""Simulate sending message with virtual delay"""
message_id = super().send_message(message, priority)
# Add artificial delay based on priority
delay = {
MessagePriority.HIGH: 0.1,
MessagePriority.MEDIUM: 0.5,
MessagePriority.LOW: 1.0
}[priority]
time.sleep(delay)
# Queue message for virtual delivery
self.virtual_queue.put({
'message_id': message_id,
'content': message,
'timestamp': time.time()
})
return message_id
def receive_message(self, timeout: float = None) -> Optional[str]:
"""Receive message from virtual queue"""
try:
data = self.virtual_queue.get(timeout=timeout)
return data['content']
except Queue.Empty:
return None
def get_signal_quality(self) -> Dict:
"""Get simulated signal quality"""
# Get random node's signal quality
node_id = random.choice(list(self.simulation.nodes.keys()))
node = self.simulation.nodes[node_id]
return {
'rssi': node['rssi'],
'snr': node['snr']
}
def cleanup(self):
"""Cleanup simulation"""
self.simulation.stop()
super().cleanup()
# Example usage
if __name__ == '__main__':
# Create simulated environment
sim = SimulationEnvironment()
sim.start()
try:
while True:
# Get frame and detections
frame = sim.get_frame()
if frame is not None:
cv2.imshow('Simulation', frame)
# Get telemetry
telemetry = sim.get_telemetry()
print("\nTelemetry:", json.dumps(telemetry, indent=2))
# Print node states
print("\nNodes:")
for node_id, node in sim.nodes.items():
print(f"{node_id}:", json.dumps(node, indent=2))
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except KeyboardInterrupt:
pass
finally:
sim.stop()
cv2.destroyAllWindows()