Trip log crash-safe like a FIT: an append-only journal per trip (data/trip_log/<started>.ndjson, fsynced every 5 s, a torn last line skipped and the next one on a line of its own), a restart picks the running trip up from it into the same track, no state file to corrupt; the library's track built from it every 5 min and at the end. Drive mode: a pinned side panel's room goes back to the map
This commit is contained in:
1 parent
0c809b3e2b
commit
bd689faa93
5 files changed
+154
-62
No files matched your search
+104
-49
@@ -1,5 +1,6 @@
|
||||
require "json"
|
||||
require "time"
|
||||
require "fileutils"
|
||||
require_relative "track_stats"
|
||||
require_relative "gnss_sim"
|
||||
|
||||
@@ -8,37 +9,43 @@ module Maptool
|
||||
# a trip is a library folder, Trips/<date> <name>. Start makes it — with
|
||||
# the planned route and its named stops in it — and from then on every
|
||||
# GNSS fix (App.gnss_update) that moved MIN_STEP_M goes into the car's
|
||||
# track there, written into the library every FLUSH_EVERY_S (a power cut
|
||||
# loses that much at most) and at the end. A walk away from the car comes
|
||||
# from another device's track put into the same folder (a FIT, LiveTrack).
|
||||
# track there.
|
||||
#
|
||||
# Crash-safe like a FIT file, by being append-only: each point is a line
|
||||
# appended to the trip's journal (<dir>/<started_at>.ndjson), fsynced
|
||||
# every FSYNC_EVERY_S — a power cut loses those few seconds at most, a
|
||||
# torn last line is skipped. The journal's first line says which trip it
|
||||
# is, a line names the library track once made, the last one ends it; so
|
||||
# a restart (or a lost state file) picks the running trip up again from
|
||||
# the newest journal with no end. The library's track is built from it
|
||||
# every LIBRARY_EVERY_S and at the end (each build rewrites it — the
|
||||
# journal is what's kept per point).
|
||||
class TripLog
|
||||
MIN_STEP_M = 10
|
||||
FLUSH_EVERY_S = 60
|
||||
FSYNC_EVERY_S = 5
|
||||
LIBRARY_EVERY_S = 300
|
||||
ROOT = "Trips".freeze
|
||||
|
||||
def initialize(path, library:)
|
||||
@path = path
|
||||
def initialize(dir, library:)
|
||||
@dir = dir
|
||||
@library = library
|
||||
@mutex = Mutex.new
|
||||
@state = begin
|
||||
JSON.parse(File.read(path), symbolize_names: true)
|
||||
rescue Errno::ENOENT, JSON::ParserError
|
||||
{}
|
||||
end
|
||||
@flushed_at = 0
|
||||
FileUtils.mkdir_p(dir)
|
||||
@trip = resume
|
||||
@synced_at = @built_at = 0
|
||||
end
|
||||
|
||||
def active?
|
||||
@mutex.synchronize { !!@state[:folder] }
|
||||
@mutex.synchronize { !!@trip }
|
||||
end
|
||||
|
||||
# { active:, folder:, started_at:, points:, distance_m: } — coordinates
|
||||
# from index `since` on with `since:` (the map draws the line as it grows).
|
||||
def status(since: nil)
|
||||
@mutex.synchronize do
|
||||
points = @state[:points] || []
|
||||
result = { active: !!@state[:folder], folder: @state[:folder], started_at: @state[:started_at], points: points.size,
|
||||
distance_m: TrackStats.compute(points.map { |p| p.first(3) })["distance_meters"] }
|
||||
points = @trip ? @trip[:points] : []
|
||||
result = { active: !!@trip, folder: @trip&.dig(:folder), started_at: @trip&.dig(:started_at), points: points.size,
|
||||
distance_m: TrackStats.compute(points.map { |p| p.first(2) })["distance_meters"] }
|
||||
result[:coordinates] = points[since.to_i..].to_a.map { |p| p.first(2) } if since
|
||||
result
|
||||
end
|
||||
@@ -48,7 +55,7 @@ module Maptool
|
||||
# folder as a route and points. Returns the folder.
|
||||
def start(name, plan: nil, stops: [], now: Time.now)
|
||||
@mutex.synchronize do
|
||||
raise ArgumentError, "a trip is already running (#{@state[:folder]})" if @state[:folder]
|
||||
raise ArgumentError, "a trip is already running (#{@trip[:folder]})" if @trip
|
||||
|
||||
folder = "#{ROOT}/#{[now.strftime('%Y-%m-%d'), name.to_s.strip].reject(&:empty?).join(' ')}"
|
||||
@library.create_folder(folder)
|
||||
@@ -62,8 +69,11 @@ module Maptool
|
||||
features << { "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => s[:lngLat] }, "properties" => { "name" => s[:name] } }
|
||||
end
|
||||
@library.import_features(features, folder: folder) unless features.empty?
|
||||
@state = { folder: folder, started_at: now.to_i, points: [], item: nil }
|
||||
save
|
||||
started = now.to_i
|
||||
@trip = { folder: folder, started_at: started, points: [], item: nil, path: File.join(@dir, "#{started}.ndjson") }
|
||||
journal(trip: folder, started_at: started)
|
||||
sync
|
||||
File.open(@dir, &:fsync) # the new journal's name on disk too
|
||||
folder
|
||||
end
|
||||
end
|
||||
@@ -71,54 +81,99 @@ module Maptool
|
||||
# A fix: [lon, lat], altitude (m, or nil), at (epoch seconds).
|
||||
def record(lon, lat, alt, at)
|
||||
@mutex.synchronize do
|
||||
return unless @state[:folder]
|
||||
return unless @trip
|
||||
|
||||
last = @state[:points].last
|
||||
last = @trip[:points].last
|
||||
return if last && GnssSim.meters(last, [lon, lat]) < MIN_STEP_M
|
||||
|
||||
@state[:points] << [lon, lat, alt, at.to_f.round(1)]
|
||||
flush if at.to_f - @flushed_at >= FLUSH_EVERY_S
|
||||
point = [lon, lat, alt, at.to_f.round(1)]
|
||||
@trip[:points] << point
|
||||
journal(point)
|
||||
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||||
if now - @synced_at >= FSYNC_EVERY_S
|
||||
sync
|
||||
@synced_at = now
|
||||
end
|
||||
if now - @built_at >= LIBRARY_EVERY_S
|
||||
build
|
||||
@built_at = now
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Ends it: the track written a last time. Returns the folder.
|
||||
# Ends it: the track built a last time, the journal closed. Returns the folder.
|
||||
def stop
|
||||
@mutex.synchronize do
|
||||
folder = @state[:folder] or return nil
|
||||
flush
|
||||
@state = {}
|
||||
save
|
||||
return nil unless @trip
|
||||
|
||||
build
|
||||
journal(end: Time.now.to_i)
|
||||
sync
|
||||
@file&.close
|
||||
@file = nil
|
||||
folder = @trip[:folder]
|
||||
@trip = nil
|
||||
folder
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# The car's track into the library (made on the first flush, replaced
|
||||
# after), the state file with it.
|
||||
def flush
|
||||
points = @state[:points]
|
||||
if points.size >= 2
|
||||
coordinates = points.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] }
|
||||
times = points.map { |p| Time.at(p[3]) }
|
||||
name = "Car #{Time.at(@state[:started_at]).strftime('%Y-%m-%d %H:%M')}"
|
||||
feature = { "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => coordinates },
|
||||
"properties" => { "kind" => "track", "name" => name, "activity_type" => "driving" }
|
||||
.merge(TrackStats.compute(coordinates, times: times))
|
||||
.merge("profile" => TrackStats.build_profile(coordinates, times: times)) }
|
||||
if @state[:item]
|
||||
@library.update_feature(@state[:item], @state[:item].delete_prefix("item:"), feature)
|
||||
else
|
||||
@state[:item] = @library.import_features([feature], folder: @state[:folder]).find { |key| key.start_with?("item:") }
|
||||
# The newest journal with no end: the trip still running.
|
||||
def resume
|
||||
Dir[File.join(@dir, "*.ndjson")].max_by { |path| File.basename(path, ".ndjson").to_i }&.then do |path|
|
||||
trip = nil
|
||||
File.foreach(path) do |line|
|
||||
entry = JSON.parse(line) rescue next # a line torn by a power cut
|
||||
case entry
|
||||
when Array then trip&.dig(:points)&.push(entry)
|
||||
when Hash
|
||||
trip = { folder: entry["trip"], started_at: entry["started_at"], points: [], item: nil, path: path } if entry["trip"]
|
||||
trip[:item] = entry["item"] if trip && entry["item"]
|
||||
trip = nil if entry["end"]
|
||||
end
|
||||
end
|
||||
trip
|
||||
end
|
||||
@flushed_at = points.last ? points.last[3] : 0
|
||||
save
|
||||
end
|
||||
|
||||
def save
|
||||
File.write("#{@path}.tmp", JSON.generate(@state))
|
||||
File.rename("#{@path}.tmp", @path)
|
||||
def journal(entry)
|
||||
unless @file
|
||||
@file = File.open(@trip[:path], "a+")
|
||||
# a line torn by a power cut: the next one starts on a line of its own
|
||||
if @file.size.positive?
|
||||
@file.seek(-1, IO::SEEK_END)
|
||||
@file.write("\n") unless @file.read(1) == "\n"
|
||||
end
|
||||
end
|
||||
@file.puts(JSON.generate(entry))
|
||||
end
|
||||
|
||||
def sync
|
||||
@file&.flush
|
||||
@file&.fsync
|
||||
end
|
||||
|
||||
# The car's track into the library from the points so far (made on the
|
||||
# first build, its key journaled, replaced after).
|
||||
def build
|
||||
points = @trip[:points]
|
||||
return if points.size < 2
|
||||
|
||||
coordinates = points.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] }
|
||||
times = points.map { |p| Time.at(p[3]) }
|
||||
name = "Car #{Time.at(@trip[:started_at]).strftime('%Y-%m-%d %H:%M')}"
|
||||
feature = { "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => coordinates },
|
||||
"properties" => { "kind" => "track", "name" => name, "activity_type" => "driving" }
|
||||
.merge(TrackStats.compute(coordinates, times: times))
|
||||
.merge("profile" => TrackStats.build_profile(coordinates, times: times)) }
|
||||
if @trip[:item]
|
||||
@library.update_feature(@trip[:item], @trip[:item].delete_prefix("item:"), feature)
|
||||
else
|
||||
@trip[:item] = @library.import_features([feature], folder: @trip[:folder]).find { |key| key.start_with?("item:") }
|
||||
journal(item: @trip[:item])
|
||||
sync
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user