#!/usr/bin/env python3

import re
import subprocess
from influxdb import InfluxDBClient
import json

response = subprocess.Popen('/home/pi/speedtest/ookla_bin/speedtest -b --progress=no -f json-pretty', shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')

json_data = json.loads(response)

ping = round(json_data["ping"]["latency"], 2)
upload = round(json_data["upload"]["bytes"]/1024/1024, 2)
download = round(json_data["download"]["bytes"]/1024/1024, 2)

speed_data = [
    {
        "measurement" : "internet_speed",
        "tags" : {
            "host": "home"
        },
        "fields" : {
            "download": download,
            "upload": upload,
            "ping": ping
        }
    }
]
client = InfluxDBClient("192.168.178.25", 8086, 'no', 'credentials', 'here')

client.write_points(speed_data)

print(f"Ping: {ping}; Download: {download}; Upload: {upload}")
