-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_visualization_test.py
More file actions
128 lines (106 loc) · 4.17 KB
/
Copy pathsimple_visualization_test.py
File metadata and controls
128 lines (106 loc) · 4.17 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
"""
Simplified visualization test to debug update issues
"""
import serial
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
from collections import deque
import re
class SimpleVisualizer:
def __init__(self, port='COM3', baud_rate=9600):
self.port = port
self.baud_rate = baud_rate
self.serial_conn = None
# Simple data buffers
self.time_data = deque(maxlen=100)
self.feature0_data = deque(maxlen=100)
self.sample_count = 0
self.start_time = None
# Setup plot
self.fig, self.ax = plt.subplots(figsize=(10, 6))
self.line, = self.ax.plot([], [], 'b-', linewidth=2)
self.ax.set_xlabel('Time (s)')
self.ax.set_ylabel('Feature 0 Value')
self.ax.set_title('Simple Sensor Visualization Test')
self.ax.grid(True)
self.ax.set_ylim(0, 1)
def connect(self):
try:
self.serial_conn = serial.Serial(self.port, self.baud_rate, timeout=1)
print(f"Connected to {self.port}")
return True
except Exception as e:
print(f"Connection error: {e}")
return False
def parse_line(self, line):
"""Parse feature data from serial line"""
try:
match = re.search(r'Features:\s*\[(.*?)\]', line)
if match:
features_str = match.group(1)
features = [float(x.strip()) for x in features_str.split(',')]
return features[0] if len(features) > 0 else None
except:
pass
return None
def update(self, frame):
"""Update function called by animation"""
import time as time_module
from datetime import datetime
# Read serial data
if self.serial_conn and self.serial_conn.in_waiting:
line = self.serial_conn.readline().decode('utf-8', errors='ignore').strip()
if 'Features:' in line:
feat_val = self.parse_line(line)
if feat_val is not None:
# Update time
if self.start_time is None:
self.start_time = datetime.now()
current_time = (datetime.now() - self.start_time).total_seconds()
# Store data
self.time_data.append(current_time)
self.feature0_data.append(feat_val)
self.sample_count += 1
print(f"Sample {self.sample_count}: t={current_time:.2f}s, feat0={feat_val:.3f}")
# Update plot
if len(self.time_data) > 0:
time_array = np.array(self.time_data)
feat_array = np.array(self.feature0_data)
self.line.set_data(time_array, feat_array)
# Update axes
if len(time_array) > 0:
self.ax.set_xlim(max(0, time_array[-1] - 10), time_array[-1] + 1)
if len(feat_array) > 0:
y_min, y_max = feat_array.min(), feat_array.max()
y_range = max(y_max - y_min, 0.1)
self.ax.set_ylim(y_min - y_range*0.1, y_max + y_range*0.1)
# Force redraw
self.fig.canvas.draw()
return [self.line]
def run(self):
if not self.connect():
return
print("Starting simple visualization...")
print("Watch the plot and terminal output")
ani = animation.FuncAnimation(
self.fig,
self.update,
interval=100,
blit=False,
cache_frame_data=False
)
try:
plt.show(block=True)
except KeyboardInterrupt:
print("\nStopping...")
finally:
if self.serial_conn:
self.serial_conn.close()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--port', type=str, default='COM3')
args = parser.parse_args()
viz = SimpleVisualizer(port=args.port)
viz.run()