Planning (the Design canvas' Plan and GridToday, ideas from azedler/roadplanner): a stop's type as its NPS pictogram (marker and list), notes on the trip, its days and stops, + on a leg inserts the next point there; a parking spot per stop (P marker, the route goes there, the walk shown); a link pasted into the search becomes a place (/api/link: the URL's coordinates, else the page's geo meta / JSON-LD / a map link; public addresses only, logged in), added on the leg it lengthens least; avoids for the trip (+ ferries, unpaved) or a day (routed in pieces, joined); Check and Costs folds in the Route panel (no leave time, long days, arriving after sunset, long walks, missing vignettes; fuel from km × consumption × price, stop costs / paid, the budget); Today in drive mode's Menu (stops left, tonight, sunset, Open-Meteo weather, the day's notes, Skip next, Tomorrow). Plugins along the trip's route (Maptool::Corridor, a corridor width; Overpass around:) and plugin settings saved server-side; p4n via a host Firefox's cookies (docs/deployment.adoc). The recording's days (cut where the car stood ≥ 4 h, or by hand) and their export (days, a piece A–B, the whole trip; GPX with times). Track replay in the GNSS simulator. Step advance 5 m past a maneuver. The level gauge (drive mode, from Terrain): lift per wheel to the ramps' steps from roll, pitch, wheelbase and track
This commit is contained in:
1 parent
5e31dfaba9
commit
87d7bd2463
36 files changed
+2047
-123
No files matched your search
@@ -0,0 +1,66 @@
|
||||
module Maptool
|
||||
# A corridor either side of a route ([[lon, lat], ...]): what a plugin run
|
||||
# along the trip's route covers (lib/maptool/plugins.rb). Flat-earth
|
||||
# distances (equirectangular per segment) — fine for a few km either side.
|
||||
module Corridor
|
||||
KM_PER_DEG = 111.32
|
||||
|
||||
def self.km(a, b)
|
||||
Math.hypot((b[0] - a[0]) * Math.cos((a[1] + b[1]) / 2 * Math::PI / 180), b[1] - a[1]) * KM_PER_DEG
|
||||
end
|
||||
|
||||
# The route's vertices at least step_km apart (its ends kept): a short
|
||||
# enough line for a query (Overpass' around: takes a polyline).
|
||||
def self.thin(coords, step_km)
|
||||
kept = [coords.first]
|
||||
coords.each { |c| kept << c if km(kept.last, c) >= step_km }
|
||||
kept << coords.last unless kept.last == coords.last
|
||||
kept
|
||||
end
|
||||
|
||||
# Circles ([[lon, lat], radius km]) covering the corridor half_km either
|
||||
# side: centers every 1.5 × half_km along the line, radius 1.25 × half_km
|
||||
# (√(0.75² + 1²) = 1.25, so no gap between two of them at the corridor's edge).
|
||||
def self.circles(coords, half_km)
|
||||
step = 1.5 * half_km
|
||||
centers = [coords.first]
|
||||
left = step
|
||||
coords.each_cons(2) do |a, b|
|
||||
length = km(a, b)
|
||||
at = 0.0
|
||||
while length - at >= left
|
||||
at += left
|
||||
t = at / length
|
||||
centers << [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
|
||||
left = step
|
||||
end
|
||||
left -= length - at
|
||||
end
|
||||
centers << coords.last unless centers.last == coords.last
|
||||
centers.map { |c| [c, 1.25 * half_km] }
|
||||
end
|
||||
|
||||
# Shortest distance (km) from a point to the line.
|
||||
def self.distance_km(point, coords)
|
||||
lat0 = point[1] * Math::PI / 180
|
||||
xy = ->(c) { [(c[0] - point[0]) * Math.cos(lat0) * KM_PER_DEG, (c[1] - point[1]) * KM_PER_DEG] }
|
||||
return Math.hypot(*xy.(coords.first)) if coords.size == 1
|
||||
|
||||
coords.each_cons(2).map do |a, b|
|
||||
(ax, ay), (bx, by) = xy.(a), xy.(b)
|
||||
dx, dy = bx - ax, by - ay
|
||||
len2 = dx * dx + dy * dy
|
||||
t = len2.zero? ? 0.0 : (-(ax * dx + ay * dy) / len2).clamp(0.0, 1.0)
|
||||
Math.hypot(ax + t * dx, ay + t * dy)
|
||||
end.min
|
||||
end
|
||||
|
||||
# [south, west, north, east] around the line, half_km wider each way.
|
||||
def self.bbox(coords, half_km)
|
||||
lons, lats = coords.map(&:first), coords.map { |c| c[1] }
|
||||
dlat = half_km / KM_PER_DEG
|
||||
dlon = half_km / (KM_PER_DEG * Math.cos(lats.map(&:abs).max * Math::PI / 180))
|
||||
[lats.min - dlat, lons.min - dlon, lats.max + dlat, lons.max + dlon]
|
||||
end
|
||||
end
|
||||
end
|
||||
+33
-1
@@ -54,12 +54,16 @@ module Maptool
|
||||
# Feature), that route from its start first, random trips after it;
|
||||
# each fix to the block:
|
||||
# { lat:, lon:, speed: m/s, satellites:, hdop:, mode: 3, time: the simulation's epoch s }.
|
||||
def start(lon = nil, lat = nil, bboxes: nil, route: nil, &on_fix)
|
||||
# With track ([[lon, lat, elapsed s], ...], a library track's) instead:
|
||||
# that track replayed at its own speed, then it stops.
|
||||
def start(lon = nil, lat = nil, bboxes: nil, route: nil, track: nil, &on_fix)
|
||||
stop
|
||||
@error = nil
|
||||
@clock = Time.now.to_f
|
||||
@mutex.synchronize do
|
||||
@thread = Thread.new do
|
||||
next replay(track, &on_fix) if track
|
||||
|
||||
position, route = if route then [route[:geometry][:coordinates].first, with_detours(route)]
|
||||
elsif bboxes then random_start(bboxes)
|
||||
else [[Float(lon), Float(lat)], nil]
|
||||
@@ -120,6 +124,34 @@ module Maptool
|
||||
coords.last
|
||||
end
|
||||
|
||||
MAX_GAP_S = 30 # a stop longer than this in a replayed track: cut to it
|
||||
|
||||
# A recorded track driven again at its own pace (sped up like the
|
||||
# rest): points [lon, lat, elapsed s]; long stops shortened to MAX_GAP_S.
|
||||
def replay(points, &on_fix)
|
||||
shift = 0.0
|
||||
points = points.each_cons(2).each_with_object([[*points.first.first(2), 0.0]]) do |(a, b), out|
|
||||
shift += [b[2] - a[2] - MAX_GAP_S, 0].max
|
||||
out << [b[0], b[1], b[2] - points.first[2] - shift]
|
||||
end
|
||||
t = 0.0
|
||||
i = 1
|
||||
while i < points.size
|
||||
t += TICK_S * @speedup
|
||||
@clock += TICK_S * @speedup
|
||||
i += 1 while i < points.size - 1 && points[i][2] < t
|
||||
a, b = points[i - 1], points[i]
|
||||
dt = b[2] - a[2]
|
||||
f = dt.positive? ? ((t - a[2]) / dt).clamp(0.0, 1.0) : 1.0
|
||||
lon, lat = a.first(2).zip(b.first(2)).map { |p, q| p + (q - p) * f }
|
||||
speed = dt.positive? ? self.class.meters(a, b) / dt : 0.0
|
||||
on_fix&.call(lat: lat, lon: lon, speed: speed, satellites: 12, hdop: 0.8, mode: 3, time: @clock.round(1))
|
||||
break if i == points.size - 1 && f >= 1
|
||||
|
||||
@sleep.call(TICK_S)
|
||||
end
|
||||
end
|
||||
|
||||
def speed_kmh(limit)
|
||||
(limit == "unlimited" ? UNLIMITED_KMH : limit || NO_LIMIT_KMH) * LIMIT_SHARE
|
||||
end
|
||||
|
||||
+6
-1
@@ -117,9 +117,14 @@ module Maptool
|
||||
if route
|
||||
segments.flatten(1).each { |c| add_text(element.add_element("rtept", position_attributes(c)), "ele", c[2]) }
|
||||
else
|
||||
times = props["times"] if segments.size == 1 # a LineString's: an ISO time per point
|
||||
segments.each do |segment|
|
||||
trkseg = element.add_element("trkseg")
|
||||
segment.each { |c| add_text(trkseg.add_element("trkpt", position_attributes(c)), "ele", c[2]) }
|
||||
segment.each_with_index do |c, i|
|
||||
trkpt = trkseg.add_element("trkpt", position_attributes(c))
|
||||
add_text(trkpt, "ele", c[2])
|
||||
add_text(trkpt, "time", times&.[](i))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -539,6 +539,11 @@ module Maptool
|
||||
|
||||
# A folder's own items (not its subfolders') as one GPX with points and
|
||||
# tracks together — what Locus imports into one folder.
|
||||
# A folder's own features (not its subfolders').
|
||||
def folder_features(path)
|
||||
export_entries(path).map { |e| e[:feature] }
|
||||
end
|
||||
|
||||
def export_gpx(path)
|
||||
Gpx.from_features(export_entries(path).map { |e| e[:feature] })
|
||||
end
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
require "net/http"
|
||||
require "uri"
|
||||
require "ipaddr"
|
||||
require "resolv"
|
||||
require "cgi"
|
||||
|
||||
module Maptool
|
||||
# A link pasted into the search (the Design canvas' Plan) → a place:
|
||||
# { name:, lat:, lng:, url: }, or nil. The coordinates come from the URL
|
||||
# itself (Google Maps' @lat,lng / !3d!4d / ?q=, geo:), else from the page
|
||||
# it leads to (redirects followed: maps.app.goo.gl): its geo meta tags,
|
||||
# JSON-LD, or a map link in it — the way a chat app unfurls a link, one
|
||||
# page the user pasted. Only public addresses are fetched (never this
|
||||
# server's LAN).
|
||||
module LinkPlace
|
||||
MAX_BYTES = 2_000_000
|
||||
MAX_REDIRECTS = 5
|
||||
TIMEOUT_S = 10
|
||||
LAT_LNG = /(-?\d{1,2}\.\d+)\s*[,;]\s*(-?\d{1,3}\.\d+)/
|
||||
|
||||
class Error < StandardError; end
|
||||
|
||||
def self.resolve(url)
|
||||
place = from_url(url)
|
||||
return place if place
|
||||
|
||||
html, final = fetch(url)
|
||||
from_url(final) || from_html(html)&.then { |p| p.merge(url: final) }
|
||||
end
|
||||
|
||||
# Coordinates in the link itself.
|
||||
def self.from_url(url)
|
||||
text = CGI.unescape(url.to_s)
|
||||
lat, lng = text.match(/!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)/)&.captures ||
|
||||
text.match(/[?&](?:q|query|ll|destination|daddr|center)=(?:loc:)?#{LAT_LNG}/)&.captures ||
|
||||
text.match(/@#{LAT_LNG}/)&.captures ||
|
||||
text.match(/\Ageo:#{LAT_LNG}/)&.captures ||
|
||||
text.match(%r{/place/#{LAT_LNG}})&.captures
|
||||
return nil unless lat
|
||||
|
||||
name = text[%r{/place/([^/@]+)/}, 1]&.tr("+", " ")
|
||||
place(name, lat, lng, url)
|
||||
end
|
||||
|
||||
# Coordinates in the page: meta tags, JSON-LD, then a map link.
|
||||
def self.from_html(html)
|
||||
meta = ->(key) { html[/<meta[^>]+(?:property|name)=["']#{Regexp.escape(key)}["'][^>]*content=["']([^"']+)/i, 1] || html[/<meta[^>]+content=["']([^"']+)["'][^>]*(?:property|name)=["']#{Regexp.escape(key)}["']/i, 1] }
|
||||
name = meta.("og:title") || html[%r{<title[^>]*>([^<]+)</title>}i, 1]
|
||||
name = CGI.unescapeHTML(name.strip) if name
|
||||
lat, lng = [meta.("place:location:latitude") || meta.("og:latitude"), meta.("place:location:longitude") || meta.("og:longitude")]
|
||||
lat, lng = (meta.("geo.position") || meta.("ICBM"))&.match(LAT_LNG)&.captures unless lat && lng
|
||||
lat, lng = html.match(/"latitude"\s*:\s*"?(-?\d+\.\d+)"?\s*,\s*"longitude"\s*:\s*"?(-?\d+\.\d+)/)&.captures unless lat && lng
|
||||
lat, lng = html.scan(%r{https?://(?:www\.)?google\.[a-z.]+/maps[^"'\s<>]*}).lazy.filter_map { |u| from_url(CGI.unescapeHTML(u)) }.first&.values_at(:lat, :lng) unless lat && lng
|
||||
lat && lng ? place(name, lat, lng, nil) : nil
|
||||
end
|
||||
|
||||
def self.place(name, lat, lng, url)
|
||||
lat = Float(lat)
|
||||
lng = Float(lng)
|
||||
return nil unless lat.between?(-90, 90) && lng.between?(-180, 180)
|
||||
|
||||
{ name: name&.strip&.then { |n| n.empty? ? nil : n[0, 160] }, lat: lat, lng: lng, url: url }.compact
|
||||
end
|
||||
|
||||
# [body, final url]; raises Error.
|
||||
def self.fetch(url, redirects = MAX_REDIRECTS)
|
||||
uri = URI.parse(url)
|
||||
raise Error, "only http(s) links" unless %w[http https].include?(uri.scheme) && uri.host
|
||||
ip = public_ip(uri.host)
|
||||
http = Net::HTTP.new(uri.host, uri.port)
|
||||
http.ipaddr = ip # the address checked, not a second lookup
|
||||
http.use_ssl = uri.scheme == "https"
|
||||
http.open_timeout = http.read_timeout = TIMEOUT_S
|
||||
request = Net::HTTP::Get.new(uri, "User-Agent" => "Mozilla/5.0 (maptool link preview)", "Accept" => "text/html")
|
||||
http.request(request) do |response|
|
||||
case response
|
||||
when Net::HTTPRedirection
|
||||
raise Error, "too many redirects" if redirects.zero?
|
||||
|
||||
return fetch(URI.join(url, response["location"]).to_s, redirects - 1)
|
||||
when Net::HTTPSuccess
|
||||
body = +""
|
||||
response.read_body do |chunk|
|
||||
body << chunk
|
||||
break if body.bytesize > MAX_BYTES
|
||||
end
|
||||
return [body.force_encoding("UTF-8").scrub, url]
|
||||
else
|
||||
raise Error, "the page answered #{response.code}"
|
||||
end
|
||||
end
|
||||
rescue URI::InvalidURIError, SocketError, Timeout::Error, SystemCallError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse => e
|
||||
raise Error, e.message
|
||||
end
|
||||
|
||||
def self.public_ip(host)
|
||||
address = Resolv.getaddress(host)
|
||||
ip = IPAddr.new(address)
|
||||
raise Error, "not a public address" if ip.private? || ip.loopback? || ip.link_local? || address.start_with?("0.") || ip == IPAddr.new("::") ||
|
||||
IPAddr.new("100.64.0.0/10").include?(ip) # CGNAT: Tailscale
|
||||
|
||||
address
|
||||
rescue Resolv::ResolvError
|
||||
raise Error, "unknown host #{host}"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -58,9 +58,10 @@ module Maptool
|
||||
["operator", "Operator"],
|
||||
].freeze
|
||||
|
||||
# bbox: [south, west, north, east] (Overpass's own axis order).
|
||||
def self.fetch(bbox, timeout: 60)
|
||||
query = build_query(bbox, timeout: timeout)
|
||||
# bbox: [south, west, north, east] (Overpass's own axis order); or
|
||||
# around: [radius m, [[lon, lat], ...]] — a corridor along a line.
|
||||
def self.fetch(bbox, timeout: 60, around: nil)
|
||||
query = build_query(bbox, timeout: timeout, around: around)
|
||||
errors = OVERPASS_APIS.map do |url|
|
||||
return post(URI(url), query, timeout)
|
||||
rescue FetchError, Net::OpenTimeout, Net::ReadTimeout, SystemCallError, SocketError, OpenSSL::SSL::SSLError, JSON::ParserError => e
|
||||
@@ -83,8 +84,13 @@ module Maptool
|
||||
JSON.parse(response.body)
|
||||
end
|
||||
|
||||
def self.build_query(bbox, timeout: 60)
|
||||
bbox_str = bbox.join(",")
|
||||
def self.build_query(bbox, timeout: 60, around: nil)
|
||||
bbox_str = if around
|
||||
radius, line = around
|
||||
"around:#{radius.round},#{line.map { |lon, lat| "#{lat.round(5)},#{lon.round(5)}" }.join(',')}"
|
||||
else
|
||||
bbox.join(",")
|
||||
end
|
||||
filters = CATEGORIES.keys.map do |tags|
|
||||
conditions = tags.map { |k, v| %(["#{k}"="#{v}"]) }.join
|
||||
"node#{conditions}(#{bbox_str});"
|
||||
|
||||
+49
-9
@@ -1,5 +1,6 @@
|
||||
require "json"
|
||||
require "open3"
|
||||
require "fileutils"
|
||||
|
||||
module Maptool
|
||||
# Runs an external "importer" script that turns a bbox into a GeoJSON
|
||||
@@ -33,26 +34,64 @@ module Maptool
|
||||
Dir.glob(File.join(dir, "*", "plugin.json")).filter_map do |manifest_path|
|
||||
name = File.basename(File.dirname(manifest_path))
|
||||
manifest = JSON.parse(File.read(manifest_path))
|
||||
{ "name" => name, "label" => manifest["label"] || name }
|
||||
{ "name" => name, "label" => manifest["label"] || name, "route" => manifest["route"] == true,
|
||||
"settings" => setting_fields(manifest) }
|
||||
rescue JSON::ParserError
|
||||
nil
|
||||
end
|
||||
end.uniq { |plugin| plugin["name"] }.sort_by { |p| p["label"] }
|
||||
end
|
||||
|
||||
# bbox: [south, west, north, east]. Raises RunError with a short
|
||||
# The settings a plugin asks for in its plugin.json ("settings": [{"key":
|
||||
# "P4N_COOKIE", "label": "…", "help": "…"}]) — a login cookie, a key —
|
||||
# set in the panel, kept server-side (never sent back to a browser) and
|
||||
# handed to the plugin's command as environment variables. A key is an
|
||||
# env var name; anything else in the list is ignored.
|
||||
SETTING_KEY = /\A[A-Z][A-Z0-9_]*\z/
|
||||
|
||||
def self.setting_fields(manifest)
|
||||
Array(manifest["settings"]).select { |f| f.is_a?(Hash) && f["key"].to_s =~ SETTING_KEY }
|
||||
.map { |f| f.slice("key", "label", "help") }
|
||||
end
|
||||
|
||||
# Saved settings: { name => { KEY => value } } in one JSON file (mode 600).
|
||||
def self.saved_settings(path)
|
||||
File.file?(path) ? JSON.parse(File.read(path)) : {}
|
||||
rescue JSON::ParserError
|
||||
{}
|
||||
end
|
||||
|
||||
# Sets (or, empty, clears) the plugin's declared keys only.
|
||||
def self.save_settings(path, dirs, name, values)
|
||||
plugin_dir = find(dirs, name)
|
||||
fields = setting_fields(JSON.parse(File.read(File.join(plugin_dir, "plugin.json")))).map { |f| f["key"] }
|
||||
all = saved_settings(path)
|
||||
mine = (all[name] || {}).merge(values.to_h.slice(*fields).transform_values { |v| v.to_s.strip })
|
||||
all[name] = mine.reject { |_, v| v.empty? }
|
||||
FileUtils.mkdir_p(File.dirname(path))
|
||||
File.write("#{path}.part", JSON.generate(all), perm: 0o600)
|
||||
File.rename("#{path}.part", path)
|
||||
all[name].keys
|
||||
end
|
||||
|
||||
def self.find(dirs, name)
|
||||
raise RunError, "unknown plugin" unless name =~ NAME_PATTERN
|
||||
|
||||
Array(dirs).map { |dir| File.join(dir, name) }.find { |dir| File.file?(File.join(dir, "plugin.json")) } or raise RunError, "unknown plugin"
|
||||
end
|
||||
|
||||
# bbox: [south, west, north, east]. With route (a GeoJSON file's path,
|
||||
# the trip's route) and corridor_km, a plugin with "route": true in its
|
||||
# plugin.json also gets --route=<path> --corridor-km=<km> (the bbox is
|
||||
# then the corridor's). env: its saved settings. Raises RunError with a short
|
||||
# message on anything that isn't a clean run — an unknown plugin, a
|
||||
# non-zero exit, or output that isn't a GeoJSON FeatureCollection — so
|
||||
# the route can turn it into a single error response without knowing
|
||||
# any of these details itself. When the same name exists under more
|
||||
# than one of `dirs`, the first one that has it wins — same precedence
|
||||
# as list's `uniq` above.
|
||||
def self.run(dirs, name, bbox)
|
||||
raise RunError, "unknown plugin" unless name =~ NAME_PATTERN
|
||||
|
||||
plugin_dir = Array(dirs).map { |dir| File.join(dir, name) }.find { |dir| File.file?(File.join(dir, "plugin.json")) }
|
||||
raise RunError, "unknown plugin" unless plugin_dir
|
||||
|
||||
def self.run(dirs, name, bbox, route: nil, corridor_km: nil, env: {})
|
||||
plugin_dir = find(dirs, name)
|
||||
manifest_path = File.join(plugin_dir, "plugin.json")
|
||||
|
||||
command = begin
|
||||
@@ -64,8 +103,9 @@ module Maptool
|
||||
|
||||
south, west, north, east = bbox
|
||||
args = ["--south=#{south}", "--west=#{west}", "--north=#{north}", "--east=#{east}"]
|
||||
args += ["--route=#{route}", "--corridor-km=#{corridor_km}"] if route
|
||||
|
||||
stdout, stderr, status = Open3.capture3(command, *args, chdir: plugin_dir)
|
||||
stdout, stderr, status = Open3.capture3(env.to_h, command, *args, chdir: plugin_dir)
|
||||
# First stderr line too — for a Ruby plugin that's the exception
|
||||
# message (e.g. "...: unexpected response 406"), the only clue to why.
|
||||
unless status.success?
|
||||
|
||||
+40
-2
@@ -185,7 +185,8 @@ module Maptool
|
||||
BICYCLE_TYPES = %w[Road Hybrid Cross Mountain].freeze
|
||||
# speed: km/h (bicycle, foot); hills: 0 avoid .. 1 seek (Valhalla's
|
||||
# use_hills); sac: the hardest SAC hiking grade allowed on foot.
|
||||
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60, speed: 1..60, hills: 0..1, sac: 1..6 }.freeze
|
||||
# wheelbase, track (m): the level gauge's geometry (drive_menus.js levelMenu).
|
||||
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60, wheelbase: 1..10, track: 1..3, consumption: 1..100, speed: 1..60, hills: 0..1, sac: 1..6 }.freeze
|
||||
# Up to this weight Valhalla's "auto" costing (with height/width) fits
|
||||
# better than "truck": a camper isn't kept off roads closed to lorries.
|
||||
CAR_MAX_WEIGHT = 3.5
|
||||
@@ -249,6 +250,9 @@ module Maptool
|
||||
raise ArgumentError, "#{name}: invalid Euro class" unless euro.nil? || EUROS.include?(euro)
|
||||
|
||||
stickers = values["stickers"].to_s.strip[0, 80]
|
||||
# the levelling ramps' steps, cm ("3 6 9"), for the level gauge
|
||||
ramps = values["ramps"].to_s.scan(/\d+(?:[.,]\d+)?/).map { |s| s.tr(",", ".").to_f }
|
||||
raise ArgumentError, "#{name}: ramps: up to 6 steps of 1 to 40 cm" unless ramps.size <= 6 && ramps.all? { |cm| (1..40).cover?(cm) }
|
||||
list = values["vignettes"] || []
|
||||
raise ArgumentError, "#{name}: invalid vignettes" unless list.is_a?(Array) && list.size <= 30
|
||||
|
||||
@@ -262,7 +266,8 @@ module Maptool
|
||||
|
||||
{ country: country, kind: kind, until: (until_date unless until_date.empty?) }.compact
|
||||
end
|
||||
{ fuel: fuel, euro: euro, stickers: (stickers unless stickers.empty?), vignettes: (vignettes unless vignettes.empty?) }
|
||||
{ fuel: fuel, euro: euro, stickers: (stickers unless stickers.empty?), vignettes: (vignettes unless vignettes.empty?),
|
||||
ramps: (ramps.sort.map { |cm| cm % 1 == 0 ? cm.to_i : cm }.join(" ") unless ramps.empty?) }
|
||||
end
|
||||
private_class_method :car_details
|
||||
|
||||
@@ -293,6 +298,37 @@ module Maptool
|
||||
raise RouteError, "invalid coordinates"
|
||||
end
|
||||
|
||||
# Routes of consecutive pieces (a trip's days with avoids of their own,
|
||||
# TripStore) as one: the lines joined, km along it shifted by the pieces
|
||||
# before, the countries summed.
|
||||
def self.merge(parts)
|
||||
return parts.first if parts.size <= 1
|
||||
|
||||
km = 0.0
|
||||
coords = []
|
||||
out = { distance_km: 0.0, time_s: 0.0, legs_km: [], legs_s: [], maneuvers: [], speed_limits: [], signals: [], roads: [] }
|
||||
countries = {}
|
||||
parts.each do |part|
|
||||
props = part[:properties]
|
||||
line = part[:geometry][:coordinates]
|
||||
coords.concat(coords.empty? ? line : line.drop(1))
|
||||
out[:distance_km] += props[:distance_km]
|
||||
out[:time_s] += props[:time_s]
|
||||
%i[legs_km legs_s maneuvers].each { |key| out[key].concat(props[key] || []) }
|
||||
out[:speed_limits].concat((props[:speed_limits] || []).map { |at, limit| [(at + km).round(3), limit] })
|
||||
out[:signals].concat((props[:signals] || []).map { |lon, lat, at| [lon, lat, (at + km).round(3)] })
|
||||
out[:roads].concat((props[:roads] || []).map { |at, *rest| [(at + km).round(3), *rest] })
|
||||
(props[:countries] || []).each do |row|
|
||||
sum = countries[row[:code]] ||= { code: row[:code], km: 0.0, motorway_km: 0.0, toll_km: 0.0 }
|
||||
%i[km motorway_km toll_km].each { |key| sum[key] = (sum[key] + row[key].to_f).round(1) }
|
||||
end
|
||||
km += props[:distance_km]
|
||||
end
|
||||
first = parts.first
|
||||
{ type: "Feature", geometry: { type: "LineString", coordinates: coords },
|
||||
properties: first[:properties].merge(out, distance_km: out[:distance_km].round(3), countries: countries.values) }
|
||||
end
|
||||
|
||||
def self.maneuver(m)
|
||||
{ text: m["instruction"], km: m["length"], type: m["type"], street: (m["begin_street_names"] || m["street_names"])&.first,
|
||||
exit: m["roundabout_exit_count"], lanes: m["lanes"],
|
||||
@@ -429,6 +465,8 @@ module Maptool
|
||||
avoid = {} unless avoid.is_a?(Hash)
|
||||
options = options.merge(use_tolls: 0.0) if avoid["tolls"]
|
||||
options = options.merge(use_highways: 0.0) if avoid["highways"]
|
||||
options = options.merge(use_ferry: 0.0) if avoid["ferries"]
|
||||
options = options.merge(exclude_unpaved: true) if avoid["unpaved"]
|
||||
[costing, options]
|
||||
end
|
||||
private_class_method :costing
|
||||
|
||||
+53
-10
@@ -12,8 +12,14 @@ module Maptool
|
||||
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 and a note.
|
||||
# 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/
|
||||
|
||||
@@ -21,17 +27,38 @@ module Maptool
|
||||
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 = p[:note].to_s.strip[0, 500]
|
||||
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?) }.compact
|
||||
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
|
||||
|
||||
def self.itinerary(name:, start:, day_start:)
|
||||
# € 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?) }
|
||||
{ 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)
|
||||
@@ -134,25 +161,41 @@ module Maptool
|
||||
[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)
|
||||
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)
|
||||
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[:lngLat] } }
|
||||
same_route = routed.(before[:points]) == routed.(points) &&
|
||||
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
|
||||
[yield(routed.(points), vehicle, avoid), nil]
|
||||
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
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
require "time"
|
||||
require_relative "track_stats"
|
||||
require_relative "gpx"
|
||||
|
||||
module Maptool
|
||||
# The days of a recorded trip (the Design canvas' GridRecording): the log
|
||||
# stays one continuous journal (lib/maptool/trip_log.rb), the days are only
|
||||
# cuts in it — where the car stood ≥ STOOD_S, else at NIGHT_HOUR local time
|
||||
# (a drive through the night with no long stop), plus the cuts made by
|
||||
# hand, minus the ones joined. A cut is the index of a day's first point.
|
||||
# points: [[lon, lat, alt, t], ...] (t: epoch s), as the journal has them.
|
||||
module TripDays
|
||||
STOOD_S = 4 * 3600
|
||||
NIGHT_HOUR = 3
|
||||
PAUSE_S = 300 # this long between two fixes: standing (a fix comes every 10 m moved)
|
||||
|
||||
# [[index, "auto" | "night" | "hand"], ...], sorted. hand / joined: epoch
|
||||
# s — a hand cut starts the day at the first point from then on; a join
|
||||
# names the cut by its day's first point's time.
|
||||
# ponytail: NIGHT_HOUR in the server's time zone, the client's if they differ
|
||||
def self.cuts(points, hand: [], joined: [])
|
||||
t = points.map { |p| p[3] }
|
||||
auto = (1...points.size).select { |i| t[i] - t[i - 1] >= STOOD_S }
|
||||
night = (1...points.size).select do |i|
|
||||
crossed = Time.at(t[i]).then { |b| Time.new(b.year, b.month, b.day, NIGHT_HOUR) }
|
||||
crossed = crossed - 86_400 if crossed.to_f > t[i]
|
||||
crossed.to_f > t[i - 1] && auto.none? { |j| (t[j] - t[i]).abs < 12 * 3600 }
|
||||
end
|
||||
by_hand = hand.filter_map { |h| t.index { |x| x >= h } }.select { |i| i.positive? }
|
||||
all = auto.map { |i| [i, "auto"] } + night.map { |i| [i, "night"] } + by_hand.map { |i| [i, "hand"] }
|
||||
all.reject { |i, _| joined.any? { |j| (t[i] - j).abs < 0.05 } }.uniq(&:first).sort_by(&:first)
|
||||
end
|
||||
|
||||
# The days: { index:, from:, to: (exclusive), started_at:, ended_at:,
|
||||
# distance_m:, driving_s:, ascent_m:, max_alt_m:, cut: (what ends it:
|
||||
# { kind:, stood_s:, at: [lon, lat], next: its time }) }.
|
||||
def self.days(points, cuts)
|
||||
bounds = [0, *cuts.map(&:first), points.size]
|
||||
bounds.each_cons(2).each_with_index.map do |(from, to), n|
|
||||
piece = points[from...to]
|
||||
day = { index: n + 1, from: from, to: to, started_at: piece.first[3], ended_at: piece.last[3] }.merge(stats(piece))
|
||||
if to < points.size
|
||||
day[:cut] = { kind: cuts[n][1], stood_s: (points[to][3] - piece.last[3]).round, at: piece.last.first(2), next: points[to][3] }
|
||||
end
|
||||
day
|
||||
end
|
||||
end
|
||||
|
||||
def self.stats(piece)
|
||||
coords = piece.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] }
|
||||
gaps = piece.each_cons(2).map { |a, b| b[3] - a[3] }
|
||||
{
|
||||
distance_m: TrackStats.compute(coords)["distance_meters"],
|
||||
driving_s: gaps.select { |g| g < PAUSE_S }.sum.round,
|
||||
standing_s: gaps.select { |g| g >= PAUSE_S }.sum.round,
|
||||
stops: gaps.count { |g| g >= PAUSE_S },
|
||||
ascent_m: TrackStats.compute(coords)["elevation_gain_meters"],
|
||||
max_alt_m: piece.filter_map { |p| p[2] }.max,
|
||||
}
|
||||
end
|
||||
|
||||
# [west, south, east, north] of a piece.
|
||||
def self.bbox(piece)
|
||||
lons, lats = piece.map(&:first), piece.map { |p| p[1] }
|
||||
[lons.min, lats.min, lons.max, lats.max]
|
||||
end
|
||||
|
||||
# A GPX of tracks — pieces: [[name, points], ...] — with each point's
|
||||
# time; extras: Features to add (the planned route, stops, pauses).
|
||||
def self.gpx(pieces, extras = [])
|
||||
tracks = pieces.map do |name, piece|
|
||||
{ "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => piece.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] } },
|
||||
"properties" => { "kind" => "track", "name" => name, "activity_type" => "driving",
|
||||
"times" => piece.map { |p| Time.at(p[3]).utc.iso8601 } } }
|
||||
end
|
||||
Gpx.from_features(extras + tracks)
|
||||
end
|
||||
|
||||
# The stands (≥ PAUSE_S) in a piece as waypoints.
|
||||
def self.pauses(piece)
|
||||
piece.each_cons(2).filter_map do |a, b|
|
||||
next if b[3] - a[3] < PAUSE_S
|
||||
|
||||
{ "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => a.first(2) },
|
||||
"properties" => { "name" => "Stood #{duration(b[3] - a[3])}", "time" => Time.at(a[3]).utc.iso8601 } }
|
||||
end
|
||||
end
|
||||
|
||||
def self.duration(seconds)
|
||||
h, m = (seconds / 60).round.divmod(60)
|
||||
h.positive? ? format("%d h %02d", h, m) : "#{m} min"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -117,6 +117,47 @@ module Maptool
|
||||
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.
|
||||
|
||||
Reference in new issue
Block a user