forked from Lizzard44/zero-log-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzero_log_parser.py
More file actions
executable file
·3490 lines (3016 loc) · 147 KB
/
zero_log_parser.py
File metadata and controls
executable file
·3490 lines (3016 loc) · 147 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Little decoder utility to parse Zero Motorcycle main bike board (MBB) and
battery management system (BMS) logs. These may be extracted from the bike
using the Zero mobile app. Once paired over bluetooth, select 'Support' >
'Email bike logs' and send the logs to yourself rather than / in addition to
zero support.
Usage:
$ python zero_log_parser.py <*.bin file> [-o output_file]
Architecture:
This parser uses a hybrid approach combining Gen2/Gen3 binary parsing with
structured data extraction. Gen2 parsers have been optimized to generate
structured data directly from binary data, eliminating the "string formatting
→ regex re-parsing" overhead that existed previously.
Gen2 Parser Optimization - Completed (19 methods):
- Phase 1: disarmed_status(), bms_contactor_state(), bms_soc_adj_voltage()
- Phase 2: battery_status(), bms_discharge_cut(), bms_contactor_drive()
- Phase 3: bms_curr_sens_zero(), sevcon_status(), bms_isolation_fault(), power_state()
- Phase 4: charger_status(), bms_reflash(), key_state()
- Phase 5: battery_discharge_current_limited(), low_chassis_isolation(), sevcon_power_state(), battery_contactor_closed()
- Additional: vehicle_state_telemetry(), sensor_data()
All optimized parsers use direct binary extraction via BinaryTools.unpack() and
generate structured JSON data with human-readable conditions for all output formats.
This eliminates the previous "string formatting → regex re-parsing" overhead while
maintaining full backward compatibility. Redundant patterns removed from improve_message_parsing.
"""
import codecs
import json
import logging
import os
import re
import string
import struct
from collections import OrderedDict, namedtuple
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from math import trunc
from time import gmtime, localtime, strftime
from typing import Dict, List, Union, Optional
# Parser version - try to import from package, fallback to hardcoded
try:
from src.zero_log_parser import __version__ as PARSER_VERSION
except ImportError:
PARSER_VERSION = "2.2.0" # Fallback version
# Localized time format - use system locale preference
ZERO_TIME_FORMAT = '%Y-%m-%d %H:%M:%S' # ISO format is more universal
# The output from the MBB (via serial port) lists time as GMT-7
MBB_TIMESTAMP_GMT_OFFSET = -7 * 60 * 60
class MismatchingVinError(Exception):
"""Raised when attempting to merge LogData objects with different VINs"""
def __init__(self, vin1, vin2):
self.vin1 = vin1
self.vin2 = vin2
super().__init__(f"Cannot merge logs with different VINs: '{vin1}' != '{vin2}'")
try:
from src.zero_log_parser.utils import get_timezone_offset
except ImportError:
try:
from zero_log_parser.utils import get_timezone_offset
except ImportError:
pass
@dataclass
class ProcessedLogEntry:
"""Standardized log entry structure for all output formats"""
entry_number: int
timestamp: str
sort_timestamp: float
log_level: str
event: str
conditions: str
uninterpreted: str = ""
structured_data: Optional[dict] = None
has_structured_data: bool = False
message_type: str = "unknown"
original_timestamp: Optional[str] = None # Raw timestamp before interpolation
def __eq__(self, other):
"""
Compare ProcessedLogEntry objects based on content, not sequence.
Compares: original_timestamp (or timestamp), event, message_type,
and structured_data if available, otherwise conditions.
Excludes: entry_number, log_level, sort_timestamp, uninterpreted, has_structured_data
"""
if not isinstance(other, ProcessedLogEntry):
return False
# Use original_timestamp if available, fallback to timestamp
self_ts = self.original_timestamp or self.timestamp
other_ts = other.original_timestamp or other.timestamp
# Use structured_data if available, otherwise use conditions
self_content = self.structured_data if self.structured_data else self.conditions
other_content = other.structured_data if other.structured_data else other.conditions
return (
self_ts == other_ts and
self.event == other.event and
self.message_type == other.message_type and
self_content == other_content
)
def __hash__(self):
"""
Generate hash based on content for set operations and deduplication.
Uses same fields as __eq__: original_timestamp (or timestamp), event,
message_type, and structured_data or conditions.
"""
# Use original_timestamp if available, fallback to timestamp
timestamp_val = self.original_timestamp or self.timestamp
# Handle structured_data vs conditions with robust hashing for complex data
if self.structured_data:
# Convert to JSON string for consistent hashing of complex data structures
import json
content_val = json.dumps(self.structured_data, sort_keys=True, separators=(',', ':'))
else:
content_val = self.conditions
return hash((
timestamp_val,
self.event,
self.message_type,
content_val
))
def improve_message_parsing(event_text: str, conditions_text: str = None, verbosity_level: int = 1, logger=None) -> tuple:
"""
Improve message parsing by removing redundant prefixes and converting structured data to JSON.
Args:
event_text: The event text to process
conditions_text: Optional conditions text
verbosity_level: Verbosity level (0=quiet, 1=normal, 2=verbose, 3+=very verbose)
logger: Logger instance for verbose output
Returns tuple: (improved_event, improved_conditions, json_data, has_json_data, was_modified, modification_type)
Note: This method tracks modifications to help identify which Gen2 binary parsers
need to incorporate advanced message parsing directly for optimization.
"""
if not event_text:
return event_text, conditions_text, None, False, False, None
improved_event = event_text
improved_conditions = conditions_text
json_data = None
was_modified = False
modification_type = None
# Remove redundant DEBUG: prefix since we have log_level
original_event = improved_event
if improved_event.startswith('DEBUG: '):
improved_event = improved_event[7:]
was_modified = True
modification_type = "prefix_removal"
elif improved_event.startswith('INFO: '):
improved_event = improved_event[6:]
was_modified = True
modification_type = "prefix_removal"
elif improved_event.startswith('ERROR: '):
improved_event = improved_event[7:]
was_modified = True
modification_type = "prefix_removal"
elif improved_event.startswith('WARNING: '):
improved_event = improved_event[9:]
was_modified = True
modification_type = "prefix_removal"
# Handle edge cases only - most patterns have been moved to optimized Gen2 parsers
try:
# Handle abbreviated hex patterns from newer log formats (2025+)
if re.match(r'^0x[0-9a-f]+(\s+0x[0-9a-f]+)*$', improved_event or '', re.IGNORECASE):
# Parse hex pattern like "0x28 0x02" or "0x01"
hex_parts = improved_event.split()
if len(hex_parts) >= 1:
try:
main_type = int(hex_parts[0], 16)
# Handle specific abbreviated patterns for newer formats
if main_type == 0x28: # Battery CAN Link Up
if len(hex_parts) >= 2:
module_num = int(hex_parts[1], 16)
improved_event = f"Module {module_num:02d} CAN Link Up"
else:
improved_event = "Battery CAN Link Up"
improved_conditions = None
was_modified = True
modification_type = "hex_pattern_expansion"
if verbosity_level >= 2 and logger:
logger.debug(f"Hex pattern expanded: {original_event} → {improved_event} (needs Gen2 optimization)")
elif main_type == 0x29: # Battery CAN Link Down
if len(hex_parts) >= 2:
module_num = int(hex_parts[1], 16)
improved_event = f"Module {module_num:02d} CAN Link Down"
else:
improved_event = "Battery CAN Link Down"
improved_conditions = None
was_modified = True
modification_type = "hex_pattern_expansion"
if verbosity_level >= 2 and logger:
logger.debug(f"Hex pattern expanded: {original_event} → {improved_event} (needs Gen2 optimization)")
else:
# Mark other unknown hex patterns
improved_event = f"Unknown (Type 0x{main_type:02x})"
if len(hex_parts) > 1:
data_parts = [f"0x{int(part, 16):02x}" for part in hex_parts[1:]]
improved_conditions = f"Data: {' '.join(data_parts)}"
else:
improved_conditions = "No additional data"
was_modified = True
modification_type = "hex_pattern_expansion"
if verbosity_level >= 2 and logger:
logger.debug(f"Hex pattern expanded: {original_event} → {improved_event} (needs Gen2 optimization)")
except ValueError:
# If hex conversion fails, mark as malformed
improved_event = f"Unknown - {improved_event}"
improved_conditions = "Malformed hex pattern"
was_modified = True
modification_type = "malformed_hex_handling"
if verbosity_level >= 2 and logger:
logger.debug(f"Malformed hex handled: {original_event} → {improved_event} (needs Gen2 optimization)")
# Handle single character entries (likely corrupted)
elif improved_event and len(improved_event) == 1 and improved_event.isalpha():
improved_event = f"Unknown - Single character: {improved_event}"
improved_conditions = "Possibly corrupted entry"
was_modified = True
modification_type = "corrupted_entry_handling"
if verbosity_level >= 2 and logger:
logger.debug(f"Corrupted entry handled: {original_event} → {improved_event} (needs Gen2 optimization)")
except (ValueError, AttributeError, IndexError):
# If parsing fails, keep original format
pass
# Determine if this entry contains JSON data
has_json_data = json_data is not None
return improved_event, improved_conditions, json_data, has_json_data, was_modified, modification_type
def determine_log_level(message: str) -> str:
"""Determine log level based on message content patterns"""
if not message:
return 'UNKNOWN'
message_upper = message.upper()
# Explicit level indicators (check for redundant prefixes)
if message.startswith('DEBUG:'):
return 'DEBUG'
elif message.startswith('INFO:'):
return 'INFO'
elif message.startswith('ERROR:') or message.startswith('FAULT:'):
return 'ERROR'
elif message.startswith('WARNING:') or message.startswith('WARN:'):
return 'WARNING'
# Error patterns
if any(pattern in message_upper for pattern in [
'ERROR', 'FAULT', 'FAILED', 'FAILURE', 'CRITICAL', 'ALARM',
'ABORT', 'EXCEPTION', 'TIMEOUT'
]):
return 'ERROR'
# Warning patterns
if any(pattern in message_upper for pattern in [
'WARNING', 'WARN', 'CAUTION', 'OVERTEMP', 'UNDERVOLT', 'OVERVOLT'
]):
return 'WARNING'
# State change patterns (important operational states)
if any(pattern in message_upper for pattern in [
'RIDING', 'DISARMED', 'CHARGING', 'ARMED', 'STANDBY',
'POWER ON', 'POWER OFF', 'SLEEP', 'WAKE', 'BOOT',
'STARTUP', 'SHUTDOWN', 'CONNECTED', 'DISCONNECTED'
]):
return 'STATE'
# System/informational patterns
if any(pattern in message_upper for pattern in [
'MODULE', 'SEVCON', 'CONTACTOR', 'TEMPERATURE', 'VOLTAGE',
'CURRENT', 'BATTERY', 'MOTOR', 'CONFIG', 'SETTING'
]):
return 'INFO'
# Debug patterns (verbose/detailed info)
if any(pattern in message_upper for pattern in [
'DEBUG', 'TRACE', 'VERBOSE', 'DETAIL'
]):
return 'DEBUG'
# Default to INFO for unmatched messages
return 'INFO'
# noinspection PyMissingOrEmptyDocstring
class BinaryTools:
"""
Utility class for dealing with serialised data from the Zero's
"""
TYPES = {
'int8': 'b',
'uint8': 'B',
'int16': 'h',
'uint16': 'H',
'int32': 'l',
'uint32': 'L',
'int64': 'q',
'uint64': 'Q',
'float': 'f',
'double': 'd',
'char': 's',
'bool': '?'
}
TYPE_CONVERSIONS = {
'int8': int,
'uint8': int,
'int16': int,
'uint16': int,
'int32': int,
'uint32': int,
'int64': int,
'uint64': int,
'float': float,
'double': float,
'char': None, # chr
'bool': bool
}
@classmethod
def unpack(cls,
type_name: str,
buff: bytearray,
address: int,
count=1, offset=0) -> Union[bytearray, int, float, bool]:
# noinspection PyAugmentAssignment
buff = buff + bytearray(32)
type_key = type_name.lower()
type_char = cls.TYPES[type_key]
type_convert = cls.TYPE_CONVERSIONS[type_key]
type_format = '<{}{}'.format(count, type_char)
unpacked = struct.unpack_from(type_format, buff, address + offset)[0]
if type_convert:
# if count > 1:
# return [type_convert(each) for each in unpacked]
# else:
return type_convert(unpacked)
else:
return unpacked
@staticmethod
def unescape_block(data):
start_offset = 0
escape_offset = data.find(b'\xfe')
while escape_offset != -1:
escape_offset += start_offset
if escape_offset + 1 < len(data):
data[escape_offset] = data[escape_offset] ^ data[escape_offset + 1] - 1
data = data[0:escape_offset + 1] + data[escape_offset + 2:]
start_offset = escape_offset + 1
escape_offset = data[start_offset:].find(b'\xfe')
return data
@staticmethod
def decode_str(log_text_segment: bytearray, encoding='utf-8') -> str:
"""Decodes UTF-8 strings from a test segment, ignoring any errors"""
return log_text_segment.decode(encoding=encoding, errors='ignore')
@classmethod
def unpack_str(cls, log_text_segment: bytearray, address, count=1, offset=0,
encoding='utf-8') -> str:
"""Unpacks and decodes UTF-8 strings from a test segment, ignoring any errors"""
unpacked = cls.unpack('char', log_text_segment, address, count, offset)
return cls.decode_str(unpacked.partition(b'\0')[0], encoding=encoding)
@staticmethod
def is_printable(bytes_or_str: str) -> bool:
return all(c in string.printable for c in bytes_or_str)
@classmethod
def bms_discharge_level_binary(cls, x):
# Enhanced BMS discharge decoder with state names and better formatting
state_names = {
0x01: 'Bike On',
0x02: 'Charge',
0x03: 'Idle'
}
return {
'event': 'BMS Discharge Level',
'conditions':
'{AH:03.0f}Ah, SOC:{SOC:3d}%, I:{I:+4.0f}A, State:{STATE}, '
'LowCell:{L}mV, HighCell:{H}mV, Balance:{B:+4d}mV, UnloadedCell:{l}mV, '
'PackTemp:{PT:3d}°C, BMSTemp:{BT:3d}°C, PackV:{PV:6.1f}V'.format(
AH=trunc(BinaryTools.unpack('uint32', x, 0x06) / 1000000.0),
SOC=BinaryTools.unpack('uint8', x, 0x0a),
I=trunc(BinaryTools.unpack('int32', x, 0x10) / 1000000.0),
STATE=state_names.get(BinaryTools.unpack('uint8', x, 0x0f), f'Unknown({BinaryTools.unpack("uint8", x, 0x0f)})'),
L=BinaryTools.unpack('uint16', x, 0x0),
H=BinaryTools.unpack('uint16', x, 0x02),
B=BinaryTools.unpack('uint16', x, 0x02) - BinaryTools.unpack('uint16', x, 0x0),
l=BinaryTools.unpack('uint16', x, 0x14),
PT=BinaryTools.unpack('uint8', x, 0x04),
BT=BinaryTools.unpack('uint8', x, 0x05),
PV=BinaryTools.unpack('uint32', x, 0x0b) / 1000.0)
}
@classmethod
def bms_unknown_type_5(cls, x):
"""BMS Unknown Type 5 - raw hex display"""
hex_data = ' '.join(f'{b:02x}' for b in x[:min(16, len(x))])
return {
'event': 'BMS Unknown Type 5',
'conditions': f'Unknown: {hex_data}'
}
@classmethod
def bms_unknown_type_14(cls, x):
"""BMS Unknown Type 14 - raw hex display"""
hex_data = ' '.join(f'{b:02x}' for b in x[:min(16, len(x))])
return {
'event': 'BMS Unknown Type 14',
'conditions': f'Unknown: {hex_data}'
}
@classmethod
def mbb_unknown_type_28(cls, x):
"""MBB Unknown Type 28 - raw hex display"""
hex_data = ' '.join(f'{b:02x}' for b in x[:min(16, len(x))])
return {
'event': 'MBB Unknown Type 28',
'conditions': f'Unknown: {hex_data}'
}
@classmethod
def mbb_unknown_type_38(cls, x):
"""MBB Unknown Type 38 - raw hex display"""
hex_data = ' '.join(f'{b:02x}' for b in x[:min(16, len(x))])
return {
'event': 'MBB Unknown Type 38',
'conditions': f'Unknown: {hex_data}'
}
@classmethod
def mbb_bt_rx_buffer_overflow(cls, x):
"""MBB BT RX Buffer Overflow"""
hex_data = ' '.join(f'{b:02x}' for b in x[:min(16, len(x))])
return {
'event': 'MBB BT RX Buffer Overflow',
'conditions': f'Data: {hex_data}'
}
vin_length = 17
vin_guaranteed_prefix = '538'
def is_vin(vin: str):
"""Whether the string matches a Zero VIN."""
return (BinaryTools.is_printable(vin)
and len(vin) == vin_length
and vin.startswith(vin_guaranteed_prefix))
# noinspection PyMissingOrEmptyDocstring
class LogFile:
"""
Wrapper for our raw log file
"""
def __init__(self, file_path: str, logger=None):
self.file_path = file_path
self._data = bytearray()
self.reload()
self.log_type = self.get_log_type()
def reload(self):
with open(self.file_path, 'rb') as f:
self._data = bytearray(f.read())
def index_of_sequence(self, sequence, start=None):
try:
return self._data.index(sequence, start)
except ValueError:
return None
def indexes_of_sequence(self, sequence, start=None):
result = []
last_index = self.index_of_sequence(sequence, start)
while last_index is not None:
result.append(last_index)
last_index = self.index_of_sequence(sequence, last_index + 1)
return result
def unpack(self, type_name, address, count=1, offset=0):
return BinaryTools.unpack(type_name, self._data, address + offset,
count=count)
def decode_str(self, address, count=1, offset=0, encoding='utf-8'):
return BinaryTools.decode_str(BinaryTools.unpack('char', self._data, address + offset,
count=count), encoding=encoding)
def unpack_str(self, address, count=1, offset=0, encoding='utf-8') -> str:
"""Unpacks and decodes UTF-8 strings from a test segment, ignoring any errors"""
unpacked = self.unpack('char', address, count, offset)
return BinaryTools.decode_str(unpacked.partition(b'\0')[0], encoding=encoding)
def is_printable(self, address, count=1, offset=0) -> bool:
unpacked = self.unpack('char', address, count, offset).decode('utf-8', 'ignore')
return BinaryTools.is_printable(unpacked) and len(unpacked) == count
def extract(self, start_address, length, offset=0):
return self._data[start_address + offset:
start_address + length + offset]
def raw(self):
return bytearray(self._data)
log_type_mbb = 'MBB'
log_type_bms = 'BMS'
log_type_unknown = 'Unknown Type'
def get_log_type(self):
log_type = None
if self.is_printable(0x000, count=3):
log_type = self.unpack_str(0x000, count=3)
elif self.is_printable(0x00d, count=3):
log_type = self.unpack_str(0x00d, count=3)
elif self.log_type_mbb in self.file_path.upper():
log_type = self.log_type_mbb
elif self.log_type_bms in self.file_path.upper():
log_type = self.log_type_bms
if log_type not in [self.log_type_mbb, self.log_type_bms]:
log_type = self.log_type_unknown
return log_type
def is_mbb(self):
return self.log_type == self.log_type_mbb
def is_bms(self):
return self.log_type == self.log_type_bms
def is_unknown(self):
return self.log_type == self.log_type_unknown
def get_filename_vin(self):
basename = os.path.basename(self.file_path)
if basename and len(basename) > vin_length and vin_guaranteed_prefix in basename:
vin_index = basename.index(vin_guaranteed_prefix)
return basename[vin_index:vin_index + vin_length]
def convert_mv_to_v(milli_volts: int) -> float:
return milli_volts / 1000.0
def convert_ratio_to_percent(numerator: Union[int, float], denominator: Union[int, float]) -> float:
return numerator * 100 / denominator if denominator != 0 else 0
def convert_bit_to_on_off(bit: int) -> str:
return 'On' if bit else 'Off'
def hex_of_value(value):
if isinstance(value, str):
return value
if isinstance(value, float):
return value.hex()
if isinstance(value, bytearray):
return value.hex()
if isinstance(value, bytes):
return value.hex()
return str(value)
def display_bytes_hex(x: Union[List[int], bytearray, bytes, str]):
byte_values = bytearray(x, 'utf8') if isinstance(x, str) else x
return ' '.join(['0x{:02x}'.format(c) for c in byte_values])
EMPTY_CSV_VALUE = ''
CSV_DELIMITER = ';'
def print_value_tabular(value, omit_units=False):
"""Stringify the value for CSV/TSV; treat None as empty text."""
if value is None:
return EMPTY_CSV_VALUE
if isinstance(value, str) and not BinaryTools.is_printable(value):
return display_bytes_hex(value)
if isinstance(value, int):
return str(value)
if isinstance(value, bytearray):
return display_bytes_hex(value)
if isinstance(value, float):
return '{0:.2f}'.format(value)
if omit_units and value is str:
matches = re.match(r"^([0-9.]+)\s*([A-Za-z]+)$", value)
if matches:
return matches.group(1)
# Clean up string values to be CSV-safe
result = str(value)
if isinstance(value, str):
# Replace problematic characters that break CSV parsing
result = result.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ')
result = result.replace(';', ':') # Replace CSV delimiter
# Remove non-printable characters except spaces
result = ''.join(c for c in result if c.isprintable() or c == ' ')
result = result.strip()
return result
class Gen2:
@classmethod
def timestamp_from_event(cls, unescaped_block, use_local_time=True, timezone_offset=None):
timestamp = BinaryTools.unpack('uint32', unescaped_block, 0x01)
if timestamp > 0xfff:
# Apply timezone offset and use GMT to avoid double timezone conversion
adjusted_timestamp = timestamp + (timezone_offset or 0)
timestamp_corrected = gmtime(adjusted_timestamp)
return strftime(ZERO_TIME_FORMAT, timestamp_corrected)
else:
return str(timestamp)
@classmethod
def interpolate_missing_timestamps(cls, entries_with_metadata, logger=None):
"""
Improve missing timestamp detection by interpolating from neighboring entries.
Args:
entries_with_metadata: List of tuples (sort_timestamp, entry_payload, entry_num)
logger: Optional logger for debugging
Returns:
List of tuples with improved timestamps
"""
if not entries_with_metadata:
return entries_with_metadata
improved_entries = []
# First pass: identify entries with valid and invalid timestamps
for i, (sort_timestamp, entry_payload, entry_num) in enumerate(entries_with_metadata):
time_str = entry_payload.get('time', '0')
has_valid_timestamp = not time_str.isdigit() and sort_timestamp > 0
improved_entries.append({
'index': i,
'sort_timestamp': sort_timestamp,
'entry_payload': entry_payload,
'entry_num': entry_num,
'has_valid_timestamp': has_valid_timestamp,
'original_time_str': time_str
})
# Second pass: interpolate missing timestamps
for i, entry in enumerate(improved_entries):
if not entry['has_valid_timestamp']:
# Find nearest valid timestamps before and after
before_entry = None
after_entry = None
# Look backwards for valid timestamp
for j in range(i - 1, -1, -1):
if improved_entries[j]['has_valid_timestamp']:
before_entry = improved_entries[j]
break
# Look forwards for valid timestamp
for j in range(i + 1, len(improved_entries)):
if improved_entries[j]['has_valid_timestamp']:
after_entry = improved_entries[j]
break
# Interpolate timestamp if we have neighbors
interpolated_timestamp = None
interpolated_time_str = None
if before_entry and after_entry:
# Interpolate between two valid timestamps
before_ts = before_entry['sort_timestamp']
after_ts = after_entry['sort_timestamp']
before_entry_num = before_entry['entry_num']
after_entry_num = after_entry['entry_num']
current_entry_num = entry['entry_num']
# Calculate position ratio based on entry numbers
if after_entry_num != before_entry_num:
ratio = (current_entry_num - before_entry_num) / (after_entry_num - before_entry_num)
interpolated_timestamp = before_ts + ratio * (after_ts - before_ts)
else:
interpolated_timestamp = before_ts
elif before_entry:
# Extrapolate from previous entry (assume 1 second interval)
entry_gap = entry['entry_num'] - before_entry['entry_num']
interpolated_timestamp = before_entry['sort_timestamp'] + entry_gap
elif after_entry:
# Extrapolate from next entry (assume 1 second interval)
entry_gap = after_entry['entry_num'] - entry['entry_num']
interpolated_timestamp = after_entry['sort_timestamp'] - entry_gap
# Apply interpolated timestamp if we calculated one
if interpolated_timestamp and interpolated_timestamp > 0:
try:
from datetime import datetime
interpolated_dt = datetime.fromtimestamp(interpolated_timestamp)
interpolated_time_str = interpolated_dt.strftime(ZERO_TIME_FORMAT)
# Update the entry
entry['sort_timestamp'] = interpolated_timestamp
entry['entry_payload']['time'] = interpolated_time_str
entry['has_valid_timestamp'] = True
if logger:
logger.debug('Interpolated timestamp for entry %d: %s (was: %s)',
entry['entry_num'] + 1, interpolated_time_str, entry['original_time_str'])
except:
# If interpolation fails, keep original
pass
# Return in the original format
return [(entry['sort_timestamp'], entry['entry_payload'], entry['entry_num'])
for entry in improved_entries]
@classmethod
def bms_discharge_level(cls, x):
bike_states = {
0x01: 'Bike On',
0x02: 'Charge',
0x03: 'Idle'
}
# Extract raw data once from binary
structured_data = {
'amp_hours': trunc(BinaryTools.unpack('uint32', x, 0x06) / 1000000.0),
'state_of_charge_percent': BinaryTools.unpack('uint8', x, 0x0a),
'current_amps': trunc(BinaryTools.unpack('int32', x, 0x10) / 1000000.0),
'voltage_low_cell_volts': BinaryTools.unpack('uint16', x, 0x0) / 1000.0,
'voltage_unloaded_cell_volts': BinaryTools.unpack('uint16', x, 0x14) / 1000.0,
'voltage_high_cell_volts': BinaryTools.unpack('uint16', x, 0x02) / 1000.0,
'voltage_balance_mv': BinaryTools.unpack('uint16', x, 0x02) - BinaryTools.unpack('uint16', x, 0x0),
'pack_temp_celsius': BinaryTools.unpack('uint8', x, 0x04),
'bms_temp_celsius': BinaryTools.unpack('uint8', x, 0x05),
'pack_voltage_volts': BinaryTools.unpack('uint32', x, 0x0b) / 1000.0,
'pack_voltage_mv': BinaryTools.unpack('uint32', x, 0x0b), # For backward compatibility
'mode': bike_states.get(BinaryTools.unpack('uint8', x, 0x0f))
}
# Generate legacy conditions string for backward compatibility
legacy_conditions = (
'{AH:03.0f} AH, SOC:{SOC:3d}%, I:{I:3.0f}A, L:{L:4.2f}V, l:{l:4.2f}V, H:{H:4.2f}V, B:{B:03d}mV, '
'PT:{PT:03d}C, BT:{BT:03d}C, PV:{PV:6.1f}V, M:{M}').format(
AH=structured_data['amp_hours'],
SOC=structured_data['state_of_charge_percent'],
I=structured_data['current_amps'],
L=structured_data['voltage_low_cell_volts'],
l=structured_data['voltage_unloaded_cell_volts'],
H=structured_data['voltage_high_cell_volts'],
B=structured_data['voltage_balance_mv'],
PT=structured_data['pack_temp_celsius'],
BT=structured_data['bms_temp_celsius'],
PV=structured_data['pack_voltage_volts'],
M=structured_data['mode']
)
return {
'event': 'Discharge level',
'structured_data': structured_data, # NEW: Direct structured data
'conditions': legacy_conditions # LEGACY: For backward compatibility
}
@classmethod
def bms_charge_event_fields(cls, x):
return {
'AH': trunc(BinaryTools.unpack('uint32', x, 0x06) / 1000000.0),
'B': BinaryTools.unpack('uint16', x, 0x02) - BinaryTools.unpack('uint16', x, 0x0),
'L': BinaryTools.unpack('uint16', x, 0x00) / 1000.0, # Convert to volts
'H': BinaryTools.unpack('uint16', x, 0x02) / 1000.0, # Convert to volts
'PT': BinaryTools.unpack('uint8', x, 0x04),
'BT': BinaryTools.unpack('uint8', x, 0x05),
'SOC': BinaryTools.unpack('uint8', x, 0x0a),
'PV': BinaryTools.unpack('uint32', x, 0x0b) / 1000.0 # Convert to volts
}
@classmethod
def bms_charge_full(cls, x):
# Extract raw binary data once into structured format
fields = cls.bms_charge_event_fields(x)
# Build structured data dictionary with descriptive names
structured_data = {
'amp_hours': fields['AH'],
'state_of_charge_percent': fields['SOC'],
'voltage_low_cell_volts': fields['L'],
'voltage_high_cell_volts': fields['H'],
'voltage_balance_mv': fields['B'],
'pack_temp_celsius': fields['PT'],
'bms_temp_celsius': fields['BT'],
'pack_voltage_volts': fields['PV'],
'event_type': 'charge_complete'
}
# Generate legacy conditions string for backward compatibility
legacy_conditions = (
'{AH:03.0f} AH, SOC: {SOC}%, L:{L:4.2f}V, H:{H:4.2f}V, B:{B:03d}mV, '
'PT:{PT:03d}C, BT:{BT:03d}C, PV:{PV:6.1f}V').format_map(fields)
return {
'event': 'Charged To Full',
'structured_data': structured_data, # NEW: Direct structured data
'conditions': legacy_conditions # LEGACY: For backward compatibility
}
@classmethod
def bms_discharge_low(cls, x):
# Extract raw binary data once into structured format
fields = cls.bms_charge_event_fields(x)
# Build structured data dictionary with descriptive names
structured_data = {
'amp_hours': fields['AH'],
'state_of_charge_percent': fields['SOC'],
'voltage_low_cell_volts': fields['L'],
'voltage_high_cell_volts': fields['H'],
'voltage_balance_mv': fields['B'],
'pack_temp_celsius': fields['PT'],
'bms_temp_celsius': fields['BT'],
'pack_voltage_volts': fields['PV'],
'event_type': 'discharge_low'
}
# Generate legacy conditions string for backward compatibility
legacy_conditions = (
'{AH:03.0f} AH, SOC:{SOC:3d}%, L:{L:4.2f}V, H:{H:4.2f}V, B:{B:03d}mV, '
'PT:{PT:03d}C, BT:{BT:03d}C, PV:{PV:6.1f}V').format_map(fields)
return {
'event': 'Discharged To Low',
'structured_data': structured_data, # NEW: Direct structured data
'conditions': legacy_conditions # LEGACY: For backward compatibility
}
@classmethod
def bms_system_state(cls, x):
return {
'event': 'System Turned ' + convert_bit_to_on_off(BinaryTools.unpack('bool', x, 0x0))
}
@classmethod
def bms_soc_adj_voltage(cls, x):
# Extract binary data once
old_uah = BinaryTools.unpack('uint32', x, 0x00)
old_soc = BinaryTools.unpack('uint8', x, 0x04)
new_uah = BinaryTools.unpack('uint32', x, 0x05)
new_soc = BinaryTools.unpack('uint8', x, 0x09)
low_cell_mv = BinaryTools.unpack('uint16', x, 0x0a)
# Build structured data
structured_data = {
'old_capacity_microamp_hours': old_uah,
'old_state_of_charge_percent': old_soc,
'new_capacity_microamp_hours': new_uah,
'new_state_of_charge_percent': new_soc,
'low_cell_voltage_millivolts': low_cell_mv,
'capacity_change_microamp_hours': new_uah - old_uah,
'soc_change_percent': new_soc - old_soc
}
# Generate legacy conditions string for backward compatibility
legacy_conditions = ('old: {old}uAH (soc:{old_soc}%), '
'new: {new}uAH (soc:{new_soc}%), '
'low cell: {low} mV').format(
old=old_uah, old_soc=old_soc,
new=new_uah, new_soc=new_soc,
low=low_cell_mv)
return {
'event': 'SOC adjusted for voltage',
'structured_data': structured_data,
'conditions': legacy_conditions
}
@classmethod
def bms_curr_sens_zero(cls, x):
# Extract binary data once
old_mv = BinaryTools.unpack('uint16', x, 0x00)
new_mv = BinaryTools.unpack('uint16', x, 0x02)
corrfact = BinaryTools.unpack('uint8', x, 0x04)
# Build structured data
structured_data = {
'old_value_millivolts': old_mv,
'new_value_millivolts': new_mv,
'correction_factor': corrfact,
'old_value_volts': old_mv / 1000.0,
'new_value_volts': new_mv / 1000.0,
'adjustment_millivolts': new_mv - old_mv
}
# Generate legacy conditions string for backward compatibility
legacy_conditions = 'old: {old}mV, new: {new}mV, corrfact: {corrfact}'.format(
old=old_mv, new=new_mv, corrfact=corrfact
)
return {
'event': 'Current Sensor Zeroed',
'structured_data': structured_data,
'conditions': legacy_conditions
}
@classmethod
def bms_state(cls, x):
entering_hibernate = BinaryTools.unpack('bool', x, 0x0)
return {
'event': ('Entering' if entering_hibernate else 'Exiting') + ' Hibernate'
}
@classmethod
def bms_isolation_fault(cls, x):
# Extract binary data once
resistance_ohms = BinaryTools.unpack('uint32', x, 0x00)
cell_number = BinaryTools.unpack('uint8', x, 0x04)
# Build structured data
structured_data = {
'resistance_ohms': resistance_ohms,
'cell_number': cell_number,
'resistance_kiloohms': resistance_ohms / 1000.0,
'resistance_megaohms': resistance_ohms / 1000000.0,
'is_low_resistance': resistance_ohms < 1000000, # Less than 1 megaohm is concerning
'fault_severity': 'critical' if resistance_ohms < 100000 else 'warning' if resistance_ohms < 1000000 else 'info'
}
# Generate legacy conditions string for backward compatibility
legacy_conditions = '{ohms} ohms to cell {cell}'.format(
ohms=resistance_ohms, cell=cell_number
)
return {
'event': 'Chassis Isolation Fault',
'structured_data': structured_data,
'conditions': legacy_conditions
}
@classmethod
def bms_reflash(cls, x):
# Extract binary data once
revision = BinaryTools.unpack('uint8', x, 0x00)
build_str = BinaryTools.unpack_str(x, 0x01, 20)
# Build structured data
structured_data = {
'revision': revision,
'build_string': build_str,
'revision_hex': f'0x{revision:02X}',
'is_printable_build': all(c.isprintable() for c in build_str),
'build_length': len(build_str.rstrip('\x00'))
}
# Generate legacy conditions string for backward compatibility
legacy_conditions = 'Revision {rev}, Built {build}'.format(
rev=revision, build=build_str
)
return {
'event': 'BMS Reflash',
'structured_data': structured_data,
'conditions': legacy_conditions
}
@classmethod
def bms_change_can_id(cls, x):