import speedtest
import socket
import paho.mqtt.client as mqtt
import time
import os
import sys
import traceback
from datetime import datetime
import httplib
import psycopg2
#Declare the db vars
conn = psycopg2.connect("dbname='Add your DB' user='pi' host='add your host' password='password")
cur = conn.cursor()
download = 0.0
upload = 0.0
ping = 0.0
source_ip =" "
source_isp = " "
server_name = " "
# On connect Callback
def on_connect(client, userdata, flags, rc):
print("rc: " + str(rc))
mqttc = mqtt.Client()
# Assign event callbacks
mqttc.on_connect = on_connect
# Connect
mqttc.connect("10.64.9.34", 1883,50)
#Start the mqtt loop
mqttc.loop_start()
# Write apikey of emoncms account
apikey2 = "add your key"
run = True
servers = []
source = "10.64.9.42"
speedtest.SOURCE = source
socket.socket = speedtest.bound_socket
while run:
try:
os.system('cls')
print("Set source ip : " + source)
s = speedtest.Speedtest()
source_ip = s.config['client'].get('ip')
source_isp = s.config['client'].get('isp')
print("Source ISP ip : " + source_ip)
print("Source ISP : " + source_isp )
print("Get the server list")
s.get_servers(servers)
print("Find the best server")
s.get_best_server()
print("Start download test")
s.download()
print("Start upload test")
s.upload()
download = s.results.download / 1000.0 / 1000.0
upload = s.results.upload / 1000.0 / 1000.0
server_name = s.results.server['sponsor']
ping = s.results.ping
print("Server : " + server_name)
print("Ping: {0:.2f}".format(ping))
print("Download: {0:.2f}".format(download) + " Mbit/s")
print("Upload: {0:.2f}".format(upload) + " Mbit/s")
#Write the values to the DB
print("Write vales to the DB")
cur.execute("insert into speedtest(record_timestamp , source_isp , source_ip , server_name , ping , download , upload) values (now(), %s , %s , %s , %s , %s , %s )" , (source_isp, source_ip, server_name , ping , download , upload ))
conn.commit()
print("Send Values via MQTT")
mqttc.publish("Internetspeed/Download", str(round(download , 2)))
mqttc.publish("Internetspeed/Upload", str(round(upload , 2)))
print("Send Values via EMONCMS")
domain = "10.64.9.34"
emon_conn = httplib.HTTPConnection(domain,timeout = 1)
emon_conn.request("GET", "/emoncms/input/post.json?node=internetspeed&json={ping:" + str(round(s.results.ping , 2)) + ",download:" + str(round(download , 2)) + ",upload:" + str(round(upload , 2)) + "}&apikey="+apikey2)
emon_response = emon_conn.getresponse()
print emon_response.read()
print("Waiting for 10 minutes")
time.sleep(600)
except KeyboardInterrupt:
print "End"
run = False
except:
traceback.print_exc()
time.sleep(10)
pass