-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeedtest_runner.py
More file actions
183 lines (155 loc) · 6.32 KB
/
Copy pathspeedtest_runner.py
File metadata and controls
183 lines (155 loc) · 6.32 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
"""
speedtest_runner.py - Periodic bandwidth testing via speedtest-cli
"""
import subprocess
import json
import threading
import time
from datetime import datetime
_thread = None
_stop_event = threading.Event()
def run_once() -> dict | None:
"""Run a single speedtest and return results dict."""
try:
# speedtest-cli installs as "speedtest-cli", not "speedtest"
result = subprocess.run(
["speedtest-cli", "--json"],
capture_output=True, text=True, timeout=120
)
data = json.loads(result.stdout)
return {
"timestamp": datetime.utcnow().isoformat(),
"download_mbps": round(data["download"] / 1_000_000, 2),
"upload_mbps": round(data["upload"] / 1_000_000, 2),
"ping_ms": round(data["ping"], 2),
"server": data.get("server", {}).get("name", ""),
"isp": data.get("client", {}).get("isp", ""),
}
except Exception as e:
print(f"[Speedtest] Failed: {e}")
return None
def run_once_streaming(emit) -> dict | None:
"""Run speedtest using the Python API, streaming live speed via emit(phase, dict).
Phases emitted:
("init", {})
("ping", {"ping_ms": float, "server": str})
("download", {"speed": float}) -- repeated ~every 300ms
("download_done", {"download_mbps": float})
("upload", {"speed": float, "download_mbps": float}) -- repeated ~every 300ms
("complete", {full result dict})
("error", {"message": str})
"""
try:
import speedtest as _st
s = _st.Speedtest()
emit("init", {})
s.get_best_server()
ping = round(s.results.ping, 1)
server = (s.results.server or {}).get("name", "")
emit("ping", {"ping_ms": ping, "server": server})
# ── Download ──────────────────────────────────────────────────────────
# s.results.bytes_received is only written after download() returns, so
# we monkey-patch HTTPDownloader to track running threads and sum their
# live result lists directly.
emit("download", {"speed": 0})
dl_done = threading.Event()
_dl_active = []
_dl_lock = threading.Lock()
_dl_done_bytes = [0]
_OrigDL = _st.HTTPDownloader
class _TrackedDL(_OrigDL):
def run(self):
with _dl_lock:
_dl_active.append(self)
try:
super().run()
finally:
with _dl_lock:
_dl_active.remove(self)
_dl_done_bytes[0] += sum(self.result)
_st.HTTPDownloader = _TrackedDL
def _poll_dl():
start_t = time.perf_counter()
while not dl_done.is_set():
time.sleep(0.1)
with _dl_lock:
cur_b = _dl_done_bytes[0] + sum(sum(t.result) for t in _dl_active)
dt = time.perf_counter() - start_t
if dt >= 0.3 and cur_b > 0:
emit("download", {"speed": round(cur_b * 8 / (dt * 1_000_000), 1)})
t = threading.Thread(target=_poll_dl, daemon=True)
t.start()
dl_bps = s.download()
dl_done.set()
t.join(timeout=1)
_st.HTTPDownloader = _OrigDL
dl_mbps = round(dl_bps / 1_000_000, 2)
emit("download_done", {"download_mbps": dl_mbps})
# ── Upload ────────────────────────────────────────────────────────────
# Same issue: s.results.bytes_sent is only written after upload() returns.
# Track live upload bytes via request.data.total (a list appended per chunk).
emit("upload", {"speed": 0, "download_mbps": dl_mbps})
ul_done = threading.Event()
_ul_active = []
_ul_lock = threading.Lock()
_ul_done_bytes = [0]
_OrigUL = _st.HTTPUploader
class _TrackedUL(_OrigUL):
def run(self):
with _ul_lock:
_ul_active.append(self)
try:
super().run()
finally:
with _ul_lock:
_ul_active.remove(self)
_ul_done_bytes[0] += sum(self.request.data.total)
_st.HTTPUploader = _TrackedUL
def _poll_ul():
start_t = time.perf_counter()
while not ul_done.is_set():
time.sleep(0.1)
with _ul_lock:
cur_b = _ul_done_bytes[0] + sum(sum(t.request.data.total) for t in _ul_active)
dt = time.perf_counter() - start_t
if dt >= 0.3 and cur_b > 0:
emit("upload", {"speed": round(cur_b * 8 / (dt * 1_000_000), 1),
"download_mbps": dl_mbps})
t2 = threading.Thread(target=_poll_ul, daemon=True)
t2.start()
ul_bps = s.upload()
ul_done.set()
t2.join(timeout=1)
_st.HTTPUploader = _OrigUL
ul_mbps = round(ul_bps / 1_000_000, 2)
isp = (s.results.client or {}).get("isp", "")
result = {
"timestamp": datetime.utcnow().isoformat(),
"download_mbps": dl_mbps,
"upload_mbps": ul_mbps,
"ping_ms": ping,
"server": server,
"isp": isp,
}
emit("complete", result)
return result
except Exception as e:
print(f"[Speedtest streaming] Failed: {e}")
emit("error", {"message": str(e)})
return None
def _loop(interval_minutes: int, stop: threading.Event):
while not stop.is_set():
import storage
result = run_once()
if result:
storage.save_speedtest(result)
print(f"[Speedtest] ↓{result['download_mbps']} ↑{result['upload_mbps']} ping:{result['ping_ms']}ms")
stop.wait(interval_minutes * 60)
def start(interval_minutes: int = 60):
global _thread, _stop_event
_stop_event = threading.Event()
_thread = threading.Thread(target=_loop, args=(interval_minutes, _stop_event), daemon=True)
_thread.start()
def stop():
if _stop_event:
_stop_event.set()