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 COURSE_POINT = [32, [[254, 0x84, "S<"], [1, 0x86, "L<"], [2, 0x85, "l<"], [3, 0x85, "l<"], [4, 0x86, "L<"], [5, 0x00, "C"], [6, 0x07, "a16"]]].freeze DEFAULT_SPEED = 4.0 # m/s, when the line has no time of its own # FIT course_point types, guessed from a point's name/category/icon # (English and Slovak words); anything else is generic (0). POINT_TYPES = [ [3, /water|spring|fountain|drink|voda|prame|studni/i], [4, /food|restaurant|caf|shop|bakery|jedlo|reštaur|krčm|obchod/i], [9, /first.?aid|hospital|pharmac|doctor|lekár|nemocn/i], [5, /danger|warning|caution|pozor|nebezpe/i], [1, /summit|peak|top\b|vrch|štít|kopec/i], [2, /valley|saddle|pass\b|údoli|sedlo/i], ].freeze # coordinates: [[lon, lat(, ele)], ...]; duration: seconds or nil; # points: [{ coordinate:, name:, hint: }] shown along the course (each # placed at the nearest point of the line). def self.encode(coordinates, name:, sport: nil, duration: nil, points: []) 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 unless points.empty? body << definition(5, COURSE_POINT) at_index = ->(i) { start + (total.positive? ? duration * distances[i] / total : 0).round } points.map { |point| [nearest(coordinates, point[:coordinate]), point] }.sort_by(&:first).each_with_index do |(i, point), n| type = POINT_TYPES.find { |_, pattern| point[:hint].to_s.match?(pattern) }&.first || 0 label = point[:name].to_s.byteslice(0, 15).scrub("") body << data(5, COURSE_POINT, [n, at_index.(i), *semicircles(point[:coordinate]), (distances[i] * 100).round, type, label]) end end body << data(3, EVENT, [finish, 0, 9]) # timer, stop_disable_all header = [14, 0x10, 2132, body.bytesize].pack("CCS 1, "S<" => 2, "L<" => 4, "l<" => 4, "a16" => 16, "a32" => 32 }.freeze def self.definition(local, (global, fields)) [0x40 | local, 0, 0, global, fields.size].pack("CCCS> 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