python-fitparse 2.10.0__py3-none-any.whl → 2.13.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/__init__.py CHANGED
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env python
2
2
 
3
+ import importlib.metadata
4
+
3
5
  # Make classes available
4
6
  from fitparse.base import FitFile, FitFileDecoder, UncachedFitFile, \
5
7
  FitParseError, CacheMixin, DataProcessorMixin
@@ -7,4 +9,7 @@ from fitparse.records import DataMessage
7
9
  from fitparse.processors import FitFileDataProcessor, StandardUnitsDataProcessor
8
10
 
9
11
 
10
- __version__ = '1.2.0'
12
+ try:
13
+ __version__ = importlib.metadata.version("python-fitparse")
14
+ except importlib.metadata.PackageNotFoundError:
15
+ __version__ = "unknown"
fitparse/base.py CHANGED
@@ -65,6 +65,9 @@ class DeveloperDataMixin:
65
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')
68
71
 
69
72
  for name, value in (('developer_data_index', dev_data_index),
70
73
  ('field_definition_number', field_def_num),
@@ -76,6 +79,10 @@ class DeveloperDataMixin:
76
79
  field_name = "unnamed_dev_field_%s" % field_def_num
77
80
  if not isinstance(units, str):
78
81
  units = None
82
+ if not isinstance(scale, int):
83
+ scale = None
84
+ if not isinstance(offset, int):
85
+ offset = None
79
86
  base_type = BASE_TYPES.get(base_type_id)
80
87
  if base_type is None:
81
88
  warnings.warn(
@@ -102,6 +109,9 @@ class DeveloperDataMixin:
102
109
  type=base_type,
103
110
  name=field_name,
104
111
  units=units,
112
+ scale=scale,
113
+ offset=offset,
114
+ native_mesg_num=native_mesg_num,
105
115
  native_field_num=native_field_num
106
116
  )
107
117
 
@@ -139,11 +149,14 @@ class DeveloperDataMixin:
139
149
  class FitFileDecoder(DeveloperDataMixin):
140
150
  """Basic decoder for fit files"""
141
151
 
142
- 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):
143
153
  self._file = fileish_open(fileish, 'rb')
144
154
 
145
155
  self.check_crc = check_crc
156
+ self.allow_truncated = allow_truncated
157
+ self.truncated = None
146
158
  self._crc = None
159
+ self._in_header = False
147
160
 
148
161
  # Get total filesize
149
162
  self._file.seek(0, os.SEEK_END)
@@ -198,11 +211,12 @@ class FitFileDecoder(DeveloperDataMixin):
198
211
  return unpacked if (len(unpacked) > 1) or always_tuple else unpacked[0]
199
212
 
200
213
  def _read_and_assert_crc(self, allow_zero=False):
201
- # CRC Calculation is little endian from SDK
202
- # TODO - How to handle the case of unterminated file? Error out and have user retry with check_crc=false?
203
- crc_computed, crc_read = self._crc.value, self._read_struct(Crc.FMT)
204
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))
205
217
  return
218
+ # CRC Calculation is little endian from SDK
219
+ crc_computed, crc_read = self._crc.value, self._read_struct(Crc.FMT)
206
220
  if crc_computed == crc_read or (allow_zero and crc_read == 0):
207
221
  return
208
222
  raise FitCRCError('CRC Mismatch [computed: {}, read: {}]'.format(
@@ -221,6 +235,7 @@ class FitFileDecoder(DeveloperDataMixin):
221
235
  self._crc = Crc()
222
236
  self._local_mesgs = {}
223
237
 
238
+ segment_start = self._file.tell()
224
239
  header_data = self._read(12)
225
240
  if header_data[8:12] != b'.FIT':
226
241
  raise FitHeaderError("Invalid .FIT File Header")
@@ -248,12 +263,26 @@ class FitFileDecoder(DeveloperDataMixin):
248
263
 
249
264
  # After we've consumed the header, set the bytes left to be read
250
265
  self._bytes_left = data_size
266
+ self._segment_end = segment_start + header_size + data_size + struct.calcsize(Crc.FMT)
251
267
 
252
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):
253
283
  # When done, calculate the CRC and return None
254
284
  if self._bytes_left <= 0:
255
- # Don't assert CRC if requested not
256
- if not self._complete and self.check_crc:
285
+ if not self._complete:
257
286
  self._read_and_assert_crc()
258
287
 
259
288
  if self._file.tell() >= self._filesize:
@@ -262,8 +291,10 @@ class FitFileDecoder(DeveloperDataMixin):
262
291
  return None
263
292
 
264
293
  # Still have data left in the file - assuming chained fit files
294
+ self._in_header = True
265
295
  self._parse_file_header()
266
- return self._parse_message()
296
+ self._in_header = False
297
+ return self._read_message()
267
298
 
268
299
  header = self._parse_message_header()
269
300
 
@@ -319,19 +350,12 @@ class FitFileDecoder(DeveloperDataMixin):
319
350
  )
320
351
  base_type = BASE_TYPE_BYTE
321
352
 
322
- # If the field has components that are accumulators
323
- # start recording their accumulation at 0
324
- if field and field.components:
325
- for component in field.components:
326
- if component.accumulate:
327
- accumulators = self._accumulators.setdefault(global_mesg_num, {})
328
- accumulators[component.def_num] = 0
329
-
330
353
  field_defs.append(FieldDefinition(
331
354
  field=field,
332
355
  def_num=field_def_num,
333
356
  base_type=base_type,
334
357
  size=field_size,
358
+ unpacker=self._field_unpacker(endian, base_type, field_size),
335
359
  ))
336
360
 
337
361
  dev_field_defs = []
@@ -344,8 +368,9 @@ class FitFileDecoder(DeveloperDataMixin):
344
368
  field=field,
345
369
  dev_data_index=dev_data_index,
346
370
  def_num=field_def_num,
347
- size=field_size
348
- ))
371
+ size=field_size,
372
+ unpacker=self._field_unpacker(endian, field.type, field_size),
373
+ ))
349
374
 
350
375
  def_mesg = DefinitionMessage(
351
376
  header=header,
@@ -358,24 +383,32 @@ class FitFileDecoder(DeveloperDataMixin):
358
383
  self._local_mesgs[header.local_mesg_num] = def_mesg
359
384
  return def_mesg
360
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
+
361
392
  def _parse_raw_values_from_data_message(self, def_mesg):
362
393
  # Go through mesg's field defs and read them
363
394
  raw_values = []
364
395
  for field_def in def_mesg.field_defs + def_mesg.dev_field_defs:
365
396
  base_type = field_def.base_type
366
397
  is_byte = base_type.name == 'byte'
367
- # Struct to read n base types (field def size / base type size)
368
- 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))
369
401
 
370
- # Extract the raw value, ask for a tuple if it's a byte type
371
402
  try:
372
- raw_value = self._read_struct(
373
- struct_fmt, endian=def_mesg.endian, always_tuple=is_byte,
374
- )
403
+ raw_value = unpacker.unpack(self._read(unpacker.size))
375
404
  except FitEOFError:
405
+ if self.allow_truncated:
406
+ raise
376
407
  # file was suddenly terminated
377
408
  warnings.warn("File was terminated unexpectedly, some data will not be loaded.")
378
409
  break
410
+ if len(raw_value) == 1 and not is_byte:
411
+ raw_value = raw_value[0]
379
412
 
380
413
  # If the field returns with a tuple of values it's definitely an
381
414
  # oddball, but we'll parse it on a per-value basis it.
@@ -390,20 +423,39 @@ class FitFileDecoder(DeveloperDataMixin):
390
423
  return raw_values
391
424
 
392
425
  @staticmethod
393
- def _resolve_subfield(field, def_mesg, raw_values):
426
+ def _resolve_subfield(field, ref_values):
394
427
  # Resolve into (field, parent) ie (subfield, field) or (field, None)
395
428
  if field.subfields:
396
429
  for sub_field in field.subfields:
397
- # Go through reference fields for this sub field
398
430
  for ref_field in sub_field.ref_fields:
399
- # Go through field defs AND their raw values
400
- for field_def, raw_value in zip(def_mesg.field_defs, raw_values):
401
- # If there's a definition number AND raw value match on the
402
- # reference field, then we return this subfield
403
- if (field_def.def_num == ref_field.def_num) and (ref_field.raw_value == raw_value):
404
- return sub_field, field
431
+ if ref_values.get(ref_field.def_num) == ref_field.raw_value:
432
+ return sub_field, field
405
433
  return field, None
406
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
+
407
459
  def _apply_scale_offset(self, field, raw_value):
408
460
  # Apply numeric transformations (scale+offset)
409
461
  if isinstance(raw_value, tuple):
@@ -427,6 +479,58 @@ class FitFileDecoder(DeveloperDataMixin):
427
479
 
428
480
  return base_value
429
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
+
430
534
  def _parse_data_message_components(self, header):
431
535
  def_mesg = self._local_mesgs.get(header.local_mesg_num)
432
536
  if not def_mesg:
@@ -434,6 +538,7 @@ class FitFileDecoder(DeveloperDataMixin):
434
538
  header.local_mesg_num))
435
539
 
436
540
  raw_values = self._parse_raw_values_from_data_message(def_mesg)
541
+ ref_values = self._reference_values(def_mesg, raw_values)
437
542
  field_datas = [] # TODO: I don't love this name, update on DataMessage too
438
543
 
439
544
  # TODO: Maybe refactor this and make it simpler (or at least broken
@@ -441,46 +546,9 @@ class FitFileDecoder(DeveloperDataMixin):
441
546
  for field_def, raw_value in zip(def_mesg.field_defs + def_mesg.dev_field_defs, raw_values):
442
547
  field, parent_field = field_def.field, None
443
548
  if field:
444
- field, parent_field = self._resolve_subfield(field, def_mesg, raw_values)
445
-
446
- # Resolve component fields
447
- if field.components:
448
- for component in field.components:
449
- # Render its raw value
450
- try:
451
- cmp_raw_value = component.render(raw_value)
452
- except ValueError:
453
- continue
454
-
455
- # Apply accumulated value
456
- if component.accumulate and cmp_raw_value is not None:
457
- accumulator = self._accumulators[def_mesg.mesg_num]
458
- cmp_raw_value = self._apply_compressed_accumulation(
459
- cmp_raw_value, accumulator[component.def_num], component.bits,
460
- )
461
- accumulator[component.def_num] = cmp_raw_value
462
-
463
- # Apply scale and offset from component, not from the dynamic field
464
- # as they may differ
465
- cmp_raw_value = self._apply_scale_offset(component, cmp_raw_value)
466
-
467
- # Extract the component's dynamic field from def_mesg
468
- cmp_field = def_mesg.mesg_type.fields[component.def_num]
469
-
470
- # Resolve a possible subfield
471
- cmp_field, cmp_parent_field = self._resolve_subfield(cmp_field, def_mesg, raw_values)
472
- cmp_value = cmp_field.render(cmp_raw_value)
473
-
474
- # Plop it on field_datas
475
- field_datas.append(
476
- FieldData(
477
- field_def=None,
478
- field=cmp_field,
479
- parent_field=cmp_parent_field,
480
- value=cmp_value,
481
- raw_value=cmp_raw_value,
482
- )
483
- )
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,))
484
552
 
485
553
  # TODO: Do we care about a base_type and a resolved field mismatch?
486
554
  # My hunch is we don't
@@ -623,12 +691,13 @@ class DataProcessorMixin:
623
691
  class UncachedFitFile(DataProcessorMixin, FitFileDecoder):
624
692
  """FitFileDecoder with data processing"""
625
693
 
626
- 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):
627
695
  # Ensure all optional params are passed as kwargs
628
696
  super().__init__(
629
697
  fileish,
630
698
  *args,
631
699
  check_crc=check_crc,
700
+ allow_truncated=allow_truncated,
632
701
  data_processor=data_processor,
633
702
  **kwargs
634
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:
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
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-fitparse
3
- Version: 2.10.0
3
+ Version: 2.13.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
@@ -34,13 +34,14 @@ Classifier: Development Status :: 5 - Production/Stable
34
34
  Classifier: Intended Audience :: Developers
35
35
  Classifier: License :: OSI Approved :: MIT License
36
36
  Classifier: Programming Language :: Python :: 3
37
- Classifier: Programming Language :: Python :: 3.8
38
- Classifier: Programming Language :: Python :: 3.9
39
37
  Classifier: Programming Language :: Python :: 3.10
40
38
  Classifier: Programming Language :: Python :: 3.11
41
39
  Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Programming Language :: Python :: 3.13
41
+ Classifier: Programming Language :: Python :: 3.14
42
+ Classifier: Programming Language :: Python :: 3.15
42
43
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
43
- Requires-Python: >=3.8
44
+ Requires-Python: >=3.10
44
45
  Provides-Extra: generate
45
46
  Requires-Dist: openpyxl==3.1.5; extra == 'generate'
46
47
  Requires-Dist: requests; extra == 'generate'
@@ -0,0 +1,12 @@
1
+ fitparse/__init__.py,sha256=X8-iSTwkUyJIGQKoGroGtYHQ-fyPGQmJ8zjWh58Dfik,486
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.13.0.dist-info/METADATA,sha256=-ZQRl2Yvzfpjk1z8Uwlsc8Lyl5NAgWtm4dP8qUJvin0,4196
9
+ python_fitparse-2.13.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ python_fitparse-2.13.0.dist-info/entry_points.txt,sha256=4OUq-aV4hvyCK8CwHGiaM6zkn8nYBn1dbFqE6zaBEoA,50
11
+ python_fitparse-2.13.0.dist-info/licenses/LICENSE,sha256=RK-rKfCYWql9q58dgvYwpDuo-N4g0L4iXxr8D5ubMIo,1157
12
+ python_fitparse-2.13.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=Mgm3iX4RBSvx2No1GKqx-2zwoHblvGsqdzR9aSnCxZA,25082
3
- fitparse/processors.py,sha256=vLQi32r1_0DejyMAofxBarhyz0sE1W7vcUCjWahcFs8,5372
4
- fitparse/profile.py,sha256=BZ7-gxXLnekCNKASgpLqCs1Dz-lYX5onjZNRBaAntrA,695175
5
- fitparse/records.py,sha256=8agfso31ONipGCGcJrmDaiiB_yLUAZUZRLGYIuLAuZE,14490
6
- fitparse/utils.py,sha256=cYmAKRktsiTKpxAAvp9XwjfN2BKzEP9-0fAKoTTu_Sw,1750
7
- python_fitparse-2.10.0.dist-info/METADATA,sha256=RV9fZy4_WRy6Z-tbb1ytkHeNi3MvYLzp4a2uTu46-Qk,4142
8
- python_fitparse-2.10.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
- python_fitparse-2.10.0.dist-info/entry_points.txt,sha256=cM-FrZMgY175Od7pYZX7yu48XDynph8o2w-FBOBIyRU,49
10
- python_fitparse-2.10.0.dist-info/licenses/LICENSE,sha256=RK-rKfCYWql9q58dgvYwpDuo-N4g0L4iXxr8D5ubMIo,1157
11
- python_fitparse-2.10.0.dist-info/RECORD,,
@@ -1,2 +0,0 @@
1
- [console_scripts]
2
- fitdump = scripts.fitdump:main