Ejemplo n.º 1
0
def t():
    client = InfluxDBClient(host='localhost',
                            port=8086,
                            username='******',
                            password='******',
                            database='home')
    measurement_name = "speedtest"
    if datetime.datetime.now().minute % 5 == 0:
        # take a timestamp for this measurement
        time = datetime.datetime.utcnow()

        speedtester = speedtest.Speedtest()
        speedtester.get_best_server()
        speedtester.download()
        speedtester.upload()
        res = speedtester.results.dict()
        # format the data as a single measurement for influx
        body = [{
            "measurement": measurement_name,
            "time": time,
            "fields": {
                "download": res["download"],
                "upload": res["upload"],
                "ping": res["ping"]
            }
        }]

        # connect to influx
        ifclient = InfluxDBClient(ifhost, ifport, ifuser, ifpass, ifdb)

        # write the measurement
        ifclient.write_points(body)

    else:
        result3 = client.query("select last(download) from speedtest")

        points = result3.get_points()
        for item in points:
            data = item['last']
        data1 = data / 1000000

        if data1 <= 300:

            def speed():
                # take a timestamp for this measurement
                time = datetime.datetime.utcnow()

                speedtester = speedtest.Speedtest()
                speedtester.get_best_server()
                speedtester.download()
                speedtester.upload()
                res = speedtester.results.dict()
                #connect and write to influxdb
                # format the data as a single measurement for influx
                body = [{
                    "measurement": measurement_name,
                    "time": time,
                    "fields": {
                        "download": res["download"],
                        "upload": res["upload"],
                        "ping": res["ping"]
                    }
                }]

                # connect to influx
                ifclient = InfluxDBClient(ifhost, ifport, ifuser, ifpass, ifdb)

                # write the measurement
                ifclient.write_points(body)

            speed()
Ejemplo n.º 2
0
 def __get_net_speed(self):
     st = speedtest.Speedtest()
     while True:
         self.speed = st.download()
def getSpeed(down=100, up=100, time=1800, threshold=15):
    # down and up are the expected values for download and upload speed, respectively, in Megabytes.
    # threshold is the "cutoff" point. If obtained download speed < down-threshold or obtained upload speed < up-threshold, then we'll nag your ISP!
    threading.Timer(time, getSpeed).start(
    )  # Runs the function every 30 minutes (unless you specify another one).

    speedtester = speedtest.Speedtest()
    speedtester.get_best_server()

    # speedtester.download() and speedtester.upload() return a float which represents the internet speed in B/s.
    # I use this to create a very rough approximation to MB/s.

    # Say the download speed is 96540000.423932.
    # First, I make dSpeed a string so that I can split the value.
    # I split the float by the dot, which turns dSpeed into a list.

    #  dSpeed = ['96540000', '423932']

    # To finalize, I concatenate the first two digits of the first index with the first two digits of the second index.

    # dSpeed = dSpeed[0][0:2] + '.' + dSpeed[1][0:2]
    # print(dSpeed)
    # 93.79

    dSpeed = str(speedtester.download())
    dSpeed = dSpeed.split('.')
    dSpeed = dSpeed[0][0:2] + '.' + dSpeed[1][0:2]
    dSpeed = float(
        dSpeed
    )  # Converting dSpeed from string to float so that I can compare the value later on.

    # Same process for the upload speed.

    uSpeed = str(speedtester.upload())
    uSpeed = uSpeed.split('.')
    uSpeed = uSpeed[0][0:2] + '.' + uSpeed[1][0:2]
    uSpeed = float(uSpeed)

    if dSpeed < down - threshold and uSpeed < down - threshold:
        api.update_status(
            f'@MEOpt porque é que as minhas velocidades de download e upload estão a {dSpeed}MB/s e {uSpeed}MB/s, respetivamente, quando tenho um contrato para {down}/{up} MB/s? #meo #meofibra'
        )
        print(
            f"Mensagem enviada: @MEOpt porque é que as minhas velocidades de download e upload estão a {dSpeed}MB/s e {uSpeed}MB/s, respetivamente, quando tenho um contrato para {down}/{up} MB/s? #meo #meofibra"
        )

    elif dSpeed < down - threshold:  # Compares the download speed from the speedtest with the expected download speed passed as a function argument minus the threshold value.

        # api.update_status sends a status update.
        api.update_status(
            f'@MEOpt porque é que a minha velocidade de download está a {dSpeed}MB/s quando tenho um contrato para {down}MB/s? #meo #meofibra'
        )

        print(
            f"Mensagem enviada: @MEOpt porque é que a minha velocidade de download está a {dSpeed}MB/s quando tenho um contrato para {down}MB/s? #meo #meofibra"
        )

    elif uSpeed < up - threshold:  # Compares the upload speed from the speedtest with the expected download speed passed as a function argument minus the threshold value.
        api.update_status(
            f'@MEOpt porque é que a minha velocidade de upload está a {uSpeed}MB/s quando tenho um contrato para {up}MB/s? #meo #meofibra'
        )
        print(
            f"Mensagem enviada: @MEOpt porque é que a minha velocidade de upload está a {uSpeed}MB/s quando tenho um contrato para {up}MB/s? #meo #meofibra"
        )

    else:
        pass
Ejemplo n.º 4
0
def speedtestdown():
    s = speedtest.Speedtest()
    return s.download() / 1000000
Ejemplo n.º 5
0
 def __init__(self):
     self.parser = speedtest.Speedtest()
     self.host = socket.gethostname()
     self.ip = socket.gethostbyname(self.host)
def digital_assistant(data):
    try:   
        if data == "jarvis":
            respond("yes sir! I am at your service")
            return
            
        elif "how are you" in data: 
            respond("I am well")
            return

        elif contain(data,["define yourself","what can you do","who are you"]):
            respond("I am viswanadh's personal assistant, I am programmed to do minor tasks like system monitoring, profiling,"
            "predict time, take a photo, predict weather,"
            " opening applications like youtube, google chrome ,gmail etcetre, show the top headline news and you can ask me computational or geographical questions too!")
            return
        
        elif contain(data,["who made you","who created you"]):
            respond("I was built by viswa")
            return

        elif "shutdown" in data:
            respond("Are you sure! you want to shutdown your computer")
            data = listen()
            if data == "yes":
                respond("system is going to shutdown...")
                os.system("taskkill /f /im Rainmeter.exe")
                os.system("shutdown /s /t 1")
                return
        
        elif "restart" in data:
            respond("want to restart your computer")
            data=listen()
            if data=="yes":
                os.system("shutdown /r /t 1")
                return

        elif "music" in data:
            respond("Here you go with music")
            music_dir = "C:\\Users\\VISWANADH\\Music"
            song = random.choice(os.listdir(music_dir))
            os.startfile(os.path.join(music_dir,song))
            time.sleep(5)
            return

        elif "movie" in data:
            os.system("D:\\movies\\Ala_Vaikunthapurramloo.mkv")
            time.sleep(5)
            return
        
        elif "notepad" in data:
            os.system("notepad")
            return

        elif contain(data,['select all','cut','copy','paste','history','download','undo','redo','save','enter','search','find']):
            Ctrl_Keys(data)
            return

        elif "open" in data:
            if "tab" in data:
                Tab_Opt(data)
                time.sleep(10)
                respond("what do you wanna search sir!")
                data = listen()
                if "search" in data:
                    keys.Paste()
                else:
                    pyautogui.typewrite(data)
                keys.Enter()
            elif "window" in data:
                Win_Opt(data)
            elif "chrome" in data:
                time.sleep(3)
                webbrowser.open("http://www.google.com/")
                time.sleep(10)
                respond("what do you wanna search sir!")
                data = listen()
                if "search" in data:
                    keys.Paste()
                else:
                    pyautogui.typewrite(data)
                keys.Enter()
            else:
                data = data.split(" ")
                query = data[1]
                for j in search(query, tld='com', lang='en', num=1, start=0, stop=1, pause=2.0):
                    url=j
                webbrowser.get('chrome').open_new(url)
                respond(data[1] + " is open now")
                time.sleep(7)
            return

        elif "news" in data:
            query = "news"
            url="https://timesofindia.indiatimes.com/home/headlines"
            webbrowser.get('chrome').open_new(url)
            respond("Here are some headlines from the Times of India,Happy reading")
            time.sleep(5)
            return
                
        elif "weather" in data:
            data=data.split(" ")
            api_key = "###############################"
            base_url = "https://api.openweathermap.org/data/2.5/weather?"
            if "in" not in data:
                city_name = "kurupam"
            else:
                city_name = data[-1]
            complete_url = base_url + "appid=" + api_key + "&q=" + city_name
            response = requests.get(complete_url)
            x = response.json()
            if x["cod"] != "404":
                y = x["main"]
                current_temperature = y["temp"]
                current_humidiy = y["humidity"]
                z = x["weather"]
                weather_description = z[0]["description"]
                respond(" Temperature in kelvin unit at " + city_name + " is " +
                      str(current_temperature) +
                      "\n humidity in percentage is " +
                      str(current_humidiy) +
                      "\n description  " +
                      str(weather_description))
                return
            else:
                respond(city_name + " weather details not found")
                return
        
        elif "something" in data:
            respond("Searching...")
            data=data.split(" ")
            data = data[3:]
            Req_data = ""
            for word in data:
                Req_data = Req_data + " " + word
            data =  "According to wikipedia " + wikipedia.summary(Req_data, sentences=4) 
            respond(data)
            return

        elif contain(data,["take a photo","capture the photo"]):
            ec.capture(0,False,"img.jpg")
            respond("photo captured successfully")
            return

        elif contain(data,["video","record the video"]):
            ec.auto_vidcapture(0,False,"video.mkv",10)
            respond("video recorded successfully")
            return

        elif "access" in data:
            access()
            return
        
        elif "where is" in data:
            data = data.split(" ")
            name = data[-1]
            url = "https://www.google.com/maps/place/"+name
            webbrowser.get('chrome').open_new(url)
            time.sleep(5)
            return

        elif "write a note" in data:
            respond("What should i write, sir!")
            data = listen()
            file = open('note.txt', 'a')
            file.write("\n"+ctime()+"\n")
            file.write(data)
            respond("noted successfully")
            return
        
        elif "execute" in data:
            execute_commands()
            return

        elif contain(data,["upcoming events","scheduled events","events"]):
            calendar_events()
            return

        elif contain(data,["game","play"]):
            try:
                tic_tac_toe()
                return
            except:
                return

        elif "create event" in data:
            create_event()
            return
            
        elif contain(data,["speed test","internet speed"]):
            try:
                respond("sure! wait a second to measure")
                st = speedtest.Speedtest()
                server_names = []
                st.get_servers(server_names)
                ping = st.results.ping
                downlink_Mbps = round(st.download() / 1000000, 2)
                uplink_Mbps = round(st.upload() / 1000000, 2)
                respond('ping {} ms'.format(ping))
                respond("The uplink is {} Mbps".format(uplink_Mbps))
                respond("The downlink is {}Mbps".format(downlink_Mbps))
                return
            except:
                respond ("I couldn't run a speedtest")     
                return              
        
        elif contain(data,["internet connection","connection"]):
            if internet_availability():
                respond("Internet Connection is okay!")
            return

        elif "wait" in data:
            respond("okay sir")
            time.sleep(10)
            return
        
        elif "screenshot" in data:
            Screenshot = pyautogui.screenshot()
            dir = "C:\\Users\VISWANADH\Pictures\Screenshots"
            length = len(os.listdir(dir))
            Screenshot_name = "Screenshot({}).png".format(length)
            path = os.path.join(dir,Screenshot_name)
            Screenshot.save(path)
            respond("Screenshot saved Successfully!")
            return

        elif "tab" in data:
            Tab_Opt(data)
            return
        
        elif "window" in data:
            Win_Opt(data)
            return
        
        elif contain(data,['battery', 'cpu', 'memory', 'brightness']):
            System_specs(data)
            return

        elif "time" in data:      
            respond(ctime())
            return

        else:
            respond("I can search the web for you,Do you want to continue?")
            opinion=listen()
            if opinion=="yes":
                url="https://www.google.com/search?q =" + '+'.join(data.split())
                webbrowser.get('chrome').open_new(url)
                time.sleep(5)
                return
            else:
                return
    except:
        respond("I don't understand, I can search the web for you,Do you want to continue?")
        opinion=listen()
        if opinion=="yes":
            url="https://www.google.com/search?q =" + '+'.join(data.split())
            webbrowser.get('chrome').open_new(url)
            time.sleep(5)
            return
        else:
            return
Ejemplo n.º 7
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    as_text = True
    as_document = False
    if input_str == "image":
        as_document = False
    elif input_str == "file":
        as_document = True
    elif input_str == "text":
        as_text = True
    await event.edit("`Calculating my internet speed. Please wait!`")
    start = datetime.now()
    s = speedtest.Speedtest()
    s.get_best_server()
    s.download()
    s.upload()
    end = datetime.now()
    ms = (end - start).microseconds / 1000
    response = s.results.dict()
    download_speed = response.get("download")
    upload_speed = response.get("upload")
    ping_time = response.get("ping")
    client_infos = response.get("client")
    i_s_p = client_infos.get("isp")
    i_s_p_rating = client_infos.get("isprating")
    reply_msg_id = event.message.id
    if event.reply_to_msg_id:
        reply_msg_id = event.reply_to_msg_id
    try:
        response = s.results.share()
        speedtest_image = response
        if as_text:
            await event.edit("""`SpeedTest completed in {} seconds`

`Download: {}`
`Upload: {}`
`Ping: {}`
`Internet Service Provider: {}`
`ISP Rating: {}`""".format(
                ms,
                convert_from_bytes(download_speed),
                convert_from_bytes(upload_speed),
                ping_time,
                i_s_p,
                i_s_p_rating,
            ))
        else:
            await borg.send_file(
                event.chat_id,
                speedtest_image,
                caption="**SpeedTest** completed in {} seconds".format(ms),
                force_document=as_document,
                reply_to=reply_msg_id,
                allow_cache=False,
            )
            await event.delete()
    except Exception as exc:
        await event.edit("""**SpeedTest** completed in {} seconds
Download: {}
Upload: {}
Ping: {}

__With the Following ERRORs__
{}""".format(
            ms,
            convert_from_bytes(download_speed),
            convert_from_bytes(upload_speed),
            ping_time,
            str(exc),
        ))
Ejemplo n.º 8
0
def tomar_muestra():
    s = speedtest.Speedtest()
    downspeed = s.download()
    upspeed = s.upload()
    insertar_db(downspeed, upspeed)
Ejemplo n.º 9
0
# Imports the Google Cloud client library
from google.cloud import pubsub_v1
import speedtest
import time, json
import uuid;
computer=hex(uuid.getnode())
s = speedtest.Speedtest()
# Instantiates a client
publisher = pubsub_v1.PublisherClient()
# The resource path for the new topic contains the project ID
# Data must be a bytestring # and the topic name.
topic_path = publisher.topic_path('cloudreach-mars', 'firehose')

# Create the topic.
while True:
    s = speedtest.Speedtest(); _ = s.get_best_server(); _ = s.download();
    msg = s.results.dict()
    msg["computer_id"] = computer
    data = json.dumps(msg).encode()
    # Data must be a bytestring
    publisher.publish(topic_path, data=data)
    print (data)
    time.sleep(30)
Ejemplo n.º 10
0
def speedlogger():
    print("started speedlogger")
    conn = sqlite3.connect(
        "speedloggerdb.db")  # establishing database connection
    c = conn.cursor()
    currenttime = correctdate(datetime.datetime.now().hour,
                              datetime.datetime.now().minute)  # Format 00:00
    currentday = get_date(str(datetime.datetime.now().date()))

    try:
        print("running speedtest")
        servers = []
        speedlog = speedtest.Speedtest()
        speedlog.get_servers(servers)
        speedlog.get_best_server()
        speedlog.download()
        speedlog.upload(pre_allocate=False)

        print("Current Date: %s %s", str(currentday), str(currenttime))
        print("Download: " +
              str(round(speedlog.results.download / (1000 * 1000), 2)) +
              " Mbit/s")  # fixed byte to megabit output
        print("Upload: " +
              str(round(speedlog.results.upload / (1000 * 1000), 2)) +
              " Mbit/s")  # fixed byte to megabit output
        print("Ping: " + str(speedlog.results.ping))
        print("Timestamp: " + str(speedlog.results.timestamp))
        print("Bytes received: " + str(speedlog.results.bytes_received))
        print("Bytes sent: " + str(speedlog.results.bytes_sent))
        print("Link: " + str(speedlog.results.share()))

        download = float(round(speedlog.results.download / (1000 * 1000),
                               2))  # fixed byte to megabit output
        upload = float(round(speedlog.results.upload / (1000 * 1000),
                             2))  # fixed byte to megabit output
        ping = float(round(speedlog.results.ping))
        bytes_received = float(speedlog.results.bytes_received)
        bytes_sent = float(speedlog.results.bytes_sent)
        result_pic = str(speedlog.results.share())

        params = (getnewrnr(c), currentday, currenttime, download, upload,
                  ping, bytes_received, bytes_sent, result_pic)
        c.execute("INSERT INTO results VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
                  params)

        print("finished speedtest")

        # saving the changes
        conn.commit()
        # downloading the speedtest result as .png to display it in ui later on
        # urllib.request.urlretrieve(speedlog.results.share(), str("speedtestresult.png"))

        # backup of the database
        backup()

    except speedtest.SpeedtestException:
        print("speedtest failed")
        # adding empty entrys due to failure
        params = (getnewrnr(c), currentday, currenttime, 0, 0, 0, 0, 0, "")
        c.execute("INSERT INTO results VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
                  params)
        # saving the changes
        conn.commit()
Ejemplo n.º 11
0
# imports
import speedtest
import time
import csv
import os

# Path to the files required by the program: Under the asssumption that PWD is offloadProj
PWD = os.getcwd()
PWD = PWD + '/sbc'
PATH_TO_MAXBWMON_FILE = PWD + '/data/max_bw_mon_now.csv'

while True:
    start = time.time()

    source = "192.168.43.46"
    test = speedtest.Speedtest(source_address=source)
    # test = speedtest.Speedtest()
    test.get_best_server()
    test.download()
    test.upload()
    result = test.results.dict()

    # print(result['download'], result['upload'])

    rx = result['download'] / 8
    tx = result['upload'] / 8
    timestamp = time.time()
    row = [timestamp, rx, tx]

    # write to the file(s)
    # write to csv file
Ejemplo n.º 12
0
import speedtest as s

check = s.Speedtest()

download_speed = round(check.download() / (1000**2), 2)
upload_speed = round(check.upload() / (1000**2), 2)

print('''Results:\nDownload speed : {down} Mbps
Upload speed : {up} Mbps'''.format(down=download_speed, up=upload_speed))
Ejemplo n.º 13
0
#  !usr/bin/env python
import time
from gpiozero import CPUTemperature
from influxdb import InfluxDBClient
from typing import List, Dict
import speedtest
import logging
from threading import Thread

format= '%(asctime)s %(levelname)s  %(message)s'
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H%M%S")
cpu = CPUTemperature()
network = speedtest.Speedtest()
network.get_best_server()
db = InfluxDBClient('localhost', database="test")


def _write(db:InfluxDBClient, measurement:str, point:Dict):
	data=[{
		"measurement":measurement,
		"fields":point
		}
		]
	db.write_points(data)
	logging.info(f"{measurement} write succeeded")

def _temps(db:InfluxDBClient, cpu:object)->float:
	try:
		temp={"temp":cpu.temperature}
		_write(db=db, measurement="temps",point=temp)
	except Exception as e:
Ejemplo n.º 14
0
def getDownloadSpeed():
    """
    Check the download speed of the network connection. Return the value.
    """
    st = speedtest.Speedtest()
    return st.download()
Ejemplo n.º 15
0
# Importando Biblioteca
import speedtest

# Recebe resultado Teste de velocidade
velocidade = speedtest.Speedtest()

# Atribui velocidade de Download
download = round(velocidade.download()/1000000,2)

# Atribui velocidade de Upload
upload = round(velocidade.upload()/1000000,2)
# Dividindo por 1 milhão para converter bit para mbps
# Utilizando Round para arredondar para 2 dígitos

# Mostrando Resultado
print(f"Velocidade de Download em Mbps: {download}")
# Velocidade de Download em Mbps: 52.11
printf"Velocidade de Upload em Mbps: {upload}")
# Velocidade Upload em Mbps: 10.23
Ejemplo n.º 16
0
    def do_speed_test(self, progress_bar):
        global line_sep, low_download_speed, low_upload_speed
        global speed_test_results_file_name, low_speed_test_results_file_name
        # insert here the server id's where you want to test your connection
        # if empty it will search for the nearest server to your machine
        # for example all the Frankfurt, Germany Servers:
        # [3585, 10260, 7560, 9273, 8040, 18667, 10010, 19034, 19116, 18488, 17312, 21528, 23414, 23095, 23870]
        servers = []
        times = [0, 0, 0]  # the times that will be recorded in this session
        s = speedtest.Speedtest()
        progress_bar.start()  # start the progressBar Thread

        begin = self.time.time()  # take the time the server search has started
        s.get_servers(servers)  # get all the server that match the filter
        s.get_best_server()  # get the best server from the server found previously
        times[0] = self.time.time() - begin  # compute the total time this action needed

        self.state_lock.acquire()
        self.current_State = self.states[1]  # change state to Download Speed Test state
        self.state_lock.release()
        begin = self.time.time()  # take the time the Download speed test has started
        s.download()  # make the Download Speed Test
        times[1] = self.time.time() - begin  # compute the total time this action needed

        self.state_lock.acquire()
        self.current_State = self.states[2]  # change state to Upload Speed Test state
        self.state_lock.release()
        begin = self.time.time()  # take the time the Upload speed test has started
        s.upload(pre_allocate=False)  # make the Upload Speed Test
        times[2] = self.time.time() - begin  # compute the total time this action needed

        results = s.results  # crawl all the results

        self.state_lock.acquire()
        self.current_State = self.states[3]  # change state to Finished state
        self.state_lock.release()
        progress_bar.join()  # wait for the progress bar to finish
        f = open(speed_test_results_file_name, "a+")  # open file to store speed results

        local_low_download_speed = low_download_speed
        local_low_upload_speed = low_upload_speed
        time = datetime.now().strftime('%d.%m.%Y %H:%M')  # get current Date and Time with the format: DD.MM.YYYY HH:MM

        # if result is at low Speed ad the prefix
        if int(results.download / 1000000) < local_low_download_speed or int(results.upload / 1000000) < local_low_upload_speed:
            output = "\t\tLOW SPEED" + line_sep
        else:
            output = line_sep

        # format all the result
        output2 = "\tDownload: " + str(int(results.download / 1000000)) + " Mbits/s" + line_sep
        output2 += "\tUpload: " + str(int(results.upload / 1000000)) + " Mbits/s" + line_sep
        output2 += "\tPing " + str(int(results.ping)) + " ms" + line_sep
        print(time, output, output2, "\tClient: see Text file", line_sep, "\tServer: see Text file", line_sep)
        output2 += "\tClient: " + str(results.client) + line_sep
        output2 += "\tServer: " + str(results.server) + line_sep

        f.write(time + output + output2)  # write results at the end of the file
        f.close()  # close the file

        # if speeds are low then add results to the special file
        if int(results.download / 1000000) < local_low_download_speed or int(results.upload / 1000000) < local_low_upload_speed:
            f2 = open(low_speed_test_results_file_name, "a+")  # open file
            f2.write(time + line_sep + output2)  # write results at the end of the file
            f2.close()  # close the file
        else:  # if speed are normal, store the time it took to the file
            f3 = open(time_spend_file_name, "a+")   # open file
            # write times at the end of the file
            f3.write(str(times[0]) + ";" + str(times[1]) + ";" + str(times[2]) + line_sep)
            f3.close()  # close file
            f3 = open(time_spend_file_name, "r")  # open file again
            all_lines = f3.readlines()  # get all the lines of the file
            f3.close()  # close the file
            if len(all_lines) > 1:  # if there where mor than 1 test stored compute average
                lines = []
                for i in range(1, len(all_lines)):  # get the times for each line
                    lines.append(all_lines[i].split(";"))
                for i in range(0, len(lines)):  # cast from String into float
                    for j in range(0, 3):
                        lines[i][j] = float(lines[i][j])
                avr = [lines[0][0], lines[0][1], lines[0][2]]  # begin to compute average
                for i in range(1, len(lines)):  # continue computing average
                    avr[0] += lines[i][0]
                    avr[1] += lines[i][1]
                    avr[2] += lines[i][2]
                for i in range(0, 3):  # finish computing average and cast into String
                    avr[i] /= len(lines)
                    avr[i] = str(avr[i])
                output = ";".join(avr) + line_sep
                # replace any unwanted line separators
                if line_sep == '\r\n':
                    not_correct = '\n'
                else:
                    not_correct = '\r\n'
                for i in range(1, len(all_lines)):
                    all_lines[i] = all_lines[i].replace(not_correct, line_sep)
                # put average to beginning of file
                all_lines[0] = output
                f3 = open(time_spend_file_name, "w")  # open file
                f3.writelines(all_lines)  # write new values into file
                f3.close()  # close file
Ejemplo n.º 17
0
def speed_measure():
    st = speedtest.Speedtest()
    st.get_best_server()
    return st.download()
Ejemplo n.º 18
0
 def __init__(self):
     self.parser = speedtest.Speedtest()
Ejemplo n.º 19
0
 def function(): 
   speedtester = speedtest.Speedtest()
   speedtester.get_best_server()
   speedtester.download()
   speedtester.upload()
   res = speedtester.results.dict()
Ejemplo n.º 20
0
#!/usr/bin/env python
# coding: utf-8

import requests  # Enable API request functionality
import subprocess  # Enable calling another process
import datetime  # Enable date and time functionality
import os  # Enable filesystem functionality
from pathlib import Path  # Enable filesystem path joining
import json  # Enable JSON support
from pythonping import ping  # Enable pingtest
import speedtest  # Enable Speedtest
import time  # Enable sleep

st = speedtest.Speedtest()  # Define speedtest
servers = []  # Set specific servers for speedtest (none = use best)
threads = None  # Threads for speedtest

# configDict = dict()
# configList = [line.strip().split(' = ') for line in open('config.txt')]  # pull run parameters from config.txt
testsPerRound = 3  # Number of tests before uploading to Gist (default 3)
numRounds = 2240  # Number of times to upload to Gist (2240 = 7 days of testing @ 90sec/test @ 3 tests/round)
testWaitSec = 90  # Wait time between tests (default 90 sec)

creds = [line.strip()
         for line in open('creds.txt')]  # pull API credentials from creds.txt
keY = creds[0]  # API key from creds.txt
headers1 = {
    'Accept': 'application/vnd.github.v3+json'
}  # Headers for API request
auth1 = ('pete5x5', keY)  # Login info
Ejemplo n.º 21
0
import csv
import logging
import os.path
import speedtest
from datetime import date, datetime

time_stamp = datetime.now()
today = date.today()
speedTest = speedtest.Speedtest()

logging.basicConfig(filename='SpeedTest.log', level=logging.DEBUG,
                    format='%(asctime)s -- %(levelname)s -- %(message)s')


def download_speed():
    down_speed = speedTest.download()
    return down_speed / 1000000


def upload_speed():
    up_speed = speedTest.upload()
    return up_speed / 1000000


def all_speed():
    logging.info("Download Speed : {} Mbps".format(download_speed()))
    logging.info("Upload Speed : {} Mbps".format(upload_speed()))

    today_ = today.strftime("%b-%d-%Y")
    time_stamp_ = time_stamp.strftime("%H:%M:%S")
Ejemplo n.º 22
0
def config_best_speed_test():
    s = speedtest.Speedtest()
    s.get_config()
    s.get_best_server()
    return s
Ejemplo n.º 23
0
def main(args=None):
    argp = argparse.ArgumentParser(description='Deadman server for MS Teams')

    argp.add_argument('--verbose',
                      '-v',
                      action='store_true',
                      help='Verbose log output')

    argp.add_argument('--port',
                      '-p',
                      type=int,
                      default=26543,
                      help='Where to listen')

    argp.add_argument('--interval-speedtest',
                      type=int,
                      default=600,
                      help='Interval (in seconds) of speed test')

    argp.add_argument('--interval-latency',
                      type=int,
                      default=10,
                      help='Interval (in seconds) of latency test')

    argp.add_argument(
        '--speedtest-server-refresh-interval',
        type=int,
        default=3600,
        help='How frequently the best speedtest server should be refreshed')

    args = argp.parse_args()

    configure_log(args=args)

    last_speedcheck = None
    last_latency = None
    last_server_refresh = None

    speedcheck_interval = datetime.timedelta(seconds=args.interval_speedtest)
    latency_interval = datetime.timedelta(seconds=args.interval_latency)
    server_refresh_interval = datetime.timedelta(
        seconds=args.speedtest_server_refresh_interval)

    speed = speedtest.Speedtest()

    start_http_server(args.port)

    logging.info(f"Started! Listening on port {args.port}")

    try:
        while True:
            now = datetime.datetime.now()

            # This could be done way better and more generic, but for now it's just a simple
            # script so I prefer to avoid complications
            if last_server_refresh is None or now - last_server_refresh > server_refresh_interval:
                speed.get_servers([])
                speed.get_best_server()
                last_server_refresh = now

            if last_latency is None or now - last_latency > latency_interval:
                latency_check()
                last_latency = now

            if last_speedcheck is None or now - last_speedcheck > speedcheck_interval:
                speedtest_check(speed)
                last_speedcheck = now

            # This is enough for most purposes. Maybe compute the gcm of all the intervals...
            time.sleep(1)
    except KeyboardInterrupt:
        logging.info("Ctrl-C detected, exiting")
        sys.exit(0)
Ejemplo n.º 24
0
            canvas.point([queue_draw_loc_x, hw[0] - measurement.results.download/scale_max*hw[0]], fill=1)

        queue_draw_loc_x -= 1


# Entry point of the program
if __name__ == '__main__':
    EXECUTION_PERIOD_S = 60.0 * 30.0
    # Create the I2C interface.
    i2c = busio.I2C(board.SCL, board.SDA)
    # Create the SSD1306 OLED class.
    disp = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)

    # Network measumenet queue
    queue_size = 68
    speedtest_queue = collections.deque(queue_size*[speedtest.Speedtest()], queue_size)
    # Input pins:

    # Clear display.
    disp.fill(0)
    disp.show()

    # Create blank image for drawing.
    # Make sure to create image with mode '1' for 1-bit color.
    width = disp.width
    height = disp.height
    image = Image.new('1', (width, height))
    fnt = ImageFont.truetype('Pillow/Tests/fonts/DejaVuSans.ttf', 10)

    # Get drawing object to draw on image.
    draw = ImageDraw.Draw(image)
Ejemplo n.º 25
0
import logging

import my_db

# App variables:
## Todo move to config
PingFrequency = 1
FullTestFrequency = 10
debug_level = 2

# Counters
PingCount = 0
FullTestCount = 0

# Speed test
s = speedtest.Speedtest()
s.get_servers()

#Execution Flags
isPing = False
isFull = False


def PingTest():
    s.get_best_server()
    return round(s.results.dict()["ping"], 1)


def PingTask():
    # Perform Ping test and save results to local DB
    global PingCount, isPing
Ejemplo n.º 26
0
def get_download_speed():
    s = speedtest.Speedtest()
    s.get_best_server()
    return str(int(s.download() / 1000000))
# Enter your details
consumer_key = ""
consumer_secret = ""

access_token = ""
access_token_secret = ""

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

# SPEEDTEST SETUP #

speedtester = speedtest.Speedtest()
speedtester.get_best_server()


def getSpeed(down=100, up=100, time=1800, threshold=15):
    # down and up are the expected values for download and upload speed, respectively, in Megabytes.
    # threshold is the "cutoff" point. If obtained download speed < down-threshold or obtained upload speed < up-threshold, then we'll nag your ISP!
    threading.Timer(time, getSpeed).start(
    )  # Runs the function every 30 minutes (unless you specify another one).

    speedtester = speedtest.Speedtest()
    speedtester.get_best_server()

    # speedtester.download() and speedtester.upload() return a float which represents the internet speed in B/s.
    # I use this to create a very rough approximation to MB/s.
Ejemplo n.º 28
0
 def __init__(self):
     self.parser = psutil.net_if_addrs()
     self.speed_parser = speedtest.Speedtest()
     self.interfaces = self.interface()[0]
Ejemplo n.º 29
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    as_text = True
    as_document = False
    if input_str == "image":
        as_document = False
    elif input_str == "file":
        as_document = True
    elif input_str == "text":
        as_text = True
    await event.edit("`حساب سرعة الإنترنت الخاصة بي.  ارجوك انتظر!`")
    start = datetime.now()
    s = speedtest.Speedtest()
    s.get_best_server()
    s.download()
    s.upload()
    end = datetime.now()
    ms = (end - start).microseconds / 1000
    response = s.results.dict()
    download_speed = response.get("download")
    upload_speed = response.get("upload")
    ping_time = response.get("ping")
    client_infos = response.get("client")
    i_s_p = client_infos.get("isp")
    i_s_p_rating = client_infos.get("isprating")
    reply_msg_id = event.message.id
    if event.reply_to_msg_id:
        reply_msg_id = event.reply_to_msg_id
    try:
        response = s.results.share()
        speedtest_image = response
        if as_text:
            await event.edit("""`اكتمال ** SpeedTest ** خلال {} ثانية`

`التحميل: {}`
`رفع: {}`
`بنك: {}`
`مزود خدمة الإنترنت: {}`
`تقييم ISP: {}`""".format(ms, convert_from_bytes(download_speed),
                          convert_from_bytes(upload_speed), ping_time, i_s_p,
                          i_s_p_rating))
        else:
            await borg.send_file(
                event.chat_id,
                speedtest_image,
                caption="اكتمال ** SpeedTest ** خلال {} ثانية".format(ms),
                force_document=as_document,
                reply_to=reply_msg_id,
                allow_cache=False)
            await event.delete()
    except Exception as exc:
        await event.edit("""**اكتمال ** SpeedTest ** خلال {} ثانية
تحميل: {}
رفع: {}
بنك: {}

__With the Following ERRORs__
{}""".format(ms, convert_from_bytes(download_speed),
             convert_from_bytes(upload_speed), ping_time, str(exc)))
Ejemplo n.º 30
0
def network ():
    hostname = socket.gethostname()    
    IPAddr = socket.gethostbyname(hostname)    
    print("User :"******"1.1.1.1", 53))
        return True
       except OSError:
        pass
       return False

    if(is_connected()==True):
        print(colored('Internet connection OK' , 'green' , attrs=['bold' , 'reverse', 'blink']))

        
        s = speedtest.Speedtest()
        

        print(colored(f'Upload Speed : {s.download(threads=None)/1e+6}' , "green"))
        print(colored(f'Download Speed : {s.upload(threads=None)/1e+6}' , "green"))
        
        
      #   Url = "https://geo.ipify.org/api/v1?apiKey=at_yxxDWNsLvdqKjrPHbiufYWJT2x1FA=8.8.8.8"
      #   r = requests.get(url = Url)
      #   print(r.json())

        from requests import get

        ip1 = get('https://api.ipify.org').text
        print(colored('Public IP : {}'.format(ip1) , "green"))

        ip = ip1
        api_key = 'at_yxxDWNsLvdqKjrPHbiufYWJT2x1FA'
        api_url = 'https://geo.ipify.org/api/v1?'

        url = api_url + 'apiKey=' + api_key + '&ipAddress=' + ip
        data = urlopen(url).read().decode('utf8')
        final_data = json.loads(data)
        z = final_data["location"]
        y = final_data["as"]
        x = final_data["proxy"]
       
        print(colored(f'Country : {z["country"]} ' , "green" ))
        print(colored(f'Region : {z["region"]} ' , "green" ))
        print(colored(f'Region : {z["lat"]} ' , "green"))
        print(colored(f'Latitu : {z["lng"]} ' , "green"))
        print(colored(f'timezone : {z["timezone"]} ' , "green"))
        
        print(colored(f'Network : {y["name"]} ' , "green"))
        print(colored(f'ISP : {final_data["isp"]} ' , "green"))

        if(x["proxy"]==False):

           print(colored(f'Proxy : {x["proxy"]} ' , "yellow"))
           print(colored(f'VPN : {x["vpn"]} ' , "yellow"))
           print(colored(f'TOR : {x["tor"]} ' , "yellow"))

        else:
           print(colored(f'Proxy : {x["proxy"]} ' , "green"))
           print(colored(f'VPN : {x["vpn"]} ' , "green"))
           print(colored(f'TOR : {x["tor"]} ' , "green"))

       
        
        
        

    else:
       print(colored('NO Internet connection :( ' , 'red' , attrs=['bold' , 'reverse', 'blink']))