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 : one Feature per file, geometry MultiLineString, "kind" => # "track". Only "record" messages (the track points) and one "sport"/ # "session" field (the activity type) are read — FIT also carries laps, # 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 FIELD_POSITION_LAT = 0 FIELD_POSITION_LONG = 1 FIELD_ALTITUDE = 2 FIELD_HEART_RATE = 3 FIELD_CADENCE = 4 FIELD_SPEED = 6 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) 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] } extras = result.records.map { |r| { speed_mps: r[:speed_mps], cadence_rpm: r[:cadence], heart_rate_bpm: r[:heart_rate] } } { "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)), } end private_class_method :track_feature 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 = [] 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) 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) activity_type ||= sport end end ParseResult.new(records, activity_type) 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) sport = nil if definition.global_mesg_num == RECORD_MESSAGE_NUM record = extract_record(data, offset, definition) records << record if record 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) pos = offset definition.fields.each do |field_num, size| if field_num == target_field_num value = unpack_int(data, pos, size, definition.little_endian, signed: false) return SPORT_NAMES[value] end pos += size end nil end 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 # declared size without being interpreted. def self.extract_record(data, offset, definition) lat = lon = altitude = timestamp = heart_rate = cadence = speed = 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) 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 { coordinate: coordinate, time: time, heart_rate: heart_rate, cadence: cadence, speed_mps: speed_mps } 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