Bicycle and foot route profiles (Valhalla bicycle/pedestrian costing); hiking trail colours in the elevation profile; power, splits and best efforts in the profile; TCX import; FIT course export
This commit is contained in:
1 parent
4c704045c5
commit
f8755ea65a
21 files changed
+634
-40
No files matched your search
@@ -198,6 +198,25 @@ module Maptool
|
||||
halt 400, json(error: "invalid feature")
|
||||
end
|
||||
|
||||
# The node's first line as a FIT course (FitCourse), or nil. A route
|
||||
# planned for a bicycle/foot profile keeps that sport.
|
||||
def fit_course(geojson, name)
|
||||
feature = JSON.parse(geojson)["features"].find { |f| f.dig("geometry", "type").to_s.end_with?("LineString") }
|
||||
return unless feature
|
||||
|
||||
props = feature["properties"] || {}
|
||||
coordinates = feature["geometry"]["type"] == "LineString" ? feature["geometry"]["coordinates"] : feature["geometry"]["coordinates"].flatten(1)
|
||||
vehicle = props["vehicle"].is_a?(Hash) ? props["vehicle"] : {}
|
||||
sport = case vehicle["type"]
|
||||
when "bicycle" then "cycling"
|
||||
when "foot" then vehicle["speed"].to_f >= 7 ? "running" : "hiking"
|
||||
else props["activity_type"]
|
||||
end
|
||||
FitCourse.encode(coordinates, name: props["name"] || name, sport: sport, duration: props["duration_secs"])
|
||||
rescue ArgumentError
|
||||
nil
|
||||
end
|
||||
|
||||
def save_zip_entries(folder:, io:)
|
||||
paths = []
|
||||
Zip::File.open_buffer(io) do |zip|
|
||||
@@ -631,8 +650,17 @@ module Maptool
|
||||
halt 422, json(error: "could not parse file")
|
||||
end
|
||||
|
||||
name = params[:name].to_s.empty? ? "export" : File.basename(params[:name].to_s)
|
||||
if params[:download] == "fit"
|
||||
fit = fit_course(body, name)
|
||||
halt 422, json(error: "not a track or route") unless fit
|
||||
content_type "application/vnd.ant.fit"
|
||||
attachment "#{name}.fit"
|
||||
return fit
|
||||
end
|
||||
|
||||
content_type :json
|
||||
attachment "#{params[:name].to_s.empty? ? "export" : File.basename(params[:name].to_s)}.geojson" if params[:download]
|
||||
attachment "#{name}.geojson" if params[:download]
|
||||
body
|
||||
end
|
||||
|
||||
|
||||
@@ -208,7 +208,7 @@ phone can't skip a change.
|
||||
in `properties` — what the map draws.
|
||||
|
||||
| `POST /api/library/import`
|
||||
| Multipart upload (GPX/FIT/GeoJSON/ZIP) into a folder: stores the
|
||||
| Multipart upload (GPX/FIT/TCX/GeoJSON/ZIP) into a folder: stores the
|
||||
source, extracts items, skips items whose `fingerprint` already exists
|
||||
in that folder (re-sharing the same track from OsmAnd doesn't
|
||||
duplicate it).
|
||||
@@ -235,7 +235,20 @@ phone can't skip a change.
|
||||
`osmand:icon` → `color`/`icon` (already parsed by `Gpx.waypoint_style`).
|
||||
* Folder: the one picked in the import dialog; a GPX's own waypoint
|
||||
groups (OsmAnd's per-folder favorites export) become subfolders.
|
||||
* FIT → one track. GeoJSON → items by geometry type.
|
||||
* FIT → one track; TCX → one track per `<Activity>` (`Tcx`).
|
||||
GeoJSON → items by geometry type.
|
||||
* Heart rate, cadence, speed and power (FIT field 7, GPX `power` /
|
||||
`PowerInWatts`, TCX `Watts`) go into the profile; the profile panel
|
||||
computes splits and best efforts (fastest distances, best power over
|
||||
5 s–60 min, biggest climb) from it in the browser.
|
||||
|
||||
=== FIT course out
|
||||
|
||||
`GET /api/library/node/:key?download=fit` writes the node's first line
|
||||
as a FIT course (`FitCourse`) for Garmin/Wahoo devices: one record per
|
||||
point with distance and a timestamp spread over the line's duration (a
|
||||
4 m/s guess without one); the sport comes from the route's bicycle/foot
|
||||
profile or the track's activity type.
|
||||
|
||||
=== Locus
|
||||
|
||||
|
||||
@@ -145,6 +145,14 @@ serving swaps the tiles in, and a truck route with dimensions comes back.
|
||||
(3.0 m, 2.3 m, 7 m, 3.5 t; an older single `vehicle.json` becomes the
|
||||
camper). The route panel picks one per browser (localStorage) and sends
|
||||
its id with `/api/route` and `/api/isochrone`; Edit shows the fields.
|
||||
* A profile's `type` is `car` (also when missing), `bicycle` or `foot`.
|
||||
Bicycle uses Valhalla's `bicycle` costing (`bicycle_type`
|
||||
Road/Hybrid/Cross/Mountain, `speed` as `cycling_speed`, `hills` as
|
||||
`use_hills`); foot uses `pedestrian` (`speed` as `walking_speed`, `sac`
|
||||
as `max_hiking_difficulty`, the hardest SAC grade, `hills`). The same
|
||||
tiles serve both, no rebuild. Defaults: Bicycle, Mountain bike, Run
|
||||
(10 km/h, T2), Hike (4.5 km/h, T3); a list saved before types existed
|
||||
gets them once. Avoid and the per-country summary are car-only.
|
||||
* Avoid tolls / motorways (`"avoid": {"tolls": true, "highways": true}`)
|
||||
sets Valhalla's `use_tolls` / `use_highways` to 0 for the whole route.
|
||||
Per country isn't possible in one Valhalla request.
|
||||
|
||||
+8
-4
@@ -22,6 +22,7 @@ module Maptool
|
||||
FIELD_HEART_RATE = 3
|
||||
FIELD_CADENCE = 4
|
||||
FIELD_SPEED = 6
|
||||
FIELD_POWER = 7
|
||||
FIELD_TIMESTAMP = 253
|
||||
FIELD_ENHANCED_ALTITUDE = 78
|
||||
SPORT_FIELD_BY_MESSAGE = { SPORT_MESSAGE_NUM => 0, SESSION_MESSAGE_NUM => 5 }.freeze
|
||||
@@ -60,7 +61,7 @@ module Maptool
|
||||
|
||||
def self.track_feature(result)
|
||||
coordinates = result.records.map { |r| r[:coordinate] }
|
||||
extras = result.records.map { |r| { speed_mps: r[:speed_mps], cadence_rpm: r[:cadence], heart_rate_bpm: r[:heart_rate] } }
|
||||
extras = result.records.map { |r| { speed_mps: r[:speed_mps], cadence_rpm: r[:cadence], heart_rate_bpm: r[:heart_rate], power_w: r[:power] } }
|
||||
|
||||
{
|
||||
"type" => "Feature",
|
||||
@@ -167,10 +168,10 @@ module Maptool
|
||||
private_class_method :extract_sport
|
||||
|
||||
# Only reads the fields the map/its properties need; every other field
|
||||
# in the message (power, temperature, ...) is walked past via its
|
||||
# in the message (temperature, ...) is walked past via its
|
||||
# declared size without being interpreted.
|
||||
def self.extract_record(data, offset, definition)
|
||||
lat = lon = altitude = timestamp = heart_rate = cadence = speed = nil
|
||||
lat = lon = altitude = timestamp = heart_rate = cadence = speed = power = nil
|
||||
pos = offset
|
||||
|
||||
definition.fields.each do |field_num, size|
|
||||
@@ -189,6 +190,8 @@ module Maptool
|
||||
cadence = unpack_int(data, pos, size, definition.little_endian, signed: false)
|
||||
when FIELD_SPEED
|
||||
speed = unpack_int(data, pos, size, definition.little_endian, signed: false)
|
||||
when FIELD_POWER
|
||||
power = unpack_int(data, pos, size, definition.little_endian, signed: false)
|
||||
end
|
||||
pos += size
|
||||
end
|
||||
@@ -201,8 +204,9 @@ module Maptool
|
||||
heart_rate = nil if heart_rate.nil? || invalid?(heart_rate, 1)
|
||||
cadence = nil if cadence.nil? || invalid?(cadence, 1)
|
||||
speed_mps = speed && !invalid?(speed, 2) ? speed / 1000.0 : nil
|
||||
power = nil if power.nil? || invalid?(power, 2)
|
||||
|
||||
{ coordinate: coordinate, time: time, heart_rate: heart_rate, cadence: cadence, speed_mps: speed_mps }
|
||||
{ coordinate: coordinate, time: time, heart_rate: heart_rate, cadence: cadence, speed_mps: speed_mps, power: power }
|
||||
end
|
||||
private_class_method :extract_record
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
require_relative "track_stats"
|
||||
|
||||
module Maptool
|
||||
# A line (a planned route or a track) as a FIT course file, what Garmin
|
||||
# and Wahoo devices follow: file_id, course, lap, timer start, one
|
||||
# record per point (position, altitude, distance, a timestamp spread
|
||||
# over `duration`), timer stop. https://developer.garmin.com/fit/file-types/course/
|
||||
module FitCourse
|
||||
FIT_EPOCH = Time.utc(1989, 12, 31).to_i
|
||||
SEMICIRCLES = (2**31) / 180.0
|
||||
SPORTS = { "running" => 1, "cycling" => 2, "walking" => 11, "hiking" => 17 }.freeze
|
||||
CRC_TABLE = [0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,
|
||||
0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400].freeze
|
||||
# [global message number, [[field number, base type, pack format], ...]]
|
||||
FILE_ID = [0, [[0, 0x00, "C"], [1, 0x84, "S<"], [2, 0x84, "S<"], [4, 0x86, "L<"]]].freeze
|
||||
COURSE = [31, [[4, 0x00, "C"], [5, 0x07, "a32"]]].freeze
|
||||
LAP = [19, [[253, 0x86, "L<"], [2, 0x86, "L<"], [3, 0x85, "l<"], [4, 0x85, "l<"], [5, 0x85, "l<"], [6, 0x85, "l<"],
|
||||
[7, 0x86, "L<"], [8, 0x86, "L<"], [9, 0x86, "L<"]]].freeze
|
||||
EVENT = [21, [[253, 0x86, "L<"], [0, 0x00, "C"], [1, 0x00, "C"]]].freeze
|
||||
RECORD = [20, [[253, 0x86, "L<"], [0, 0x85, "l<"], [1, 0x85, "l<"], [2, 0x84, "S<"], [5, 0x86, "L<"]]].freeze
|
||||
DEFAULT_SPEED = 4.0 # m/s, when the line has no time of its own
|
||||
|
||||
# coordinates: [[lon, lat(, ele)], ...]; duration: seconds or nil.
|
||||
def self.encode(coordinates, name:, sport: nil, duration: nil)
|
||||
raise ArgumentError, "a course needs at least two points" if coordinates.size < 2
|
||||
|
||||
distances = [0.0]
|
||||
coordinates.each_cons(2) { |(lon1, lat1), (lon2, lat2)| distances << distances.last + TrackStats.haversine(lat1, lon1, lat2, lon2) }
|
||||
total = distances.last
|
||||
duration = duration.to_f.positive? ? duration.to_f : total / DEFAULT_SPEED
|
||||
start = Time.now.to_i - FIT_EPOCH
|
||||
finish = start + duration.round
|
||||
first, last = coordinates.first, coordinates.last
|
||||
|
||||
body = message(0, FILE_ID, [6, 255, 0, start]) + # type 6: course; 255: development
|
||||
message(1, COURSE, [SPORTS.fetch(sport, 0), name.to_s.byteslice(0, 31).scrub("")]) +
|
||||
message(2, LAP, [finish, start, *semicircles(first), *semicircles(last), duration * 1000, duration * 1000, total * 100]) +
|
||||
message(3, EVENT, [start, 0, 0]) # timer, start
|
||||
body << definition(4, RECORD)
|
||||
coordinates.each_with_index do |(lon, lat, ele), i|
|
||||
at = start + (total.positive? ? duration * distances[i] / total : 0).round
|
||||
body << data(4, RECORD, [at, *semicircles([lon, lat]), ele ? ((ele + 500) * 5).round.clamp(0, 0xFFFE) : 0xFFFF, (distances[i] * 100).round])
|
||||
end
|
||||
body << data(3, EVENT, [finish, 0, 9]) # timer, stop_disable_all
|
||||
|
||||
header = [14, 0x10, 2132, body.bytesize].pack("CCS<L<") + ".FIT"
|
||||
header += [crc(header)].pack("S<")
|
||||
file = header + body
|
||||
file + [crc(file)].pack("S<")
|
||||
end
|
||||
|
||||
def self.semicircles((lon, lat))
|
||||
[(lat * SEMICIRCLES).round, (lon * SEMICIRCLES).round]
|
||||
end
|
||||
private_class_method :semicircles
|
||||
|
||||
def self.message(local, layout, values)
|
||||
definition(local, layout) + data(local, layout, values)
|
||||
end
|
||||
private_class_method :message
|
||||
|
||||
SIZES = { "C" => 1, "S<" => 2, "L<" => 4, "l<" => 4, "a32" => 32 }.freeze
|
||||
|
||||
def self.definition(local, (global, fields))
|
||||
[0x40 | local, 0, 0, global, fields.size].pack("CCCS<C") +
|
||||
fields.map { |num, type, format| [num, SIZES.fetch(format), type].pack("CCC") }.join
|
||||
end
|
||||
private_class_method :definition
|
||||
|
||||
def self.data(local, (_, fields), values)
|
||||
[local].pack("C") + fields.zip(values).map { |(_, _, format), value| [format == "a32" ? value : value.round].pack(format) }.join
|
||||
end
|
||||
private_class_method :data
|
||||
|
||||
def self.crc(bytes)
|
||||
bytes.each_byte.reduce(0) do |crc, byte|
|
||||
[byte & 0xF, byte >> 4].reduce(crc) do |c, nibble|
|
||||
tmp = CRC_TABLE[c & 0xF]
|
||||
c = (c >> 4) & 0x0FFF
|
||||
c ^ tmp ^ CRC_TABLE[nibble]
|
||||
end
|
||||
end
|
||||
end
|
||||
private_class_method :crc
|
||||
end
|
||||
end
|
||||
+2
-1
@@ -231,7 +231,7 @@ module Maptool
|
||||
end
|
||||
private_class_method :process_point
|
||||
|
||||
# Heart rate/cadence/speed live in a device-specific <extensions> block
|
||||
# Heart rate/cadence/speed/power live in a device-specific <extensions> block
|
||||
# (usually Garmin's own TrackPointExtension) — matched by local element
|
||||
# name only (`Element#name` already strips the namespace prefix), so
|
||||
# this doesn't care which extension schema a given file actually
|
||||
@@ -258,6 +258,7 @@ module Maptool
|
||||
when "hr" then values[:heart_rate_bpm] = child.text&.strip&.to_i
|
||||
when "cad" then values[:cadence_rpm] = child.text&.strip&.to_i
|
||||
when "speed" then values[:speed_mps] = child.text&.strip&.to_f
|
||||
when "power", "PowerInWatts" then values[:power_w] = child.text&.strip&.to_i
|
||||
end
|
||||
collect_extension_values(child, values)
|
||||
end
|
||||
|
||||
@@ -6,6 +6,8 @@ require "sqlite3"
|
||||
require "time"
|
||||
require_relative "gpx"
|
||||
require_relative "fit"
|
||||
require_relative "tcx"
|
||||
require_relative "fit_course"
|
||||
require_relative "gpx_store"
|
||||
|
||||
module Maptool
|
||||
@@ -32,7 +34,7 @@ module Maptool
|
||||
class InvalidValue < StandardError; end
|
||||
|
||||
ROOT = "root" # folder id in a node key for items with no folder
|
||||
EXTENSIONS = %w[.gpx .fit .geojson].freeze
|
||||
EXTENSIONS = %w[.gpx .fit .tcx .geojson].freeze
|
||||
|
||||
def initialize(db_path, gpx_store:, sources_dir:)
|
||||
@path = db_path
|
||||
@@ -511,6 +513,7 @@ module Maptool
|
||||
def parse(path)
|
||||
case File.extname(path).downcase
|
||||
when ".fit" then Fit.to_geojson(path)["features"]
|
||||
when ".tcx" then Tcx.to_geojson(path)["features"]
|
||||
when ".geojson" then JSON.parse(File.read(path)).fetch("features", [])
|
||||
else Gpx.to_geojson(path)["features"]
|
||||
end
|
||||
|
||||
+39
-11
@@ -162,24 +162,38 @@ module Maptool
|
||||
class RouteError < StandardError; end
|
||||
class Unavailable < StandardError; end
|
||||
|
||||
# A camper by default; one profile for now (docs/routing-design.adoc).
|
||||
# Vehicle profiles: a name plus optional limits (nil: no limit, a plain
|
||||
# car). Stored for everyone, picked per browser (route.js).
|
||||
# Profiles: a name, a type (car, bicycle, foot) and that type's
|
||||
# settings, nil meaning Valhalla's default (no limit for a car's size).
|
||||
# No type: a car.
|
||||
# Stored for everyone, picked per browser (route.js).
|
||||
DEFAULT_VEHICLES = [
|
||||
{ id: "car", name: "Car" },
|
||||
{ id: "camper", name: "Camper", height: 3.0, width: 2.3, length: 7.0, weight: 3.5 },
|
||||
].freeze
|
||||
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60 }.freeze
|
||||
ACTIVE_VEHICLES = [
|
||||
{ id: "bike", name: "Bicycle", type: "bicycle", bicycle_type: "Hybrid" },
|
||||
{ id: "mtb", name: "Mountain bike", type: "bicycle", bicycle_type: "Mountain" },
|
||||
{ id: "run", name: "Run", type: "foot", speed: 10.0, sac: 2.0 },
|
||||
{ id: "hike", name: "Hike", type: "foot", speed: 4.5, sac: 3.0 },
|
||||
].freeze
|
||||
TYPES = %w[car bicycle foot].freeze
|
||||
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
|
||||
# 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
|
||||
|
||||
def self.vehicles(data_dir)
|
||||
read_json(File.join(data_dir, "vehicles.json")) || begin
|
||||
list = read_json(File.join(data_dir, "vehicles.json")) || begin
|
||||
# The single vehicle stored before profiles became the camper.
|
||||
old = read_json(File.join(data_dir, "vehicle.json"))
|
||||
old ? [DEFAULT_VEHICLES[0], DEFAULT_VEHICLES[1].merge(old.slice(*VEHICLE_LIMITS.keys))] : DEFAULT_VEHICLES
|
||||
old ? [DEFAULT_VEHICLES[0], DEFAULT_VEHICLES[1].merge(old.slice(:height, :width, :length, :weight))] : DEFAULT_VEHICLES
|
||||
end
|
||||
# A list saved before types existed gets the bicycle/foot profiles
|
||||
# once; every save stores the type, so deleting them sticks.
|
||||
list.none? { |v| v.key?(:type) } ? list + ACTIVE_VEHICLES : list
|
||||
end
|
||||
|
||||
# The profile with this id, or the first one.
|
||||
@@ -188,7 +202,7 @@ module Maptool
|
||||
list.find { |v| v[:id] == id } || list.first
|
||||
end
|
||||
|
||||
# Replaces the whole list: [{ "id", "name", "height", ... }, ...].
|
||||
# Replaces the whole list: [{ "id", "name", "type", "height", ... }, ...].
|
||||
def self.save_vehicles(data_dir, list)
|
||||
raise ArgumentError, "at least one vehicle is needed" unless list.is_a?(Array) && list.any? && list.size <= 20
|
||||
|
||||
@@ -197,8 +211,13 @@ module Maptool
|
||||
|
||||
name = values["name"].to_s.strip
|
||||
id = values["id"].to_s
|
||||
type = values["type"] || "car"
|
||||
raise ArgumentError, "every vehicle needs a name" if name.empty? || name.size > 40
|
||||
raise ArgumentError, "invalid vehicle id" unless id.match?(/\A[\w-]{1,40}\z/)
|
||||
raise ArgumentError, "#{name}: invalid type" unless TYPES.include?(type)
|
||||
|
||||
bicycle_type = values["bicycle_type"] if type == "bicycle"
|
||||
raise ArgumentError, "#{name}: invalid bicycle type" unless bicycle_type.nil? || BICYCLE_TYPES.include?(bicycle_type)
|
||||
|
||||
limits = VEHICLE_LIMITS.to_h do |key, range|
|
||||
raw = values[key.to_s]
|
||||
@@ -209,7 +228,7 @@ module Maptool
|
||||
|
||||
[key, value]
|
||||
end
|
||||
{ id: id, name: name, **limits.compact }
|
||||
{ id: id, name: name, type: type, bicycle_type: bicycle_type, **limits }.compact
|
||||
end
|
||||
raise ArgumentError, "vehicle ids must be unique" unless vehicles.map { |v| v[:id] }.uniq.size == vehicles.size
|
||||
|
||||
@@ -233,7 +252,7 @@ module Maptool
|
||||
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
|
||||
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
|
||||
time_s: data["trip"]["summary"]["time"],
|
||||
countries: countries(valhalla_url, legs, costing, options),
|
||||
countries: (countries(valhalla_url, legs, costing, options) if %w[auto truck].include?(costing)),
|
||||
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
|
||||
rescue ArgumentError, TypeError
|
||||
raise RouteError, "invalid coordinates"
|
||||
@@ -280,9 +299,18 @@ module Maptool
|
||||
raise RouteError, "invalid center or times"
|
||||
end
|
||||
|
||||
# Up to CAR_MAX_WEIGHT "auto" with height/width, above it "truck".
|
||||
# bicycle / pedestrian from the profile's own settings; a car is "auto"
|
||||
# with height/width up to CAR_MAX_WEIGHT, "truck" above it. avoid only
|
||||
# applies to a car.
|
||||
def self.costing(vehicle, avoid = {})
|
||||
limits = vehicle.slice(*VEHICLE_LIMITS.keys).compact
|
||||
case vehicle[:type]
|
||||
when "bicycle"
|
||||
return ["bicycle", { bicycle_type: vehicle[:bicycle_type], cycling_speed: vehicle[:speed], use_hills: vehicle[:hills] }.compact]
|
||||
when "foot"
|
||||
return ["pedestrian", { walking_speed: vehicle[:speed], max_hiking_difficulty: vehicle[:sac]&.to_i, use_hills: vehicle[:hills] }.compact]
|
||||
end
|
||||
|
||||
limits = vehicle.slice(:height, :width, :length, :weight).compact
|
||||
costing, options = limits[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", limits.slice(:height, :width)] : ["truck", limits]
|
||||
avoid = {} unless avoid.is_a?(Hash)
|
||||
options = options.merge(use_tolls: 0.0) if avoid["tolls"]
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
require "rexml/document"
|
||||
require "time"
|
||||
require_relative "gpx"
|
||||
require_relative "track_stats"
|
||||
|
||||
module Maptool
|
||||
# Garmin's older Training Center XML (.tcx), still what some apps
|
||||
# export: each <Activity> becomes one track Feature, shaped like
|
||||
# Gpx/Fit's (MultiLineString, "kind" => "track", the same profile).
|
||||
# Points without a position (indoor, GPS lost) are skipped.
|
||||
module Tcx
|
||||
ParseError = Gpx::ParseError # every caller already rescues that one
|
||||
|
||||
SPORTS = { "Running" => "running", "Biking" => "cycling" }.freeze
|
||||
|
||||
def self.to_geojson(path)
|
||||
root = REXML::Document.new(File.read(path)).root
|
||||
raise ParseError, "not a TCX file" unless root&.name == "TrainingCenterDatabase"
|
||||
|
||||
features = []
|
||||
root.each_element("Activities/Activity") do |activity|
|
||||
points = []
|
||||
times = []
|
||||
extras = []
|
||||
activity.each_element("Lap/Track/Trackpoint") do |pt|
|
||||
lat = text(pt, "Position/LatitudeDegrees")
|
||||
lon = text(pt, "Position/LongitudeDegrees")
|
||||
next unless lat && lon
|
||||
|
||||
ele = text(pt, "AltitudeMeters")
|
||||
points << (ele ? [lon.to_f, lat.to_f, ele.to_f] : [lon.to_f, lat.to_f])
|
||||
times << (Time.iso8601(text(pt, "Time")) rescue nil)
|
||||
extras << extensions(pt).merge({ heart_rate_bpm: text(pt, "HeartRateBpm/Value")&.to_i, cadence_rpm: text(pt, "Cadence")&.to_i }.compact)
|
||||
end
|
||||
next if points.empty?
|
||||
|
||||
features << {
|
||||
"type" => "Feature",
|
||||
"geometry" => { "type" => "MultiLineString", "coordinates" => [points] },
|
||||
"properties" => { "kind" => "track", "name" => nil, "activity_type" => SPORTS.fetch(activity.attributes["Sport"], activity.attributes["Sport"]&.downcase) }
|
||||
.merge(TrackStats.compute(points, times: times))
|
||||
.merge("profile" => TrackStats.build_profile(points, times: times, extras: extras)),
|
||||
}
|
||||
end
|
||||
{ "type" => "FeatureCollection", "features" => features }
|
||||
rescue REXML::ParseException => e
|
||||
raise ParseError, e.message
|
||||
end
|
||||
|
||||
# Speed/Watts/RunCadence in Garmin's ActivityExtension (TPX), by local name.
|
||||
def self.extensions(pt)
|
||||
values = {}
|
||||
pt.elements["Extensions"]&.each_recursive do |el|
|
||||
case el.name
|
||||
when "Speed" then values[:speed_mps] = el.text.to_f
|
||||
when "Watts" then values[:power_w] = el.text.to_i
|
||||
when "RunCadence" then values[:cadence_rpm] = el.text.to_i
|
||||
end
|
||||
end
|
||||
values
|
||||
end
|
||||
private_class_method :extensions
|
||||
|
||||
def self.text(el, path)
|
||||
el.elements[path]&.text&.strip
|
||||
end
|
||||
private_class_method :text
|
||||
end
|
||||
end
|
||||
@@ -31,7 +31,7 @@ module Maptool
|
||||
# (computed the same way for every format, rather than trusting a
|
||||
# device's own odometer field — keeps a GPX and a FIT file directly
|
||||
# comparable), elapsed time since the first known timestamp, elevation,
|
||||
# and whatever per-point extras (speed/cadence/heart rate) the caller
|
||||
# and whatever per-point extras (speed/cadence/heart rate/power) the caller
|
||||
# has — nil wherever a format/file doesn't carry it.
|
||||
# `extras`: array of hashes parallel to `coordinates`, or shorter/empty.
|
||||
# `times`: array of Time (or nil) parallel to `coordinates`, or [].
|
||||
@@ -53,6 +53,7 @@ module Maptool
|
||||
"speed_mps" => extra[:speed_mps],
|
||||
"cadence_rpm" => extra[:cadence_rpm],
|
||||
"heart_rate_bpm" => extra[:heart_rate_bpm],
|
||||
"power_w" => extra[:power_w],
|
||||
"lon" => lon,
|
||||
"lat" => lat,
|
||||
}
|
||||
@@ -66,6 +67,5 @@ module Maptool
|
||||
a = (Math.sin(dlat / 2)**2) + (Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * (Math.sin(dlon / 2)**2))
|
||||
2 * EARTH_RADIUS_METERS * Math.asin(Math.sqrt(a))
|
||||
end
|
||||
private_class_method :haversine
|
||||
end
|
||||
end
|
||||
@@ -2141,6 +2141,27 @@ html, body {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.profile-stats {
|
||||
margin-top: 8px;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.profile-stats table {
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.profile-stats td {
|
||||
padding: 1px 10px 1px 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.profile-chart__trails {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 10px;
|
||||
background: #eee;
|
||||
}
|
||||
|
||||
.profile-panel__xaxis {
|
||||
position: relative;
|
||||
height: 14px;
|
||||
@@ -2390,6 +2411,11 @@ html, body {
|
||||
width: 4.5em;
|
||||
}
|
||||
|
||||
.route-panel__vehicle [hidden],
|
||||
.route-panel__avoid[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.route-panel__avoid {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
|
||||
+6
-1
@@ -366,6 +366,11 @@ export class GpxPanelControl {
|
||||
// A folder's loose points have no single file they came from.
|
||||
file.original && { label: "Original file", run: () => this._download(`${gpxFileUrl(file.path)}?download=original`, file.name) },
|
||||
{ label: "GeoJSON", run: () => this._download(geojsonUrl, `${file.name}.geojson`) },
|
||||
// A course for a Garmin/Wahoo device to follow.
|
||||
file.kinds?.some((kind) => kind === "track" || kind === "route") && {
|
||||
label: "FIT course (Garmin, Wahoo)",
|
||||
run: () => this._download(`${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "fit", name: file.name })}`, `${file.name}.fit`),
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -984,7 +989,7 @@ export class GpxPanelControl {
|
||||
// its .gpx/.fit/.geojson entries, so it's accepted here even though the
|
||||
// tree never shows a .zip itself. .geojson: e.g. a node's GeoJSON
|
||||
// download, re-imported.
|
||||
const files = [...fileList].filter((file) => /\.(gpx|fit|geojson|zip)$/i.test(file.name));
|
||||
const files = [...fileList].filter((file) => /\.(gpx|fit|tcx|geojson|zip)$/i.test(file.name));
|
||||
if (files.length === 0) return [];
|
||||
|
||||
let tree = null;
|
||||
|
||||
@@ -83,6 +83,67 @@ function normalizedTrailColor(raw) {
|
||||
return /^#[0-9a-fA-F]{3,8}$/.test(trimmed) ? trimmed : DEFAULT_TRAIL_COLOR;
|
||||
}
|
||||
|
||||
// The offline trails currently drawn (every ticked country), for
|
||||
// trailColorsAlong.
|
||||
let shownTrails = [];
|
||||
const TRAIL_MATCH_M = 20; // GPS/OSM offset a point may be off its trail
|
||||
const GRID_DEG = 0.001; // ~100 m cells
|
||||
|
||||
// For each {lon, lat} point, the colors of the drawn trails within
|
||||
// TRAIL_MATCH_M of it ([] off-trail), for the elevation profile's trail
|
||||
// band; null when no point is on a drawn trail. Only what the hiking
|
||||
// trails overlay shows, so ticking a country there is what turns it on.
|
||||
export function trailColorsAlong(points) {
|
||||
if (!shownTrails.length || !points.length) return null;
|
||||
const lons = points.map((p) => p.lon);
|
||||
const lats = points.map((p) => p.lat);
|
||||
const [w, e] = [Math.min(...lons) - GRID_DEG, Math.max(...lons) + GRID_DEG];
|
||||
const [s, n] = [Math.min(...lats) - GRID_DEG, Math.max(...lats) + GRID_DEG];
|
||||
// Only segments near the points, bucketed by cell.
|
||||
const grid = new Map();
|
||||
for (const { geometry, properties } of shownTrails) {
|
||||
const lines = geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates;
|
||||
for (const line of lines) {
|
||||
for (let i = 1; i < line.length; i++) {
|
||||
const [a, b] = [line[i - 1], line[i]];
|
||||
if (Math.max(a[0], b[0]) < w || Math.min(a[0], b[0]) > e || Math.max(a[1], b[1]) < s || Math.min(a[1], b[1]) > n) continue;
|
||||
for (let x = Math.floor(Math.min(a[0], b[0]) / GRID_DEG); x <= Math.floor(Math.max(a[0], b[0]) / GRID_DEG); x++) {
|
||||
for (let y = Math.floor(Math.min(a[1], b[1]) / GRID_DEG); y <= Math.floor(Math.max(a[1], b[1]) / GRID_DEG); y++) {
|
||||
const key = `${x},${y}`;
|
||||
if (!grid.has(key)) grid.set(key, []);
|
||||
grid.get(key).push({ a, b, color: properties.color });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let any = false;
|
||||
const colors = points.map(({ lon, lat }) => {
|
||||
const found = new Set();
|
||||
const [cx, cy] = [Math.floor(lon / GRID_DEG), Math.floor(lat / GRID_DEG)];
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
for (let dy = -1; dy <= 1; dy++) {
|
||||
for (const { a, b, color } of grid.get(`${cx + dx},${cy + dy}`) || []) {
|
||||
if (!found.has(color) && segmentDistanceM([lon, lat], a, b) <= TRAIL_MATCH_M) found.add(color);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (found.size) any = true;
|
||||
return [...found];
|
||||
});
|
||||
return any ? colors : null;
|
||||
}
|
||||
|
||||
// Point to segment, on a local flat projection (fine at these distances).
|
||||
function segmentDistanceM([lon, lat], a, b) {
|
||||
const kx = 111320 * Math.cos((lat * Math.PI) / 180);
|
||||
const ky = 110540;
|
||||
const [ax, ay, bx, by] = [(a[0] - lon) * kx, (a[1] - lat) * ky, (b[0] - lon) * kx, (b[1] - lat) * ky];
|
||||
const [dx, dy] = [bx - ax, by - ay];
|
||||
const t = Math.max(0, Math.min(1, -(ax * dx + ay * dy) / (dx * dx + dy * dy || 1)));
|
||||
return Math.hypot(ax + t * dx, ay + t * dy);
|
||||
}
|
||||
|
||||
// Online mode's highlight outline for whichever route(s) the last click
|
||||
// matched — drawn as its own separate source/layer (real geometry, from the
|
||||
// Overpass response), since the raster tiles have no paintable features to
|
||||
@@ -227,6 +288,7 @@ export class HikingTrailsControl {
|
||||
async _rebuildLanes() {
|
||||
const build = (this._lanesBuild = {});
|
||||
const features = [...this._selectedCountries].flatMap((code) => this._trailData.get(code)?.features || []);
|
||||
shownTrails = features;
|
||||
let graph = null;
|
||||
if (features.length > 0) {
|
||||
graph = buildLineGraph(features.flatMap(splitOneway), { routeProperty: "id", onewayProperty: "oneway" });
|
||||
|
||||
+8
-1
@@ -488,7 +488,8 @@ export class RoutePanelControl {
|
||||
const select = this._panel.querySelector(".route-panel__vehicle-select");
|
||||
const editButton = this._panel.querySelector('[data-action="vehicle-edit"]');
|
||||
const fieldset = this._panel.querySelector(".route-panel__vehicle");
|
||||
const inputs = [...fieldset.querySelectorAll("input")];
|
||||
const inputs = [...fieldset.querySelectorAll("input, select")];
|
||||
const avoidRow = this._panel.querySelector(".route-panel__avoid");
|
||||
try {
|
||||
this._vehicles = await (await fetch(VEHICLES_URL)).json();
|
||||
} catch {
|
||||
@@ -500,6 +501,11 @@ export class RoutePanelControl {
|
||||
this._vehicle = current();
|
||||
this._vehicleId = select.value = this._vehicle.id;
|
||||
inputs.forEach((input) => (input.value = this._vehicle[input.name] ?? ""));
|
||||
// No type: a car (profiles saved before bicycle/foot existed).
|
||||
const type = (fieldset.querySelector('[name="type"]').value = this._vehicle.type || "car");
|
||||
if (type === "bicycle" && !this._vehicle.bicycle_type) fieldset.querySelector('[name="bicycle_type"]').value = "Hybrid";
|
||||
fieldset.querySelectorAll("[data-for]").forEach((el) => (el.hidden = !el.dataset.for.split(" ").includes(type)));
|
||||
avoidRow.hidden = type !== "car"; // tolls/motorways: a car's choice
|
||||
};
|
||||
this._selectVehicle = (id) => {
|
||||
this._vehicleId = id;
|
||||
@@ -537,6 +543,7 @@ export class RoutePanelControl {
|
||||
const value = input.value.trim();
|
||||
if (input.name === "name") current().name = value;
|
||||
else if (value === "") delete current()[input.name];
|
||||
else if (input.name === "type" || input.name === "bicycle_type") current()[input.name] = value;
|
||||
else current()[input.name] = value;
|
||||
save();
|
||||
}),
|
||||
|
||||
@@ -7,7 +7,7 @@ import { escapeHtml } from "/js/gpx.js";
|
||||
// Tracks & Points. Checked on every page load, not just right after a
|
||||
// share, so a share made while logged out is still waiting after login.
|
||||
const SHARED_CACHE = "shared-files";
|
||||
const KNOWN_EXTENSION = /\.(gpx|fit|geojson|zip)$/i;
|
||||
const KNOWN_EXTENSION = /\.(gpx|fit|tcx|geojson|zip)$/i;
|
||||
// Some apps share a bare name ("Track 12") — the upload only accepts
|
||||
// these extensions, so one is added from the file's type.
|
||||
const EXTENSION_BY_TYPE = {
|
||||
@@ -18,6 +18,7 @@ const EXTENSION_BY_TYPE = {
|
||||
"application/json": ".geojson",
|
||||
"application/zip": ".zip",
|
||||
"application/vnd.ant.fit": ".fit",
|
||||
"application/vnd.garmin.tcx+xml": ".tcx",
|
||||
};
|
||||
const DEFAULT_FOLDER = "Shared";
|
||||
|
||||
|
||||
+161
-1
@@ -1,7 +1,8 @@
|
||||
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { trailColorsAlong } from "/js/hiking_trails.js";
|
||||
|
||||
// Small-multiples profile chart: one row per metric the track actually has
|
||||
// (elevation always, speed/cadence/heart rate only when present — plenty of
|
||||
// (elevation always, speed/cadence/heart rate/power only when present — plenty of
|
||||
// GPX files have none of those), sharing one x-axis (distance) and one
|
||||
// crosshair. Elevation/speed/cadence/heart rate live on wildly different
|
||||
// scales, so this is deliberately several single-series charts stacked
|
||||
@@ -22,7 +23,11 @@ const SERIES = [
|
||||
{ key: "speed_kmh", label: "Speed", unit: "km/h", color: "#1baf7a", height: 70, area: false },
|
||||
{ key: "cadence_rpm", label: "Cadence", unit: "rpm", color: "#eda100", height: 70, area: false },
|
||||
{ key: "heart_rate_bpm", label: "Heart rate", unit: "bpm", color: "#e34948", height: 70, area: false },
|
||||
{ key: "power_w", label: "Power", unit: "W", color: "#7b4fd6", height: 70, area: false },
|
||||
];
|
||||
const BEST_DISTANCES_KM = [1, 5, 10, 21.0975, 42.195, 100];
|
||||
const BEST_POWER_SECS = [5, 60, 300, 1200, 3600];
|
||||
const CLIMB_TOLERANCE_M = 10; // a dip smaller than this doesn't end a climb
|
||||
|
||||
export class TrackProfilePanel {
|
||||
constructor(map) {
|
||||
@@ -63,6 +68,8 @@ export class TrackProfilePanel {
|
||||
|
||||
this._activeSeries = SERIES.filter((s) => this._profile.some((p) => typeof p[s.key] === "number"));
|
||||
this._activeSeries.forEach((series) => this._chartsContainer.appendChild(this._renderChart(series)));
|
||||
const trails = this._renderTrailBand();
|
||||
if (trails) this._chartsContainer.appendChild(trails);
|
||||
|
||||
// One shared strip below the whole stack, not per-chart — every chart
|
||||
// above uses the same x-scale (distance-position), so a separate axis
|
||||
@@ -71,6 +78,7 @@ export class TrackProfilePanel {
|
||||
this._xAxisStripEl.className = "profile-panel__xaxis";
|
||||
this._chartsContainer.appendChild(this._xAxisStripEl);
|
||||
this._renderXAxisTicks();
|
||||
this._chartsContainer.insertAdjacentHTML("beforeend", statsTables(this._profile, properties.activity_type));
|
||||
|
||||
this._chartsContainer.addEventListener("pointermove", this._onPointerMove);
|
||||
this._chartsContainer.addEventListener("pointerleave", this._onPointerLeave);
|
||||
@@ -122,6 +130,35 @@ export class TrackProfilePanel {
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
// A strip under the charts in the color of each marked hiking trail the
|
||||
// track follows (several stacked where trails share the path), blank off
|
||||
// trail. Point i's colors span from it to the next point.
|
||||
_renderTrailBand() {
|
||||
const colors = trailColorsAlong(this._profile);
|
||||
if (!colors) return null;
|
||||
const HEIGHT = 10;
|
||||
const toX = (d) => (d / this._maxDistance) * VIEWBOX_WIDTH;
|
||||
let rects = "";
|
||||
let start = 0;
|
||||
for (let i = 1; i < this._profile.length; i++) {
|
||||
const run = colors[start];
|
||||
if (i < this._profile.length - 1 && colors[i].join() === run.join()) continue;
|
||||
const [x1, x2] = [toX(this._profile[start].distance_meters), toX(this._profile[i].distance_meters)];
|
||||
run.forEach((color, j) => {
|
||||
rects += `<rect x="${x1.toFixed(1)}" width="${(x2 - x1).toFixed(1)}" y="${((j * HEIGHT) / run.length).toFixed(2)}" height="${(HEIGHT / run.length).toFixed(2)}" fill="${color}"></rect>`;
|
||||
});
|
||||
start = i;
|
||||
}
|
||||
const band = document.createElement("div");
|
||||
band.className = "profile-trails"; // not .profile-chart: those are the series rows _updateCrosshair walks
|
||||
// Colors are normalizedTrailColor's (hiking_trails.js): known words or hex only.
|
||||
band.innerHTML = `
|
||||
<div class="profile-chart__label">Marked trails</div>
|
||||
<svg viewBox="0 0 ${VIEWBOX_WIDTH} ${HEIGHT}" preserveAspectRatio="none" class="profile-chart__trails">${rects}</svg>
|
||||
`;
|
||||
return band;
|
||||
}
|
||||
|
||||
_renderXAxisToggle() {
|
||||
const row = document.createElement("div");
|
||||
row.className = "profile-panel__xaxis-toggle";
|
||||
@@ -213,6 +250,129 @@ export class TrackProfilePanel {
|
||||
}
|
||||
}
|
||||
|
||||
// Splits and best efforts under the charts, as two collapsed <details>.
|
||||
// Splits need times (a planned route has none); the biggest climb doesn't.
|
||||
function statsTables(profile, activityType) {
|
||||
const timed = profile.filter((p) => typeof p.elapsed_secs === "number");
|
||||
const total = profile.at(-1).distance_meters;
|
||||
const ride = /cycl|bik|ride/i.test(activityType || "");
|
||||
const hasHr = profile.some((p) => typeof p.heart_rate_bpm === "number");
|
||||
const hasPower = profile.some((p) => typeof p.power_w === "number");
|
||||
const pace = (secs, meters) => (ride ? `${((meters / secs) * 3.6).toFixed(1)} km/h` : `${formatPace(secs / (meters / 1000))} /km`);
|
||||
let html = "";
|
||||
|
||||
if (timed.length > 1) {
|
||||
const step = ride || total > 50000 ? 5000 : 1000;
|
||||
const rows = splits(timed, step).map(
|
||||
(s) => `<tr><td>${(s.to / 1000).toFixed(s.to % 1000 ? 1 : 0)} km</td><td>${formatDuration(s.secs)}</td><td>${pace(s.secs, s.meters)}</td><td>↑ ${Math.round(s.gain)} m</td>${hasHr ? `<td>${s.hr ? `${Math.round(s.hr)} bpm` : ""}</td>` : ""}${hasPower ? `<td>${s.power ? `${Math.round(s.power)} W` : ""}</td>` : ""}</tr>`,
|
||||
);
|
||||
html += `<details class="profile-stats"><summary>Splits (${step / 1000} km)</summary><table>${rows.join("")}</table></details>`;
|
||||
}
|
||||
|
||||
const best = [];
|
||||
if (timed.length > 1) {
|
||||
BEST_DISTANCES_KM.filter((km) => km * 1000 <= total).forEach((km) => {
|
||||
const secs = fastest(timed, km * 1000);
|
||||
if (secs) best.push([`${km === 21.0975 ? "Half marathon" : km === 42.195 ? "Marathon" : `${km} km`}`, `${formatDuration(secs)} · ${pace(secs, km * 1000)}`]);
|
||||
});
|
||||
}
|
||||
if (hasPower) {
|
||||
BEST_POWER_SECS.forEach((secs) => {
|
||||
const watts = bestPower(timed, secs);
|
||||
if (watts) best.push([`Power ${secs < 60 ? `${secs} s` : `${secs / 60} min`}`, `${Math.round(watts)} W`]);
|
||||
});
|
||||
}
|
||||
const climb = biggestClimb(profile);
|
||||
if (climb) best.push(["Biggest climb", `↑ ${Math.round(climb.gain)} m over ${(climb.meters / 1000).toFixed(1)} km (${((climb.gain / climb.meters) * 100).toFixed(1)} %)`]);
|
||||
if (best.length) html += `<details class="profile-stats"><summary>Best efforts</summary><table>${best.map(([k, v]) => `<tr><td>${k}</td><td>${v}</td></tr>`).join("")}</table></details>`;
|
||||
return html;
|
||||
}
|
||||
|
||||
// Every `step` meters: time, gain and average heart rate/power, the last
|
||||
// split shorter. Points are the first at/after each boundary.
|
||||
function splits(profile, step) {
|
||||
const out = [];
|
||||
let start = 0;
|
||||
for (let i = 1; i < profile.length; i++) {
|
||||
const last = i === profile.length - 1;
|
||||
if (!last && profile[i].distance_meters < (out.length + 1) * step) continue;
|
||||
const part = profile.slice(start, i + 1);
|
||||
let gain = 0;
|
||||
part.forEach((p, j) => {
|
||||
const climb = j > 0 && p.elevation_meters != null && part[j - 1].elevation_meters != null ? p.elevation_meters - part[j - 1].elevation_meters : 0;
|
||||
if (climb > 0) gain += climb;
|
||||
});
|
||||
const meters = profile[i].distance_meters - profile[start].distance_meters;
|
||||
const secs = profile[i].elapsed_secs - profile[start].elapsed_secs;
|
||||
if (meters > 0 && secs > 0) out.push({ to: profile[i].distance_meters, meters, secs, gain, hr: average(part, "heart_rate_bpm"), power: average(part, "power_w") });
|
||||
start = i;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function average(points, key) {
|
||||
const values = points.map((p) => p[key]).filter((v) => typeof v === "number");
|
||||
return values.length ? values.reduce((a, b) => a + b, 0) / values.length : null;
|
||||
}
|
||||
|
||||
// Shortest time over any stretch of at least `meters` (two pointers).
|
||||
function fastest(profile, meters) {
|
||||
let best = null;
|
||||
let j = 0;
|
||||
for (let i = 0; i < profile.length; i++) {
|
||||
while (j < profile.length && profile[j].distance_meters - profile[i].distance_meters < meters) j++;
|
||||
if (j === profile.length) break;
|
||||
const secs = profile[j].elapsed_secs - profile[i].elapsed_secs;
|
||||
if (secs > 0 && (best === null || secs < best)) best = secs;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// Highest average power over any `secs` window, time-weighted (samples
|
||||
// aren't evenly spaced); a missing reading counts as 0 W.
|
||||
function bestPower(profile, secs) {
|
||||
const energy = [0];
|
||||
for (let i = 1; i < profile.length; i++) energy.push(energy[i - 1] + (profile[i].power_w || 0) * (profile[i].elapsed_secs - profile[i - 1].elapsed_secs));
|
||||
let best = null;
|
||||
let j = 0;
|
||||
for (let i = 0; i < profile.length; i++) {
|
||||
while (j < profile.length && profile[j].elapsed_secs - profile[i].elapsed_secs < secs) j++;
|
||||
if (j === profile.length) break;
|
||||
const watts = (energy[j] - energy[i]) / (profile[j].elapsed_secs - profile[i].elapsed_secs);
|
||||
if (best === null || watts > best) best = watts;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// The largest rise from a low to a later high without a dip of more than
|
||||
// CLIMB_TOLERANCE_M in between.
|
||||
function biggestClimb(profile) {
|
||||
const points = profile.filter((p) => typeof p.elevation_meters === "number");
|
||||
if (points.length < 2) return null;
|
||||
let best = null;
|
||||
let low = points[0];
|
||||
let high = points[0];
|
||||
const finish = () => {
|
||||
const gain = high.elevation_meters - low.elevation_meters;
|
||||
if (gain >= CLIMB_TOLERANCE_M && gain > (best?.gain ?? 0)) best = { gain, meters: high.distance_meters - low.distance_meters };
|
||||
};
|
||||
for (const p of points) {
|
||||
if (p.elevation_meters > high.elevation_meters) high = p;
|
||||
else if (high.elevation_meters - p.elevation_meters > CLIMB_TOLERANCE_M) {
|
||||
finish();
|
||||
low = high = p;
|
||||
}
|
||||
if (p.elevation_meters < low.elevation_meters) low = high = p;
|
||||
}
|
||||
finish();
|
||||
return best;
|
||||
}
|
||||
|
||||
function formatPace(secsPerKm) {
|
||||
const minutes = Math.floor(secsPerKm / 60);
|
||||
return `${minutes}:${String(Math.round(secsPerKm % 60)).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function nearestIndex(profile, targetDistance) {
|
||||
// Distances are monotonically non-decreasing (see TrackStats.build_profile),
|
||||
// so a binary search would work too — linear is simpler and profiles here
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"application/geo+json", "application/json", ".geojson",
|
||||
"application/zip", ".zip",
|
||||
".fit", "application/vnd.ant.fit",
|
||||
".tcx", "application/vnd.garmin.tcx+xml",
|
||||
"application/xml", "text/xml",
|
||||
"application/octet-stream"
|
||||
]
|
||||
|
||||
@@ -155,6 +155,22 @@ class AppTest < Minitest::Test
|
||||
assert_equal 2, geojson["features"][0]["geometry"]["coordinates"][0].size
|
||||
end
|
||||
|
||||
def test_tcx_upload_and_fit_course_download
|
||||
tcx = <<~XML
|
||||
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"><Activities><Activity Sport="Biking"><Lap><Track>
|
||||
<Trackpoint><Time>2026-05-01T10:00:00Z</Time><Position><LatitudeDegrees>48.1</LatitudeDegrees><LongitudeDegrees>17.1</LongitudeDegrees></Position><AltitudeMeters>140</AltitudeMeters></Trackpoint>
|
||||
<Trackpoint><Time>2026-05-01T10:01:00Z</Time><Position><LatitudeDegrees>48.11</LatitudeDegrees><LongitudeDegrees>17.1</LongitudeDegrees></Position><AltitudeMeters>150</AltitudeMeters></Trackpoint>
|
||||
</Track></Lap></Activity></Activities></TrainingCenterDatabase>
|
||||
XML
|
||||
key = json_body(upload("ride.tcx", tcx))["paths"].first
|
||||
assert_equal "cycling", json_body(request.get(node_url(key)))["features"][0]["properties"]["activity_type"]
|
||||
|
||||
fit = request.get("#{node_url(key)}?download=fit&name=Ride", **logged_in_env)
|
||||
assert_equal 200, fit.status
|
||||
assert_includes fit.headers["Content-Disposition"], 'filename="Ride.fit"'
|
||||
assert_equal ".FIT", fit.body.byteslice(8, 4)
|
||||
end
|
||||
|
||||
def test_zip_upload_expands_into_its_track_entries_and_skips_the_rest
|
||||
zip_bytes = build_zip(
|
||||
"one.gpx" => File.read(fixture_path("sample.gpx")),
|
||||
|
||||
+25
-4
@@ -1,5 +1,6 @@
|
||||
require_relative "test_helper"
|
||||
require "maptool/fit"
|
||||
require "maptool/fit_course"
|
||||
|
||||
class FitTest < Minitest::Test
|
||||
def le32(n)
|
||||
@@ -71,16 +72,16 @@ class FitTest < Minitest::Test
|
||||
body << [0b00000001].pack("C") << [sport].pack("C")
|
||||
end
|
||||
|
||||
record_definition = [0, 0].pack("CC") + [20].pack("S<") + [5].pack("C") +
|
||||
record_definition = [0, 0].pack("CC") + [20].pack("S<") + [6].pack("C") +
|
||||
[0, 4, 0x85].pack("C3") + [1, 4, 0x85].pack("C3") +
|
||||
[3, 1, 0x02].pack("C3") + [4, 1, 0x02].pack("C3") + [6, 2, 0x84].pack("C3")
|
||||
[3, 1, 0x02].pack("C3") + [4, 1, 0x02].pack("C3") + [6, 2, 0x84].pack("C3") + [7, 2, 0x84].pack("C3")
|
||||
body << [0b01000000].pack("C") << record_definition
|
||||
|
||||
records.each do |r|
|
||||
body << [0b00000000].pack("C") << le32(r[:lat]) << le32(r[:lon])
|
||||
body << [r[:heart_rate] || 0xFF].pack("C") << [r[:cadence] || 0xFF].pack("C")
|
||||
speed_raw = r[:speed_mps] ? (r[:speed_mps] * 1000).round : 0xFFFF
|
||||
body << [speed_raw].pack("S<")
|
||||
body << [speed_raw].pack("S<") << [r[:power] || 0xFFFF].pack("S<")
|
||||
end
|
||||
|
||||
header = [12, 16, 0, 0].pack("C2S<") + le32(body.bytesize) + ".FIT"
|
||||
@@ -109,7 +110,7 @@ class FitTest < Minitest::Test
|
||||
|
||||
def test_profile_carries_heart_rate_cadence_and_speed_treating_0xff_as_absent
|
||||
path = write_activity_fit([
|
||||
{ lat: 100_000_000, lon: 200_000_000, heart_rate: 140, cadence: 80, speed_mps: 3.5 },
|
||||
{ lat: 100_000_000, lon: 200_000_000, heart_rate: 140, cadence: 80, speed_mps: 3.5, power: 250 },
|
||||
{ lat: 100_000_100, lon: 200_000_100 }, # no extras -> 0xFF/0xFFFF sentinels
|
||||
])
|
||||
|
||||
@@ -118,7 +119,27 @@ class FitTest < Minitest::Test
|
||||
assert_equal 140, profile[0]["heart_rate_bpm"]
|
||||
assert_equal 80, profile[0]["cadence_rpm"]
|
||||
assert_in_delta 3.5, profile[0]["speed_mps"]
|
||||
assert_equal 250, profile[0]["power_w"]
|
||||
assert_nil profile[1]["power_w"]
|
||||
assert_nil profile[1]["heart_rate_bpm"]
|
||||
assert_nil profile[1]["speed_mps"]
|
||||
end
|
||||
|
||||
def test_a_fit_course_reads_back_with_its_points_time_and_a_valid_crc
|
||||
coordinates = [[17.1, 48.1, 140.0], [17.11, 48.11, 150.0], [17.12, 48.1]]
|
||||
bytes = Maptool::FitCourse.encode(coordinates, name: "Loop", sport: "cycling", duration: 600)
|
||||
path = File.join(Dir.mktmpdir, "course.fit")
|
||||
File.binwrite(path, bytes)
|
||||
|
||||
feature = Maptool::Fit.to_geojson(path)["features"][0]
|
||||
assert_equal 600, feature["properties"]["duration_secs"]
|
||||
feature["geometry"]["coordinates"][0].zip(coordinates).each do |got, want|
|
||||
assert_in_delta want[0], got[0], 1e-6
|
||||
assert_in_delta want[1], got[1], 1e-6
|
||||
assert_in_delta want[2], got[2], 0.2 if want[2]
|
||||
end
|
||||
# CRC-16 over a whole FIT file (its own CRC included) comes out 0.
|
||||
assert_equal 0, Maptool::FitCourse.send(:crc, bytes)
|
||||
assert_equal 0xBB3D, Maptool::FitCourse.send(:crc, "123456789")
|
||||
end
|
||||
end
|
||||
+23
-3
@@ -95,13 +95,19 @@ class RoutingTest < Minitest::Test
|
||||
end
|
||||
|
||||
def test_vehicle_profiles_are_validated_and_stored
|
||||
assert_equal %w[car camper], Maptool::Routing.vehicles(@data).map { |v| v[:id] }
|
||||
assert_equal %w[car camper bike mtb run hike], Maptool::Routing.vehicles(@data).map { |v| v[:id] }
|
||||
assert_equal "Car", Maptool::Routing.vehicle(@data, "nope")[:name]
|
||||
|
||||
Maptool::Routing.save_vehicles(@data, [{ "id" => "car", "name" => "Car", "height" => "" },
|
||||
{ "id" => "van", "name" => "Van", "height" => "3.4", "weight" => "4.2" }])
|
||||
assert_equal({ id: "van", name: "Van", height: 3.4, weight: 4.2 }, Maptool::Routing.vehicle(@data, "van"))
|
||||
assert_equal({ id: "car", name: "Car" }, Maptool::Routing.vehicle(@data, "car"))
|
||||
assert_equal({ id: "van", name: "Van", type: "car", height: 3.4, weight: 4.2 }, Maptool::Routing.vehicle(@data, "van"))
|
||||
assert_equal({ id: "car", name: "Car", type: "car" }, Maptool::Routing.vehicle(@data, "car"))
|
||||
assert_equal %w[car van], Maptool::Routing.vehicles(@data).map { |v| v[:id] } # deleted bike/foot stay deleted
|
||||
Maptool::Routing.save_vehicles(@data, [{ "id" => "b", "name" => "B", "type" => "bicycle", "bicycle_type" => "Road", "speed" => "28", "height" => "" }])
|
||||
assert_equal({ id: "b", name: "B", type: "bicycle", bicycle_type: "Road", speed: 28.0 }, Maptool::Routing.vehicle(@data))
|
||||
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "X", "type" => "boat" }]) }
|
||||
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "X", "type" => "bicycle", "bicycle_type" => "Tandem" }]) }
|
||||
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "X", "type" => "foot", "sac" => "7" }]) }
|
||||
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "X", "height" => "30" }]) }
|
||||
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "" }]) }
|
||||
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, []) }
|
||||
@@ -151,6 +157,20 @@ class RoutingTest < Minitest::Test
|
||||
assert_includes request, "/trace_attributes"
|
||||
end
|
||||
|
||||
def test_bicycle_and_foot_use_their_own_costing_without_the_country_lookup
|
||||
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 }, legs: [{ shape: "wdg|xA{ubdQc@w@", maneuvers: [] }] })
|
||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
|
||||
route = Maptool::Routing.route(url, [[1, 2], [3, 4]], Maptool::Routing::ACTIVE_VEHICLES[2], { "tolls" => true })
|
||||
assert_nil route[:properties][:countries]
|
||||
end
|
||||
assert_includes request, %("costing_options":{"pedestrian":{"walking_speed":10.0,"max_hiking_difficulty":2}})
|
||||
|
||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
|
||||
Maptool::Routing.route(url, [[1, 2], [3, 4]], Maptool::Routing::ACTIVE_VEHICLES[1])
|
||||
end
|
||||
assert_includes request, %("costing_options":{"bicycle":{"bicycle_type":"Mountain"}})
|
||||
end
|
||||
|
||||
def test_isochrone_asks_valhalla_for_each_time_and_checks_them
|
||||
reply = JSON.generate(type: "FeatureCollection", features: [])
|
||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
|
||||
|
||||
+42
-7
@@ -59,12 +59,12 @@
|
||||
<strong>Tracks & Points</strong>
|
||||
<div class="gpx-panel__actions">
|
||||
<button type="button" class="gpx-panel__action" data-action="new-folder" title="New folder" aria-label="New folder"></button>
|
||||
<button type="button" class="gpx-panel__action" data-action="upload" title="Upload GPX/FIT/GeoJSON file" aria-label="Upload GPX/FIT/GeoJSON file"></button>
|
||||
<button type="button" class="gpx-panel__action" data-action="upload" title="Upload GPX/FIT/TCX/GeoJSON file" aria-label="Upload GPX/FIT/TCX/GeoJSON file"></button>
|
||||
<button type="button" class="gpx-panel__close" aria-label="Close">×</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<input type="file" class="gpx-file-input" accept=".gpx,.fit,.geojson,.zip" multiple hidden>
|
||||
<input type="file" class="gpx-file-input" accept=".gpx,.fit,.tcx,.geojson,.zip" multiple hidden>
|
||||
<p class="gpx-upload__status" hidden></p>
|
||||
|
||||
<div class="gpx-tree"></div>
|
||||
@@ -158,11 +158,46 @@
|
||||
</div>
|
||||
<fieldset class="route-panel__vehicle" hidden>
|
||||
<label class="route-panel__vehicle-name">Name <input type="text" name="name" maxlength="40"></label>
|
||||
<label>Height <input type="number" name="height" step="0.1" min="1" max="6" placeholder="–"> m</label>
|
||||
<label>Width <input type="number" name="width" step="0.1" min="1" max="4" placeholder="–"> m</label>
|
||||
<label>Length <input type="number" name="length" step="0.5" min="2" max="25" placeholder="–"> m</label>
|
||||
<label>Weight <input type="number" name="weight" step="0.1" min="0.5" max="60" placeholder="–"> t</label>
|
||||
<p class="route-panel__vehicle-hint">Empty: no limit. Over 3.5 t routes as a truck.</p>
|
||||
<label>Type
|
||||
<select name="type">
|
||||
<option value="car">Car</option>
|
||||
<option value="bicycle">Bicycle</option>
|
||||
<option value="foot">On foot</option>
|
||||
</select>
|
||||
</label>
|
||||
<!-- data-for: the types a field applies to, the rest are hidden. -->
|
||||
<label data-for="car">Height <input type="number" name="height" step="0.1" min="1" max="6" placeholder="–"> m</label>
|
||||
<label data-for="car">Width <input type="number" name="width" step="0.1" min="1" max="4" placeholder="–"> m</label>
|
||||
<label data-for="car">Length <input type="number" name="length" step="0.5" min="2" max="25" placeholder="–"> m</label>
|
||||
<label data-for="car">Weight <input type="number" name="weight" step="0.1" min="0.5" max="60" placeholder="–"> t</label>
|
||||
<label data-for="bicycle">Bike
|
||||
<select name="bicycle_type">
|
||||
<option value="Road">Road</option>
|
||||
<option value="Hybrid">Trekking</option>
|
||||
<option value="Cross">Gravel</option>
|
||||
<option value="Mountain">MTB</option>
|
||||
</select>
|
||||
</label>
|
||||
<label data-for="bicycle foot">Speed <input type="number" name="speed" step="0.5" min="1" max="60" placeholder="–"> km/h</label>
|
||||
<label data-for="bicycle foot">Hills
|
||||
<select name="hills">
|
||||
<option value="">Default</option>
|
||||
<option value="0">Avoid</option>
|
||||
<option value="1">Seek</option>
|
||||
</select>
|
||||
</label>
|
||||
<label data-for="foot">Up to
|
||||
<select name="sac">
|
||||
<option value="">T1 hiking</option>
|
||||
<option value="2">T2 mountain hiking</option>
|
||||
<option value="3">T3 demanding</option>
|
||||
<option value="4">T4 alpine</option>
|
||||
<option value="5">T5 demanding alpine</option>
|
||||
<option value="6">T6 difficult alpine</option>
|
||||
</select>
|
||||
</label>
|
||||
<p class="route-panel__vehicle-hint" data-for="car">Empty: no limit. Over 3.5 t routes as a truck.</p>
|
||||
<p class="route-panel__vehicle-hint" data-for="bicycle foot">Empty speed: the usual one for the bike or walking.</p>
|
||||
<button type="button" data-action="vehicle-add">+ New vehicle</button>
|
||||
<button type="button" data-action="vehicle-delete">Delete</button>
|
||||
</fieldset>
|
||||
|
||||
Reference in new issue
Block a user