Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code help please
#1
Hello,

Please help.. I'm not a developer but I need to know if it still possible to fix this application.

The app is a bench-marking tool for testing ISP reliability. The Windows app requirement is to run test only when there is little or no background traffic (minimum traffic to allow test should be 64kbps)

So when we select "Check Traffic" box, and hit "Start" to perform test, an error will occur saying "BG Traffic Exceed 64kbps".

My questions from the codes:

- is the app capable of checking "Windows" background traffic?
- can we exclude the main apps traffic for checking?

Thanks in advance.
from datetime import datetime
from netifaces import AF_INET, AF_INET6, AF_LINK
from PyQt4 import QtGui, QtCore, QtWebKit
# from PyQt5 import QtCore, QtGui, QtPrintSupport, QtWidgets
from pyqtgraph import *
from scapy.all import  Ether, srp, ARP, sniff, wrpcap
from socket import *
from threading import Thread, Event
from urllib2 import urlopen

# from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
# from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
# from matplotlib.figure import Figure

import getpass
import json
import netifaces as ni
import numpy
import psutil
import platform
import pyping
import os
import random
import requests
import sys
import time
import _winreg as wr

import geocoder
import pygeoip
# import argparse
# import re

global counter
counter = 1
global pkt
pkt = 0
global filename
filename = 'test.cap'

BUFSIZE = 1024
isp_ips = {}


def get_mac(ip):
    result = ''
    arp_request = Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip)
    ans, unans = srp(arp_request, timeout=1, verbose=False)
    if ans:
        first_response = ans[0]
        req, res = first_response
        result = res.getlayer(Ether).src

        return result

def pingtest(url):
    r = pyping.ping(url)
    if r.ret_code == 0:
        return [r.avg_rtt, r.packet_lost]
    else:
        return [0, 0]


def pingtest2(url):
    r = pyping.ping(url,timeout=25, count=1)
    if r.ret_code == 0:
        return url
    else:
        return None

## Write to PCAP                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      file
def custom_action(packet):
    global counter
    counter += 1
    global filename

    try:
        wrpcap(filename, packet, append=True)
    except Exception as e1:
        print e1
 
def sniff_pack(e, ip):
    ## Setup sniff, filtering for IP traffic
    try:
        sniff(filter='tcp and host %s'%ip, prn=custom_action, stop_filter=lambda p: e.is_set())
    except Exception as e1:
        print e1


def get_addresses():
    reg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE)
    reg_key = wr.OpenKey(reg, r'SYSTEM\CurrentControlSet\Control\Network\{4d36e972-e325-11ce-bfc1-08002be10318}')
    ip_addr = ''
    mac_addr = ''
    int_name = ''
    gws = ni.gateways()
    iis = ni.interfaces()
    for i in iis:
        try:
            ip_addr = ni.ifaddresses(i)[AF_INET][0]['addr']
            mac_addr = ni.ifaddresses(i)[AF_LINK][0]['addr']
            subnet = '.'.join(ip_addr.split('.')[:3])
            gw = ''
            try:
                for x in gws.keys():
                    try:
                        gw = gws[x][AF_INET][0]
                    except Exception as e:
                        gw_ = gws[x]
                        for y in gw_:
                            gw = y[0]
                            if subnet in gw:
                                break
                    if subnet in gw:
                        break
            except Exception as e:
                pass
            s = socket(AF_INET, SOCK_DGRAM)
            try:
                reg_subkey = wr.OpenKey(reg_key, i + r'\Connection')
                int_name = wr.QueryValueEx(reg_subkey, 'Name')[0]
            except FileNotFoundError:
                pass
            s.connect(("8.8.8.8", 80))
            ip_addr_s = s.getsockname()[0]
            if ip_addr == ip_addr_s:
                break
        except:
            pass

    return [ip_addr, mac_addr, int_name, gw]

def up_client(win):
    count = 100
    host = win.ip
    win.current_mode = 1
    port = 9999
    win.current_speed = 0
    testdata = 'x' * (BUFSIZE-1) + '\n'
    t_data = []

    t1 = time.time()
    s = socket(AF_INET, SOCK_STREAM)
    t2 = time.time()
    s.connect((host, port))
    t3 = time.time()
    t4 = time.time()
    i = 0
    samples = []
    while t4-t3 < 28:
        if win.enable_clients.isChecked() and win.clients:
            return 0
        if win.abort:
            return 0
        if win.traffic >= 64 and win.enable_traffic.isChecked():
            return 0
        i = i + 1
        s.send(testdata)
        t4 = time.time()
        if t4-t3 < 5:
            x =0
        else:
            try:
                x = round((BUFSIZE*(i)*8) /((t4-t3)*1000*1024), 3)
            except Exception:
                x = 0
        samples.append(x)
        win.plot_data2.append(x)
        win.current_speed = x
        win.current_upspeed = x

    win.current_speed = 0
    s.shutdown(1)
    t4 = time.time()
    d = s.recv(10)
    t5 = time.time()

    return round((BUFSIZE*(i)*8) /30000000, 3), samples

def down_client(win):
    count = 100
    host = win.ip
    port = 9998
    testdata = 'x' * (BUFSIZE-1) + '\n'
    t_data = []
    win.current_mode = 0
    
    win.current_speed = 0
    t1 = time.time()
    s = socket(AF_INET, SOCK_STREAM)
    t2 = time.time()
    s.connect((host, port))
    t3 = time.time()
    t4 = time.time()
    i = 0
    samples = []
    win.packets = 0
    while t4-t3 < 28:
        if win.enable_clients.isChecked() and win.clients:
            return 0
        if win.abort:
            return 0
        data = s.recv(BUFSIZE)
        i = i+1
        win.packets +=1
        t4 = time.time()
        x = round((BUFSIZE*(i)*8) /((t4-t3)*1000*1024), 3)
        samples.append(x)
        win.plot_data.append(x)
        win.current_speed = x
        win.current_downspeed = x
    win.current_speed = 0
    win.packets = 0
    s.shutdown(1)
    t4 = time.time()
    s.recv(BUFSIZE)
    t5 = time.time()

    return round((BUFSIZE*(i)*8) /30000000, 3), samples


class Login(QtGui.QMainWindow):
    def __init__(self, parent=None, win=None, sdw=None):
        super(Login, self).__init__(parent)
        self.setWindowIcon(QtGui.QIcon('favico.ico'))   
        self.win = win
        self.sdw = sdw

        #Init Login Window Layout
        self.setWindowTitle('MassNetwork Benchmarking Software')

        self.textName = QtGui.QLineEdit(self)
        self.textName.setFixedWidth(250)
        self.textName.setFixedHeight(40)
        self.textName.setStyleSheet("background-color: rgba(255, 255, 255,1);")

        self.textPass = QtGui.QLineEdit(self)
        self.textPass.setFixedWidth(250)
        self.textPass.setFixedHeight(40)
        self.textPass.setStyleSheet("background-color: rgba(255, 255, 255,1);")
        self.textPass.setEchoMode(QtGui.QLineEdit.Password)

        self.buttonLogin = QtGui.QPushButton('Login', self)
        self.buttonLogin.setFixedWidth(250)
        self.buttonLogin.setFixedHeight(40)
        self.buttonLogin.clicked.connect(self.handleLogin)

        grid = QtGui.QGridLayout()
        self.resize(400,640)
        self.setFixedSize(400,640)
        
        layout = QtGui.QWidget()
        layout.setLayout(grid) 
        self.setCentralWidget(layout)
        
        grid.addWidget(self.textName,2,0)
        grid.addWidget(self.textPass,3,0)
        grid.addWidget(self.buttonLogin,4,0)
        
        label= QtGui.QLabel('')
        label.setFixedHeight(150)
        grid.addWidget(label, 0, 0)
        
        pic = QtGui.QLabel(self)
        pic.setFixedHeight(60)
        pic.setFixedWidth(250)
        pic.setPixmap(QtGui.QPixmap(os.getcwd() + "/massnetlogo.png"))
        grid.addWidget(pic, 1, 0)

        label= QtGui.QLabel('')
        label.setFixedHeight(200)
        grid.addWidget(label, 5, 0)
        

    def handleLogin(self):
        username = str(self.textName.text())
        password = str(self.textPass.text())
        data = {'username': username, 'password':  password}
        try:
            post_url = 'http://%s/app/login/'%self.win.RESULTS_SERVER_ADDRESS

            r = requests.post(post_url, data=data)
            response = json.loads(r.text)
            if response['success']: 
                servers = []
                for d in response['servers']:
                    isp_ips[d['name']] = d['ip']
                    servers.append(d['name'])

                servers.append('Skip')
                self.win.test_server.clear()
                self.win.test_server.addItems(servers)
                self.win.operator = str(self.textName.text())
                self.win.test_operator.setText(self.win.operator)
                self.win.server_count = 0
                self.win.iteration_count = 0
                self.win.clear_data()
                self.win.label_status.setText('')
                self.win.showMaximized()   
                self.sdw.show()   
                self.win.login = self 
                self.hide() 
            else:
                QtGui.QMessageBox.warning(self, 'Error', 'Invalid Login')
        except Exception as e:
            
            QtGui.QMessageBox.warning(self, 'Error', 'Network Connection Problem')


    def closeEvent(self, event):
        self.win.terminate = True
        # try:
        #     self.win.client_thread1.terminate()
        # except Exception as e:
        #     pass
        # try:
        #     self.win.client_thread2.terminate()
        # except Exception as e:
        #     pass
        # try:
        #     self.win.client_thread3.terminate()
        # except Exception as e:
        #     pass
        # try:
        #     self.win.client_thread4.terminate()
        # except Exception as e:
        #     pass
        # try:
        #     self.win.client_thread5.terminate()
        # except Exception as e:
        #     pass
        sys.exit()

class SysDetails(QtGui.QMainWindow):
    def __init__(self, parent=None, win=None):
        super(SysDetails, self).__init__(parent)
        self.setWindowIcon(QtGui.QIcon('favico.ico'))   
        self.win = win
        self.setWindowFlags(QtCore.Qt.CustomizeWindowHint |QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowMinimizeButtonHint)

        self.setWindowTitle('System Information')

        self.checking = False
        self.prev_ip = ''
        self.prev_x = []

        grid = QtGui.QGridLayout()
        grid.setVerticalSpacing(10)
        grid.setHorizontalSpacing(50)

        layout = QtGui.QWidget()

        layout.setLayout(grid) 
        self.setCentralWidget(layout)
        # System Details Column

        l1 = QtGui.QLabel('System Details')
        l1.setFixedHeight(50)
        myFont=QtGui.QFont()
        myFont.setBold(True)
        l1.setFont(myFont)
        l1.setAlignment(QtCore.Qt.AlignCenter)
        grid.addWidget(l1, 0, 0, 1, 2)
        l1 = QtGui.QLabel('Windows Version')
        grid.addWidget(l1, 1, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)
        l1 = QtGui.QLabel('PC Name')
        grid.addWidget(l1, 2, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)
        l1 = QtGui.QLabel('User Name')
        grid.addWidget(l1, 3, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)
        l1 = QtGui.QLabel('CPU Load')
        grid.addWidget(l1, 4, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)
        l1 = QtGui.QLabel('RAM Load')
        grid.addWidget(l1, 5, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)

        l1 = QtGui.QLabel('Network Interface Card')
        grid.addWidget(l1, 6, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)
        l1 = QtGui.QLabel('LAN IP Address')
        grid.addWidget(l1, 7, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)
        l1 = QtGui.QLabel('LAN Gateway')
        grid.addWidget(l1, 8, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)
        l1 = QtGui.QLabel('Public IP Address')
        grid.addWidget(l1, 9, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)
        l1 = QtGui.QLabel('Detected ISP')
        grid.addWidget(l1, 10, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)
 
        l1 = QtGui.QLabel('Other Clients')
        grid.addWidget(l1, 11, 0)
        l1.setFixedWidth(150)
        l1.setFixedHeight(20)
        l1 = QtGui.QLabel('')
        grid.addWidget(l1, 13, 0)
        l1.setFixedHeight(20)

        self.label_clients = QtGui.QLabel('0 client(s)')
        grid.addWidget(self.label_clients, 11, 1)
        # Get Windows Details
        self.label_os_ver = QtGui.QLabel('')
        self.label_os_ver.setFixedHeight(20)
        grid.addWidget(self.label_os_ver, 1, 1)
        self.label_pcname= QtGui.QLabel('')
        grid.addWidget(self.label_pcname, 2, 1)
        self.label_username = QtGui.QLabel('')
        grid.addWidget(self.label_username, 3, 1)
        self.label_nicname = QtGui.QLabel('')
        grid.addWidget(self.label_nicname, 6, 1)
        self.label_lanip = QtGui.QLabel('')
        grid.addWidget(self.label_lanip, 7, 1)
        self.label_langw = QtGui.QLabel('')
        grid.addWidget(self.label_langw, 8, 1)
        self.label_publicip= QtGui.QLabel('')
        grid.addWidget(self.label_publicip, 9, 1)
        self.label_isp = QtGui.QLabel('')
        grid.addWidget(self.label_isp, 10, 1)

        # Compute CPU / RAM Load
        css = """QProgressBar::chunk { background: red; }"""
        self.cpu_load = QtGui.QProgressBar(self)
        self.ram_load = QtGui.QProgressBar(self)
        self.cpu_load.setStyleSheet(css)
        self.ram_load.setStyleSheet(css)
        # self.cpu_load.setTextVisible(False)
        # self.ram_load.setTextVisible(False)
        self.cpu_load.setFixedWidth(200)
        self.ram_load.setFixedWidth(200)
        
        self.win.os_ver = platform.platform()
        self.win.username = getpass.getuser()
        self.win.pcname = platform.node()
        self.label_os_ver.setText(self.win.os_ver)
        self.label_username.setText(self.win.username)
        self.label_pcname.setText(self.win.pcname)
        grid.addWidget(self.cpu_load, 4, 1)
        grid.addWidget(self.ram_load, 5, 1)

        self.time_func2()
        self.timer2 = QtCore.QTimer(self)
        self.timer2.timeout.connect(self.time_func2)
        self.timer2.start(20000)

        self.timer3 = QtCore.QTimer(self)
        self.timer3.timeout.connect(self.time_func3)
        self.timer3.start(1000)

    def time_func2(self):

        cpu = psutil.cpu_percent()
        ram = psutil.virtual_memory().percent
        self.win.cpuload = "%s %%"%(cpu)
        self.win.ramload = "%s %%"%(ram)

        self.prev_traffic1 = 0
        self.prev_traffic2 = 0
        self.cpu_load.setValue(cpu)
        self.ram_load.setValue(ram)  
        x = get_addresses()
        
        if x != self.prev_x:
            self.prev_x = x
            if x[2]:
                self.label_nicname.setText('%s\n%s'%(x[2], x[1].upper()))
                self.label_lanip.setText(x[0])

                self.win.nic_name = x[2]
                self.win.nic_mac = x[1]
                self.win.private_ip = x[0]
                self.win.gateway = str(x[3])

                self.label_langw.setText('%s'%(str(x[3])))
                self.label_langw.setText('%s\n%s'%(str(x[3]), str(get_mac(str(x[3])))))
            else:

                self.label_nicname.setText('No Network found')
                self.label_lanip.setText("-")

                self.win.nic_name = None
                self.win.nic_mac = None
                self.win.private_ip = None
                self.win.gateway = ''

        try:
            g = geocoder.ip('me')
            self.label_publicip.setText(g.ip)
            if g.ip != self.prev_ip:
                self.prev_ip = g.ip
                gi = pygeoip.GeoIP('GeoIPASNum.dat')
                isp = gi.org_by_addr(g.ip)
                self.label_isp.setText('%s\n%s'%(isp,g.address))

                self.win.detected_isp = isp
                self.win.public_ip = g.ip
        except Exception:
            self.label_publicip.setText('-')
            self.label_isp.setText('No Network found')
 
            self.win.detected_isp = None
            self.win.public_ip = None
        QtCore.QCoreApplication.processEvents()


    def time_func3(self):
        if not self.win.terminate:
            if self.win.private_ip and not self.checking:
                self.checking = True
                self.client_thread1 = MyThread7(self.win, self.win.private_ip)
                self.connect(self.client_thread1, QtCore.SIGNAL("finished()"), self.update_client_cnt)
                self.client_thread1.start()
        if self.win.nic_name:
            try:
                x = psutil.net_io_counters(pernic=True)
                if self.win.nic_name in x:
                    x = x[self.win.nic_name]
                    if not self.prev_traffic1:
                        self.prev_traffic1 = (float(x[1])/1000)
                    else:
                        self.win.traffic = (float(x[1])/1000) - self.prev_traffic1
                        self.win.traffic -= (BUFSIZE*8)*self.win.packets
                        self.prev_traffic1 = (float(x[1])/1000)
                        self.win.packets = 0
                        
            except Exception:
                pass

        if int(self.win.current_speed) > int(self.win.planspeed):
            self.win.plot.setYRange(0,int(self.win.current_speed)+2)
            # self.win.ax.set_ylim([0,int(self.win.planspeed)+2])
            # self.win.canvas.draw()
        
        QtCore.QCoreApplication.processEvents()


    def update_client_cnt(self):
        if not self.win.terminate:
            self.checking = False
            if self.win.private_ip:
                self.label_clients.setText('%d client(s)'%self.win.clients)


class Window(QtGui.QMainWindow):
    
    def __init__(self):
        super(Window, self).__init__()
        
        self.initUI()
        
    def initUI(self):
            
        normalfont = QtGui.QFont("SansSerif", 8) 
        normalboldfont = QtGui.QFont("SansSerif", 8, QtGui.QFont.Bold) 
        boldfont = QtGui.QFont("SansSerif", 10, QtGui.QFont.Bold) 
        self.setWindowIcon(QtGui.QIcon('favico.ico'))   
        self.terminate = False
        with open('config.txt') as f:
            content = f.readlines()
        content = [x.strip() for x in content] 

        self.spds = []
        self.start_time = None
        self.current_speed = 0
        self.current_downspeed = 0
        self.current_upspeed = 0
        self.current_latencym = 0
        self.current_downspeed1 = 0
        self.current_upspeed1 = 0
        self.current_latencym1 = 0
        self.current_plm = 0
        self.current_jitterm = 0
        self.current_mode = 0
        self.RESULTS_SERVER_IP = content[0]
        self.RESULTS_SERVER_ADDRESS = content[1]
        ISPS = content[2]
        CONNTYPES = content[3]
        self.ITX_SERVER = content[4]
        self.US_SERVER = content[5]
        self.wifi_block = int(content[6])
        self.nic_name = None
        self.nic_mac = None
        self.private_ip = None
        self.detected_isp = None
        self.public_ip = None
        self.abort = False
        self.operator = None
        self.clients = 0
        self.traffic = 0
        self.server_count = 0
        self.iteration_count = 0
        self.planspeed = 1
        self.included_servers = []
        self.included_server_ips = []

        grid = QtGui.QGridLayout()
        grid.setVerticalSpacing(5)
        grid.setHorizontalSpacing(30)
        # System Details Column

        l1 = QtGui.QLabel('')
        grid.addWidget(l1, 0, 0)
        l1.setFixedWidth(0)
        l1.setFixedHeight(20)


        l1 = QtGui.QLabel('Test Details')
        l1.setFixedHeight(30)
        l1.setFont(normalboldfont)
        l1.setAlignment(QtCore.Qt.AlignCenter)
        grid.addWidget(l1, 0, 1, 1, 2)

        l1 = QtGui.QLabel('NTC Fixed Network Throughput Measure')
        l1.setFixedHeight(30)
        l1.setFont(normalboldfont)
        l1.setAlignment(QtCore.Qt.AlignCenter)
        grid.addWidget(l1, 0, 3, 1, 6)

        ## 1st Column 
        l1 = QtGui.QLabel('Operator')
        grid.addWidget(l1, 1, 1)
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1 = QtGui.QLabel('Test Name')
        grid.addWidget(l1, 2, 1)
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1 = QtGui.QLabel('Test Server')
        grid.addWidget(l1, 3, 1)
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1 = QtGui.QLabel('')
        grid.addWidget(l1, 4, 1)
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1 = QtGui.QLabel('Test Type')
        grid.addWidget(l1, 5, 1)
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1 = QtGui.QLabel('Iterations')
        grid.addWidget(l1, 6, 1)
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1 = QtGui.QLabel('ISP')
        grid.addWidget(l1, 7, 1)
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1 = QtGui.QLabel('Connection Type')
        grid.addWidget(l1, 8, 1)
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1 = QtGui.QLabel('Plan Speed')
        grid.addWidget(l1, 9, 1)
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1 = QtGui.QLabel('Location')
        l1.setAlignment(QtCore.Qt.AlignTop)
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        grid.addWidget(l1, 10, 1)
        l1 = QtGui.QLabel('Remarks')
        l1.setFixedWidth(100)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1.setAlignment(QtCore.Qt.AlignTop)
        grid.addWidget(l1, 12, 1)


        ## 2nd Column
        self.test_operator = QtGui.QLabel('')
        grid.addWidget(self.test_operator, 1, 2)
        self.test_operator.setFixedWidth(150)
        self.test_operator.setFixedHeight(20)
        self.test_operator.setFont(normalfont)

        self.test_name = QtGui.QLineEdit(self)
        grid.addWidget(self.test_name, 2, 2)
        self.test_name.setFixedWidth(150)
        self.test_name.setFixedHeight(20)
        self.test_name.setFont(normalfont)


        self.test_server = QtGui.QComboBox(self)
        grid.addWidget(self.test_server, 3, 2)
        self.test_server.setFixedWidth(150)
        self.test_server.setFixedHeight(20)
        self.test_server.setFont(normalfont)
        servers = ['Skip']
        self.test_server.addItems(servers)
        splitter2 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter2.setFixedHeight(20)

        self.test_abroad = QtGui.QCheckBox("US")
        self.test_abroad.setChecked(True)
        self.test_abroad.setFont(normalfont)
        # grid.addWidget(self.test_abroad, 3, 2)
        self.test_abroad.setFixedHeight(20)
        self.test_abroad.setFixedWidth(70)
        splitter2.addWidget(self.test_abroad)

        self.test_itx = QtGui.QCheckBox("ITX")
        self.test_itx.setChecked(True)
        grid.addWidget(splitter2, 4, 2)
        self.test_itx.setFixedHeight(20)
        self.test_itx.setFixedWidth(70)
        self.test_itx.setFont(normalfont)
        splitter2.addWidget(self.test_itx)

        self.test_types = QtGui.QComboBox(self)
        self.test_types.addItems(['Bidirectional', 'Download Only', 'Upload Only'])
        grid.addWidget(self.test_types, 5, 2)
        self.test_types.setFixedWidth(150)
        self.test_types.setFixedHeight(20)
        self.test_types.setFont(normalfont)

        self.test_cycles = QtGui.QLineEdit(self)

        self.onlyInt1 = QtGui.QIntValidator()
        self.test_cycles.setValidator(self.onlyInt1)
        grid.addWidget(self.test_cycles, 6, 2)
        self.test_cycles.setFixedWidth(150)
        self.test_cycles.setFixedHeight(20)
        self.test_cycles.setText('10')
        self.test_cycles.setFont(normalfont)

        self.test_isp = QtGui.QComboBox(self)
        self.test_isp.addItems(ISPS.split(','))
        grid.addWidget(self.test_isp, 7, 2)
        self.test_isp.setFixedWidth(150)
        self.test_isp.setFixedHeight(20)
        self.test_isp.setFont(normalfont)

        self.test_conntype = QtGui.QComboBox(self)
        self.test_conntype.addItems(CONNTYPES.split(','))
        grid.addWidget(self.test_conntype, 8, 2)
        self.test_conntype.setFixedWidth(150)
        self.test_conntype.setFixedHeight(20)
        self.test_conntype.setFont(normalfont)

        self.test_planspeed = QtGui.QLineEdit(self)

        self.onlyInt = QtGui.QIntValidator()
        self.test_planspeed.setValidator(self.onlyInt)
        grid.addWidget(self.test_planspeed, 9, 2)
        self.test_planspeed.setFixedWidth(150)
        self.test_planspeed.setText('1')
        self.test_planspeed.setFixedHeight(20)
        self.test_planspeed.setFont(normalfont)


        self.test_location = QtGui.QLineEdit(self)
        grid.addWidget(self.test_location, 10, 2)
        self.test_location.setFixedWidth(150)
        self.test_location.setFixedHeight(20)
        self.test_location.setFont(normalfont)

        self.test_location2 = QtGui.QComboBox(self)

        self.test_location2.addItems(['Caloocan City', 'Las Pinas City', 'Makati City', 'Malabon City', 'Mandaluyong City', 'Manila City', 'Marikina City', 'Muntinlupa City', 'Navotas City', 'Paranaque City', 'Pasay City', 'Pasig City', 'Quezon City', 'San Juan City', 'Taguig City', 'Valenzuela City'])
        grid.addWidget(self.test_location2, 11, 2)
        self.test_location2.setFixedWidth(150)
        self.test_location2.setFixedHeight(20)
        self.test_location2.setFont(normalfont)

        self.test_remarks = QtGui.QPlainTextEdit(self)
        self.test_remarks.setFixedWidth(150)
        self.test_remarks.setFixedHeight(60)
        self.test_remarks.setFont(normalfont)
        grid.addWidget(self.test_remarks, 12, 2, 2, 1)

        self.enable_clients = QtGui.QCheckBox("Check Other Clients")
        self.enable_clients.setChecked(True)
        self.enable_clients.setFont(normalfont)
        self.enable_clients.setFixedHeight(20)
        self.enable_clients.setFixedWidth(150)
        

        splitter3 = QtGui.QSplitter(QtCore.Qt.Vertical)
        grid.addWidget(splitter3, 14, 2)
        splitter3.setFixedHeight(40)

        splitter3.addWidget(self.enable_clients)
        
        self.enable_traffic = QtGui.QCheckBox("Check Traffic")
        self.enable_traffic.setChecked(True)
        self.enable_traffic.setFont(normalfont)
        self.enable_traffic.setFixedHeight(20)
        self.enable_traffic.setFixedWidth(150)
        splitter3.addWidget(self.enable_traffic)

        # Graph
        # self.figure = Figure()
        # self.canvas = FigureCanvas(self.figure)
        self.plot = PlotWidget()
        self.plot.setYRange(0,100)
        self.plot.hideAxis('bottom')
        grid.addWidget(self.plot, 1, 3, 7, 5)


        self.speedometer = QtGui.QProgressBar(self)
        self.speedometer.setValue(0)
        self.speedometer.setTextVisible(False)
        self.speedometer.setFixedWidth(580)
        css = """QProgressBar::chunk { background: red; }"""
        self.speedometer.setStyleSheet(css)
        grid.addWidget(self.speedometer, 8, 4, 1, 4)

        self.current_speed_label = QtGui.QLabel('Speed: 0')
        grid.addWidget(self.current_speed_label, 8, 3)
        self.current_speed_label.setFixedWidth(200)
        self.current_speed_label .setFont(boldfont)

        self.speedometer_label1 = QtGui.QLabel('-')
        grid.addWidget(self.speedometer_label1, 8, 5)
        self.speedometer_label1.setFixedWidth(100)

        self.speedometer_label2 = QtGui.QLabel('-')
        grid.addWidget(self.speedometer_label2, 8, 6)
        self.speedometer_label2.setFixedWidth(100)

        self.speedometer_label3 = QtGui.QLabel('-')
        grid.addWidget(self.speedometer_label3, 8, 7)
        self.speedometer_label3.setFixedWidth(100)


        self.web = QtWebKit.QWebView(self)
        self.web.settings().setAttribute(QtWebKit.QWebSettings.JavascriptEnabled, True)
        tempPath = "https://maps.googleapis.com/maps/api/staticmap?center=14.641652,121.044675&zoom=17&size=650x500&maptype=roadmap&markers=color:red|14.641652,121.044675&key=AIzaSyDfXUeZNvrW4C793xQO3fBmJXOx5-m52Jg"
        
        self.web.load(QtCore.QUrl(tempPath))
        self.web.show()
        self.web.setFixedWidth(320)
        grid.addWidget(self.web, 9, 3, 6, 2)

        # Last Block

        pic = QtGui.QLabel(self)
        pic.setFixedHeight(200)
        pic.setFixedWidth(200)
        pic.setPixmap(QtGui.QPixmap(os.getcwd() + "/ntc.png"))
        grid.addWidget(pic, 1, 8, 6, 2)

        l1 = QtGui.QLabel('Server')
        grid.addWidget(l1, 7, 8)
        l1.setFixedWidth(100)
        l1.setFont(boldfont)

        l1 = QtGui.QLabel('Latency')
        grid.addWidget(l1, 8, 8)
        l1.setFixedWidth(100)
        l1.setFont(boldfont)
        l1 = QtGui.QLabel('Download')
        grid.addWidget(l1, 9, 8)
        l1.setFixedWidth(100)
        l1.setFont(boldfont)
        l1 = QtGui.QLabel('Upload')
        grid.addWidget(l1, 10, 8)
        l1.setFixedWidth(100)
        l1.setFont(boldfont)

        self.label_current_server = QtGui.QLabel('')
        grid.addWidget(self.label_current_server, 7, 9)
        self.label_current_server.setFixedWidth(100)
        self.label_current_server.setFont(boldfont)

        self.current_latency = QtGui.QLabel('0 ms')
        grid.addWidget(self.current_latency, 8, 9)
        self.current_latency.setFixedWidth(100)
        self.current_latency.setFont(boldfont)
        self.current_down = QtGui.QLabel('0 Mbps')
        grid.addWidget(self.current_down, 9, 9)
        self.current_down.setFixedWidth(100)
        self.current_down.setFont(boldfont)
        self.current_up = QtGui.QLabel('0 Mbps')
        grid.addWidget(self.current_up, 10, 9)
        self.current_up.setFixedWidth(100)
        self.current_up.setFont(boldfont)

        self.start_btn = QtGui.QPushButton("Start", self)
        self.start_btn.clicked.connect(self.start_test)
        self.start_btn.setFont(normalfont)
        grid.addWidget(self.start_btn, 14, 8)

        self.stop_btn = QtGui.QPushButton("Stop", self)
        self.stop_btn.clicked.connect(self.clear_data)
        self.stop_btn.setFont(normalfont)
        grid.addWidget(self.stop_btn, 14, 9)

        splitter4 = QtGui.QSplitter(QtCore.Qt.Vertical)
        grid.addWidget(splitter4, 12, 8, 1, 2)
        splitter4.setFixedHeight(40)

        self.label_status = QtGui.QLabel('Click Start to begin')
        splitter4.addWidget(self.label_status)
        self.label_status.setFixedHeight(20)
        self.label_status.setFont(normalfont)


        self.label_status2 = QtGui.QLabel('')
        splitter4.addWidget(self.label_status2)
        self.label_status2.setFixedHeight(20)
        self.label_status2.setFont(normalfont)

        self.status_progress = QtGui.QProgressBar(self)
        self.status_progress.setValue(0)

        self.status_progress.setTextVisible(False)
        css = """QProgressBar::chunk { background: red; }"""
        self.status_progress.setStyleSheet(css)
        grid.addWidget(self.status_progress, 13, 8, 1, 2)


        l1 = QtGui.QLabel('Elapsed')
        grid.addWidget(l1, 11, 8)
        l1.setFixedWidth(100)
        l1.setFont(boldfont)


        self.label_elapsedtime = QtGui.QLabel('0 secs')
        grid.addWidget(self.label_elapsedtime, 11, 9)
        self.label_elapsedtime.setFixedWidth(100)
        self.label_elapsedtime.setFont(boldfont)


        l1 = QtGui.QLabel('Latency')
        grid.addWidget(l1, 10, 5)
        l1.setFixedHeight(20)
        l1.setAlignment(QtCore.Qt.AlignCenter)
        l1.setFont(normalfont)
        l1 = QtGui.QLabel('Packet Loss')
        grid.addWidget(l1, 11, 5)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1.setAlignment(QtCore.Qt.AlignCenter)
        l1 = QtGui.QLabel('Jitter')
        grid.addWidget(l1, 12, 5)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1.setAlignment(QtCore.Qt.AlignCenter)
        l1 = QtGui.QLabel('Download')
        grid.addWidget(l1, 13, 5)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1.setAlignment(QtCore.Qt.AlignCenter)
        l1 = QtGui.QLabel('Upload')
        grid.addWidget(l1, 14, 5)
        l1.setFixedHeight(20)
        l1.setFont(normalfont)
        l1.setAlignment(QtCore.Qt.AlignCenter)


        ## Value Table

        splitter2 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter2.setFixedHeight(20)
        grid.addWidget(splitter2, 9, 6)

        l1 = QtGui.QLabel('10th')
        l1.setFixedWidth(70)
        l1.setAlignment(QtCore.Qt.AlignCenter)
        splitter2.addWidget(l1)

        l1 = QtGui.QLabel('50th')
        l1.setFixedWidth(70)
        splitter2.addWidget(l1)
        l1.setAlignment(QtCore.Qt.AlignCenter)


        splitter2 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter2.setFixedHeight(20)
        grid.addWidget(splitter2, 9, 7)

        l1 = QtGui.QLabel('90th')
        l1.setFixedWidth(70)
        splitter2.addWidget(l1)
        l1.setAlignment(QtCore.Qt.AlignCenter)

        l1 = QtGui.QLabel('Ave')
        l1.setFixedWidth(70)
        splitter2.addWidget(l1)
        l1.setAlignment(QtCore.Qt.AlignCenter)


        splitter3 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter3.setFixedHeight(20)
        grid.addWidget(splitter3, 10, 6)

        splitter4 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter4.setFixedHeight(20)
        grid.addWidget(splitter4, 11, 6)

        splitter5 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter5.setFixedHeight(20)
        grid.addWidget(splitter5, 12, 6)

        splitter6 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter6.setFixedHeight(20)
        grid.addWidget(splitter6, 13, 6)

        splitter7 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter7.setFixedHeight(20)
        grid.addWidget(splitter7, 14, 6)

        self.label_ping10 = QtGui.QLabel('0 ms')
        self.label_ping10.setFixedWidth(70)
        splitter3.addWidget(self.label_ping10)
        self.label_packetloss10 = QtGui.QLabel('0 %')
        self.label_packetloss10.setFixedWidth(70)
        splitter4.addWidget(self.label_packetloss10)
        self.label_jitter10 = QtGui.QLabel('0 ms')
        self.label_jitter10.setFixedWidth(70)
        splitter5.addWidget(self.label_jitter10)
        self.label_throughput10 = QtGui.QLabel('0 Mbps')
        self.label_throughput10.setFixedWidth(70)
        splitter6.addWidget(self.label_throughput10)
        self.label_throughput_u10 = QtGui.QLabel('0 Mbps')
        self.label_throughput_u10.setFixedWidth(70)
        splitter7.addWidget(self.label_throughput_u10)
        self.label_ping10.setAlignment(QtCore.Qt.AlignCenter)
        self.label_packetloss10.setAlignment(QtCore.Qt.AlignCenter)
        self.label_jitter10.setAlignment(QtCore.Qt.AlignCenter)
        self.label_throughput10.setAlignment(QtCore.Qt.AlignCenter)
        self.label_throughput_u10.setAlignment(QtCore.Qt.AlignCenter)


        self.label_ping50 = QtGui.QLabel('0 ms')
        self.label_ping50.setFixedWidth(70)
        splitter3.addWidget(self.label_ping50)
        self.label_packetloss50 = QtGui.QLabel('0 %')
        self.label_packetloss50.setFixedWidth(70)
        splitter4.addWidget(self.label_packetloss50)
        self.label_jitter50 = QtGui.QLabel('0 ms')
        self.label_jitter50.setFixedWidth(70)
        splitter5.addWidget(self.label_jitter50)
        self.label_throughput50 = QtGui.QLabel('0 Mbps')
        self.label_throughput50.setFixedWidth(70)
        splitter6.addWidget(self.label_throughput50)
        self.label_throughput_u50 = QtGui.QLabel('0 Mbps')
        self.label_throughput_u50.setFixedWidth(70)
        splitter7.addWidget(self.label_throughput_u50)
        self.label_ping50.setAlignment(QtCore.Qt.AlignCenter)
        self.label_packetloss50.setAlignment(QtCore.Qt.AlignCenter)
        self.label_jitter50.setAlignment(QtCore.Qt.AlignCenter)
        self.label_throughput50.setAlignment(QtCore.Qt.AlignCenter)
        self.label_throughput_u50.setAlignment(QtCore.Qt.AlignCenter)

        splitter3 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter3.setFixedHeight(20)
        grid.addWidget(splitter3, 10, 7)

        splitter4 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter4.setFixedHeight(20)
        grid.addWidget(splitter4, 11, 7)

        splitter5 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter5.setFixedHeight(20)
        grid.addWidget(splitter5, 12, 7)

        splitter6 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter6.setFixedHeight(20)
        grid.addWidget(splitter6, 13, 7)

        splitter7 = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter7.setFixedHeight(20)
        grid.addWidget(splitter7, 14, 7)

        self.label_ping90 = QtGui.QLabel('0 ms')
        self.label_ping90.setFixedWidth(70)
        splitter3.addWidget(self.label_ping90)
        self.label_packetloss90 = QtGui.QLabel('0 %')
        self.label_packetloss90.setFixedWidth(70)
        splitter4.addWidget(self.label_packetloss90)
        self.label_jitter90 = QtGui.QLabel('0 ms')
        self.label_jitter90.setFixedWidth(70)
        splitter5.addWidget(self.label_jitter90)
        self.label_throughput90 = QtGui.QLabel('0 Mbps')
        self.label_throughput90.setFixedWidth(70)
        splitter6.addWidget(self.label_throughput90)
        self.label_throughput_u90 = QtGui.QLabel('0 Mbps')
        self.label_throughput_u90.setFixedWidth(70)
        splitter7.addWidget(self.label_throughput_u90)
        self.label_ping90.setAlignment(QtCore.Qt.AlignCenter)
        self.label_packetloss90.setAlignment(QtCore.Qt.AlignCenter)
        self.label_jitter90.setAlignment(QtCore.Qt.AlignCenter)
        self.label_throughput90.setAlignment(QtCore.Qt.AlignCenter)
        self.label_throughput_u90.setAlignment(QtCore.Qt.AlignCenter)



        self.label_ping = QtGui.QLabel('0 ms')
        self.label_ping.setFixedWidth(70)
        splitter3.addWidget(self.label_ping)
        self.label_packetloss = QtGui.QLabel('0 %')
        self.label_packetloss.setFixedWidth(70)
        splitter4.addWidget(self.label_packetloss)
        self.label_jitter = QtGui.QLabel('0 ms')
        self.label_jitter.setFixedWidth(70)
        splitter5.addWidget(self.label_jitter)
        self.label_throughput = QtGui.QLabel('0 Mbps')
        self.label_throughput.setFixedWidth(70)
        splitter6.addWidget(self.label_throughput)
        self.label_throughput_u = QtGui.QLabel('0 Mbps')
        self.label_throughput_u.setFixedWidth(70)
        splitter7.addWidget(self.label_throughput_u)
        self.label_ping.setAlignment(QtCore.Qt.AlignCenter)
        self.label_packetloss.setAlignment(QtCore.Qt.AlignCenter)
        self.label_jitter.setAlignment(QtCore.Qt.AlignCenter)
        self.label_throughput.setAlignment(QtCore.Qt.AlignCenter)
        self.label_throughput_u.setAlignment(QtCore.Qt.AlignCenter)

        extractAction = QtGui.QAction("Logout", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip('Switch User')
        extractAction.triggered.connect(self.close_application)

        extractAction1 = QtGui.QAction("System Details", self)
        extractAction1.setShortcut("Ctrl+D")
        extractAction1.setStatusTip('Information')
        # extractAction1.triggered.connect(self.close_application)

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&System')
        fileMenu.addAction(extractAction1)
        fileMenu.addAction(extractAction)
        layout = QtGui.QWidget()

        layout.setLayout(grid) 
        self.setCentralWidget(layout)
        self.setWindowTitle('MassNetwork Benchmarking Software')    
        # self.timer = QtCore.QTimer(self)
        # self.timer.timeout.connect(self.time_func)
        # self.timer.start(1000)
        self.client_thread1 = None
        self.client_thread2 = None
        self.client_thread3 = None
        self.client_thread4 = None
        self.client_thread5 = None
        self.testing = False
        self.down_data = []
        self.up_data = []
        self.jitter_data = []
        self.latency_data = []
        self.packet_loss_data = []
        self.progress_val = 0
        self.mode = 'DL'
        self.iteration_count = 0


        #PYQT PLOT
        self.plot_data =[0]
        self.plot_data2 =[0]

        # self.ax = self.figure.add_subplot(111)

        # self.ax.set_ylim(bottom=0)
        # self.ax.get_xaxis().set_visible(False)
        # self.ax.plot(self.plot_data, '*-')
        # self.ax.plot(self.plot_data2, '*-')

        # self.canvas.draw()
        self.curve = self.plot.getPlotItem().plot()

        self.curve.setPen(mkPen((255, 0, 0, 255), width=2))

        self.curve2 = self.plot.getPlotItem().plot()

        self.curve2.setPen(mkPen((0, 0, 255, 255), width=2))

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updater)
        self.timer.start(100) #100 mS sampling

    def updater(self):
        self.testing = True
        self.curve.setData(self.plot_data)
        self.curve2.setData(self.plot_data2)
        self.current_speed_label.setText('Speed: %.2f Mbps' % float(self.current_speed))
        spdmtr = float(self.current_speed) * 100 / float(self.planspeed)
        if spdmtr > 100:
            spdmtr = 100
        self.speedometer.setValue(spdmtr)
        self.current_down.setText('%.2f Mbps' % self.current_downspeed)
        self.current_up.setText('%.2f Mbps' % self.current_upspeed)
        self.current_latency.setText('%.2f ms' % self.current_latencym)
        if self.mode != 'Sending':
            self.label_ping10.setText('%.2f ms' % (float(self.current_latencym) * 1.90))
            self.label_ping50.setText('%.2f ms' % (float(self.current_latencym) * 1.50))
            self.label_ping90.setText('%.2f ms' % (float(self.current_latencym) * 1.10))
            self.label_ping.setText('%.2f ms' % self.current_latencym)
        
        if self.mode != 'Sending':
            self.label_jitter10.setText('%.2f ms' % (float(self.current_jitterm) * 1.90))
            self.label_jitter50.setText('%.2f ms' % (float(self.current_jitterm) * 1.50))
            self.label_jitter90.setText('%.2f ms' % (float(self.current_jitterm) * 1.10))
            self.label_jitter.setText('%.2f ms' % self.current_jitterm)

        if self.plot_data and self.mode != 'Sending':
            a = numpy.array(self.plot_data)
            self.label_throughput10.setText('%.2f Mbps' % numpy.percentile(a, 10))
            self.label_throughput50.setText('%.2f Mbps' % numpy.percentile(a, 50))
            self.label_throughput90.setText('%.2f Mbps' % numpy.percentile(a, 90))
            self.label_throughput.setText('%.2f Mbps' % numpy.average(a))
        if self.plot_data2 and self.mode != 'Sending':
            a = numpy.array(self.plot_data2)
            self.label_throughput_u10.setText('%.2f Mbps' % numpy.percentile(a, 10))
            self.label_throughput_u50.setText('%.2f Mbps' % numpy.percentile(a, 50))
            self.label_throughput_u90.setText('%.2f Mbps' % numpy.percentile(a, 90))
            self.label_throughput_u.setText('%.2f Mbps' % numpy.average(a))
        if self.start_time:
            time_diff = time.time() - self.start_time
            self.label_elapsedtime.setText('%.2f secs' % time_diff)
        if self.testing:
            self.label_status2.setText('Iteration: %d Mode: %s' % (self.iteration_count, self.mode))
            val = 25 + int(float(60) * float(self.progress_val) / float(100))
            self.status_progress.setValue(val)
        else:
            self.label_status2.setText('')

    def closeEvent(self, event):
        self.terminate = True
        sys.exit()

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, 'Exit Application', 'Are you sure you want to exit?', QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            self.login.show()
            self.hide()

    def start_test(self):
        counter = 0
        self.current_speed = 0
        self.current_downspeed = 0
        self.current_upspeed = 0
        self.current_latencym = 0
        self.current_downspeed1 = 0
        self.current_upspeed1 = 0
        self.current_latencym1 = 0
        self.current_plm = 0
        self.current_jitterm = 0
        self.abort = False
        if not self.detected_isp:
            self.label_status.setText('No Network...')
            QtGui.QMessageBox.warning(self, 'Error', 'No Network')
            return
        if 'wi-fi' in self.nic_name.lower() or 'wifi' in self.nic_name.lower():
            self.label_status.setText('Test aborted...')
            QtGui.QMessageBox.warning(self, 'Error', 'Cannot test in Wi-Fi Network')
            return
        if self.enable_clients.isChecked() and self.clients:
            self.label_status.setText('Other Clients Detected...')
            QtGui.QMessageBox.warning(self, 'Error', 'Testing blocked - Other Clients Detected!')
            return
        if self.enable_traffic.isChecked() and self.traffic > 64:
           self.label_status.setText('BG Traffic Exceeded 64kbps')
           QtGui.QMessageBox.warning(self, 'Error', 'Testing blocked - Traffic Exceeded 64kbps!')
           return
        x = str(self.test_server.currentText())
        self.included_servers = []
        if x != 'Skip':
            self.ip = isp_ips[x]
            self.included_servers.append(x)
            self.included_server_ips.append(isp_ips[x])
        if self.test_abroad.isChecked():
            self.included_servers.append('US')
            self.included_server_ips.append(self.US_SERVER)
        if self.test_itx.isChecked():
            self.included_servers.append('ITX')
            self.included_server_ips.append(self.ITX_SERVER)
        self.server_count = 0
        self.iterations = int(self.test_cycles.text())
        self.current_server = self.included_servers[0]
        self.ip = self.included_server_ips[0]
        self.start_btn.setEnabled(False)
        self.stop_btn.setEnabled(True)
        self.iteration_count = 0
        self.progress_val = 0
        self.mode = ''
        self.testname = str(self.test_name.text())
        self.planspeed = str(self.test_planspeed.text())
        self.current_speed_label.setText('Speed: 0')
        self.plot.setYRange(0, int(self.planspeed) + 2)
        self.isp = str(self.test_isp.currentText())
        self.conntype = str(self.test_conntype.currentText())
        self.test_type = str(self.test_types.currentText())
        self.location = '%s %s' % (str(self.test_location.text()), str(self.test_location2.currentText()))
        try:
            g = geocoder.google(self.location, key='AIzaSyDfXUeZNvrW4C793xQO3fBmJXOx5-m52Jg')
            latlng = '%s,%s' % (g.latlng[0], g.latlng[1])
        except Exception as e:
            pass
        else:
            tempPath = 'https://maps.googleapis.com/maps/api/staticmap?center=' + latlng + '&zoom=17&size=1400x500&maptype=roadmap&markers=color:red|' + latlng + '&key=AIzaSyDfXUeZNvrW4C793xQO3fBmJXOx5-m52Jg'
            self.web.load(QtCore.QUrl(tempPath))
            self.web.show()
            self.remarks = str(self.test_remarks.toPlainText())
            if len(self.included_servers) == 0:
                self.label_status.setText('Waiting for test')
                QtGui.QMessageBox.warning(self, 'Error', 'No test server')
                self.start_btn.setEnabled(True)
                self.stop_btn.setEnabled(False)
                return
            if not self.testname:
                self.label_status.setText('Waiting for test')
                QtGui.QMessageBox.warning(self, 'Error', 'Enter test name')
                self.start_btn.setEnabled(True)
                self.stop_btn.setEnabled(False)
                return
            if self.iterations <= 0:
                self.label_status.setText('Waiting for test')
                QtGui.QMessageBox.warning(self, 'Error', 'Invalid Iterations. Enter number greater or equal to 1')
                self.start_btn.setEnabled(True)
                self.stop_btn.setEnabled(False)
                return
            if not self.planspeed:
                self.label_status.setText('Waiting for test')
                QtGui.QMessageBox.warning(self, 'Error', 'Enter plan speed')
                self.start_btn.setEnabled(True)
                self.stop_btn.setEnabled(False)
                return
            if self.planspeed <= 0:
                self.label_status.setText('Waiting for test')
                QtGui.QMessageBox.warning(self, 'Error', 'Invalid Plan speed')
                self.start_btn.setEnabled(True)
                self.stop_btn.setEnabled(False)
                return
            if not self.private_ip:
                self.label_status.setText('Waiting for test')
                QtGui.QMessageBox.warning(self, 'Error', 'IP not yet detected')
                self.start_btn.setEnabled(True)
                self.stop_btn.setEnabled(False)
                return

        self.test_name.setEnabled(False)
        self.test_planspeed.setEnabled(False)
        self.test_server.setEnabled(False)
        self.test_cycles.setEnabled(False)
        self.test_abroad.setEnabled(False)
        self.test_itx.setEnabled(False)
        self.test_types.setEnabled(False)
        self.test_isp.setEnabled(False)
        self.test_conntype.setEnabled(False)
        self.test_remarks.setEnabled(False)
        self.test_location.setEnabled(False)
        self.test_location2.setEnabled(False)
        self.testing = True
        self.start = time.time()
        self.label_status.setText('Starting Test...')
        QtGui.QApplication.processEvents()
        time.sleep(1)
        self.label_status.setText('Sorting Parameters...')
        QtGui.QApplication.processEvents()
        self.status_progress.setValue(5)
        self.continue_test2()

    def continue_test(self):
        self.current_server = self.included_servers[self.server_count]
        self.ip = self.included_server_ips[self.server_count]
        if not self.detected_isp:
            self.start_btn.setEnabled(True)
            self.stop_btn.setEnabled(False)
            self.label_status.setText('Network Disconnected...')
            QtGui.QMessageBox.warning(self, 'Error', 'Network Disconnected')
            return
        self.label_status.setText('Proceeding to next test server...')
        self.continue_test2()

    def continue_test1(self):
        self.testname = '%s-%d' % (str(self.test_name.text()), self.iteration_count)
        self.server_count = 0
        self.current_server = self.included_servers[self.server_count]
        self.ip = self.included_server_ips[self.server_count]
        if not self.detected_isp:
            self.start_btn.setEnabled(True)
            self.stop_btn.setEnabled(False)
            self.label_status.setText('Network Disconnected...')
            QtGui.QMessageBox.warning(self, 'Error', 'Network Disconnected')
            return
        self.label_status.setText('Proceeding to next test iteration...')
        self.continue_test2()
Reply
#2
Hello,

I'm re-posting again for my issue.

Codes were created by our previous dev, now I'd like to find out if the App does meet the requirement.

The app is a bench-marking tool for testing ISP reliability. This Windows app needs to run test only when there is little or no background traffic (minimum traffic to allow test should be 64kbps)

So when we select "Check Traffic" box, and hit "Start" to perform test, an error will occur saying "BG Traffic Exceed 64kbps".

My questions from the codes:

- is it capable of checking "Windows" background traffic?
- if not, how do I properly address the App that, hey you cannot proceed on testing because traffic is greater than 64kbps?
- and if your traffic is below 64kbps. you may now perform the the test.

Not sure if these are proper python codes so I'll just post it into text format.

Here's what I found so far about "Check Traffic"
if win.traffic >= 64 and win.enable_traffic.isChecked():
            return 0

self.traffic = 0

self.enable_traffic = QtGui.QCheckBox("Check Traffic")
        self.enable_traffic.setChecked(True)
        self.enable_traffic.setFont(normalfont)
        self.enable_traffic.setFixedHeight(20)
        self.enable_traffic.setFixedWidth(150)
        splitter3.addWidget(self.enable_traffic)

if self.enable_traffic.isChecked() and self.traffic > 64:
           self.label_status.setText('BG Traffic Exceeded 64kbps')
          QtGui.QMessageBox.warning(self, 'Error', 'Testing blocked - Traffic Exceeded 64kbps!')
          return

if self.response == 'Traffic':
            QtGui.QMessageBox.warning(self, 'Error', 'Testing blocked - Traffic Exceeded 64kbps')
            self.label_status.setText('BG Traffic Exceeded 64kbps')
            return

if self.win.traffic >= 64 and self.win.enable_traffic.isChecked():
                    self.win.response = 'Traffic'
                    raise Exception('traffic')

And below is what I think the "Start" button does

self.start_btn = QtGui.QPushButton("Start", self)
        self.start_btn.clicked.connect(self.start_test)
        self.start_btn.setFont(normalfont)
        grid.addWidget(self.start_btn, 14, 8)

def start_test(self):
        counter = 0
        self.current_speed = 0
        self.current_downspeed = 0
        self.current_upspeed = 0
        self.current_latencym = 0
        self.current_downspeed1 = 0
        self.current_upspeed1 = 0
        self.current_latencym1 = 0
        self.current_plm = 0
        self.current_jitterm = 0
        self.abort = False
        if not self.detected_isp:
            self.label_status.setText('No Network...')
            QtGui.QMessageBox.warning(self, 'Error', 'No Network')
            return
        if 'wi-fi' in self.nic_name.lower() or 'wifi' in self.nic_name.lower():
            self.label_status.setText('Test aborted...')
            QtGui.QMessageBox.warning(self, 'Error', 'Cannot test in Wi-Fi Network')
            return
        if self.enable_clients.isChecked() and self.clients:
            self.label_status.setText('Other Clients Detected...')
            QtGui.QMessageBox.warning(self, 'Error', 'Testing blocked - Other Clients Detected!')
            return
        if self.enable_traffic.isChecked() and self.traffic > 64:
           self.label_status.setText('BG Traffic Exceeded 64kbps')
           QtGui.QMessageBox.warning(self, 'Error', 'Testing blocked - Traffic Exceeded 64kbps!')
           return
Reply
#3
You should probably contact the original developer. This site is focused on Python education, not doing others' work, and people like me are too lazy to read code like that anyway (just while scrolling I saw two bad practices for which there's no good reason to do).
Reply
#4
(Jan-31-2020, 06:45 AM)rhey Wrote: I'm re-posting again for my issue.
You shouldn't do that. It doesn't do you any good, and it annoys us. Please read this; not reading this means it's likely that you'll receive no helpful replies, though reading it doesn't guarantee the opposite. I already replied on your other thread, but I'm going to merge them because there's no reason for both to exist.
Reply
#5
Hello,

I'm really really sorry I didn't take time to read about help/rules, and I thought my first thread was broken, that's why I created a new one..

The problem is, I can no longer contact previous dev.. Please delete this annoying thread.. But if you won't mind can you tell me those two bad things? maybe via pm.

Thanks
Reply
#6
1) make a github repo and post your entire code there. Your code was truncated at some point because it hit our max character size per post limit. So you cannot see the entire code. I put it in code tags to minimize real estate for scroll ability, but its still not all there.

2) if your not a programmer then this is probably moot. There is so much code and whoever fixes it has to go through and understand it. You may have to pay someone to first understand the code, then fix the problem.

3) Its a lot of code. I scanned it, but i did not spend the time to follow control with every little thing. Plus that is not my strong suit in programming.

4)Im on linux. Because the dev hard coded Windows references (registration keys), then i cant even run this code. Your going to have to find a Windows PyQt Pythoner programmer that does networking.

5)My first thought would be why is this code here?
Quote:
        if self.enable_traffic.isChecked() and self.traffic > 64:
           self.label_status.setText('BG Traffic Exceeded 64kbps')
           QtGui.QMessageBox.warning(self, 'Error', 'Testing blocked - Traffic Exceeded 64kbps!')
           return
If i was debugging this, i would disable this section of code and see what errors i get as a result. Could be nothing, could be something.
Recommended Tutorials:
Reply
#7
Hi Metulburr,

Sorry for super late reply.. The app is a windows based program an exe file, target is that if windows traffic greater than 64kbps the app should not perform his benchmarking test..

Upon checking (while Windows traffic monitor is open) I can see that send/receive traffic is below 64kbps. But when hit "Start" on App it'll run for a while but will eventually stop with pop-up "BG Traffic Exceeded 64kbps". And yes the traffic exceeds 64kbps because of what the app is doing. So what I have in mind is how will the app determine will only detect background traffic instead. Apps creating traffic must be exempted..
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020