Repository navigation
Expand file tree
/
Copy pathplot_live.py
More file actions
225 lines (193 loc) · 7.84 KB
/
Copy pathplot_live.py
File metadata and controls
225 lines (193 loc) · 7.84 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
#!/usr/bin/env python3
"""
Live plot for OH Insole sensors.
Usage examples:
# HTTP mode (ESP32 AP default IP 192.168.4.1)
python3 scripts/plot_live.py --mode http --url http://192.168.4.1/data
# Serial mode (parse the single-line Serial output)
python3 scripts/plot_live.py --mode serial --port /dev/cu.usbserial-1440 --baud 115200
# Serial mode (parse the single-line Serial output)
python3 scripts/plot_live.py --mode serial --port /dev/cu.usbserial-1440 --baud 9600
The script ignores negative values by inserting NaN so the plot shows gaps instead of plotting invalid numbers.
Dependencies: requests, pyserial (only for serial mode), matplotlib
Install: pip3 install matplotlib requests pyserial
"""
import argparse
import json
import re
import sys
import time
from collections import deque
import matplotlib.pyplot as plt
import numpy as np
# Optional imports; will fail only if that mode is used
try:
import requests
except Exception:
requests = None
try:
import serial
except Exception:
serial = None
LINE_PATTERN = re.compile(r"FSR raw:\s*(?P<fsr>-?\d+)\s+V:\s*(?P<v>[0-9.]+)\s+SPO2:\s*(?P<spo2>-?\d+)\s+HR:\s*(?P<hr>-?\d+)")
def safe_append(deq, val):
# treat negative as invalid: append np.nan to preserve time base but show gap
if val is None:
deq.append(np.nan)
else:
try:
if float(val) < 0:
deq.append(np.nan)
else:
deq.append(float(val))
except Exception:
deq.append(np.nan)
class LivePlot:
def __init__(self, max_points=200):
self.max_points = max_points
self.fsr = deque([np.nan] * max_points, maxlen=max_points)
self.ir = deque([np.nan] * max_points, maxlen=max_points)
self.red = deque([np.nan] * max_points, maxlen=max_points)
# Prefer seaborn-darkgrid if available, otherwise fall back gracefully
try:
plt.style.use('seaborn-darkgrid')
except Exception:
try:
plt.style.use('ggplot')
print("Note: 'seaborn-darkgrid' style not available, using 'ggplot' fallback")
except Exception:
# last-resort: default style
plt.style.use('default')
print("Note: fallback styles not available, using default matplotlib style")
self.fig, (self.ax_fsr, self.ax_ir, self.ax_red) = plt.subplots(3, 1, figsize=(8, 6), sharex=True)
self.line_fsr, = self.ax_fsr.plot([], [], label='FSR')
self.ax_fsr.set_ylabel('FSR')
self.line_ir, = self.ax_ir.plot([], [], label='IR', color='C1')
self.ax_ir.set_ylabel('PPG IR')
self.line_red, = self.ax_red.plot([], [], label='RED', color='C2')
self.ax_red.set_ylabel('PPG RED')
self.ax_red.set_xlabel('Samples')
# initial axis limits
self.ax_fsr.set_ylim(0, 4096)
self.ax_ir.set_ylim(0, 65536)
self.ax_red.set_ylim(0, 65536)
self.fig.tight_layout()
def update_plot(self):
xs = np.arange(-len(self.fsr) + 1, 1)
self.line_fsr.set_data(xs, np.array(self.fsr))
self.line_ir.set_data(xs, np.array(self.ir))
self.line_red.set_data(xs, np.array(self.red))
# autoscale y a little to visible range (ignore NaN)
def adjust(ax, data, default_max):
arr = np.array(data)
arr = arr[~np.isnan(arr)]
if arr.size > 0:
mn, mx = np.min(arr), np.max(arr)
if mn == mx:
mx = mn + 1
ax.set_ylim(mn - abs(0.1 * mn + 1), mx + abs(0.1 * mx + 1))
else:
ax.set_ylim(0, default_max)
adjust(self.ax_fsr, self.fsr, 4096)
adjust(self.ax_ir, self.ir, 65536)
adjust(self.ax_red, self.red, 65536)
self.ax_red.relim(); self.ax_red.autoscale_view()
self.ax_ir.relim(); self.ax_ir.autoscale_view()
self.ax_fsr.relim(); self.ax_fsr.autoscale_view()
self.fig.canvas.draw()
plt.pause(0.001)
def push_http(self, js):
# expect keys 'fsr', 'ir', 'red'
safe_append(self.fsr, js.get('fsr'))
safe_append(self.ir, js.get('ir'))
safe_append(self.red, js.get('red'))
def push_serial(self, fsr_val=None, spo2_val=None, hr_val=None):
# If serial mode provides SPO2/HR, we'll map them to IR/RED charts respectively
safe_append(self.fsr, fsr_val)
safe_append(self.ir, spo2_val)
safe_append(self.red, hr_val)
def run_http_mode(url, interval=0.2, points=200):
if requests is None:
print('requests library missing. Install with: pip3 install requests')
return
lp = LivePlot(points)
print('HTTP mode: polling', url)
try:
while True:
try:
r = requests.get(url, timeout=1.0)
if r.status_code == 200:
try:
js = r.json()
lp.push_http(js)
except Exception as e:
# invalid json
lp.push_http({})
else:
lp.push_http({})
except Exception:
lp.push_http({})
lp.update_plot()
time.sleep(interval)
except KeyboardInterrupt:
print('\nStopped by user')
def run_serial_mode(port, baud=115200, interval=0.1, points=200):
if serial is None:
print('pyserial missing. Install with: pip3 install pyserial')
return
lp = LivePlot(points)
print('Serial mode: reading', port, '@', baud)
try:
ser = serial.Serial(port, baud, timeout=1)
except Exception as e:
print('Failed to open serial port:', e)
return
try:
while True:
try:
line = ser.readline().decode(errors='ignore').strip()
if not line:
# no data; push NaNs to keep timebase
lp.push_serial(None, None, None)
else:
m = LINE_PATTERN.search(line)
if m:
fsr = int(m.group('fsr'))
spo2 = int(m.group('spo2'))
hr = int(m.group('hr'))
lp.push_serial(fsr, spo2, hr)
else:
# Could be JSON (from /data via some gateway) or other formatted line
# try to parse numbers loosely
nums = re.findall(r'-?\d+', line)
if len(nums) >= 1:
fsr = int(nums[0])
lp.push_serial(fsr, None, None)
else:
lp.push_serial(None, None, None)
except Exception:
lp.push_serial(None, None, None)
lp.update_plot()
time.sleep(interval)
except KeyboardInterrupt:
print('\nStopped by user')
finally:
ser.close()
def main():
p = argparse.ArgumentParser()
p.add_argument('--mode', choices=['http', 'serial'], default='http', help='Data source mode')
p.add_argument('--url', default='http://192.168.4.1/data', help='HTTP data endpoint (for http mode)')
p.add_argument('--port', default=None, help='Serial port (for serial mode)')
p.add_argument('--baud', type=int, default=9600, help='Serial baud')
p.add_argument('--interval', type=float, default=0.2, help='Polling interval seconds')
p.add_argument('--points', type=int, default=200, help='Number of points to display')
args = p.parse_args()
if args.mode == 'http':
run_http_mode(args.url, interval=args.interval, points=args.points)
else:
if not args.port:
print('Serial mode requires --port')
sys.exit(1)
run_serial_mode(args.port, baud=args.baud, interval=args.interval, points=args.points)
if __name__ == '__main__':
main()