263 lines
11 KiB
Ruby
263 lines
11 KiB
Ruby
require_relative "track_stats"
|
|
|
|
module Maptool
|
|
# Converts a Garmin FIT file (binary — see https://developer.garmin.com/fit/)
|
|
# to a GeoJSON FeatureCollection, in the same shape Gpx.to_geojson produces
|
|
# for a <trk>: one Feature per file, geometry MultiLineString, "kind" =>
|
|
# "track". Only "record" messages (the track points) and one "sport"/
|
|
# "session" field (the activity type) and lap start times are read — FIT also carries
|
|
# events, device info, developer fields, none of which this app has
|
|
# anywhere to show, so they're skipped by byte-length rather than
|
|
# interpreted.
|
|
module Fit
|
|
class ParseError < StandardError; end
|
|
|
|
FIT_EPOCH = Time.utc(1989, 12, 31).to_i
|
|
RECORD_MESSAGE_NUM = 20
|
|
SPORT_MESSAGE_NUM = 12
|
|
SESSION_MESSAGE_NUM = 18
|
|
LAP_MESSAGE_NUM = 19
|
|
FIELD_LAP_START_TIME = 2
|
|
FIELD_POSITION_LAT = 0
|
|
FIELD_POSITION_LONG = 1
|
|
FIELD_ALTITUDE = 2
|
|
FIELD_HEART_RATE = 3
|
|
FIELD_CADENCE = 4
|
|
FIELD_SPEED = 6
|
|
FIELD_POWER = 7
|
|
FIELD_TEMPERATURE = 13
|
|
FIELD_TIMESTAMP = 253
|
|
FIELD_ENHANCED_ALTITUDE = 78
|
|
SPORT_FIELD_BY_MESSAGE = { SPORT_MESSAGE_NUM => 0, SESSION_MESSAGE_NUM => 5 }.freeze
|
|
SEMICIRCLE_TO_DEGREES = 180.0 / (2**31)
|
|
|
|
# Garmin's own sport enum (github.com/garmin/fit-python-sdk's
|
|
# profile.py, `types.sport`) — not exhaustive of every value Garmin has
|
|
# ever defined (rare ones omitted), but every mainstream activity type.
|
|
SPORT_NAMES = {
|
|
0 => "generic", 1 => "running", 2 => "cycling", 3 => "transition",
|
|
4 => "fitness_equipment", 5 => "swimming", 6 => "basketball", 7 => "soccer",
|
|
8 => "tennis", 9 => "american_football", 10 => "training", 11 => "walking",
|
|
12 => "cross_country_skiing", 13 => "alpine_skiing", 14 => "snowboarding",
|
|
15 => "rowing", 16 => "mountaineering", 17 => "hiking", 18 => "multisport",
|
|
19 => "paddling", 20 => "flying", 21 => "e_biking", 22 => "motorcycling",
|
|
23 => "boating", 24 => "driving", 25 => "golf", 30 => "inline_skating",
|
|
31 => "rock_climbing", 32 => "sailing", 33 => "ice_skating", 37 => "stand_up_paddleboarding",
|
|
38 => "surfing", 39 => "wakeboarding", 40 => "water_skiing", 41 => "kayaking",
|
|
49 => "baseball", 53 => "diving", 62 => "hiit", 87 => "geocaching", 88 => "canoeing"
|
|
}.freeze
|
|
|
|
Definition = Struct.new(:global_mesg_num, :little_endian, :fields, :total_size)
|
|
ParseResult = Struct.new(:records, :activity_type, :lap_starts)
|
|
|
|
def self.kinds(path)
|
|
to_geojson(path)["features"].empty? ? [] : ["track"]
|
|
rescue ParseError
|
|
[]
|
|
end
|
|
|
|
def self.to_geojson(path)
|
|
result = parse(File.binread(path))
|
|
features = result.records.empty? ? [] : [track_feature(result)]
|
|
{ "type" => "FeatureCollection", "features" => features }
|
|
end
|
|
|
|
def self.track_feature(result)
|
|
coordinates = result.records.map { |r| r[:coordinate] }
|
|
laps = lap_indices(result)
|
|
extras = result.records.map { |r| { speed_mps: r[:speed_mps], cadence_rpm: r[:cadence], heart_rate_bpm: r[:heart_rate], power_w: r[:power], temperature_c: r[:temperature] } }
|
|
|
|
{
|
|
"type" => "Feature",
|
|
"geometry" => { "type" => "MultiLineString", "coordinates" => [coordinates] },
|
|
"properties" => { "kind" => "track", "name" => nil, "activity_type" => result.activity_type }
|
|
.merge(TrackStats.compute(coordinates, times: result.records.map { |r| r[:time] }))
|
|
.merge("profile" => TrackStats.build_profile(coordinates, times: result.records.map { |r| r[:time] }, extras: extras))
|
|
.merge(laps ? { "laps" => laps } : {}),
|
|
}
|
|
end
|
|
private_class_method :track_feature
|
|
|
|
# Index of the first record of each lap, nil for a single lap.
|
|
def self.lap_indices(result)
|
|
indices = result.lap_starts.sort.map { |t| result.records.index { |r| r[:time] && r[:time].to_i >= t } }.compact.uniq
|
|
indices[0] = 0 if indices.any?
|
|
indices.size > 1 ? indices : nil
|
|
end
|
|
private_class_method :lap_indices
|
|
|
|
def self.parse(data)
|
|
raise ParseError, "not a FIT file" if data.bytesize < 12 || data.byteslice(8, 4) != ".FIT"
|
|
|
|
header_size = data.getbyte(0)
|
|
data_size = data.byteslice(4, 4).unpack1("L<")
|
|
data_end = header_size + data_size
|
|
raise ParseError, "truncated file" if data_end > data.bytesize
|
|
|
|
offset = header_size
|
|
definitions = {}
|
|
records = []
|
|
lap_starts = []
|
|
activity_type = nil
|
|
|
|
while offset < data_end
|
|
header = data.getbyte(offset)
|
|
offset += 1
|
|
|
|
if header & 0x80 != 0
|
|
local_type = (header >> 5) & 0x3
|
|
definition = definitions[local_type] or raise ParseError, "data message before its definition"
|
|
offset, sport = read_data_message(data, offset, definition, records, lap_starts)
|
|
activity_type ||= sport
|
|
elsif header & 0x40 != 0
|
|
local_type = header & 0x0F
|
|
definition, offset = read_definition(data, offset, header & 0x20 != 0)
|
|
definitions[local_type] = definition
|
|
else
|
|
local_type = header & 0x0F
|
|
definition = definitions[local_type] or raise ParseError, "data message before its definition"
|
|
offset, sport = read_data_message(data, offset, definition, records, lap_starts)
|
|
activity_type ||= sport
|
|
end
|
|
end
|
|
|
|
ParseResult.new(records, activity_type, lap_starts)
|
|
rescue ArgumentError, NoMethodError => e
|
|
raise ParseError, e.message
|
|
end
|
|
private_class_method :parse
|
|
|
|
def self.read_definition(data, offset, has_developer_fields)
|
|
architecture = data.getbyte(offset + 1)
|
|
little_endian = architecture.zero?
|
|
global_mesg_num = data.byteslice(offset + 2, 2).unpack1(little_endian ? "S<" : "S>")
|
|
num_fields = data.getbyte(offset + 4)
|
|
offset += 5
|
|
|
|
fields = []
|
|
num_fields.times do
|
|
fields << [data.getbyte(offset), data.getbyte(offset + 1)]
|
|
offset += 3
|
|
end
|
|
|
|
if has_developer_fields
|
|
num_dev_fields = data.getbyte(offset)
|
|
offset += 1
|
|
num_dev_fields.times do
|
|
fields << [nil, data.getbyte(offset + 1)]
|
|
offset += 3
|
|
end
|
|
end
|
|
|
|
total_size = fields.sum { |_field_num, size| size }
|
|
[Definition.new(global_mesg_num, little_endian, fields, total_size), offset]
|
|
end
|
|
private_class_method :read_definition
|
|
|
|
# Returns [next_offset, sport_name_or_nil] — the latter only set when
|
|
# this message happens to be the one sport/session message carrying it.
|
|
def self.read_data_message(data, offset, definition, records, lap_starts)
|
|
sport = nil
|
|
if definition.global_mesg_num == RECORD_MESSAGE_NUM
|
|
record = extract_record(data, offset, definition)
|
|
records << record if record
|
|
elsif definition.global_mesg_num == LAP_MESSAGE_NUM
|
|
start = field_value(data, offset, definition, FIELD_LAP_START_TIME)
|
|
lap_starts << FIT_EPOCH + start if start && !invalid?(start, 4)
|
|
elsif (field_num = SPORT_FIELD_BY_MESSAGE[definition.global_mesg_num])
|
|
sport = extract_sport(data, offset, definition, field_num)
|
|
end
|
|
[offset + definition.total_size, sport]
|
|
end
|
|
private_class_method :read_data_message
|
|
|
|
def self.extract_sport(data, offset, definition, target_field_num)
|
|
value = field_value(data, offset, definition, target_field_num)
|
|
value && SPORT_NAMES[value]
|
|
end
|
|
|
|
def self.field_value(data, offset, definition, target_field_num)
|
|
pos = offset
|
|
definition.fields.each do |field_num, size|
|
|
return unpack_int(data, pos, size, definition.little_endian, signed: false) if field_num == target_field_num
|
|
|
|
pos += size
|
|
end
|
|
nil
|
|
end
|
|
private_class_method :field_value
|
|
private_class_method :extract_sport
|
|
|
|
# Only reads the fields the map/its properties need; every other field
|
|
# 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 = power = temperature = nil
|
|
pos = offset
|
|
|
|
definition.fields.each do |field_num, size|
|
|
case field_num
|
|
when FIELD_POSITION_LAT
|
|
lat = unpack_int(data, pos, size, definition.little_endian, signed: true)
|
|
when FIELD_POSITION_LONG
|
|
lon = unpack_int(data, pos, size, definition.little_endian, signed: true)
|
|
when FIELD_ALTITUDE, FIELD_ENHANCED_ALTITUDE
|
|
altitude ||= unpack_int(data, pos, size, definition.little_endian, signed: false)
|
|
when FIELD_TIMESTAMP
|
|
timestamp = unpack_int(data, pos, size, definition.little_endian, signed: false)
|
|
when FIELD_HEART_RATE
|
|
heart_rate = unpack_int(data, pos, size, definition.little_endian, signed: false)
|
|
when FIELD_CADENCE
|
|
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)
|
|
when FIELD_TEMPERATURE
|
|
temperature = unpack_int(data, pos, size, definition.little_endian, signed: true)
|
|
end
|
|
pos += size
|
|
end
|
|
|
|
return nil if lat.nil? || lon.nil? || invalid?(lat, 4) || invalid?(lon, 4)
|
|
|
|
coordinate = [lon * SEMICIRCLE_TO_DEGREES, lat * SEMICIRCLE_TO_DEGREES]
|
|
coordinate << (altitude / 5.0 - 500) if altitude && !invalid?(altitude, 2) && !invalid?(altitude, 4)
|
|
time = Time.at(FIT_EPOCH + timestamp).utc if timestamp && !invalid?(timestamp, 4)
|
|
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)
|
|
temperature = nil if temperature.nil? || invalid?(temperature, 1)
|
|
|
|
{ coordinate: coordinate, time: time, heart_rate: heart_rate, cadence: cadence, speed_mps: speed_mps, power: power, temperature: temperature }
|
|
end
|
|
private_class_method :extract_record
|
|
|
|
UNPACK_FORMATS = {
|
|
[1, true] => "c", [1, false] => "C",
|
|
[2, true] => "s", [2, false] => "S",
|
|
[4, true] => "l", [4, false] => "L",
|
|
[8, true] => "q", [8, false] => "Q",
|
|
}.freeze
|
|
|
|
def self.unpack_int(data, offset, size, little_endian, signed:)
|
|
format = UNPACK_FORMATS[[size, signed]]
|
|
return nil unless format
|
|
|
|
format += little_endian ? "<" : ">" if size > 1
|
|
data.byteslice(offset, size)&.unpack1(format)
|
|
end
|
|
private_class_method :unpack_int
|
|
|
|
# FIT's per-base-type "field not present" sentinel: all bits set for an
|
|
# unsigned/positive-only reading, the same pattern for signed. Good
|
|
# enough for the fields this cares about without needing every base
|
|
# type's exact invalid value.
|
|
def self.invalid?(value, size)
|
|
value == (1 << (size * 8 - 1)) - 1 || value == -1 || value == (1 << (size * 8)) - 1
|
|
end
|
|
private_class_method :invalid?
|
|
end
|
|
end
|