-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathread-optic.py
More file actions
executable file
·3659 lines (3211 loc) · 154 KB
/
read-optic.py
File metadata and controls
executable file
·3659 lines (3211 loc) · 154 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/python3
# XXX FIXME: Need to implement SFF-8636 to read 4-lane optics
#
# XXX FIXME: Need to read all user-pages on 0xa0 with page-select-byte (?)
# (c) 2015-2023 Jared Mauch jared@puck.nether.net
# (c) 2015 WhiteBoxOptical LLC
#
# Unauthorized copying Prohibited
#
# Raspberry PI 2 setup details:
# % # echo dtparam=i2c_arm=on >> /boot/config.txt
# % # echo dtparam=i2c_vc=on >> /boot/config.txt
# % # apt-get install python-smbus2
# % # modprobe i2c_dev ; echo i2c_dev >> /etc/modules
# % ** append bcm2708.vc_i2c_override=1 to /boot/cmdline.txt
#
# INF-8074 version: 1.0
# INF-8077 version: 4.5
# SFF-8024 version: 4.12
# SFF-8419 version: 1.3
# SFF-8436 version: FIXME (needs to be 4.8)
# SFF-8472 version: 12.4.3
# SFF-8636 version: 2.11 (needs to be x)
# SFF-8679 version: 1.8 (needs to be x)
# SFF-8690 version: 1.4.2
# OIF-CMIS version: 5.3
#
#
#
from __future__ import division
from __future__ import print_function
# some optics (eg: GLC-T) come soft-disabled for some reason
# added code to soft-enable them
from builtins import chr
from builtins import range
import argparse
import fcntl
import os
import re
import struct
import sys
# Linux I2C ioctl constants and structures for raw /dev/i2c-N access
I2C_RDWR = 0x0707
I2C_M_RD = 0x0001
real_hardware = True # smbus2 not used; use raw I2C for probe
import time
import json
import math
usleep = lambda x: time.sleep(x/1000000.0)
def _isprint(b):
"""Return True if byte b is a printable ASCII character."""
return 0x20 <= b <= 0x7E
# Import specification-specific modules
try:
import oif_cmis
import sff_8472
import sff_8636
SPEC_MODULES_AVAILABLE = True
except ImportError as e:
SPEC_MODULES_AVAILABLE = False
print(f"Warning: Specification modules not available ({e}), using legacy functions")
# Import code mappings for resolving unknown interface codes
try:
import code_mappings
CODE_MAPPINGS_AVAILABLE = True
except ImportError as e:
CODE_MAPPINGS_AVAILABLE = False
print(f"Warning: Code mappings module not available ({e}), unknown codes will not be resolved")
# globals
address_one = 0x50 # A0
address_two = 0x51 # A2 DDM and SFF-8690 Tunable support
# Global page dictionaries
optic_pages = {}
optic_ddm_pages = {}
optic_dwdm_pages = {}
optic_sff_read = 0
optic_ddm_read = 0
optic_dwdm_read = 0
tmp102_address = 0x48
#tmp102_address = 0x4e
# lower page
#optic_lower_page = bytearray.fromhex("18400407000000000000000000002fb8811f000000003486000020000000000000000000000100030400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030402111e840111438401ff00000000000000000000000000000000000000000000000000000000000000001118434947202020202020202020202020000b405452443554483230454e462d4c4630303030315332324a423035525220202020202020323230393236202020202020202020202020a0300007000000000000f00006000000000000000000d6000000000000000000000000000000000000000000000000000000000000000000")
# page 0
#optic_sff = bytearray.fromhex("18400407000000000000000000002fb8811f000000003486000020000000000000000000000100030400000000000000000000000000000000000000000000000000000000000000000000000000000000000000030402111e840111438401ff000000000000000000000000000000000000000000000000000000000000000011030402004a000000000065a4051424f017c2460000009c1a00fa773b03070613075d3d77ff00003822000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000099")
#optic_sff_read = len(optic_sff)
upper_page = { }
#upper_page{1} = bytearray.fromhex("030402004a000000000065a4051424f017c2460000009c1a00fa773b03070613075d3d77ff00003822000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000099")
#upper_page{2}=bytearray.fromhex("4b00fb00460000008dcc7404875a7a76000000000000000000000000000000003f8029803c802c8000000000000000009f220a847e6714fac35030d4afc8445c9f2202777e6704eb000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007c")
#upper_page{0x10}=bytearray.fromhex("00000000000000000000000000000000001010101010101010ff000000000000ffff2222222200000000333333330000000000002121212121212121ff000000000000ffff2222222200000000333333330000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
#upper_page{0x11}=bytearray.fromhex("44444444000000000000000000000000000000000000000000005552564c549b561b00000000000000007417687461a861a80000000000000000481a4bbf432546810000000000000000111111111010101010101010ff000000000000ffff222222220000000033333333000000000011213141000000001121314100000000")
# page 1
#optic_ddm = bytearray.fromhex("5000f6004b00fb0088b8785087f07918d6d82710c3503a986e181ba7621f1f070c5a002809d000320000000000000000000000000000000000000000000000000000000003f8000000000000001000000010000000100000001000000000000b116a980d700000000000000000000000005400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
#optic_sff_read = len(optic_sff)
#optic_ddm_read = len(optic_ddm)
optic_dwdm = []
optic_dwdm_read = -1
def get_byte(page_dict, page, offset):
"""Get a single byte from a specific page."""
if page not in page_dict:
return None
page_data = page_dict[page]
if offset < len(page_data):
return page_data[offset]
return None
def get_bytes(page_dict, page, start, end):
"""Get a range of bytes from a specific page."""
if page not in page_dict:
return bytes([0] * (end - start))
page_data = page_dict[page]
result = []
for i in range(start, end):
if i < len(page_data):
result.append(page_data[i])
else:
result.append(0)
return bytes(result)
def parse_hex_dump_line(line):
"""Parse a hex dump line and return the hex bytes"""
# Handle space-separated hex format like "0x80 3d 0b 01 02 bf 00 00"
# Also handle formats like "0x80: 3d 0b 01 02 bf 00 00" and "0x80 3d 0b 01 02 bf 00 00"
# First, try to find all hex patterns in the line
hex_patterns = re.findall(r'([0-9a-fA-F]{2})', line)
if len(hex_patterns) > 1:
# Skip the first hex byte (address) and convert the rest to integers
data_bytes = [int(b, 16) for b in hex_patterns[1:]]
return data_bytes
elif len(hex_patterns) == 1:
# Only one hex value found, might be just an address
return []
# If no hex patterns found with regex, try alternative parsing
# Handle formats like "0x80: 3d 0b 01 02 bf 00 00"
if ':' in line:
parts = line.split(':')
if len(parts) == 2:
hex_data = parts[1].strip()
# Split on whitespace and filter out empty strings
hex_values = [x for x in hex_data.split() if x]
try:
data_bytes = [int(val, 16) for val in hex_values]
return data_bytes
except ValueError:
return []
return []
def map_cmis_page_offset(current_page, base_addr, offset):
"""Map CMIS hex dump addresses to absolute page offsets according to CMIS specification."""
if current_page == '00h':
# Lower Page 00h: addresses 0x00-0x7F map to bytes 0-127
if 0x00 <= base_addr <= 0x7F:
return base_addr + offset
# Upper Page 00h: addresses 0x80-0xFF map to bytes 128-255
elif 0x80 <= base_addr <= 0xFF:
return base_addr + offset
elif current_page == '80h':
# Upper Page 00h: addresses 0x80-0xFF map to bytes 128-255
if 0x80 <= base_addr <= 0xFF:
return base_addr + offset
elif current_page in ['01h', '02h', '03h', '04h', '06h', '10h', '11h', '12h', '13h', '25h']:
# Upper Pages: addresses 0x80-0xFF map to array indices 0-127
# For Page 01h: 0x80 -> page[0], 0x88 -> page[8], 0x90 -> page[16], etc.
if 0x80 <= base_addr <= 0xFF:
return (base_addr - 0x80) + offset
# For other pages, use direct mapping
return base_addr + offset
def parse_optic_file(filename, debug=False):
"""Parse optic data from a file and populate the global page dictionary"""
import re
global optic_pages, optic_ddm_pages, optic_dwdm_pages, optic_sff_read, optic_ddm_read, optic_dwdm_read
try:
with open(filename, 'r') as f:
content = f.read()
except FileNotFoundError:
print(f"Error: File '{filename}' not found")
return False
except Exception as e:
print(f"Error reading file '{filename}': {e}")
return False
lines = content.split('\n')
# Use dicts to store each page with consistent string keys
optic_pages = {}
optic_ddm_pages = {}
optic_dwdm_pages = {}
# Store raw high and low page data before combining
raw_lower_page = [0] * 128 # Addresses 0x00-0x7F
raw_upper_pages = {} # Upper pages by page ID
current_device = None
current_address = None
current_page = 'lower' # Track if we're in lower or upper page
current_upper_page_id = '00h' # Which upper page (00h, 01h, 02h, etc.)
is_juniper_qsfp = False
# Initialize default pages
optic_pages['00h'] = [0] * 256
optic_pages['01h'] = [0] * 256
optic_pages['02h'] = [0] * 256
optic_pages['03h'] = [0] * 256
optic_pages['04h'] = [0] * 256
optic_pages['06h'] = [0] * 256
optic_pages['10h'] = [0] * 256
optic_pages['11h'] = [0] * 256
optic_pages['12h'] = [0] * 256
optic_pages['13h'] = [0] * 256
optic_pages['25h'] = [0] * 256
# Initialize raw upper pages
for page_id in ['00h', '01h', '02h', '03h', '04h', '06h', '10h', '11h', '12h', '13h', '25h']:
raw_upper_pages[page_id] = [0] * 128 # Upper pages are 128 bytes (0x80-0xFF)
optic_ddm_pages['00h'] = [0] * 256
for idx, orig_line in enumerate(lines):
line = orig_line.strip()
if not line:
continue
lstripped = orig_line.lstrip()
# Device address detection (SFP/SFP+)
if "2-wire device address" in line:
addr_match = re.search(r'0x([0-9a-fA-F]+)', line)
if addr_match:
current_address = int(addr_match.group(1), 16)
if current_address == 0x50:
current_device = 'sff'
elif current_address == 0x51:
current_device = 'ddm'
else:
current_device = None
if debug:
print(f"DEBUG: Set current_device={current_device} for address 0x{current_address:02x}")
continue
# Handle formatted hex dumps with headers (QSFP-DD format) - removed generic detection
# Juniper QSFP format detection
if line.startswith('QSFP IDEEPROM (Low Page 00h'):
is_juniper_qsfp = True
current_device = 'sff'
current_page = 'lower'
continue
if line.startswith('QSFP IDEEPROM (Upper Page 00h'):
is_juniper_qsfp = True
current_device = 'sff'
current_page = 'upper'
continue
if line.startswith('QSFP IDEEPROM (Upper Page 03h'):
is_juniper_qsfp = True
current_device = 'ddm'
current_page = 'lower'
continue
# QSFP-DD format detection (prioritize over generic detection)
if line.startswith('QSFP-DD Lower Page'):
is_juniper_qsfp = True
current_device = 'sff'
current_page = 'lower'
if debug:
print(f"DEBUG: Set QSFP-DD Lower Page -> current_page=lower")
continue
if 'QSFP-DD Upper Page' in line:
is_juniper_qsfp = True
current_device = 'sff'
current_page = 'upper'
# Extract page ID (00h, 01h, 02h, etc.)
page_match = re.search(r'Upper Page (\w+h)', line)
if page_match:
current_upper_page_id = page_match.group(1)
if debug:
print(f"DEBUG: Set QSFP-DD Upper Page {current_upper_page_id} -> current_page=upper")
continue
# Generic QSFP IDEEPROM format
if line.startswith('QSFP IDEEPROM:') or 'QSFP IDEEPROM (Low Page' in line or 'Lower Page' in line:
current_device = 'sff'
current_page = 'lower'
if debug:
print(f"DEBUG: Set QSFP IDEEPROM Lower Page -> current_page=lower")
continue
if 'QSFP IDEEPROM (Upper Page' in line:
current_device = 'sff'
current_page = 'upper'
# Extract page ID (00h, 01h, 02h, etc.)
page_match = re.search(r'Upper Page (\w+h)', line)
if page_match:
current_upper_page_id = page_match.group(1)
if debug:
print(f"DEBUG: Set QSFP IDEEPROM Upper Page {current_upper_page_id} -> current_page=upper")
continue
# Generic "Upper Page XXh" pattern detection (catches pages 10h, 11h, etc.)
if line.strip().startswith('Upper Page') and 'h' in line:
current_device = 'sff'
current_page = 'upper'
# Extract page ID (00h, 01h, 02h, 10h, 11h, etc.)
page_match = re.search(r'Upper Page (\w+h)', line)
if page_match:
current_upper_page_id = page_match.group(1)
if debug:
print(f"DEBUG: Set Generic Upper Page {current_upper_page_id} -> current_page=upper")
continue
if line.startswith('QSFP IDEEPROM (diagnostics):'):
current_device = 'ddm'
current_page = 'lower'
continue
# Handle hex dump format with 0x00= and 0x01= prefixes
if line.startswith('0x00='):
hex_data = line[5:]
hex_bytes = [int(hex_data[i:i+2], 16) for i in range(0, len(hex_data), 2)]
for i, val in enumerate(hex_bytes):
if i < 256:
optic_pages['00h'][i] = val
continue
if line.startswith('0x01='):
hex_data = line[5:]
hex_bytes = [int(hex_data[i:i+2], 16) for i in range(0, len(hex_data), 2)]
for i, val in enumerate(hex_bytes):
if i < 256:
optic_ddm_pages['00h'][i] = val
continue
# Handle SFP format hex dumps (e.g., "0x00: 03 04 07 20 . 00 00 00 00")
if line.startswith('0x') and ':' in line and current_device:
try:
# Extract base address (e.g., "0x00:" -> 0x00)
addr_part = line.split(':')[0]
base_addr = int(addr_part, 16)
# Extract hex values (skip the first part which is the address)
hex_parts = line.split(':')[1].strip().split()
hex_bytes = []
for part in hex_parts:
if part == '.' or part == '-':
continue # Skip separators
if len(part) == 2 and all(c in '0123456789abcdefABCDEF' for c in part):
hex_bytes.append(int(part, 16))
if debug:
print(f"DEBUG: SFP hex line: base_addr=0x{base_addr:02x}, hex_bytes={[f'0x{b:02x}' for b in hex_bytes[:4]]}")
# Store data in appropriate pages based on device address
if current_device == 'sff':
# Main SFP data goes to optic_pages['00h']
for i, val in enumerate(hex_bytes):
addr = base_addr + i
if 0 <= addr < 256:
optic_pages['00h'][addr] = val
if debug:
print(f"DEBUG: SFP main: 0x{addr:02x} = 0x{val:02x}")
elif current_device == 'ddm':
# DDM data goes to optic_ddm_pages['00h']
for i, val in enumerate(hex_bytes):
addr = base_addr + i
if 0 <= addr < 256:
optic_ddm_pages['00h'][addr] = val
if debug:
print(f"DEBUG: SFP DDM: 0x{addr:02x} = 0x{val:02x}")
except Exception as e:
if debug:
print(f"DEBUG: Error parsing SFP hex line: {e}")
continue
# Address lines (Juniper format)
if line.startswith('Address 0x'):
addr_match = re.match(r'Address 0x([0-9a-fA-F]+):\s+(.+)', line)
if addr_match and current_device:
base_addr = int(addr_match.group(1), 16)
hex_bytes = [int(b, 16) for b in addr_match.group(2).split() if len(b) == 2]
if debug:
print(f"DEBUG: Processing Address line: base_addr=0x{base_addr:02x}, current_page={current_page}, hex_bytes={[f'0x{b:02x}' for b in hex_bytes[:4]]}")
# Handle Juniper QSFP format properly
if current_device == 'sff':
if current_page == 'lower':
# Lower page data (0x00-0x7F) goes to raw_lower_page
for i, val in enumerate(hex_bytes):
addr = base_addr + i
if 0x00 <= addr <= 0x7F:
raw_lower_page[addr] = val
if debug:
print(f"DEBUG: Lower page: 0x{addr:02x} = 0x{val:02x}")
elif current_page == 'upper':
# Upper page data (0x80-0xFF) goes to raw_upper_pages['00h']
for i, val in enumerate(hex_bytes):
addr = base_addr + i
if 0x80 <= addr <= 0xFF:
upper_offset = addr - 0x80 # Convert to 0-127 range
if '00h' not in raw_upper_pages:
raw_upper_pages['00h'] = [0] * 128
raw_upper_pages['00h'][upper_offset] = val
if debug:
print(f"DEBUG: Upper page: 0x{addr:02x} -> offset {upper_offset} = 0x{val:02x}")
elif current_device == 'ddm':
if current_page == 'lower':
# Lower page data (0x00-0x7F) goes to optic_ddm_pages['00h']
for i, val in enumerate(hex_bytes):
addr = base_addr + i
if 0x00 <= addr <= 0x7F:
optic_ddm_pages['00h'][addr] = val
if debug:
print(f"DEBUG: DDM Lower page: 0x{addr:02x} = 0x{val:02x}")
elif current_page == 'upper':
# Upper page data (0x80-0xFF) goes to optic_ddm_pages['80h']
for i, val in enumerate(hex_bytes):
addr = base_addr + i
if 0x80 <= addr <= 0xFF:
upper_offset = addr - 0x80 # Convert to 0-127 range
optic_ddm_pages['80h'][upper_offset] = val
if debug:
print(f"DEBUG: DDM Upper page: 0x{addr:02x} -> offset {upper_offset} = 0x{val:02x}")
continue
# Parse hex dump lines in formatted output (All module types)
if line.startswith('0x') and current_device and '----' not in line and 'Addr' not in line:
parts = line.split()
if len(parts) >= 2:
try:
# Extract address from first part (e.g., "0x80" -> 0x80)
base_addr = int(parts[0], 16)
if debug:
print(f"DEBUG: Parsing hex line: base_addr=0x{base_addr:02x}, current_page={current_page}")
# Parse all hex values after the address
for i in range(1, len(parts)):
try:
val = int(parts[i], 16)
addr = base_addr + (i - 1)
# Store data in raw pages based on address range
if current_page == 'lower' and 0x00 <= addr <= 0x7F:
# Lower page data (0x00-0x7F)
raw_lower_page[addr] = val
if debug:
print(f"DEBUG: Lower page: 0x{addr:02x} = 0x{val:02x}")
elif current_page == 'upper' and 0x80 <= addr <= 0xFF:
# Upper page data (0x80-0xFF) -> store in raw upper page
# Dynamically create page if it doesn't exist
if current_upper_page_id not in raw_upper_pages:
raw_upper_pages[current_upper_page_id] = [0] * 128
if debug:
print(f"DEBUG: Created new upper page {current_upper_page_id}")
upper_offset = addr - 0x80 # Convert to 0-127 range
raw_upper_pages[current_upper_page_id][upper_offset] = val
if debug:
print(f"DEBUG: Upper page {current_upper_page_id}: 0x{addr:02x} -> offset {upper_offset} = 0x{val:02x}")
except ValueError:
continue
except ValueError:
continue
continue
# SFP hex dump lines (indented, after device address)
if current_device and lstripped.startswith('0x') and ':' in lstripped and not is_juniper_qsfp:
hex_bytes = parse_hex_dump_line(lstripped)
if hex_bytes:
try:
base_addr = int(lstripped.split(':')[0], 16)
page = optic_pages if current_device == 'sff' else optic_ddm_pages
for i, val in enumerate(hex_bytes):
addr = base_addr + i
if addr < 256:
page['00h'][addr] = val
except (ValueError, IndexError):
continue
continue
# Always parse lines that look like hex dumps if current_device is set
if current_device and re.match(r'^0x[0-9a-fA-F]{2}\s', lstripped):
if debug:
print(f"DEBUG: Found hex dump line: '{lstripped[:50]}'")
elif current_device and '0x' in lstripped and ':' in lstripped:
if debug:
print(f"DEBUG: Potential hex line not matched: '{lstripped[:50]}', current_device={current_device}, current_page={current_page}")
elif '0x' in lstripped and lstripped.startswith('0x'):
if debug:
print(f"DEBUG: Hex line found: '{lstripped[:50]}', current_device={current_device}, current_page={current_page}")
elif '0x' in lstripped:
if debug:
print(f"DEBUG: Line with 0x but not starting with 0x: '{lstripped[:50]}', starts_with_0x={lstripped.startswith('0x')}, current_device={current_device}, current_page={current_page}")
# Try to parse as hex dump line
hex_bytes = parse_hex_dump_line(lstripped)
if hex_bytes and current_device:
try:
# Extract base address from the first hex value (before spaces)
base_addr_str = lstripped.split()[0] # Get "0x80" from "0x80 3d 0b 01 02 bf 00 00"
base_addr = int(base_addr_str, 16)
page = optic_pages if current_device == 'sff' else optic_ddm_pages
if debug:
print(f"DEBUG: Processing hex line: base_addr=0x{base_addr:02x}, current_page={current_page}, hex_bytes={[f'0x{b:02x}' for b in hex_bytes[:4]]}")
for i, val in enumerate(hex_bytes):
# Use unified CMIS page mapping function
page_offset = map_cmis_page_offset(current_page, base_addr, i)
if 0 <= page_offset < 256:
page[current_page][page_offset] = val
if debug:
print(f"DEBUG: Mapped 0x{base_addr:02x}+{i} -> page[{current_page}][{page_offset}] = 0x{val:02x}")
except (ValueError, IndexError):
continue
# Set global arrays to zero length if not present
# Check if this is an SFP module (flat memory structure, not paged)
is_sfp_module = False
if debug:
print(f"DEBUG: raw_lower_page[0] = 0x{raw_lower_page[0]:02x}")
print(f"DEBUG: raw_lower_page has {sum(1 for b in raw_lower_page if b != 0)} non-zero bytes")
print(f"DEBUG: optic_pages['00h'][0] = 0x{optic_pages['00h'][0]:02x}")
print(f"DEBUG: optic_pages['00h'] has {sum(1 for b in optic_pages['00h'] if b != 0)} non-zero bytes")
# Check both raw_lower_page and optic_pages['00h'] for SFP identifier
if raw_lower_page[0] == 0x03 or optic_pages['00h'][0] == 0x03: # SFP identifier
is_sfp_module = True
if debug:
print(f"DEBUG: Detected SFP module, skipping CMIS page combination")
if not is_sfp_module:
# Combine raw pages into final pages according to CMIS specification
# Page 00h = Lower Page (0x00-0x7F) + Upper Page 00h (0x80-0xFF)
optic_pages['00h'][:128] = raw_lower_page # Lower half
optic_pages['00h'][128:] = raw_upper_pages['00h'] # Upper half
# Other pages = Upper Page XX (0x80-0xFF) with lower half as zeros
# Handle all dynamically created pages
for page_id in raw_upper_pages.keys():
if page_id != '00h': # Skip page 00h as it's handled above
# Create page if it doesn't exist in optic_pages
if page_id not in optic_pages:
optic_pages[page_id] = [0] * 256
optic_pages[page_id][:128] = [0] * 128 # Lower half zeros
optic_pages[page_id][128:] = raw_upper_pages[page_id] # Upper half from raw data
else:
if debug:
print(f"DEBUG: SFP module detected, preserving direct page data")
optic_sff_read = sum(len(v) for v in optic_pages.values())
optic_ddm_read = sum(len(v) for v in optic_ddm_pages.values())
optic_dwdm_read = sum(len(v) for v in optic_dwdm_pages.values())
if debug:
print(f"DEBUG: Combined pages into final format")
print(f"DEBUG: Parsed {optic_sff_read} SFF bytes, {optic_ddm_read} DDM bytes")
for page_key, page_data in optic_pages.items():
non_zero = sum(1 for b in page_data if b != 0)
print(f"DEBUG: Page {page_key}: {non_zero} non-zero bytes")
# Show combined page 00h structure
if non_zero > 0:
print(f"DEBUG: Page 00h lower half (0x00-0x7F): {sum(1 for b in optic_pages['00h'][:128] if b != 0)} non-zero bytes")
print(f"DEBUG: Page 00h upper half (0x80-0xFF): {sum(1 for b in optic_pages['00h'][128:] if b != 0)} non-zero bytes")
return True
def reset_muxes(busno):
if not real_hardware:
return
# smbus2 not imported; would need it here for hardware reset
return
for mcp23017 in [0x20, 0x21, 0x22, 0x23]:
try:
optic_bus.write_byte_data(mcp23017, 0, 0)
usleep(20)
optic_bus.write_byte_data(mcp23017, 0, 0xff)
except IOError:
usleep(0)
def fetch_psu_data(busno):
if not real_hardware:
return
# smbus2 not imported; would need it here for PSU read
return
try:
with smbus2.SMBus(busno) as psu_bus:
for psu_address in [0x40, 0x47]:
psu=[]
psu_read = -1
while psu_read < 128:
try:
if (psu_read == -1):
psu_tmp = psu_bus.read_i2c_block_data(psu_address, 0, 32)
else:
psu_tmp = psu_bus.read_i2c_block_data(psu_address, psu_read, 32)
for member in psu_tmp:
psu.append(member)
psu_read = len(psu)
except IOError:
break
if psu_read >= 128:
psu_model=""
psu_sn=""
psu_rev=""
psu_mfg=""
for byte in range (1, 16):
if (_isprint(psu[byte])):
psu_model += "%c" % psu[byte]
for byte in range (17, 26):
if (_isprint(psu[byte])):
psu_sn += "%c" % psu[byte]
for byte in range (27, 29):
if (_isprint(psu[byte])):
psu_rev += "%c" % psu[byte]
for byte in range (33, 42):
if (_isprint(psu[byte])):
psu_mfg += "%c" % psu[byte]
psu_date = "%4.4d-%-2.2d-%2.2d" % (psu[29]+2000, psu[30], psu[31])
print("PSU_MODEL: %s" % psu_model)
print("PSU_SN: %s" % psu_sn)
print("PSU_DATE: %s" % psu_date)
print("PSU_MFG: %s" % psu_mfg)
print("PSU_MFG_LOC: %d" % psu[42])
print("PSU_SPEC_VOLTAGE: %d" % ((psu[43]*256)+psu[44]))
print("PSU_SPEC_CURRENT: %d" % ((psu[46]*256)+psu[47]))
print("PSU_SPEC_POWER: %d" % ((psu[49]*256)+psu[50]))
print("PSU_SPEC_MIN_AC: %d" % ((psu[51]*256)+psu[52]))
print("PSU_SPEC_MAX_AC: %d" % ((psu[53]*256)+psu[54]))
print("PSU_CHECKSUM: %d" % psu[55])
print("PSU_FAULT: 0x%x" % psu[56])
if (psu[56] & 0x10): # 0b00010000
print("PSU_FAULT: OVER_TEMP")
if (psu[56] & 0x08): #
print("PSU_FAULT: FAN_FAIL")
if (psu[56] & 0x04): #
print("PSU_FAULT: DC_OUTPUT_FAIL")
if (psu[56] & 0x02): #
print("PSU_FAULT: AC_INPUT_FAIL")
if (psu[56] & 0x01): #
print("PSU_FAULT: SEATED_IMPROPERLY")
print("PSU_FAN_SPEED: %d RPM" % (psu[57]*100))
if (psu[58] & 0x80):
print("PSU_TEMP: OUT_OF_RANGE")
else:
psu_temp = (psu[58] & 0b01111111)-34
print("PSU_TEMP: %d C" % psu_temp)
print("PSU_ROHS_BYTE: %c" % psu[59])
except IOError as e:
print(f"Error accessing PSU on bus {busno}: {str(e)}")
return
except Exception as e:
print(f"Unexpected error accessing PSU on bus {busno}: {str(e)}")
return
def fetch_optic_data(optic_bus):
# import as globals
global optic_sff
global optic_sff_read
global optic_ddm
global optic_ddm_read
global optic_dwdm
global optic_dwdm_read
# initalize them
optic_sff = []
optic_sff_read = 0
optic_ddm = []
optic_ddm_read = -1
optic_dwdm = []
optic_dwdm_read = -1
fast_read = 0
# read SFF data
while optic_sff_read < 256:
try:
if fast_read == 1:
optic_sff_tmp = optic_bus.read_i2c_block_data(address_one, optic_sff_read, 32, force=True)
for member in optic_sff_tmp:
optic_sff.append(member)
optic_sff_read = len(optic_sff)
else:
value = optic_bus.read_byte_data(address_one, optic_sff_read)
optic_sff.append(value)
optic_sff_read = len(optic_sff)
except IOError as e:
print(f"Error reading SFF data: {str(e)}")
break
except Exception as e:
print(f"Unexpected error reading SFF data: {str(e)}")
break
# regular page
try:
# write data to set to default page
optic_bus.write_byte_data(address_two, 127, 0x0)
except IOError as e:
print(f"Error switching optic page: {str(e)}")
except Exception as e:
print(f"Unexpected error switching optic page: {str(e)}")
# read DDM data
while optic_ddm_read < 256:
try:
if fast_read == 1:
if (optic_ddm_read == -1):
optic_ddm_tmp = optic_bus.read_i2c_block_data(address_two, 0, 32)
else:
optic_ddm_tmp = optic_bus.read_i2c_block_data(address_two, optic_ddm_read, 32)
for member in optic_ddm_tmp:
optic_ddm.append(member)
optic_ddm_read = len(optic_ddm)
else:
value = optic_bus.read_byte_data(address_two, optic_ddm_read)
optic_ddm.append(value)
optic_ddm_read = len(optic_ddm)
except IOError:
break
# if dwdm optic value (use optic_sff; optic_pages not populated until later in process_optic_data)
if (optic_sff_read > 65):
if (optic_sff[65] & 0x40):
# switch to page with DWDM dwdm data
try:
# write data
optic_bus.write_byte_data(address_two, 127, 0x2)
except IOError:
# error switching to dwdm data page
a=0
# read DWDM-DDM data
while optic_dwdm_read < 256:
try:
if (optic_dwdm_read == -1):
optic_dwdm_tmp = optic_bus.read_i2c_block_data(address_two, 0, 32)
else:
optic_dwdm_tmp = optic_bus.read_i2c_block_data(address_two, optic_dwdm_read, 32)
for member in optic_dwdm_tmp:
optic_dwdm.append(member)
optic_dwdm_read = len(optic_dwdm)
except IOError:
break
def validate_optic_type(optic_type):
"""Validate optic type against SFF-8024 specification and return detailed information"""
optic_type_info = {
0x00: {"name": "Unknown or unspecified", "spec": "SFF-8024", "status": "supported"},
0x01: {"name": "GBIC", "spec": "SFF-8053", "status": "supported"},
0x02: {"name": "Module/connector soldered to motherboard", "spec": "SFF-8472", "status": "supported"},
0x03: {"name": "SFP/SFP+/SFP28", "spec": "SFF-8472", "status": "supported"},
0x04: {"name": "300 pin XBI", "spec": "Legacy", "status": "supported"},
0x05: {"name": "XENPAK", "spec": "Legacy", "status": "supported"},
0x06: {"name": "XFP", "spec": "INF-8077", "status": "supported"},
0x07: {"name": "XFF", "spec": "Legacy", "status": "supported"},
0x08: {"name": "XFP-E", "spec": "Legacy", "status": "supported"},
0x09: {"name": "XPAK", "spec": "Legacy", "status": "supported"},
0x0A: {"name": "X2", "spec": "Legacy", "status": "supported"},
0x0B: {"name": "DWDM-SFP/SFP+", "spec": "Legacy", "status": "supported"},
0x0C: {"name": "QSFP", "spec": "INF-8438", "status": "supported"},
0x0D: {"name": "QSFP+", "spec": "SFF-8636", "status": "supported"},
0x0E: {"name": "CXP", "spec": "SFF-8643", "status": "supported"},
0x0F: {"name": "Shielded Mini Multilane HD 4X", "spec": "Legacy", "status": "supported"},
0x10: {"name": "Shielded Mini Multilane HD 8X", "spec": "Legacy", "status": "supported"},
0x11: {"name": "QSFP28", "spec": "SFF-8636", "status": "supported"},
0x12: {"name": "CXP2 (CXP28)", "spec": "SFF-8643", "status": "supported"},
0x13: {"name": "CDFP (Style 1/Style2)", "spec": "INF-TA-1003", "status": "supported"},
0x14: {"name": "Shielded Mini Multilane HD 4X Fanout Cable", "spec": "Legacy", "status": "supported"},
0x15: {"name": "Shielded Mini Multilane HD 8X Fanout Cable", "spec": "Legacy", "status": "supported"},
0x16: {"name": "CDFP (Style 3)", "spec": "INF-TA-1003", "status": "supported"},
0x17: {"name": "microQSFP", "spec": "Legacy", "status": "supported"},
0x18: {"name": "QSFP-DD", "spec": "SFF-8663", "status": "supported"},
0x19: {"name": "OSFP", "spec": "OSFP MSA", "status": "supported"},
0x1A: {"name": "SFP-DD", "spec": "SFP-DD MSA", "status": "supported"},
0x1B: {"name": "DSFP", "spec": "DSFP MSA", "status": "supported"},
0x1C: {"name": "x4 MiniLink/OcuLink", "spec": "Legacy", "status": "supported"},
0x1D: {"name": "x8 MiniLink", "spec": "Legacy", "status": "supported"},
0x1E: {"name": "QSFP+ with CMIS", "spec": "OIF-CMIS", "status": "supported"},
0x1F: {"name": "SFP-DD with CMIS", "spec": "OIF-CMIS", "status": "supported"},
0x20: {"name": "SFP+ with CMIS", "spec": "OIF-CMIS", "status": "supported"},
0x21: {"name": "OSFP-XD with CMIS", "spec": "OIF-CMIS", "status": "supported"},
0x22: {"name": "OIF-ELSFP with CMIS", "spec": "OIF-CMIS", "status": "supported"},
0x23: {"name": "CDFP (x4 PCIe) with CMIS", "spec": "OIF-CMIS", "status": "supported"},
0x24: {"name": "CDFP (x8 PCIe) with CMIS", "spec": "OIF-CMIS", "status": "supported"},
0x25: {"name": "CDFP (x16 PCIe) with CMIS", "spec": "OIF-CMIS", "status": "supported"}
}
if optic_type in optic_type_info:
info = optic_type_info[optic_type]
return {
"valid": True,
"name": info["name"],
"spec": info["spec"],
"status": info["status"],
"type": optic_type
}
elif 0x26 <= optic_type <= 0x7F:
return {
"valid": False,
"name": "Reserved",
"spec": "SFF-8024",
"status": "reserved",
"type": optic_type
}
elif 0x80 <= optic_type <= 0xFF:
return {
"valid": True,
"name": "Vendor Specific",
"spec": "Vendor Defined",
"status": "vendor_specific",
"type": optic_type
}
else:
return {
"valid": False,
"name": "Invalid",
"spec": "Unknown",
"status": "invalid",
"type": optic_type
}
def read_optic_type():
# defined in SFF-8024 4.11
# updated 2023-12-05
# Get the optic type from the page dictionary
optic_type = get_byte(optic_pages, '00h', 0)
# Debug output
if DEBUG:
print(f"DEBUG: optic_pages keys: {list(optic_pages.keys())}")
if '00h' in optic_pages:
print(f"DEBUG: optic_pages['00h'] length: {len(optic_pages['00h'])}")
print(f"DEBUG: optic_pages['00h'][0:5]: {[f'0x{b:02x}' for b in optic_pages['00h'][0:5]]}")
else:
print("DEBUG: '00h' key not found in optic_pages")
if optic_type == 0x00:
sff_type_text = "Unknown or unspecified"
elif optic_type == 0x01:
sff_type_text = "GBIC"
elif optic_type == 0x02:
sff_type_text = "Module soldered to motherboard" # SFF-8472
elif optic_type == 0x03:
sff_type_text = "SFP/SFP+/SFP28" # SFF-8472
elif optic_type == 0x04:
sff_type_text = "300 pin XBI"
elif optic_type == 0x05:
sff_type_text = "XENPAK"
elif optic_type == 0x06:
sff_type_text = "XFP" # INF-8077i, SFF-8477
elif optic_type == 0x07:
sff_type_text = "XFF"
elif optic_type == 0x08:
sff_type_text = "XFP-E"
elif optic_type == 0x09:
sff_type_text = "XPAK"
elif optic_type == 0x0A:
sff_type_text = "X2"
elif optic_type == 0x0B:
sff_type_text = "DWDM-SFP/SFP+" # DOES NOT USE SFF-8472
elif optic_type == 0x0C:
sff_type_text = "QSFP"
elif optic_type == 0x0D:
sff_type_text = "QSFP+" # SFF-8436 SFF-8635 SFF-8665 SFF-8685
elif optic_type == 0x0E:
sff_type_text = "CXP"
elif optic_type == 0x0F:
sff_type_text = "Shielded Mini Multilane HD 4X"
elif optic_type == 0x10:
sff_type_text = "Shielded Mini Multilane HD 8X"
elif optic_type == 0x11:
sff_type_text = "QSFP28" # SFF-8636/SFF-8665
elif optic_type == 0x12:
sff_type_text = "CXP2/CFP28"
elif optic_type == 0x13:
sff_type_text = "CDFP" # INF-TA-1003 style 1/2
elif optic_type == 0x14:
sff_type_text = "Shielded Mini Multilane HD 4X Fanout"
elif optic_type == 0x15:
sff_type_text = "Shielded Mini Multilane HD 8X Fanout"
elif optic_type == 0x16:
sff_type_text = "CDFP Style 3" # INF-TA-1003
elif optic_type == 0x17:
sff_type_text = "microQSFP"
elif optic_type == 0x18:
sff_type_text = "QSFP-DD" # CMIS 5.0
elif optic_type == 0x19:
sff_type_text = "OSFP 8X Pluggable Transceiver"
elif optic_type == 0x1a:
sff_type_text = "SFP-DD Double Density 2X Pluggable Transceiver"
elif optic_type == 0x1b:
sff_type_text = "DSFP Dual Small Form Factor Pluggable Transceiver"
elif optic_type == 0x1c:
sff_type_text = "x4 MiniLink/OcuLink"
elif optic_type == 0x1d:
sff_type_text = "x8 MiniLink"
elif optic_type == 0x1e:
sff_type_text = "QSFP+ or later with Common Management Interface Specification (CMIS)"
elif optic_type == 0x1f:
sff_type_text = "SFP-DD Double Density 2X Pluggable Transceiver with Common Management Interface Specification (CMIS)"
elif optic_type == 0x20:
sff_type_text = "SFP+ and later with Common Management Interface Specification (CMIS)"
elif optic_type == 0x21:
sff_type_text = "OSFP-XD with Common Management interface Specification (CMIS)"
elif optic_type == 0x22:
sff_type_text = "OIF-ELSFP with Common Management interface Specification (CMIS)"
elif optic_type == 0x23:
sff_type_text = "CDFP (x4 PCIe) SFF-TA-1032 with Common Management interface Specification (CMIS)"
elif optic_type == 0x24:
sff_type_text = "CDFP (x8 PCIe) SFF-TA-1032 with Common Management interface Specification (CMIS)"
elif optic_type == 0x25:
sff_type_text = "CDFP (x16 PCIe) SFF-TA-1032 with Common Management interface Specification (CMIS)"
elif optic_type >= 0x80:
sff_type_text = "Vendor Specific"
else:
sff_type_text = "Not yet specified value (%d) check SFF-8024" % optic_type
return optic_type, sff_type_text
def read_optic_mod_def():
# SFF-8472 Physical Device Extended Identifer Values
# Byte 1 Table 5-2
val = get_byte(optic_pages, '00h', 1)
if val == 0x00:
mod_def_text = ("Not Specified")
elif val == 0x01:
mod_def_text = ("MOD_DEF 1")
elif val == 0x02:
mod_def_text = ("MOD_DEF 2")
elif val == 0x03:
mod_def_text = ("MOD_DEF 3")
elif val == 0x04:
mod_def_text = ("function defined by i2c ID only")
elif val == 0x05:
mod_def_text = ("MOD_DEF 5")
elif val == 0x06:
mod_def_text = ("MOD_DEF 6")
elif val == 0x07:
mod_def_text = ("MOD_DEF 7")
else:
mod_def_text = ("Unallocated (%d)" % val)
print("Extended Identifier Value:", mod_def_text)
def read_optic_connector_type(connector_type):
# defined in SFF-8024 4-3, INF-8077 Table 48
if connector_type == 0x00:
connector_type_text = "Unknown or unspecified"
elif connector_type == 0x01:
connector_type_text = "SC"
elif connector_type == 0x02:
connector_type_text ="Fibre Channel Style 1 copper connector"
elif connector_type == 0x03:
connector_type_text ="Fibre Channel Style 2 copper connector"
elif connector_type == 0x04:
connector_type_text ="BNC/TNC"
elif connector_type == 0x05:
connector_type_text ="Fiber Channel coax headers"
elif connector_type == 0x06:
connector_type_text ="Fiber Jack"
elif connector_type == 0x07:
connector_type_text ="LC"
elif connector_type == 0x08:
connector_type_text ="MT-RJ"