Class: F4R::Decoder

Inherits:
Object
  • Object
show all
Defined in:
lib/f4r.rb

Overview

Decode/Read binary FIT file and return data in a Registry.

Class Method Summary collapse

Class Method Details

.decode(file_name) ⇒ Object

FIT binary file decoder/reader by providing data in a human readable format [Hash]

Parameters:

  • file_name (String)

    path for file to be read



1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
# File 'lib/f4r.rb', line 1672

def self.decode(file_name)
  io = ::File.open(file_name, 'rb')

  begin
    until io.eof?
      offset = io.pos

      registry = Registry.new(Definition::Header.read(io))

      while io.pos < offset + registry.header.file_size
        record_header = Definition::RecordHeader.read(io)

        local_message_number = record_header.local_message_type.snapshot

        if record_header.for_new_definition?
          record_definition = Definition::Record.read(io)

          registry.definitions << {
            local_message_number: local_message_number,
            message_name: record_definition.global_message[:name],
            header: record_header,
            record: record_definition
          }
        else
          record_definition = registry.definitions.reverse.find do |d|
            d[:local_message_number] == local_message_number
          end[:record]

          data = record_definition.read_data(io)

          record = Record.new(record_definition.global_message[:name])

          record_definition.data_fields.each do |field|
            value = data[field.number].snapshot
            record.set_field_value(field, value)
          end

          registry.add record, local_message_number
        end
      end

      io.seek(2, :CUR)
    end
  ensure
    io.close
  end

  Log.info "Finished reading #{file_name} file."

  registry
end