-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscreen.py
More file actions
1123 lines (1039 loc) · 43.6 KB
/
Copy pathscreen.py
File metadata and controls
1123 lines (1039 loc) · 43.6 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
# AtomMan unlock + retries + (optional) colored dashboard + multi-vendor GPU + smart NIC picker
# ENQ (dev→host): AA 05 <SEQ_ASCII> CC 33 C3 3C
# REPLY (host→dev): AA <TileID> 00 <SEQ_ASCII> {ASCII payload} CC 33 C3 3C
#
# DATE tile payload is ALWAYS full:
# With internet/API OK:
# {Date:YYYY/MM/DD;Time:HH:MM:SS;Week:N;Weather:X;TemprLo:L,TemprHi:H,Zone:Z,Desc:D}
# Without internet / missing API key / API fail:
# {Date:YYYY/MM/DD;Time:HH:MM:SS;Week:N;Weather:;TemprLo:,TemprHi:,Zone:,Desc:}
#
# Weather:N is mapped from OpenWeather condition id/icon.
import os, sys, time, subprocess, re, glob, argparse, json, socket, signal, urllib.parse, urllib.request
import serial
# ===================== User Weather Settings (HARD-CODED) =====================
# Leave OW_API_KEY empty to behave as "no internet": blanks + one-time console note.
OW_API_KEY = "" # e.g. "abcdef123456..."
OW_LOCATION = "denver,us" # city | "zip,country" (e.g. "80014,us") | "lat,lon" (e.g. "39.7392,-104.9903")
OW_UNITS = "metric" # "metric" (°C) or "imperial" (°F)
OW_LANG = "en" # language for Desc
# Cache refresh cadence (seconds). Env override: ATOMMAN_WEATHER_REFRESH
WEATHER_REFRESH_SECONDS = int(os.getenv("ATOMMAN_WEATHER_REFRESH", "600"))
# ==============================================================================
# -------- Config (env overrides) --------
PORT = os.getenv("ATOMMAN_PORT", "/dev/serial/by-id/usb-Synwit_USB_Virtual_COM-if00")
BAUD = int(os.getenv("ATOMMAN_BAUD", "115200"))
RTSCTS = os.getenv("ATOMMAN_RTSCTS", "false").lower() in ("1","true","yes","on")
DSRDTR = os.getenv("ATOMMAN_DSRDTR", "true").lower() in ("1","true","yes","on")
TRAILER = b"\xCC\x33\xC3\x3C"
DEFAULT_WAIT_START = float(os.getenv("ATOMMAN_WAIT_START", "3.0"))
UNLOCK_WINDOW = float(os.getenv("ATOMMAN_UNLOCK_SECONDS", "5.0"))
POST_WRITE_SLEEP = float(os.getenv("ATOMMAN_WRITE_SLEEP", "0.006"))
# Fan controls default via env, can be overridden by CLI
# Note: NVIDIA only reports fan speed as percentage (0-100%). We estimate RPM as:
# RPM = percentage × max_rpm / 100
# Default 2000 RPM is typical for modern GPUs. Adjust --fan-max-rpm for your card.
# hwmon sensors (if available) report actual RPM directly.
ENV_FAN_PREFER = os.getenv("ATOMMAN_FAN_PREFER", "auto").lower() # auto|hwmon|nvidia
ENV_FAN_MAX_RPM = int(os.getenv("ATOMMAN_FAN_MAX_RPM", "2000"))
# -------- ANSI colors (dashboard only) --------
class C:
R="\033[31m"; G="\033[32m"; Y="\033[33m"; B="\033[34m"; M="\033[35m"; C_="\033[36m"; W="\033[37m"
BR="\033[91m"; BG="\033[92m"; BY="\033[93m"; BB="\033[94m"; BM="\033[95m"; BC="\033[96m"; BW="\033[97m"
DIM="\033[2m"; RESET="\033[0m"
NOCOLOR = False
def colorize(txt, color):
if NOCOLOR: return txt
return f"{color}{txt}{C.RESET}"
def temp_color(t):
try: t = float(t)
except: return lambda s: s
if t < 60: return lambda s: colorize(s, C.BG)
if t < 80: return lambda s: colorize(s, C.BY)
return lambda s: colorize(s, C.BR)
def util_color(pct):
try: pct=float(pct)
except: return lambda s: s
if pct < 40: return lambda s: colorize(s, C.BG)
if pct < 80: return lambda s: colorize(s, C.BY)
return lambda s: colorize(s, C.BR)
def usage_color(pct): # disk/mem usage
try: pct=float(pct)
except: return lambda s: s
if pct < 70: return lambda s: colorize(s, C.BG)
if pct < 90: return lambda s: colorize(s, C.BY)
return lambda s: colorize(s, C.BR)
# -------- Utilities --------
def _run(cmd, timeout=0.7):
try:
return subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL, timeout=timeout)
except Exception:
return ""
def _read(path: str) -> str:
try:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
return f.read()
except Exception:
return ""
# -------- CPU --------
_cpu_model_cache = None
def cpu_model() -> str:
global _cpu_model_cache
if _cpu_model_cache is not None:
return _cpu_model_cache
for ln in _read("/proc/cpuinfo").splitlines():
if ln.startswith("model name"):
_cpu_model_cache = ln.split(":",1)[1].strip()
return _cpu_model_cache
_cpu_model_cache = "Linux CPU"
return _cpu_model_cache
# CPU usage cache: sample once per tile cycle, reuse for payload + dashboard
_cpu_cache = {"usage": 0, "idle": 0, "total": 0, "ts": 0.0}
def cpu_usage_pct() -> int:
"""Return cached CPU usage if fresh (< 0.5s), else sample and cache."""
now = time.time()
if now - _cpu_cache["ts"] < 0.5:
return _cpu_cache["usage"]
# Take a snapshot
parts = _read("/proc/stat").splitlines()[0].split()[1:]
n = list(map(int, parts))
idle = n[3] + n[4]
total = sum(n)
# Calculate delta from previous snapshot
di = idle - _cpu_cache["idle"]
dt = total - _cpu_cache["total"]
if dt > 0 and _cpu_cache["ts"] > 0:
usage = max(0, min(100, int(round(100 * (1 - (di / float(dt)))))))
else:
usage = 0
# Update cache
_cpu_cache["idle"] = idle
_cpu_cache["total"] = total
_cpu_cache["usage"] = usage
_cpu_cache["ts"] = now
return usage
def cpu_freq_khz() -> int:
"""Return max frequency across all cores (handles hybrid P/E-core CPUs)."""
max_freq = 0
# Try reading from all cores via sysfs
for cpu_dir in glob.glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq"):
for suffix in ("scaling_cur_freq", "cpuinfo_cur_freq"):
p = os.path.join(cpu_dir, suffix)
s = _read(p).strip()
if s.isdigit():
max_freq = max(max_freq, int(s))
break
if max_freq > 0:
return max_freq
# Fallback: read from /proc/cpuinfo (also aggregates all cores)
for ln in _read("/proc/cpuinfo").splitlines():
if ln.startswith("cpu MHz"):
try:
mhz = float(ln.split(":", 1)[1].strip())
max_freq = max(max_freq, int(mhz * 1000))
except (ValueError, IndexError):
pass
if max_freq > 0:
return max_freq
# Last resort: lscpu
out = _run(["lscpu"])
m = re.search(r"CPU MHz:\s*([\d.]+)", out)
return int(float(m.group(1)) * 1000) if m else 0
_cpu_temp_path: str | None = None
def _find_cpu_temp_path() -> str:
for hw in glob.glob("/sys/class/hwmon/hwmon*"):
name = _read(os.path.join(hw, "name")).strip().lower()
if name in ("coretemp", "k10temp", "zenpower", "cpu_thermal", "acpitz"):
for n in range(8):
p = os.path.join(hw, f"temp{n}_input")
if _read(p).strip().isdigit():
return p
for hw in glob.glob("/sys/class/hwmon/hwmon*"):
for n in range(8):
label = _read(os.path.join(hw, f"temp{n}_label")).strip().lower()
if any(k in label for k in ("package", "tctl", "tdie", "cpu", "core 0")):
p = os.path.join(hw, f"temp{n}_input")
if _read(p).strip().isdigit():
return p
for hw in glob.glob("/sys/class/hwmon/hwmon*"):
for n in range(8):
p = os.path.join(hw, f"temp{n}_input")
if _read(p).strip().isdigit():
return p
return ""
def cpu_temp_c() -> int:
global _cpu_temp_path
if _cpu_temp_path is None:
_cpu_temp_path = _find_cpu_temp_path()
if not _cpu_temp_path:
return 0
s = _read(_cpu_temp_path).strip()
if not s.isdigit():
return 0
v = int(s)
return v // 1000 if v > 1000 else v
# -------- FAN (RPM) with caching + smoothing --------
class FanCache:
"""Caches fan readings to avoid repeated syscalls/subprocess spawns."""
def __init__(self, cache_ttl: float = 2.0, smooth_window: int = 5):
self.cache_ttl = cache_ttl
self.smooth_window = smooth_window
# Cached hwmon path (None = not yet discovered, "" = no hwmon fans)
self._hwmon_path: str | None = None
# pynvml handle (None = not initialized, False = unavailable)
self._nvml_handle = None
self._nvml_checked = False
# Cached values
self._cached_rpm: int | None = None
self._cached_time: float = 0.0
self._cached_source: str = ""
# Smoothing buffer (rolling average)
self._history: list[int] = []
def _discover_hwmon_fan(self) -> str:
"""Find first working hwmon fan path, cache it."""
for hm in glob.glob("/sys/class/hwmon/hwmon*"):
for fan in glob.glob(os.path.join(hm, "fan*_input")):
s = _read(fan).strip()
if s.isdigit() and int(s) > 0:
return fan
return "" # No fans found
def _read_hwmon(self) -> int | None:
"""Read from cached hwmon path."""
if self._hwmon_path is None:
self._hwmon_path = self._discover_hwmon_fan()
if not self._hwmon_path:
return None
s = _read(self._hwmon_path).strip()
if s.isdigit():
v = int(s)
return v if v > 0 else None
return None
def _init_nvml(self) -> bool:
"""Try to initialize pynvml (much faster than nvidia-smi)."""
if self._nvml_checked:
return self._nvml_handle is not None
self._nvml_checked = True
try:
import pynvml
pynvml.nvmlInit()
self._nvml_handle = pynvml.nvmlDeviceGetHandleByIndex(0)
return True
except Exception:
self._nvml_handle = None
return False
def _read_nvml(self) -> int | None:
"""Read fan speed via pynvml (returns percentage)."""
if not self._init_nvml():
return None
try:
import pynvml
percent = pynvml.nvmlDeviceGetFanSpeed(self._nvml_handle)
return percent # Return as percentage, caller converts
except Exception:
return None
def _read_nvidia_smi(self) -> int | None:
"""Fallback: read fan speed via nvidia-smi subprocess (returns percentage)."""
out = _run(["nvidia-smi", "--query-gpu=fan.speed", "--format=csv,noheader,nounits"])
if not out:
return None
try:
line = out.splitlines()[0].strip()
if line:
return int(float(line))
except Exception:
pass
return None
def _read_nvidia(self, max_rpm: int) -> int | None:
"""Read NVIDIA GPU fan, prefer pynvml over nvidia-smi."""
percent = self._read_nvml()
if percent is None:
percent = self._read_nvidia_smi()
if percent is not None:
return int(round((percent / 100.0) * max(1, max_rpm)))
return None
def _smooth(self, rpm: int) -> int:
"""Apply rolling average smoothing."""
self._history.append(rpm)
if len(self._history) > self.smooth_window:
self._history.pop(0)
return int(sum(self._history) / len(self._history))
def get_rpm(self, prefer: str, max_rpm: int) -> int:
"""Get fan RPM with caching and smoothing."""
now = time.time()
# Return cached value if still valid
if self._cached_rpm is not None and (now - self._cached_time) < self.cache_ttl:
return self._cached_rpm
prefer = (prefer or "auto").lower()
rpm: int | None = None
source = ""
if prefer == "hwmon":
rpm = self._read_hwmon()
source = "hwmon"
if rpm is None:
rpm = self._read_nvidia(max_rpm)
source = "nvidia"
elif prefer == "nvidia":
rpm = self._read_nvidia(max_rpm)
source = "nvidia"
if rpm is None:
rpm = self._read_hwmon()
source = "hwmon"
else: # auto
rpm = self._read_hwmon()
source = "hwmon"
if rpm is None:
rpm = self._read_nvidia(max_rpm)
source = "nvidia"
if rpm is None:
rpm = -1
source = "none"
# Apply smoothing (only for valid readings)
if rpm > 0:
rpm = self._smooth(rpm)
# Cache result
self._cached_rpm = rpm
self._cached_time = now
self._cached_source = source
return rpm
# Global fan cache instance
_fan_cache = FanCache(cache_ttl=2.0, smooth_window=5)
def fan_rpm(prefer: str, max_rpm: int) -> int:
"""Get fan RPM (cached, smoothed). Uses GPU fan if no hwmon fans available."""
return _fan_cache.get_rpm(prefer, max_rpm)
# -------- GPU (NVIDIA/AMD/Intel/fallback) --------
def clean_gpu_name(name: str) -> str:
s = name.strip()
s = re.sub(r"\(R\)|\(TM\)|NVIDIA Corporation|Advanced Micro Devices,? Inc\.?|Intel\(R\)\s*", "", s, flags=re.I)
s = re.sub(r"\s+", " ", s).strip()
return s or "GPU"
_gpu_cache = {"data": None, "ts": 0.0}
def gpu_info():
now = time.time()
if _gpu_cache["data"] is not None and now - _gpu_cache["ts"] < 2.0:
return _gpu_cache["data"]
data = _gpu_info_uncached()
_gpu_cache["data"] = data
_gpu_cache["ts"] = now
return data
def _gpu_info_uncached():
out = _run(["nvidia-smi","--query-gpu=name,temperature.gpu,utilization.gpu","--format=csv,noheader,nounits"])
if out:
try:
name,temp,util=[x.strip() for x in out.splitlines()[0].split(",")]
return clean_gpu_name(name), int(temp), int(util)
except Exception:
pass
out = _run(["rocm-smi","--showtemp","--showuse"])
if out:
tm = re.search(r"(\d+(\.\d+)?)\s*c", out, re.I)
um = re.search(r"(\d+)\s*%", out)
temp = int(float(tm.group(1))) if tm else 0
util = int(um.group(1)) if um else 0
nm = re.search(r"GPU\[\d+\].*?\s(.*?)\s{2,}", out)
name = nm.group(1).strip() if nm else "AMD Radeon"
return clean_gpu_name(name), temp, util
name = ""
for path in ("/sys/class/drm/card0/device/product_name",
"/sys/class/drm/card0/device/name"):
if os.path.exists(path):
name = _read(path).strip(); break
if not name:
pci = _run(["lspci","-mmnn"])
m = re.search(r'VGA compatible controller \[0300\]\s+"([^"]+)"', pci)
if m: name = m.group(1)
temp = 0
for cand in glob.glob("/sys/class/drm/card0/device/hwmon/hwmon*/temp*_input"):
s = _read(cand).strip()
if s.isdigit():
temp = int(s) // 1000
break
if name:
return clean_gpu_name(name), temp, 0
return "GPU", 0, 0
# -------- Memory / Disk --------
def mem_info():
d={}
for ln in _read("/proc/meminfo").splitlines():
parts=ln.replace(":","").split()
if len(parts)>=2 and parts[1].isdigit(): d[parts[0]]=int(parts[1]) # kB
total=d.get("MemTotal",0); avail=d.get("MemAvailable",0); used=max(0,total-avail)
to_gb=lambda kb: round(kb/1024.0/1024.0,1)
usage=int(round(100.0*(used/float(total or 1))))
return (to_gb(used),to_gb(avail),to_gb(total),usage)
def disk_numbers():
st=os.statvfs("/")
tot_b=st.f_frsize*st.f_blocks; avail_b=st.f_frsize*st.f_bavail; used_b=tot_b-avail_b
to_gb=lambda b: int(round(b/1024/1024/1024))
usage=int(round(100.0*(used_b/float(tot_b or 1))))
return (to_gb(used_b), to_gb(tot_b), usage)
_disk_temp_src: tuple[str, str] | None = None # (kind, path_or_dev)
def _find_disk_temp_src() -> tuple[str, str]:
for hwmon in glob.glob("/sys/class/hwmon/hwmon*"):
if _read(os.path.join(hwmon, "name")).strip() == "nvme":
for n in range(4):
p = os.path.join(hwmon, f"temp{n}_input")
if _read(p).strip().isdigit():
return ("sysfs", p)
for nvme in glob.glob("/sys/class/nvme/nvme*"):
for temp_file in ("temp1_input", "hwmon/hwmon*/temp1_input"):
for p in glob.glob(os.path.join(nvme, temp_file)):
if _read(p).strip().isdigit():
return ("sysfs", p)
for hwmon in glob.glob("/sys/class/hwmon/hwmon*"):
if _read(os.path.join(hwmon, "name")).strip() == "drivetemp":
p = os.path.join(hwmon, "temp1_input")
if _read(p).strip().isdigit():
return ("sysfs", p)
if _run(["smartctl", "-A", "/dev/sda"], timeout=2.0):
return ("smartctl", "/dev/sda")
if _run(["hddtemp", "-n", "/dev/sda"], timeout=2.0).strip().isdigit():
return ("hddtemp", "/dev/sda")
return ("none", "")
def disk_temp_c() -> int:
global _disk_temp_src
if _disk_temp_src is None:
_disk_temp_src = _find_disk_temp_src()
kind, target = _disk_temp_src
if kind == "sysfs":
s = _read(target).strip()
if s.isdigit():
v = int(s)
return v // 1000 if v > 1000 else v
elif kind == "smartctl":
out = _run(["smartctl", "-A", target], timeout=2.0)
for line in out.splitlines():
if "Temperature_Celsius" in line or "194 " in line:
for p in line.split():
if p.isdigit() and 10 <= int(p) <= 100:
return int(p)
elif kind == "hddtemp":
out = _run(["hddtemp", "-n", target], timeout=2.0).strip()
if out.isdigit():
return int(out)
return 0
# ---- RAM & Disk vendor (cached) ----
_cache={"ram":("",0.0),"disk":("",0.0)}
def _cache_get(k,ttl=3600):
v,t=_cache.get(k,("",0.0)); return v if v and time.time()-t<ttl else None
def _cache_set(k,v): _cache[k]=(v,time.time())
def ram_label():
cached=_cache_get("ram")
if cached is not None: return cached
manu=""
out = _run(["dmidecode","-t","memory"]) or _run(["sudo","-n","dmidecode","-t","memory"])
if out:
m=re.search(r"^\s*Manufacturer:\s*(.+)$",out,re.MULTILINE|re.IGNORECASE)
if m:
manu=m.group(1).strip()
if manu in ("Undefined","Not Specified","Unknown","To Be Filled By O.E.M."): manu=""
if not manu:
out=_run(["lshw","-class","memory"])
if out:
m=re.search(r"^\s*manufacturer:\s*(.+)$",out,re.MULTILINE|re.IGNORECASE)
if m: manu=m.group(1).strip()
manu=(manu.replace("Micron Technology","Micron")
.replace("Samsung Electronics","Samsung")
.replace("HYNIX","SK hynix")
.replace("Hynix","SK hynix")).strip()
_cache_set("ram",manu); return manu
def disk_label():
cached=_cache_get("disk")
if cached is not None: return cached
label=""
try:
for n in sorted(glob.glob("/sys/class/nvme/nvme*")):
model=_read(os.path.join(n,"model")).strip()
if model: label=model; break
except Exception: pass
if not label:
try:
out=_run(["lsblk","-dno","NAME,MODEL,VENDOR"])
root_dev=""
try:
src=_run(["findmnt","-nro","SOURCE","/"]).strip()
root_dev=os.path.basename(re.sub(r"p?\d+$","",src.replace("/dev/","")))
except Exception: pass
pick=None
for ln in out.splitlines():
parts=ln.split(None,2)
if not parts: continue
name=parts[0]; rest=parts[1:] if len(parts)>1 else []
if root_dev and name==root_dev: pick=rest; break
if not root_dev and pick is None: pick=rest
if pick: label=" ".join(pick).strip()
except Exception: pass
label=re.sub(r"\s+"," ",label).strip()
_cache_set("disk",label); return label
# ---------- Network (active iface picker, prefer LAN) ----------
def _sh(cmd, timeout=0.6):
try: return subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL, timeout=timeout).strip()
except Exception: return ""
def _is_wireless(iface: str) -> bool:
return os.path.isdir(f"/sys/class/net/{iface}/wireless")
def _iface_info(iface: str) -> dict:
info = {"name": iface, "up": False, "carrier": False, "wireless": _is_wireless(iface)}
try:
with open(f"/sys/class/net/{iface}/operstate") as f:
info["up"] = (f.read().strip() == "up")
except Exception:
pass
try:
with open(f"/sys/class/net/{iface}/carrier") as f:
info["carrier"] = (f.read().strip() == "1")
except Exception:
pass
return info
def _default_route_ifaces() -> list:
out = _sh(["ip", "-o", "route", "show", "default"])
devs = []
for line in out.splitlines():
m = re.search(r"\bdev\s+([^\s]+)", line)
if m: devs.append(m.group(1))
return list(dict.fromkeys(devs))
def _list_candidate_ifaces() -> list:
try:
return [i for i in sorted(os.listdir("/sys/class/net")) if i != "lo"]
except Exception:
return []
def _pick_iface(preferred: str | None = None) -> str | None:
if preferred: # env override
return preferred
defaults = _default_route_ifaces()
ranked = []
for i in defaults:
inf = _iface_info(i)
score = (2 if (inf["up"] and inf["carrier"]) else 1 if inf["up"] else 0) + (1 if not inf["wireless"] else 0)
ranked.append((score, not inf["wireless"], inf["name"]))
ranked.sort(reverse=True)
for score, _wired, name in ranked:
if score > 0: return name
cands=[]
for i in _list_candidate_ifaces():
inf = _iface_info(i)
score = (2 if (inf["up"] and inf["carrier"]) else 1 if inf["up"] else 0) + (1 if not inf["wireless"] else 0)
cands.append((score, not inf["wireless"], inf["name"]))
cands.sort(reverse=True)
for score, _wired, name in cands:
if score > 0: return name
pool=_list_candidate_ifaces()
return pool[0] if pool else None
def _read_netdev():
try:
with open("/proc/net/dev","r") as f:
return f.read().splitlines()
except Exception:
return []
def _parse_netdev(lines, iface):
for ln in lines:
if ":" not in ln: continue
name, rest = ln.split(":", 1)
if name.strip() == iface:
cols = rest.split()
if len(cols) >= 16:
rx = int(cols[0]); tx = int(cols[8])
return rx, tx
return None, None
class NetMeter:
def __init__(self):
env = os.getenv("ATOMMAN_NET_IFACE", "").strip() or None
self.iface = _pick_iface(env)
self.rx0 = self.tx0 = None
self.t0 = None
self._prime()
def _prime(self):
if not self.iface: return
lines = _read_netdev()
rx, tx = _parse_netdev(lines, self.iface)
if rx is None:
self.iface = _pick_iface()
if not self.iface: return
lines = _read_netdev()
rx, tx = _parse_netdev(lines, self.iface)
if rx is not None:
self.rx0, self.tx0, self.t0 = rx, tx, time.time()
def maybe_repick(self):
if not self.iface:
self.iface = _pick_iface(); self._prime(); return
inf = _iface_info(self.iface)
if not inf["up"] or (inf["wireless"] and not inf["carrier"]):
new = _pick_iface()
if new and new != self.iface:
self.iface = new
self._prime()
def rates_ks(self):
self.maybe_repick()
if not self.iface:
return None, None
lines = _read_netdev()
rx1, tx1 = _parse_netdev(lines, self.iface)
if rx1 is None or self.rx0 is None:
self._prime(); return None, None
t1 = time.time(); dt = max(1e-3, t1 - self.t0)
rxk = (rx1 - self.rx0) / dt / 1024.0
txk = (tx1 - self.tx0) / dt / 1024.0
self.rx0, self.tx0, self.t0 = rx1, tx1, t1
rxk = max(0.0, rxk); txk = max(0.0, txk)
return rxk, txk
_nm = NetMeter()
_last_net = {"rxk": None, "txk": None, "rpm": None}
# -------- Helpers --------
def _fmt_rate(rate_kbs: float) -> str:
if rate_kbs is None:
return "N/A"
if rate_kbs < 1024.0:
return f"{rate_kbs:.1f} K/s"
mbps = rate_kbs / 1024.0
if mbps < 1024.0:
return f"{mbps:.1f} M/s"
gbps = mbps / 1024.0
return f"{gbps:.1f} G/s"
# ===================== OpenWeather integration (cached) =====================
# Weather cache: refresh at most every WEATHER_REFRESH_SECONDS
_weather_cache = {
"ts": 0.0, # last successful fetch time
"data": None, # dict or None
"warned_no_key": False,
}
def _internet_ok(host="8.8.8.8", port=53, timeout=1.5) -> bool:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); sock.settimeout(timeout)
sock.connect((host, port)); sock.close()
return True
except Exception:
return False
def _http_get_json(url: str, timeout: float = 7.0) -> dict:
req = urllib.request.Request(url, headers={"User-Agent": "AtomMan-Echo/1.0"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8", errors="replace"))
def _parse_location_ow(loc: str, key: str):
"""Return (lat, lon, zone) or None."""
s = (loc or "").strip()
if not s:
return None
# Lat,lon
if "," in s:
a, b = [x.strip() for x in s.split(",", 1)]
try:
la, lo = float(a), float(b)
return la, lo, f"{la:.4f},{lo:.4f}"
except ValueError:
pass
# ZIP (requires country with OWM zip endpoint)
if s.replace("-", "").replace(" ", "").isdigit() or ("," in s and s.split(",")[0].strip().isdigit()):
if "," in s:
q = urllib.parse.quote(s)
try:
j = _http_get_json(f"https://api.openweathermap.org/geo/1.0/zip?zip={q}&appid={key}")
return float(j["lat"]), float(j["lon"]), f'{j.get("name","ZIP")}'
except Exception:
pass
# City,Country
q = urllib.parse.quote(s)
j = _http_get_json(f"https://api.openweathermap.org/geo/1.0/direct?q={q}&limit=1&appid={key}")
if isinstance(j, list) and j:
ent = j[0]
name = ent.get("name") or s
cc = ent.get("country") or ""
st = ent.get("state")
zone = name if not cc else f"{name},{cc}"
if st and st not in zone:
zone = f"{name}, {st}, {cc}" if cc else f"{name}, {st}"
return float(ent["lat"]), float(ent["lon"]), zone
return None
def _map_openweather_id_to_weatherN(ow_id: int, icon: str) -> int:
day = icon.endswith("d") if icon else True
if ow_id == 800:
return 1 if day else 3 # clear day/night
if ow_id == 801:
return 5 if day else 6 # few clouds
if ow_id == 802:
return 7 if day else 8 # scattered/mostly cloudy
if ow_id in (803, 804):
return 9 # overcast
g = ow_id // 100
if g == 2: # thunderstorm
if ow_id in (202, 212, 232): return 16 # storm (strong)
return 11 # thundershower
if g == 3: return 13 # drizzle → light rain
if g == 5:
if ow_id == 511: return 19 # freezing rain
if ow_id in (520,521,522,531): return 10 # showers
if ow_id in (500,501): return 13 if ow_id==500 else 14
if ow_id in (502,503,504): return 15 # heavy rain
return 14
if g == 6:
if ow_id in (611,612,615,616): return 20 # sleet / wintry mix
if ow_id == 600: return 22 # light snow
if ow_id == 601: return 23 # moderate snow
if ow_id in (602,621,622): return 24 # heavy/snow showers
if ow_id == 620: return 21 # flurry
return 22
if g == 7:
if ow_id in (701,741): return 30 # mist/fog
if ow_id in (711,721): return 31 # smoke/haze
if ow_id in (731,751): return 27 # sand
if ow_id in (761,762): return 26 # dust/ash
if ow_id == 771: return 33 # squalls/blustery
if ow_id == 781: return 36 # tornado
return 31
return 99
def _fetch_openweather(lat: float, lon: float, key: str) -> dict:
qs = urllib.parse.urlencode({
"lat": f"{lat:.6f}",
"lon": f"{lon:.6f}",
"units": OW_UNITS,
"lang": OW_LANG,
"exclude": "minutely,hourly,alerts",
"appid": key,
})
return _http_get_json(f"https://api.openweathermap.org/data/3.0/onecall?{qs}")
def _weather_fetch_now() -> dict | None:
"""Return dict {weatherN, lo, hi, zone, desc} or None on any failure/disabled."""
key = (OW_API_KEY or "").strip()
if not key:
if not _weather_cache["warned_no_key"]:
print("[Weather] No OpenWeather API key set — DATE payload will carry blank weather fields.")
_weather_cache["warned_no_key"] = True
return None
if not _internet_ok():
return None
try:
loc = _parse_location_ow(OW_LOCATION, key)
if not loc:
return None
lat, lon, zone = loc
j = _fetch_openweather(lat, lon, key)
if not j or "current" not in j or "daily" not in j or not j["daily"]:
return None
cur = j["current"]; d0 = j["daily"][0]
w = cur.get("weather", [{}])[0]
owid = int(w.get("id", 0) or 0)
icon = str(w.get("icon", "") or "")
desc = str(w.get("description", "") or "")
weatherN = _map_openweather_id_to_weatherN(owid, icon)
temps = d0.get("temp", {})
lo = int(round(float(temps.get("min", cur.get("temp", 0)))))
hi = int(round(float(temps.get("max", cur.get("temp", 0)))))
zone_ascii = re.sub(r"[^\x20-\x7E]", "?", zone).replace(";", ",")
desc_ascii = re.sub(r"[^\x20-\x7E]", "?", desc).replace(";", ",")
return {"weatherN": weatherN, "lo": lo, "hi": hi, "zone": zone_ascii, "desc": desc_ascii}
except Exception:
return None
def get_weather_cached() -> dict | None:
"""Return cached weather or refresh if stale. Respects WEATHER_REFRESH_SECONDS."""
now = time.time()
if _weather_cache["data"] is not None and (now - _weather_cache["ts"] < WEATHER_REFRESH_SECONDS):
return _weather_cache["data"]
data = _weather_fetch_now()
# Cache the (possibly None) result to avoid spamming on repeated failures
_weather_cache["data"] = data
_weather_cache["ts"] = now
return data
# =================== End OpenWeather integration ===================
# -------- Tile payload generators --------
def _week_num_from_localtime(t):
# Python: Monday=0..Sunday=6 → panel wants Sunday=0..Saturday=6
return (t.tm_wday + 1) % 7
def p_cpu():
t0=cpu_temp_c()
return f"{{CPU:{cpu_model()};Tempr:{t0};Useage:{cpu_usage_pct()};Freq:{cpu_freq_khz()};Tempr1:{t0};}}"
def p_gpu():
name,temp,util=gpu_info()
return f"{{GPU:{name};Tempr:{temp};Useage:{util}}}"
def p_mem():
used,avail,total,usage=mem_info()
manu=ram_label() or "Memory"
return f"{{Memory:{manu};Used:{used};Available:{avail};Total:{total};Useage:{usage}}}"
def p_dsk():
used,total,usage=disk_numbers()
lab=disk_label() or "Disk"
temp=disk_temp_c()
return f"{{DiskName:{lab};Tempr:{temp};UsageSpace:{used};AllSpace:{total};Usage:{usage}}}"
def p_date():
# ALWAYS full payload; weather fields may be blank
t=time.localtime()
week_num = _week_num_from_localtime(t)
w = get_weather_cached()
if w:
return (
f"{{Date:{t.tm_year:04d}/{t.tm_mon:02d}/{t.tm_mday:02d};"
f"Time:{t.tm_hour:02d}:{t.tm_min:02d}:{t.tm_sec:02d};"
f"Week:{week_num};Weather:{w['weatherN']};"
f"TemprLo:{w['lo']},TemprHi:{w['hi']},"
f"Zone:{w['zone']},Desc:{w['desc']}}}"
)
else:
return (
f"{{Date:{t.tm_year:04d}/{t.tm_mon:02d}/{t.tm_mday:02d};"
f"Time:{t.tm_hour:02d}:{t.tm_min:02d}:{t.tm_sec:02d};"
f"Week:{week_num};Weather:;TemprLo:,TemprHi:,Zone:,Desc:}}"
)
def p_net(fan_prefer: str, fan_max_rpm: int):
rxk, txk = _nm.rates_ks() # sample once per NET tile visit
rpm = fan_rpm(fan_prefer, fan_max_rpm)
# cache for dashboard/update_latest
_last_net["rxk"], _last_net["txk"], _last_net["rpm"] = rxk, txk, rpm
if rxk is None or txk is None:
return f"{{SPEED:{rpm};NETWORK:N/A,N/A}}"
return f"{{SPEED:{rpm};NETWORK:{_fmt_rate(rxk)},{_fmt_rate(txk)}}}"
_last_vol_bat = {"volume": -1, "battery": 177}
def _read_volume() -> int:
out=_run(["pactl","get-sink-volume","@DEFAULT_SINK@"], timeout=0.7)
m=re.search(r"(\d+)%",out)
return int(m.group(1)) if m else -1
def _read_battery() -> int:
try:
for base in os.listdir("/sys/class/power_supply"):
if base.startswith("BAT"):
with open(f"/sys/class/power_supply/{base}/capacity") as f:
return int(f.read().strip())
except Exception: pass
return 177 # sentinel: no battery present (desktop)
def p_vol():
vol = _read_volume()
_last_vol_bat["volume"] = vol
return f"{{VOLUME:{vol}}}"
def p_bat():
pct = _read_battery()
_last_vol_bat["battery"] = pct
return f"{{Battery:{pct}}}"
# Tile IDs & rotations
CPU, GPU, MEM, DSK, DAT, NET, VOL, BAT = 0x53,0x36,0x49,0x4F,0x6B,0x27,0x10,0x1A
UNLOCK_ROT = [(CPU,p_cpu),(GPU,p_gpu),(MEM,p_mem)] # reliable unlock
# -------- Per-tile SEQ mapping (CPU='2') --------
SEQ_FOR = {CPU:'2', GPU:'3', MEM:'4', DSK:'5', DAT:'6', NET:'7', VOL:'9', BAT:'2'}
def seq_for(tile_id: int) -> int:
ch = SEQ_FOR.get(tile_id, '2')
return (ord('<') if ch == '<' else ord(ch))
# -------- Protocol --------
def read_enq(ser):
if ser.read(1)!=b"\xAA": return None
if ser.read(1)!=b"\x05": return None
b3=ser.read(1)
if not b3: return None
if ser.read(4)!=TRAILER: return None
return b3[0] # ASCII during BOOT; tile_id during NORMAL (panel quirk)
def build_reply(id_byte:int, seq_ascii:int, txt:str)->bytes:
return bytes([0xAA,id_byte,0x00,seq_ascii]) + txt.encode("latin-1","ignore") + TRAILER
def open_serial(wait_start: float):
time.sleep(wait_start) # allow USB CDC / drivers / fans to come up
s=serial.Serial(PORT,BAUD,timeout=1.0,write_timeout=1.0,dsrdtr=DSRDTR,rtscts=RTSCTS)
try:
s.reset_input_buffer(); s.reset_output_buffer()
except Exception: pass
return s
# -------- Dashboard (optional) --------
def render_dashboard(latest):
sys.stdout.write("\033[2J\033[H") # clear + home
t=time.strftime("%Y-%m-%d %H:%M:%S")
print(f"{colorize('AtomMan — Active', C.BW)} Time: {colorize(t, C.BC)}")
print("-"*72)
tc = temp_color(latest.get('cpu_temp','?'))
uc = util_color(latest.get('cpu_usage','?'))
print(f"Processor type : {latest.get('cpu_model','')}")
print(f"Processor temp : {tc(str(latest.get('cpu_temp','?')) + ' °C')}")
print(f"CPU usage : {uc(str(latest.get('cpu_usage','?')) + ' %')}")
print(f"CPU freq : {str(latest.get('cpu_freq_khz','?'))} kHz")
print()
gname = latest.get('gpu_name','N/A')
gtc = temp_color(latest.get('gpu_temp','0'))
guc = util_color(latest.get('gpu_util','0'))
print(f"GPU model : {gname}")
print(f"GPU temp : {gtc(str(latest.get('gpu_temp','0')) + ' °C')}")
print(f"GPU usage : {guc(str(latest.get('gpu_util','0')) + ' %')}")
print()
muc = usage_color(latest.get('mem_usage','?'))
print(f"RAM (vendor) : {latest.get('ram_vendor','')}")
print(f"RAM used : {str(latest.get('mem_used','?'))} GB")
print(f"RAM avail : {str(latest.get('mem_avail','?'))} GB")
print(f"RAM total : {str(latest.get('mem_total','?'))} GB")
print(f"RAM usage : {muc(str(latest.get('mem_usage','?')) + ' %')}")
print()
duc = usage_color(latest.get('disk_usage','?'))
dtc = temp_color(latest.get('disk_temp','0'))
print(f"Disk (label) : {latest.get('disk_label','')}")
print(f"Disk temp : {dtc(str(latest.get('disk_temp','0')) + ' °C')}")
print(f"Disk used : {str(latest.get('disk_used','?'))} GB")
print(f"Disk total : {str(latest.get('disk_total','?'))} GB")
print(f"Disk usage : {duc(str(latest.get('disk_usage','?')) + ' %')}")
print()
iface = latest.get('iface', 'N/A')
print(f"Net iface : {iface}")
rx = latest.get('net_rx', None)
tx = latest.get('net_tx', None)
print(f"Net RX,TX : {_fmt_rate(rx)}, {_fmt_rate(tx)}")
print(f"Fan speed : {str(latest.get('fan_rpm','-1'))} r/min")
print(f"Volume : {str(latest.get('volume','-1'))} %")
print(f"Battery : {str(latest.get('battery','177'))} %")
print()
# --- Weather block (from cache) ---
w = get_weather_cached()
if w:
print(colorize("Weather : ONLINE", C.BG))
unit_label = "°C" if OW_UNITS == "metric" else "°F"
print(f" Code : {w['weatherN']} (mapped)")
print(f" Lo/Hi : {w['lo']}/{w['hi']} {unit_label}")
print(f" Zone : {w['zone']}")
print(f" Desc : {w['desc']}")
age = int(time.time() - _weather_cache['ts'])
print(f" Age : {age}s (refresh {WEATHER_REFRESH_SECONDS}s)")
else:
reason = "no API key" if not OW_API_KEY.strip() else "offline/unavailable"
print(colorize(f"Weather : OFFLINE ({reason})", C.BY))
print("-"*72)
sys.stdout.flush()
def update_latest_from_payload(id_byte, latest, fan_prefer, fan_max_rpm):
if id_byte==CPU:
latest.update({
"cpu_model": cpu_model(),
"cpu_temp" : cpu_temp_c(),
"cpu_usage": cpu_usage_pct(),
"cpu_freq_khz" : cpu_freq_khz(),
})
elif id_byte==GPU:
n,t,u=gpu_info()
latest.update({"gpu_name": n, "gpu_temp": t, "gpu_util": u})
elif id_byte==MEM:
used,avail,total,usage=mem_info()
latest.update({
"ram_vendor": ram_label() or "",
"mem_used": used, "mem_avail": avail, "mem_total": total, "mem_usage": usage
})
elif id_byte==DSK:
used,total,usage=disk_numbers()
latest.update({
"disk_label": disk_label() or "Disk",
"disk_temp": disk_temp_c(),
"disk_used": used, "disk_total": total, "disk_usage": usage
})
elif id_byte==NET:
rxk = _last_net.get("rxk")
txk = _last_net.get("txk")
rpm = _last_net.get("rpm")
# Fallback once if cache is empty
if rxk is None or txk is None or rpm is None:
rxk, txk = _nm.rates_ks()
rpm = fan_rpm(fan_prefer, fan_max_rpm)
_last_net["rxk"], _last_net["txk"], _last_net["rpm"] = rxk, txk, rpm
latest.update({
"net_rx": rxk,
"net_tx": txk,
"fan_rpm": rpm,
"iface": _nm.iface or "N/A"
})
elif id_byte==VOL:
latest.update({"volume": _last_vol_bat["volume"]})
elif id_byte==BAT:
latest.update({"battery": _last_vol_bat["battery"]})
elif id_byte==DAT:
# Nudge the weather cache on DATE tile cycles (will only fetch if stale)
get_weather_cached()