blob: 33a3de1c5907ae87358cc79352efe5e79c798a44 [file] [log] [blame]
James Kuszmaul5f5e1232020-12-22 20:58:00 -08001// This library provides a wrapper around our WebGL plotter that makes it
2// easy to plot AOS messages/channels as time series.
3//
4// This is works by subscribing to each channel that we want to plot, storing
5// all the messages for that channel, and then periodically running through
6// every message and extracting the fields to plot.
7// It is also possible to insert code to make modifications to the messages
8// as we read/process them, as is the case for the IMU processing code (see
9// //frc971/wpilib:imu*.ts) where each message is actually a batch of several
10// individual messages that need to be plotted as separate points.
11//
12// The basic flow for using the AosPlotter is:
13// // 1) Construct the plotter
14// const aosPlotter = new AosPlotter(connection);
15// // 2) Add messages sources that we'll want to subscribe to.
16// const source = aosPlotter.addMessageSource('/aos', 'aos.timing.Report');
17// // 3) Create figures at defined positions within a given HTML element..
18// const timingPlot = aosPlotter.addPlot(parentDiv, [0, 0], [width, height]);
19// // 4) Add specific signals to each figure, using the message sources you
20// defined at the start.
21// timingPlot.addMessageLine(source, ['pid']);
22//
23// The demo_plot.ts script has a basic example of using this library, with all
24// the required boilerplate, as well as some extra examples about how to
25// add axis labels and the such.
26import * as configuration from 'org_frc971/aos/configuration_generated';
27import {Line, Plot} from 'org_frc971/aos/network/www/plotter';
28import * as proxy from 'org_frc971/aos/network/www/proxy';
29import * as web_proxy from 'org_frc971/aos/network/web_proxy_generated';
30import * as reflection from 'org_frc971/aos/network/www/reflection'
31import * as flatbuffers_builder from 'org_frc971/external/com_github_google_flatbuffers/ts/builder';
32import {ByteBuffer} from 'org_frc971/external/com_github_google_flatbuffers/ts/byte-buffer';
33
34import Channel = configuration.aos.Channel;
35import Connection = proxy.Connection;
36import Configuration = configuration.aos.Configuration;
37import Schema = configuration.reflection.Schema;
38import Parser = reflection.Parser;
39import Table = reflection.Table;
40import SubscriberRequest = web_proxy.aos.web_proxy.SubscriberRequest;
41import ChannelRequest = web_proxy.aos.web_proxy.ChannelRequest;
42import TransferMethod = web_proxy.aos.web_proxy.TransferMethod;
43
44export class TimestampedMessage {
45 constructor(
46 public readonly message: Table, public readonly time: number) {}
47}
48
49// The MessageHandler stores an array of every single message on a given channel
50// and then supplies individual fields as arrays when requested. Currently this
51// is very much unoptimized and re-processes the entire array of messages on
52// every call to getField().
53export class MessageHandler {
54 protected parser: Parser;
55 protected messages: TimestampedMessage[] = [];
56 constructor(schema: Schema) {
57 this.parser = new Parser(schema);
58 }
59 addMessage(data: Uint8Array, time: number): void {
60 this.messages.push(
61 new TimestampedMessage(Table.getRootTable(new ByteBuffer(data)), time));
62 }
63 // Returns a time-series of every single instance of the given field. Format
64 // of the return value is [time0, value0, time1, value1,... timeN, valueN],
65 // to match with the Line.setPoint() interface.
66 // By convention, NaN is used to indicate that a message existed at a given
67 // timestamp but the requested field was not populated.
68 getField(field: string[]): Float32Array {
69 const fieldName = field[field.length - 1];
70 const subMessage = field.slice(0, field.length - 1);
71 const results = new Float32Array(this.messages.length * 2);
72 for (let ii = 0; ii < this.messages.length; ++ii) {
73 let message = this.messages[ii].message;
74 for (const subMessageName of subMessage) {
75 message = this.parser.readTable(message, subMessageName);
76 if (message === undefined) {
77 break;
78 }
79 }
80 results[ii * 2] = this.messages[ii].time;
81 if (message === undefined) {
82 results[ii * 2 + 1] = NaN;
83 } else {
84 results[ii * 2 + 1] = this.parser.readScalar(message, fieldName);
85 }
86 }
87 return results;
88 }
89 numMessages(): number {
90 return this.messages.length;
91 }
92}
93
94class MessageLine {
95 constructor(
96 public readonly messages: MessageHandler, public readonly line: Line,
97 public readonly field: string[]) {}
98}
99
100class AosPlot {
101 private lines: MessageLine[] = [];
102 constructor(
103 private readonly plotter: AosPlotter, public readonly plot: Plot) {}
104
105 // Adds a line to the figure.
106 // message specifies what channel/data source to pull from, and field
107 // specifies the field within that channel. field is an array specifying
108 // the full path to the field within the message. For instance, to
109 // plot whether the drivetrain is currently zeroed based on the drivetrain
110 // status message, you would specify the ['zeroing', 'zeroed'] field to
111 // get the DrivetrainStatus.zeroing().zeroed() member.
112 // Currently, this interface does not provide any support for non-numeric
113 // fields or for repeated fields (or sub-messages) of any sort.
114 addMessageLine(message: MessageHandler, field: string[]): Line {
115 const line = this.plot.getDrawer().addLine();
116 line.setLabel(field.join('.'));
117 this.lines.push(new MessageLine(message, line, field));
118 return line;
119 }
120
121 draw(): void {
122 // Only redraw lines if the number of points has changed--because getField()
123 // is a relatively expensive call, we don't want to do it any more than
124 // necessary.
125 for (const line of this.lines) {
126 if (line.messages.numMessages() * 2 != line.line.getPoints().length) {
127 line.line.setPoints(line.messages.getField(line.field));
128 }
129 }
130 }
131}
132
133export class AosPlotter {
134 private plots: AosPlot[] = [];
135 private messages = new Set<MessageHandler>();
136 constructor(private readonly connection: Connection) {
137 // Set up to redraw at some regular interval. The exact rate is unimportant.
138 setInterval(() => {
139 this.draw();
140 }, 100);
141 }
142
143 // Sets up an AOS channel as a message source. Returns a handler that can
144 // be passed to addMessageLine().
145 addMessageSource(name: string, type: string): MessageHandler {
146 return this.addRawMessageSource(
147 name, type, new MessageHandler(this.connection.getSchema(type)));
148 }
149
150 // Same as addMessageSource, but allows you to specify a custom MessageHandler
151 // that does some processing on the requested message. This allows you to
152 // create post-processed versions of individual channels.
153 addRawMessageSource(
154 name: string, type: string,
155 messageHandler: MessageHandler): MessageHandler {
156 this.messages.add(messageHandler);
157 // Use a "reliable" handler so that we get *all* the data when we are
158 // plotting from a logfile.
159 this.connection.addReliableHandler(
160 name, type, (data: Uint8Array, time: number) => {
161 messageHandler.addMessage(data, time);
162 });
163 return messageHandler;
164 }
165 // Add a new figure at the provided position with the provided size within
166 // parentElement.
167 addPlot(parentElement: Element, topLeft: number[], size: number[]): AosPlot {
168 const div = document.createElement("div");
169 div.style.top = topLeft[1].toString();
170 div.style.left = topLeft[0].toString();
171 div.style.position = 'absolute';
172 parentElement.appendChild(div);
173 const newPlot = new Plot(div, size[0], size[1]);
174 for (let plot of this.plots.values()) {
175 newPlot.linkXAxis(plot.plot);
176 }
177 this.plots.push(new AosPlot(this, newPlot));
178 return this.plots[this.plots.length - 1];
179 }
180 private draw(): void {
181 for (const plot of this.plots) {
182 plot.draw();
183 }
184 }
185}