-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalpha_connect_web.py
More file actions
executable file
·1565 lines (1424 loc) · 66.7 KB
/
Copy pathalpha_connect_web.py
File metadata and controls
executable file
·1565 lines (1424 loc) · 66.7 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
"""
Alpha Connect Web Wrapper — a browser UI for the reverse-engineered
LuxTronic GLT-enable protocol + integrated USB license manager.
Runs a local HTTP server that serves a config UI:
1. Send UDP packet to heat pump on port 4444 to write /home/GLT.conf
and call InitGLT() (protocol decoded from CDemoappl::UDP_Handler at 0xddc54).
2. Read/write license blocks on a USB dongle (Python port of
https://github.com/Jaarden/luxtronic-glt-licensetool/blob/main/licensetool.c).
USAGE
# For UDP-only features:
python3 alpha_connect_web.py [--port 8080]
# For license operations (writes raw block device — needs root):
sudo python3 alpha_connect_web.py [--port 8080]
Then open http://localhost:8080/ in a browser.
STDLIB ONLY. No third-party packages required.
"""
import argparse
import json
import os
import secrets
import socket
import struct
import subprocess
import threading
import time
from http.server import HTTPServer, BaseHTTPRequestHandler
# ── Protocol layer ────────────────────────────────────────────────────────
def build_glt_packet(config):
"""Build the UDP payload from a config dict. Field order MUST match
what UDP_Handler at 0xddc54 expects when subcmd=0xBAC1.
"""
fields = [
"5000", # cmd: config write
"47809", # subcmd 0xBAC1: GLT WRITE (0xBAC0 is read-only)
str(int(config.get("mode", 0))), # Einst_GLT_akt (0=off default, 1=BACnet, 2=Modbus — 1/2 need license)
str(int(config.get("bacnet_port", 47808))), # BACnet listen port (vector[0])
"0", # vector[1] — reserved/unused by handler
str(int(config.get("fkt_at", 0))),
str(int(config.get("fkt_freigabe", 1))),
str(int(config.get("fkt_sollwert", 1))),
str(int(config.get("fkt_sollwert_mk1", 1))),
str(int(config.get("fkt_sollwert_mk2", 1))),
str(int(config.get("fkt_sollwert_mk3", 0))),
str(int(config.get("fkt_ba_heizen", 1))),
str(int(config.get("fkt_ba_brauchw", 1))),
str(int(config.get("fkt_ba_mk1", 1))),
str(int(config.get("fkt_ba_mk2", 1))),
str(int(config.get("fkt_ba_mk3", 0))),
str(int(config.get("fkt_ba_kuehl", 1))),
str(int(config.get("fkt_ba_lueftung", 0))),
str(int(config.get("fkt_ba_schwimmbad", 0))),
str(config.get("vendorname", "JaSec")),
str(int(config.get("vendor_id", 123))),
str(config.get("modelname", "FordKuga")),
str(config.get("location", "Somewhere")),
str(config.get("device_description", "YourDescription")),
str(int(config.get("device_id", 50))),
str(config.get("devicename", "HackedByJAarden")),
]
return (";".join(fields) + ";").encode("ascii")
def send_udp(ip, port, payload, timeout=5):
"""Send UDP packet, return (response_bytes, from_addr) or (None, None)."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(timeout)
try:
s.sendto(payload, (ip, port))
try:
data, addr = s.recvfrom(4096)
return data, addr
except socket.timeout:
return None, None
finally:
s.close()
def check_tcp_port(ip, port, timeout=2):
"""Simple TCP connect test — returns True if we can open a socket."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
try:
s.connect((ip, port))
return True
except Exception:
return False
finally:
s.close()
def check_modbus_alive(ip, timeout=3):
"""
Modbus TCP test: attempt a MBAP-framed Read Holding Registers request
on port 502. If a well-formed reply comes back, Modbus is live.
If port is closed we get ConnectionRefused; if unreachable we time out.
Returns (up: bool, reply_or_error: str).
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
try:
s.connect((ip, 502))
# MBAP header: transaction=1, protocol=0, length=6, unit=1
# PDU: fn=0x03 (Read Holding Regs), addr=0, count=1
req = struct.pack("!HHHBBHH", 1, 0, 6, 1, 0x03, 0, 1)
s.sendall(req)
try:
resp = s.recv(64)
if len(resp) >= 8:
return True, f"MBAP reply ({len(resp)} bytes): {resp.hex()}"
return True, f"TCP open (short reply: {resp.hex()!r})"
except socket.timeout:
return True, "TCP open, no Modbus reply (device may be busy)"
except ConnectionRefusedError:
return False, "connection refused (Modbus off / mode 0)"
except socket.timeout:
return False, "TCP connect timeout"
except Exception as e:
return False, str(e)
finally:
s.close()
def check_bacnet_alive(ip, timeout=2):
"""BACnet Who-Is unicast — succeeds if port 47808 responds."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(timeout)
# BVLC + NPDU + APDU Who-Is
whois = bytes([0x81, 0x0b, 0x00, 0x0c, 0x01, 0x20,
0xff, 0xff, 0x00, 0xff, 0x10, 0x08])
try:
s.sendto(whois, (ip, 47808))
data, addr = s.recvfrom(1024)
return True, data.hex()
except socket.timeout:
return False, None
except Exception as e:
return False, str(e)
finally:
s.close()
# ── License tool (Python port of Jaarden/luxtronic-glt-licensetool) ───────
# Source: https://github.com/Jaarden/luxtronic-glt-licensetool/blob/main/licensetool.c
#
# The license lives in the LAST 512 bytes of the USB dongle's raw block device.
# Layout:
# offset 0x34 uint16 LE license count
# offset 0x65 2 bytes fixed value 0x01 0x02 (used in checksum)
# offset 0x69 2 bytes fixed value 0x03 0x04 (used in checksum)
# offset 0x1FC uint16 LE stored checksum = getChecksum(0x34) + getChecksum(0x65) + getChecksum(0x69)
# remainder random bytes
#
# getCheckSum sums exactly 2 bytes starting at the given offset.
LICENSE_BLOCK_SIZE = 512
def _get_checksum(block, offset):
# Matches getCheckSum() at 0x001b1d88 in appl: sums two bytes at [offset], [offset+1].
return (block[offset] + block[offset + 1]) & 0xFFFF
def _check_not_mounted(device_path):
"""Refuse to operate on a mounted device — the FS could overwrite our writes,
which is the most likely cause of intermittent license failures."""
try:
with open("/proc/mounts") as f:
for line in f:
parts = line.split()
if not parts:
continue
src = parts[0]
# /dev/sdb1, /dev/sdb-part1, /dev/mapper/*, etc — anything that starts with our device
if src == device_path or src.startswith(device_path):
mp = parts[1] if len(parts) > 1 else "?"
raise IOError(
f"{src} is mounted at {mp}. Unmount it first "
f"(sudo umount {src}) — a mounted filesystem can overwrite "
f"the license block and cause intermittent failures."
)
except FileNotFoundError:
pass # not on Linux, skip
def _device_size(fd):
"""Get block-device or file size in bytes."""
# Try BLKGETSIZE64 first (block device); fall back to lseek for regular files.
try:
import fcntl
BLKGETSIZE64 = 0x80081272
buf = fcntl.ioctl(fd, BLKGETSIZE64, b"\x00" * 8)
return int.from_bytes(buf, "little")
except (OSError, ImportError):
return os.lseek(fd, 0, os.SEEK_END)
def _read_license_block(device_path):
"""Raw unbuffered read of the last 512 bytes. Bypasses Python's buffered IO."""
_check_not_mounted(device_path)
fd = os.open(device_path, os.O_RDONLY)
try:
size = _device_size(fd)
if size < LICENSE_BLOCK_SIZE:
raise IOError(f"{device_path} too small: {size} bytes")
os.lseek(fd, size - LICENSE_BLOCK_SIZE, os.SEEK_SET)
data = b""
while len(data) < LICENSE_BLOCK_SIZE:
chunk = os.read(fd, LICENSE_BLOCK_SIZE - len(data))
if not chunk:
raise IOError(f"short read from {device_path}: {len(data)} bytes")
data += chunk
return data
finally:
os.close(fd)
def _write_license_block(device_path, block):
"""Raw synchronous write of the last 512 bytes, followed by fsync + BLKFLSBUF.
Uses O_SYNC so each write is committed before returning, and issues fsync
at the end to force the kernel page cache to disk. This is what fixes the
intermittency in the original licensetool.c which only did fflush() on stdio.
"""
if len(block) != LICENSE_BLOCK_SIZE:
raise ValueError(f"block must be {LICENSE_BLOCK_SIZE} bytes")
_check_not_mounted(device_path)
flags = os.O_RDWR | os.O_SYNC
fd = os.open(device_path, flags)
try:
size = _device_size(fd)
if size < LICENSE_BLOCK_SIZE:
raise IOError(f"{device_path} too small: {size} bytes")
offset = size - LICENSE_BLOCK_SIZE
os.lseek(fd, offset, os.SEEK_SET)
written = 0
while written < LICENSE_BLOCK_SIZE:
n = os.write(fd, bytes(block[written:]))
if n <= 0:
raise IOError(f"write stalled at {written} bytes")
written += n
os.fsync(fd)
# For block devices, also flush the kernel buffer cache so subsequent
# reads (from a different fd or another tool) see our data.
try:
import fcntl
BLKFLSBUF = 0x1261
fcntl.ioctl(fd, BLKFLSBUF)
except (OSError, ImportError):
pass
finally:
os.close(fd)
def _build_license_block(license_count):
"""Compose a 512-byte block matching the licensetool layout."""
block = bytearray(secrets.token_bytes(LICENSE_BLOCK_SIZE))
# license count at 0x34, little-endian
block[0x34] = license_count & 0xFF
block[0x35] = (license_count >> 8) & 0xFF
# Checksum-source bytes
block[0x65] = 0x01
block[0x66] = 0x02
block[0x69] = 0x03
block[0x6A] = 0x04
# Compute checksum
c1 = _get_checksum(block, 0x34)
c2 = _get_checksum(block, 0x65)
c3 = _get_checksum(block, 0x69)
total = (c1 + c2 + c3) & 0xFFFF
block[0x1FC] = total & 0xFF
block[0x1FD] = (total >> 8) & 0xFF
return bytes(block)
def check_licenses(device_path):
"""Read + validate the license block. Returns dict with count and checksum info."""
block = _read_license_block(device_path)
count = block[0x34] | (block[0x35] << 8)
c1 = _get_checksum(block, 0x34)
c2 = _get_checksum(block, 0x65)
c3 = _get_checksum(block, 0x69)
calculated = (c1 + c2 + c3) & 0xFFFF
stored = block[0x1FC] | (block[0x1FD] << 8)
return {
"count": count,
"calculated_checksum": calculated,
"stored_checksum": stored,
"checksum_ok": calculated == stored,
"components": {"c1": c1, "c2": c2, "c3": c3},
}
def create_licenses(device_path, license_count):
"""Write a new license block with the given license count.
Writes to the raw device AND every partition, because the heat pump's
/dev/usb symlink may point to either — writing to only one of them is
the primary cause of intermittent success.
"""
if license_count < 1 or license_count > 0xFFFF:
raise ValueError("license count must be 1..65535")
block = _build_license_block(license_count)
targets = _write_targets_for(device_path)
results = []
last_err = None
for tgt in targets:
try:
_write_license_block(tgt, block)
verify = check_licenses(tgt)
results.append({"target": tgt, "ok": True, "verify": verify})
except Exception as e:
results.append({"target": tgt, "ok": False, "error": str(e)})
last_err = e
# Primary result is verification of the original device_path
primary = check_licenses(device_path)
primary["targets_written"] = results
if last_err and not any(r["ok"] for r in results):
raise last_err
return primary
def decrement_licenses(device_path):
"""Read the license count, decrement by 1, write to raw device AND all partitions."""
current = check_licenses(device_path)
if current["count"] == 0:
raise ValueError("no licenses left to decrement")
new_count = current["count"] - 1
block = _build_license_block(new_count)
targets = _write_targets_for(device_path)
results = []
last_err = None
for tgt in targets:
try:
_write_license_block(tgt, block)
verify = check_licenses(tgt)
results.append({"target": tgt, "ok": True, "verify": verify})
except Exception as e:
results.append({"target": tgt, "ok": False, "error": str(e)})
last_err = e
primary = check_licenses(device_path)
primary["targets_written"] = results
if last_err and not any(r["ok"] for r in results):
raise last_err
return primary
def _list_partitions(dev_name):
"""Given 'sda', return ['/dev/sda1', '/dev/sda2', ...] partitions that exist."""
parts = []
try:
for sub in sorted(os.listdir(f"/sys/block/{dev_name}")):
if sub.startswith(dev_name):
parts.append(f"/dev/{sub}")
except FileNotFoundError:
pass
return parts
def list_usb_candidates():
"""
Enumerate removable block devices that look like USB dongles.
Reads /sys/block/*/removable to filter, and includes size for sanity-checking.
Also lists partitions of each device — the heat pump's /dev/usb might point
to either the raw device or a partition depending on udev rules.
"""
candidates = []
try:
for name in os.listdir("/sys/block"):
# Skip virtual/loop devices
if name.startswith(("loop", "ram", "sr", "dm-")):
continue
removable_path = f"/sys/block/{name}/removable"
try:
with open(removable_path) as f:
if f.read().strip() != "1":
continue
except FileNotFoundError:
continue
# Get size in bytes (512-byte sectors)
size_bytes = 0
try:
with open(f"/sys/block/{name}/size") as f:
size_bytes = int(f.read().strip()) * 512
except FileNotFoundError:
pass
# Get model
model = ""
try:
with open(f"/sys/block/{name}/device/model") as f:
model = f.read().strip()
except FileNotFoundError:
pass
partitions = _list_partitions(name)
candidates.append({
"device": f"/dev/{name}",
"model": model,
"size_bytes": size_bytes,
"size_human": _human_size(size_bytes),
"partitions": partitions,
})
except FileNotFoundError:
pass
return candidates
def _write_targets_for(device_path):
"""Given a user-selected device path, return the list of paths we should
write the license block to. If the device has partitions we write to BOTH
the raw device AND every partition — the heat pump's /dev/usb symlink might
point to either, and this is the most likely cause of intermittent failures.
"""
targets = [device_path]
# /dev/sda → sda; check if there are partitions
if device_path.startswith("/dev/"):
dev_name = device_path.rsplit("/", 1)[-1]
parts = _list_partitions(dev_name)
for p in parts:
if p != device_path and p not in targets:
targets.append(p)
return targets
def _human_size(n):
if n < 1024:
return f"{n} B"
for unit in ("KiB", "MiB", "GiB", "TiB"):
n /= 1024
if n < 1024:
return f"{n:.1f} {unit}"
return f"{n:.1f} PiB"
# ── HTML UI (embedded) ────────────────────────────────────────────────────
HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Alpha Connect — LuxTronic GLT Enabler</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg:#12131a; --surface:#1a1d2e; --card:#0f3460;
--accent:#e94560; --accent2:#5a3fad; --text:#e8eaf0;
--muted:#7a8499; --border:#252d45;
--green:#4ecca3; --yellow:#f5a623; --red:#e94560;
}
body { background:var(--bg); color:var(--text); font-family:'Segoe UI',system-ui,sans-serif; font-size:14px; min-height:100vh; }
header {
background:var(--surface); border-bottom:1px solid var(--border);
padding:14px 24px; display:flex; align-items:center; gap:12px;
position:sticky; top:0; z-index:10;
}
header h1 { font-size:17px; font-weight:600; }
header .subtitle { font-size:12px; color:var(--muted); margin-left:auto; }
.nav-tabs { display:flex; gap:4px; margin-left:20px; }
.nav-tab {
background:transparent; color:var(--muted); border:none; border-bottom:2px solid transparent;
padding:6px 14px; font-size:13px; cursor:pointer; font-family:inherit; border-radius:0;
transition: color .15s, border-color .15s;
}
.nav-tab:hover { color:var(--text); }
.nav-tab.active { color:var(--text); border-bottom-color:var(--accent); }
.status-dot { width:10px; height:10px; border-radius:50%; background:var(--muted); transition:background .3s, box-shadow .3s; }
.status-dot.connected { background:var(--green); box-shadow:0 0 8px var(--green); }
.status-dot.error { background:var(--red); }
#status-text { font-size:12px; color:var(--muted); }
.container { max-width:1140px; margin:0 auto; padding:20px 24px; display:grid; grid-template-columns:1fr 1fr; gap:14px; }
.full-width { grid-column:1/-1; }
.card { background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:20px; }
.card h2 { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.1em; color:var(--muted); margin-bottom:14px; display:flex; align-items:center; gap:8px; }
label { display:block; font-size:12px; color:var(--muted); margin-bottom:4px; margin-top:11px; }
label:first-of-type { margin-top:0; }
input[type="text"], input[type="number"], select, textarea {
width:100%; background:var(--bg); border:1px solid var(--border); border-radius:6px;
color:var(--text); padding:8px 10px; font-size:13px; font-family:inherit; transition:border-color .2s;
}
input:focus, select:focus, textarea:focus { outline:none; border-color:var(--accent2); }
input[readonly] { color:var(--muted); background:#0a0b10; cursor:not-allowed; opacity:0.7; }
.gated { opacity:0.4; pointer-events:none; filter:grayscale(0.5); transition:opacity .25s, filter .25s; }
.gated-unlocked { opacity:1; pointer-events:auto; filter:none; }
.row { display:flex; gap:8px; } .row > * { flex:1; } .row > .narrow { flex:0 0 90px; }
button {
background:var(--accent2); color:white; border:none; border-radius:6px;
padding:8px 14px; font-size:13px; cursor:pointer; font-family:inherit;
transition:opacity .15s, background .15s; white-space:nowrap; font-weight:500;
}
button:hover:not(:disabled) { opacity:.82; }
button.primary { background:var(--accent); }
button.success { background:#2e7d5e; }
button.neutral { background:#2a3a55; }
button:disabled { opacity:.35; cursor:not-allowed; }
.btn-row { display:flex; gap:8px; margin-top:12px; flex-wrap:wrap; }
.mode-grid { display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-bottom:12px; }
.mode-card {
background:var(--bg); border:2px solid var(--border); border-radius:8px;
padding:11px 13px; cursor:pointer; transition:border-color .2s, background .2s; user-select:none;
}
.mode-card.active { border-color:var(--green); background:rgba(78,204,163,.08); }
.mode-card .mnum { font-size:18px; font-weight:700; line-height:1; color:var(--muted); }
.mode-card.active .mnum { color:var(--green); }
.mode-card .mlabel { font-size:13px; font-weight:600; margin-top:4px; }
.mode-card .mdesc { font-size:11px; color:var(--muted); margin-top:2px; }
.toggle-grid { display:grid; grid-template-columns:1fr 1fr; gap:7px; }
.toggle-row {
display:flex; align-items:center; justify-content:space-between;
background:var(--bg); border:1px solid var(--border); border-radius:6px; padding:9px 12px;
}
.toggle-name { font-size:12px; line-height:1.3; }
.toggle-sub { font-size:10px; color:var(--muted); }
.toggle { position:relative; display:inline-block; width:38px; height:21px; flex-shrink:0; }
.toggle input { opacity:0; width:0; height:0; position:absolute; }
.tslider { position:absolute; cursor:pointer; inset:0; background:#2a3a55; border-radius:11px; transition:.25s; }
.tslider:before { content:''; position:absolute; height:15px; width:15px; left:3px; bottom:3px; background:#7a8499; border-radius:50%; transition:.25s; }
.toggle input:checked + .tslider { background:rgba(78,204,163,.25); }
.toggle input:checked + .tslider:before { transform:translateX(17px); background:var(--green); }
#packet-preview, #log {
background:#0a0b10; border:1px solid var(--border); border-radius:6px;
padding:10px 12px; font-family:'Courier New',monospace; font-size:11.5px;
line-height:1.65; white-space:pre-wrap; word-break:break-all;
}
#packet-preview { color:#a08ee0; min-height:2em; }
#log { min-height:90px; max-height:280px; overflow-y:auto; color:var(--text); }
.log-info { color:var(--yellow); }
.log-ok { color:var(--green); }
.log-err { color:var(--red); }
.log-line { padding:2px 0; }
.two-col { display:grid; grid-template-columns:1fr 1fr; gap:16px; }
.sub-label { font-size:12px; color:var(--muted); margin-bottom:6px; }
.note { font-size:11px; color:var(--muted); margin-top:9px; line-height:1.55; }
.chip { display:inline-block; background:rgba(90,63,173,.25); border:1px solid rgba(90,63,173,.4);
border-radius:4px; padding:1px 7px; font-size:10px; font-family:monospace; color:#a08ee0; }
.license-note {
background: rgba(245,166,35,.08); border:1px solid rgba(245,166,35,.35);
border-radius:6px; padding:10px 12px; font-size:12px; color:#f5c95a; line-height:1.55; margin-bottom:12px;
}
.license-note a { color:#f5c95a; text-decoration:underline; }
.license-note code { background:rgba(0,0,0,.25); padding:1px 5px; border-radius:3px; font-size:11px; }
.license-warn {
background: rgba(233,69,96,.08); border:1px solid rgba(233,69,96,.4);
border-radius:6px; padding:10px 12px; font-size:12px; color:#ff8b9a; line-height:1.55;
}
.license-warn code { background:rgba(0,0,0,.25); padding:1px 5px; border-radius:3px; font-size:11px; }
.root-warning {
background: rgba(233,69,96,.15) !important;
border:2px solid var(--red) !important;
display:flex; gap:16px; align-items:flex-start;
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { box-shadow: 0 0 0 0 rgba(233,69,96,.4); }
50% { box-shadow: 0 0 0 8px rgba(233,69,96,0); }
}
.root-warning-icon { font-size:44px; line-height:1; padding-top:4px; }
.root-warning-body { flex:1; }
.root-warning-body h3 { color:var(--red); font-size:18px; margin-bottom:8px; }
.root-warning-body p { color:#ffb3c0; font-size:13px; line-height:1.6; }
.root-warning-body pre {
background: rgba(0,0,0,.35); border:1px solid rgba(255,255,255,.1); border-radius:5px;
padding:10px 12px; margin-top:10px; font-family:'Courier New',monospace; font-size:13px;
color: var(--green); font-weight:600;
}
.root-warning-body code { background:rgba(0,0,0,.35); padding:1px 6px; border-radius:3px; font-size:11px; }
.root-warning-body kbd {
background:rgba(255,255,255,.1); border:1px solid rgba(255,255,255,.2); border-bottom-width:2px;
border-radius:4px; padding:1px 5px; font-family:monospace; font-size:11px;
}
.usb-list { margin-top:10px; }
.usb-item {
background: var(--bg); border:1px solid var(--border); border-radius:6px;
padding:8px 10px; margin-top:6px; font-family:'Courier New',monospace; font-size:12px;
cursor:pointer; transition: border-color .15s;
}
.usb-item:hover { border-color:var(--accent2); }
.usb-item .u-dev { color:var(--accent); font-weight:600; }
.usb-item .u-model { color:var(--text); }
.usb-item .u-size { color:var(--muted); font-size:11px; }
</style>
</head>
<body>
<header>
<div class="status-dot" id="status-dot"></div>
<h1>LuxTronic Toolbox</h1>
<nav class="nav-tabs">
<button class="nav-tab active" id="tab-alpha" onclick="showPage('alpha')">Alpha Connect Tool</button>
<button class="nav-tab" id="tab-license" onclick="showPage('license')">License Manager</button>
</nav>
<span id="status-text">Ready</span>
<span class="subtitle" id="page-subtitle">GLT/BACnet Enable via UDP 4444</span>
</header>
<div id="page-alpha" class="container">
<!-- Target -->
<div class="card">
<h2>Target Device</h2>
<label>Device IP Address</label>
<div class="row">
<input type="text" id="ip" placeholder="192.168.10.50" autocomplete="off">
<input type="number" id="port" value="4444" class="narrow" title="Alpha Connect UDP port">
</div>
<p class="note">The heat pump listens on UDP 4444 (default). Custom port only if <code>WPPORT</code> env var was set.</p>
<div class="btn-row">
<button class="primary" id="btn-connect" onclick="connectToDevice()">Connect & verify</button>
<button class="neutral" onclick="checkModbus()">Check Modbus (502)</button>
<button class="neutral" onclick="checkBacnet()">Check BACnet (47808)</button>
</div>
<p class="note" id="connect-hint" style="margin-top:8px; color:var(--yellow);">
Enter the device IP, then click <b>Connect & verify</b> to enable configuration.
</p>
</div>
<!-- Everything below this point is gated on a successful connect (see JS setGated) -->
<!-- GLT Mode -->
<div class="card gated" data-gated="1">
<h2>GLT Enable Mode <span class="chip">Einst_GLT_aktiviert</span></h2>
<div class="license-note">
<b>⚠ License required.</b> The GLT feature is a paid unlock. Before enabling mode 1 or 2,
write a license to the USB dongle in the
<a href="#" onclick="showPage('license'); return false;"><b>License Manager</b> tab</a>,
then plug the dongle into the heat pump. Reference implementation:
<a href="https://github.com/Jaarden/luxtronic-glt-licensetool" target="_blank" rel="noopener">github.com/Jaarden/luxtronic-glt-licensetool</a>.
</div>
<div class="mode-grid" style="grid-template-columns: 1fr 1fr 1fr;">
<div class="mode-card active" id="mc-0" onclick="selectMode(0)">
<div class="mnum">0</div><div class="mlabel">Disabled</div><div class="mdesc">GLT interface off (default)</div>
</div>
<div class="mode-card" id="mc-1" onclick="selectMode(1)">
<div class="mnum">1</div><div class="mlabel">BACnet UDP</div><div class="mdesc">Port 47808 (0xBAC0) — needs license</div>
</div>
<div class="mode-card" id="mc-2" onclick="selectMode(2)">
<div class="mnum">2</div><div class="mlabel">Modbus TCP</div><div class="mdesc">Port 502 — needs license</div>
</div>
</div>
</div>
<!-- Identity -->
<div class="card gated" data-gated="1" id="bacnet-identity-card">
<h2>Modbus/BACnet Settings <span class="chip" id="mode-hint-chip">applies to selected mode</span></h2>
<div class="row">
<div>
<label>Port</label>
<input type="number" id="bacnet_port" value="47808" readonly onchange="updatePreview()">
</div>
<div>
<label>Device ID</label>
<input type="number" id="device_id" value="50" onchange="updatePreview()">
</div>
</div>
<label>Device Name</label>
<input type="text" id="devicename" value="HackedByJAarden" onchange="updatePreview()">
<label>Vendor Name</label>
<input type="text" id="vendorname" value="JAarden" onchange="updatePreview()">
<div class="row">
<div>
<label>Vendor ID</label>
<input type="number" id="vendor_id" value="123" onchange="updatePreview()">
</div>
<div>
<label>Model Name</label>
<input type="text" id="modelname" value="Alpha Innotec" onchange="updatePreview()">
</div>
</div>
<label>Location</label>
<input type="text" id="location" value="Somewhere" onchange="updatePreview()">
<label>Device Description</label>
<input type="text" id="device_description" value="YourDescription" onchange="updatePreview()">
</div>
<!-- Functions -->
<div class="card gated" data-gated="1">
<h2>GLT Functions <span class="chip">Fkt_*_akt</span></h2>
<div class="toggle-grid">
<div class="toggle-row"><div><div class="toggle-name">AT</div><div class="toggle-sub">Outside temperature</div></div>
<label class="toggle"><input type="checkbox" id="fkt_at" onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">Freigabe</div><div class="toggle-sub">Enable/release</div></div>
<label class="toggle"><input type="checkbox" id="fkt_freigabe" checked onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">Sollwert</div><div class="toggle-sub">Setpoint control</div></div>
<label class="toggle"><input type="checkbox" id="fkt_sollwert" checked onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">Sollwert MK1</div><div class="toggle-sub">Mixer 1 setpoint</div></div>
<label class="toggle"><input type="checkbox" id="fkt_sollwert_mk1" checked onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">Sollwert MK2</div><div class="toggle-sub">Mixer 2 setpoint</div></div>
<label class="toggle"><input type="checkbox" id="fkt_sollwert_mk2" checked onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">Sollwert MK3</div><div class="toggle-sub">Mixer 3 setpoint</div></div>
<label class="toggle"><input type="checkbox" id="fkt_sollwert_mk3" onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">BA Heizen</div><div class="toggle-sub">Heating mode</div></div>
<label class="toggle"><input type="checkbox" id="fkt_ba_heizen" checked onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">BA Brauchwasser</div><div class="toggle-sub">Domestic hot water</div></div>
<label class="toggle"><input type="checkbox" id="fkt_ba_brauchw" checked onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">BA MK1</div><div class="toggle-sub">Mixer 1 mode</div></div>
<label class="toggle"><input type="checkbox" id="fkt_ba_mk1" checked onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">BA MK2</div><div class="toggle-sub">Mixer 2 mode</div></div>
<label class="toggle"><input type="checkbox" id="fkt_ba_mk2" checked onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">BA MK3</div><div class="toggle-sub">Mixer 3 mode</div></div>
<label class="toggle"><input type="checkbox" id="fkt_ba_mk3" onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">BA Kühlung</div><div class="toggle-sub">Cooling mode</div></div>
<label class="toggle"><input type="checkbox" id="fkt_ba_kuehl" checked onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">BA Lüftung</div><div class="toggle-sub">Ventilation mode</div></div>
<label class="toggle"><input type="checkbox" id="fkt_ba_lueftung" onchange="updatePreview()"><span class="tslider"></span></label></div>
<div class="toggle-row"><div><div class="toggle-name">BA Schwimmbad</div><div class="toggle-sub">Pool mode</div></div>
<label class="toggle"><input type="checkbox" id="fkt_ba_schwimmbad" onchange="updatePreview()"><span class="tslider"></span></label></div>
</div>
</div>
<!-- Packet + Send -->
<div class="card full-width gated" data-gated="1">
<h2>UDP Packet — subcmd 5000;47809; writes GLT.conf + calls InitGLT()</h2>
<div class="sub-label" style="display:flex; justify-content:space-between; align-items:center;">
<span>Packet that will be sent to <code id="target-info">device:4444</code>:</span>
<span id="packet-mode-badge" class="chip">auto from form</span>
</div>
<div id="packet-preview"></div>
<textarea id="packet-override" rows="3" style="display:none; margin-top:8px; font-family:'Courier New',monospace; font-size:12px;"></textarea>
<div class="btn-row">
<button class="primary" onclick="send()">Apply Configuration + Enable BACnet</button>
<button class="neutral" onclick="copyPacket()">Copy Packet</button>
<button class="neutral" id="btn-override" onclick="toggleOverride()">Override packet…</button>
<button class="neutral" id="btn-reset-override" onclick="resetOverride()" style="display:none;">Reset to form values</button>
</div>
<p class="note">
On the device, <code>UDP_Handler</code> parses this packet, writes <code>/home/GLT.conf</code>,
then calls <code>InitGLT()</code>. BACnet appears on port 47808 within seconds.
</p>
</div>
<!-- Log -->
<div class="card full-width">
<h2>Send Log</h2>
<div id="log"><span style="color:var(--muted)">Actions and responses appear here…</span></div>
</div>
</div>
<!-- /page-alpha -->
<!-- License Manager page -->
<div id="page-license" class="container" style="display:none;">
<!-- Non-root warning — populated by JS -->
<div id="root-warning" class="card full-width root-warning" style="display:none;">
<div class="root-warning-icon">⛔</div>
<div class="root-warning-body">
<h3>Not running as root!</h3>
<p>
The License Manager needs to read and write raw block devices (e.g. <code>/dev/sdb</code>),
which requires root privileges. Stop this server (<kbd>Ctrl-C</kbd> in the terminal) and restart it with:
</p>
<pre>sudo python3 alpha_connect_web.py</pre>
<p style="margin-top:8px; font-size:11px; opacity:0.85;">
Every license operation on this page will fail with <code>permission denied</code> until you restart as root.
</p>
</div>
</div>
<div class="card full-width">
<h2>License Manager <span class="chip">USB dongle · requires root</span></h2>
<p class="note" style="margin-bottom:12px;">
Ports the C implementation from
<a href="https://github.com/Jaarden/luxtronic-glt-licensetool" target="_blank" rel="noopener" style="color:#a08ee0;">luxtronic-glt-licensetool</a>.
Writes the license block to the LAST 512 bytes of a USB dongle. When plugged into the heat pump,
<code>CDemoappl::onUsbDongle()</code> reads it and calls <code>SetZugangMitDongleEinstellung(true, N)</code>
which raises the access level so <code>InitGLT()</code> starts BACnet/Modbus.
</p>
<div class="license-warn">
<b>⚠ WARNING:</b> writing to a wrong device path will DESTROY DATA on that device.
Double-check the size and model before clicking Create/Decrement. This server must run as root
(<code>sudo python3 alpha_connect_web.py</code>) to access raw block devices.
<br><br>
<b>⚠ UNMOUNT FIRST.</b> If the USB has a filesystem (FAT/exFAT/etc), unmount it before writing —
the filesystem may overwrite the license block near the end of the device, causing intermittent
"invalid checksum" failures. This tool will refuse to write while the device is mounted.
</div>
<div class="two-col" style="margin-top:14px;">
<div>
<div class="sub-label">USB dongle device path</div>
<div class="row">
<input type="text" id="lic-device" placeholder="/dev/sdX">
<button class="neutral" onclick="listDevices()" style="flex:0 0 auto;">Scan USB</button>
</div>
<div id="usb-candidates" class="usb-list"></div>
</div>
<div>
<div class="sub-label">Operations</div>
<div class="btn-row">
<button class="neutral" onclick="licCheck()">Check current licenses</button>
</div>
<label style="margin-top:14px;">Create license count</label>
<div class="row">
<input type="number" id="lic-count" value="10" min="1" max="65535">
<button class="primary" onclick="licCreate()" style="flex:0 0 auto;">Create</button>
</div>
<label style="margin-top:14px;">Decrement</label>
<div class="btn-row">
<button class="neutral" onclick="licDecrement()">Decrement by 1</button>
</div>
</div>
</div>
<div id="lic-log" style="background:#0a0b10; border:1px solid var(--border); border-radius:6px;
padding:10px 12px; font-family:'Courier New',monospace; font-size:11.5px; line-height:1.65;
min-height:60px; max-height:280px; overflow-y:auto; margin-top:14px;">
<span style="color:var(--muted)">License operations output appears here…</span>
</div>
</div>
</div>
<!-- /page-license -->
<script>
'use strict';
// ── Page navigation ─────────────────────────────────────────────────────
let rootChecked = false;
async function checkRoot() {
try {
const r = await fetch('/whoami');
const j = await r.json();
const warn = document.getElementById('root-warning');
if (j.is_root) {
warn.style.display = 'none';
} else {
warn.style.display = '';
// Scroll the warning into view
warn.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
} catch(e) {
console.warn('root check failed', e);
}
rootChecked = true;
}
function showPage(name) {
document.getElementById('page-alpha').style.display = (name === 'alpha') ? '' : 'none';
document.getElementById('page-license').style.display = (name === 'license') ? '' : 'none';
document.getElementById('tab-alpha').classList.toggle('active', name === 'alpha');
document.getElementById('tab-license').classList.toggle('active', name === 'license');
const subtitle = document.getElementById('page-subtitle');
subtitle.textContent = (name === 'license')
? 'USB dongle license writer'
: 'GLT/BACnet Enable via UDP 4444';
// Check root status every time the license page is shown
if (name === 'license') checkRoot();
// Remember choice
try { localStorage.setItem('lux-page', name); } catch(e) {}
}
let selectedMode = 0; // 0 = Disabled by default; needs license (see luxtronic-glt-licensetool) before enabling
function selectMode(n) {
selectedMode = n;
[0,1,2].forEach(i => document.getElementById('mc-'+i).classList.toggle('active', i === n));
// Swap the (read-only) port and mode hint based on which protocol is active.
// 1 = BACnet UDP → port 47808
// 2 = Modbus TCP → port 502
// 0 = Disabled → keep 47808 as harmless default
const portInput = document.getElementById('bacnet_port');
const chip = document.getElementById('mode-hint-chip');
if (n === 2) {
portInput.value = 502;
chip.textContent = 'Modbus mode — port 502';
} else if (n === 1) {
portInput.value = 47808;
chip.textContent = 'BACnet mode — port 47808';
} else {
portInput.value = 47808;
chip.textContent = 'GLT disabled — identity ignored';
}
updatePreview();
}
function gv(id) { return document.getElementById(id).value; }
function gc(id) { return document.getElementById(id).checked ? 1 : 0; }
function collectConfig() {
return {
mode: selectedMode,
bacnet_port: parseInt(gv('bacnet_port')) || 47808,
fkt_at: gc('fkt_at'),
fkt_freigabe: gc('fkt_freigabe'),
fkt_sollwert: gc('fkt_sollwert'),
fkt_sollwert_mk1: gc('fkt_sollwert_mk1'),
fkt_sollwert_mk2: gc('fkt_sollwert_mk2'),
fkt_sollwert_mk3: gc('fkt_sollwert_mk3'),
fkt_ba_heizen: gc('fkt_ba_heizen'),
fkt_ba_brauchw: gc('fkt_ba_brauchw'),
fkt_ba_mk1: gc('fkt_ba_mk1'),
fkt_ba_mk2: gc('fkt_ba_mk2'),
fkt_ba_mk3: gc('fkt_ba_mk3'),
fkt_ba_kuehl: gc('fkt_ba_kuehl'),
fkt_ba_lueftung: gc('fkt_ba_lueftung'),
fkt_ba_schwimmbad: gc('fkt_ba_schwimmbad'),
vendorname: gv('vendorname'),
vendor_id: parseInt(gv('vendor_id')) || 123,
modelname: gv('modelname'),
location: gv('location'),
device_description: gv('device_description'),
device_id: parseInt(gv('device_id')) || 50,
devicename: gv('devicename'),
};
}
function buildPacketString(cfg) {
const fields = [
"5000", "47809",
String(cfg.mode),
String(cfg.bacnet_port),
"0",
cfg.fkt_at, cfg.fkt_freigabe, cfg.fkt_sollwert,
cfg.fkt_sollwert_mk1, cfg.fkt_sollwert_mk2, cfg.fkt_sollwert_mk3,
cfg.fkt_ba_heizen, cfg.fkt_ba_brauchw,
cfg.fkt_ba_mk1, cfg.fkt_ba_mk2, cfg.fkt_ba_mk3,
cfg.fkt_ba_kuehl, cfg.fkt_ba_lueftung, cfg.fkt_ba_schwimmbad,
cfg.vendorname, String(cfg.vendor_id),
cfg.modelname, cfg.location, cfg.device_description,
String(cfg.device_id), cfg.devicename,
];
return fields.join(';') + ';';
}
let packetOverride = false; // true when user has manually edited the packet
function updatePreview() {
const cfg = collectConfig();
const packet = buildPacketString(cfg);
if (!packetOverride) {
document.getElementById('packet-preview').textContent = packet;
}
const ip = gv('ip') || '<device>';
const port = gv('port') || '4444';
document.getElementById('target-info').textContent = ip + ':' + port;
}
function currentPacket() {
return packetOverride
? document.getElementById('packet-override').value
: document.getElementById('packet-preview').textContent;
}
function toggleOverride() {
const preview = document.getElementById('packet-preview');
const ta = document.getElementById('packet-override');
const badge = document.getElementById('packet-mode-badge');
const btnReset = document.getElementById('btn-reset-override');
const btnOverride = document.getElementById('btn-override');
if (!packetOverride) {
// Enter override mode: copy current preview text into the textarea
ta.value = preview.textContent;
preview.style.display = 'none';
ta.style.display = 'block';
ta.focus();
packetOverride = true;
badge.textContent = 'MANUAL OVERRIDE';
badge.style.background = 'rgba(233,69,96,.2)';
badge.style.borderColor = 'rgba(233,69,96,.5)';
badge.style.color = '#ff8b9a';
btnReset.style.display = '';
btnOverride.textContent = 'Cancel override';
} else {
// Exit override mode: revert to auto-generated
resetOverride();
}
}
function resetOverride() {
const preview = document.getElementById('packet-preview');
const ta = document.getElementById('packet-override');
const badge = document.getElementById('packet-mode-badge');
const btnReset = document.getElementById('btn-reset-override');
const btnOverride = document.getElementById('btn-override');
packetOverride = false;
preview.style.display = '';
ta.style.display = 'none';
badge.textContent = 'auto from form';
badge.style.background = '';
badge.style.borderColor = '';