221 lines
8.1 KiB
Ruby
221 lines
8.1 KiB
Ruby
require "json"
|
|
require "time"
|
|
require "fileutils"
|
|
require_relative "track_stats"
|
|
require_relative "gnss_sim"
|
|
|
|
module Maptool
|
|
# The trip being driven, recorded (docs: TODO "The trip as plan + log"):
|
|
# 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.
|
|
#
|
|
# 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
|
|
FSYNC_EVERY_S = 5
|
|
LIBRARY_EVERY_S = 300
|
|
ROOT = "Trips".freeze
|
|
|
|
def initialize(dir, library:)
|
|
@dir = dir
|
|
@library = library
|
|
@mutex = Mutex.new
|
|
FileUtils.mkdir_p(dir)
|
|
@trip = resume
|
|
@synced_at = @built_at = 0
|
|
end
|
|
|
|
def active?
|
|
@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 = @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
|
|
end
|
|
|
|
# plan: the trip's route Feature (or nil) and its points, kept in the
|
|
# 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 (#{@trip[:folder]})" if @trip
|
|
|
|
folder = "#{ROOT}/#{[now.strftime('%Y-%m-%d'), name.to_s.strip].reject(&:empty?).join(' ')}"
|
|
@library.create_folder(folder)
|
|
features = []
|
|
if plan
|
|
props = (plan[:properties] || {}).slice(:distance_km, :time_s, :costing).transform_keys(&:to_s)
|
|
features << { "type" => "Feature", "geometry" => JSON.parse(JSON.generate(plan[:geometry])),
|
|
"properties" => props.merge("kind" => "route", "name" => "Plan") }
|
|
end
|
|
stops.select { |s| s[:name] && s[:name] != "My position" }.each do |s|
|
|
features << { "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => s[:lngLat] }, "properties" => { "name" => s[:name] } }
|
|
end
|
|
@library.import_features(features, folder: folder) unless features.empty?
|
|
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
|
|
|
|
# A fix: [lon, lat], altitude (m, or nil), at (epoch seconds).
|
|
def record(lon, lat, alt, at)
|
|
@mutex.synchronize do
|
|
return unless @trip
|
|
|
|
last = @trip[:points].last
|
|
return if last && GnssSim.meters(last, [lon, lat]) < MIN_STEP_M
|
|
|
|
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 built a last time, the journal closed. Returns the folder.
|
|
def stop
|
|
@mutex.synchronize do
|
|
return nil unless @trip
|
|
|
|
build
|
|
journal(end: Time.now.to_i)
|
|
sync
|
|
@file&.close
|
|
@file = nil
|
|
folder = @trip[:folder]
|
|
@trip = nil
|
|
folder
|
|
end
|
|
end
|
|
|
|
# The running trip's journal, else the newest (the trip just ended), read
|
|
# whole: { folder:, started_at:, points:, hand:, joined:, active: } — or nil.
|
|
def recording
|
|
path = @mutex.synchronize do
|
|
@file&.flush
|
|
@trip ? @trip[:path] : Dir[File.join(@dir, "*.ndjson")].max_by { |p| File.basename(p, ".ndjson").to_i }
|
|
end
|
|
return nil unless path
|
|
|
|
out = { points: [], hand: [], joined: [], active: false, path: path }
|
|
File.foreach(path) do |line|
|
|
entry = JSON.parse(line) rescue next
|
|
case entry
|
|
when Array then out[:points] << entry
|
|
when Hash
|
|
out[:folder] ||= entry["trip"]
|
|
out[:started_at] ||= entry["started_at"]
|
|
out[:hand] << entry["cut"] if entry["cut"]
|
|
out[:joined] << entry["join"] if entry["join"]
|
|
end
|
|
end
|
|
out[:active] = @mutex.synchronize { @trip&.dig(:path) == path }
|
|
out
|
|
end
|
|
|
|
# A day cut by hand at `at` (epoch s), or a cut joined (`at`: its day's
|
|
# first point's time): a line in the journal, the trip itself untouched.
|
|
def mark(kind, at)
|
|
raise ArgumentError, "cut or join" unless %i[cut join].include?(kind)
|
|
|
|
path = recording&.dig(:path) or raise ArgumentError, "no trip recorded"
|
|
@mutex.synchronize do
|
|
if @trip && @trip[:path] == path
|
|
journal(kind => at.to_f)
|
|
sync
|
|
else
|
|
File.open(path, "a") { |f| f.puts(JSON.generate(kind => at.to_f)) }
|
|
end
|
|
end
|
|
end
|
|
|
|
private
|
|
|
|
# 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
|
|
end
|
|
|
|
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
|