python-fitparse 2.8.0__py3-none-any.whl → 2.12.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fitparse/base.py CHANGED
@@ -62,9 +62,34 @@ class DeveloperDataMixin:
62
62
  dev_data_index = message.get_raw_value('developer_data_index')
63
63
  field_def_num = message.get_raw_value('field_definition_number')
64
64
  base_type_id = message.get_raw_value('fit_base_type_id')
65
- field_name = message.get_raw_value('field_name') or "unnamed_dev_field_%s" % field_def_num
65
+ field_name = message.get_raw_value('field_name')
66
66
  units = message.get_raw_value("units")
67
67
  native_field_num = message.get_raw_value('native_field_num')
68
+ native_mesg_num = message.get_raw_value('native_mesg_num')
69
+ scale = message.get_raw_value('scale')
70
+ offset = message.get_raw_value('offset')
71
+
72
+ for name, value in (('developer_data_index', dev_data_index),
73
+ ('field_definition_number', field_def_num),
74
+ ('fit_base_type_id', base_type_id)):
75
+ if not isinstance(value, int):
76
+ raise FitParseError(
77
+ "Invalid %s=%r in developer field description" % (name, value))
78
+ if not isinstance(field_name, str) or not field_name:
79
+ field_name = "unnamed_dev_field_%s" % field_def_num
80
+ if not isinstance(units, str):
81
+ units = None
82
+ if not isinstance(scale, int):
83
+ scale = None
84
+ if not isinstance(offset, int):
85
+ offset = None
86
+ base_type = BASE_TYPES.get(base_type_id)
87
+ if base_type is None:
88
+ warnings.warn(
89
+ "Unknown base type %d for developer field %d; falling back to byte encoding."
90
+ % (base_type_id, field_def_num)
91
+ )
92
+ base_type = BASE_TYPE_BYTE
68
93
 
69
94
  if dev_data_index not in self.dev_types:
70
95
  if self.check_developer_data:
@@ -81,9 +106,12 @@ class DeveloperDataMixin:
81
106
  fields[field_def_num] = DevField(
82
107
  dev_data_index=dev_data_index,
83
108
  def_num=field_def_num,
84
- type=BASE_TYPES[base_type_id],
109
+ type=base_type,
85
110
  name=field_name,
86
111
  units=units,
112
+ scale=scale,
113
+ offset=offset,
114
+ native_mesg_num=native_mesg_num,
87
115
  native_field_num=native_field_num
88
116
  )
89
117
 
@@ -121,11 +149,14 @@ class DeveloperDataMixin:
121
149
  class FitFileDecoder(DeveloperDataMixin):
122
150
  """Basic decoder for fit files"""
123
151
 
124
- def __init__(self, fileish, *args, check_crc=True, data_processor=None, **kwargs):
152
+ def __init__(self, fileish, *args, check_crc=True, allow_truncated=False, data_processor=None, **kwargs):
125
153
  self._file = fileish_open(fileish, 'rb')
126
154
 
127
155
  self.check_crc = check_crc
156
+ self.allow_truncated = allow_truncated
157
+ self.truncated = None
128
158
  self._crc = None
159
+ self._in_header = False
129
160
 
130
161
  # Get total filesize
131
162
  self._file.seek(0, os.SEEK_END)
@@ -180,11 +211,12 @@ class FitFileDecoder(DeveloperDataMixin):
180
211
  return unpacked if (len(unpacked) > 1) or always_tuple else unpacked[0]
181
212
 
182
213
  def _read_and_assert_crc(self, allow_zero=False):
183
- # CRC Calculation is little endian from SDK
184
- # TODO - How to handle the case of unterminated file? Error out and have user retry with check_crc=false?
185
- crc_computed, crc_read = self._crc.value, self._read_struct(Crc.FMT)
186
214
  if not self.check_crc:
215
+ # A missing or short CRC at the end of the file is tolerated when checking is off
216
+ self._file.read(struct.calcsize(Crc.FMT))
187
217
  return
218
+ # CRC Calculation is little endian from SDK
219
+ crc_computed, crc_read = self._crc.value, self._read_struct(Crc.FMT)
188
220
  if crc_computed == crc_read or (allow_zero and crc_read == 0):
189
221
  return
190
222
  raise FitCRCError('CRC Mismatch [computed: {}, read: {}]'.format(
@@ -203,6 +235,7 @@ class FitFileDecoder(DeveloperDataMixin):
203
235
  self._crc = Crc()
204
236
  self._local_mesgs = {}
205
237
 
238
+ segment_start = self._file.tell()
206
239
  header_data = self._read(12)
207
240
  if header_data[8:12] != b'.FIT':
208
241
  raise FitHeaderError("Invalid .FIT File Header")
@@ -230,12 +263,26 @@ class FitFileDecoder(DeveloperDataMixin):
230
263
 
231
264
  # After we've consumed the header, set the bytes left to be read
232
265
  self._bytes_left = data_size
266
+ self._segment_end = segment_start + header_size + data_size + struct.calcsize(Crc.FMT)
233
267
 
234
268
  def _parse_message(self):
269
+ try:
270
+ return self._read_message()
271
+ except FitEOFError as e:
272
+ if not (self.allow_truncated and self._truncated()):
273
+ raise
274
+ self.truncated = e
275
+ self._complete = True
276
+ self.close()
277
+ return None
278
+
279
+ def _truncated(self):
280
+ return self._in_header or self._filesize < self._segment_end
281
+
282
+ def _read_message(self):
235
283
  # When done, calculate the CRC and return None
236
284
  if self._bytes_left <= 0:
237
- # Don't assert CRC if requested not
238
- if not self._complete and self.check_crc:
285
+ if not self._complete:
239
286
  self._read_and_assert_crc()
240
287
 
241
288
  if self._file.tell() >= self._filesize:
@@ -244,8 +291,10 @@ class FitFileDecoder(DeveloperDataMixin):
244
291
  return None
245
292
 
246
293
  # Still have data left in the file - assuming chained fit files
294
+ self._in_header = True
247
295
  self._parse_file_header()
248
- return self._parse_message()
296
+ self._in_header = False
297
+ return self._read_message()
249
298
 
250
299
  header = self._parse_message_header()
251
300
 
@@ -296,23 +345,17 @@ class FitFileDecoder(DeveloperDataMixin):
296
345
  if (field_size % base_type.size) != 0:
297
346
  warnings.warn(
298
347
  "Invalid field size %d for field '%s' of type '%s' (expected a multiple of %d); falling back to byte encoding." % (
299
- field_size, field.name, base_type.name, base_type.size)
348
+ field_size, field.name if field else 'unknown_%d' % field_def_num,
349
+ base_type.name, base_type.size)
300
350
  )
301
351
  base_type = BASE_TYPE_BYTE
302
352
 
303
- # If the field has components that are accumulators
304
- # start recording their accumulation at 0
305
- if field and field.components:
306
- for component in field.components:
307
- if component.accumulate:
308
- accumulators = self._accumulators.setdefault(global_mesg_num, {})
309
- accumulators[component.def_num] = 0
310
-
311
353
  field_defs.append(FieldDefinition(
312
354
  field=field,
313
355
  def_num=field_def_num,
314
356
  base_type=base_type,
315
357
  size=field_size,
358
+ unpacker=self._field_unpacker(endian, base_type, field_size),
316
359
  ))
317
360
 
318
361
  dev_field_defs = []
@@ -325,8 +368,9 @@ class FitFileDecoder(DeveloperDataMixin):
325
368
  field=field,
326
369
  dev_data_index=dev_data_index,
327
370
  def_num=field_def_num,
328
- size=field_size
329
- ))
371
+ size=field_size,
372
+ unpacker=self._field_unpacker(endian, field.type, field_size),
373
+ ))
330
374
 
331
375
  def_mesg = DefinitionMessage(
332
376
  header=header,
@@ -339,24 +383,32 @@ class FitFileDecoder(DeveloperDataMixin):
339
383
  self._local_mesgs[header.local_mesg_num] = def_mesg
340
384
  return def_mesg
341
385
 
386
+ @staticmethod
387
+ def _field_unpacker(endian, base_type, size):
388
+ # Struct to read n base types (field def size / base type size)
389
+ count = int(size / base_type.size)
390
+ return struct.Struct(endian + str(count) + base_type.fmt) if count > 0 else None
391
+
342
392
  def _parse_raw_values_from_data_message(self, def_mesg):
343
393
  # Go through mesg's field defs and read them
344
394
  raw_values = []
345
395
  for field_def in def_mesg.field_defs + def_mesg.dev_field_defs:
346
396
  base_type = field_def.base_type
347
397
  is_byte = base_type.name == 'byte'
348
- # Struct to read n base types (field def size / base type size)
349
- struct_fmt = str(int(field_def.size / base_type.size)) + base_type.fmt
398
+ unpacker = field_def.unpacker
399
+ if unpacker is None:
400
+ raise FitParseError("Invalid struct format: %s0%s" % (def_mesg.endian, base_type.fmt))
350
401
 
351
- # Extract the raw value, ask for a tuple if it's a byte type
352
402
  try:
353
- raw_value = self._read_struct(
354
- struct_fmt, endian=def_mesg.endian, always_tuple=is_byte,
355
- )
403
+ raw_value = unpacker.unpack(self._read(unpacker.size))
356
404
  except FitEOFError:
405
+ if self.allow_truncated:
406
+ raise
357
407
  # file was suddenly terminated
358
408
  warnings.warn("File was terminated unexpectedly, some data will not be loaded.")
359
409
  break
410
+ if len(raw_value) == 1 and not is_byte:
411
+ raw_value = raw_value[0]
360
412
 
361
413
  # If the field returns with a tuple of values it's definitely an
362
414
  # oddball, but we'll parse it on a per-value basis it.
@@ -371,20 +423,39 @@ class FitFileDecoder(DeveloperDataMixin):
371
423
  return raw_values
372
424
 
373
425
  @staticmethod
374
- def _resolve_subfield(field, def_mesg, raw_values):
426
+ def _resolve_subfield(field, ref_values):
375
427
  # Resolve into (field, parent) ie (subfield, field) or (field, None)
376
428
  if field.subfields:
377
429
  for sub_field in field.subfields:
378
- # Go through reference fields for this sub field
379
430
  for ref_field in sub_field.ref_fields:
380
- # Go through field defs AND their raw values
381
- for field_def, raw_value in zip(def_mesg.field_defs, raw_values):
382
- # If there's a definition number AND raw value match on the
383
- # reference field, then we return this subfield
384
- if (field_def.def_num == ref_field.def_num) and (ref_field.raw_value == raw_value):
385
- return sub_field, field
431
+ if ref_values.get(ref_field.def_num) == ref_field.raw_value:
432
+ return sub_field, field
386
433
  return field, None
387
434
 
435
+ def _reference_values(self, def_mesg, raw_values):
436
+ ref_values = {
437
+ field_def.def_num: raw_value
438
+ for field_def, raw_value in zip(def_mesg.field_defs, raw_values)
439
+ if raw_value is not None
440
+ }
441
+ native = dict(ref_values)
442
+ for field_def, raw_value in zip(def_mesg.field_defs, raw_values):
443
+ if not field_def.field:
444
+ continue
445
+ field, _ = self._resolve_subfield(field_def.field, native)
446
+ # Accumulating components are skipped so this pass leaves the accumulators
447
+ # alone; references are enums, which never accumulate.
448
+ for component in field.components or ():
449
+ if component.accumulate:
450
+ continue
451
+ try:
452
+ cmp_raw_value = component.render(raw_value)
453
+ except ValueError:
454
+ continue
455
+ if cmp_raw_value is not None:
456
+ ref_values.setdefault(component.def_num, self._apply_scale_offset(component, cmp_raw_value))
457
+ return ref_values
458
+
388
459
  def _apply_scale_offset(self, field, raw_value):
389
460
  # Apply numeric transformations (scale+offset)
390
461
  if isinstance(raw_value, tuple):
@@ -408,6 +479,58 @@ class FitFileDecoder(DeveloperDataMixin):
408
479
 
409
480
  return base_value
410
481
 
482
+ def _expand_components(self, def_mesg, field, raw_value, ref_values, field_datas, path):
483
+ for component in field.components or ():
484
+ # Render its raw value
485
+ try:
486
+ cmp_raw_value = component.render(raw_value)
487
+ except ValueError:
488
+ continue
489
+
490
+ # Apply accumulated value
491
+ if component.accumulate and cmp_raw_value is not None:
492
+ accumulator = self._accumulators.setdefault(def_mesg.mesg_num, {})
493
+ cmp_raw_value = self._apply_compressed_accumulation(
494
+ cmp_raw_value, accumulator.get(component.def_num, 0), component.bits,
495
+ )
496
+ accumulator[component.def_num] = cmp_raw_value
497
+
498
+ # Apply scale and offset from component, not from the dynamic field
499
+ # as they may differ
500
+ cmp_raw_value = self._apply_scale_offset(component, cmp_raw_value)
501
+
502
+ # Extract the component's dynamic field from def_mesg
503
+ cmp_field = def_mesg.mesg_type.fields[component.def_num]
504
+
505
+ # Resolve a possible subfield
506
+ cmp_field, cmp_parent_field = self._resolve_subfield(cmp_field, ref_values)
507
+ cmp_value = cmp_field.render(cmp_raw_value)
508
+
509
+ # Plop it on field_datas
510
+ field_datas.append(
511
+ FieldData(
512
+ field_def=None,
513
+ field=cmp_field,
514
+ parent_field=cmp_parent_field,
515
+ value=cmp_value,
516
+ raw_value=cmp_raw_value,
517
+ )
518
+ )
519
+
520
+ # As in the FIT SDK, a target's own components (speed -> enhanced_speed) expand from
521
+ # its raw value; path stops a profile cycle from recursing forever
522
+ if cmp_field.components and cmp_field.def_num not in path:
523
+ self._expand_components(
524
+ def_mesg, cmp_field, self._unapply_scale_offset(cmp_field, cmp_raw_value), ref_values,
525
+ field_datas, path + (cmp_field.def_num,),
526
+ )
527
+
528
+ @staticmethod
529
+ def _unapply_scale_offset(field, value):
530
+ if not isinstance(value, (int, float)):
531
+ return None
532
+ return round((value + (field.offset or 0)) * (field.scale or 1))
533
+
411
534
  def _parse_data_message_components(self, header):
412
535
  def_mesg = self._local_mesgs.get(header.local_mesg_num)
413
536
  if not def_mesg:
@@ -415,6 +538,7 @@ class FitFileDecoder(DeveloperDataMixin):
415
538
  header.local_mesg_num))
416
539
 
417
540
  raw_values = self._parse_raw_values_from_data_message(def_mesg)
541
+ ref_values = self._reference_values(def_mesg, raw_values)
418
542
  field_datas = [] # TODO: I don't love this name, update on DataMessage too
419
543
 
420
544
  # TODO: Maybe refactor this and make it simpler (or at least broken
@@ -422,46 +546,9 @@ class FitFileDecoder(DeveloperDataMixin):
422
546
  for field_def, raw_value in zip(def_mesg.field_defs + def_mesg.dev_field_defs, raw_values):
423
547
  field, parent_field = field_def.field, None
424
548
  if field:
425
- field, parent_field = self._resolve_subfield(field, def_mesg, raw_values)
426
-
427
- # Resolve component fields
428
- if field.components:
429
- for component in field.components:
430
- # Render its raw value
431
- try:
432
- cmp_raw_value = component.render(raw_value)
433
- except ValueError:
434
- continue
435
-
436
- # Apply accumulated value
437
- if component.accumulate and cmp_raw_value is not None:
438
- accumulator = self._accumulators[def_mesg.mesg_num]
439
- cmp_raw_value = self._apply_compressed_accumulation(
440
- cmp_raw_value, accumulator[component.def_num], component.bits,
441
- )
442
- accumulator[component.def_num] = cmp_raw_value
443
-
444
- # Apply scale and offset from component, not from the dynamic field
445
- # as they may differ
446
- cmp_raw_value = self._apply_scale_offset(component, cmp_raw_value)
447
-
448
- # Extract the component's dynamic field from def_mesg
449
- cmp_field = def_mesg.mesg_type.fields[component.def_num]
450
-
451
- # Resolve a possible subfield
452
- cmp_field, cmp_parent_field = self._resolve_subfield(cmp_field, def_mesg, raw_values)
453
- cmp_value = cmp_field.render(cmp_raw_value)
454
-
455
- # Plop it on field_datas
456
- field_datas.append(
457
- FieldData(
458
- field_def=None,
459
- field=cmp_field,
460
- parent_field=cmp_parent_field,
461
- value=cmp_value,
462
- raw_value=cmp_raw_value,
463
- )
464
- )
549
+ field, parent_field = self._resolve_subfield(field, ref_values)
550
+
551
+ self._expand_components(def_mesg, field, raw_value, ref_values, field_datas, (field.def_num,))
465
552
 
466
553
  # TODO: Do we care about a base_type and a resolved field mismatch?
467
554
  # My hunch is we don't
@@ -470,7 +557,7 @@ class FitFileDecoder(DeveloperDataMixin):
470
557
  value = raw_value
471
558
 
472
559
  # Update compressed timestamp field
473
- if (field_def.def_num == FIELD_TYPE_TIMESTAMP.def_num) and (raw_value is not None):
560
+ if (field_def.def_num == FIELD_TYPE_TIMESTAMP.def_num) and isinstance(raw_value, int):
474
561
  self._compressed_ts_accumulator = raw_value
475
562
 
476
563
  field_datas.append(
@@ -604,12 +691,13 @@ class DataProcessorMixin:
604
691
  class UncachedFitFile(DataProcessorMixin, FitFileDecoder):
605
692
  """FitFileDecoder with data processing"""
606
693
 
607
- def __init__(self, fileish, *args, check_crc=True, data_processor=None, **kwargs):
694
+ def __init__(self, fileish, *args, check_crc=True, allow_truncated=False, data_processor=None, **kwargs):
608
695
  # Ensure all optional params are passed as kwargs
609
696
  super().__init__(
610
697
  fileish,
611
698
  *args,
612
699
  check_crc=check_crc,
700
+ allow_truncated=allow_truncated,
613
701
  data_processor=data_processor,
614
702
  **kwargs
615
703
  )
fitparse/fitdump.py ADDED
@@ -0,0 +1,198 @@
1
+ import argparse
2
+ import codecs
3
+ import datetime
4
+ import itertools
5
+ import json
6
+ import os.path
7
+ import types
8
+
9
+ import fitparse
10
+
11
+
12
+ def format_message(num, message, options):
13
+ s = [f"{num}. {message.name}"]
14
+ if options.with_defs:
15
+ s.append(f' [{message.type}]')
16
+ s.append('\n')
17
+
18
+ if message.type == 'data':
19
+ for field_data in message:
20
+ s.append(f' * {field_data.name}: {field_data.value}')
21
+ if field_data.units:
22
+ s.append(f' [{field_data.units}]')
23
+ s.append('\n')
24
+
25
+ s.append('\n')
26
+ return "".join(s)
27
+
28
+
29
+ def parse_args(args=None):
30
+ parser = argparse.ArgumentParser(
31
+ description='Dump .FIT files to various formats',
32
+ epilog='python-fitparse version %s' % fitparse.__version__,
33
+ )
34
+ parser.add_argument('-v', '--verbose', action='count', default=0)
35
+ parser.add_argument(
36
+ '-o', '--output', type=argparse.FileType(mode='w', encoding="utf-8"),
37
+ default="-",
38
+ help='File to output data into (defaults to stdout)',
39
+ )
40
+ parser.add_argument(
41
+ # TODO: csv
42
+ '-t', '--type', choices=('readable', 'json', 'gpx'), default='readable',
43
+ help='File type to output. (DEFAULT: %(default)s)',
44
+ )
45
+ parser.add_argument(
46
+ '-n', '--name', action='append', help='Message name (or number) to filter',
47
+ )
48
+ parser.add_argument(
49
+ 'infile', metavar='FITFILE', type=argparse.FileType(mode='rb'),
50
+ help='Input .FIT file (Use - for stdin)',
51
+ )
52
+ parser.add_argument(
53
+ '--ignore-crc', action='store_const', const=True, help='Some devices seem to write invalid crc\'s, ignore these.'
54
+ )
55
+
56
+ options = parser.parse_args(args)
57
+
58
+ options.verbose = options.verbose >= 1
59
+ options.with_defs = (options.type == "readable" and options.verbose)
60
+ options.as_dict = (options.type != "readable" and options.verbose)
61
+
62
+ return options
63
+
64
+
65
+ class RecordJSONEncoder(json.JSONEncoder):
66
+ def default(self, obj):
67
+ if isinstance(obj, types.GeneratorType):
68
+ return list(obj)
69
+ if isinstance(obj, (datetime.datetime, datetime.time)):
70
+ return obj.isoformat()
71
+ if isinstance(obj, fitparse.DataMessage):
72
+ return {
73
+ "type": obj.name,
74
+ "data": {
75
+ data.name: data.value for data in obj
76
+ }
77
+ }
78
+ # Fall back to original to raise a TypeError
79
+ return super().default(obj)
80
+
81
+
82
+ def generate_gpx(records, filename=None):
83
+ # TODO: Use xml.etree.ElementTree ?
84
+
85
+ GPX_TIME_FMT = "%Y-%m-%dT%H:%M:%SZ" # ISO 8601 format
86
+
87
+ records = iter(records)
88
+
89
+ # header + open tags
90
+ yield '<?xml version="1.0"?>\n'
91
+ yield '<gpx xmlns="http://www.topografix.com/GPX/1/1" version="1.1" creator="python-fitparse (fitdump)" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">\n'
92
+ yield ' <metadata>\n'
93
+
94
+ # file creation time (if a file_id record exists)
95
+ first_record = []
96
+ for message in records:
97
+ if message.name == "file_id":
98
+ for field_data in message:
99
+ if field_data.name == "time_created" and type(field_data.value) == datetime.datetime:
100
+ yield f' <time>{field_data.value.strftime(GPX_TIME_FMT)}</time>\n'
101
+ break
102
+ else:
103
+ # No time found in the fields, check next record
104
+ continue
105
+ break
106
+ elif message.name == "record":
107
+ first_record.append(message)
108
+ break
109
+
110
+ if filename:
111
+ yield f' <src>{filename}</src>\n'
112
+
113
+ yield ' </metadata>\n'
114
+ yield ' <trk>\n'
115
+
116
+ if filename:
117
+ yield f' <name>{filename}</name>\n'
118
+
119
+ yield ' <trkseg>\n'
120
+
121
+ # track points
122
+ for message in itertools.chain(first_record, records):
123
+ if message.name != "record":
124
+ continue
125
+
126
+ trkpt = {}
127
+
128
+ # TODO: support more data types (heart rate, cadence, etc)
129
+ for field_data in message:
130
+ if field_data.name == "position_lat":
131
+ # Units are decimal degrees
132
+ trkpt["lat"] = field_data.value
133
+ elif field_data.name == "position_long":
134
+ # Units are decimal degrees
135
+ trkpt["lon"] = field_data.value
136
+ elif field_data.name == "enhanced_altitude":
137
+ # Units are m
138
+ trkpt["ele"] = field_data.value
139
+ elif field_data.name == "timestamp" and type(field_data.value) == datetime.datetime:
140
+ trkpt["time"] = field_data.value.strftime(GPX_TIME_FMT)
141
+ elif field_data.name == "enhanced_speed" and type(field_data.value) == float:
142
+ # convert from km/h to m/s
143
+ trkpt["speed"] = field_data.value / 3.6
144
+
145
+ # Add trackpoint
146
+ if "lat" in trkpt and "lon" in trkpt:
147
+ yield ' <trkpt lat="{lat}" lon="{lon}">\n'.format(**trkpt)
148
+ if "ele" in trkpt:
149
+ yield ' <ele>{ele}</ele>\n'.format(**trkpt)
150
+ if "time" in trkpt:
151
+ yield ' <time>{time}</time>\n'.format(**trkpt)
152
+ if "speed" in trkpt:
153
+ yield ' <speed>{speed}</speed>\n'.format(**trkpt)
154
+ yield ' </trkpt>\n'
155
+
156
+ # close tags
157
+ yield ' </trkseg>\n'
158
+ yield ' </trk>\n'
159
+ yield '</gpx>\n'
160
+
161
+
162
+ def main(args=None):
163
+ options = parse_args(args)
164
+
165
+ fitfile = fitparse.UncachedFitFile(
166
+ options.infile,
167
+ data_processor=fitparse.StandardUnitsDataProcessor(),
168
+ check_crc=not(options.ignore_crc),
169
+ )
170
+ records = fitfile.get_messages(
171
+ name=options.name,
172
+ with_definitions=options.with_defs,
173
+ as_dict=options.as_dict
174
+ )
175
+
176
+ try:
177
+ if options.type == "json":
178
+ json.dump(records, fp=options.output, cls=RecordJSONEncoder)
179
+ elif options.type == "readable":
180
+ options.output.writelines(
181
+ format_message(n, record, options) for n, record in enumerate(records, 1)
182
+ )
183
+ elif options.type == "gpx":
184
+ filename = getattr(options.infile, "name")
185
+ if filename:
186
+ filename = os.path.basename(filename)
187
+ options.output.writelines(generate_gpx(records, filename))
188
+ finally:
189
+ try:
190
+ options.output.close()
191
+ except OSError:
192
+ pass
193
+
194
+ if __name__ == '__main__':
195
+ try:
196
+ main()
197
+ except BrokenPipeError:
198
+ pass
fitparse/processors.py CHANGED
@@ -1,5 +1,5 @@
1
1
  import datetime
2
- from fitparse.utils import scrub_method_name, is_iterable
2
+ from fitparse.utils import FitParseError, scrub_method_name, is_iterable
3
3
 
4
4
  # Datetimes (uint32) represent seconds since this UTC_REFERENCE
5
5
  UTC_REFERENCE = 631065600 # timestamp for UTC 00:00 Dec 31 1989
@@ -58,10 +58,17 @@ class FitFileDataProcessor:
58
58
  'process_message_%s' % data_message.def_mesg.name), data_message)
59
59
 
60
60
  def _run_processor(self, processor_name, data):
61
+ processors = vars(self).setdefault('_processors', {})
61
62
  try:
62
- getattr(self, processor_name)(data)
63
- except AttributeError:
64
- pass
63
+ processor = processors[processor_name]
64
+ except KeyError:
65
+ processor = processors[processor_name] = getattr(self, processor_name, None)
66
+ if processor is None:
67
+ return
68
+ try:
69
+ processor(data)
70
+ except AttributeError as e:
71
+ raise FitParseError("%s failed: %s" % (processor_name, e)) from e
65
72
 
66
73
  def process_type_bool(self, field_data):
67
74
  if field_data.value is not None:
@@ -69,12 +76,12 @@ class FitFileDataProcessor:
69
76
 
70
77
  def process_type_date_time(self, field_data):
71
78
  value = field_data.value
72
- if value is not None and value >= 0x10000000:
79
+ if isinstance(value, int) and value >= 0x10000000:
73
80
  field_data.value = datetime.datetime.fromtimestamp(timestamp=(UTC_REFERENCE + value), tz=datetime.timezone.utc).replace(tzinfo=None)
74
81
  field_data.units = None # Units were 's', set to None
75
82
 
76
83
  def process_type_local_date_time(self, field_data):
77
- if field_data.value is not None:
84
+ if isinstance(field_data.value, int):
78
85
  # NOTE: This value was created on the device using it's local timezone.
79
86
  # Unless we know that timezone, this value won't be correct. However, if we
80
87
  # assume UTC, at least it'll be consistent.
@@ -82,7 +89,7 @@ class FitFileDataProcessor:
82
89
  field_data.units = None
83
90
 
84
91
  def process_type_localtime_into_day(self, field_data):
85
- if field_data.value is not None:
92
+ if isinstance(field_data.value, int):
86
93
  # NOTE: Values larger or equal to 86400 should not be possible.
87
94
  # Additionally, if the value is exactly 86400, it will lead to an error when trying to
88
95
  # create the time with datetime.time(24, 0 , 0).
fitparse/profile.py CHANGED
@@ -1,8 +1,8 @@
1
1
  # ***************** BEGIN AUTOMATICALLY GENERATED FIT PROFILE ******************
2
2
  # *************************** DO NOT EDIT THIS FILE ****************************
3
- # *********** EXPORTED PROFILE FROM SDK VERSION 21.221 ON 2026-11-03 ***********
4
- # ********* PARSED 220 TYPES (4819 VALUES), 128 MESSAGES (1599 FIELDS) *********
5
- # ***************************** APPLIED 2 PATCHES ******************************
3
+ # *********** EXPORTED PROFILE FROM SDK VERSION 21.221 ON 2026-11-10 ***********
4
+ # ********* PARSED 220 TYPES (4819 VALUES), 129 MESSAGES (1606 FIELDS) *********
5
+ # ***************************** APPLIED 8 PATCHES ******************************
6
6
 
7
7
  from fitparse.records import (
8
8
  ComponentField,
@@ -6249,6 +6249,11 @@ MESSAGE_TYPES = {
6249
6249
  name='location',
6250
6250
  mesg_num=29,
6251
6251
  fields={
6252
+ 0: Field( # Label shown on the device, defaults to the save date and time (e.g. 22 Feb 15:12)
6253
+ name='name',
6254
+ type=BASE_TYPES[0x07], # string
6255
+ def_num=0,
6256
+ ),
6252
6257
  1: Field(
6253
6258
  name='position_lat',
6254
6259
  type=BASE_TYPES[0x85], # sint32
@@ -6261,21 +6266,18 @@ MESSAGE_TYPES = {
6261
6266
  def_num=2,
6262
6267
  units='semicircles',
6263
6268
  ),
6264
- 3: Field(
6265
- name='count',
6266
- type=BASE_TYPES[0x84], # uint16
6267
- def_num=3,
6268
- ),
6269
- 4: Field( # UTC timestamp used to set the devices clock and date
6270
- name='clock_time',
6269
+ 4: Field( # Inferred from saved locations: values follow the standard FIT altitude encoding
6270
+ name='altitude',
6271
6271
  type=BASE_TYPES[0x84], # uint16
6272
6272
  def_num=4,
6273
- units='min',
6273
+ scale=5,
6274
+ offset=500,
6275
+ units='m',
6274
6276
  ),
6275
- 8: Field( # Used to correlate UTC to system time if the timestamp of the message is in system time. This UTC time is derived from the GPS data.
6276
- name='date',
6277
- type=BASE_TYPES[0x07], # string
6278
- def_num=8,
6277
+ 254: Field(
6278
+ name='message_index',
6279
+ type=FIELD_TYPES['message_index'],
6280
+ def_num=254,
6279
6281
  ),
6280
6282
  },
6281
6283
  ),
@@ -6340,6 +6342,19 @@ MESSAGE_TYPES = {
6340
6342
  253: FIELD_TYPE_TIMESTAMP, # Whole second part of UTC timestamp at the time the system timestamp was recorded.
6341
6343
  },
6342
6344
  ),
6345
+ 397: MessageType( # Undocumented per-minute skin temperature, found only in SkinTemp files
6346
+ name='skin_temp_sample',
6347
+ mesg_num=397,
6348
+ fields={
6349
+ 1: Field( # Inferred: one per minute over the day before skin_temp_overnight, -11 to +5; the baseline is unconfirmed, the sleep-window mean sits about 1 C below average_deviation
6350
+ name='deviation',
6351
+ type=BASE_TYPES[0x88], # float32
6352
+ def_num=1,
6353
+ units='C',
6354
+ ),
6355
+ 253: FIELD_TYPE_TIMESTAMP,
6356
+ },
6357
+ ),
6343
6358
 
6344
6359
 
6345
6360
  # ************************* Activity File Messages *************************
@@ -9301,6 +9316,11 @@ MESSAGE_TYPES = {
9301
9316
  scale=100,
9302
9317
  units='m',
9303
9318
  ),
9319
+ 90: Field( # Inferred: -7 to 9 on real runs, and never present before six minutes into the activity
9320
+ name='performance_condition',
9321
+ type=BASE_TYPES[0x01], # sint8
9322
+ def_num=90,
9323
+ ),
9304
9324
  91: Field( # Includes atmospheric pressure
9305
9325
  name='absolute_pressure',
9306
9326
  type=BASE_TYPES[0x86], # uint32
@@ -9460,6 +9480,24 @@ MESSAGE_TYPES = {
9460
9480
  scale=100,
9461
9481
  units='percent',
9462
9482
  ),
9483
+ 136: Field( # Inferred: equals heart_rate in all but 2 of 171,509 records
9484
+ name='wrist_heart_rate',
9485
+ type=BASE_TYPES[0x02], # uint8
9486
+ def_num=136,
9487
+ units='bpm',
9488
+ ),
9489
+ 137: Field( # Inferred: starts near 100 and falls over an activity, never below stamina
9490
+ name='stamina_potential',
9491
+ type=BASE_TYPES[0x02], # uint8
9492
+ def_num=137,
9493
+ units='percent',
9494
+ ),
9495
+ 138: Field( # Inferred: 1 to 100, never above stamina_potential
9496
+ name='stamina',
9497
+ type=BASE_TYPES[0x02], # uint8
9498
+ def_num=138,
9499
+ units='percent',
9500
+ ),
9463
9501
  139: Field(
9464
9502
  name='core_temperature',
9465
9503
  type=BASE_TYPES[0x84], # uint16
@@ -9467,6 +9505,12 @@ MESSAGE_TYPES = {
9467
9505
  scale=100,
9468
9506
  units='C',
9469
9507
  ),
9508
+ 143: Field( # Inferred: within 0.3 on average of the stress_level body_battery of the same 3-minute slot
9509
+ name='body_battery',
9510
+ type=BASE_TYPES[0x02], # uint8
9511
+ def_num=143,
9512
+ units='percent',
9513
+ ),
9470
9514
  253: FIELD_TYPE_TIMESTAMP,
9471
9515
  },
9472
9516
  ),
fitparse/records.py CHANGED
@@ -49,7 +49,7 @@ class DefinitionMessage(RecordBase):
49
49
 
50
50
 
51
51
  class FieldDefinition(RecordBase):
52
- __slots__ = ('field', 'def_num', 'base_type', 'size')
52
+ __slots__ = ('field', 'def_num', 'base_type', 'size', 'unpacker')
53
53
 
54
54
  @property
55
55
  def name(self):
@@ -69,7 +69,7 @@ class FieldDefinition(RecordBase):
69
69
 
70
70
 
71
71
  class DevFieldDefinition(RecordBase):
72
- __slots__ = ('field', 'dev_data_index', 'base_type', 'def_num', 'size')
72
+ __slots__ = ('field', 'dev_data_index', 'base_type', 'def_num', 'size', 'unpacker')
73
73
 
74
74
  def __init__(self, **kwargs):
75
75
  super().__init__(**kwargs)
@@ -159,12 +159,15 @@ class DataMessage(RecordBase):
159
159
  class FieldData(RecordBase):
160
160
  __slots__ = ('field_def', 'field', 'parent_field', 'value', 'raw_value', 'units')
161
161
 
162
- def __init__(self, *args, **kwargs):
163
- super().__init__(self, *args, **kwargs)
164
- if not self.units and self.field:
165
- # Default to units on field, otherwise None.
166
- # NOTE:Not a property since you may want to override this in a data processor
167
- self.units = self.field.units
162
+ def __init__(self, field_def=None, field=None, parent_field=None, value=None, raw_value=None, units=None):
163
+ self.field_def = field_def
164
+ self.field = field
165
+ self.parent_field = parent_field
166
+ self.value = value
167
+ self.raw_value = raw_value
168
+ # Default to units on field, otherwise None.
169
+ # NOTE:Not a property since you may want to override this in a data processor
170
+ self.units = field.units if not units and field else units
168
171
 
169
172
  @property
170
173
  def name(self):
@@ -287,9 +290,10 @@ class SubField(FieldAndSubFieldBase):
287
290
 
288
291
 
289
292
  class DevField(FieldAndSubFieldBase):
290
- __slots__ = ('dev_data_index', 'def_num', 'type', 'name', 'units', 'native_field_num',
291
- # The rest of these are just to be compatible with Field objects. They're always None
292
- 'scale', 'offset', 'components', 'subfields')
293
+ __slots__ = ('dev_data_index', 'def_num', 'type', 'name', 'units', 'scale', 'offset',
294
+ 'native_mesg_num', 'native_field_num',
295
+ # Only for compatibility with Field objects; always None
296
+ 'components', 'subfields')
293
297
  field_type = 'devfield'
294
298
 
295
299
 
@@ -316,6 +320,9 @@ class ComponentField(RecordBase):
316
320
  if self.bit_offset and self.bit_offset >= len(raw_value) << 3:
317
321
  raise ValueError()
318
322
 
323
+ if not all(isinstance(value, int) for value in raw_value):
324
+ return None
325
+
319
326
  unpacked_num = 0
320
327
 
321
328
  # Unpack byte array as little endian
@@ -324,11 +331,11 @@ class ComponentField(RecordBase):
324
331
 
325
332
  raw_value = unpacked_num
326
333
 
327
- # Mask and shift like a normal number
328
- if isinstance(raw_value, int):
329
- raw_value = (raw_value >> self.bit_offset) & ((1 << self.bits) - 1)
334
+ if not isinstance(raw_value, int):
335
+ return None
330
336
 
331
- return raw_value
337
+ # Mask and shift like a normal number
338
+ return (raw_value >> self.bit_offset) & ((1 << self.bits) - 1)
332
339
 
333
340
 
334
341
  class Crc:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-fitparse
3
- Version: 2.8.0
3
+ Version: 2.12.0
4
4
  Summary: Python library to parse ANT/Garmin .FIT files
5
5
  Project-URL: Homepage, https://github.com/nbr23/python-fitparse
6
6
  Project-URL: Repository, https://github.com/nbr23/python-fitparse
@@ -0,0 +1,12 @@
1
+ fitparse/__init__.py,sha256=XigqA8TTG1j9B3PyV7PfAfJhVL2NQVGQrMtfmElEuNM,336
2
+ fitparse/base.py,sha256=17IS0ixw3ll9EKkTO20WlzDSw5OGoyXWI88S6JGa-uQ,27512
3
+ fitparse/fitdump.py,sha256=ftk6fDdSCAqbraghvelifa5POyK6g4Qd2C3A4qAtFns,6509
4
+ fitparse/processors.py,sha256=AuVxTrCcGnTMkLTT_PXLsDK-xFNCOFIFbUy_6L_rk7c,5722
5
+ fitparse/profile.py,sha256=3WOZ7Ofp54Xhjjf5HiyAIkNwjwIYsJfNrLytYoxlny4,697066
6
+ fitparse/records.py,sha256=rvIeYDu8xiuQz7xM0FRNHaHrJewEKwJIr_2tqjDxIC0,14683
7
+ fitparse/utils.py,sha256=cYmAKRktsiTKpxAAvp9XwjfN2BKzEP9-0fAKoTTu_Sw,1750
8
+ python_fitparse-2.12.0.dist-info/METADATA,sha256=RivHXjOXkjQ5EawpKpFltP-um8L-Ws7mn9ldrAvEnZE,4142
9
+ python_fitparse-2.12.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ python_fitparse-2.12.0.dist-info/entry_points.txt,sha256=4OUq-aV4hvyCK8CwHGiaM6zkn8nYBn1dbFqE6zaBEoA,50
11
+ python_fitparse-2.12.0.dist-info/licenses/LICENSE,sha256=RK-rKfCYWql9q58dgvYwpDuo-N4g0L4iXxr8D5ubMIo,1157
12
+ python_fitparse-2.12.0.dist-info/RECORD,,
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fitdump = fitparse.fitdump:main
@@ -1,11 +0,0 @@
1
- fitparse/__init__.py,sha256=XigqA8TTG1j9B3PyV7PfAfJhVL2NQVGQrMtfmElEuNM,336
2
- fitparse/base.py,sha256=9Prisb5xfPGM79kszvfATVIgYMC3gWnHWaX1kqoHmAQ,24202
3
- fitparse/processors.py,sha256=gQNdFiT5xVn3R9uX-cjijL2JQ3cKtuygjAPKIZ7J53Q,5357
4
- fitparse/profile.py,sha256=BZ7-gxXLnekCNKASgpLqCs1Dz-lYX5onjZNRBaAntrA,695175
5
- fitparse/records.py,sha256=bjiuG6P2SrRHxmGWjcNbj29nnM6UAl9sw-toR2rFudk,14396
6
- fitparse/utils.py,sha256=cYmAKRktsiTKpxAAvp9XwjfN2BKzEP9-0fAKoTTu_Sw,1750
7
- python_fitparse-2.8.0.dist-info/METADATA,sha256=l1OU1Myxk1L8JC8y9PfbBi1T_ABF0pivqCnPs0hIww8,4141
8
- python_fitparse-2.8.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
- python_fitparse-2.8.0.dist-info/entry_points.txt,sha256=cM-FrZMgY175Od7pYZX7yu48XDynph8o2w-FBOBIyRU,49
10
- python_fitparse-2.8.0.dist-info/licenses/LICENSE,sha256=RK-rKfCYWql9q58dgvYwpDuo-N4g0L4iXxr8D5ubMIo,1157
11
- python_fitparse-2.8.0.dist-info/RECORD,,
@@ -1,2 +0,0 @@
1
- [console_scripts]
2
- fitdump = scripts.fitdump:main