blob: 65b9a2076bde7156ee0050a074a44c26ac962ff2 [file] [log] [blame]
Maxwell Hendersonad312342023-01-10 12:07:47 -08001import {ByteBuffer} from 'flatbuffers';
2import {Connection} from '../../aos/network/www/proxy';
James Kuszmaulfb894572023-02-23 17:25:06 -08003import {LocalizerOutput} from '../../frc971/control_loops/drivetrain/localization/localizer_output_generated';
4import {RejectionReason} from '../localizer/status_generated';
Maxwell Hendersonad312342023-01-10 12:07:47 -08005import {Status as DrivetrainStatus} from '../../frc971/control_loops/drivetrain/drivetrain_status_generated';
Milo Line6571c02023-03-04 21:08:20 -08006import {Status as SuperstructureStatus, EndEffectorState, ArmState, ArmStatus} from '../control_loops/superstructure/superstructure_status_generated'
7import {Class} from '../vision/game_pieces_generated'
Milo Lin72fb9012023-03-10 19:53:19 -08008import {ZeroingError} from '../../frc971/control_loops/control_loops_generated';
James Kuszmaulfb894572023-02-23 17:25:06 -08009import {Visualization, TargetEstimateDebug} from '../localizer/visualization_generated';
Maxwell Hendersonad312342023-01-10 12:07:47 -080010
11import {FIELD_LENGTH, FIELD_WIDTH, FT_TO_M, IN_TO_M} from './constants';
12
13// (0,0) is field center, +X is toward red DS
14const FIELD_SIDE_Y = FIELD_WIDTH / 2;
15const FIELD_EDGE_X = FIELD_LENGTH / 2;
16
James Kuszmaulfb894572023-02-23 17:25:06 -080017const ROBOT_WIDTH = 25 * IN_TO_M;
18const ROBOT_LENGTH = 32 * IN_TO_M;
Maxwell Hendersonad312342023-01-10 12:07:47 -080019
20const PI_COLORS = ['#ff00ff', '#ffff00', '#00ffff', '#ffa500'];
James Kuszmaulfb894572023-02-23 17:25:06 -080021const PIS = ['pi1', 'pi2', 'pi3', 'pi4'];
Maxwell Hendersonad312342023-01-10 12:07:47 -080022
23export class FieldHandler {
24 private canvas = document.createElement('canvas');
James Kuszmaulfb894572023-02-23 17:25:06 -080025 private localizerOutput: LocalizerOutput|null = null;
Maxwell Hendersonad312342023-01-10 12:07:47 -080026 private drivetrainStatus: DrivetrainStatus|null = null;
Milo Line6571c02023-03-04 21:08:20 -080027 private superstructureStatus: SuperstructureStatus|null = null;
Maxwell Hendersonad312342023-01-10 12:07:47 -080028
29 // Image information indexed by timestamp (seconds since the epoch), so that
30 // we can stop displaying images after a certain amount of time.
James Kuszmaulfb894572023-02-23 17:25:06 -080031 private localizerImageMatches = new Map<number, Visualization>();
32 private x: HTMLElement = (document.getElementById('x') as HTMLElement);
Maxwell Hendersonad312342023-01-10 12:07:47 -080033 private y: HTMLElement = (document.getElementById('y') as HTMLElement);
34 private theta: HTMLElement =
35 (document.getElementById('theta') as HTMLElement);
Maxwell Hendersonad312342023-01-10 12:07:47 -080036 private imagesAcceptedCounter: HTMLElement =
37 (document.getElementById('images_accepted') as HTMLElement);
James Kuszmaulfb894572023-02-23 17:25:06 -080038 private rejectionReasonCells: HTMLElement[] = [];
Maxwell Hendersonad312342023-01-10 12:07:47 -080039 private fieldImage: HTMLImageElement = new Image();
Milo Line6571c02023-03-04 21:08:20 -080040 private endEffectorState: HTMLElement =
41 (document.getElementById('end_effector_state') as HTMLElement);
42 private wrist: HTMLElement =
43 (document.getElementById('wrist') as HTMLElement);
44 private armState: HTMLElement =
45 (document.getElementById('arm_state') as HTMLElement);
46 private gamePiece: HTMLElement =
47 (document.getElementById('game_piece') as HTMLElement);
48 private armX: HTMLElement =
49 (document.getElementById('arm_x') as HTMLElement);
50 private armY: HTMLElement =
51 (document.getElementById('arm_y') as HTMLElement);
52 private circularIndex: HTMLElement =
53 (document.getElementById('arm_circular_index') as HTMLElement);
54 private roll: HTMLElement =
55 (document.getElementById('arm_roll') as HTMLElement);
56 private proximal: HTMLElement =
57 (document.getElementById('arm_proximal') as HTMLElement);
58 private distal: HTMLElement =
59 (document.getElementById('arm_distal') as HTMLElement);
Milo Lin72fb9012023-03-10 19:53:19 -080060 private zeroingFaults: HTMLElement =
61 (document.getElementById('zeroing_faults') as HTMLElement);_
Maxwell Hendersonad312342023-01-10 12:07:47 -080062
63 constructor(private readonly connection: Connection) {
64 (document.getElementById('field') as HTMLElement).appendChild(this.canvas);
65
James Kuszmaulfb894572023-02-23 17:25:06 -080066 this.fieldImage.src = "2023.png";
67
68 for (const value in RejectionReason) {
69 // Typescript generates an iterator that produces both numbers and
70 // strings... don't do anything on the string iterations.
71 if (isNaN(Number(value))) {
72 continue;
73 }
74 const row = document.createElement('div');
75 const nameCell = document.createElement('div');
76 nameCell.innerHTML = RejectionReason[value];
77 row.appendChild(nameCell);
78 const valueCell = document.createElement('div');
79 valueCell.innerHTML = 'NA';
80 this.rejectionReasonCells.push(valueCell);
81 row.appendChild(valueCell);
82 document.getElementById('vision_readouts').appendChild(row);
83 }
Maxwell Hendersonad312342023-01-10 12:07:47 -080084
85 for (let ii = 0; ii < PI_COLORS.length; ++ii) {
86 const legendEntry = document.createElement('div');
87 legendEntry.style.color = PI_COLORS[ii];
88 legendEntry.innerHTML = 'PI' + (ii + 1).toString()
89 document.getElementById('legend').appendChild(legendEntry);
90 }
91
92 this.connection.addConfigHandler(() => {
93 // Visualization message is reliable so that we can see *all* the vision
94 // matches.
James Kuszmaulfb894572023-02-23 17:25:06 -080095 for (const pi in PIS) {
96 this.connection.addReliableHandler(
97 '/' + PIS[pi] + '/camera', "y2023.localizer.Visualization",
98 (data) => {
99 this.handleLocalizerDebug(pi, data);
100 });
101 }
Maxwell Hendersonad312342023-01-10 12:07:47 -0800102 this.connection.addHandler(
103 '/drivetrain', "frc971.control_loops.drivetrain.Status", (data) => {
104 this.handleDrivetrainStatus(data);
105 });
106 this.connection.addHandler(
James Kuszmaulfb894572023-02-23 17:25:06 -0800107 '/localizer', "frc971.controls.LocalizerOutput", (data) => {
108 this.handleLocalizerOutput(data);
Maxwell Hendersonad312342023-01-10 12:07:47 -0800109 });
Milo Line6571c02023-03-04 21:08:20 -0800110 this.connection.addHandler(
111 '/superstructure', "y2023.control_loops.superstructure.Status",
112 (data) => {
113 this.handleSuperstructureStatus(data)
114 });
Maxwell Hendersonad312342023-01-10 12:07:47 -0800115 });
116 }
117
James Kuszmaulfb894572023-02-23 17:25:06 -0800118 private handleLocalizerDebug(pi: string, data: Uint8Array): void {
119 const now = Date.now() / 1000.0;
120
121 const fbBuffer = new ByteBuffer(data);
122 this.localizerImageMatches.set(
123 now, Visualization.getRootAsVisualization(fbBuffer));
124
125 const debug = this.localizerImageMatches.get(now);
126
127 if (debug.statistics()) {
128 if (debug.statistics().rejectionReasonsLength() ==
129 this.rejectionReasonCells.length) {
130 for (let ii = 0; ii < debug.statistics().rejectionReasonsLength();
131 ++ii) {
132 this.rejectionReasonCells[ii].innerHTML =
133 debug.statistics().rejectionReasons(ii).count().toString();
134 }
135 } else {
136 console.error('Unexpected number of rejection reasons in counter.');
137 }
138 }
139 }
140
141 private handleLocalizerOutput(data: Uint8Array): void {
142 const fbBuffer = new ByteBuffer(data);
143 this.localizerOutput = LocalizerOutput.getRootAsLocalizerOutput(fbBuffer);
144 }
145
Maxwell Hendersonad312342023-01-10 12:07:47 -0800146 private handleDrivetrainStatus(data: Uint8Array): void {
147 const fbBuffer = new ByteBuffer(data);
148 this.drivetrainStatus = DrivetrainStatus.getRootAsStatus(fbBuffer);
149 }
150
Milo Line6571c02023-03-04 21:08:20 -0800151 private handleSuperstructureStatus(data: Uint8Array): void {
152 const fbBuffer = new ByteBuffer(data);
153 this.superstructureStatus = SuperstructureStatus.getRootAsStatus(fbBuffer);
154 }
155
Maxwell Hendersonad312342023-01-10 12:07:47 -0800156 drawField(): void {
157 const ctx = this.canvas.getContext('2d');
158 ctx.save();
James Kuszmaulfb894572023-02-23 17:25:06 -0800159 ctx.scale(1.0, -1.0);
Maxwell Hendersonad312342023-01-10 12:07:47 -0800160 ctx.drawImage(
161 this.fieldImage, 0, 0, this.fieldImage.width, this.fieldImage.height,
162 -FIELD_EDGE_X, -FIELD_SIDE_Y, FIELD_LENGTH, FIELD_WIDTH);
163 ctx.restore();
164 }
165
166 drawCamera(
James Kuszmaulfb894572023-02-23 17:25:06 -0800167 x: number, y: number, theta: number, color: string = 'blue'): void {
Maxwell Hendersonad312342023-01-10 12:07:47 -0800168 const ctx = this.canvas.getContext('2d');
169 ctx.save();
170 ctx.translate(x, y);
171 ctx.rotate(theta);
172 ctx.strokeStyle = color;
173 ctx.beginPath();
174 ctx.moveTo(0.5, 0.5);
175 ctx.lineTo(0, 0);
Maxwell Hendersonad312342023-01-10 12:07:47 -0800176 ctx.lineTo(0.5, -0.5);
177 ctx.stroke();
178 ctx.beginPath();
179 ctx.arc(0, 0, 0.25, -Math.PI / 4, Math.PI / 4);
180 ctx.stroke();
181 ctx.restore();
182 }
183
184 drawRobot(
James Kuszmaulfb894572023-02-23 17:25:06 -0800185 x: number, y: number, theta: number,
186 color: string = 'blue', dashed: boolean = false): void {
Maxwell Hendersonad312342023-01-10 12:07:47 -0800187 const ctx = this.canvas.getContext('2d');
188 ctx.save();
189 ctx.translate(x, y);
190 ctx.rotate(theta);
191 ctx.strokeStyle = color;
192 ctx.lineWidth = ROBOT_WIDTH / 10.0;
193 if (dashed) {
194 ctx.setLineDash([0.05, 0.05]);
195 } else {
196 // Empty array = solid line.
197 ctx.setLineDash([]);
198 }
199 ctx.rect(-ROBOT_LENGTH / 2, -ROBOT_WIDTH / 2, ROBOT_LENGTH, ROBOT_WIDTH);
200 ctx.stroke();
201
202 // Draw line indicating which direction is forwards on the robot.
203 ctx.beginPath();
204 ctx.moveTo(0, 0);
James Kuszmaulfb894572023-02-23 17:25:06 -0800205 ctx.lineTo(ROBOT_LENGTH / 2.0, 0);
Maxwell Hendersonad312342023-01-10 12:07:47 -0800206 ctx.stroke();
207
208 ctx.restore();
209 }
210
211 setZeroing(div: HTMLElement): void {
212 div.innerHTML = 'zeroing';
213 div.classList.remove('faulted');
214 div.classList.add('zeroing');
215 div.classList.remove('near');
216 }
217
Milo Line6571c02023-03-04 21:08:20 -0800218 setEstopped(div: HTMLElement): void {
219 div.innerHTML = 'estopped';
220 div.classList.add('faulted');
221 div.classList.remove('zeroing');
222 div.classList.remove('near');
223 }
224
225 setTargetValue(
226 div: HTMLElement, target: number, val: number, tolerance: number): void {
227 div.innerHTML = val.toFixed(4);
228 div.classList.remove('faulted');
229 div.classList.remove('zeroing');
230 if (Math.abs(target - val) < tolerance) {
231 div.classList.add('near');
232 } else {
233 div.classList.remove('near');
234 }
235 }
236
Maxwell Hendersonad312342023-01-10 12:07:47 -0800237 setValue(div: HTMLElement, val: number): void {
238 div.innerHTML = val.toFixed(4);
239 div.classList.remove('faulted');
240 div.classList.remove('zeroing');
241 div.classList.remove('near');
242 }
243
244 draw(): void {
245 this.reset();
246 this.drawField();
247
248 // Draw the matches with debugging information from the localizer.
249 const now = Date.now() / 1000.0;
James Kuszmaulfb894572023-02-23 17:25:06 -0800250
Milo Line6571c02023-03-04 21:08:20 -0800251 if (this.superstructureStatus) {
252 this.endEffectorState.innerHTML =
253 EndEffectorState[this.superstructureStatus.endEffectorState()];
254 if (!this.superstructureStatus.wrist() ||
255 !this.superstructureStatus.wrist().zeroed()) {
256 this.setZeroing(this.wrist);
257 } else if (this.superstructureStatus.wrist().estopped()) {
258 this.setEstopped(this.wrist);
259 } else {
260 this.setTargetValue(
261 this.wrist,
262 this.superstructureStatus.wrist().unprofiledGoalPosition(),
263 this.superstructureStatus.wrist().estimatorState().position(),
264 1e-3);
265 }
266 this.armState.innerHTML =
267 ArmState[this.superstructureStatus.arm().state()];
268 this.gamePiece.innerHTML =
269 Class[this.superstructureStatus.gamePiece()];
270 this.armX.innerHTML =
271 this.superstructureStatus.arm().armX().toFixed(2);
272 this.armY.innerHTML =
273 this.superstructureStatus.arm().armY().toFixed(2);
274 this.circularIndex.innerHTML =
275 this.superstructureStatus.arm().armCircularIndex().toFixed(0);
276 this.roll.innerHTML =
277 this.superstructureStatus.arm().rollJointEstimatorState().position().toFixed(2);
278 this.proximal.innerHTML =
279 this.superstructureStatus.arm().proximalEstimatorState().position().toFixed(2);
280 this.distal.innerHTML =
281 this.superstructureStatus.arm().distalEstimatorState().position().toFixed(2);
Milo Lin72fb9012023-03-10 19:53:19 -0800282 let zeroingErrors: string = "Roll Joint Errors:"+'<br/>';
283 for (let i = 0; i < this.superstructureStatus.arm().rollJointEstimatorState().errors.length; i++) {
284 zeroingErrors += ZeroingError[this.superstructureStatus.arm().rollJointEstimatorState().errors(i)]+'<br/>';
285 }
286 zeroingErrors += '<br/>'+"Proximal Joint Errors:"+'<br/>';
287 for (let i = 0; i < this.superstructureStatus.arm().proximalEstimatorState().errors.length; i++) {
288 zeroingErrors += ZeroingError[this.superstructureStatus.arm().proximalEstimatorState().errors(i)]+'<br/>';
289 }
290 zeroingErrors += '<br/>'+"Distal Joint Errors:"+'<br/>';
291 for (let i = 0; i < this.superstructureStatus.arm().distalEstimatorState().errors.length; i++) {
292 zeroingErrors += ZeroingError[this.superstructureStatus.arm().distalEstimatorState().errors(i)]+'<br/>';
293 }
294 zeroingErrors += '<br/>'+"Wrist Errors:"+'<br/>';
295 for (let i = 0; i < this.superstructureStatus.wrist().estimatorState().errors.length; i++) {
296 zeroingErrors += ZeroingError[this.superstructureStatus.wrist().estimatorState().errors(i)]+'<br/>';
297 }
298 this.zeroingFaults.innerHTML = zeroingErrors;
Milo Line6571c02023-03-04 21:08:20 -0800299 }
300
Maxwell Hendersonad312342023-01-10 12:07:47 -0800301 if (this.drivetrainStatus && this.drivetrainStatus.trajectoryLogging()) {
302 this.drawRobot(
303 this.drivetrainStatus.trajectoryLogging().x(),
304 this.drivetrainStatus.trajectoryLogging().y(),
James Kuszmaulfb894572023-02-23 17:25:06 -0800305 this.drivetrainStatus.trajectoryLogging().theta(), "#000000FF",
Maxwell Hendersonad312342023-01-10 12:07:47 -0800306 false);
307 }
308
James Kuszmaulfb894572023-02-23 17:25:06 -0800309 if (this.localizerOutput) {
310 if (!this.localizerOutput.zeroed()) {
311 this.setZeroing(this.x);
312 this.setZeroing(this.y);
313 this.setZeroing(this.theta);
314 } else {
315 this.setValue(this.x, this.localizerOutput.x());
316 this.setValue(this.y, this.localizerOutput.y());
317 this.setValue(this.theta, this.localizerOutput.theta());
318 }
319
320 this.drawRobot(
321 this.localizerOutput.x(), this.localizerOutput.y(),
322 this.localizerOutput.theta());
323
324 this.imagesAcceptedCounter.innerHTML =
325 this.localizerOutput.imageAcceptedCount().toString();
326 }
327
328 for (const [time, value] of this.localizerImageMatches) {
329 const age = now - time;
330 const kRemovalAge = 1.0;
331 if (age > kRemovalAge) {
332 this.localizerImageMatches.delete(time);
333 continue;
334 }
335 const kMaxImageAlpha = 0.5;
336 const ageAlpha = kMaxImageAlpha * (kRemovalAge - age) / kRemovalAge
337 for (let i = 0; i < value.targetsLength(); i++) {
338 const imageDebug = value.targets(i);
339 const x = imageDebug.impliedRobotX();
340 const y = imageDebug.impliedRobotY();
341 const theta = imageDebug.impliedRobotTheta();
342 const cameraX = imageDebug.cameraX();
343 const cameraY = imageDebug.cameraY();
344 const cameraTheta = imageDebug.cameraTheta();
345 const accepted = imageDebug.accepted();
346 // Make camera readings fade over time.
347 const alpha = Math.round(255 * ageAlpha).toString(16).padStart(2, '0');
348 const dashed = false;
James Kuszmaulfb894572023-02-23 17:25:06 -0800349 const cameraRgb = PI_COLORS[imageDebug.camera()];
350 const cameraRgba = cameraRgb + alpha;
James Kuszmaul122a22b2023-02-25 18:14:15 -0800351 this.drawRobot(x, y, theta, cameraRgba, dashed);
James Kuszmaulfb894572023-02-23 17:25:06 -0800352 this.drawCamera(cameraX, cameraY, cameraTheta, cameraRgba);
353 }
354 }
355
Maxwell Hendersonad312342023-01-10 12:07:47 -0800356 window.requestAnimationFrame(() => this.draw());
357 }
358
359 reset(): void {
360 const ctx = this.canvas.getContext('2d');
361 ctx.setTransform(1, 0, 0, 1, 0, 0);
362 const size = window.innerHeight * 0.9;
363 ctx.canvas.height = size;
364 const width = size / 2 + 20;
365 ctx.canvas.width = width;
366 ctx.clearRect(0, 0, size, width);
367
368 // Translate to center of display.
369 ctx.translate(width / 2, size / 2);
370 // Coordinate system is:
371 // x -> forward.
372 // y -> to the left.
373 ctx.rotate(-Math.PI / 2);
374 ctx.scale(1, -1);
375
376 const M_TO_PX = (size - 10) / FIELD_LENGTH;
377 ctx.scale(M_TO_PX, M_TO_PX);
378 ctx.lineWidth = 1 / M_TO_PX;
379 }
380}