-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathChartPlotter.tsx
265 lines (241 loc) · 6.87 KB
/
ChartPlotter.tsx
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
import React, {
useState,
useRef,
useImperativeHandle,
useEffect,
useCallback,
} from "react";
import { Line } from "react-chartjs-2";
import { addDataPoints, MonitorSettings, PluggableMonitor } from "./utils";
import { Legend } from "./Legend";
import { Chart, ChartData, ChartOptions } from "chart.js";
import "chartjs-adapter-luxon";
import ChartStreaming from "chartjs-plugin-streaming";
import { ChartJSOrUndefined } from "react-chartjs-2/dist/types";
import { MessageToBoard } from "./MessageToBoard";
// eslint-disable-next-line
import Worker from "worker-loader!./msgAggregatorWorker";
import { Snackbar } from "@arduino/arc";
Chart.register(ChartStreaming);
const worker = new Worker();
function _Chart(
{
config,
websocket,
}: {
config: Partial<MonitorSettings>;
websocket: React.MutableRefObject<WebSocket | null>;
},
ref: React.ForwardedRef<any>
): React.ReactElement {
const chartRef = useRef<ChartJSOrUndefined<"line">>();
const [, setForceUpdate] = useState(0);
const [pause, setPause] = useState(false);
const [connected, setConnected] = useState(
config?.monitorUISettings?.connected
);
const [dataPointThreshold] = useState(50);
const [cubicInterpolationMode, setCubicInterpolationMode] = useState<
"default" | "monotone"
>(config?.monitorUISettings?.interpolate ? "monotone" : "default");
const [initialData] = useState<ChartData<"line">>({
datasets: [],
});
const [opts, setOpts] = useState<ChartOptions<"line">>({
animation: false,
maintainAspectRatio: false,
normalized: true,
parsing: false,
datasets: {
line: {
pointRadius: 0,
pointHoverRadius: 0,
},
},
interaction: {
intersect: false,
},
plugins: {
tooltip: {
caretPadding: 9,
enabled: false, // tooltips are enabled on stop only
bodyFont: {
family: "Open Sans",
},
titleFont: {
family: "Open Sans",
},
},
decimation: {
enabled: true,
algorithm: "min-max",
},
legend: {
display: false,
},
},
elements: {
line: {
tension: 0, // disables bezier curves
},
},
scales: {
y: {
grid: {
color: config?.monitorUISettings?.darkTheme ? "#2C353A" : "#ECF1F1",
},
ticks: {
color: config?.monitorUISettings?.darkTheme ? "#DAE3E3" : "#2C353A",
font: {
family: "Open Sans",
},
},
grace: "5%",
},
x: {
grid: {
color: config?.monitorUISettings?.darkTheme ? "#2C353A" : "#ECF1F1",
},
display: true,
ticks: {
font: {
family: "Open Sans",
},
color: config?.monitorUISettings?.darkTheme ? "#DAE3E3" : "#2C353A",
count: 5,
callback: (value) => {
return parseInt(value.toString(), 10);
},
align: "center",
},
type: "linear",
bounds: "data",
// Other notable settings:
// type: "timeseries"
// time: {
// unit: "second",
// stepSize: 1,
// },
// type: "realtime"
// duration: 10000,
// delay: 500,
},
},
});
const enableTooltips = useCallback(
(newState: boolean) => {
(opts.plugins as any).tooltip.enabled = newState;
opts.datasets!.line!.pointHoverRadius = newState ? 3 : 0;
setOpts(opts);
chartRef.current?.update();
},
[opts]
);
useEffect(() => {
if (!config?.monitorUISettings?.connected) {
setConnected(false);
// when disconnected, force tooltips to be enabled
enableTooltips(true);
return;
}
// when the connection becomes connected, need to cleanup the previous state
if (!connected && config?.monitorUISettings?.connected) {
// cleanup buffer state
worker.postMessage({ command: "cleanup" });
setConnected(true);
// restore the tooltips state (which match the pause state when connected)
enableTooltips(pause);
}
}, [config?.monitorUISettings?.connected, connected, pause, enableTooltips]);
const togglePause = (newState: boolean) => {
if (newState === pause) {
return;
}
if (opts.scales!.x?.type === "realtime") {
(chartRef.current as any).options.scales.x.realtime.pause = pause;
}
setPause(newState);
worker.postMessage({ command: "cleanup" });
enableTooltips(newState);
};
const setInterpolate = (interpolate: boolean) => {
const newCubicInterpolationMode = interpolate ? "monotone" : "default";
if (chartRef && chartRef.current) {
for (let i = 0; i < chartRef.current.data.datasets.length; i++) {
const dataset = chartRef.current.data.datasets[i];
if (dataset) {
dataset.cubicInterpolationMode = newCubicInterpolationMode;
}
}
chartRef.current.update();
setCubicInterpolationMode(newCubicInterpolationMode);
}
};
useImperativeHandle(ref, () => ({
addNewData(data: string[]) {
if (pause) {
return;
}
// upon message receival update the chart
worker.postMessage({ data });
},
}));
useEffect(() => {
const addData = (event: MessageEvent<any>) => {
addDataPoints(
event.data,
chartRef.current,
opts,
cubicInterpolationMode,
dataPointThreshold,
setForceUpdate
);
};
worker.addEventListener("message", addData);
return () => {
worker.removeEventListener("message", addData);
};
}, [cubicInterpolationMode, opts, dataPointThreshold]);
const wsSend = (
clientCommand: PluggableMonitor.Protocol.ClientCommandMessage
) => {
if (websocket && websocket?.current?.readyState === WebSocket.OPEN) {
websocket.current.send(JSON.stringify(clientCommand));
}
};
return (
<>
<div className="chart-container">
<Legend
chartRef={chartRef.current}
pause={pause}
config={config}
cubicInterpolationMode={cubicInterpolationMode}
wsSend={wsSend}
setPause={togglePause}
setInterpolate={setInterpolate}
/>
<div className="canvas-container">
<Line data={initialData} ref={chartRef as any} options={opts} />
</div>
<MessageToBoard config={config} wsSend={wsSend} />
{!connected && (
<Snackbar
anchorOrigin={{
horizontal: "center",
vertical: "bottom",
}}
autoHideDuration={7000}
className="snackbar"
closeable
isOpen
message="Board disconnected"
theme={config?.monitorUISettings?.darkTheme ? "dark" : "light"}
turnOffAutoHide
/>
)}
</div>
</>
);
}
export const ChartPlotter = React.forwardRef(_Chart);