Files
maptool/lib/maptool/trip.rb
T
2026-12-03 23:34:25 +01:00

215 lines
10 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
require "json"
require_relative "routing"
module Maptool
# The trip being driven, one for every screen of this server (the cab's
# display, the tablet in the back, the phone): its points, vehicle and
# avoids, and the route through them. Any screen edits it (PUT
# /api/trip), the server routes it again and bumps the version; every
# screen polls GET /api/trip and swaps the route in without touching its
# camera. Kept in data/trip.json across restarts.
class TripStore
EMPTY = { version: 0, points: [], vehicle: nil, avoid: {}, editing: nil, route: nil, error: nil }.freeze
# The itinerary: the trip's name, when it starts (local "YYYY-MM-DDTHH:MM")
# and when a day after a night stop starts ("HH:MM"); per point a night
# stop (the day ends there), the stay in minutes, a note, its type (an
# NPS pictogram's name, public/js/route.js STOP_TYPES) and, on a day's
# first point, the day's note; park: where the car stays ({ lngLat:,
# name: }, the route goes there, the place is a walk away); on a day's
# first point avoid: the day's own (AVOIDS), else the trip's; cost / paid:
# € planned there and paid; the trip's own note, budget and fuel price.
MAX_STAY_MIN = 7 * 24 * 60
AVOIDS = %i[tolls highways ferries unpaved].freeze
DATE_TIME = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}\z/
TIME = /\A\d{2}:\d{2}\z/
def self.point(p)
stay = p[:stay].nil? || p[:stay].to_s.empty? ? nil : Integer(p[:stay], exception: false)
raise ArgumentError, "stay must be 0–#{MAX_STAY_MIN} minutes" if stay && !(0..MAX_STAY_MIN).cover?(stay)
note, day_note = [p[:note], p[:day_note]].map { |n| n.to_s.strip[0, 500] }
type = p[:type].to_s
raise ArgumentError, "type must be an icon name" unless type.empty? || type.match?(/\A[a-z0-9-]{1,60}\z/)
cost, paid = [p[:cost], p[:paid]].map { |v| money(v) }
avoid = (p[:avoid].to_h.slice(*AVOIDS).to_h { |k, v| [k, !!v] } if p[:avoid].is_a?(Hash))
park = ({ lngLat: p[:park].fetch(:lngLat).map { |v| Float(v) }, name: p[:park][:name]&.to_s&.strip&.[](0, 120) }.compact if p[:park].is_a?(Hash))
{ lngLat: p.fetch(:lngLat).map { |v| Float(v) }, name: p[:name], nav: !!p[:nav], passed: !!p[:passed],
night: (true if p[:night]), stay: (stay if stay&.positive?), note: (note unless note.empty?),
type: (type unless type.empty?), day_note: (day_note unless day_note.empty?), park: park, avoid: avoid, cost: cost, paid: paid }.compact
end
# € or nil; ArgumentError past MAX_MONEY or below 0.
MAX_MONEY = 1_000_000
def self.money(value)
return nil if value.nil? || value.to_s.strip.empty?
amount = Float(value, exception: false)
raise ArgumentError, "amounts must be 0–#{MAX_MONEY}" unless amount && (0..MAX_MONEY).cover?(amount)
amount.round(2)
end
def self.itinerary(name:, start:, day_start:, note: nil, budget: nil, fuel_price: nil)
name = name.to_s.strip[0, 80]
note = note.to_s.strip[0, 2000]
raise ArgumentError, "start must be YYYY-MM-DDTHH:MM" unless start.to_s.empty? || start.to_s.match?(DATE_TIME)
raise ArgumentError, "day_start must be HH:MM" unless day_start.to_s.empty? || day_start.to_s.match?(TIME)
{ name: (name unless name.empty?), start: (start unless start.to_s.empty?), day_start: (day_start unless day_start.to_s.empty?),
note: (note unless note.empty?), budget: money(budget), fuel_price: money(fuel_price) }.compact
end
def initialize(path)
@path = path
@mutex = Mutex.new
@trip = begin
EMPTY.merge(JSON.parse(File.read(path), symbolize_names: true))
rescue Errno::ENOENT, JSON::ParserError
EMPTY.dup
end
end
def get
@mutex.synchronize { @trip.dup }
end
ON_ROUTE_M = 30 # as the dashboard's
OFF_ROUTE_FIXES = 3
MAX_HDOP = 5
MIN_SPEED = 1.5 # m/s: standing next to the route isn't a detour
REROUTE_EVERY_S = 15
# Every GNSS fix (App.gnss_update): off the trip's route for
# OFF_ROUTE_FIXES fixes while driving, routes again from here to the
# points not reached yet — on the server, so it happens with no screen
# open; the screens pick the new version up by polling. The block routes
# (as #update's). In a thread of its own: CAN's reader doesn't wait.
def follow(position, speed:, hdop: nil, now: Time.now.to_f, &router)
trip = get
route = trip[:route]
return unless route && trip[:points].count { |p| !p[:passed] } >= 2
at, off = self.class.locate(route[:geometry][:coordinates], position)
if off <= ON_ROUTE_M
@off_fixes = 0
@last_at = at
return
end
return if (hdop || 0) > MAX_HDOP
@off_fixes = (@off_fixes || 0) + 1
return if @off_fixes < OFF_ROUTE_FIXES || speed.to_f < MIN_SPEED || (@reroute_at && now - @reroute_at < REROUTE_EVERY_S) || @rerouting
@reroute_at = now
@rerouting = true
leg = 0
passed = (route[:properties][:legs_km] || [])[0...-1].map { |km| leg += km }.count { |km| km <= (@last_at || 0) }
points = self.class.passed_on(trip[:points], passed, position)
Thread.new do
update(points: points, vehicle: trip[:vehicle], avoid: trip[:avoid], editing: trip[:editing], &router)
rescue StandardError => e
warn "trip reroute: #{e.message}"
ensure
@rerouting = false
@off_fixes = 0
end
end
# The points after a detour: the start and the `passed` vias reached so
# far marked passed (the start dropped if it was an earlier "My
# position", not a stop), then the position as the new start, then the rest.
def self.passed_on(points, passed, position)
done, ahead = points.partition { |p| p[:passed] }
ahead = ahead.dup
reached = ahead.shift(1 + passed)
reached.shift if reached.first&.dig(:name) == "My position"
done + reached.map { |p| p.merge(passed: true) } + [{ lngLat: position, name: "My position", nav: false, passed: false }] + ahead
end
# Nearest point on the line ([[lon, lat], ...]): [km along it, meters off it].
def self.locate(coords, (lon, lat))
cos = Math.cos(lat * Math::PI / 180)
along = 0.0
best = [0.0, Float::INFINITY]
coords.each_cons(2) do |(ax, ay), (bx, by)|
ax *= cos
bx *= cos
px = lon * cos
len2 = (bx - ax)**2 + (by - ay)**2
t = len2.zero? ? 0.0 : (((px - ax) * (bx - ax) + (lat - ay) * (by - ay)) / len2).clamp(0.0, 1.0)
off = Math.hypot(px - (ax + t * (bx - ax)), lat - (ay + t * (by - ay))) * 111_320
length = Math.sqrt(len2) * 111.32
best = [along + t * length, off] if off < best[1]
along += length
end
best
end
# Dead reckoning along the line: from the point nearest `position`,
# `meters` further on — [[lon, lat], bearing °], or nil if `position`
# is more than ON_ROUTE_M off it (no telling where the car went then).
# Stops at the line's end.
def self.ahead(coords, position, meters)
at, off = locate(coords, position)
return nil if off > ON_ROUTE_M
km = coords.each_cons(2).reduce([0.0]) { |acc, (a, b)| acc << acc.last + GnssSim.meters(a, b) / 1000 }
to = [at + meters / 1000.0, km.last].min
here = GnssSim.point_at(coords, km, to)
[here, GnssSim.bearing(GnssSim.point_at(coords, km, [to - 0.02, 0].max), GnssSim.point_at(coords, km, [to + 0.02, km.last].min)).round(1)]
end
# The points to route, in pieces of the same avoids: [[locations,
# avoid], ...] — one piece unless a day has avoids of its own (on its
# first point in the list, the one after the night spot). A leg takes
# the avoids of the day it's driven in.
def self.pieces(points, avoid)
day = points.first&.dig(:avoid) || avoid
legs = points.each_with_index.filter_map do |p, i|
day = points[i + 1]&.dig(:avoid) || avoid if p[:night] # the next day leaves from the night spot
[p.dig(:park, :lngLat) || p[:lngLat], day] unless p[:passed]
end
legs.each_cons(2).chunk_while { |x, y| x[0][1] == y[0][1] }.map do |run|
[[run.first[0][0], *run.map { |_, to| to[0] }], run.first[0][1]]
end
end
# points: [{ lngLat: [lon, lat], name:, nav:, passed: }]. Routes through
# the ones not passed with the block (locations, vehicle id, avoid → the
# /api/route Feature, may raise Routing errors) unless only names/nav
# changed — the old route stays then. Passed points stay in the trip
# (shown dimmed, still editable: a stop missed out added afterwards),
# just not routed. Last write wins.
def update(points:, vehicle:, avoid:, editing:, name: nil, start: nil, day_start: nil, note: nil, budget: nil, fuel_price: nil)
points = points.map { |p| self.class.point(p) }
itinerary = self.class.itinerary(name: name, start: start, day_start: day_start, note: note, budget: budget, fuel_price: fuel_price)
avoid = (avoid || {}).to_h { |k, v| [k.to_sym, !!v] }
before = get
routed = ->(list) { list.reject { |p| p[:passed] }.map { |p| p.dig(:park, :lngLat) || p[:lngLat] } }
same_route = self.class.pieces(before[:points], before[:avoid]) == self.class.pieces(points, avoid) &&
before[:vehicle] == vehicle && before[:avoid] == avoid && !before[:error]
route, error = if same_route then [before[:route], nil]
elsif routed.(points).size < 2 then [nil, nil]
else
begin
pieces = self.class.pieces(points, avoid)
[Routing.merge(pieces.map { |locations, day_avoid| yield(locations, vehicle, day_avoid) }), nil]
rescue Routing::RouteError, Routing::Unavailable => e
[nil, e.message]
end
end
@mutex.synchronize do
@trip = { version: @trip[:version] + 1, points: points, vehicle: vehicle, avoid: avoid, editing: editing,
**itinerary, route: route, error: error, updated_at: Time.now.to_f }.compact
@trip[:route] = route # nil kept: the client reads it
@trip[:error] = error
File.write("#{@path}.tmp", JSON.generate(@trip))
File.rename("#{@path}.tmp", @path)
@trip.dup
end
end
end
end