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
|
{ pkgs, lib, depot, ... }:
let
sfttime = depot.users.Profpatsch.sfttime;
script = pkgs.writeText "display-infos-script" ''
#!@python3@
import sys
import os
import glob
import json
import socket
import subprocess as sub
import os.path as path
import statistics as st
import jc
from datetime import datetime, timezone
def readint(fn):
with open(fn, 'r') as f:
return int(f.read())
def seconds_to_sft(secs):
p = sub.Popen(["@bc@", "-l"], stdin=sub.PIPE, stdout=sub.PIPE)
(sft, _) = p.communicate(input="scale=2; obase=16; {} / 86400\n".format(secs).encode())
p.terminate()
return str(sft.strip().decode())
def claude_usage():
"""Query the claude-usage varlink service for the current 5-hour session
usage. The service serves a cached snapshot instantly (it refreshes the
backend in the background), so this never blocks on the network.
Returns a dict {percent, reset_secs, reachable} on success, or None when
the service is unreachable / has no data, so the status line degrades
gracefully. 'reachable' is False when the service's last background
refresh failed (network down / claude.ai unreachable) but a cached value
is still available."""
sock_path = "/run/user/{}/de.profpatsch.ClaudeUsage".format(os.getuid())
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(2.0)
s.connect(sock_path)
s.sendall(json.dumps({"method": "de.profpatsch.ClaudeUsage.GetUsage"}).encode() + b"\0")
buf = b""
while not buf.endswith(b"\0"):
chunk = s.recv(65536)
if not chunk:
break
buf += chunk
s.close()
reply = json.loads(buf.rstrip(b"\0"))
except Exception:
return None
if reply.get("error"):
return None
params = reply.get("parameters") or {}
five = params.get("five_hour")
if not five:
return None
resets_at = five["resets_at"].replace("Z", "+00:00")
secs = (datetime.fromisoformat(resets_at) - datetime.now(timezone.utc)).total_seconds()
return {
"percent": int(round(five["utilization"])),
"reset_secs": max(0, secs),
# reachable defaults to True for forward-compat with older services.
"reachable": params.get("reachable", True),
}
def get_5_min_load():
with open('/proc/loadavg', 'r') as f:
return f.read().split(' ')[1]
charging = readint("/sys/class/power_supply/AC/online")
full = 0
now = 0
seconds_remaining = 0
for bat in glob.iglob("/sys/class/power_supply/BAT*"):
full += readint(path.join(bat, "energy_full"))
now += readint(path.join(bat, "energy_now" ))
current_rate = readint(path.join(bat, "power_now"))
if current_rate == 0:
continue
elif charging:
seconds_remaining += 3600 * (full - now) / current_rate
else:
seconds_remaining += 3600 * now / current_rate
bat = round( now/full, 2 )
ac = "⚡ " if charging else ""
sft_remaining = seconds_to_sft(seconds_remaining)
date = sub.run(["date", "+%d.%m. KW%V %a %T"], stdout=sub.PIPE).stdout.strip().decode()
dottime = sub.run(["date", "--utc", "+%H·%M"], stdout=sub.PIPE).stdout.strip().decode()
sftdate = sub.run(["@sfttime@"], stdout=sub.PIPE).stdout.strip().decode()
load = get_5_min_load()
free_mem_gibi = jc.parse('free', sub.check_output(['free', '--gibi'], text=True))[0]['available']
cu = claude_usage()
if cu is None:
claude_segment = ""
else:
# ⚠ marks that the service could not reach claude.ai on its last refresh,
# so the shown numbers are stale.
stale_marker = "" if cu["reachable"] else "⚠"
claude_segment = "Claude: {pct}% {sft}{stale} | ".format(
pct = cu["percent"],
sft = seconds_to_sft(cu["reset_secs"]),
stale = stale_marker,
)
notify = "BAT: {percent}% {ac}{charge}{{{load}, {free_mem_gibi}G}} | {claude_segment}{date} | {sftdate} | {dottime}".format(
percent = int(bat*100),
ac = ac,
charge = "{} ".format(sft_remaining) if seconds_remaining else "",
load = load,
free_mem_gibi = free_mem_gibi,
claude_segment = claude_segment,
date = date,
sftdate = sftdate,
dottime = dottime
)
print(notify)
'';
python = pkgs.python3.withPackages (pp: [ pp.jc ]);
in pkgs.runCommandLocal "display-infos" {
meta.description = "Script to display time & battery";
} ''
substitute ${script} script \
--replace "@python3@" "${lib.getBin python}/bin/python3" \
--replace "@bc@" "${lib.getBin pkgs.bc}/bin/bc" \
--replace "@sfttime@" "${lib.getBin sfttime}/bin/sfttime"
install -D script $out/bin/display-infos
''
|