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
CI / check (push) Successful in 19s
CI / deploy (push) Successful in 18s

This commit is contained in:
randy committed 2026-11-16 12:18:06 +01:00
1 parent 4c704045c5
commit f8755ea65a
21 files changed
+634 -40

No files matched your search

+8 -4
View File
@@ -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
+86
View File
@@ -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
View File
@@ -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
+4 -1
View File
@@ -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
View File
@@ -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"]
+69
View File
@@ -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
+2 -2
View File
@@ -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