m-bus-parser 0.1.1

A library for parsing M-Bus frames
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>M-Bus Parser (Wired & Wireless)</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/styles/default.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/languages/json.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #ffffff;
        }

        .header {
            display: flex;
            flex-direction: row;
            align-items: flex-start;
            justify-content: flex-start;
            margin-bottom: 20px;
            max-width: 1100px;
            margin-left: auto;
            margin-right: auto;
        }

        .header-text {
            text-align: left;
            margin-left: 16px;
        }

        .header-controls {
            display: flex;
            gap: 10px;
            margin-top: 10px;
            margin-left: 0;
        }

        .header-text h1 {
            margin: 0;
            font-size: 2em;
            color: #333;
        }

        .header-text .subtitle {
            font-size: 0.9em;
            color: #666;
            margin-top: 4px;
        }

        .header-text .subtitle a {
            color: #666;
            text-decoration: none;
        }

        .parser-version {
            font-size: 0.7em;
            color: #888;
            font-weight: normal;
            margin-left: 8px;
        }

        form {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            max-width: 1100px;
            margin: 0 auto;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
        }

        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            margin-bottom: 10px;
            font-family: monospace;
        }

        input[type="text"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            margin-bottom: 10px;
            font-family: monospace;
        }

        .key-input-container {
            position: relative;
            margin-bottom: 15px;
        }

        .key-help {
            font-size: 0.85em;
            color: #666;
            margin-top: 4px;
            margin-bottom: 8px;
        }

        .key-toggle {
            position: absolute;
            right: 10px;
            top: 10px;
            background: none;
            border: none;
            cursor: pointer;
            padding: 4px;
            color: #666;
        }

        .key-toggle:hover {
            color: #333;
        }

        input[type="button"] {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }

        input[type="button"]:hover {
            background-color: #45a049;
        }

        pre {
            background: #f0f0f0;
            padding: 10px;
            border-radius: 4px;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        #output {
            margin-top: 20px;
            max-width: 1100px;
            margin: 20px auto 0;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            background: #f0f0f0;
            color: #222;
        }

        #output-container {
            position: relative;
            max-width: 1100px;
            margin: 20px auto 0;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        #copy_output {
            position: absolute;
            top: 10px;
            right: 45px; /* Make space for download button */
            background: #fff;
            border: 1px solid #ccc;
            border-radius: 50%;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
            cursor: pointer;
            padding: 8px;
            z-index: 10;
            transition: background 0.2s, box-shadow 0.2s;
        }

        #download_output {
            position: absolute;
            top: 10px;
            right: 10px;
            background: #fff;
            border: 1px solid #ccc;
            border-radius: 50%;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
            cursor: pointer;
            padding: 8px;
            z-index: 10;
            transition: background 0.2s, box-shadow 0.2s;
        }

        #copy_output:hover,
        #download_output:hover {
            background: #f0f0f0;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        #copy_output svg,
        #download_output svg {
            display: block;
        }

        body.dark-mode #share_button svg {
            stroke: #aaa;
        }

        body.dark-mode {
            background-color: #181a1b;
            color: #e0e0e0;
        }

        body.dark-mode .header-text h1 {
            color: #e0e0e0;
        }

        body.dark-mode .header-text .subtitle,
        body.dark-mode .parser-version {
            color: #aaa;
        }

        body.dark-mode form {
            background: #23272a;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
        }

        body.dark-mode #output-container {
            background: #23272a;
            border-radius: 8px;
        }

        body.dark-mode textarea {
            background: #23272a;
            color: #e0e0e0;
            border: 1px solid #444;
        }

        body.dark-mode input[type="text"] {
            background: #23272a;
            color: #e0e0e0;
            border: 1px solid #444;
        }

        body.dark-mode .key-help {
            color: #aaa;
        }

        body.dark-mode .key-toggle {
            color: #aaa;
        }

        body.dark-mode .key-toggle:hover {
            color: #e0e0e0;
        }

        body.dark-mode pre {
            background: #23272a;
            color: #e0e0e0;
        }

        body.dark-mode #output {
            background: #23272a;
            color: #e0e0e0;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
        }

        body.dark-mode #copy_output,
        body.dark-mode #download_output {
            background: #23272a;
            border: 1px solid #444;
        }

        body.dark-mode #copy_output:hover,
        body.dark-mode #download_output:hover {
            background: #181a1b;
        }

        body.dark-mode input[type="button"] {
            background-color: #444;
            color: #e0e0e0;
        }

        body.dark-mode input[type="button"]:hover {
            background-color: #333;
        }

        body.dark-mode pre code,
        body.dark-mode .hljs {
            background: #23272a !important;
            color: #e0e0e0 !important;
        }

        body.dark-mode .hljs-keyword,
        body.dark-mode .hljs-selector-tag,
        body.dark-mode .hljs-literal,
        body.dark-mode .hljs-section,
        body.dark-mode .hljs-link {
            color: #ffcb6b !important;
        }

        body.dark-mode .hljs-string,
        body.dark-mode .hljs-title,
        body.dark-mode .hljs-name,
        body.dark-mode .hljs-type,
        body.dark-mode .hljs-attribute,
        body.dark-mode .hljs-symbol,
        body.dark-mode .hljs-bullet,
        body.dark-mode .hljs-addition {
            color: #c3e88d !important;
        }

        body.dark-mode .hljs-comment,
        body.dark-mode .hljs-quote,
        body.dark-mode .hljs-deletion {
            color: #616161 !important;
        }

        body.dark-mode .hljs-meta {
            color: #82aaff !important;
        }

        /* ── Interactive Hex Viewer ─────────────────────────── */
        .hex-viewer {
            display: flex;
            gap: 0;
            font-family: 'Menlo', 'Consolas', 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.5;
            min-height: 200px;
        }
        .hex-viewer-left {
            flex: 1;
            min-width: 0;
            overflow-x: auto;
            padding: 40px 12px 12px;
        }
        .hex-viewer-right {
            width: 320px;
            min-width: 260px;
            border-left: 1px solid #ddd;
            overflow-y: auto;
            max-height: 600px;
            padding: 40px 0 8px;
        }
        body.dark-mode .hex-viewer-right {
            border-left-color: #444;
        }

        /* Hex grid */
        .hex-header {
            color: #888;
            margin-bottom: 4px;
            white-space: pre;
            user-select: none;
        }
        .hex-row {
            white-space: pre;
            margin: 0;
            padding: 0;
        }
        .hex-offset {
            color: #888;
            user-select: none;
        }
        .hex-byte {
            display: inline-block;
            width: 26px;
            text-align: center;
            cursor: pointer;
            border-radius: 2px;
            transition: outline 0.1s;
        }
        .hex-byte:hover {
            outline: 2px solid #666;
            outline-offset: -1px;
        }
        .hex-gap {
            display: inline-block;
            width: 8px;
        }
        .hex-ascii-sep {
            display: inline-block;
            width: 16px;
        }
        .hex-ascii {
            display: inline-block;
            width: 9px;
            text-align: center;
            cursor: pointer;
            border-radius: 2px;
        }
        .hex-byte.highlight, .hex-ascii.highlight {
            outline: 2px solid #1565c0 !important;
            outline-offset: -1px;
        }
        body.dark-mode .hex-byte.highlight, body.dark-mode .hex-ascii.highlight {
            outline-color: #64b5f6 !important;
        }

        /* Layer colors */
        .hex-layer-frame      { background: #bbdefb; color: #0d47a1; }
        .hex-layer-appheader  { background: #c8e6c9; color: #1b5e20; }
        .hex-layer-record     { background: #fff9c4; color: #f57f17; }
        body.dark-mode .hex-layer-frame     { background: #1a3a5c; color: #90caf9; }
        body.dark-mode .hex-layer-appheader { background: #1b3d1f; color: #a5d6a7; }
        body.dark-mode .hex-layer-record    { background: #3e3510; color: #fff176; }

        /* Segment tooltip */
        .hex-tooltip {
            position: fixed;
            background: #333;
            color: #fff;
            padding: 6px 10px;
            border-radius: 4px;
            font-size: 12px;
            pointer-events: none;
            z-index: 1000;
            max-width: 350px;
            white-space: nowrap;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
            display: none;
        }

        /* Tree panel */
        .hex-tree-section {
            padding: 0;
            margin: 0;
        }
        .hex-tree-layer {
            font-weight: bold;
            font-size: 12px;
            padding: 6px 12px 4px;
            color: #555;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            user-select: none;
        }
        body.dark-mode .hex-tree-layer {
            color: #aaa;
        }
        .hex-tree-group {
            margin: 0;
            padding: 0;
        }
        .hex-tree-group-header {
            padding: 4px 12px;
            cursor: pointer;
            font-weight: 600;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 6px;
            user-select: none;
            border-radius: 4px;
            margin: 0 4px;
        }
        .hex-tree-group-header:hover {
            background: #e3f2fd;
        }
        body.dark-mode .hex-tree-group-header:hover {
            background: #1a3a5c;
        }
        .hex-tree-group-header .arrow {
            display: inline-block;
            transition: transform 0.15s;
            font-size: 10px;
            width: 12px;
        }
        .hex-tree-group-header.collapsed .arrow {
            transform: rotate(-90deg);
        }
        .hex-tree-group-body {
            padding: 0;
            margin: 0;
        }
        .hex-tree-group-body.hidden {
            display: none;
        }
        .hex-tree-item {
            padding: 2px 12px 2px 30px;
            cursor: pointer;
            font-size: 12px;
            border-radius: 4px;
            margin: 0 4px;
            display: flex;
            justify-content: space-between;
            gap: 8px;
        }
        .hex-tree-item:hover,
        .hex-tree-item.active {
            background: #e3f2fd;
        }
        body.dark-mode .hex-tree-item:hover,
        body.dark-mode .hex-tree-item.active {
            background: #1a3a5c;
        }
        .hex-tree-item .tree-kind {
            color: #666;
            flex-shrink: 0;
        }
        .hex-tree-item .tree-detail {
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        body.dark-mode .hex-tree-item .tree-kind {
            color: #aaa;
        }
        body.dark-mode .hex-tree-item .tree-detail {
            color: #e0e0e0;
        }
        .hex-tree-item .tree-offset {
            color: #999;
            font-size: 11px;
            flex-shrink: 0;
        }

        @media (max-width: 800px) {
            .hex-viewer {
                flex-direction: column;
            }
            .hex-viewer-right {
                width: 100%;
                border-left: none;
                border-top: 1px solid #ddd;
                max-height: 400px;
            }
        }
    </style>
</head>

<body>
    <div class="header">
        <img id="banner" src="meter.png" alt="Meter Banner">
        <div class="header-text">
            <h1>Online M-Bus Parser <span class="parser-version" id="parser-version"></span></h1>
            <div class="subtitle">
                <a href="https://maebli.github.io/m-bus-parser" target="_blank">maebli.github.io/m-bus-parser</a> • <a href="https://github.com/maebli" target="_blank">Michael Aebli</a>
            </div>
        </div>
        <div class="header-controls">
            <button id="dark_mode_toggle" title="Toggle dark mode" style="background:none;border:none;cursor:pointer;padding:8px;">
                <svg id="dark_mode_icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#333" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <circle cx="12" cy="12" r="5" />
                    <path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" />
                </svg>
            </button>
            <button id="share_button" title="Copy share link" style="background:none;border:none;cursor:pointer;padding:8px;">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#333" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/>
                    <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
                </svg>
            </button>
            <button id="report_issue" title="Report Issue" style="background:none;border:none;cursor:pointer;padding:8px;">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#e74c3c" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <circle cx="12" cy="12" r="10" />
                    <line x1="12" y1="8" x2="12" y2="12" />
                    <circle cx="12" cy="16" r="1" />
                </svg>
            </button>
        </div>
    </div>
    <form>
        <label for="inputstring">Input String:</label>
        <textarea rows="5" cols="80"
            id="inputstring">68 3D 3D 68 08 01 72 00 51 20 02 82 4D 02 04 00 88 00 00 04 07 00 00 00 00 0C 15 03 00 00 00 0B 2E 00 00 00 0B 3B 00 00 00 0A 5A 88 12 0A 5E 16 05 0B 61 23 77 00 02 6C 8C 11 02 27 37 0D 0F 60 00 67 16</textarea>

        <label for="aeskey">AES-128 Decryption Key (optional):</label>
        <div class="key-input-container">
            <input type="password" id="aeskey" placeholder="Enter 32 hex characters (16 bytes)" maxlength="32" pattern="[0-9A-Fa-f]{32}" />
            <button type="button" class="key-toggle" id="key-toggle" title="Show/Hide key">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                    <circle cx="12" cy="12" r="3"></circle>
                </svg>
            </button>
        </div>
        <div class="key-help">Leave empty for unencrypted frames. Format: 32 hexadecimal characters (e.g., 0123456789ABCDEF0123456789ABCDEF)</div>

        <input id="parse_json" type="button" value="Parse to JSON" />
        <input id="parse_yaml" type="button" value="Parse to YAML" />
        <input id="parse_table" type="button" value="Parse to Table" />
        <input id="parse_csv" type="button" value="Parse to CSV" />
        <input id="parse_mermaid" type="button" value="Parse to Diagram" />
        <input id="parse_hexview" type="button" value="Hex View" />
    </form>
    <div id="output-container">
        <button id="copy_output" title="Copy Output">
            <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#333" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1-2 2v1" />
            </svg>
        </button>
        <a id="download_output" title="Download Output" href="#" download="">
            <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#333" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                <polyline points="7 10 12 15 17 10" />
                <line x1="12" y1="15" x2="12" y2="3" />
            </svg>
        </a>
        <pre id="output"></pre>
    </div>
    <script type="module">
        import init, { m_bus_parse, m_bus_parse_with_key, version } from "./m_bus_parser_wasm_pack.js";

        let currentFormat = "json"; // Keep track of the last used format

        mermaid.initialize({ startOnLoad: false, theme: 'default' });

        async function setup() {
            // Dark mode setup
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            const savedMode = localStorage.getItem('darkMode');
            const body = document.body;
            const icon = document.getElementById('dark_mode_icon');
            function setDarkMode(on) {
                if (on) {
                    body.classList.add('dark-mode');
                    icon.innerHTML = '<path d="M21.64 13.64A9 9 0 1 1 12 3v0a7 7 0 0 0 9.64 10.64z" />';
                } else {
                    body.classList.remove('dark-mode');
                    icon.innerHTML = '<circle cx="12" cy="12" r="5" /><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" />';
                }
            }
            let darkMode = savedMode === null ? prefersDark : savedMode === 'true';
            setDarkMode(darkMode);
            document.getElementById('dark_mode_toggle').addEventListener('click', () => {
                darkMode = !body.classList.contains('dark-mode');
                setDarkMode(darkMode);
                localStorage.setItem('darkMode', darkMode);
            });

            // Key visibility toggle
            const keyInput = document.getElementById('aeskey');
            const keyToggle = document.getElementById('key-toggle');
            keyToggle.addEventListener('click', () => {
                const type = keyInput.getAttribute('type');
                if (type === 'password') {
                    keyInput.setAttribute('type', 'text');
                    keyToggle.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>';
                } else {
                    keyInput.setAttribute('type', 'password');
                    keyToggle.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>';
                }
            });

            await init(); // Ensure the WASM module is initialized
            document.getElementById('parser-version').textContent = 'v' + version();

            // Load data and format from URL params and auto-parse if present
            const urlParams = new URLSearchParams(window.location.search);
            const urlData = urlParams.get('data');
            const urlFormat = urlParams.get('format');
            if (urlData) {
                document.getElementById('inputstring').value = urlData;
                parseInput(urlFormat || 'mermaid');
            }

            document.getElementById('parse_json').addEventListener('click', () => {
                parseInput("json");
            });

            document.getElementById('parse_yaml').addEventListener('click', () => {
                parseInput("yaml");
            });

            document.getElementById('parse_table').addEventListener('click', () => {
                parseInput("table_format");
            });

            document.getElementById('parse_csv').addEventListener('click', () => {
                parseInput("csv");
            });

            document.getElementById('parse_mermaid').addEventListener('click', () => {
                parseInput("mermaid");
            });

            document.getElementById('parse_hexview').addEventListener('click', () => {
                parseInput("hexview");
            });

            document.getElementById('copy_output').addEventListener('click', () => {
                let text;
                if (currentFormat === 'mermaid' && window._mermaidSource) {
                    text = window._mermaidSource;
                } else {
                    const codeElem = document.getElementById('output_code');
                    text = codeElem ? codeElem.textContent : document.getElementById('output').textContent;
                }
                navigator.clipboard.writeText(text);
            });

            document.getElementById('share_button').addEventListener('click', () => {
                const inputString = document.getElementById('inputstring').value;
                const params = new URLSearchParams({ data: inputString, format: currentFormat });
                const shareUrl = `${location.origin}${location.pathname}?${params}`;
                navigator.clipboard.writeText(shareUrl);
                const btn = document.getElementById('share_button');
                btn.title = 'Copied!';
                setTimeout(() => { btn.title = 'Copy share link'; }, 2000);
            });

            document.getElementById('report_issue').addEventListener('click', () => {
                window.open('https://github.com/maebli/m-bus-parser/issues/new', '_blank');
            });

            async function parseInput(format) {
                currentFormat = format; // Update the current format
                const inputString = document.getElementById('inputstring').value;
                const aesKey = document.getElementById('aeskey').value.trim();

                // Update URL so the current parse can be shared
                const params = new URLSearchParams({ data: inputString, format });
                history.replaceState(null, '', `?${params}`);

                // Validate key if provided
                if (aesKey && aesKey.length > 0) {
                    if (!/^[0-9A-Fa-f]{32}$/.test(aesKey)) {
                        alert('Invalid AES key format. Please enter exactly 32 hexadecimal characters (0-9, A-F).');
                        return;
                    }
                }

                // Use the appropriate parsing function based on whether a key is provided
                // (hexview handles its own WASM call below)
                let formattedResult;
                if (format !== 'hexview') {
                    formattedResult = (aesKey && aesKey.length > 0)
                        ? m_bus_parse_with_key(inputString, format, aesKey)
                        : m_bus_parse(inputString, format);
                }

                const outputContainer = document.getElementById('output');
                const outputCode = document.getElementById('output_code');
                let lang = '', extension = 'txt', mimeType = 'text/plain';
                if (format === 'json') { lang = 'json'; extension = 'json'; mimeType = 'application/json'; }
                else if (format === 'yaml') { lang = 'yaml'; extension = 'yaml'; mimeType = 'application/x-yaml'; }
                else if (format === 'csv') { extension = 'csv'; mimeType = 'text/csv'; }
                else if (format === 'table_format') { lang = 'plaintext'; extension = 'txt'; }
                else if (format === 'mermaid') { extension = 'mmd'; mimeType = 'text/plain'; }

                outputContainer.style.background = '';
                outputContainer.style.whiteSpace = '';

                if (format === 'hexview') {
                    // Hex view: get annotated JSON from WASM, then render interactive viewer
                    const annotatedJson = (aesKey && aesKey.length > 0)
                        ? m_bus_parse_with_key(inputString, "annotated", aesKey)
                        : m_bus_parse(inputString, "annotated");
                    window._lastAnnotatedJson = annotatedJson;
                    extension = 'json'; mimeType = 'application/json';
                    outputContainer.style.background = 'none';
                    outputContainer.style.whiteSpace = 'normal';
                    outputContainer.innerHTML = '';
                    renderHexViewer(outputContainer, annotatedJson, inputString);
                } else if (format === 'csv') {
                    outputContainer.innerHTML = formattedResult;
                } else if (format === 'mermaid') {
                    window._mermaidSource = formattedResult;
                    outputContainer.style.background = 'none';
                    outputContainer.style.whiteSpace = 'normal';
                    outputContainer.innerHTML = '';
                    const mermaidDiv = document.createElement('div');
                    mermaidDiv.id = 'mermaid_diagram';
                    mermaidDiv.textContent = formattedResult;
                    outputContainer.appendChild(mermaidDiv);
                    await mermaid.run({ nodes: [mermaidDiv] });
                } else {
                    outputContainer.innerHTML = '<code id="output_code"></code>';
                    const newOutputCode = document.getElementById('output_code');
                    newOutputCode.className = lang ? `language-${lang}` : '';
                    newOutputCode.textContent = formattedResult;
                    if (window.hljs && lang) hljs.highlightElement(newOutputCode);
                }

                // Update download link
                if (window._lastDownloadUrl) URL.revokeObjectURL(window._lastDownloadUrl);
                const downloadContent = format === 'hexview' ? (window._lastAnnotatedJson || '') : (formattedResult || '');
                const blob = new Blob([downloadContent], { type: mimeType });
                const url = URL.createObjectURL(blob);
                const downloadLink = document.getElementById('download_output');
                downloadLink.href = url;
                downloadLink.download = `m-bus-output.${extension}`;
                window._lastDownloadUrl = url;
            }
        }

        function renderHexViewer(container, annotatedJson, inputString) {
            let segments;
            try {
                segments = JSON.parse(annotatedJson);
            } catch (e) {
                container.innerHTML = '<pre style="color:red;">Error parsing annotation data: ' + e.message + '</pre>';
                return;
            }
            if (!Array.isArray(segments) || segments.length === 0) {
                container.innerHTML = '<pre style="color:red;">No annotation segments returned. Check input.</pre>';
                return;
            }

            // Parse raw bytes from input string
            const rawBytes = inputString.replace(/\s+/g, '').match(/.{1,2}/g).map(h => parseInt(h, 16));

            // Build byte-to-segment lookup
            const byteToSeg = new Array(rawBytes.length).fill(null);
            segments.forEach((seg, idx) => {
                for (let i = seg.start; i < seg.end && i < rawBytes.length; i++) {
                    byteToSeg[i] = idx;
                }
            });

            // Layer CSS class
            function layerClass(layer) {
                if (layer === 'Frame') return 'hex-layer-frame';
                if (layer === 'AppHeader') return 'hex-layer-appheader';
                return 'hex-layer-record';
            }

            // Create viewer structure
            const viewer = document.createElement('div');
            viewer.className = 'hex-viewer';

            const leftPanel = document.createElement('div');
            leftPanel.className = 'hex-viewer-left';

            const rightPanel = document.createElement('div');
            rightPanel.className = 'hex-viewer-right';

            viewer.appendChild(leftPanel);
            viewer.appendChild(rightPanel);
            container.appendChild(viewer);

            // Tooltip
            const tooltip = document.createElement('div');
            tooltip.className = 'hex-tooltip';
            document.body.appendChild(tooltip);

            // Render hex grid
            const header = document.createElement('div');
            header.className = 'hex-header';
            let hdrText = '  Offset  ';
            for (let i = 0; i < 16; i++) {
                hdrText += i.toString(16).toUpperCase().padStart(2, '0') + ' ';
                if (i === 7) hdrText += ' ';
            }
            hdrText += '  ASCII';
            header.textContent = hdrText;
            leftPanel.appendChild(header);

            const byteElements = [];
            const asciiElements = [];

            for (let row = 0; row * 16 < rawBytes.length; row++) {
                const rowDiv = document.createElement('div');
                rowDiv.className = 'hex-row';

                // Offset
                const offsetSpan = document.createElement('span');
                offsetSpan.className = 'hex-offset';
                offsetSpan.textContent = '  ' + (row * 16).toString(16).toUpperCase().padStart(4, '0') + '  ';
                rowDiv.appendChild(offsetSpan);

                const rowAsciiSpans = [];

                for (let col = 0; col < 16; col++) {
                    const byteIdx = row * 16 + col;
                    if (byteIdx >= rawBytes.length) {
                        // Pad
                        const pad = document.createElement('span');
                        pad.style.display = 'inline-block';
                        pad.style.width = '26px';
                        rowDiv.appendChild(pad);
                        if (col === 7) {
                            const gap = document.createElement('span');
                            gap.className = 'hex-gap';
                            rowDiv.appendChild(gap);
                        }
                        continue;
                    }

                    const b = rawBytes[byteIdx];
                    const segIdx = byteToSeg[byteIdx];
                    const seg = segIdx !== null ? segments[segIdx] : null;

                    const span = document.createElement('span');
                    span.className = 'hex-byte ' + (seg ? layerClass(seg.layer) : '');
                    span.textContent = b.toString(16).toUpperCase().padStart(2, '0') + ' ';
                    span.dataset.byteIdx = byteIdx;
                    if (segIdx !== null) span.dataset.segIdx = segIdx;
                    byteElements[byteIdx] = span;
                    rowDiv.appendChild(span);

                    if (col === 7) {
                        const gap = document.createElement('span');
                        gap.className = 'hex-gap';
                        rowDiv.appendChild(gap);
                    }

                    // ASCII
                    const aSpan = document.createElement('span');
                    const ch = (b >= 0x21 && b <= 0x7e) ? String.fromCharCode(b) : '\u00b7';
                    aSpan.className = 'hex-ascii ' + (seg ? layerClass(seg.layer) : '');
                    aSpan.textContent = ch;
                    aSpan.dataset.byteIdx = byteIdx;
                    if (segIdx !== null) aSpan.dataset.segIdx = segIdx;
                    asciiElements[byteIdx] = aSpan;
                    rowAsciiSpans.push(aSpan);
                }

                // ASCII separator
                const sep = document.createElement('span');
                sep.className = 'hex-ascii-sep';
                rowDiv.appendChild(sep);

                rowAsciiSpans.forEach(s => rowDiv.appendChild(s));

                leftPanel.appendChild(rowDiv);
            }

            // Highlight helpers
            let activeSegIdx = null;
            function highlightSegment(segIdx) {
                clearHighlight();
                if (segIdx === null || segIdx === undefined) return;
                activeSegIdx = segIdx;
                const seg = segments[segIdx];
                for (let i = seg.start; i < seg.end; i++) {
                    if (byteElements[i]) byteElements[i].classList.add('highlight');
                    if (asciiElements[i]) asciiElements[i].classList.add('highlight');
                }
                // Highlight tree item
                const treeItem = rightPanel.querySelector(`[data-seg-idx="${segIdx}"]`);
                if (treeItem) {
                    treeItem.classList.add('active');
                    treeItem.scrollIntoView({ block: 'nearest' });
                    // Expand parent group if collapsed
                    const groupBody = treeItem.closest('.hex-tree-group-body');
                    if (groupBody && groupBody.classList.contains('hidden')) {
                        groupBody.classList.remove('hidden');
                        const groupHeader = groupBody.previousElementSibling;
                        if (groupHeader) groupHeader.classList.remove('collapsed');
                    }
                }
            }
            function clearHighlight() {
                activeSegIdx = null;
                byteElements.forEach(el => { if (el) el.classList.remove('highlight'); });
                asciiElements.forEach(el => { if (el) el.classList.remove('highlight'); });
                rightPanel.querySelectorAll('.hex-tree-item.active').forEach(el => el.classList.remove('active'));
            }

            // Hex grid events
            leftPanel.addEventListener('mouseover', e => {
                const el = e.target.closest('[data-seg-idx]');
                if (!el) return;
                const segIdx = parseInt(el.dataset.segIdx);
                const seg = segments[segIdx];
                tooltip.textContent = seg.kind + ': ' + seg.detail;
                tooltip.style.display = 'block';
            });
            leftPanel.addEventListener('mousemove', e => {
                tooltip.style.left = (e.clientX + 12) + 'px';
                tooltip.style.top = (e.clientY - 30) + 'px';
            });
            leftPanel.addEventListener('mouseout', e => {
                const el = e.target.closest('[data-seg-idx]');
                if (el) tooltip.style.display = 'none';
            });
            leftPanel.addEventListener('click', e => {
                const el = e.target.closest('[data-seg-idx]');
                if (!el) { clearHighlight(); return; }
                const segIdx = parseInt(el.dataset.segIdx);
                if (activeSegIdx === segIdx) { clearHighlight(); }
                else { highlightSegment(segIdx); }
            });

            // Build tree panel
            // Group segments by layer, then by record group
            let currentLayer = null;
            let currentGroup = null;
            let groupBody = null;

            segments.forEach((seg, segIdx) => {
                if (seg.layer !== currentLayer) {
                    currentLayer = seg.layer;
                    currentGroup = null;
                    const layerLabel = document.createElement('div');
                    layerLabel.className = 'hex-tree-layer';
                    const layerNames = { 'Frame': 'Frame', 'AppHeader': 'Application Header', 'RecordField': 'Data Records' };
                    layerLabel.textContent = layerNames[seg.layer] || seg.layer;
                    rightPanel.appendChild(layerLabel);
                    groupBody = null;
                }

                // Record grouping
                if (seg.layer === 'RecordField' && seg.group !== null && seg.group !== currentGroup) {
                    currentGroup = seg.group;
                    const groupDiv = document.createElement('div');
                    groupDiv.className = 'hex-tree-group';

                    const groupHeader = document.createElement('div');
                    groupHeader.className = 'hex-tree-group-header';
                    groupHeader.innerHTML = '<span class="arrow">\u25BC</span> Record ' + seg.group;
                    groupDiv.appendChild(groupHeader);

                    groupBody = document.createElement('div');
                    groupBody.className = 'hex-tree-group-body';
                    groupDiv.appendChild(groupBody);

                    groupHeader.addEventListener('click', () => {
                        groupBody.classList.toggle('hidden');
                        groupHeader.classList.toggle('collapsed');
                    });

                    rightPanel.appendChild(groupDiv);
                }

                const item = document.createElement('div');
                item.className = 'hex-tree-item';
                item.dataset.segIdx = segIdx;

                const offsetStr = seg.end - seg.start === 1
                    ? '[' + seg.start.toString(16).toUpperCase().padStart(2, '0') + ']'
                    : '[' + seg.start.toString(16).toUpperCase().padStart(2, '0') + '..' + seg.end.toString(16).toUpperCase().padStart(2, '0') + ']';

                item.innerHTML =
                    '<span class="tree-kind">' + escHtml(seg.kind) + '</span>' +
                    '<span class="tree-detail">' + escHtml(seg.detail) + '</span>' +
                    '<span class="tree-offset">' + offsetStr + '</span>';

                item.addEventListener('click', () => {
                    if (activeSegIdx === segIdx) { clearHighlight(); }
                    else { highlightSegment(segIdx); }
                });
                item.addEventListener('mouseover', () => {
                    if (activeSegIdx === null) {
                        const s = segments[segIdx];
                        for (let i = s.start; i < s.end; i++) {
                            if (byteElements[i]) byteElements[i].classList.add('highlight');
                            if (asciiElements[i]) asciiElements[i].classList.add('highlight');
                        }
                    }
                });
                item.addEventListener('mouseout', () => {
                    if (activeSegIdx === null) {
                        clearHighlight();
                    }
                });

                if (groupBody && seg.group !== null) {
                    groupBody.appendChild(item);
                } else {
                    rightPanel.appendChild(item);
                }
            });

            // Cleanup tooltip on viewer removal
            const observer = new MutationObserver(() => {
                if (!document.body.contains(viewer)) {
                    tooltip.remove();
                    observer.disconnect();
                }
            });
            observer.observe(container, { childList: true });
        }

        function escHtml(s) {
            return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
        }

        setup(); // Set up the event listeners after the page is loaded
    </script>
</body>

</html>