Add engine monitor data (CGR-30P/CGR-30C) to flight logs

Attach a CGR-30 flight recording when logging a flight or later from the
flight page. The flight page shows engine run time, fuel burned, tach and
engine hours, peak RPM/EGT/CHT/oil/fuel flow, and charts per cylinder.
Unreadable files are rejected; recordings from another tail are flagged.

Also replace the real tail number in test data with N12345.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-05 20:25:18 -05:00
1 parent 86aadfcf6c
commit 6c6e7af8e6
12 files changed
+561 -6

No files matched your search

+41 -3
View File
@@ -1,19 +1,26 @@
class FlightLogsController < ApplicationController class FlightLogsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner!, only: :destroy before_action :require_owner!, only: :destroy
before_action :set_flight_log, only: %i[show 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?
def index def index
@flight_logs = @aircraft.flight_logs.recent_first.includes(:user).with_attached_track_log @flight_logs = @aircraft.flight_logs.recent_first.includes(:user).with_attached_track_log.with_attached_engine_data
@stats = FlightStats.new(@aircraft) @stats = FlightStats.new(@aircraft)
end end
def show def show
@flight_log = @aircraft.flight_logs.find(params[:id])
begin begin
@track = TrackParser.parse_attachment(@flight_log.track_log) @track = TrackParser.parse_attachment(@flight_log.track_log)
rescue TrackParser::Error => e rescue TrackParser::Error => e
@track_error = "Couldn't read track: #{e.message}" @track_error = "Couldn't read track: #{e.message}"
end end
begin
@engine_data = EngineDataParser.parse_attachment(@flight_log.engine_data)
rescue EngineDataParser::Error, ActiveStorage::FileNotFoundError => e
@engine_data_error = "Couldn't read engine data: #{e.message}"
end
@air_trail_connection = @flight_log.user&.air_trail_connection @air_trail_connection = @flight_log.user&.air_trail_connection
@air_trail_sync = @flight_log.air_trail_syncs.first @air_trail_sync = @flight_log.air_trail_syncs.first
end end
@@ -39,6 +46,23 @@ class FlightLogsController < ApplicationController
render :new, status: :conflict render :new, status: :conflict
end end
def attach_engine_data
file = params.dig(:flight_log, :engine_data)
return redirect_to(aircraft_flight_log_path(@aircraft, @flight_log), alert: "Choose an engine data file.") if file.blank?
@flight_log.engine_data = file
if @flight_log.save
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: "Engine data attached."
else
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: @flight_log.errors.full_messages.to_sentence
end
end
def remove_engine_data
@flight_log.engine_data.purge_later
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: "Engine data removed."
end
# Deleting a flight does not roll back hours; correct those with an hours update. # Deleting a flight does not roll back hours; correct those with an hours update.
def destroy def destroy
@aircraft.flight_logs.find(params[:id]).destroy! @aircraft.flight_logs.find(params[:id]).destroy!
@@ -48,11 +72,25 @@ class FlightLogsController < ApplicationController
private private
def set_flight_log
@flight_log = @aircraft.flight_logs.find(params[:id])
end
# Owners, or the pilot who logged the flight.
def manage_engine_data?
owner? || (@flight_log.user_id.present? && @flight_log.user_id == current_user.id)
end
def require_engine_data_access!
return if manage_engine_data?
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: "Only owners or the flight's pilot can do that."
end
def flight_log_params def flight_log_params
params.require(:flight_log).permit( params.require(:flight_log).permit(
:date, :tach_time, :tach_out, :tach_in, :hobbs_time, :hobbs_out, :hobbs_in, :date, :tach_time, :tach_out, :tach_in, :hobbs_time, :hobbs_out, :hobbs_in,
:departure_location, :destination_location, :route, :oil_added, :oil_added_type, :departure_location, :destination_location, :route, :oil_added, :oil_added_type,
:oil_level_after, :fuel_added, :fuel_added_type, :fuel_level_after, :notes, :track_log :oil_level_after, :fuel_added, :fuel_added_type, :fuel_level_after, :notes, :track_log, :engine_data
) )
end end
end end
+22
View File
@@ -0,0 +1,22 @@
module FlightLogsHelper
# Cylinder colors, mid-tone so they read on light and dark backgrounds.
CYLINDER_COLORS = %w[#0ea5e9 #f97316 #22c55e #a855f7 #eab308 #ec4899].freeze
# 519 → "8m 39s", 4000 → "1h 06m"
def run_duration(seconds)
s = seconds.to_i
s >= 3600 ? format("%dh %02dm", s / 3600, s % 3600 / 60) : format("%dm %02ds", s / 60, s % 60)
end
def engine_value(value, unit, precision: 0)
return "—" if value.nil?
"#{number_with_delimiter(number_with_precision(value, precision: precision))} #{unit}"
end
def engine_chart(recording, *keys, ytitle:, colors: nil)
series = recording.chart(*keys)
return if series.empty?
line_chart series, ytitle: ytitle, height: "200px", points: false, curve: false, colors: colors,
legend: series.size > 1 ? "bottom" : false, library: { animation: false }
end
end
+16 -1
View File
@@ -8,11 +8,13 @@ class FlightLog < ApplicationRecord
before_destroy :remember_air_trail_flights, prepend: true before_destroy :remember_air_trail_flights, prepend: true
has_many :air_trail_syncs, dependent: :delete_all has_many :air_trail_syncs, dependent: :delete_all
has_one_attached :track_log has_one_attached :track_log
has_one_attached :engine_data # engine monitor recording (CGR-30P CSV)
validates :date, presence: true validates :date, presence: true
validates :tach_time, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :tach_time, presence: true, numericality: { greater_than_or_equal_to: 0 }
validates :hobbs_time, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true validates :hobbs_time, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
validates_uploads :track_log validates_uploads :track_log, :engine_data
validate :engine_data_readable
before_validation :derive_times before_validation :derive_times
normalizes :departure_location, :destination_location, with: ->(code) { code.strip.upcase.presence } normalizes :departure_location, :destination_location, with: ->(code) { code.strip.upcase.presence }
after_commit :push_to_air_trail, on: %i[create update] after_commit :push_to_air_trail, on: %i[create update]
@@ -26,6 +28,19 @@ class FlightLog < ApplicationRecord
private private
# Reject files the engine data parser can't read, before they're stored.
def engine_data_readable
change = attachment_changes["engine_data"]
io = change.attachable if change.is_a?(ActiveStorage::Attached::Changes::CreateOne)
io = io[:io] if io.is_a?(Hash)
return unless io.respond_to?(:read)
content = io.read
io.rewind
EngineDataParser.new(content, filename: engine_data.filename.to_s).parse
rescue EngineDataParser::Error => e
errors.add(:engine_data, e.message)
end
def push_to_air_trail def push_to_air_trail
AirTrailPushJob.perform_later(id) if user_id && AirTrailConnection.active.exists?(user_id: user_id) AirTrailPushJob.perform_later(id) if user_id && AirTrailConnection.active.exists?(user_id: user_id)
end end
+211
View File
@@ -0,0 +1,211 @@
# Parses an engine monitor's flight data recording into time series plus a
# summary (run time, hours, fuel burned, peak temperatures).
#
# Supported: Electronics International CGR-30P / CGR-30C CSV recordings —
# a metadata block ("Aircraft ID....: N12345", "Local Time: 2025/07/14 08:11:45",
# "Zulu Time.: …"), then a header row "TIME,SEL TANK QTY,RPMLEFT;RPM,…,EGT1;*F,…"
# (name;unit) and one row per sample stamped with local HH:MM:SS, several per
# second. A recording cut off mid-write leaves a partial row; those are skipped.
class EngineDataParser
class Error < StandardError; end
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
CACHE_VERSION = 1 # bump when parsing changes, to re-read cached recordings
# Column name (before ";", whitespace squeezed) → channel. First match wins,
# so "RPM" (the displayed value) beats the per-magneto RPMLEFT/RPMRIGHT.
CHANNELS = {
"RPM" => [ :rpm, "RPM", "RPM" ], "RPMLEFT" => [ :rpm, "RPM", "RPM" ],
"MAP" => [ :map, "Manifold pressure", "inHg" ],
"FLOW" => [ :fuel_flow, "Fuel flow", "gph" ],
"OIL P" => [ :oil_p, "Oil pressure", "psi" ],
"OIL T" => [ :oil_t, "Oil temp", "°F" ],
"FUEL P" => [ :fuel_p, "Fuel pressure", "psi" ],
"VOLTS" => [ :volts, "Volts", "V" ],
"AMPS" => [ :amps, "Amps", "A" ],
"OAT" => [ :oat, "OAT", "°F" ],
"CARB" => [ :carb, "Carb temp", "°F" ],
"TIT" => [ :tit, "TIT", "°F" ],
"FUEL L" => [ :fuel_l, "Fuel left", "gal" ],
"FUEL R" => [ :fuel_r, "Fuel right", "gal" ],
"FLT" => [ :flight_hours, "Flight hours", "hrs" ],
"TACH" => [ :tach, "Tach", "hrs" ],
"ENG" => [ :engine_hours, "Engine hours", "hrs" ]
}.freeze
CYLINDER = /\A(EGT|CHT)(\d{1,2})\z/
Channel = Struct.new(:key, :label, :unit, :values, keyword_init: true)
Recording = Struct.new(:format, :metadata, :times, :channels, keyword_init: true) do
def [](key) = channels[key]&.values
def samples = times.size
def started_at = times.first
def ended_at = times.last
def duration = ended_at - started_at
def egt_keys = channels.keys.grep(/\Aegt\d+\z/)
def cht_keys = channels.keys.grep(/\Acht\d+\z/)
def cylinders = [ egt_keys.size, cht_keys.size ].max
def utc_offset = metadata[:utc_offset].to_i
def local(time) = time && (time + utc_offset).utc # wall clock on the monitor
# Indexes of samples with the engine running (all of them if there's no RPM).
def running
@running ||= (rpm = self[:rpm]) ? rpm.each_index.select { rpm[_1].to_f >= RUNNING_RPM } : times.each_index.to_a
end
def engine_start = running.any? ? times[running.first] : nil
def engine_stop = running.any? ? times[running.last] : nil
def run_time = running.any? ? engine_stop - engine_start : 0
def first(key) = self[key]&.compact&.first
def last(key) = self[key]&.compact&.last
# [value, time] of the extreme while running.
def max(key) = extreme(key, :max_by)
def min(key) = extreme(key, :min_by)
# Hottest cylinder: { value:, cylinder:, at: }.
def hottest(kind)
keys = kind == :egt ? egt_keys : cht_keys
keys.filter_map { |k| (m = max(k)) && { value: m[0], at: m[1], cylinder: k.to_s[/\d+/].to_i } }.max_by { _1[:value] }
end
# Gallons burned, integrating fuel flow (gph) over time.
def fuel_burned
flow = self[:fuel_flow] or return nil
total = 0.0
times.each_cons(2).with_index do |(t0, t1), i|
dt = t1 - t0
next unless dt.positive? && dt <= MAX_GAP_SECONDS && flow[i] && flow[i + 1]
total += (flow[i] + flow[i + 1]) / 2.0 * dt / 3600
end
total
end
# Chartkick series for the given channels, thinned to CHART_POINTS.
def chart(*keys)
step = [ (samples.to_f / CHART_POINTS).ceil, 1 ].max
idx = (0...samples).step(step).to_a
keys.filter_map do |key|
ch = channels[key] or next
{ name: ch.label, data: idx.filter_map { |i| [ times[i], ch.values[i] ] unless ch.values[i].nil? } }
end
end
private
def extreme(key, how)
values = self[key] or return nil
i = running.select { values[_1] }.public_send(how) { values[_1] } or return nil
[ values[i], times[i] ]
end
end
# Parsing an hour of data takes ~0.2s, so cache by blob (blobs are immutable).
def self.parse_attachment(attachment)
return nil unless attachment&.attached?
Rails.cache.fetch([ "engine-data", CACHE_VERSION, attachment.blob.key ], expires_in: 30.days) do
attachment.blob.open { |file| new(file.read, filename: attachment.filename.to_s).parse }
end
end
def initialize(content, filename: nil)
@content = content.to_s.dup.force_encoding("UTF-8").scrub.delete_prefix("")
@filename = filename.to_s
end
def parse
lines = @content.lines.map(&:chomp)
header_at = lines.index { _1.start_with?("TIME,") }
unless header_at && @content[0, 500].match?(/CGR-30|Electronics International/i)
raise Error, "Not a recognized engine monitor file (expected a CGR-30P/CGR-30C .csv recording)"
end
metadata = parse_metadata(lines[0...header_at])
columns = map_columns(lines[header_at].split(","))
width = lines[header_at].count(",") + 1
local_date, utc_offset = clock(metadata)
metadata[:utc_offset] = utc_offset
times = []
values = columns.to_h { |key, _| [ key, [] ] }
previous = nil
lines[(header_at + 1)..].each do |line|
fields = line.split(",", -1)
next unless fields.size == width && (hms = fields[0].strip).match?(/\A\d{1,2}:\d{2}:\d{2}\z/)
local = Time.utc(local_date.year, local_date.month, local_date.day, *hms.split(":").map(&:to_i))
local += 1.day while previous && local < previous - 12.hours # past midnight
previous = local
times << local - utc_offset
columns.each { |key, i| values[key] << number(fields[i]) }
end
raise Error, "No data rows found" if times.size < 2
channels = columns.keys.to_h do |key|
label, unit = describe(key)
[ key, Channel.new(key: key, label: label, unit: unit, values: values[key]) ]
end
channels.reject! { |_, ch| ch.values.all?(&:nil?) }
Recording.new(format: "CGR-30", metadata: metadata, times: spread(times), channels: channels)
end
private
# "Aircraft ID....: N12345" → { aircraft_id: "N12345" }
def parse_metadata(lines)
lines.each_with_object({}) do |line, meta|
key, value = line.split(":", 2)
next unless value
name = key.delete(".").strip.downcase.gsub(/\W+/, "_")
meta[name.to_sym] = value.strip.delete_suffix(",,").strip
end
end
# Local date of the recording and its offset from UTC (Zulu - Local).
def clock(meta)
local = parse_time(meta[:local_time])
zulu = parse_time(meta[:zulu_time])
raise Error, "Recording has no start date (Local Time line missing)" unless local
offset = zulu ? ((local - zulu) / 900).round * 900 : 0 # whole quarter hours
[ local.to_date, offset ]
end
def parse_time(value)
Time.strptime("#{value} UTC", "%Y/%m/%d %H:%M:%S %Z").utc if value.present?
rescue ArgumentError
nil
end
def map_columns(headers)
headers.each_with_index.each_with_object({}) do |(header, i), cols|
name = header.split(";").first.to_s.squeeze(" ").strip.upcase
key = (m = CYLINDER.match(name)) ? :"#{m[1].downcase}#{m[2]}" : CHANNELS.dig(name, 0)
cols[key] ||= i if key
end
end
def describe(key)
if (m = key.to_s.match(/\A(egt|cht)(\d+)\z/))
[ "#{m[1].upcase} #{m[2]}", "°F" ]
else
CHANNELS.values.find { _1[0] == key }.drop(1)
end
end
def number(value)
Float(value.to_s.strip)
rescue ArgumentError
nil
end
# Rows are stamped to the second but logged several times a second; spread
# each run of equal stamps evenly across its second so charts don't step.
def spread(times)
times.chunk_while { _1 == _2 }.flat_map do |run|
run.each_with_index.map { |t, i| t + Rational(i, run.size) }
end
end
end
@@ -0,0 +1,82 @@
<%# Engine monitor recording: summary and charts. Locals: flight_log, recording, error %>
<section class="card max-w-5xl" id="engine-data">
<div class="card-header">
<h2 class="card-title">Engine data</h2>
<% if flight_log.engine_data.attached? %>
<div class="flex items-center gap-2 text-xs">
<%= link_to flight_log.engine_data.filename, rails_blob_path(flight_log.engine_data, disposition: :attachment), class: "link" %>
<% if manage_engine_data? %><%= delete_button "Remove", engine_data_aircraft_flight_log_path(@aircraft, flight_log), confirm: "Remove the engine data file from this flight?" %><% end %>
</div>
<% end %>
</div>
<% if recording %>
<% hours_line = ->(key, places) { (a = recording.first(key)) && (b = recording.last(key)) ? "#{number_with_precision(a, precision: places)} → #{number_with_precision(b, precision: places)} (#{number_with_precision(b - a, precision: places)})" : "—" } %>
<% egt, cht = recording.hottest(:egt), recording.hottest(:cht) %>
<% tail = recording.metadata[:aircraft_id] %>
<% if tail.present? && tail.upcase != @aircraft.tail_number.to_s.upcase %>
<p class="border-b border-slate-100 bg-amber-50 px-4 py-2 text-xs text-amber-800">This recording is from <strong><%= tail %></strong>, not <%= @aircraft.tail_number %>.</p>
<% end %>
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-4">
<dt class="text-slate-500">Recorded</dt>
<dd class="col-span-3"><%= recording.local(recording.started_at).strftime("%Y-%m-%d %H:%M") %>–<%= recording.local(recording.ended_at).strftime("%H:%M") %> monitor time
<span class="text-xs text-slate-500">· <%= recording.format %><%= " flight ##{recording.metadata[:flight_number]}" if recording.metadata[:flight_number] %> · <%= number_with_delimiter(recording.samples) %> samples</span></dd>
<dt class="text-slate-500">Engine run</dt><dd><%= recording.engine_start ? run_duration(recording.run_time) : "Engine not run" %></dd>
<dt class="text-slate-500">Fuel burned</dt><dd><%= engine_value(recording.fuel_burned, "gal", precision: 1) %></dd>
<dt class="text-slate-500">Tach</dt><dd class="tabular-nums"><%= hours_line.(:tach, 2) %></dd>
<dt class="text-slate-500">Engine hrs</dt><dd class="tabular-nums"><%= hours_line.(:engine_hours, 2) %></dd>
<% if (flt = recording.last(:flight_hours)) %><dt class="text-slate-500">Airborne</dt><dd><%= flt.zero? ? "No (ground run)" : "#{number_with_precision(flt, precision: 2)} hrs" %></dd><% end %>
</dl>
<div class="overflow-x-auto border-t border-slate-100">
<table class="table">
<thead><tr><th>Peak (engine running)</th><th class="text-right">Value</th><th class="text-right">At</th></tr></thead>
<tbody>
<% peaks = [
[ "RPM", recording.max(:rpm), "rpm" ],
[ "Manifold pressure", recording.max(:map), "inHg", 1 ],
[ (egt ? "EGT (cyl #{egt[:cylinder]})" : "EGT"), egt && [ egt[:value], egt[:at] ], "°F" ],
[ (cht ? "CHT (cyl #{cht[:cylinder]})" : "CHT"), cht && [ cht[:value], cht[:at] ], "°F" ],
[ "TIT", recording.max(:tit), "°F" ],
[ "Oil temp", recording.max(:oil_t), "°F" ],
[ "Oil pressure", recording.max(:oil_p), "psi" ],
[ "Fuel flow", recording.max(:fuel_flow), "gph", 1 ],
[ "Volts (low)", recording.min(:volts), "V", 1 ]
].select { _2 } %>
<% peaks.each do |label, (value, at), unit, places| %>
<tr><td><%= label %></td><td class="text-right tabular-nums"><%= engine_value(value, unit, precision: places || 0) %></td>
<td class="text-right tabular-nums text-slate-500"><%= recording.local(at).strftime("%H:%M:%S") %></td></tr>
<% end %>
</tbody>
</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 %>
<% end %>
</div>
<% elsif error %>
<p class="card-body text-sm text-amber-700"><%= error %></p>
<% end %>
<% if manage_engine_data? && !flight_log.engine_data.attached? %>
<%= form_with model: flight_log, url: engine_data_aircraft_flight_log_path(@aircraft, flight_log), method: :patch, class: "card-body flex flex-wrap items-end gap-3" do |f| %>
<%= f.field :engine_data, as: :file, label: "Attach engine monitor data", hint: "CGR-30P / CGR-30C flight recording (.csv).", accept: ".csv,text/csv" %>
<%= f.submit "Upload", class: "btn-secondary" %>
<% end %>
<% elsif !flight_log.engine_data.attached? %>
<%= empty_state "No engine data for this flight." %>
<% end %>
</section>
+1
View File
@@ -15,6 +15,7 @@
<td class="whitespace-nowrap"> <td class="whitespace-nowrap">
<%= fl.route_summary.presence || blank %> <%= fl.route_summary.presence || blank %>
<% if fl.track_log.attached? %><span class="ml-1" title="GPS track attached" aria-label="GPS track attached">📍</span><% end %> <% if fl.track_log.attached? %><span class="ml-1" title="GPS track attached" aria-label="GPS track attached">📍</span><% end %>
<% if fl.engine_data.attached? %><span class="ml-1" title="Engine data attached" aria-label="Engine data attached">📈</span><% end %>
</td> </td>
<td class="text-right tabular-nums"><%= fl.tach_time ? hours(fl.tach_time) : blank %></td> <td class="text-right tabular-nums"><%= fl.tach_time ? hours(fl.tach_time) : blank %></td>
<td class="text-right tabular-nums"><%= fl.hobbs_time ? hours(fl.hobbs_time) : blank %></td> <td class="text-right tabular-nums"><%= fl.hobbs_time ? hours(fl.hobbs_time) : blank %></td>
+4 -1
View File
@@ -30,7 +30,10 @@
</fieldset> </fieldset>
<%= f.field :route, as: :textarea, rows: 2 %> <%= f.field :route, as: :textarea, rows: 2 %>
<%= f.field :notes, as: :textarea, rows: 2 %> <%= f.field :notes, as: :textarea, rows: 2 %>
<%= f.field :track_log, as: :file, label: "Track log (GPX/KML/CSV)" %> <div class="grid gap-4 sm:grid-cols-2">
<%= f.field :track_log, as: :file, label: "Track log (GPX/KML/CSV)" %>
<%= f.field :engine_data, as: :file, label: "Engine monitor data", hint: "CGR-30P / CGR-30C flight recording (.csv).", accept: ".csv,text/csv" %>
</div>
<p class="hint">Saving adds the tach time to the aircraft and all in-service components, and records any oil/fuel added.</p> <p class="hint">Saving adds the tach time to the aircraft and all in-service components, and records any oil/fuel added.</p>
<div class="flex gap-2"><%= f.submit "Log Flight" %><%= link_to "Cancel", aircraft_flight_logs_path(@aircraft), class: "btn-secondary" %></div> <div class="flex gap-2"><%= f.submit "Log Flight" %><%= link_to "Cancel", aircraft_flight_logs_path(@aircraft), class: "btn-secondary" %></div>
<% end %> <% end %>
+3
View File
@@ -1,4 +1,5 @@
<%= render "shared/aircraft_header", aircraft: @aircraft %> <%= render "shared/aircraft_header", aircraft: @aircraft %>
<div class="space-y-6">
<section class="card max-w-3xl"> <section class="card max-w-3xl">
<div class="card-header"><h2 class="card-title">Flight on <%= fmt_date(@flight_log.date) %></h2> <div class="card-header"><h2 class="card-title">Flight on <%= fmt_date(@flight_log.date) %></h2>
<% if owner? %><%= delete_button "Delete", aircraft_flight_log_path(@aircraft, @flight_log), confirm: "Delete this flight log? Aircraft and component hours will NOT be rolled back." %><% end %></div> <% if owner? %><%= delete_button "Delete", aircraft_flight_log_path(@aircraft, @flight_log), confirm: "Delete this flight log? Aircraft and component hours will NOT be rolled back." %><% end %></div>
@@ -23,3 +24,5 @@
</dl> </dl>
<% if @flight_log.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @flight_log.notes %></div><% end %> <% if @flight_log.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @flight_log.notes %></div><% end %>
</section> </section>
<%= render "engine_data", flight_log: @flight_log, recording: @engine_data, error: @engine_data_error %>
</div>
+6 -1
View File
@@ -24,7 +24,12 @@ Rails.application.routes.draw do
end end
end end
resources :notes, except: :show resources :notes, except: :show
resources :flight_logs, only: %i[index new create show destroy] resources :flight_logs, only: %i[index new create show destroy] do
member do
patch :engine_data, action: :attach_engine_data
delete :engine_data, action: :remove_engine_data
end
end
resource :air_trail_export, path: "airtrail_export", only: %i[new create] resource :air_trail_export, path: "airtrail_export", only: %i[new create]
resource :airport_codes, only: %i[show update] resource :airport_codes, only: %i[show update]
resource :flight_import, only: %i[new create show] do resource :flight_import, only: %i[new create show] do
+26
View File
@@ -0,0 +1,26 @@
Electronics International Inc
CGR-30P Flight Data Recording
Aircraft ID....: N12345
Unit ID........: 10000000
EDC Models.....: P-4-6-H,,
SW Version.....: 1.2
Tracking Number: 1
Local Time: 2025/07/14 08:11:45
Zulu Time.: 2025/07/14 12:11:45
Flight Number: 144
Engine Hours.: 436.90 hrs
Tach Time....: 7149.77 hrs
Data Logging Interval: 0.3 sec
TIME,SEL TANK QTY,RPMLEFT;RPM,RPMRIGHT;RPM,RPM;***,TEMP COMP;*F,VOLTS;V,VOLTS ANN;V,AMPS;A,FLOW;GPH,EGT1;*F,EGT2;*F,EGT3;*F,EGT4;*F,EGT:;***,EGT-D:;***,EGT-H:;***,CHT1;*F,CHT2;*F,CHT3;*F,CHT4;*F,CHT:;***,CHT-D:;***,CHT-H:;***,FUEL L;GAL,FUEL L ANN;GAL,FUEL R;GAL,FUEL R ANN;GAL,OIL P;PSI,OIL T;*F,OIL T ANN;*F,FLT;HRS,TACH;HRS,ENG;HRS,EST TOTAL;GAL,EST F;GAL,RANGE;NM,TO DEST;NM,AT DEST;NM,REMAIN;GAL,TO DEST;GAL,AT DEST;GAL,TO EMPTY;H:M,TO DEST;H:M,AT DEST;H:M,DISTANCE;NM,TIME;H:M,QUANTITY;GAL,FLIGHT;GAL,SINCE ADD;GAL,ECONOMY;MPG,ENGINE;GPH,SWITCH IN;H:M,SWTCH ANN; ,FUEL ANN; ,GPS Altitude,Gnd Speed,Wpt,Dist to Wpt,Dist to Dest,Latitude,Longitude
08:11:45,TOTAL : 14.79,0,0,0,58,12.5,12.5,-3.6,0.0,58,57,58,57,51,1,51,51,51,51,51,43,0,43,2.8,2.8,0.0,0.0,0,51,51, 0.00,7149.77,436.90,14.8,14.8,0.0,0.0,0.0,14.8,0.0,0.0, 99:59, 0:00, 0:00,0.0, 99:59,0.0,0.0,7.5,0.0,0.0,359940.0,100.0,14.8, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
08:11:46,TOTAL : 14.79,0,0,0,65,12.5,12.5,-4.0,0.0,65,64,65,64,58,1,58,58,58,58,58,51,0,51,3.1,3.1,1.5,1.5,0,58,58, 0.00,7149.77,436.90,14.8,14.8,0.0,0.0,0.0,14.8,0.0,0.0, 99:59, 0:00, 0:00,0.0, 99:59,0.0,0.0,7.5,0.0,0.0,359940.0,100.0,14.8, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
08:12:17,TOTAL : 14.79,710,720,720,65,11.3,11.3,-7.7,0.7,65,64,67,64,65,1,65,65,65,65,65,65,0,65,9.9,9.9,4.8,4.8,0,65,65, 0.00,7149.77,436.90,14.8,14.8,0.0,0.0,0.0,14.8,0.0,0.0, 99:59, 0:00, 0:00,0.0, 99:59,0.0,0.0,7.5,0.0,0.7,59.0,100.0,14.8, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
08:12:18,TOTAL : 14.79,970,970,970,65,11.7,11.7,-5.8,2.0,68,64,70,64,67,3,67,65,65,65,65,65,0,65,9.9,9.9,4.9,4.9,0,65,65, 0.00,7149.77,436.90,14.8,14.8,0.0,0.0,0.0,14.8,0.0,0.0, 21:51, 0:00, 0:00,0.0, 21:51,0.0,0.0,7.5,0.0,2.0,59.0,100.0,14.8, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
08:12:18,TOTAL : 14.79,850,850,850,65,12.0,12.0,-3.4,2.4,71,68,70,65,70,6,70,65,65,65,65,65,0,65,9.9,9.9,4.9,4.9,0,65,65, 0.00,7149.77,436.90,14.8,14.8,0.0,0.0,0.0,14.8,0.0,0.0, 7:17, 0:00, 0:00,0.0, 7:17,0.0,0.0,7.5,0.0,2.4,59.0,100.0,14.8, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
08:17:38,TOTAL : 14.72,2450,2490,2490,66,14.6,14.6,8.8,6.8,1059,1165,1180,1226,1217,165,1217,187,198,174,201,201,27,201,9.5,9.5,5.0,5.0,42,78,78, 0.00,7149.78,436.97,14.7,14.7,0.0,0.0,0.0,14.7,0.0,0.0, 2:10, 0:00, 0:00,0.0, 2:10,0.0,0.0,7.6,0.0,6.8,59.0,100.0,14.7, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
08:17:41,TOTAL : 14.71,2530,2530,2530,66,14.6,14.6,7.9,7.8,1116,1212,1222,1261,1257,148,1257,189,197,174,204,203,29,203,9.4,9.4,5.0,5.0,42,78,78, 0.00,7149.78,436.97,14.7,14.7,0.0,0.0,0.0,14.7,0.0,0.0, 1:58, 0:00, 0:00,0.0, 1:58,0.0,0.0,7.6,0.0,7.8,59.0,100.0,14.7, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
08:20:56,TOTAL : 14.59,330,330,330,66,13.2,13.2,-4.0,0.3,830,898,816,850,901,82,901,237,234,232,265,265,33,265,10.1,10.1,3.7,3.7,31,94,94, 0.00,7149.81,437.02,14.6,14.6,0.0,0.0,0.0,14.6,0.0,0.0, 43:08, 0:00, 0:00,0.0, 43:08,0.0,0.0,7.7,0.0,0.3,59.0,100.0,14.6, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
08:20:57,TOTAL : 14.59,0,0,0,66,13.2,13.2,-4.5,0.0,820,883,802,835,888,82,888,237,234,234,265,265,32,265,9.9,9.9,3.8,3.8,25,94,94, 0.00,7149.81,437.03,14.6,14.6,0.0,0.0,0.0,14.6,0.0,0.0, 43:08, 0:00, 0:00,0.0, 43:08,0.0,0.0,7.7,0.0,0.0,359940.0,100.0,14.6, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
4.6, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
08:21:04,TOTAL : 14.59,0,0,0,66,13.1,13.1,-4.0,0.0,761,811,736,760,813,74,813,241,238,242,270,269,32,269,9.4,9.4,4.3,4.3,6,95,95, 0.00,7149.81,437.03,14.6,14.6,0.0,0.0,0.0,14.6,0.0,0.0, 99:59, 0:00, 0:00,0.0, 99:59,0.0,0.0,7.7,0.0,0.0,359940.0,100.0,14.6, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
1 Electronics International Inc
2 CGR-30P Flight Data Recording
3 Aircraft ID....: N12345
4 Unit ID........: 10000000
5 EDC Models.....: P-4-6-H,,
6 SW Version.....: 1.2
7 Tracking Number: 1
8 Local Time: 2025/07/14 08:11:45
9 Zulu Time.: 2025/07/14 12:11:45
10 Flight Number: 144
11 Engine Hours.: 436.90 hrs
12 Tach Time....: 7149.77 hrs
13 Data Logging Interval: 0.3 sec
14 TIME,SEL TANK QTY,RPMLEFT;RPM,RPMRIGHT;RPM,RPM;***,TEMP COMP;*F,VOLTS;V,VOLTS ANN;V,AMPS;A,FLOW;GPH,EGT1;*F,EGT2;*F,EGT3;*F,EGT4;*F,EGT:;***,EGT-D:;***,EGT-H:;***,CHT1;*F,CHT2;*F,CHT3;*F,CHT4;*F,CHT:;***,CHT-D:;***,CHT-H:;***,FUEL L;GAL,FUEL L ANN;GAL,FUEL R;GAL,FUEL R ANN;GAL,OIL P;PSI,OIL T;*F,OIL T ANN;*F,FLT;HRS,TACH;HRS,ENG;HRS,EST TOTAL;GAL,EST F;GAL,RANGE;NM,TO DEST;NM,AT DEST;NM,REMAIN;GAL,TO DEST;GAL,AT DEST;GAL,TO EMPTY;H:M,TO DEST;H:M,AT DEST;H:M,DISTANCE;NM,TIME;H:M,QUANTITY;GAL,FLIGHT;GAL,SINCE ADD;GAL,ECONOMY;MPG,ENGINE;GPH,SWITCH IN;H:M,SWTCH ANN; ,FUEL ANN; ,GPS Altitude,Gnd Speed,Wpt,Dist to Wpt,Dist to Dest,Latitude,Longitude
15 08:11:45,TOTAL : 14.79,0,0,0,58,12.5,12.5,-3.6,0.0,58,57,58,57,51,1,51,51,51,51,51,43,0,43,2.8,2.8,0.0,0.0,0,51,51, 0.00,7149.77,436.90,14.8,14.8,0.0,0.0,0.0,14.8,0.0,0.0, 99:59, 0:00, 0:00,0.0, 99:59,0.0,0.0,7.5,0.0,0.0,359940.0,100.0,14.8, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
16 08:11:46,TOTAL : 14.79,0,0,0,65,12.5,12.5,-4.0,0.0,65,64,65,64,58,1,58,58,58,58,58,51,0,51,3.1,3.1,1.5,1.5,0,58,58, 0.00,7149.77,436.90,14.8,14.8,0.0,0.0,0.0,14.8,0.0,0.0, 99:59, 0:00, 0:00,0.0, 99:59,0.0,0.0,7.5,0.0,0.0,359940.0,100.0,14.8, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
17 08:12:17,TOTAL : 14.79,710,720,720,65,11.3,11.3,-7.7,0.7,65,64,67,64,65,1,65,65,65,65,65,65,0,65,9.9,9.9,4.8,4.8,0,65,65, 0.00,7149.77,436.90,14.8,14.8,0.0,0.0,0.0,14.8,0.0,0.0, 99:59, 0:00, 0:00,0.0, 99:59,0.0,0.0,7.5,0.0,0.7,59.0,100.0,14.8, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
18 08:12:18,TOTAL : 14.79,970,970,970,65,11.7,11.7,-5.8,2.0,68,64,70,64,67,3,67,65,65,65,65,65,0,65,9.9,9.9,4.9,4.9,0,65,65, 0.00,7149.77,436.90,14.8,14.8,0.0,0.0,0.0,14.8,0.0,0.0, 21:51, 0:00, 0:00,0.0, 21:51,0.0,0.0,7.5,0.0,2.0,59.0,100.0,14.8, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
19 08:12:18,TOTAL : 14.79,850,850,850,65,12.0,12.0,-3.4,2.4,71,68,70,65,70,6,70,65,65,65,65,65,0,65,9.9,9.9,4.9,4.9,0,65,65, 0.00,7149.77,436.90,14.8,14.8,0.0,0.0,0.0,14.8,0.0,0.0, 7:17, 0:00, 0:00,0.0, 7:17,0.0,0.0,7.5,0.0,2.4,59.0,100.0,14.8, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
20 08:17:38,TOTAL : 14.72,2450,2490,2490,66,14.6,14.6,8.8,6.8,1059,1165,1180,1226,1217,165,1217,187,198,174,201,201,27,201,9.5,9.5,5.0,5.0,42,78,78, 0.00,7149.78,436.97,14.7,14.7,0.0,0.0,0.0,14.7,0.0,0.0, 2:10, 0:00, 0:00,0.0, 2:10,0.0,0.0,7.6,0.0,6.8,59.0,100.0,14.7, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
21 08:17:41,TOTAL : 14.71,2530,2530,2530,66,14.6,14.6,7.9,7.8,1116,1212,1222,1261,1257,148,1257,189,197,174,204,203,29,203,9.4,9.4,5.0,5.0,42,78,78, 0.00,7149.78,436.97,14.7,14.7,0.0,0.0,0.0,14.7,0.0,0.0, 1:58, 0:00, 0:00,0.0, 1:58,0.0,0.0,7.6,0.0,7.8,59.0,100.0,14.7, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
22 08:20:56,TOTAL : 14.59,330,330,330,66,13.2,13.2,-4.0,0.3,830,898,816,850,901,82,901,237,234,232,265,265,33,265,10.1,10.1,3.7,3.7,31,94,94, 0.00,7149.81,437.02,14.6,14.6,0.0,0.0,0.0,14.6,0.0,0.0, 43:08, 0:00, 0:00,0.0, 43:08,0.0,0.0,7.7,0.0,0.3,59.0,100.0,14.6, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
23 08:20:57,TOTAL : 14.59,0,0,0,66,13.2,13.2,-4.5,0.0,820,883,802,835,888,82,888,237,234,234,265,265,32,265,9.9,9.9,3.8,3.8,25,94,94, 0.00,7149.81,437.03,14.6,14.6,0.0,0.0,0.0,14.6,0.0,0.0, 43:08, 0:00, 0:00,0.0, 43:08,0.0,0.0,7.7,0.0,0.0,359940.0,100.0,14.6, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
24 4.6, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
25 08:21:04,TOTAL : 14.59,0,0,0,66,13.1,13.1,-4.0,0.0,761,811,736,760,813,74,813,241,238,242,270,269,32,269,9.4,9.4,4.3,4.3,6,95,95, 0.00,7149.81,437.03,14.6,14.6,0.0,0.0,0.0,14.6,0.0,0.0, 99:59, 0:00, 0:00,0.0, 99:59,0.0,0.0,7.7,0.0,0.0,359940.0,100.0,14.6, 0, 0, , 0.0, 0.0, 00 0.00, 000 0.00
+71
View File
@@ -0,0 +1,71 @@
require "test_helper"
class EngineDataFlowTest < ActionDispatch::IntegrationTest
setup do
@owner = create_user
@pilot = create_user
@other_pilot = create_user
@aircraft = create_aircraft(owner: @owner, pilot: @pilot, tail_number: "N12345", tach_time: 7149.7)
@aircraft.roles.create!(user: @other_pilot, role: "pilot")
end
def upload(name = "cgr30p.csv") = fixture_file_upload("engine_data/#{name}", "text/csv")
test "pilot logs a flight with engine data and sees the summary and charts" do
sign_in @pilot
post aircraft_flight_logs_path(@aircraft), params: { flight_log: { date: "2025-07-14", tach_out: 7149.7, tach_in: 7149.8, engine_data: upload } }
flight = @aircraft.flight_logs.last
assert flight.engine_data.attached?
get aircraft_flight_logs_path(@aircraft)
assert_includes response.body, "Engine data attached"
get aircraft_flight_log_path(@aircraft, flight)
assert_response :success
assert_includes response.body, "8m 39s"
assert_includes response.body, "7149.77 → 7149.81 (0.04)"
assert_includes response.body, "EGT (cyl 4)"
assert_includes response.body, "No (ground run)"
assert_includes response.body, "Chartkick"
refute_includes response.body, "This recording is from"
end
test "an unreadable file is rejected when logging" do
sign_in @pilot
post aircraft_flight_logs_path(@aircraft), params: { flight_log: { date: "2025-07-14", tach_time: 0.1,
engine_data: fixture_file_upload("flights.csv", "text/csv") } }
assert_response :unprocessable_entity
assert_includes response.body, "Not a recognized engine monitor file"
assert_equal 0, @aircraft.flight_logs.count
end
test "attach to and remove from an existing flight; only owners or the flight's pilot" do
flight = @aircraft.flight_logs.create!(date: Date.current, tach_time: 0.1, user: @pilot)
sign_in @other_pilot
patch engine_data_aircraft_flight_log_path(@aircraft, flight), params: { flight_log: { engine_data: upload } }
assert_redirected_to aircraft_flight_log_path(@aircraft, flight)
refute flight.reload.engine_data.attached?
get aircraft_flight_log_path(@aircraft, flight)
refute_includes response.body, "Attach engine monitor data"
sign_in @pilot
get aircraft_flight_log_path(@aircraft, flight)
assert_includes response.body, "Attach engine monitor data"
patch engine_data_aircraft_flight_log_path(@aircraft, flight), params: { flight_log: { engine_data: upload } }
assert flight.reload.engine_data.attached?
sign_in @owner
delete engine_data_aircraft_flight_log_path(@aircraft, flight)
perform_enqueued_jobs
refute flight.reload.engine_data.attached?
end
test "warns when the recording is from another aircraft" do
@aircraft.update!(tail_number: "N54321")
flight = @aircraft.flight_logs.create!(date: Date.current, tach_time: 0.1, engine_data: upload)
sign_in @owner
get aircraft_flight_log_path(@aircraft, flight)
assert_includes response.body, "This recording is from <strong>N12345</strong>"
end
end
+78
View File
@@ -0,0 +1,78 @@
require "test_helper"
class EngineDataParserTest < ActiveSupport::TestCase
def fixture(name) = Rails.root.join("test/fixtures/files/engine_data", name).read
def recording = @recording ||= EngineDataParser.new(fixture("cgr30p.csv"), filename: "Flt0144.csv").parse
test "reads CGR-30P metadata and converts local stamps to UTC" do
assert_equal "N12345", recording.metadata[:aircraft_id]
assert_equal "144", recording.metadata[:flight_number]
assert_equal(-4.hours.to_i, recording.utc_offset)
assert_equal Time.utc(2025, 7, 14, 12, 11, 45), recording.started_at
assert_equal Time.utc(2025, 7, 14, 8, 11, 45), recording.local(recording.started_at)
end
test "skips the partial row and maps channels by column name" do
assert_equal 10, recording.samples
assert_equal 4, recording.cylinders
assert_equal %i[egt1 egt2 egt3 egt4], recording.egt_keys
assert_equal 2530.0, recording.max(:rpm)[0] # the "RPM" column, not RPMLEFT
refute recording.channels.key?(:map) # not on this unit
end
test "spreads samples within a second" do
second_18 = recording.times.select { _1.to_i == Time.utc(2025, 7, 14, 12, 12, 18).to_i }
assert_equal 2, second_18.size
assert_in_delta 0.5, second_18.last - second_18.first, 0.001
end
test "summary: engine run, hours, peaks" do
assert_equal Time.utc(2025, 7, 14, 12, 12, 17), recording.engine_start
assert_equal 519, recording.run_time.to_i # 08:12:17 → 08:20:56
assert_equal [ 7149.77, 7149.81 ], [ recording.first(:tach), recording.last(:tach) ]
assert_equal [ 436.9, 437.03 ], [ recording.first(:engine_hours), recording.last(:engine_hours) ]
assert_equal 0.0, recording.last(:flight_hours)
assert_equal({ value: 1261.0, cylinder: 4, at: Time.utc(2025, 7, 14, 12, 17, 41) }, recording.hottest(:egt))
assert_equal 265.0, recording.hottest(:cht)[:value]
# CHT after shutdown (269 at 08:21:04) doesn't count as a running peak
assert_operator recording.fuel_burned, :>, 0
end
test "integrates fuel flow, not across gaps" do
r = EngineDataParser.new(<<~CSV).parse
CGR-30P Flight Data Recording
Local Time: 2025/07/14 08:00:00
Zulu Time.: 2025/07/14 12:00:00
TIME,RPM;***,FLOW;GPH
08:00:00,2400,10.0
08:00:01,2400,10.0
08:00:02,2400,10.0
08:05:00,2400,10.0
CSV
assert_in_delta 10.0 * 2 / 3600, r.fuel_burned, 1e-9
end
test "rolls past midnight" do
r = EngineDataParser.new(<<~CSV).parse
CGR-30P Flight Data Recording
Local Time: 2025/07/14 23:59:59
TIME,RPM;***
23:59:59,2400
00:00:00,2400
CSV
assert_equal Time.utc(2025, 7, 15), r.ended_at
end
test "chart series are thinned and skip blanks" do
series = recording.chart(:cht1, :rpm, :nope)
assert_equal [ "CHT 1", "RPM" ], series.map { _1[:name] }
assert_equal [ recording.started_at, 51.0 ], series.first[:data].first
end
test "rejects other files" do
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
end