-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFastSenseWidget.m
More file actions
452 lines (407 loc) · 16.9 KB
/
FastSenseWidget.m
File metadata and controls
452 lines (407 loc) · 16.9 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
classdef FastSenseWidget < DashboardWidget
%FASTSENSEWIDGET Dashboard widget wrapping a FastSense instance.
%
% Supports data binding modes:
% Tag: w = FastSenseWidget('Tag', tagObj)
% DataStore: w = FastSenseWidget('DataStore', dsObj)
% Inline: w = FastSenseWidget('XData', x, 'YData', y)
% File: w = FastSenseWidget('File', 'path.mat', 'XVar', 'x', 'YVar', 'y')
properties (Access = public)
DataStoreObj = []
XData = []
YData = []
File = ''
XVar = ''
YVar = ''
Thresholds = 'auto'
XLabel = '' % X-axis label (auto-set from Sensor if empty)
YLabel = '' % Y-axis label (auto-set from Sensor if empty)
YLimits = [] % Fixed Y-axis range [min max]; empty = auto-scale
ShowThresholdLabels = false % show inline name labels on threshold lines
end
% (Tag property now lives on the DashboardWidget base class — Plan 1009-02.)
properties (SetAccess = private)
FastSenseObj = []
IsSettingTime = false % guard to distinguish programmatic vs user xlim change
CachedXMin = inf % cached minimum of X data for O(1) getTimeRange()
CachedXMax = -inf % cached maximum of X data for O(1) getTimeRange()
LastTagRef = [] % Tag handle snapshot for cache-invalidation
end
methods
function obj = FastSenseWidget(varargin)
obj = obj@DashboardWidget(varargin{:});
if isequal(obj.Position, [1 1 6 2])
obj.Position = [1 1 12 3];
end
% Tag cascade (v2.0 Tag API).
if ~isempty(obj.Tag)
if ~isa(obj.Tag, 'Tag')
error('FastSenseWidget:invalidTag', ...
'Tag must be a Tag subclass; got %s.', class(obj.Tag));
end
if isempty(obj.XLabel), obj.XLabel = 'Time'; end
if isempty(obj.YLabel)
if isprop(obj.Tag, 'Units') && ~isempty(obj.Tag.Units)
obj.YLabel = obj.Tag.Units;
elseif ~isempty(obj.Tag.Name)
obj.YLabel = obj.Tag.Name;
else
obj.YLabel = obj.Tag.Key;
end
end
obj.LastTagRef = obj.Tag;
obj.updateTimeRangeCache();
end
end
function render(obj, parentPanel)
obj.hPanel = parentPanel;
% Create axes inside the panel
ax = axes('Parent', parentPanel, ...
'Units', 'normalized', ...
'Position', [0.08 0.12 0.88 0.78]);
% Create FastSense on this axes
fp = FastSense('Parent', ax);
obj.FastSenseObj = fp;
fp.ShowThresholdLabels = obj.ShowThresholdLabels;
% Bind data — Tag-first dispatch (v2.0).
if ~isempty(obj.Tag)
fp.addTag(obj.Tag);
elseif ~isempty(obj.DataStoreObj)
fp.addLine([], [], 'DataStore', obj.DataStoreObj);
elseif ~isempty(obj.File)
data = load(obj.File);
x = data.(obj.XVar);
y = data.(obj.YVar);
fp.addLine(x, y);
elseif ~isempty(obj.XData) && ~isempty(obj.YData)
fp.addLine(obj.XData, obj.YData);
end
% Set title and axis labels
if ~isempty(obj.Title)
title(ax, obj.Title, 'Color', get(ax, 'XColor'));
end
if ~isempty(obj.XLabel)
xlabel(ax, obj.XLabel, 'Color', get(ax, 'XColor'));
end
if ~isempty(obj.YLabel)
ylabel(ax, obj.YLabel, 'Color', get(ax, 'XColor'));
end
fp.render();
% Reformat time-axis ticks to HH:MM:SS / MM:SS for readability.
obj.formatTimeAxis_(ax);
% Apply fixed Y-axis limits if configured
if ~isempty(obj.YLimits) && numel(obj.YLimits) == 2
ylim(ax, obj.YLimits);
end
% Update time range cache and data-source identity snapshots
obj.LastTagRef = obj.Tag;
obj.updateTimeRangeCache();
% Listen for manual zoom/pan to disable global time for this widget
try
addlistener(ax, 'XLim', 'PostSet', @(~,~) obj.onXLimChanged());
catch
end
end
function refresh(obj)
% Re-render Tag-bound widgets so updated data shows.
% Uses incremental updateData() path when tag identity is unchanged
% (PERF2-01); falls back to full teardown/rebuild on first render,
% tag swap, or error. Zoom state (xlim) is preserved in both paths.
if isempty(obj.Tag), return; end
if isempty(obj.hPanel) || ~ishandle(obj.hPanel), return; end
tagUnchanged = ~isempty(obj.LastTagRef) && obj.Tag == obj.LastTagRef;
fpValid = ~isempty(obj.FastSenseObj) && ...
obj.FastSenseObj.IsRendered && ...
~isempty(obj.FastSenseObj.hAxes) && ...
ishandle(obj.FastSenseObj.hAxes);
if tagUnchanged && fpValid
try
[x, y] = obj.Tag.getXY();
obj.FastSenseObj.updateData(1, x, y);
obj.updateTimeRangeCache();
obj.formatTimeAxis_(obj.FastSenseObj.hAxes);
return;
catch
% fall through to full teardown/rebuild
end
end
obj.rebuildForTag_();
end
function update(obj)
%UPDATE Incrementally update Tag data without full axes rebuild.
% Uses FastSenseObj.updateData() to replace data and re-downsample,
% avoiding the expensive delete/recreate cycle of refresh().
% Falls back to refresh() if FastSenseObj is not in a renderable state.
if isempty(obj.Tag), return; end
if isempty(obj.hPanel) || ~ishandle(obj.hPanel), return; end
if ~isempty(obj.FastSenseObj) && obj.FastSenseObj.IsRendered
try
[x, y] = obj.Tag.getXY();
obj.FastSenseObj.updateData(1, x, y);
obj.updateTimeRangeCache();
obj.formatTimeAxis_(obj.FastSenseObj.hAxes);
return;
catch
% fall through to refresh()
end
end
obj.refresh();
end
function setTimeRange(obj, tStart, tEnd)
if ~obj.UseGlobalTime
return; % widget has its own zoom, skip global time
end
if ~isempty(obj.FastSenseObj)
try
ax = obj.FastSenseObj.hAxes;
if ~isempty(ax) && ishandle(ax)
obj.IsSettingTime = true;
xlim(ax, [tStart tEnd]);
obj.IsSettingTime = false;
end
catch
obj.IsSettingTime = false;
end
end
end
function onXLimChanged(obj)
% If xlim changed by user zoom/pan (not by setTimeRange),
% detach this widget from global time.
if ~obj.IsSettingTime
obj.UseGlobalTime = false;
end
end
function [tMin, tMax] = getTimeRange(obj)
% Return cached min/max in O(1). Cache is kept up to date by
% updateTimeRangeCache() which is called from render/refresh/update.
tMin = obj.CachedXMin;
tMax = obj.CachedXMax;
if isinf(tMin) || isinf(tMax)
tMin = inf; tMax = -inf;
end
end
function t = getType(~)
t = 'fastsense';
end
function lines = asciiRender(obj, width, height)
if height <= 0, lines = {}; return; end
blank = repmat(' ', 1, width);
lines = cell(1, height);
for i = 1:height, lines{i} = blank; end
ttl = obj.Title;
if numel(ttl) > width, ttl = ttl(1:width); end
lines{1} = [ttl, repmat(' ', 1, width - numel(ttl))];
yData = [];
if ~isempty(obj.Tag)
try
[~, yData] = obj.Tag.getXY();
catch
yData = [];
end
elseif ~isempty(obj.YData)
yData = obj.YData;
end
if ~isempty(yData) && height >= 2
bars = char(9601):char(9608);
nBars = numel(bars);
yMin = min(yData); yMax = max(yData);
if yMax == yMin, yMax = yMin + 1; end
nPts = min(numel(yData), width);
idx = round(linspace(1, numel(yData), nPts));
sampled = yData(idx);
spark = blanks(nPts);
for si = 1:nPts
level = round((sampled(si) - yMin) / (yMax - yMin) * (nBars - 1)) + 1;
level = max(1, min(nBars, level));
spark(si) = bars(level);
end
if numel(spark) < width
spark = [spark, repmat(' ', 1, width - numel(spark))];
end
lines{2} = spark(1:width);
elseif height >= 2
ph = '[~~ fastsense ~~]';
if numel(ph) > width, ph = ph(1:width); end
lines{2} = [ph, repmat(' ', 1, width - numel(ph))];
end
end
function s = toStruct(obj)
s = toStruct@DashboardWidget(obj);
if ~isempty(obj.XLabel), s.xLabel = obj.XLabel; end
if ~isempty(obj.YLabel), s.yLabel = obj.YLabel; end
if ~isempty(obj.YLimits), s.yLimits = obj.YLimits; end
if obj.ShowThresholdLabels, s.showThresholdLabels = true; end
if ~isempty(obj.Tag) && ~isempty(obj.Tag.Key)
s.source = struct('type', 'tag', 'key', obj.Tag.Key);
s.thresholds = obj.Thresholds;
elseif ~isempty(obj.File)
s.source = struct('type', 'file', 'path', obj.File, ...
'xVar', obj.XVar, 'yVar', obj.YVar);
elseif ~isempty(obj.XData)
s.source = struct('type', 'data', 'x', obj.XData, 'y', obj.YData);
end
end
end
methods (Access = private)
function formatTimeAxis_(~, ax)
%FORMATTIMEAXIS_ Replace numeric-seconds x-ticks with HH:MM:SS labels.
% No-op when range <= 300s (raw seconds readable) or ax invalid.
if isempty(ax) || ~ishandle(ax), return; end
xl = get(ax, 'XLim');
rangeSec = xl(2) - xl(1);
if rangeSec <= 300, return; end
xt = get(ax, 'XTick');
if isempty(xt), return; end
if rangeSec >= 3600
fmt = 'HH:MM:SS';
else
fmt = 'MM:SS';
end
lbl = cell(1, numel(xt));
for i = 1:numel(xt)
% xt(i) is seconds; serial-date day = seconds / 86400
lbl{i} = datestr(xt(i) / 86400, fmt);
end
set(ax, 'XTickMode', 'manual', 'XTickLabelMode', 'manual', ...
'XTickLabel', lbl);
end
function updateTimeRangeCache(obj)
%UPDATETIMERANGECACHE Maintain CachedXMin/CachedXMax incrementally.
% For sorted time arrays (the common case) the last element is the
% max candidate and the first is the min candidate, so this avoids
% a full-array scan on every live tick.
if ~isempty(obj.Tag)
try
[x, ~] = obj.Tag.getXY();
n = numel(x);
if n == 0
obj.CachedXMin = inf;
obj.CachedXMax = -inf;
return;
end
obj.CachedXMax = x(n);
if isinf(obj.CachedXMin)
obj.CachedXMin = x(1);
end
catch
obj.CachedXMin = inf;
obj.CachedXMax = -inf;
end
return;
end
if ~isempty(obj.XData)
obj.CachedXMin = min(obj.XData);
obj.CachedXMax = max(obj.XData);
else
obj.CachedXMin = inf;
obj.CachedXMax = -inf;
end
end
function rebuildForTag_(obj)
%REBUILDFORTAG_ Full teardown + rebuild FastSense from obj.Tag.
% Preserves zoom state (xlim) across the rebuild.
% Save zoom state before teardown
savedXLim = [];
if ~isempty(obj.FastSenseObj) && ~isempty(obj.FastSenseObj.hAxes) && ...
ishandle(obj.FastSenseObj.hAxes)
savedXLim = get(obj.FastSenseObj.hAxes, 'XLim');
end
% Delete old FastSense + leftover axes in the panel
if ~isempty(obj.FastSenseObj)
try delete(obj.FastSenseObj); catch, end
obj.FastSenseObj = [];
end
ch = findobj(obj.hPanel, 'Type', 'axes');
delete(ch);
ax = axes('Parent', obj.hPanel, ...
'Units', 'normalized', ...
'Position', [0.08 0.12 0.88 0.78]);
fp = FastSense('Parent', ax);
obj.FastSenseObj = fp;
fp.ShowThresholdLabels = obj.ShowThresholdLabels;
fp.addTag(obj.Tag);
if ~isempty(obj.Title)
title(ax, obj.Title, 'Color', get(ax, 'XColor'));
end
if ~isempty(obj.XLabel)
xlabel(ax, obj.XLabel, 'Color', get(ax, 'XColor'));
end
if ~isempty(obj.YLabel)
ylabel(ax, obj.YLabel, 'Color', get(ax, 'XColor'));
end
fp.render();
% Reformat time-axis ticks to HH:MM:SS / MM:SS for readability.
obj.formatTimeAxis_(ax);
if ~isempty(obj.YLimits) && numel(obj.YLimits) == 2
ylim(ax, obj.YLimits);
end
obj.LastTagRef = obj.Tag;
obj.updateTimeRangeCache();
if ~isempty(savedXLim)
obj.IsSettingTime = true;
xlim(ax, savedXLim);
obj.IsSettingTime = false;
end
try
addlistener(ax, 'XLim', 'PostSet', @(~,~) obj.onXLimChanged());
catch
end
end
end
methods (Static)
function obj = fromStruct(s)
obj = FastSenseWidget();
obj.Title = s.title;
obj.Position = [s.position.col, s.position.row, ...
s.position.width, s.position.height];
if isfield(s, 'description')
obj.Description = s.description;
end
if isfield(s, 'source')
switch s.source.type
case 'tag'
if exist('TagRegistry', 'class')
try
obj.Tag = TagRegistry.get(s.source.key);
catch
warning('FastSenseWidget:tagNotFound', ...
'TagRegistry key ''%s'' not found.', s.source.key);
end
end
case 'sensor'
% Backward compat: old JSON with type='sensor' resolves via TagRegistry.
if exist('TagRegistry', 'class')
try
obj.Tag = TagRegistry.get(s.source.name);
catch
% Tag not in registry; resolver will
% bind it in configToWidgets if provided.
end
end
case 'file'
obj.File = s.source.path;
obj.XVar = s.source.xVar;
obj.YVar = s.source.yVar;
case 'data'
obj.XData = s.source.x(:).';
obj.YData = s.source.y(:).';
end
end
if isfield(s, 'thresholds')
obj.Thresholds = s.thresholds;
end
if isfield(s, 'xLabel')
obj.XLabel = s.xLabel;
end
if isfield(s, 'yLabel')
obj.YLabel = s.yLabel;
end
if isfield(s, 'yLimits')
obj.YLimits = s.yLimits;
end
if isfield(s, 'showThresholdLabels')
obj.ShowThresholdLabels = s.showThresholdLabels;
end
end
end
end