-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
961 lines (806 loc) · 30 KB
/
Copy pathcli.py
File metadata and controls
961 lines (806 loc) · 30 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
#!/usr/bin/env python3
"""
SpaceSense - WiFi Spatial Intelligence Sensing Engine CLI.
Command-line interface for monitoring, analyzing, and exporting
WiFi-based spatial intelligence data.
Usage:
python cli.py monitor [--config FILE] [--sensitivity N] [--zones Z1,Z2,...]
python cli.py analyze --input FILE [--output FILE]
python cli.py export --input FILE --format FORMAT [--output-dir DIR]
python cli.py demo [--duration SECONDS] [--scenario SCENARIO]
python cli.py config [--show] [--reset] [--output FILE]
"""
import argparse
import json
import math
import os
import random
import sys
import time
from typing import Any, Dict, List, Optional
# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from spacesense import (
ActivityRecognizer,
AlertManager,
Config,
DataExporter,
PatternMatcher,
PresenceDetector,
SignalAnalyzer,
SignalProcessor,
TrendDetector,
ZoneMonitor,
__version__,
)
from spacesense.tui import create_dashboard
from spacesense.utils import Color, ProgressBar
# ---------------------------------------------------------------------------
# Demo Data Generator
# ---------------------------------------------------------------------------
class DemoDataGenerator:
"""Generate realistic simulated WiFi RSSI data for demonstration.
Produces signal patterns that mimic real WiFi signal behavior
including noise, multi-path fading, and human-induced variations.
Attributes:
base_rssi: Base RSSI level in dBm.
noise_level: Standard deviation of Gaussian noise.
scenario: Current simulation scenario.
"""
SCENARIOS = ["empty_room", "person_still", "person_walking", "person_running", "mixed"]
def __init__(
self,
base_rssi: float = -55.0,
noise_level: float = 0.5,
scenario: str = "mixed",
) -> None:
"""Initialize the DemoDataGenerator.
Args:
base_rssi: Base RSSI level in dBm.
noise_level: Gaussian noise standard deviation.
scenario: Simulation scenario name.
"""
self.base_rssi = base_rssi
self.noise_level = noise_level
self.scenario = scenario
self._step = 0
self._phase = 0.0
self._current_activity = "still"
self._activity_timer = 0
self._activity_duration = 50
def generate_sample(self, sensor_id: str = "default") -> float:
"""Generate a single RSSI sample.
Args:
sensor_id: Sensor identifier for multi-sensor scenarios.
Returns:
Simulated RSSI value in dBm.
"""
self._step += 1
self._phase += 0.1
# Base signal with slow drift
drift = 0.3 * math.sin(self._phase * 0.05)
base = self.base_rssi + drift
# Gaussian noise
noise = random.gauss(0, self.noise_level)
# Activity-dependent signal variation
activity_signal = self._activity_signal()
# Sensor-specific offset
sensor_offsets = {"default": 0.0, "sensor_a": -2.0, "sensor_b": 1.5, "sensor_c": -0.5}
offset = sensor_offsets.get(sensor_id, 0.0)
# Multi-path fading (occasional deep fades)
fade = 0.0
if random.random() < 0.02:
fade = random.uniform(-5, -2)
value = base + noise + activity_signal + offset + fade
return max(-100.0, min(-20.0, value))
def _activity_signal(self) -> float:
"""Generate activity-dependent signal variation.
Returns:
Signal variation in dBm based on current simulated activity.
"""
self._activity_timer += 1
# Switch activities periodically
if self.scenario == "mixed" and self._activity_timer >= self._activity_duration:
self._cycle_activity()
self._activity_timer = 0
self._activity_duration = random.randint(30, 80)
if self.scenario == "empty_room":
self._current_activity = "still"
elif self.scenario == "person_still":
self._current_activity = "sitting"
elif self.scenario == "person_walking":
self._current_activity = "walking"
elif self.scenario == "person_running":
self._current_activity = "running"
signal = 0.0
if self._current_activity == "still":
signal = random.gauss(0, 0.2)
elif self._current_activity == "sitting":
signal = random.gauss(0, 0.5) + 0.3 * math.sin(self._phase * 0.2)
elif self._current_activity == "walking":
signal = 2.0 * math.sin(self._phase * 0.5) + random.gauss(0, 0.8)
elif self._current_activity == "running":
signal = 4.0 * math.sin(self._phase * 1.0) + random.gauss(0, 1.2)
elif self._current_activity == "approaching":
signal = -0.1 * self._step + random.gauss(0, 0.5)
elif self._current_activity == "leaving":
signal = 0.1 * self._step + random.gauss(0, 0.5)
elif self._current_activity == "falling":
signal = 8.0 * math.exp(-((self._step % 20) - 10) ** 2 / 8) + random.gauss(0, 1.5)
return signal
def _cycle_activity(self) -> None:
"""Cycle to the next activity in the simulation."""
activities = ["still", "sitting", "walking", "running", "approaching", "leaving"]
current_idx = activities.index(self._current_activity) if self._current_activity in activities else 0
self._current_activity = activities[(current_idx + 1) % len(activities)]
@property
def current_activity(self) -> str:
"""Get the currently simulated activity."""
return self._current_activity
# ---------------------------------------------------------------------------
# Command Handlers
# ---------------------------------------------------------------------------
def cmd_monitor(args: argparse.Namespace) -> int:
"""Handle the 'monitor' subcommand - real-time monitoring mode.
Args:
args: Parsed command-line arguments.
Returns:
Exit code (0 for success).
"""
config = Config()
if args.config:
try:
config.load_file(args.config)
except (FileNotFoundError, ValueError) as e:
print(f"Error loading config: {e}", file=sys.stderr)
return 1
if args.sensitivity:
config.set("presence.variance_threshold", args.sensitivity)
print(Color.bold("SpaceSense Monitor Mode"))
print(f"Version: {__version__}")
print(f"Sensitivity: {config.presence['variance_threshold']}")
print("-" * 50)
# Initialize components
processor = SignalProcessor(config)
detector = PresenceDetector(config)
recognizer = ActivityRecognizer(config)
alert_mgr = AlertManager(config.alerts)
alert_mgr.setup_default_rules()
exporter = DataExporter(config.export["output_dir"])
# Zone setup
zones = None
zone_monitor = None
if args.zones:
zone_names = [z.strip() for z in args.zones.split(",")]
zone_monitor = ZoneMonitor(zone_names, config)
zones = zone_names
# Create dashboard
dashboard = create_dashboard(
refresh_rate_ms=config.tui["refresh_rate_ms"],
waveform_width=config.tui["waveform_width"],
waveform_height=config.tui["waveform_height"],
)
# Data buffers
signal_buffer: List[float] = []
processed_data: List[Dict[str, Any]] = []
prev_activity = "unknown"
def update() -> None:
"""Update all components with new data."""
nonlocal prev_activity
# Generate demo data (in real mode, this would come from WiFi hardware)
generator = DemoDataGenerator(scenario="mixed")
rssi = generator.generate_sample()
# Process signal
processed = processor.add_sample(rssi)
signal_buffer.append(processed["smoothed"])
processed_data.append(processed)
# Presence detection
presence_result = detector.update(rssi)
dashboard.update_presence(
presence_result["present"],
presence_result["confidence"],
)
# Activity recognition
activity_result = recognizer.update(rssi)
dashboard.update_activity(
activity_result["activity"],
activity_result["confidence"],
)
# Zone monitoring
if zone_monitor and zones:
for zone in zones:
zone_rssi = DemoDataGenerator(
base_rssi=-55.0 + random.uniform(-5, 5),
).generate_sample(zone)
zone_monitor.update(zone, zone_rssi)
dashboard.update_zones(zone_monitor.get_zone_status())
# Alerts
alert_ctx = {
"variance": presence_result["variance"],
"present": presence_result["present"],
"confidence": presence_result["confidence"],
"activity": activity_result["activity"],
"prev_activity": prev_activity,
}
new_alerts = alert_mgr.evaluate(alert_ctx)
if new_alerts:
dashboard.update_alerts(alert_mgr.get_history(limit=5))
prev_activity = activity_result["activity"]
# Stats
if signal_buffer:
analyzer = SignalAnalyzer()
stats = analyzer.analyze(signal_buffer[-50:])
stats["total_samples"] = len(signal_buffer)
dashboard.update_stats(stats)
# Update signal waveform
dashboard.update_signal(signal_buffer)
try:
dashboard.run(update)
except KeyboardInterrupt:
print("\nMonitor stopped.")
# Export collected data
if processed_data:
path = exporter.export_signal_data(processed_data)
print(f"\nSignal data exported to: {path}")
if alert_mgr.history:
path = exporter.export_alerts(alert_mgr.history)
print(f"Alert history exported to: {path}")
return 0
def cmd_analyze(args: argparse.Namespace) -> int:
"""Handle the 'analyze' subcommand - offline data analysis.
Args:
args: Parsed command-line arguments.
Returns:
Exit code (0 for success).
"""
print(Color.bold("SpaceSense Analysis Mode"))
print("-" * 50)
# Load input data
data = _load_input_data(args.input)
if not data:
print("No data to analyze.", file=sys.stderr)
return 1
print(f"Loaded {len(data)} samples")
# Signal analysis
print("\n--- Signal Statistics ---")
analyzer = SignalAnalyzer()
analyzer.set_data(data)
stats = analyzer.analyze()
for key, value in stats.items():
print(f" {key:<20} {value}")
# Windowed analysis
print("\n--- Windowed Analysis (window=10) ---")
windowed = analyzer.analyze_windowed(window_size=10)
if windowed:
print(f" {len(windowed)} windows analyzed")
print(f" Avg variance: {sum(w['variance'] for w in windowed) / len(windowed):.4f}")
print(f" Max variance: {max(w['variance'] for w in windowed):.4f}")
print(f" Min variance: {min(w['variance'] for w in windowed):.4f}")
# Spectral features
print("\n--- Spectral Features ---")
spectral = analyzer.compute_spectral_features()
for key, value in spectral.items():
print(f" {key:<20} {value}")
# Pattern matching
print("\n--- Pattern Matching ---")
matcher = PatternMatcher()
match_result = matcher.match(data)
print(f" Best match: {match_result['best_match']} (score: {match_result['score']:.4f})")
print(" All scores:")
for name, score in sorted(match_result["all_scores"].items(), key=lambda x: -x[1]):
bar_len = int(score * 30)
bar = "#" * bar_len + "-" * (30 - bar_len)
print(f" {name:<15} [{bar}] {score:.4f}")
# Trend detection
print("\n--- Trend Detection ---")
trend_det = TrendDetector()
trend_det.set_data(data)
trend = trend_det.detect_trend()
print(f" Direction: {trend['direction']}")
print(f" Slope: {trend['slope']:.6f}")
print(f" Strength: {trend['strength']:.4f}")
print(f" R-squared: {trend['r_squared']:.4f}")
# Changepoints
changepoints = trend_det.detect_changepoints()
print(f"\n Changepoints detected: {len(changepoints)}")
for cp in changepoints[:5]:
print(f" Index {cp['index']}: {cp['direction']} (magnitude: {cp['magnitude']:.2f})")
# Periodicity
periodicity = trend_det.detect_periodicity()
print(f"\n Periodic: {periodicity['is_periodic']}")
if periodicity["is_periodic"]:
print(f" Period: {periodicity['period']} samples")
print(f" Confidence: {periodicity['confidence']:.4f}")
# Export results
if args.output:
exporter = DataExporter()
report = {
"statistics": stats,
"spectral_features": spectral,
"pattern_match": match_result,
"trend": trend,
"changepoints": changepoints,
"periodicity": periodicity,
}
path = exporter.export_analysis(report, args.output)
print(f"\nResults exported to: {path}")
return 0
def cmd_export(args: argparse.Namespace) -> int:
"""Handle the 'export' subcommand - data export.
Args:
args: Parsed command-line arguments.
Returns:
Exit code (0 for success).
"""
print(Color.bold("SpaceSense Export Mode"))
print("-" * 50)
data = _load_input_data(args.input)
if not data:
print("No data to export.", file=sys.stderr)
return 1
exporter = DataExporter(output_dir=args.output_dir or "./exports")
fmt = args.format or "csv"
print(f"Exporting {len(data)} samples in {fmt.upper()} format...")
# Export as signal data
signal_records = [
{"raw": v, "smoothed": v, "timestamp": i}
for i, v in enumerate(data)
]
path = exporter.export_signal_data(signal_records, fmt=fmt)
print(f" Signal data: {path}")
# Export statistics
analyzer = SignalAnalyzer()
stats = analyzer.analyze(data)
path = exporter.export_stats(stats, fmt=fmt)
print(f" Statistics: {path}")
print(f"\nExport complete. Files saved to: {exporter.output_dir}")
return 0
def cmd_demo(args: argparse.Namespace) -> int:
"""Handle the 'demo' subcommand - demonstration mode.
Runs a full demonstration using simulated WiFi data, showing all
SpaceSense capabilities without requiring real hardware.
Args:
args: Parsed command-line arguments.
Returns:
Exit code (0 for success).
"""
duration = args.duration or 30
scenario = args.scenario or "mixed"
print(Color.bold("SpaceSense Demo Mode"))
print(f"Version: {__version__}")
print(f"Scenario: {scenario}")
print(f"Duration: {duration}s")
print("=" * 60)
# Initialize all components
config = Config()
processor = SignalProcessor(config)
detector = PresenceDetector(config)
recognizer = ActivityRecognizer(config)
analyzer = SignalAnalyzer()
trend_det = TrendDetector(sensitivity=1.5)
matcher = PatternMatcher()
alert_mgr = AlertManager()
alert_mgr.setup_default_rules()
exporter = DataExporter(output_dir="./exports")
# Zone monitor with demo zones
zone_monitor = ZoneMonitor(
zone_names=["living_room", "bedroom", "kitchen"],
config=config,
)
# Data generators for each zone
generators = {
"living_room": DemoDataGenerator(base_rssi=-50.0, scenario=scenario),
"bedroom": DemoDataGenerator(base_rssi=-62.0, scenario=scenario),
"kitchen": DemoDataGenerator(base_rssi=-58.0, scenario=scenario),
}
# Data collection
signal_buffer: List[float] = []
processed_data: List[Dict[str, Any]] = []
presence_history: List[Dict[str, Any]] = []
activity_history: List[Dict[str, Any]] = []
prev_activity = "unknown"
total_steps = int(duration * 2) # 2 samples per second
progress = ProgressBar(total=total_steps, description="Simulating")
print(f"\nSimulating {duration}s of WiFi signal data...")
print(f"(2 samples/sec, {total_steps} total samples)\n")
for step in range(total_steps):
progress.update(step + 1)
# Generate main sensor data
gen = generators["living_room"]
rssi = gen.generate_sample("default")
# Process signal
processed = processor.add_sample(rssi)
signal_buffer.append(processed["smoothed"])
processed_data.append(processed)
# Presence detection
presence_result = detector.update(rssi)
presence_history.append(presence_result)
# Activity recognition
activity_result = recognizer.update(rssi)
activity_history.append(activity_result)
# Zone updates
for zone_name, zone_gen in generators.items():
zone_rssi = zone_gen.generate_sample(zone_name)
zone_monitor.update(zone_name, zone_rssi)
# Alerts
alert_ctx = {
"variance": presence_result["variance"],
"present": presence_result["present"],
"confidence": presence_result["confidence"],
"activity": activity_result["activity"],
"prev_activity": prev_activity,
}
alert_mgr.evaluate(alert_ctx)
prev_activity = activity_result["activity"]
progress.finish()
# Print analysis results
print("\n" + "=" * 60)
print(Color.bold(" ANALYSIS RESULTS"))
print("=" * 60)
# Signal statistics
print("\n--- Signal Statistics ---")
stats = analyzer.analyze(signal_buffer)
for key, value in stats.items():
print(f" {key:<20} {value}")
# Pattern matching
print("\n--- Activity Pattern Matching ---")
if len(signal_buffer) >= 20:
match_result = matcher.match(signal_buffer)
print(f" Best match: {match_result['best_match']} (score: {match_result['score']:.4f})")
for name, score in sorted(match_result["all_scores"].items(), key=lambda x: -x[1]):
bar_len = int(score * 30)
bar = "#" * bar_len + "-" * (30 - bar_len)
print(f" {name:<15} [{bar}] {score:.4f}")
# Trend detection
print("\n--- Trend Analysis ---")
trend_det.set_data(signal_buffer)
trend = trend_det.detect_trend()
print(f" Direction: {trend['direction']}")
print(f" Strength: {trend['strength']:.4f}")
changepoints = trend_det.detect_changepoints()
print(f" Changepoints: {len(changepoints)}")
periodicity = trend_det.detect_periodicity()
print(f" Periodic: {periodicity['is_periodic']}")
if periodicity["is_periodic"]:
print(f" Period: {periodicity['period']} samples")
# Presence summary
print("\n--- Presence Detection Summary ---")
present_count = sum(1 for r in presence_history if r["present"])
total = len(presence_history)
print(f" Presence detected: {present_count}/{total} ({present_count/total:.1%})")
if presence_history:
avg_conf = sum(r["confidence"] for r in presence_history) / len(presence_history)
print(f" Average confidence: {avg_conf:.4f}")
# Activity summary
print("\n--- Activity Recognition Summary ---")
activity_counts: Dict[str, int] = {}
for r in activity_history:
act = r["activity"]
activity_counts[act] = activity_counts.get(act, 0) + 1
for act, count in sorted(activity_counts.items(), key=lambda x: -x[1]):
pct = count / len(activity_history) * 100
bar = "#" * int(pct / 3)
print(f" {act:<15} {count:>5} ({pct:>5.1f}%) {bar}")
# Zone summary
print("\n--- Zone Monitoring Summary ---")
zone_summary = zone_monitor.get_summary()
print(f" Total zones: {zone_summary['total_zones']}")
print(f" Zone transitions: {zone_summary['total_transitions']}")
for zone_name, zone_status in zone_summary["zone_details"].items():
samples = zone_status["sample_count"]
print(f" {zone_name}: {samples} samples")
# Alert summary
print("\n--- Alert Summary ---")
alert_stats = alert_mgr.get_stats()
print(f" Total alerts: {alert_stats['total']}")
for level, count in alert_stats["by_level"].items():
print(f" {level}: {count}")
# Export all data
print("\n--- Exporting Data ---")
report = {
"signal_statistics": stats,
"pattern_match": match_result if len(signal_buffer) >= 20 else {},
"trend": trend,
"changepoints": changepoints,
"periodicity": periodicity,
"presence_summary": {
"detection_rate": present_count / total if total > 0 else 0,
"avg_confidence": avg_conf if presence_history else 0,
},
"activity_distribution": activity_counts,
"zone_summary": {
"total_transitions": zone_summary["total_transitions"],
},
"alert_stats": alert_stats,
}
path = exporter.export_report(report)
print(f" Full report: {path}")
path = exporter.export_signal_data(processed_data)
print(f" Signal data: {path}")
if alert_mgr.history:
path = exporter.export_alerts(alert_mgr.history)
print(f" Alert log: {path}")
print(f"\nAll files saved to: {exporter.output_dir}")
print("\n" + Color.green("Demo complete!"))
return 0
def cmd_config(args: argparse.Namespace) -> int:
"""Handle the 'config' subcommand - configuration management.
Args:
args: Parsed command-line arguments.
Returns:
Exit code (0 for success).
"""
if args.show or (not args.reset and not args.output):
config = Config()
if args.config:
try:
config.load_file(args.config)
except (FileNotFoundError, ValueError) as e:
print(f"Error loading config: {e}", file=sys.stderr)
return 1
print(Color.bold("SpaceSense Configuration"))
print("=" * 50)
print(json.dumps(config.to_dict(), indent=2, ensure_ascii=False))
return 0
if args.reset:
config = Config()
output = args.output or "spacesense_default.json"
config.save(output)
print(f"Default configuration saved to: {output}")
return 0
if args.output:
config = Config()
if args.config:
try:
config.load_file(args.config)
except (FileNotFoundError, ValueError) as e:
print(f"Error loading config: {e}", file=sys.stderr)
return 1
config.save(args.output)
print(f"Configuration saved to: {args.output}")
return 0
return 0
# ---------------------------------------------------------------------------
# Helper Functions
# ---------------------------------------------------------------------------
def _load_input_data(filepath: str) -> List[float]:
"""Load signal data from a file.
Supports JSON format (array of numbers or objects with 'rssi'/'raw' key)
and CSV format (one number per line).
Args:
filepath: Path to the input file.
Returns:
List of RSSI values.
"""
if not os.path.exists(filepath):
print(f"Input file not found: {filepath}", file=sys.stderr)
return []
with open(filepath, "r", encoding="utf-8") as f:
content = f.read().strip()
if not content:
return []
# Try JSON
try:
data = json.loads(content)
if isinstance(data, list):
result: List[float] = []
for item in data:
if isinstance(item, (int, float)):
result.append(float(item))
elif isinstance(item, dict):
for key in ("rssi", "raw", "value", "smoothed"):
if key in item:
result.append(float(item[key]))
break
return result
except json.JSONDecodeError:
pass
# Try CSV (one number per line)
result = []
for line in content.splitlines():
line = line.strip().rstrip(",")
if not line or line.startswith("#"):
continue
try:
result.append(float(line))
except ValueError:
# Skip header lines
continue
return result
# ---------------------------------------------------------------------------
# CLI Setup
# ---------------------------------------------------------------------------
def build_parser() -> argparse.ArgumentParser:
"""Build the argument parser with all subcommands.
Returns:
Configured ArgumentParser instance.
"""
parser = argparse.ArgumentParser(
prog="spacesense",
description=(
"SpaceSense - WiFi Spatial Intelligence Sensing Engine\n"
"Detect human presence and activities through WiFi signal analysis.\n"
"No cameras required. Privacy preserving."
),
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"Examples:\n"
" python cli.py demo --duration 30\n"
" python cli.py demo --scenario person_walking\n"
" python cli.py monitor --sensitivity 1.5\n"
" python cli.py analyze --input data.json\n"
" python cli.py export --input data.csv --format json\n"
" python cli.py config --show\n"
),
)
parser.add_argument(
"-v", "--version",
action="version",
version=f"SpaceSense {__version__}",
)
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Monitor subcommand
monitor_parser = subparsers.add_parser(
"monitor",
help="Start real-time monitoring mode",
description=(
"Start real-time WiFi signal monitoring with live TUI dashboard.\n"
"Displays signal waveform, presence detection, activity recognition,\n"
"zone monitoring, and alerts in real-time."
),
)
monitor_parser.add_argument(
"--config", "-c",
type=str,
default=None,
help="Path to JSON configuration file",
)
monitor_parser.add_argument(
"--sensitivity", "-s",
type=float,
default=None,
help="Detection sensitivity (0.1 - 10.0, default: from config)",
)
monitor_parser.add_argument(
"--zones", "-z",
type=str,
default=None,
help="Comma-separated zone names (e.g., 'living_room,bedroom')",
)
# Analyze subcommand
analyze_parser = subparsers.add_parser(
"analyze",
help="Analyze signal data offline",
description=(
"Perform comprehensive offline analysis on signal data.\n"
"Computes statistics, matches activity patterns, detects trends\n"
"and changepoints, and identifies periodicity."
),
)
analyze_parser.add_argument(
"--input", "-i",
type=str,
required=True,
help="Input data file (JSON array or CSV)",
)
analyze_parser.add_argument(
"--output", "-o",
type=str,
default=None,
help="Output file for analysis results",
)
# Export subcommand
export_parser = subparsers.add_parser(
"export",
help="Export data to CSV or JSON",
description=(
"Export signal data and statistics to CSV or JSON format.\n"
"Supports raw signal data, analysis results, and alert records."
),
)
export_parser.add_argument(
"--input", "-i",
type=str,
required=True,
help="Input data file (JSON array or CSV)",
)
export_parser.add_argument(
"--format", "-f",
type=str,
choices=["csv", "json"],
default=None,
help="Export format (default: csv)",
)
export_parser.add_argument(
"--output-dir", "-d",
type=str,
default=None,
help="Output directory (default: ./exports)",
)
# Demo subcommand
demo_parser = subparsers.add_parser(
"demo",
help="Run demonstration with simulated data",
description=(
"Run a full demonstration of SpaceSense capabilities using\n"
"realistic simulated WiFi RSSI data. No real hardware required.\n"
"Shows signal processing, presence detection, activity recognition,\n"
"zone monitoring, alerts, and data export."
),
)
demo_parser.add_argument(
"--duration", "-d",
type=int,
default=30,
help="Demo duration in seconds (default: 30)",
)
demo_parser.add_argument(
"--scenario",
type=str,
choices=DemoDataGenerator.SCENARIOS,
default="mixed",
help="Simulation scenario (default: mixed)",
)
# Config subcommand
config_parser = subparsers.add_parser(
"config",
help="Manage configuration",
description=(
"View, save, or reset SpaceSense configuration.\n"
"Configuration is loaded from JSON files and merged with defaults."
),
)
config_parser.add_argument(
"--show",
action="store_true",
help="Show current configuration",
)
config_parser.add_argument(
"--reset",
action="store_true",
help="Save default configuration to file",
)
config_parser.add_argument(
"--config", "-c",
type=str,
default=None,
help="Path to configuration file to load",
)
config_parser.add_argument(
"--output", "-o",
type=str,
default=None,
help="Output file path for configuration",
)
return parser
def main() -> int:
"""Main entry point for the SpaceSense CLI.
Returns:
Exit code (0 for success, non-zero for errors).
"""
parser = build_parser()
args = parser.parse_args()
if not args.command:
parser.print_help()
return 0
commands = {
"monitor": cmd_monitor,
"analyze": cmd_analyze,
"export": cmd_export,
"demo": cmd_demo,
"config": cmd_config,
}
handler = commands.get(args.command)
if handler is None:
parser.print_help()
return 1
try:
return handler(args)
except KeyboardInterrupt:
print("\nInterrupted.")
return 130
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())