77 lines
1.8 KiB
Python
Executable File
77 lines
1.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
import sys
|
|
import datetime
|
|
import configparser
|
|
import mysql.connector
|
|
import speedtest
|
|
from socket import timeout
|
|
|
|
cfg = configparser.ConfigParser()
|
|
with open('config.ini') as f:
|
|
cfg.read_file(f)
|
|
|
|
db_config = {k: v for k, v in cfg['db'].items() if k in ['user', 'password', 'host', 'database']}
|
|
|
|
|
|
SPEEDTEST_TABLE_CMD = """CREATE TABLE IF NOT EXISTS sts (
|
|
test_no INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
|
server_id INTEGER,
|
|
sponsor NATIONAL CHARACTER VARYING(40),
|
|
time DATETIME,
|
|
distance FLOAT UNSIGNED,
|
|
ping FLOAT UNSIGNED,
|
|
download FLOAT UNSIGNED,
|
|
upload FLOAT UNSIGNED
|
|
);
|
|
"""
|
|
|
|
try:
|
|
cx = mysql.connector.connect(**db_config)
|
|
c = cx.cursor()
|
|
upload_statement = """INSERT INTO sts (server_id, sponsor, time, distance, ping, download, upload)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s)"""
|
|
|
|
try:
|
|
s = speedtest.Speedtest()
|
|
s.get_servers()
|
|
s.get_best_server()
|
|
s.download()
|
|
s.upload()
|
|
d = s.results.dict()
|
|
u = (
|
|
d['server']['id'],
|
|
d['server']['sponsor'],
|
|
d['timestamp'],
|
|
d['server']['d'], # distance
|
|
d['server']['latency'],
|
|
d['download'],
|
|
d['upload']
|
|
)
|
|
except (speedtest.SpeedtestException, timeout):
|
|
u = (
|
|
None,
|
|
None,
|
|
str(datetime.datetime.utcnow().isoformat()) + 'Z',
|
|
None,
|
|
None,
|
|
None,
|
|
None
|
|
)
|
|
print("Speedtest failed", file=sys.stderr)
|
|
try:
|
|
c.execute(SPEEDTEST_TABLE_CMD)
|
|
c.execute(upload_statement, u)
|
|
|
|
cx.commit()
|
|
except mysql.connector.Error:
|
|
cx.rollback()
|
|
raise
|
|
c.close()
|
|
cx.close()
|
|
except mysql.connector.Error as err:
|
|
print(err)
|
|
exit('Could not open database')
|
|
|
|
|
|
# print("Uploaded" + str(u))
|