示例#1
0
def speedy(site):
    pst = pyspeedtest.SpeedTest(site)
    print()
    nicePrint("Using site", site)
    nicePrint("Ping", pyspeedtest.pretty_speed(pst.ping()))
    nicePrint("Download", pyspeedtest.pretty_speed(pst.download()))
    print()
示例#2
0
    def update_statistics(self):
        """
        Updates the statistics display on the GUI menu.

        Responsible for keeping track of rolling averages and last tests.
        Called directly by the tester thread.
        """

        self.lasttest = self.thread.last_result
        self.ntests += 1

        ping_offset = (self.lasttest['ping'] - self.avg['ping']) / self.ntests
        down_offset = (self.lasttest['down'] - self.avg['down']) / self.ntests
        up_offset = (self.lasttest['up'] - self.avg['up']) / self.ntests
        self.avg['ping'] = self.avg['ping'] + ping_offset
        self.avg['down'] = self.avg['down'] + down_offset
        self.avg['up'] = self.avg['up'] + up_offset

        # create new format strings from computed averages/last test
        # \u2191 is an up arrow
        # \u2193 is a down arrow
        last_str = u"Last: {ping}ms / {up}\u2191 / {down}\u2193".format(
            ping=self.lasttest['ping'],
            up=pretty_speed(self.lasttest['up']),
            down=pretty_speed(self.lasttest['down']))
        avg_str = u"Avg: {ping}ms / {up}\u2191 / {down}\u2193".format(
            ping=round(self.avg['ping'], 2),
            up=pretty_speed(self.avg['up']),
            down=pretty_speed(self.avg['down']))

        # apply changes
        self.last_test_label.config(text=last_str)
        self.avg_test_label.config(text=avg_str)
示例#3
0
 def getSpeedtest(self):
     try:  # Speed Test
         st = pyspeedtest.SpeedTest()
         self.ping = pyspeedtest.pretty_speed(st.ping())
         self.download = pyspeedtest.pretty_speed(st.download())
         self.upload = pyspeedtest.pretty_speed(st.upload())
         self.timeStamp()  # Set Time stamp after Speed Tests
         if self.verbose:
             self.printSpeedTestData()
     except Exception as e:
         print("Speedtest Error:", e)
示例#4
0
    def _get_speedtest(self):

        try:
            self.speed_test.connect(SPEEDTEST_URL)

            self.procs.append(
                Process(target=self.task_queue.put,
                        args=({
                            "Speed_Test": {
                                "Ping": "%.2f ms" % self.speed_test.ping()
                            }
                        }, )))

            self.procs.append(
                Process(target=self.task_queue.put,
                        args=({
                            "Speed_Test": {
                                "Download":
                                pyspeedtest.pretty_speed(
                                    self.speed_test.download())
                            }
                        }, )))
            self.procs.append(
                Process(target=self.task_queue.put,
                        args=({
                            "Speed_Test": {
                                "Upload":
                                pyspeedtest.pretty_speed(
                                    self.speed_test.upload())
                            }
                        }, )))

        except:

            self.procs.append(
                Process(target=self.task_queue.put,
                        args=({
                            "Speed_Test": {
                                "Download": "0.0 Mbps",
                                "Upload": "0.0 Mbps",
                                "Ping": "0.0 ms"
                            }
                        }, )))
示例#5
0
    def run(self):
        self.parent.listWidget.clear()
        self.parent.hizihesapla.setEnabled(False)
        self.parent.listWidget.insertItem(0,"Test yapılıyor, lütfen bekleyiniz.")
        self.sonuclari_sifirla()

        self.st = pyspeedtest.SpeedTest() # Programa işlevsellik kazandıran kodlar.
        self.downloadbilgisi = pyspeedtest.pretty_speed(self.st.download()) #Download hızı hesaplanıyor.
        self.uploadbilgisi = pyspeedtest.pretty_speed(self.st.upload()) # Upload hızı hesaplanıyor.
        self.pingbilgisi = pyspeedtest.pretty_speed(self.st.ping()) # Ping hesaplanıyor.

        self.item = ["Download: " + self.downloadbilgisi, "Upload: " + self.uploadbilgisi,
                     "Ping: " + self.pingbilgisi]

        self.parent.sonuc_yazi_1.setText(self.downloadbilgisi)
        self.parent.sonuc_yazi_2.setText(self.uploadbilgisi)
        self.parent.sonuc_yazi_3.setText(self.pingbilgisi)
        self.parent.listWidget.clear()
        self.parent.listWidget.insertItems(0, self.item)
        self.parent.hizihesapla.setEnabled(True)
示例#6
0
def send_speed_test(ws):
    print("Preparing message for server...")
    try:
        st = pyspeedtest.SpeedTest()
        st.connect('speedtestba1.telecomitalia.it')
        ping = round(st.ping(), 2)
        download_speed = pyspeedtest.pretty_speed(st.download())
        upload_speed = pyspeedtest.pretty_speed(st.upload())
        msg = {
            'type': "speedTestClient",
            'message': "",
            'userId': USER_ID,
            'mac': MAC_ADDRESS,
            'ping': ping,
            'dw_speed': download_speed,
            'up_speed': upload_speed
        }
    except Exception as e:
        print(e)
    json_msg = json.dumps(msg)
    yield from ws.send(json_msg)
    print("Message sent to the web socket: " + json_msg)
示例#7
0
def speedtest(host,
              runs=2,
              index=None,
              sourcetype="speedtest",
              source="speedtest_search_command",
              logger=None):
    """
    Performs a bandwidth speedtest and sends the results to an index.
    """

    # This will contain the event we will index and return
    result = {}

    speedtester = pyspeedtest.SpeedTest(host=host, runs=runs)
    result['ping'] = round(speedtester.ping(), 2)

    result['download'] = round(speedtester.download(), 2)
    result['download_readable'] = pyspeedtest.pretty_speed(
        speedtester.download())

    result['upload'] = round(speedtester.upload(), 2)
    result['upload_readable'] = pyspeedtest.pretty_speed(speedtester.upload())

    result['server'] = speedtester.host

    # Write the event as a stash new file
    if index is not None:
        writer = StashNewWriter(index=index,
                                source_name=source,
                                sourcetype=sourcetype,
                                file_extension=".stash_output")

        # Log that we performed the speedtest
        if logger:
            logger.debug("Wrote stash file=%s", writer.write_event(result))

    # Return the result
    return result
示例#8
0
def run_analytics():

    with open(readfilename, 'r') as record:
        lines = record.readlines()

    records = {"time": [], "locs": [], "ping": [], "down": [], "up": []}
    fails, totaltries = 0, 0

    for line in lines:
        try:
            time, loc, ping, down, up = line.split(", ")
            records['time'].append(
                tm.strptime(time, "%a %b %d %w %Y at %H:%M:%S"))
            records['locs'].append(loc)
            records['ping'].append(float(ping))
            records['down'].append(float(down))
            records['up'].append(float(up))
        except ValueError:
            # it was a connection error
            fails += 1
        totaltries += 1

    statlines = []

    # meta
    statlines.append(" " * 10 + " INTERNET SPEED REPORT")
    statlines.append("     Location: " + LOCATION)
    statlines.append("Time window: beginning " +
                     tm.asctime(records['time'][0]))
    statlines.append("             end       " +
                     tm.asctime(records['time'][-1]))
    statlines.append("Server specified: " + str(FORCE_SERVER))

    statlines.append("\n")

    # pings
    statlines.append(" " * 10 + "  PING STATISTICS  " + " " * 10)
    statlines.append("Fastest ping: " + str(min(records['ping'])) + " ms")
    statlines.append("Slowest ping: " + str(max(records['ping'])) + " ms")
    statlines.append("Average ping: " + str(avg(records['ping'])) + " ms")

    statlines.append("\n")

    # download
    statlines.append(" " * 10 + "DOWNLOAD STATISTICS" + " " * 10)
    statlines.append("Fastest download: " + pretty_speed(max(records['down'])))
    statlines.append("Slowest download: " + pretty_speed(min(records['down'])))
    statlines.append("Average download: " + pretty_speed(avg(records['down'])))

    statlines.append("\n")

    # upload
    statlines.append(" " * 10 + " UPLOAD STATISTICS " + " " * 10)
    statlines.append("Fastest upload: " + pretty_speed(max(records['up'])))
    statlines.append("Slowest upload: " + pretty_speed(min(records['up'])))
    statlines.append("Average upload: " + pretty_speed(avg(records['up'])))

    statlines.append("\n")

    if STANDARDS_ENABLE:
        print("Standards!" + str(STANDARDS_ENABLE))

        statlines.append(" " * 10 + " OUT-OF-STANDARDS" + " " * 10)

        # below standard rates
        statlines.append("Total connection attempts: " + str(totaltries))
        statlines.append("Total failed connection attempts: " + str(fails))
        statlines.append("Total successful connection attempts: " +
                         str(totaltries - fails))
        statlines.append("Percentage of failed connections: " +
                         str(round(fails / totaltries, 4) * 100) + "%")

        statlines.append("")

        n_ping_above_std = 0
        for ping in records['ping']:
            if ping > STANDARD_PING:
                n_ping_above_std += 1
        statlines.append("Number of ping times above " + str(STANDARD_PING) +
                         " ms: " + str(n_ping_above_std))
        p_ping_above_std = round(n_ping_above_std / totaltries, 3)
        statlines.append("Percentage of ping times below standard: " +
                         str(p_ping_above_std * 100) + "%")
        statlines.append("Hours/day ping time is below standard: " +
                         str(round(p_ping_above_std * 24, 1)) + " hours")
        statlines.append("")

        n_down_below_std = 0
        for down in records['down']:
            if down < STANDARD_DOWN:
                n_down_below_std += 1
        statlines.append("Number of download speeds below " +
                         pretty_speed(STANDARD_DOWN) + ": " +
                         str(n_down_below_std))
        p_down_below_std = round(n_down_below_std / totaltries, 3)
        statlines.append("Percentage of download speeds below standard: " +
                         str(p_down_below_std * 100) + "%")
        statlines.append("Hours/day download speed is below standard: " +
                         str(round(p_down_below_std * 24, 1)) + " hours")
        statlines.append("")

        n_up_below_std = 0
        for up in records['up']:
            if up < STANDARD_UP:
                n_up_below_std += 1
        statlines.append("Number of upload speeds below " +
                         pretty_speed(STANDARD_UP) + ": " +
                         str(n_up_below_std))
        p_up_below_std = round(n_up_below_std / totaltries, 3)
        statlines.append("Percentage of upload speeds below standard: " +
                         str(p_up_below_std * 100) + "%")
        statlines.append("Hours/day upload speed is below standard: " +
                         str(round(p_up_below_std * 24, 1)) + " hours")
        statlines.append("\n")

    with open(ANALYTICS_REC_FILE, 'w') as out:
        out.writelines('\n'.join(statlines))
示例#9
0
 def __get_down__(self):
     self.actual_down_str = pyspeedtest.pretty_speed(self.speedtest.download())
     self.actual_down, _ = self.actual_down_str.split()
     self.actual_down = int(round(float(self.actual_down)))
示例#10
0
 def __get_up__(self):
     self.actual_up_str = pyspeedtest.pretty_speed(self.speedtest.upload())
     self.actual_up, _ = self.actual_up_str.split()
     self.actual_up = int(round(float(self.actual_up)))
示例#11
0
    sys.stdout.write('\r{0} Testing upload'.format(msg))
    upload = tester.upload()

    results[profile_name] = {
        'id': profile['id'],
        'name': profile_name,
        'ping': ping,
        'upload': upload,
        'download': download,
        'score': (upload * download) / ping
    }

    sys.stdout.write('\r{0:7.0f}s {1} {2:5.0f}ms {3:>13s} {4:>13s}\n'.format(
        time() - test_time, profile_name.rjust(profiles_longuest_name + 1),
        ping, pyspeedtest.pretty_speed(download),
        pyspeedtest.pretty_speed(upload)))

best_profile = max(results.values(), key=lambda p: p['score'])
print('\nApplying best found profile "{0}"'.format(best_profile['name']))

client.post('/xdsl/{0}/lines/{1}/dslamPort/changeProfile'.format(
    service, line),
            dslamProfileId=best_profile['id'])

connection_status = 'down'
while True:
    try:
        sleep(.5)
        requests.get('https://www.ovh.com', timeout=2)
        if connection_status == 'up':
示例#12
0
import pyspeedtest
from time import localtime, strftime
import os.path
import csv


fname = 'speed.csv'
today = localtime()

# Run speed test
st = pyspeedtest.SpeedTest()
st.ping()
up = pyspeedtest.pretty_speed(st.upload())
down = pyspeedtest.pretty_speed(st.download())


# Check if file exists -- create and initialize with headers
if(not os.path.isfile('speed.csv')):
	row = [['Weekday','Time','Month','Day','Year','Up','Down']]
	file = open(fname,'w')
	with file:
		writer = csv.writer(file)
		writer.writerows([['Weekday','Time','Month','Day','Year','Up','Down']])	


row = [[strftime("%a",today), strftime("%H:%M",today), today[1], today[2], today[0], up, down]]

file = open(fname,'a')
with file:
	writer = csv.writer(file)
	writer.writerows(row)
示例#13
0
import pyspeedtest

i = 0
testLoop = 100

while i < testLoop:

    st = pyspeedtest.SpeedTest(host='www.speedtest.net')
    resultDownload = pyspeedtest.pretty_speed(st.download())

    print('Download: %s') % (resultDownload)

    i += 1