python-fitparse 2.8.0__tar.gz → 2.12.0__tar.gz

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.
@@ -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
@@ -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
  )
@@ -1,5 +1,3 @@
1
- #!/usr/bin/env python
2
-
3
1
  import argparse
4
2
  import codecs
5
3
  import datetime
@@ -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).
@@ -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
  ),
@@ -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:
@@ -10,15 +10,15 @@ MESSAGE_INFO = MessageInfo(
10
10
  group_name='',
11
11
  fields=[
12
12
  FieldInfo(
13
- name='date',
13
+ name='name',
14
14
  type='string',
15
- num=8,
15
+ num=0,
16
16
  scale=None,
17
17
  offset=None,
18
18
  units=None,
19
19
  components=[],
20
20
  subfields=[],
21
- comment='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.'
21
+ comment='Label shown on the device, defaults to the save date and time (e.g. 22 Feb 15:12)'
22
22
  ),
23
23
  FieldInfo(
24
24
  name='position_lat',
@@ -43,27 +43,27 @@ MESSAGE_INFO = MessageInfo(
43
43
  comment=''
44
44
  ),
45
45
  FieldInfo(
46
- name='count',
46
+ name='altitude',
47
47
  type='uint16',
48
- num=3,
49
- scale=None,
50
- offset=None,
51
- units=None,
48
+ num=4,
49
+ scale=5,
50
+ offset=500,
51
+ units='m',
52
52
  components=[],
53
53
  subfields=[],
54
- comment=''
54
+ comment='Inferred from saved locations: values follow the standard FIT altitude encoding'
55
55
  ),
56
56
  FieldInfo(
57
- name='clock_time',
58
- type='uint16',
59
- num=4,
57
+ name='message_index',
58
+ type='message_index',
59
+ num=254,
60
60
  scale=None,
61
61
  offset=None,
62
- units='min',
62
+ units=None,
63
63
  components=[],
64
64
  subfields=[],
65
- comment='UTC timestamp used to set the devices clock and date'
65
+ comment=''
66
66
  ),
67
67
  ],
68
68
  comment=''
69
- )
69
+ )
@@ -0,0 +1,69 @@
1
+ # patches/message_types/record.py
2
+ import sys
3
+ import os
4
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'scripts'))
5
+ from generate_profile import MessageInfo, FieldInfo
6
+
7
+ MESSAGE_INFO = MessageInfo(
8
+ name='record',
9
+ num=20,
10
+ group_name='',
11
+ fields=[
12
+ FieldInfo(
13
+ name='performance_condition',
14
+ type='sint8',
15
+ num=90,
16
+ scale=None,
17
+ offset=None,
18
+ units=None,
19
+ components=[],
20
+ subfields=[],
21
+ comment='Inferred: -7 to 9 on real runs, and never present before six minutes into the activity'
22
+ ),
23
+ FieldInfo(
24
+ name='wrist_heart_rate',
25
+ type='uint8',
26
+ num=136,
27
+ scale=None,
28
+ offset=None,
29
+ units='bpm',
30
+ components=[],
31
+ subfields=[],
32
+ comment='Inferred: equals heart_rate in all but 2 of 171,509 records'
33
+ ),
34
+ FieldInfo(
35
+ name='stamina_potential',
36
+ type='uint8',
37
+ num=137,
38
+ scale=None,
39
+ offset=None,
40
+ units='percent',
41
+ components=[],
42
+ subfields=[],
43
+ comment='Inferred: starts near 100 and falls over an activity, never below stamina'
44
+ ),
45
+ FieldInfo(
46
+ name='stamina',
47
+ type='uint8',
48
+ num=138,
49
+ scale=None,
50
+ offset=None,
51
+ units='percent',
52
+ components=[],
53
+ subfields=[],
54
+ comment='Inferred: 1 to 100, never above stamina_potential'
55
+ ),
56
+ FieldInfo(
57
+ name='body_battery',
58
+ type='uint8',
59
+ num=143,
60
+ scale=None,
61
+ offset=None,
62
+ units='percent',
63
+ components=[],
64
+ subfields=[],
65
+ comment='Inferred: within 0.3 on average of the stress_level body_battery of the same 3-minute slot'
66
+ ),
67
+ ],
68
+ comment=''
69
+ )
@@ -0,0 +1,37 @@
1
+ # patches/message_types/skin_temp_sample.py
2
+ import sys
3
+ import os
4
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'scripts'))
5
+ from generate_profile import MessageInfo, FieldInfo
6
+
7
+ MESSAGE_INFO = MessageInfo(
8
+ name='skin_temp_sample',
9
+ num=397,
10
+ group_name='',
11
+ fields=[
12
+ FieldInfo(
13
+ name='deviation',
14
+ type='float32',
15
+ num=1,
16
+ scale=None,
17
+ offset=None,
18
+ units='C',
19
+ components=[],
20
+ subfields=[],
21
+ comment='Inferred: one per minute over the day before skin_temp_overnight, -11 to +5; '
22
+ 'the baseline is unconfirmed, the sleep-window mean sits about 1 C below average_deviation'
23
+ ),
24
+ FieldInfo(
25
+ name='timestamp',
26
+ type='date_time',
27
+ num=253,
28
+ scale=None,
29
+ offset=None,
30
+ units='s',
31
+ components=[],
32
+ subfields=[],
33
+ comment=''
34
+ ),
35
+ ],
36
+ comment='Undocumented per-minute skin temperature, found only in SkinTemp files'
37
+ )
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "python-fitparse"
7
- version = "2.8.0"
7
+ version = "2.12.0"
8
8
  description = "Python library to parse ANT/Garmin .FIT files"
9
9
  authors = [
10
10
  {name = "David Cooper", email = "dave@kupesoft.com"},
@@ -33,7 +33,7 @@ Repository = "https://github.com/nbr23/python-fitparse"
33
33
  Issues = "https://github.com/nbr23/python-fitparse/issues"
34
34
 
35
35
  [project.scripts]
36
- fitdump = "scripts.fitdump:main"
36
+ fitdump = "fitparse.fitdump:main"
37
37
 
38
38
  # Dependencies needed for profile generation
39
39
  [project.optional-dependencies]
@@ -44,7 +44,6 @@ generate = [
44
44
 
45
45
  [tool.hatch.build.targets.wheel]
46
46
  packages = ["fitparse"]
47
- artifacts = ["scripts/fitdump"]
48
47
 
49
48
  [tool.hatch.build.targets.sdist]
50
49
  include = [
@@ -18,6 +18,7 @@
18
18
 
19
19
  from collections import namedtuple
20
20
  import datetime
21
+ import hashlib
21
22
  import os
22
23
  import re
23
24
  import sys
@@ -32,6 +33,8 @@ import glob
32
33
 
33
34
  FIELD_NUM_TIMESTAMP = 253
34
35
 
36
+ DOWNLOAD_TIMEOUT = 60
37
+
35
38
  XLS_HEADER_MAGIC = b'\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1'
36
39
 
37
40
  SYMBOL_NAME_SCRUBBER = re.compile(r'\W|^(?=\d)')
@@ -545,10 +548,12 @@ def parse_messages(messages_rows, type_list):
545
548
  )
546
549
 
547
550
  assert len(subfield.ref_fields) == len(ref_field_names)
548
- if "alert_type" not in ref_field_names:
549
- field.subfields.append(subfield)
551
+ field.subfields.append(subfield)
552
+
553
+ return message_list
550
554
 
551
- # Resolve reference fields for subfields and components
555
+
556
+ def resolve_references(message_list, type_list):
552
557
  for message in message_list.messages:
553
558
  for field in message.fields:
554
559
  for sub_field in field.subfields:
@@ -572,8 +577,6 @@ def parse_messages(messages_rows, type_list):
572
577
  )
573
578
  bit_offset += component.bits
574
579
 
575
- return message_list
576
-
577
580
 
578
581
  def get_xls_and_version_from_zip(path):
579
582
  archive = zipfile.ZipFile(path, 'r')
@@ -591,41 +594,40 @@ def get_xls_and_version_from_zip(path):
591
594
  except KeyError:
592
595
  return archive.open('Profile.xlsx'), profile_version
593
596
 
597
+
598
+ class PatchError(Exception):
599
+ pass
600
+
601
+
602
+ PATCH_ATTRIBUTES = {
603
+ 'message_types': ('MESSAGE_INFO', lambda info: info.num),
604
+ 'field_types': ('TYPE_INFO', lambda info: info.name),
605
+ }
606
+
607
+
594
608
  def load_patches_from_directory(patches_dir, patch_type):
595
- patches = {}
609
+ if patch_type not in PATCH_ATTRIBUTES:
610
+ raise PatchError(f"Unknown patch type {patch_type}")
611
+ attribute, key_of = PATCH_ATTRIBUTES[patch_type]
596
612
 
613
+ patches = {}
597
614
  if not os.path.exists(patches_dir):
598
615
  return patches
599
616
 
600
- patch_files = glob.glob(os.path.join(patches_dir, "*.py"))
617
+ for patch_file in sorted(glob.glob(os.path.join(patches_dir, "*.py"))):
618
+ spec = importlib.util.spec_from_file_location("patch_module", patch_file)
619
+ patch_module = importlib.util.module_from_spec(spec)
620
+ spec.loader.exec_module(patch_module)
601
621
 
602
- for patch_file in patch_files:
603
- try:
604
- spec = importlib.util.spec_from_file_location("patch_module", patch_file)
605
- patch_module = importlib.util.module_from_spec(spec)
606
- spec.loader.exec_module(patch_module)
622
+ if not hasattr(patch_module, attribute):
623
+ raise PatchError(f"{patch_file} has no {attribute}")
624
+ patch_obj = getattr(patch_module, attribute)
625
+ patch_key = key_of(patch_obj)
626
+ if patch_key in patches:
627
+ raise PatchError(f"{patch_file} patches {patch_type} {patch_key}, already patched by another file")
607
628
 
608
- if patch_type == 'message_types':
609
- if not hasattr(patch_module, 'MESSAGE_INFO'):
610
- print(f"Warning: {patch_file} missing MESSAGE_INFO, skipping")
611
- continue
612
- patch_obj = patch_module.MESSAGE_INFO
613
- patch_key = patch_obj.num
614
- elif patch_type == 'field_types':
615
- if not hasattr(patch_module, 'TYPE_INFO'):
616
- print(f"Warning: {patch_file} missing TYPE_INFO, skipping")
617
- continue
618
- patch_obj = patch_module.TYPE_INFO
619
- patch_key = patch_obj.name
620
- else:
621
- print(f"Warning: Unknown patch type {patch_type}")
622
- continue
623
-
624
- print(f"Loaded patch: {patch_type} - {patch_key}")
625
- patches[patch_key] = patch_obj
626
-
627
- except Exception as e:
628
- print(f"Error loading patch {patch_file}: {e}")
629
+ print(f"Loaded patch: {patch_type} - {patch_key}")
630
+ patches[patch_key] = patch_obj
629
631
 
630
632
  return patches
631
633
 
@@ -642,6 +644,69 @@ def load_field_type_patches():
642
644
  return load_patches_from_directory(patches_dir, 'field_types')
643
645
 
644
646
 
647
+ def merge_type_values(existing_type, patch_type_info):
648
+ if existing_type.base_type != patch_type_info.base_type:
649
+ raise PatchError(
650
+ f"Field type {existing_type.name} is {existing_type.base_type} in the SDK, "
651
+ f"the patch declares {patch_type_info.base_type}"
652
+ )
653
+ existing_values = {normalize_def_num(v.value): v for v in existing_type.values}
654
+ added = 0
655
+ for patch_value in patch_type_info.values:
656
+ official = existing_values.get(normalize_def_num(patch_value.value))
657
+ if official is None:
658
+ existing_type.values.append(patch_value)
659
+ added += 1
660
+ print(f" Added value: {existing_type.name}.{patch_value.name} ({patch_value.value})")
661
+ elif official.name != patch_value.name:
662
+ raise PatchError(
663
+ f"{existing_type.name} value {patch_value.value} is '{official.name}' in the SDK, "
664
+ f"the patch names it '{patch_value.name}'"
665
+ )
666
+ else:
667
+ print(f" Redundant value: {existing_type.name}.{patch_value.name} is in the SDK, remove it from the patch")
668
+ return added
669
+
670
+
671
+ def merge_subfields(message_name, existing_field, patch_field):
672
+ existing_names = {s.name for s in existing_field.subfields}
673
+ added = 0
674
+ for patch_subfield in patch_field.subfields:
675
+ if patch_subfield.name in existing_names:
676
+ print(f" Redundant subfield: {message_name}.{existing_field.name}.{patch_subfield.name} is in the SDK")
677
+ else:
678
+ existing_field.subfields.append(patch_subfield)
679
+ added += 1
680
+ print(f" Added subfield: {message_name}.{existing_field.name}.{patch_subfield.name}")
681
+ return added
682
+
683
+
684
+ def merge_message_fields(existing_message, patch_message_info):
685
+ if existing_message.name != patch_message_info.name:
686
+ raise PatchError(
687
+ f"Message {patch_message_info.num} is '{existing_message.name}' in the SDK, "
688
+ f"the patch names it '{patch_message_info.name}'"
689
+ )
690
+ existing_fields = {normalize_def_num(f.num): f for f in existing_message.fields}
691
+ added = 0
692
+ for patch_field in patch_message_info.fields:
693
+ official = existing_fields.get(normalize_def_num(patch_field.num))
694
+ if official is None:
695
+ existing_message.fields.append(patch_field)
696
+ added += 1
697
+ print(f" Added field: {existing_message.name}.{patch_field.name} (def_num {patch_field.num})")
698
+ elif official.name != patch_field.name:
699
+ raise PatchError(
700
+ f"{existing_message.name} field {patch_field.num} is '{official.name}' in the SDK, "
701
+ f"the patch names it '{patch_field.name}'"
702
+ )
703
+ else:
704
+ added += merge_subfields(existing_message.name, official, patch_field)
705
+ print(f" Field {existing_message.name}.{patch_field.name} is in the SDK now, "
706
+ f"only its patched subfields still apply")
707
+ return added
708
+
709
+
645
710
  def apply_patches(type_list, message_list):
646
711
  print("Loading patches...")
647
712
  applied = 0
@@ -650,36 +715,28 @@ def apply_patches(type_list, message_list):
650
715
  if field_type_patches:
651
716
  print(f"Applying {len(field_type_patches)} field type patches...")
652
717
  for patch_name, patch_type_info in field_type_patches.items():
653
- if not type_list.get(patch_name, raise_exception=False):
718
+ existing_type = type_list.get(patch_name, raise_exception=False)
719
+ if existing_type:
720
+ applied += merge_type_values(existing_type, patch_type_info)
721
+ else:
654
722
  type_list.types.append(patch_type_info)
655
723
  applied += 1
656
724
  print(f" Added field type: {patch_name}")
657
- else:
658
- print(f" Skipped field type: {patch_name} (already exists in generated profile)")
659
725
 
660
726
  message_type_patches = load_message_type_patches()
661
727
  if message_type_patches:
662
728
  print(f"Applying {len(message_type_patches)} message type patches...")
663
729
  for patch_num, patch_message_info in message_type_patches.items():
664
- existing_message = None
665
- for msg in message_list.messages:
666
- if msg.num == patch_num:
667
- existing_message = msg
668
- break
669
-
670
- if not existing_message:
730
+ existing_message = next(
731
+ (m for m in message_list.messages if normalize_def_num(m.num) == normalize_def_num(patch_num)),
732
+ None,
733
+ )
734
+ if existing_message:
735
+ applied += merge_message_fields(existing_message, patch_message_info)
736
+ else:
671
737
  message_list.messages.append(patch_message_info)
672
738
  applied += 1
673
739
  print(f" Added message type: {patch_message_info.name} (num: {patch_num})")
674
- else:
675
- existing_nums = {normalize_def_num(f.num) for f in existing_message.fields}
676
- for patch_field in patch_message_info.fields:
677
- if normalize_def_num(patch_field.num) in existing_nums:
678
- print(f" Skipped field: {existing_message.name}.{patch_field.name} (def_num {patch_field.num} already defined)")
679
- else:
680
- existing_message.fields.append(patch_field)
681
- applied += 1
682
- print(f" Added field: {existing_message.name}.{patch_field.name} (def_num {patch_field.num})")
683
740
 
684
741
  return applied
685
742
 
@@ -688,10 +745,8 @@ def download_latest_sdk(path):
688
745
  repo_url = 'https://api.github.com/repos/garmin/fit-sdk-tools/releases/latest'
689
746
  print("Fetching latest SDK release from GitHub...")
690
747
 
691
- r = requests.get(repo_url)
692
- if r.status_code != 200:
693
- print(f"Failed to fetch GitHub releases: {r.status_code}")
694
- sys.exit(1)
748
+ r = requests.get(repo_url, timeout=DOWNLOAD_TIMEOUT)
749
+ r.raise_for_status()
695
750
 
696
751
  release_data = r.json()
697
752
 
@@ -705,16 +760,29 @@ def download_latest_sdk(path):
705
760
  print("Couldn't find Profile.xlsx in latest release. Exiting.")
706
761
  sys.exit(1)
707
762
 
763
+ algorithm, _, expected_digest = (profile_asset.get('digest') or '').partition(':')
764
+ if algorithm != 'sha256' or not expected_digest:
765
+ print("Profile.xlsx has no sha256 digest in the release metadata. Exiting.")
766
+ sys.exit(1)
767
+
708
768
  download_url = profile_asset['browser_download_url']
709
769
  print("Downloading Profile.xlsx from %s" % download_url)
710
770
 
711
- r = requests.get(download_url, stream=True)
771
+ r = requests.get(download_url, stream=True, timeout=DOWNLOAD_TIMEOUT)
772
+ r.raise_for_status()
712
773
 
774
+ sha256 = hashlib.sha256()
713
775
  with open(path, 'wb') as f:
714
776
  for chunk in r.iter_content(chunk_size=1024):
715
777
  if chunk:
778
+ sha256.update(chunk)
716
779
  f.write(chunk)
717
780
 
781
+ if sha256.hexdigest() != expected_digest:
782
+ print("Profile.xlsx sha256 {} does not match the release digest {}. Exiting.".format(
783
+ sha256.hexdigest(), expected_digest))
784
+ sys.exit(1)
785
+
718
786
  tag_name = release_data.get('tag_name', '')
719
787
  version_match = re.search(r'(\d+\.\d+)', tag_name)
720
788
  if version_match:
@@ -754,6 +822,7 @@ def main(input_xls_or_zip, output_py_path=None):
754
822
  message_list = parse_messages(messages_rows, type_list)
755
823
 
756
824
  patches_applied = apply_patches(type_list, message_list)
825
+ resolve_references(message_list, type_list)
757
826
 
758
827
  mesg_num_declarations = []
759
828
  for mesg_name in MESSAGE_NUM_DECLARATIONS:
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env python
2
+
3
+ import importlib.machinery
4
+ import importlib.util
5
+ import itertools
6
+ import os
7
+ import sys
8
+ from dataclasses import dataclass, field
9
+
10
+ _module_ids = itertools.count()
11
+
12
+
13
+ @dataclass
14
+ class ProfileDiff:
15
+ added: list = field(default_factory=list)
16
+ removed: list = field(default_factory=list)
17
+ renamed: list = field(default_factory=list)
18
+ changed: list = field(default_factory=list)
19
+
20
+ @property
21
+ def breaking(self):
22
+ return bool(self.removed or self.renamed)
23
+
24
+ def __bool__(self):
25
+ return bool(self.added or self.removed or self.renamed or self.changed)
26
+
27
+
28
+ def load_profile(path):
29
+ name = 'profile_snapshot_%d' % next(_module_ids)
30
+ loader = importlib.machinery.SourceFileLoader(name, path)
31
+ spec = importlib.util.spec_from_loader(name, loader)
32
+ module = importlib.util.module_from_spec(spec)
33
+ loader.exec_module(module)
34
+ return module.FIELD_TYPES, module.MESSAGE_TYPES
35
+
36
+
37
+ def _components(components):
38
+ return tuple(
39
+ (c.name, c.def_num, c.scale, c.offset, c.units, c.accumulate, c.bits, c.bit_offset)
40
+ for c in components or ()
41
+ )
42
+
43
+
44
+ def _field_shape(f):
45
+ return {
46
+ 'type': f.type.name,
47
+ 'scale': f.scale,
48
+ 'offset': f.offset,
49
+ 'units': f.units,
50
+ 'components': _components(f.components),
51
+ }
52
+
53
+
54
+ def _subfield_shape(s):
55
+ shape = _field_shape(s)
56
+ shape['ref_fields'] = tuple((r.def_num, r.raw_value) for r in s.ref_fields or ())
57
+ return shape
58
+
59
+
60
+ def _describe_change(label, old_shape, new_shape):
61
+ changes = [
62
+ '{} {!r} -> {!r}'.format(key, old_shape[key], new_shape[key])
63
+ for key in old_shape
64
+ if old_shape[key] != new_shape[key]
65
+ ]
66
+ return '{}: {}'.format(label, ', '.join(changes)) if changes else None
67
+
68
+
69
+ def _diff_keyed(old, new, describe, diff, on_common=None):
70
+ for key in sorted(new.keys() - old.keys()):
71
+ diff.added.append(describe(key, new[key]))
72
+ for key in sorted(old.keys() - new.keys()):
73
+ diff.removed.append(describe(key, old[key]))
74
+ for key in sorted(old.keys() & new.keys()):
75
+ if on_common:
76
+ on_common(key, old[key], new[key])
77
+
78
+
79
+ def _diff_types(old_types, new_types, diff):
80
+ def common(name, old, new):
81
+ if old.base_type.name != new.base_type.name:
82
+ diff.changed.append('type `{}`: base_type {} -> {}'.format(name, old.base_type.name, new.base_type.name))
83
+ old_values, new_values = old.values or {}, new.values or {}
84
+ _diff_keyed(
85
+ old_values, new_values,
86
+ lambda value, label: 'value `{}.{}` ({})'.format(name, label, value),
87
+ diff,
88
+ )
89
+ for value in sorted(old_values.keys() & new_values.keys()):
90
+ if old_values[value] != new_values[value]:
91
+ diff.renamed.append('value `{}` {}: `{}` -> `{}`'.format(
92
+ name, value, old_values[value], new_values[value]))
93
+
94
+ _diff_keyed(old_types, new_types, lambda name, _: 'type `{}`'.format(name), diff, common)
95
+
96
+
97
+ def _diff_subfields(label, old_field, new_field, diff):
98
+ old_subs = {s.name: s for s in old_field.subfields or ()}
99
+ new_subs = {s.name: s for s in new_field.subfields or ()}
100
+
101
+ def common(name, old, new):
102
+ change = _describe_change('subfield `{}.{}`'.format(label, name), _subfield_shape(old), _subfield_shape(new))
103
+ if change:
104
+ diff.changed.append(change)
105
+
106
+ _diff_keyed(old_subs, new_subs, lambda name, _: 'subfield `{}.{}`'.format(label, name), diff, common)
107
+
108
+
109
+ def _diff_fields(mesg_name, old_fields, new_fields, diff):
110
+ def common(def_num, old, new):
111
+ if old.name != new.name:
112
+ diff.renamed.append('field `{}` {}: `{}` -> `{}`'.format(mesg_name, def_num, old.name, new.name))
113
+ label = '{}.{}'.format(mesg_name, new.name)
114
+ change = _describe_change('field `{}`'.format(label), _field_shape(old), _field_shape(new))
115
+ if change:
116
+ diff.changed.append(change)
117
+ _diff_subfields(label, old, new, diff)
118
+
119
+ _diff_keyed(
120
+ old_fields, new_fields,
121
+ lambda def_num, f: 'field `{}.{}` ({})'.format(mesg_name, f.name, def_num),
122
+ diff, common,
123
+ )
124
+
125
+
126
+ def _diff_messages(old_messages, new_messages, diff):
127
+ def common(mesg_num, old, new):
128
+ if old.name != new.name:
129
+ diff.renamed.append('message {}: `{}` -> `{}`'.format(mesg_num, old.name, new.name))
130
+ _diff_fields(new.name, old.fields, new.fields, diff)
131
+
132
+ _diff_keyed(
133
+ old_messages, new_messages,
134
+ lambda mesg_num, m: 'message `{}` ({})'.format(m.name, mesg_num),
135
+ diff, common,
136
+ )
137
+
138
+
139
+ def diff_profiles(old, new):
140
+ diff = ProfileDiff()
141
+ _diff_types(old[0], new[0], diff)
142
+ _diff_messages(old[1], new[1], diff)
143
+ return diff
144
+
145
+
146
+ def render_markdown(diff):
147
+ if not diff:
148
+ return 'No changes to the decoded profile.\n'
149
+ sections = [
150
+ ('Removed', diff.removed),
151
+ ('Renamed', diff.renamed),
152
+ ('Added', diff.added),
153
+ ('Changed', diff.changed),
154
+ ]
155
+ out = ['## Profile changes', '']
156
+ if diff.breaking:
157
+ out += ['**Removals or renames: this update breaks existing consumers and needs a patch or a manual decision.**', '']
158
+ for title, entries in sections:
159
+ if entries:
160
+ out += ['### {} ({})'.format(title, len(entries)), '']
161
+ out += ['- {}'.format(entry) for entry in entries]
162
+ out.append('')
163
+ return '\n'.join(out)
164
+
165
+
166
+ def main(argv):
167
+ if len(argv) != 3:
168
+ print('Usage: %s <old profile.py> <new profile.py>' % os.path.basename(argv[0]), file=sys.stderr)
169
+ return 2
170
+ diff = diff_profiles(load_profile(argv[1]), load_profile(argv[2]))
171
+ sys.stdout.write(render_markdown(diff))
172
+ return 1 if diff.breaking else 0
173
+
174
+
175
+ if __name__ == '__main__':
176
+ sys.exit(main(sys.argv))