Module: F4R::Encoder

Defined in:
lib/f4r.rb

Overview

FIT binary file Encoder/Writer

Defined Under Namespace

Classes: RegistryBuilder

Class Method Summary collapse

Class Method Details

.encode(file_name, records, source) ⇒ File

Encode/Write binary FIT file

Parameters:

  • file_name (String)

    path for new FIT file

  • records (Hash, Registry)
  • source (String)

    Optional source FIT file to be used as a reference for structuring the binary data.

Returns:

  • (File)

    binary FIT file



1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
# File 'lib/f4r.rb', line 1366

def self.encode(file_name, records, source)
  io = ::File.open(file_name, 'wb+')

  if records.is_a? Registry
    registry = records
  else
    registry = RegistryBuilder.new(records, source).registry
  end

  begin
    start_pos = registry.header.header_size

    io.seek(start_pos)

    local_messages = []
    last_local_message_number = nil
    registry.records.each do |record|

      local_message = local_messages.find do |lm|
        lm[:local_message_number] == record[:local_message_number] &&
          lm[:message_name] == record[:message_name]
      end

      unless local_message ||
          record[:local_message_number] == last_local_message_number

        local_messages << {
          local_message_number: record[:local_message_number],
          message_name: record[:message_name]
        }

        definition = registry.definition(record)
        definition[:header].write(io)
        definition[:record].write(io)
      end

      definition = registry.definition(record)
      definition[:header].write_data_header(io, record)
      definition[:record].write_data(io, record)

      last_local_message_number = record[:local_message_number]
    end

    end_pos = io.pos
    BinData::Uint16le.new(CRC16.crc(IO.binread(io, end_pos, start_pos))).write(io)
    registry.header.data_size = end_pos - start_pos
    io.rewind
    registry.header.write(io)
  ensure
    io.close
  end

  file_name
end