Interactive engine data charts: click to zoom, crosshair readout, range stats

Clicking a chart opens a viewer with higher-resolution data (new JSON
endpoint, fetched once): drag to zoom, tabs keep the zoom across metrics,
legend toggles, and min/avg/max for the visible range in monitor time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-06 17:42:24 -05:00
1 parent 4b6329843d
commit 2d068e1a63
8 files changed
+497 -15

No files matched your search

+10 -1
View File
@@ -1,7 +1,7 @@
class FlightLogsController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: :destroy
before_action :set_flight_log, only: %i[show attach_engine_data remove_engine_data]
before_action :set_flight_log, only: %i[show engine_data_series attach_engine_data remove_engine_data]
before_action :require_engine_data_access!, only: %i[attach_engine_data remove_engine_data]
helper_method :manage_engine_data?
@@ -25,6 +25,15 @@ class FlightLogsController < ApplicationController
@air_trail_sync = @flight_log.air_trail_syncs.first
end
# JSON for the interactive engine chart viewer (loaded when a chart is clicked).
def engine_data_series
recording = EngineDataParser.parse_attachment(@flight_log.engine_data) or return head(:not_found)
return unless stale?(etag: [ @flight_log.engine_data.blob.key, EngineDataParser::CACHE_VERSION ], public: false)
render json: recording.detail.merge(groups: helpers.engine_chart_groups(recording))
rescue EngineDataParser::Error, ActiveStorage::FileNotFoundError => e
render json: { error: e.message }, status: :unprocessable_entity
end
def new
# Aircraft almost always depart from where they last landed.
last = @aircraft.flight_logs.where.not(destination_location: [ nil, "" ]).recent_first.first
+19
View File
@@ -13,6 +13,25 @@ module FlightLogsHelper
"#{number_with_delimiter(number_with_precision(value, precision: precision))} #{unit}"
end
CHART_COLOR = "#3366CC".freeze # Chartkick's first color, for single-series charts
# The charts shown for a recording; shared by the page and the interactive viewer.
def engine_chart_groups(recording)
[
[ "CHT", recording.cht_keys, "°F", CYLINDER_COLORS ],
[ "EGT", recording.egt_keys, "°F", CYLINDER_COLORS ],
[ "RPM", [ :rpm ], "rpm" ],
[ "Manifold pressure", [ :map ], "inHg" ],
[ "Fuel flow", [ :fuel_flow ], "gph" ],
[ "Oil temp", [ :oil_t ], "°F" ],
[ "Oil pressure", [ :oil_p ], "psi" ],
[ "Volts", [ :volts ], "V" ]
].filter_map do |title, keys, unit, colors|
keys = keys.select { recording.channels.key?(_1) }
{ title: title, keys: keys, unit: unit, colors: colors || [ CHART_COLOR ] } if keys.any?
end
end
def engine_chart(recording, *keys, ytitle:, colors: nil)
series = recording.chart(*keys)
return if series.empty?
@@ -0,0 +1,340 @@
import { Controller } from "@hotwired/stimulus"
// Interactive viewer for engine monitor charts. Clicking a chart opens it large
// with higher-resolution data (fetched once, on first open): a crosshair shows
// every series' value at that moment, dragging across the chart zooms into that
// stretch of the flight, and the table shows min/avg/max for the visible range.
// Times are shown as monitor (local) time, like the peaks table.
const STEPS = [ 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600 ].map((s) => s * 1000)
const MIN_ZOOM_MS = 5000
export default class extends Controller {
static targets = [ "dialog", "tabs", "canvas", "frame", "selection", "status", "stats", "range", "reset", "zoomOut" ]
static values = { url: String }
connect() {
this.group = 0
this.zoom = null // [min, max] in ms since epoch, or null for the whole recording
this.restyle = () => this.chart?.update("none")
window.addEventListener("theme:change", this.restyle)
}
disconnect() {
window.removeEventListener("theme:change", this.restyle)
this.chart?.destroy()
if (this.dialogTarget.open) this.dialogTarget.close()
}
async open(event) {
event.preventDefault()
this.group = Number(event.params.group) || 0
this.dialogTarget.showModal()
try {
this.series ||= await this.load()
this.renderTabs()
this.render()
} catch (error) {
this.statusTarget.hidden = false
this.statusTarget.textContent = `Couldn't load the engine data (${error.message}).`
}
}
close() {
this.dialogTarget.close()
}
closed() {
this.endDrag()
}
keydown(event) {
if (event.target.closest("[role=tablist]") && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
event.preventDefault()
const count = this.series.groups.length
this.select((this.group + (event.key === "ArrowRight" ? 1 : -1) + count) % count, true)
}
}
async load() {
const response = await fetch(this.urlValue, { headers: { Accept: "application/json" }, credentials: "same-origin" })
const body = await response.json().catch(() => ({}))
if (!response.ok) throw new Error(body.error || `HTTP ${response.status}`)
const times = body.times.map((t) => body.started_at + t)
return { ...body, times, end: times[times.length - 1], start: times[0] }
}
// ---- metric tabs ----
renderTabs() {
this.tabsTarget.replaceChildren(...this.series.groups.map((group, i) => {
const tab = document.createElement("button")
tab.type = "button"
tab.setAttribute("role", "tab")
tab.textContent = group.title
tab.className = "shrink-0 rounded-md px-3 py-1.5 text-sm font-medium whitespace-nowrap"
tab.addEventListener("click", () => this.select(i))
return tab
}))
this.highlightTab()
}
highlightTab() {
Array.from(this.tabsTarget.children).forEach((tab, i) => {
const active = i === this.group
tab.setAttribute("aria-selected", active)
tab.tabIndex = active ? 0 : -1
tab.classList.toggle("bg-accent", active)
tab.classList.toggle("text-white", active)
tab.classList.toggle("text-slate-600", !active)
tab.classList.toggle("hover:bg-slate-100", !active)
})
}
select(index, focus = false) {
this.group = index
this.highlightTab()
if (focus) this.tabsTarget.children[index].focus()
this.tabsTarget.children[index].scrollIntoView({ block: "nearest", inline: "nearest" })
this.render()
}
// ---- chart ----
render() {
const { groups, channels, times } = this.series
const group = groups[this.group]
const datasets = group.keys.map((key, i) => {
const channel = channels[key]
const color = group.colors[i % group.colors.length]
return {
label: channel.label,
unit: channel.unit,
data: channel.values.map((y, j) => ({ x: times[j], y })),
borderColor: color,
backgroundColor: color,
borderWidth: 1.5,
pointRadius: 0,
pointHoverRadius: 3,
tension: 0
}
})
this.chart?.destroy()
this.statusTarget.hidden = true
this.chart = new window.Chart(this.canvasTarget, {
type: "line",
data: { datasets },
options: this.options(group, datasets.length > 1),
plugins: [ crosshair ]
})
this.applyZoom()
}
options(group, legend) {
const format = (ms, seconds) => this.clock(ms, seconds)
return {
animation: false,
parsing: false,
normalized: true,
responsive: true,
maintainAspectRatio: false,
spanGaps: false,
interaction: { mode: "index", intersect: false },
scales: {
x: {
type: "linear",
ticks: { maxRotation: 0, autoSkipPadding: 12, includeBounds: false, callback: (value) => format(value, this.step < 60000) }
},
y: { title: { display: true, text: group.unit } }
},
plugins: {
legend: {
display: legend,
position: "bottom",
labels: { boxWidth: 12, boxHeight: 2 },
onClick: (event, item, legendBox) => {
window.Chart.defaults.plugins.legend.onClick.call(legendBox, event, item, legendBox)
this.renderStats()
}
},
tooltip: {
callbacks: {
title: (items) => items.length ? format(items[0].parsed.x, true) : "",
label: (item) => `${item.dataset.label}: ${number(item.parsed.y, item.dataset.unit)} ${item.dataset.unit}`
}
}
}
}
}
// ---- zoom ----
applyZoom() {
const [ min, max ] = this.zoom || [ this.series.start, this.series.end ]
this.step = niceStep(max - min)
const x = this.chart.options.scales.x
x.min = min
x.max = max
x.ticks.stepSize = this.step
this.chart.update("none")
this.resetTarget.disabled = this.zoomOutTarget.disabled = !this.zoom
this.rangeTarget.textContent = `${this.clock(min, true)} – ${this.clock(max, true)} (${duration(max - min)})`
this.renderStats()
}
zoomTo(min, max) {
const { start, end } = this.series
if (max - min < MIN_ZOOM_MS) {
const mid = (min + max) / 2
min = mid - MIN_ZOOM_MS / 2
max = mid + MIN_ZOOM_MS / 2
}
min = Math.max(start, min)
max = Math.min(end, max)
this.zoom = (min <= start && max >= end) ? null : [ min, max ]
this.applyZoom()
}
zoomOut() {
if (!this.zoom) return
const [ min, max ] = this.zoom
const half = max - min
this.zoomTo(min - half / 2, max + half / 2)
}
resetZoom() {
this.zoom = null
if (this.chart) this.applyZoom()
}
// Drag across the plot area to select a time range.
dragStart(event) {
if (!this.chart || event.button > 0) return
const x = this.plotX(event)
const y = event.clientY - this.canvasTarget.getBoundingClientRect().top
if (x == null || y < this.chart.chartArea.top || y > this.chart.chartArea.bottom) return // e.g. the legend
this.drag = { from: x, to: x, pointer: event.pointerId }
}
dragMove(event) {
if (!this.drag || event.pointerId !== this.drag.pointer) return
this.drag.to = this.plotX(event, true)
const left = Math.min(this.drag.from, this.drag.to)
const width = Math.abs(this.drag.to - this.drag.from)
if (width < 4) return
// Capture only once it's really a drag, so plain clicks still reach the chart.
if (!this.frameTarget.hasPointerCapture(event.pointerId)) this.frameTarget.setPointerCapture(event.pointerId)
const area = this.chart.chartArea
const offset = this.canvasTarget.offsetLeft
Object.assign(this.selectionTarget.style, {
left: `${offset + left}px`, width: `${width}px`,
top: `${this.canvasTarget.offsetTop + area.top}px`, height: `${area.bottom - area.top}px`
})
this.selectionTarget.hidden = false
}
dragEnd(event) {
if (!this.drag || event.pointerId !== this.drag.pointer) return
const { from, to } = this.drag
this.endDrag()
if (Math.abs(to - from) < 8) return // a tap or click, not a drag
const scale = this.chart.scales.x
const area = this.chart.chartArea
this.zoomTo(scale.getValueForPixel(area.left + Math.min(from, to)), scale.getValueForPixel(area.left + Math.max(from, to)))
}
dragCancel() {
this.endDrag()
}
endDrag() {
this.drag = null
if (this.hasSelectionTarget) this.selectionTarget.hidden = true
}
// Pointer x within the chart's plot area (clamped when dragging out of it).
plotX(event, clamp = false) {
const area = this.chart.chartArea
const x = event.clientX - this.canvasTarget.getBoundingClientRect().left - area.left
const width = area.right - area.left
if (clamp) return Math.min(Math.max(x, 0), width)
return x >= 0 && x <= width ? x : null
}
// ---- stats ----
renderStats() {
if (!this.chart) return
const [ min, max ] = this.zoom || [ this.series.start, this.series.end ]
const rows = this.chart.data.datasets.map((dataset, i) => {
const values = dataset.data.filter((p) => p.x >= min && p.x <= max && p.y != null).map((p) => p.y)
const hidden = !this.chart.isDatasetVisible(i)
const row = document.createElement("tr")
if (hidden) row.className = "opacity-40"
const name = document.createElement("td")
const swatch = document.createElement("span")
swatch.className = "mr-2 inline-block h-2.5 w-2.5 rounded-full align-middle"
swatch.style.background = dataset.borderColor
name.append(swatch, dataset.label)
row.append(name)
const stats = values.length ? [ Math.min(...values), values.reduce((a, b) => a + b, 0) / values.length, Math.max(...values) ] : [ null, null, null ]
stats.forEach((value) => {
const cell = document.createElement("td")
cell.className = "text-right tabular-nums"
cell.textContent = value == null ? "—" : `${number(value, dataset.unit)} ${dataset.unit}`
row.append(cell)
})
return row
})
this.statsTarget.replaceChildren(...rows)
}
// ---- formatting ----
// Monitor wall-clock time for an epoch-ms value.
clock(ms, seconds) {
const d = new Date(ms + this.series.utc_offset * 1000)
const pad = (n) => String(n).padStart(2, "0")
return `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}${seconds ? `:${pad(d.getUTCSeconds())}` : ""}`
}
}
// The smallest "round" tick interval that gives at most ~8 ticks.
function niceStep(range) {
return STEPS.find((step) => range / step <= 8) || STEPS[STEPS.length - 1]
}
function duration(ms) {
const s = Math.round(ms / 1000)
if (s >= 3600) return `${Math.floor(s / 3600)}h ${String(Math.floor(s % 3600 / 60)).padStart(2, "0")}m`
return `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s`
}
// Temperatures, RPM and pressures read as whole numbers; volts, flows and fuel to a tenth.
const TENTHS = [ "inHg", "gph", "V", "A", "gal" ]
function number(value, unit) {
const digits = TENTHS.includes(unit) ? 1 : 0
return value.toLocaleString(undefined, { maximumFractionDigits: digits, minimumFractionDigits: digits })
}
// Vertical line at the hovered time.
const crosshair = {
id: "crosshair",
afterDatasetsDraw(chart) {
const active = chart.tooltip?.getActiveElements?.()
if (!active?.length) return
const x = active[0].element.x
const { top, bottom } = chart.chartArea
const ctx = chart.ctx
ctx.save()
ctx.beginPath()
ctx.moveTo(x, top)
ctx.lineTo(x, bottom)
ctx.lineWidth = 1
ctx.strokeStyle = window.Chart.defaults.color
ctx.globalAlpha = 0.5
ctx.stroke()
ctx.restore()
}
}
+17
View File
@@ -12,6 +12,7 @@ class EngineDataParser
RUNNING_RPM = 300 # below this the engine is off (or starting)
MAX_GAP_SECONDS = 10 # don't integrate fuel flow across a hole in the data
CHART_POINTS = 600
DETAIL_POINTS = 6000 # the interactive chart viewer's resolution
CACHE_VERSION = 1 # bump when parsing changes, to re-read cached recordings
# Column name (before ";", whitespace squeezed) → channel. First match wins,
@@ -94,6 +95,22 @@ class EngineDataParser
end
end
# Higher-resolution data for the interactive viewer: times in ms after the
# start, values rounded and with whole numbers as integers to keep it small.
def detail(max_points: DETAIL_POINTS)
step = [ (samples.to_f / max_points).ceil, 1 ].max
idx = (0...samples).step(step).to_a
start = times.first
{
started_at: (start.to_r * 1000).round,
utc_offset: utc_offset,
times: idx.map { ((times[_1] - start) * 1000).round },
channels: channels.transform_values do |ch|
{ label: ch.label, unit: ch.unit, values: idx.map { |i| (v = ch.values[i]) && (v == v.round ? v.round : v.round(2)) } }
end
}
end
private
def extreme(key, how)
+50 -14
View File
@@ -51,22 +51,58 @@
</table>
</div>
<div class="grid gap-6 border-t border-slate-100 p-4 lg:grid-cols-2">
<% colors = FlightLogsHelper::CYLINDER_COLORS %>
<% [
[ "CHT", recording.cht_keys, "°F", colors ],
[ "EGT", recording.egt_keys, "°F", colors ],
[ "RPM", [ :rpm ], "rpm" ],
[ "Manifold pressure", [ :map ], "inHg" ],
[ "Fuel flow", [ :fuel_flow ], "gph" ],
[ "Oil temp", [ :oil_t ], "°F" ],
[ "Oil pressure", [ :oil_p ], "psi" ],
[ "Volts", [ :volts ], "V" ]
].each do |title, keys, unit, palette| %>
<% chart = engine_chart(recording, *keys, ytitle: unit, colors: palette) %>
<% if chart %><figure><figcaption class="mb-1 text-xs font-semibold text-slate-600"><%= title %></figcaption><%= chart %></figure><% end %>
<div data-controller="engine-chart" data-engine-chart-url-value="<%= engine_data_aircraft_flight_log_path(@aircraft, flight_log, format: :json) %>"
class="border-t border-slate-100">
<p class="px-4 pt-3 text-xs text-slate-500">Click a chart to explore it: zoom into any part of the flight and read exact values.</p>
<div class="grid gap-6 p-4 lg:grid-cols-2">
<% engine_chart_groups(recording).each_with_index do |group, i| %>
<% chart = engine_chart(recording, *group[:keys], ytitle: group[:unit], colors: group[:colors].many? ? group[:colors] : nil) %>
<% next unless chart %>
<figure role="button" tabindex="0" aria-label="Explore the <%= group[:title] %> chart"
class="group cursor-zoom-in rounded-md p-1 ring-sky-500/40 transition hover:ring-2 focus-visible:outline-none focus-visible:ring-2"
data-action="click->engine-chart#open keydown.enter->engine-chart#open keydown.space->engine-chart#open"
data-engine-chart-group-param="<%= i %>">
<figcaption class="mb-1 flex items-center justify-between text-xs font-semibold text-slate-600">
<%= group[:title] %>
<span class="font-normal text-slate-400 group-hover:text-sky-700" aria-hidden="true">⤢ Explore</span>
</figcaption>
<%= chart %>
</figure>
<% end %>
</div>
<dialog data-engine-chart-target="dialog" aria-label="Engine data viewer"
class="m-auto h-dvh max-h-none w-screen max-w-none bg-surface p-0 text-slate-800 shadow-2xl backdrop:bg-black/60 sm:h-[min(52rem,94dvh)] sm:w-[min(80rem,96vw)] sm:rounded-lg"
data-action="keydown->engine-chart#keydown close->engine-chart#closed">
<div class="flex h-full flex-col">
<div class="flex items-center gap-2 border-b border-slate-200 px-3 py-2">
<div data-engine-chart-target="tabs" role="tablist" class="flex min-w-0 flex-1 gap-1 overflow-x-auto"></div>
<button type="button" data-action="engine-chart#close" class="rounded px-2 py-1 text-lg leading-none text-slate-500 hover:bg-slate-100" aria-label="Close">✕</button>
</div>
<div class="flex flex-wrap items-center gap-2 px-4 py-2 text-xs text-slate-500">
<span data-engine-chart-target="range" class="tabular-nums"></span>
<span class="hidden sm:inline">· Drag across the chart to zoom in, double-click to reset.</span>
<span class="sm:hidden">· Drag to zoom.</span>
<span class="ml-auto flex gap-2">
<button type="button" data-engine-chart-target="zoomOut" data-action="engine-chart#zoomOut" class="btn-secondary btn-sm" disabled>Zoom out</button>
<button type="button" data-engine-chart-target="reset" data-action="engine-chart#resetZoom" class="btn-secondary btn-sm" disabled>Reset zoom</button>
</span>
</div>
<div class="relative min-h-0 flex-1 touch-none select-none px-2 sm:px-4" data-engine-chart-target="frame"
data-action="pointerdown->engine-chart#dragStart pointermove->engine-chart#dragMove pointerup->engine-chart#dragEnd pointercancel->engine-chart#dragCancel dblclick->engine-chart#resetZoom">
<canvas data-engine-chart-target="canvas"></canvas>
<div data-engine-chart-target="selection" hidden class="pointer-events-none absolute border-x border-sky-500 bg-sky-500/15"></div>
<p data-engine-chart-target="status" class="absolute inset-0 grid place-items-center text-sm text-slate-500">Loading…</p>
</div>
<div class="max-h-[30%] overflow-auto border-t border-slate-200">
<table class="table text-sm">
<thead><tr><th>Series <span class="font-normal normal-case text-slate-400">(visible range)</span></th><th class="text-right">Min</th><th class="text-right">Avg</th><th class="text-right">Max</th></tr></thead>
<tbody data-engine-chart-target="stats"></tbody>
</table>
</div>
</div>
</dialog>
</div>
<% elsif error %>
<p class="card-body text-sm text-amber-700"><%= error %></p>
<% end %>
+1
View File
@@ -26,6 +26,7 @@ Rails.application.routes.draw do
resources :notes, except: :show
resources :flight_logs, only: %i[index new create show destroy] do
member do
get :engine_data, action: :engine_data_series
patch :engine_data, action: :attach_engine_data
delete :engine_data, action: :remove_engine_data
end
+44
View File
@@ -68,4 +68,48 @@ class EngineDataFlowTest < ActionDispatch::IntegrationTest
get aircraft_flight_log_path(@aircraft, flight)
assert_includes response.body, "This recording is from <strong>N12345</strong>"
end
test "charts open an interactive viewer fed by a JSON series" do
flight = @aircraft.flight_logs.create!(date: Date.new(2025, 7, 14), tach_time: 0.1, user: @pilot, engine_data: upload)
sign_in @other_pilot # anyone with access to the aircraft can explore the charts
get aircraft_flight_log_path(@aircraft, flight)
url = engine_data_aircraft_flight_log_path(@aircraft, flight, format: :json)
assert_select "[data-controller=engine-chart][data-engine-chart-url-value='#{url}']" do
assert_select "figure[role=button][data-action*='engine-chart#open']", minimum: 4
assert_select "figure[data-engine-chart-group-param='0'] figcaption", text: /CHT/
assert_select "dialog[data-engine-chart-target=dialog] canvas[data-engine-chart-target=canvas]"
end
get url
assert_response :success
data = response.parsed_body
assert_equal data["times"].size, data["channels"]["rpm"]["values"].size
assert_equal 0, data["times"].first
assert data["times"].each_cons(2).all? { _1 <= _2 }, "times ascend"
assert_kind_of Integer, data["started_at"]
assert_equal %w[CHT EGT RPM], data["groups"].first(3).map { _1["title"] }
cht = data["groups"].first
assert_equal %w[cht1 cht2 cht3 cht4], cht["keys"]
assert_equal "°F", cht["unit"]
data["groups"].flat_map { _1["keys"] }.each { assert data["channels"].key?(_1), "#{_1} has data" }
etag = response.headers["ETag"]
get url, headers: { "If-None-Match" => etag }
assert_response :not_modified
end
test "the series stays private to people with access to the aircraft" do
flight = @aircraft.flight_logs.create!(date: Date.new(2025, 7, 14), tach_time: 0.1, user: @pilot, engine_data: upload)
sign_in create_user
get engine_data_aircraft_flight_log_path(@aircraft, flight, format: :json)
assert_response :not_found
end
test "a flight without engine data has no series" do
flight = @aircraft.flight_logs.create!(date: Date.new(2025, 7, 14), tach_time: 0.1, user: @pilot)
sign_in @pilot
get engine_data_aircraft_flight_log_path(@aircraft, flight, format: :json)
assert_response :not_found
end
end
+16
View File
@@ -75,4 +75,20 @@ class EngineDataParserTest < ActiveSupport::TestCase
assert_raises(EngineDataParser::Error) { EngineDataParser.new("lat,lon\n1,2\n").parse }
assert_raises(EngineDataParser::Error) { EngineDataParser.new("CGR-30P\nLocal Time: 2025/07/14 08:00:00\nTIME,RPM;***\n").parse }
end
test "detail series for the chart viewer: ms offsets, compact values, thinned to a limit" do
full = recording.detail
assert_equal (recording.started_at.to_r * 1000).round, full[:started_at]
assert_equal recording.samples, full[:times].size
assert_equal 0, full[:times].first
assert_equal ((recording.ended_at - recording.started_at) * 1000).round, full[:times].last
assert_equal(-4.hours.to_i, full[:utc_offset])
rpm = full[:channels][:rpm]
assert_equal [ "RPM", "RPM" ], [ rpm[:label], rpm[:unit] ]
assert rpm[:values].compact.all?(Integer), "whole numbers are sent as integers"
thin = recording.detail(max_points: 4)
assert_operator thin[:times].size, :<=, 4
assert_equal thin[:times].size, thin[:channels][:cht1][:values].size
end
end