def connect_to_server(self): if self.connected or self.listening: self.connect_pb.setChecked(True) return server_ip = str(self.server_ip_text.text()) port = int(str(self.local_port_text.text())) print("Server IP: ", server_ip) if server_ip.find('xxx') != -1: print("bad IP") QMessageBox.about( self, 'Bad Server IP', 'Please give a correct Server IP\n' 'IP is ' + server_ip) self.connect_pb.setChecked(False) return else: self.client_socket = QTcpSocket(self) print("Connecting to " + server_ip + ":", port) self.client_socket.connectToHost(server_ip, port) self.client_socket.waitForConnected(1000) self.client_socket.readyRead.connect(self.client_read) if self.client_socket.state() != QTcpSocket.ConnectedState: QMessageBox.about( self, 'Connection failed', 'Please check IP address and port number\nIs the server running?' ) self.connect_pb.setChecked(False) return print("Connection established") self.connect_pb.setText("Connected") self.client_server_tab.setTabEnabled(0, False) print("Connecting send button") self.send_button.clicked.connect(self.send_msg) self.connected = True
def __init__(self): super().__init__() self.targetAddr = '0.0.0.0' self.targetPort = 0 QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, QDir.currentPath()) self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope, 'config') self.readSettings() self.connectionSettings = ConnectionSettings(self.targetAddr, self.targetPort, self) self.connectionSettings.settingsChanged.connect( self.onConnectionSettingsSettingsChanged) self.socket = QTcpSocket(self) self.socket.stateChanged.connect(self.onSocketStateChanged) self.socket.readyRead.connect(self.onSocketReadyRead) self.frameLength = 0 self.lastSocketState = QAbstractSocket.UnconnectedState self.animationTimer = QTimer(self) self.animationTimer.timeout.connect(self.onAnimationTimerTimeout) self.animationCounter = 0 self.connectionTimer = QTimer(self) self.connectionTimer.setSingleShot(True) self.connectionTimer.timeout.connect(self.onConnectionTimerTimeout) self.dataExchangeTimer = QTimer(self) self.dataExchangeTimer.timeout.connect(self.onDataExchangeTimerTimeout) self.initUI() self.onConnectionSettingsSettingsChanged(self.targetAddr, self.targetPort) self.onSocketStateChanged()
def __init__(self, args): super().__init__() self.socket = QTcpSocket() self.socket.connectToHost('localhost', args.port) self.socket.readyRead.connect(self.readFromEmotool) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("EmoTool - {}".format(version())) self.main_widget = QtWidgets.QTabWidget(self) plot_tab = QtWidgets.QWidget(self.main_widget) self.main_widget.addTab(plot_tab, "plot") l = QtWidgets.QVBoxLayout(plot_tab) self.plot_widget = plot_widget = pg.PlotWidget() l.addWidget(plot_widget) self.plot_widget = plot_widget # TODO - make a menu action, not open by default c = pg.console.ConsoleWidget(namespace=globals(), text="test console") self.main_widget.addTab(c, "debug") self.main_widget.setFocus() self.setCentralWidget(self.main_widget) self.statusBar().showMessage("Starting", 2000) self.ticks = defaultdict(list) self.vals = defaultdict(list) self.data_items = defaultdict(pg.PlotDataItem) self.incoming = b'' self.next_message_size = None
def __init__(self): self.xsize = 512 self.ysize = 512 self.size = self.xsize * self.ysize self.freq = 125.0 self.period = 200 self.trgtime = 100 self.trginv = 0 self.shdelay = 1.5 self.shtime = 0.1 self.shinv = 0 self.acqdelay = 10 self.samples = 32 self.pulses = 2 self.idle = True self.socket = QTcpSocket() self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) # self.socket.error.connect(self.display_error) X, Y = np.meshgrid(np.arange(self.xsize),np.arange(self.ysize)) self.xco = X self.yco = Y self.buffer = bytearray(8 * self.xsize*self.ysize) self.data = np.frombuffer(self.buffer, np.int32)
def __init__(self, ip='127.0.0.1', port=8888): super().__init__(flags=(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)) print("test: ", Qt.WindowStaysOnTopHint) print("test: ", (Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)) self.q_rect = QDesktopWidget().screenGeometry() self.ip = ip self.port = int(port) self.interval = 15 self.fonts_size = 48 self.danmaku_list = list() self.line_list = [ None for _ in range( 0, self.q_rect.height() // (self.fonts_size + self.interval)) ] self.brush = MyBrush() self.timer = QTimer() self.socket = QTcpSocket(self) self.set_transparent() self.init_ui() self.init_net() self.set_timer()
def connect(self): if self.isConnectedToServer: return True self.sock = QTcpSocket(self) host_ip_addr = '192.168.1.150' port = 8080 self.sock.connectToHost(host_ip_addr, port) if not self.sock.waitForConnected(2500): msg = self.sock.errorString() self.add_message(msg + '\n') QMessageBox.critical(self, "Error", msg) return False self.sock.connected.connect(self.on_socket_connected) self.sock.disconnected.connect(self.on_socket_disconnected) self.sock.readyRead.connect(self.on_socket_receive) self.sock.bytesWritten.connect(self.on_socket_transmit) self.add_message("Connected to {} on port {}\n".format(host_ip_addr, port)) self.isConnectedToServer = True self.lineEdit.setEnabled(True) self.pushButton.setEnabled(True) return True
def __init__(self): """Constructor.""" self.__tcpSocket = QTcpSocket() self.__name = "" super().__init__() # Used at the end because it launches the app
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Výroba ovládacích prvků self.connectButton = QPushButton(self, text="Start") self.connectButton.clicked.connect(self.connect) self.disconnectButton = QPushButton(self, text="Stop") self.disconnectButton.clicked.connect(self.disconnect) # Rozložení ovládacích prvků self.layout = QVBoxLayout(self) self.layout.addWidget(self.connectButton) self.layout.addWidget(self.disconnectButton) # Příprava TCP socketu self.socket = QTcpSocket(self) self.socket.readyRead.connect(self.read) self.socket.connected.connect(self.connected) self.readBuffer = bytearray() self.travellers = {} # Zobrazení self.setLayout(self.layout) self.show()
def run(self): self.socket = QTcpSocket() self.myclientid1 = 0 if not self.socket.setSocketDescriptor(self.socketId): self.error.connect(self.socket.error) return self.sinOut1.emit( str(self.socketId) + "#" + QDateTime.currentDateTime().toString("yyyy-MM-dd HH:mm:ss") ) #发送信号量 //建立连接 while self.socket.state() == QAbstractSocket.ConnectedState: if (self.socket.waitForReadyRead(1000 * 60 * 10) and self.socket.bytesAvailable() > 0): #waitForReadyRead(1000*60*10)说明,单位为毫秒,时间内等待接收数据,超时为假 mygetdata = self.socket.readAll() mygetdata = bytes(mygetdata) #print(mygetdata) self.sinOut2.emit("get data:" + str(mygetdata)) #client发送来的数据 #分析客户端数据中的ID值 myclientid = self.myanalyseframe(mygetdata) if myclientid != 0 and myclientid != self.myclientid1: self.myclientid1 = myclientid # 利用client数据,标识处TCP连接的对象ID值,指令中的值 self.sinOut1.emit( str(self.socketId) + "#" + QDateTime.currentDateTime().toString( "yyyy-MM-dd HH:mm:ss") + "#" + str(myclientid)) else: self.senddata(self.socket, 'TCP time out') self.sinOut3.emit(str(self.socketId)) #超时,线程结束,删除前台listw中的条目 return #超时,线程结束
def __init__(self, sock_type='TCP Client', ip='127.0.0.1', port=2007): '''打开网络设备,建立连接 ## sock_type: - 'TCP Client' - 'TCP Server' - 'UDP' ''' self.sock_type = sock_type # self.ip = ip self.port = port if sock_type == 'TCP Client': tcp_client = QTcpSocket() tcp_client.connectToHost(ip, port) self.sock = tcp_client elif sock_type == 'TCP Server': tcp_server = QTcpServer() tcp_server.listen(QHostAddress(ip), port) self.sock = tcp_server elif sock_type == 'UDP': udp = QUdpSocket() udp.bind(QHostAddress(ip), port) self.sock = udp else: print('Unkonw sock_type=%r' % sock_type)
def __init__(self): super(Client, self).__init__() self.resize(500, 450) # 1 self.browser = QTextBrowser(self) self.edit = QTextEdit(self) self.splitter = QSplitter(self) self.splitter.setOrientation(Qt.Vertical) self.splitter.addWidget(self.browser) self.splitter.addWidget(self.edit) self.splitter.setSizes([350, 100]) self.send_btn = QPushButton('Send', self) self.close_btn = QPushButton('Close', self) self.h_layout = QHBoxLayout() self.v_layout = QVBoxLayout() # 2 self.sock = QTcpSocket(self) self.sock.connectToHost(QHostAddress.LocalHost, 8080) self.layout_init() self.signal_init()
def enterRoom(self): self.tcpSocket = QTcpSocket(self) self.tcpSocket.connectToHost(self.serverIP, self.port) self.tcpSocket.connected.connect(self.slotConnected) self.tcpSocket.readyRead.connect(self.slotDataReceived) self.tcpSocket.disconnected.connect(self.slotDisconnected) self.tcpSocket.error.connect(self.slotErrorOccured)
def __init__(self, parent=None): super(TcpSocketClient, self).__init__() self.tcpSocketClient = QTcpSocket(parent) self.setIsConnected(False) self.setTcpClientID(0) self.setPeerFullAddrStr(str()) self.tcpSocketClient.readyRead.connect(self.dataReceived) self.connectClientDisconnect(self.disConnected)
def __init__(self, argv): super().__init__(argv) self.server = QTcpServer(self) self.server.setMaxPendingConnections(1) self.server.newConnection.connect(self.onNewConnection) self.server.listen(QHostAddress.Any, 6666) self.client = QTcpSocket(self) self.cap = cv2.VideoCapture(0)
def __init__(self): super(Scanner, self).__init__() self.setupUi(self) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variable self.idle = True # number of samples to show on the plot self.size = 512 * 512 self.freq = 125.0 # buffer and offset for the incoming samples self.buffer = bytearray(8 * self.size) self.offset = 0 self.data = np.frombuffer(self.buffer, np.int32) # create figure figure = Figure() figure.set_facecolor('none') self.axes = figure.add_subplot(111) self.canvas = FigureCanvas(figure) self.plotLayout.addWidget(self.canvas) self.axes.axis((0.0, 512.0, 0.0, 512.0)) x, y = np.meshgrid(np.linspace(0.0, 512.0, 513), np.linspace(0.0, 512.0, 513)) z = x / 512.0 + y * 0.0 self.mesh = self.axes.pcolormesh(x, y, z, cmap = cm.plasma) # create navigation toolbar self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False) # remove subplots action actions = self.toolbar.actions() if int(matplotlib.__version__[0]) < 2: self.toolbar.removeAction(actions[7]) else: self.toolbar.removeAction(actions[6]) self.plotLayout.addWidget(self.toolbar) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from buttons and boxes self.connectButton.clicked.connect(self.start) self.scanButton.clicked.connect(self.scan) self.periodValue.valueChanged.connect(self.set_period) self.trgtimeValue.valueChanged.connect(self.set_trgtime) self.trginvCheck.stateChanged.connect(self.set_trginv) self.shdelayValue.valueChanged.connect(self.set_shdelay) self.shtimeValue.valueChanged.connect(self.set_shtime) self.shinvCheck.stateChanged.connect(self.set_shinv) self.acqdelayValue.valueChanged.connect(self.set_acqdelay) self.samplesValue.valueChanged.connect(self.set_samples) self.pulsesValue.valueChanged.connect(self.set_pulses) # create timers self.startTimer = QTimer(self) self.startTimer.timeout.connect(self.timeout) self.meshTimer = QTimer(self) self.meshTimer.timeout.connect(self.update_mesh) # set default values self.periodValue.setValue(200.0)
def __init__(self): super().__init__() self.tcpSocket = QTcpSocket(self) self.blockSize = 0 self.makeRequest() self.tcpSocket.waitForConnected(1000) # send any message you like it could come from a widget text. self.tcpSocket.write(b'hello') self.tcpSocket.readyRead.connect(self.dealCommunication) self.tcpSocket.error.connect(self.displayError)
def __init__(self): super(Client, self).__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.file = QFile() self.tcpsocket = QTcpSocket() self.ui.pushButton_Connect.clicked.connect(self.ConnectToServer) self.tcpsocket.connected.connect(self.SuccessConnect) self.tcpsocket.readyRead.connect(self.HandleReceive)
def dealSocket(self): tcpSocket = QTcpSocket() #通信套接字 if tcpSocket.setSocketDescriptor(self.socket): socktList.append(tcpSocket) # QTcpSocket缓存接收到新的数据时触发readyRead tcpSocket.readyRead.connect(lambda: dealRecvMsgE(tcpSocket)) # 断开连接时 tcpSocket.disconnected.connect(lambda: dealDisconnect(tcpSocket)) else: print("出错了")
def __init__(self, gui): SessionManager.__init__(self, gui) self.session_type = SessionType.STUDENT self.gui = gui self.running = False self.teacher_socket = QTcpSocket( ) # this socket connects to the teacher self.teacher_paused_at = None # pause time if session is paused; None otherwise self.traffic = [] # FgmsAircraft list self.known_METAR = None
def __init__(self, request_handler_instance): QObject.__init__(self) self.socket = QTcpSocket(self) self.connectionAttempts = 1 self.socket.readyRead.connect(self.onData) self.socket.error.connect(self.onSocketError) self.request_handler_instance = request_handler_instance self.nextid = 1 self.callbacks_result = {} self.callbacks_error = {} self.buffer = b''
def __init__(self, parent=None): super().__init__(parent) self.main = parent # Die Membervariable tcpSocket verwaltet den Kommunikationskanal zum Server. self.tcpSocket = QTcpSocket(self) # In der connectToHost-Routine muss die IP-Adresse des Servers eingetragen werden. # Hier steht zurzeit nur die localhost Adresse: 127.0.0.1 self.tcpSocket.connectToHost('127.0.0.1', 40890) self.tcpSocket.readyRead.connect(self.readData) self.mx = None self.my = None
class TcpClient(QObject): finished = pyqtSignal() connected = pyqtSignal() connectionLost = pyqtSignal() interpretCmd = pyqtSignal(str) def __init__(self): super(TcpClient, self).__init__() self.__tcp_socket = None self.connectionLost.connect(self.finished) self.connectionLost.connect( lambda: print('## Disconnected from the robot ##')) @pyqtSlot() def start_client(self): print(f'## Connecting to robot at IP: {WIFI_IP}, PORT: {WIFI_PORT} ##') self.__tcp_socket = QTcpSocket() self.__tcp_socket.disconnected.connect(self.connectionLost) self.__tcp_socket.readyRead.connect(self.read_ready) self.__tcp_socket.connected.connect(self.connected) self.__tcp_socket.connectToHost(WIFI_IP, WIFI_PORT) if not self.__tcp_socket.waitForConnected(TIMEOUT_MSEC): print( f'## Timeout! {TIMEOUT_MSEC/1000}s has passed and it still hasn\'t connect ##' ) self.__tcp_socket.disconnectFromHost() self.finished.emit() else: print( f'## Connected to robot at IP: {WIFI_IP}, PORT: {WIFI_PORT} ##' ) def stop_client(self): if self.__tcp_socket is not None: self.__tcp_socket.disconnectFromHost() self.finished.emit() @pyqtSlot() def read_ready(self): try: data = self.__tcp_socket.readAll() self.interpretCmd.emit(str(data, "utf-8").strip()) except Exception as err: print(f'tcpClient::read_ready() error msg: {err}') @pyqtSlot(str) def send_message(self, payload): try: # Example message: 'FP|tr' # self.__tcp_socket.write(QByteArray().append(json.dumps({'target': 'ARD', 'payload': 'hi'}))) self.__tcp_socket.write(QByteArray().append(payload)) # self.__tcp_socket.flush() except Exception as err: print(f'tcpClient::send_message() error msg: {err}')
def __init__(self): super(TcpClient, self).__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.tcpSocket = QTcpSocket(self) self.ui.connectButton.clicked.connect(self.buttonConnect) self.tcpSocket.connected.connect(self.sucessConnect) self.ui.sendButton.clicked.connect(self.sendMessage) self.tcpSocket.readyRead.connect(self.showMessage) self.ui.closeButton.clicked.connect(self.closeConnect)
def __init__(self): super(TcpServer, self).__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.tcpServer = QTcpServer(self) #指定父对象自动回收空间 监听套接字 self.tcpSocket = QTcpSocket(self) #通信套接字 self.tcpServer.listen(QHostAddress.Any, 8888) #any默认绑定当前网卡的所有IP self.tcpServer.newConnection.connect(self.handleNewConnection) self.ui.sendButton.clicked.connect(self.sendMessage) self.ui.closeButton.clicked.connect(self.closeConnect)
def connect(self, remoteAddress, port): """Establishes a connection with the IDE""" self.__socket = QTcpSocket() if remoteAddress is None: self.__socket.connectToHost(QHostAddress.LocalHost, port) else: self.__socket.connectToHost(remoteAddress, port) if not self.__socket.waitForConnected(1000): raise Exception('Cannot connect to the IDE') self.__socket.setSocketOption(QAbstractSocket.KeepAliveOption, 1) self.__socket.setSocketOption(QAbstractSocket.LowDelayOption, 1) self.__socket.disconnected.connect(self.__onDisconnected)
def __init__(self, parent=None): super(Voltmeter, self).__init__(parent) self.setupUi(self) self.needle = QwtDialSimpleNeedle(QwtDialSimpleNeedle.Arrow) self.Dial.setNeedle(self.needle) self.Dial.setValue(1.5) self.lcdNumber.display(1.5) self.actionQuit.triggered.connect(self.quit) self.connect_pb.clicked.connect(self.connect) self.calib = 3.3 / 256 self.client_socket = QTcpSocket(self) self.connected = False
def run(self): print("新连接进入") self.clientSocket = QTcpSocket() self.clientSocket.connectToHost(QHostAddress(self.ip), self.port) clientSocketList.append((self.clientSocket, self.ip, self.port)) self.clientSocket.connected.connect(lambda: print("连接成功")) self.clientSocket.readyRead.connect(lambda:self.handle_read(self.clientSocket),Qt.DirectConnection) self.clientSocket.disconnected.connect(self.dealDisconnected,Qt.DirectConnection) self.exec()
def __init__(self, host, port): super().__init__() self.tcpSocket = QTcpSocket() self.blockSize = 0 self.host = host self.port = port self.jim = None self.connected = False self.chat_list = [] self.online_users = [] self.active_chat = '' self.logon()
def invoke_query_of_smhub(self): self.sock = QTcpSocket() self.sock.error.connect(self.on_tcp_error) self.sock.readyRead.connect(self.on_ready_read) try: self.sock.connectToHost(self.smarthubIP, 9990) if not self.sock.waitForConnected(1000): errstr = "Error Communicating with SmartHub" print(errstr) except: print(self.sock.SocketError())
def __init__(self): super(Scanner, self).__init__() self.setupUi(self) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variable self.idle = True # number of samples to show on the plot self.size = 512 * 512 self.freq = 143.0 # buffer and offset for the incoming samples self.buffer = bytearray(8 * self.size) self.offset = 0 self.data = np.frombuffer(self.buffer, np.int32) # create figure figure = Figure() figure.set_facecolor('none') self.axes = figure.add_subplot(111) self.canvas = FigureCanvas(figure) self.plotLayout.addWidget(self.canvas) self.axes.axis((0.0, 512.0, 0.0, 512.0)) x, y = np.meshgrid(np.linspace(0.0, 512.0, 513), np.linspace(0.0, 512.0, 513)) z = x / 512.0 + y * 0.0 self.mesh = self.axes.pcolormesh(x, y, z, cmap = cm.plasma) # create navigation toolbar self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False) # remove subplots action actions = self.toolbar.actions() if int(matplotlib.__version__[0]) < 2: self.toolbar.removeAction(actions[7]) else: self.toolbar.removeAction(actions[6]) self.plotLayout.addWidget(self.toolbar) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from buttons and boxes self.connectButton.clicked.connect(self.start) self.scanButton.clicked.connect(self.scan) self.periodValue.valueChanged.connect(self.set_period) self.trgtimeValue.valueChanged.connect(self.set_trgtime) self.trginvCheck.stateChanged.connect(self.set_trginv) self.shdelayValue.valueChanged.connect(self.set_shdelay) self.shtimeValue.valueChanged.connect(self.set_shtime) self.shinvCheck.stateChanged.connect(self.set_shinv) self.acqdelayValue.valueChanged.connect(self.set_acqdelay) self.samplesValue.valueChanged.connect(self.set_samples) self.pulsesValue.valueChanged.connect(self.set_pulses) # create timers self.startTimer = QTimer(self) self.startTimer.timeout.connect(self.timeout) self.meshTimer = QTimer(self) self.meshTimer.timeout.connect(self.update_mesh) # set default values self.periodValue.setValue(200.0)
class Client(QObject): def __init__(self, parent=None): super().__init__(parent) self.log = logging.getLogger(__name__) self._socket_setup() def _socket_setup(self): self.socket = QTcpSocket(self) self.socket.setSocketOption(QTcpSocket.KeepAliveOption, 1) self.socket.connected.connect(self.on_connected) self.socket.disconnected.connect(self.on_disconnected) self.socket.readyRead.connect(self.on_readyRead) self.socket.error.connect(self.on_error) self.socket.stateChanged.connect(self.on_stateChanged) def connect(self, host=HOST, port=PORT): if not self.socket.isOpen(): self.log.info('connecting to {}:{}'.format(host, port)) self.socket.connectToHost(QHostAddress(host), port) def disconnect(self): self.log.info('disconnecting') self.socket.disconnectFromHost() def on_readyRead(self): data = bytes() while self.socket.bytesAvailable(): data += self.socket.read(1024) self.log.debug(data) def on_connected(self): self.log.info('connected') def on_disconnected(self): self.log.info('disconnected') def on_error(self, error): self.log.error('error {}: {}'.format(error, self.socket.errorString())) def on_stateChanged(self, state): states = ['Unconnected', 'HostLookup', 'Connecting', 'Connected', 'Bound', 'Closing', 'Listening'] self.log.debug('state changed to {}'.format(states[state]))
def _socket_setup(self): self.socket = QTcpSocket(self) self.socket.setSocketOption(QTcpSocket.KeepAliveOption, 1) self.socket.connected.connect(self.on_connected) self.socket.disconnected.connect(self.on_disconnected) self.socket.readyRead.connect(self.on_readyRead) self.socket.error.connect(self.on_error) self.socket.stateChanged.connect(self.on_stateChanged)
def __init__(self, socket=None): super(TcpClient, self).__init__() self.is_connected = False if socket is None: self.socket = QTcpSocket() else: self.socket = socket self.socket.error.connect(self.error) self.socket.connected.connect(self.connected) self.socket.disconnected.connect(self.disconnected) self.socket.readyRead.connect(self.readyRead)
def run(self): tcpSocket = QTcpSocket() if not tcpSocket.setSocketDescriptor(self.socketDescriptor): self.error.emit(tcpSocket.error()) return block = QByteArray() outstr = QDataStream(block, QIODevice.WriteOnly) outstr.setVersion(QDataStream.Qt_4_0) outstr.writeUInt16(0) outstr.writeQString(self.text) outstr.device().seek(0) outstr.writeUInt16(block.size() - 2) tcpSocket.write(block) tcpSocket.disconnectFromHost() tcpSocket.waitForDisconnected()
class TcpClient(QObject): def __init__(self, socket=None): super(TcpClient, self).__init__() self.is_connected = False if socket is None: self.socket = QTcpSocket() else: self.socket = socket self.socket.error.connect(self.error) self.socket.connected.connect(self.connected) self.socket.disconnected.connect(self.disconnected) self.socket.readyRead.connect(self.readyRead) @pyqtSlot() def error(self): print self.socket.errorString() @pyqtSlot() def connected(self): self.is_connected = True print 'TcpClient connected' @pyqtSlot() def disconnected(self): self.is_connected = False print 'TcpClient disconnected' @pyqtSlot() def readyRead(self): data = self.socket.readAll() self.parse_data(data) def connectToHost(self, host, port): print 'Trying to connect to host', host, 'at port', port self.socket.connectToHost(host, port) def disconnectFromHost(self): self.socket.disconnectFromHost() def write(self, buf): self.socket.write(buf) def parse_data(self, data): # Placeholder function; override it with your own implementation print str(data).strip()
def __init__(self): super(PulsedNMR, self).__init__() self.setupUi(self) self.rateValue.addItems(['25', '50', '250', '500', '2500']) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variable self.idle = True # number of samples to show on the plot self.size = 50000 # buffer and offset for the incoming samples self.buffer = bytearray(8 * self.size) self.offset = 0 self.data = np.frombuffer(self.buffer, np.complex64) # create figure figure = Figure() figure.set_facecolor('none') self.axes = figure.add_subplot(111) self.canvas = FigureCanvas(figure) self.plotLayout.addWidget(self.canvas) # create navigation toolbar self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False) # remove subplots action actions = self.toolbar.actions() self.toolbar.removeAction(actions[7]) self.plotLayout.addWidget(self.toolbar) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from buttons and boxes self.startButton.clicked.connect(self.start) self.freqValue.valueChanged.connect(self.set_freq) self.awidthValue.valueChanged.connect(self.set_awidth) self.deltaValue.valueChanged.connect(self.set_delta) self.rateValue.currentIndexChanged.connect(self.set_rate) # set rate self.rateValue.setCurrentIndex(2) # create timer for the repetitions self.timer = QTimer(self) self.timer.timeout.connect(self.fire)
def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.tcpServer = QTcpServer() self.tcpClient = QTcpSocket() self.bytesToWrite = 0 self.bytesWritten = 0 self.bytesReceived = 0 self.clientProgressBar = QProgressBar() self.clientStatusLabel = QLabel("Client ready") self.serverProgressBar = QProgressBar() self.serverStatusLabel = QLabel("Server ready") self.startButton = QPushButton("&Start") self.quitButton = QPushButton("&Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) self.startButton.clicked.connect(self.start) self.quitButton.clicked.connect(self.close) self.tcpServer.newConnection.connect(self.acceptConnection) self.tcpClient.connected.connect(self.startTransfer) self.tcpClient.bytesWritten.connect(self.updateClientProgress) self.tcpClient.error.connect(self.displayError) mainLayout = QVBoxLayout() mainLayout.addWidget(self.clientProgressBar) mainLayout.addWidget(self.clientStatusLabel) mainLayout.addWidget(self.serverProgressBar) mainLayout.addWidget(self.serverStatusLabel) mainLayout.addStretch(1) mainLayout.addSpacing(10) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Loopback")
def __init__(self, *args): super(Main, self).__init__(*args) loadUi('mainwindow.ui', self) self.host.setText("localhost") self.port.setText("11010") self.prompt.setText("M114") self.conn = QTcpSocket(self) self.conn.readyRead.connect(self.readSocket) self.conn.error.connect(self.socketError) self.conn.connected.connect(self.socketConnect) self.conn.disconnected.connect(self.socketDisconnect) self.connected = False self.actionSave.triggered.connect(self.save) self.prompt.setFocus() self.do_connect()
class Dialog(QDialog): TotalBytes = 50 * 1024 * 1024 PayloadSize = 65536 def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.tcpServer = QTcpServer() self.tcpClient = QTcpSocket() self.bytesToWrite = 0 self.bytesWritten = 0 self.bytesReceived = 0 self.clientProgressBar = QProgressBar() self.clientStatusLabel = QLabel("Client ready") self.serverProgressBar = QProgressBar() self.serverStatusLabel = QLabel("Server ready") self.startButton = QPushButton("&Start") self.quitButton = QPushButton("&Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) self.startButton.clicked.connect(self.start) self.quitButton.clicked.connect(self.close) self.tcpServer.newConnection.connect(self.acceptConnection) self.tcpClient.connected.connect(self.startTransfer) self.tcpClient.bytesWritten.connect(self.updateClientProgress) self.tcpClient.error.connect(self.displayError) mainLayout = QVBoxLayout() mainLayout.addWidget(self.clientProgressBar) mainLayout.addWidget(self.clientStatusLabel) mainLayout.addWidget(self.serverProgressBar) mainLayout.addWidget(self.serverStatusLabel) mainLayout.addStretch(1) mainLayout.addSpacing(10) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Loopback") def start(self): self.startButton.setEnabled(False) QApplication.setOverrideCursor(Qt.WaitCursor) self.bytesWritten = 0 self.bytesReceived = 0 while not self.tcpServer.isListening() and not self.tcpServer.listen(): ret = QMessageBox.critical(self, "Loopback", "Unable to start the test: %s." % self.tcpServer.errorString(), QMessageBox.Retry | QMessageBox.Cancel) if ret == QMessageBox.Cancel: return self.serverStatusLabel.setText("Listening") self.clientStatusLabel.setText("Connecting") self.tcpClient.connectToHost(QHostAddress(QHostAddress.LocalHost), self.tcpServer.serverPort()) def acceptConnection(self): self.tcpServerConnection = self.tcpServer.nextPendingConnection() self.tcpServerConnection.readyRead.connect(self.updateServerProgress) self.tcpServerConnection.error.connect(self.displayError) self.serverStatusLabel.setText("Accepted connection") self.tcpServer.close() def startTransfer(self): self.bytesToWrite = Dialog.TotalBytes - self.tcpClient.write(QByteArray(Dialog.PayloadSize, '@')) self.clientStatusLabel.setText("Connected") def updateServerProgress(self): self.bytesReceived += self.tcpServerConnection.bytesAvailable() self.tcpServerConnection.readAll() self.serverProgressBar.setMaximum(Dialog.TotalBytes) self.serverProgressBar.setValue(self.bytesReceived) self.serverStatusLabel.setText("Received %dMB" % (self.bytesReceived / (1024 * 1024))) if self.bytesReceived == Dialog.TotalBytes: self.tcpServerConnection.close() self.startButton.setEnabled(True) QApplication.restoreOverrideCursor() def updateClientProgress(self, numBytes): self.bytesWritten += numBytes if self.bytesToWrite > 0: self.bytesToWrite -= self.tcpClient.write(QByteArray( min(self.bytesToWrite, Dialog.PayloadSize), '@')) self.clientProgressBar.setMaximum(Dialog.TotalBytes) self.clientProgressBar.setValue(self.bytesWritten) self.clientStatusLabel.setText("Sent %dMB" % (self.bytesWritten / (1024 * 1024))) def displayError(self, socketError): if socketError == QTcpSocket.RemoteHostClosedError: return QMessageBox.information(self, "Network error", "The following error occured: %s." % self.tcpClient.errorString()) self.tcpClient.close() self.tcpServer.close() self.clientProgressBar.reset() self.serverProgressBar.reset() self.clientStatusLabel.setText("Client ready") self.serverStatusLabel.setText("Server ready") self.startButton.setEnabled(True) QApplication.restoreOverrideCursor()
def __init__(self): super(VNA, self).__init__() self.setupUi(self) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variables self.idle = True self.reading = False # sweep parameters self.sweep_start = 100 self.sweep_stop = 60000 self.sweep_size = 600 self.xaxis, self.sweep_step = np.linspace(self.sweep_start, self.sweep_stop, self.sweep_size, retstep = True) self.xaxis *= 1000 # buffer and offset for the incoming samples self.buffer = bytearray(24 * VNA.max_size) self.offset = 0 self.data = np.frombuffer(self.buffer, np.complex64) self.adc1 = np.zeros(VNA.max_size, np.complex64) self.adc2 = np.zeros(VNA.max_size, np.complex64) self.dac1 = np.zeros(VNA.max_size, np.complex64) self.open = np.zeros(VNA.max_size, np.complex64) self.short = np.zeros(VNA.max_size, np.complex64) self.load = np.zeros(VNA.max_size, np.complex64) self.dut = np.zeros(VNA.max_size, np.complex64) self.mode = 'dut' # create figure self.figure = Figure() self.figure.set_facecolor('none') self.canvas = FigureCanvas(self.figure) self.plotLayout.addWidget(self.canvas) # create navigation toolbar self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False) # initialize cursor self.cursor = None # remove subplots action actions = self.toolbar.actions() self.toolbar.removeAction(actions[7]) self.plotLayout.addWidget(self.toolbar) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from buttons and boxes self.sweepFrame.setEnabled(False) self.dutSweep.setEnabled(False) self.connectButton.clicked.connect(self.start) self.writeButton.clicked.connect(self.write_cfg) self.readButton.clicked.connect(self.read_cfg) self.openSweep.clicked.connect(self.sweep_open) self.shortSweep.clicked.connect(self.sweep_short) self.loadSweep.clicked.connect(self.sweep_load) self.dutSweep.clicked.connect(self.sweep_dut) self.csvButton.clicked.connect(self.write_csv) self.s1pButton.clicked.connect(self.write_s1p) self.s2pButton.clicked.connect(self.write_s2p) self.startValue.valueChanged.connect(self.set_start) self.stopValue.valueChanged.connect(self.set_stop) self.sizeValue.valueChanged.connect(self.set_size) self.rateValue.addItems(['500', '100', '50', '10', '5', '1']) self.rateValue.lineEdit().setReadOnly(True) self.rateValue.lineEdit().setAlignment(Qt.AlignRight) for i in range(0, self.rateValue.count()): self.rateValue.setItemData(i, Qt.AlignRight, Qt.TextAlignmentRole) self.rateValue.currentIndexChanged.connect(self.set_rate) self.corrValue.valueChanged.connect(self.set_corr) self.levelValue.valueChanged.connect(self.set_level) self.openPlot.clicked.connect(self.plot_open) self.shortPlot.clicked.connect(self.plot_short) self.loadPlot.clicked.connect(self.plot_load) self.dutPlot.clicked.connect(self.plot_dut) self.smithPlot.clicked.connect(self.plot_smith) self.impPlot.clicked.connect(self.plot_imp) self.rcPlot.clicked.connect(self.plot_rc) self.swrPlot.clicked.connect(self.plot_swr) self.rlPlot.clicked.connect(self.plot_rl) self.gainPlot.clicked.connect(self.plot_gain) # create timer self.startTimer = QTimer(self) self.startTimer.timeout.connect(self.timeout)
class VNA(QMainWindow, Ui_VNA): max_size = 16384 def __init__(self): super(VNA, self).__init__() self.setupUi(self) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variables self.idle = True self.reading = False # sweep parameters self.sweep_start = 100 self.sweep_stop = 60000 self.sweep_size = 600 self.xaxis, self.sweep_step = np.linspace(self.sweep_start, self.sweep_stop, self.sweep_size, retstep = True) self.xaxis *= 1000 # buffer and offset for the incoming samples self.buffer = bytearray(24 * VNA.max_size) self.offset = 0 self.data = np.frombuffer(self.buffer, np.complex64) self.adc1 = np.zeros(VNA.max_size, np.complex64) self.adc2 = np.zeros(VNA.max_size, np.complex64) self.dac1 = np.zeros(VNA.max_size, np.complex64) self.open = np.zeros(VNA.max_size, np.complex64) self.short = np.zeros(VNA.max_size, np.complex64) self.load = np.zeros(VNA.max_size, np.complex64) self.dut = np.zeros(VNA.max_size, np.complex64) self.mode = 'dut' # create figure self.figure = Figure() self.figure.set_facecolor('none') self.canvas = FigureCanvas(self.figure) self.plotLayout.addWidget(self.canvas) # create navigation toolbar self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False) # initialize cursor self.cursor = None # remove subplots action actions = self.toolbar.actions() self.toolbar.removeAction(actions[7]) self.plotLayout.addWidget(self.toolbar) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from buttons and boxes self.sweepFrame.setEnabled(False) self.dutSweep.setEnabled(False) self.connectButton.clicked.connect(self.start) self.writeButton.clicked.connect(self.write_cfg) self.readButton.clicked.connect(self.read_cfg) self.openSweep.clicked.connect(self.sweep_open) self.shortSweep.clicked.connect(self.sweep_short) self.loadSweep.clicked.connect(self.sweep_load) self.dutSweep.clicked.connect(self.sweep_dut) self.csvButton.clicked.connect(self.write_csv) self.s1pButton.clicked.connect(self.write_s1p) self.s2pButton.clicked.connect(self.write_s2p) self.startValue.valueChanged.connect(self.set_start) self.stopValue.valueChanged.connect(self.set_stop) self.sizeValue.valueChanged.connect(self.set_size) self.rateValue.addItems(['500', '100', '50', '10', '5', '1']) self.rateValue.lineEdit().setReadOnly(True) self.rateValue.lineEdit().setAlignment(Qt.AlignRight) for i in range(0, self.rateValue.count()): self.rateValue.setItemData(i, Qt.AlignRight, Qt.TextAlignmentRole) self.rateValue.currentIndexChanged.connect(self.set_rate) self.corrValue.valueChanged.connect(self.set_corr) self.levelValue.valueChanged.connect(self.set_level) self.openPlot.clicked.connect(self.plot_open) self.shortPlot.clicked.connect(self.plot_short) self.loadPlot.clicked.connect(self.plot_load) self.dutPlot.clicked.connect(self.plot_dut) self.smithPlot.clicked.connect(self.plot_smith) self.impPlot.clicked.connect(self.plot_imp) self.rcPlot.clicked.connect(self.plot_rc) self.swrPlot.clicked.connect(self.plot_swr) self.rlPlot.clicked.connect(self.plot_rl) self.gainPlot.clicked.connect(self.plot_gain) # create timer self.startTimer = QTimer(self) self.startTimer.timeout.connect(self.timeout) def start(self): if self.idle: self.connectButton.setEnabled(False) self.socket.connectToHost(self.addrValue.text(), 1001) self.startTimer.start(5000) else: self.stop() def stop(self): self.idle = True self.socket.abort() self.connectButton.setText('Connect') self.connectButton.setEnabled(True) self.sweepFrame.setEnabled(False) self.selectFrame.setEnabled(True) self.dutSweep.setEnabled(False) def timeout(self): self.display_error('timeout') def connected(self): self.startTimer.stop() self.idle = False self.set_start(self.startValue.value()) self.set_stop(self.stopValue.value()) self.set_size(self.sizeValue.value()) self.set_rate(self.rateValue.currentIndex()) self.set_corr(self.corrValue.value()) self.set_level(self.levelValue.value()) self.connectButton.setText('Disconnect') self.connectButton.setEnabled(True) self.sweepFrame.setEnabled(True) self.dutSweep.setEnabled(True) def read_data(self): if not self.reading: self.socket.readAll() return size = self.socket.bytesAvailable() self.progress.setValue((self.offset + size) / 24) limit = 24 * (self.sweep_size + 1) if self.offset + size < limit: self.buffer[self.offset:self.offset + size] = self.socket.read(size) self.offset += size else: self.buffer[self.offset:limit] = self.socket.read(limit - self.offset) self.adc1 = self.data[0::3] self.adc2 = self.data[1::3] self.dac1 = self.data[2::3] getattr(self, self.mode)[0:self.sweep_size] = self.adc1[1:self.sweep_size + 1] / self.dac1[1:self.sweep_size + 1] getattr(self, 'plot_%s' % self.mode)() self.reading = False self.sweepFrame.setEnabled(True) self.selectFrame.setEnabled(True) def display_error(self, socketError): self.startTimer.stop() if socketError == 'timeout': QMessageBox.information(self, 'VNA', 'Error: connection timeout.') else: QMessageBox.information(self, 'VNA', 'Error: %s.' % self.socket.errorString()) self.stop() def set_start(self, value): self.sweep_start = value self.xaxis, self.sweep_step = np.linspace(self.sweep_start, self.sweep_stop, self.sweep_size, retstep = True) self.xaxis *= 1000 if self.idle: return self.socket.write(struct.pack('<I', 0<<28 | int(value * 1000))) def set_stop(self, value): self.sweep_stop = value self.xaxis, self.sweep_step = np.linspace(self.sweep_start, self.sweep_stop, self.sweep_size, retstep = True) self.xaxis *= 1000 if self.idle: return self.socket.write(struct.pack('<I', 1<<28 | int(value * 1000))) def set_size(self, value): self.sweep_size = value self.xaxis, self.sweep_step = np.linspace(self.sweep_start, self.sweep_stop, self.sweep_size, retstep = True) self.xaxis *= 1000 if self.idle: return self.socket.write(struct.pack('<I', 2<<28 | int(value))) def set_rate(self, value): if self.idle: return rate = [1, 5, 10, 50, 100, 500][value] self.socket.write(struct.pack('<I', 3<<28 | int(rate))) def set_corr(self, value): if self.idle: return self.socket.write(struct.pack('<I', 4<<28 | int(value))) def set_level(self, value): if self.idle: return self.socket.write(struct.pack('<I', 5<<28 | int(32767 * np.power(10.0, value / 20.0)))) def sweep(self): if self.idle: return self.sweepFrame.setEnabled(False) self.selectFrame.setEnabled(False) self.socket.write(struct.pack('<I', 6<<28)) self.offset = 0 self.reading = True self.progress = QProgressDialog('Sweep status', 'Cancel', 0, self.sweep_size + 1) self.progress.setModal(True) self.progress.setMinimumDuration(1000) self.progress.canceled.connect(self.cancel) def cancel(self): self.offset = 0 self.reading = False self.socket.write(struct.pack('<I', 7<<28)) self.sweepFrame.setEnabled(True) self.selectFrame.setEnabled(True) def sweep_open(self): self.mode = 'open' self.sweep() def sweep_short(self): self.mode = 'short' self.sweep() def sweep_load(self): self.mode = 'load' self.sweep() def sweep_dut(self): self.mode = 'dut' self.sweep() def gain(self): size = self.sweep_size return self.dut[0:size]/self.short[0:size] def impedance(self): size = self.sweep_size return 50.0 * (self.open[0:size] - self.load[0:size]) * (self.dut[0:size] - self.short[0:size]) / ((self.load[0:size] - self.short[0:size]) * (self.open[0:size] - self.dut[0:size])) def gamma(self): z = self.impedance() return (z - 50.0)/(z + 50.0) def plot_gain(self): if self.cursor is not None: self.cursor.hide().disable() matplotlib.rcdefaults() self.figure.clf() self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98) axes1 = self.figure.add_subplot(111) axes1.cla() axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix)) axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix)) axes1.tick_params('y', color = 'blue', labelcolor = 'blue') axes1.yaxis.label.set_color('blue') gain = self.gain() axes1.plot(self.xaxis, 20.0 * np.log10(np.absolute(gain)), color = 'blue', label = 'Gain') axes2 = axes1.twinx() axes2.spines['left'].set_color('blue') axes2.spines['right'].set_color('red') axes1.set_xlabel('Hz') axes1.set_ylabel('Gain, dB') axes2.set_ylabel('Phase angle') axes2.tick_params('y', color = 'red', labelcolor = 'red') axes2.yaxis.label.set_color('red') axes2.plot(self.xaxis, np.angle(gain, deg = True), color = 'red', label = 'Phase angle') self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple') self.canvas.draw() def plot_magphase(self, data): if self.cursor is not None: self.cursor.hide().disable() matplotlib.rcdefaults() self.figure.clf() self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98) axes1 = self.figure.add_subplot(111) axes1.cla() axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix)) axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix)) axes1.tick_params('y', color = 'blue', labelcolor = 'blue') axes1.yaxis.label.set_color('blue') axes1.plot(self.xaxis, np.absolute(data), color = 'blue', label = 'Magnitude') axes2 = axes1.twinx() axes2.spines['left'].set_color('blue') axes2.spines['right'].set_color('red') axes1.set_xlabel('Hz') axes1.set_ylabel('Magnitude') axes2.set_ylabel('Phase angle') axes2.tick_params('y', color = 'red', labelcolor = 'red') axes2.yaxis.label.set_color('red') axes2.plot(self.xaxis, np.angle(data, deg = True), color = 'red', label = 'Phase angle') self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple') self.canvas.draw() def plot_open(self): self.plot_magphase(self.open[0:self.sweep_size]) def plot_short(self): self.plot_magphase(self.short[0:self.sweep_size]) def plot_load(self): self.plot_magphase(self.load[0:self.sweep_size]) def plot_dut(self): self.plot_magphase(self.dut[0:self.sweep_size]) def plot_smith_grid(self, axes, color): load = 50.0 ticks = np.array([0.0, 0.2, 0.5, 1.0, 2.0, 5.0]) for tick in ticks * load: axis = np.logspace(-4, np.log10(1.0e3), 200) * load z = tick + 1.0j * axis gamma = (z - load)/(z + load) axes.plot(gamma.real, gamma.imag, color = color, linewidth = 0.4, alpha = 0.3) axes.plot(gamma.real, -gamma.imag, color = color, linewidth = 0.4, alpha = 0.3) z = axis + 1.0j * tick gamma = (z - load)/(z + load) axes.plot(gamma.real, gamma.imag, color = color, linewidth = 0.4, alpha = 0.3) axes.plot(gamma.real, -gamma.imag, color = color, linewidth = 0.4, alpha = 0.3) if tick == 0.0: axes.text(1.0, 0.0, u'\u221E', color = color, ha = 'left', va = 'center', clip_on = True, fontsize = 18.0) axes.text(-1.0, 0.0, u'0\u03A9', color = color, ha = 'left', va = 'bottom', clip_on = True, fontsize = 12.0) continue lab = u'%d\u03A9' % tick x = (tick - load) / (tick + load) axes.text(x, 0.0, lab, color = color, ha = 'left', va = 'bottom', clip_on = True, fontsize = 12.0) lab = u'j%d\u03A9' % tick z = 1.0j * tick gamma = (z - load)/(z + load) * 1.05 x = gamma.real y = gamma.imag angle = np.angle(gamma) * 180.0 / np.pi - 90.0 axes.text(x, y, lab, color = color, ha = 'center', va = 'center', clip_on = True, rotation = angle, fontsize = 12.0) lab = u'-j%d\u03A9' % tick axes.text(x, -y, lab, color = color, ha = 'center', va = 'center', clip_on = True, rotation = -angle, fontsize = 12.0) def plot_smith(self): if self.cursor is not None: self.cursor.hide().disable() matplotlib.rcdefaults() self.figure.clf() self.figure.subplots_adjust(left = 0.0, bottom = 0.0, right = 1.0, top = 1.0) axes1 = self.figure.add_subplot(111) self.plot_smith_grid(axes1, 'blue') gamma = self.gamma() plot, = axes1.plot(gamma.real, gamma.imag, color = 'red') axes1.axis('equal') axes1.set_xlim(-1.12, 1.12) axes1.set_ylim(-1.12, 1.12) axes1.xaxis.set_visible(False) axes1.yaxis.set_visible(False) for loc, spine in axes1.spines.items(): spine.set_visible(False) self.cursor = datacursor(plot, formatter = SmithFormatter(self.xaxis), display = 'multiple') self.canvas.draw() def plot_imp(self): self.plot_magphase(self.impedance()) def plot_rc(self): self.plot_magphase(self.gamma()) def plot_swr(self): if self.cursor is not None: self.cursor.hide().disable() matplotlib.rcdefaults() self.figure.clf() self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98) axes1 = self.figure.add_subplot(111) axes1.cla() axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix)) axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix)) axes1.set_xlabel('Hz') axes1.set_ylabel('SWR') magnitude = np.absolute(self.gamma()) swr = np.maximum(1.0, np.minimum(100.0, (1.0 + magnitude) / np.maximum(1.0e-20, 1.0 - magnitude))) axes1.plot(self.xaxis, swr, color = 'blue', label = 'SWR') self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple') self.canvas.draw() def plot_rl(self): if self.cursor is not None: self.cursor.hide().disable() matplotlib.rcdefaults() self.figure.clf() self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98) axes1 = self.figure.add_subplot(111) axes1.cla() axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix)) axes1.set_xlabel('Hz') axes1.set_ylabel('Return loss, dB') magnitude = np.absolute(self.gamma()) axes1.plot(self.xaxis, 20.0 * np.log10(magnitude), color = 'blue', label = 'Return loss') self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple') self.canvas.draw() def write_cfg(self): dialog = QFileDialog(self, 'Write configuration settings', '.', '*.ini') dialog.setDefaultSuffix('ini') dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setOptions(QFileDialog.DontConfirmOverwrite) if dialog.exec() == QDialog.Accepted: name = dialog.selectedFiles() settings = QSettings(name[0], QSettings.IniFormat) self.write_cfg_settings(settings) def read_cfg(self): dialog = QFileDialog(self, 'Read configuration settings', '.', '*.ini') dialog.setDefaultSuffix('ini') dialog.setAcceptMode(QFileDialog.AcceptOpen) if dialog.exec() == QDialog.Accepted: name = dialog.selectedFiles() settings = QSettings(name[0], QSettings.IniFormat) self.read_cfg_settings(settings) def write_cfg_settings(self, settings): settings.setValue('addr', self.addrValue.text()) settings.setValue('start', self.startValue.value()) settings.setValue('stop', self.stopValue.value()) settings.setValue('rate', self.rateValue.currentIndex()) settings.setValue('corr', self.corrValue.value()) size = self.sizeValue.value() settings.setValue('size', size) for i in range(0, size): settings.setValue('open_real_%d' % i, float(self.open.real[i])) settings.setValue('open_imag_%d' % i, float(self.open.imag[i])) for i in range(0, size): settings.setValue('short_real_%d' % i, float(self.short.real[i])) settings.setValue('short_imag_%d' % i, float(self.short.imag[i])) for i in range(0, size): settings.setValue('load_real_%d' % i, float(self.load.real[i])) settings.setValue('load_imag_%d' % i, float(self.load.imag[i])) for i in range(0, size): settings.setValue('dut_real_%d' % i, float(self.dut.real[i])) settings.setValue('dut_imag_%d' % i, float(self.dut.imag[i])) def read_cfg_settings(self, settings): self.addrValue.setText(settings.value('addr', '192.168.1.100')) self.startValue.setValue(settings.value('start', 100, type = int)) self.stopValue.setValue(settings.value('stop', 60000, type = int)) self.rateValue.setCurrentIndex(settings.value('rate', 0, type = int)) self.corrValue.setValue(settings.value('corr', 0, type = int)) size = settings.value('size', 600, type = int) self.sizeValue.setValue(size) for i in range(0, size): real = settings.value('open_real_%d' % i, 0.0, type = float) imag = settings.value('open_imag_%d' % i, 0.0, type = float) self.open[i] = real + 1.0j * imag for i in range(0, size): real = settings.value('short_real_%d' % i, 0.0, type = float) imag = settings.value('short_imag_%d' % i, 0.0, type = float) self.short[i] = real + 1.0j * imag for i in range(0, size): real = settings.value('load_real_%d' % i, 0.0, type = float) imag = settings.value('load_imag_%d' % i, 0.0, type = float) self.load[i] = real + 1.0j * imag for i in range(0, size): real = settings.value('dut_real_%d' % i, 0.0, type = float) imag = settings.value('dut_imag_%d' % i, 0.0, type = float) self.dut[i] = real + 1.0j * imag def write_csv(self): dialog = QFileDialog(self, 'Write csv file', '.', '*.csv') dialog.setDefaultSuffix('csv') dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setOptions(QFileDialog.DontConfirmOverwrite) if dialog.exec() == QDialog.Accepted: name = dialog.selectedFiles() fh = open(name[0], 'w') gamma = self.gamma() size = self.sizeValue.value() fh.write('frequency;open.real;open.imag;short.real;short.imag;load.real;load.imag;dut.real;dut.imag\n') for i in range(0, size): fh.write('0.0%.8d;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f\n' % (self.xaxis[i], self.open.real[i], self.open.imag[i], self.short.real[i], self.short.imag[i], self.load.real[i], self.load.imag[i], self.dut.real[i], self.dut.imag[i])) fh.close() def write_s1p(self): dialog = QFileDialog(self, 'Write s1p file', '.', '*.s1p') dialog.setDefaultSuffix('s1p') dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setOptions(QFileDialog.DontConfirmOverwrite) if dialog.exec() == QDialog.Accepted: name = dialog.selectedFiles() fh = open(name[0], 'w') gamma = self.gamma() size = self.sizeValue.value() fh.write('# GHz S MA R 50\n') for i in range(0, size): fh.write('0.0%.8d %8.6f %7.2f\n' % (self.xaxis[i], np.absolute(gamma[i]), np.angle(gamma[i], deg = True))) fh.close() def write_s2p(self): dialog = QFileDialog(self, 'Write s2p file', '.', '*.s2p') dialog.setDefaultSuffix('s2p') dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setOptions(QFileDialog.DontConfirmOverwrite) if dialog.exec() == QDialog.Accepted: name = dialog.selectedFiles() fh = open(name[0], 'w') gain = self.gain() gamma = self.gamma() size = self.sizeValue.value() fh.write('# GHz S MA R 50\n') for i in range(0, size): fh.write('0.0%.8d %8.6f %7.2f %8.6f %7.2f 0.000000 0.00 0.000000 0.00\n' % (self.xaxis[i], np.absolute(gamma[i]), np.angle(gamma[i], deg = True), np.absolute(gain[i]), np.angle(gain[i], deg = True))) fh.close()
class VNA(QMainWindow, Ui_VNA): graphs = ['open', 'short', 'load', 'dut', 'smith', 'imp', 'swr', 'gamma', 'rl', 'gain_short', 'gain_open'] def __init__(self): super(VNA, self).__init__() self.setupUi(self) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variables self.idle = True self.reading = False self.auto = False # sweep parameters self.sweep_start = 10 self.sweep_stop = 60000 self.sweep_size = 6000 # buffer and offset for the incoming samples self.buffer = bytearray(16 * 32768) self.offset = 0 self.data = np.frombuffer(self.buffer, np.complex64) # create measurements self.open = Measurement(self.sweep_start, self.sweep_stop, self.sweep_size) self.short = Measurement(self.sweep_start, self.sweep_stop, self.sweep_size) self.load = Measurement(self.sweep_start, self.sweep_stop, self.sweep_size) self.dut = Measurement(self.sweep_start, self.sweep_stop, self.sweep_size) self.mode = 'open' # create figures self.tabs = {} for i in range(len(self.graphs)): layout = getattr(self, '%sLayout' % self.graphs[i]) self.tabs[i] = FigureTab(layout, self) # configure widgets self.rateValue.addItems(['10000', '5000', '1000', '500', '100', '50', '10', '5', '1']) self.rateValue.lineEdit().setReadOnly(True) self.rateValue.lineEdit().setAlignment(Qt.AlignRight) for i in range(self.rateValue.count()): self.rateValue.setItemData(i, Qt.AlignRight, Qt.TextAlignmentRole) self.set_enabled(False) self.stopSweep.setEnabled(False) # read settings settings = QSettings('vna.ini', QSettings.IniFormat) self.read_cfg_settings(settings) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from widgets self.connectButton.clicked.connect(self.start) self.writeButton.clicked.connect(self.write_cfg) self.readButton.clicked.connect(self.read_cfg) self.openSweep.clicked.connect(partial(self.sweep, 'open')) self.shortSweep.clicked.connect(partial(self.sweep, 'short')) self.loadSweep.clicked.connect(partial(self.sweep, 'load')) self.singleSweep.clicked.connect(partial(self.sweep, 'dut')) self.autoSweep.clicked.connect(self.sweep_auto) self.stopSweep.clicked.connect(self.cancel) self.csvButton.clicked.connect(self.write_csv) self.s1pButton.clicked.connect(self.write_s1p) self.s2pshortButton.clicked.connect(self.write_s2p_short) self.s2popenButton.clicked.connect(self.write_s2p_open) self.startValue.valueChanged.connect(self.set_start) self.stopValue.valueChanged.connect(self.set_stop) self.sizeValue.valueChanged.connect(self.set_size) self.rateValue.currentIndexChanged.connect(self.set_rate) self.corrValue.valueChanged.connect(self.set_corr) self.phase1Value.valueChanged.connect(self.set_phase1) self.phase2Value.valueChanged.connect(self.set_phase2) self.level1Value.valueChanged.connect(self.set_level1) self.level2Value.valueChanged.connect(self.set_level2) self.tabWidget.currentChanged.connect(self.update_tab) # create timers self.startTimer = QTimer(self) self.startTimer.timeout.connect(self.timeout) self.sweepTimer = QTimer(self) self.sweepTimer.timeout.connect(self.sweep_timeout) def set_enabled(self, enabled): widgets = [self.rateValue, self.level1Value, self.level2Value, self.corrValue, self.phase1Value, self.phase2Value, self.startValue, self.stopValue, self.sizeValue, self.openSweep, self.shortSweep, self.loadSweep, self.singleSweep, self.autoSweep] for entry in widgets: entry.setEnabled(enabled) def start(self): if self.idle: self.connectButton.setEnabled(False) self.socket.connectToHost(self.addrValue.text(), 1001) self.startTimer.start(5000) else: self.stop() def stop(self): self.idle = True self.cancel() self.socket.abort() self.connectButton.setText('Connect') self.connectButton.setEnabled(True) self.set_enabled(False) self.stopSweep.setEnabled(False) def timeout(self): self.display_error('timeout') def connected(self): self.startTimer.stop() self.idle = False self.set_rate(self.rateValue.currentIndex()) self.set_corr(self.corrValue.value()) self.set_phase1(self.phase1Value.value()) self.set_phase2(self.phase2Value.value()) self.set_level1(self.level1Value.value()) self.set_level2(self.level2Value.value()) self.set_gpio(1) self.connectButton.setText('Disconnect') self.connectButton.setEnabled(True) self.set_enabled(True) self.stopSweep.setEnabled(True) def read_data(self): while(self.socket.bytesAvailable() > 0): if not self.reading: self.socket.readAll() return size = self.socket.bytesAvailable() self.progressBar.setValue((self.offset + size) / 16) limit = 16 * self.sweep_size if self.offset + size < limit: self.buffer[self.offset:self.offset + size] = self.socket.read(size) self.offset += size else: self.buffer[self.offset:limit] = self.socket.read(limit - self.offset) adc1 = self.data[0::2] adc2 = self.data[1::2] attr = getattr(self, self.mode) start = self.sweep_start stop = self.sweep_stop size = self.sweep_size attr.freq = np.linspace(start, stop, size) attr.data = adc1[0:size].copy() self.update_tab() self.reading = False if not self.auto: self.progressBar.setValue(0) self.set_enabled(True) def display_error(self, socketError): self.startTimer.stop() if socketError == 'timeout': QMessageBox.information(self, 'VNA', 'Error: connection timeout.') else: QMessageBox.information(self, 'VNA', 'Error: %s.' % self.socket.errorString()) self.stop() def set_start(self, value): self.sweep_start = value def set_stop(self, value): self.sweep_stop = value def set_size(self, value): self.sweep_size = value def set_rate(self, value): if self.idle: return rate = [5, 10, 50, 100, 500, 1000, 5000, 10000, 50000][value] self.socket.write(struct.pack('<I', 3<<28 | int(rate))) def set_corr(self, value): if self.idle: return self.socket.write(struct.pack('<I', 4<<28 | int(value))) def set_phase1(self, value): if self.idle: return self.socket.write(struct.pack('<I', 5<<28 | int(value))) def set_phase2(self, value): if self.idle: return self.socket.write(struct.pack('<I', 6<<28 | int(value))) def set_level1(self, value): if self.idle: return data = 0 if value == -90 else int(32766 * np.power(10.0, value / 20.0)) self.socket.write(struct.pack('<I', 7<<28 | int(data))) def set_level2(self, value): if self.idle: return data = 0 if value == -90 else int(32766 * np.power(10.0, value / 20.0)) self.socket.write(struct.pack('<I', 8<<28 | int(data))) def set_gpio(self, value): if self.idle: return self.socket.write(struct.pack('<I', 9<<28 | int(value))) def sweep(self, mode): if self.idle: return self.set_enabled(False) self.mode = mode self.offset = 0 self.reading = True self.socket.write(struct.pack('<I', 0<<28 | int(self.sweep_start * 1000))) self.socket.write(struct.pack('<I', 1<<28 | int(self.sweep_stop * 1000))) self.socket.write(struct.pack('<I', 2<<28 | int(self.sweep_size))) self.socket.write(struct.pack('<I', 10<<28)) self.progressBar.setMinimum(0) self.progressBar.setMaximum(self.sweep_size) self.progressBar.setValue(0) def cancel(self): self.sweepTimer.stop() self.auto = False self.reading = False self.socket.write(struct.pack('<I', 11<<28)) self.progressBar.setValue(0) self.set_enabled(True) def sweep_auto(self): self.auto = True self.sweepTimer.start(100) def sweep_timeout(self): if not self.reading: self.sweep('dut') def update_tab(self): index = self.tabWidget.currentIndex() self.tabs[index].update(self.graphs[index]) def interp(self, freq, meas): real = np.interp(freq, meas.freq, meas.data.real, period = meas.period) imag = np.interp(freq, meas.freq, meas.data.imag, period = meas.period) return real + 1j * imag def gain_short(self, freq): short = self.interp(freq, self.short) dut = self.interp(freq, self.dut) return np.divide(dut, short) def gain_open(self, freq): open = self.interp(freq, self.open) dut = self.interp(freq, self.dut) return np.divide(dut, open) def impedance(self, freq): open = self.interp(freq, self.open) short = self.interp(freq, self.short) load = self.interp(freq, self.load) dut = self.interp(freq, self.dut) z = np.divide(50.0 * (open - load) * (dut - short), (load - short) * (open - dut)) z = np.asarray(z) z.real[z.real < 1.0e-2] = 9.99e-3 return z def gamma(self, freq): z = self.impedance(freq) return np.divide(z - 50.0, z + 50.0) def swr(self, freq): magnitude = np.absolute(self.gamma(freq)) swr = np.divide(1.0 + magnitude, 1.0 - magnitude) return np.clip(swr, 1.0, 99.99) def write_cfg(self): dialog = QFileDialog(self, 'Write configuration settings', '.', '*.ini') dialog.setDefaultSuffix('ini') dialog.selectFile('vna.ini') dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setOptions(QFileDialog.DontConfirmOverwrite) if dialog.exec() == QDialog.Accepted: name = dialog.selectedFiles() settings = QSettings(name[0], QSettings.IniFormat) self.write_cfg_settings(settings) def read_cfg(self): dialog = QFileDialog(self, 'Read configuration settings', '.', '*.ini') dialog.setDefaultSuffix('ini') dialog.selectFile('vna.ini') dialog.setAcceptMode(QFileDialog.AcceptOpen) if dialog.exec() == QDialog.Accepted: name = dialog.selectedFiles() settings = QSettings(name[0], QSettings.IniFormat) self.read_cfg_settings(settings) window.update_tab() def write_cfg_settings(self, settings): settings.setValue('addr', self.addrValue.text()) settings.setValue('rate', self.rateValue.currentIndex()) settings.setValue('corr', self.corrValue.value()) settings.setValue('phase_1', self.phase1Value.value()) settings.setValue('phase_2', self.phase2Value.value()) settings.setValue('level_1', self.level1Value.value()) settings.setValue('level_2', self.level2Value.value()) settings.setValue('open_start', int(self.open.freq[0])) settings.setValue('open_stop', int(self.open.freq[-1])) settings.setValue('open_size', self.open.freq.size) settings.setValue('short_start', int(self.short.freq[0])) settings.setValue('short_stop', int(self.short.freq[-1])) settings.setValue('short_size', self.short.freq.size) settings.setValue('load_start', int(self.load.freq[0])) settings.setValue('load_stop', int(self.load.freq[-1])) settings.setValue('load_size', self.load.freq.size) settings.setValue('dut_start', int(self.dut.freq[0])) settings.setValue('dut_stop', int(self.dut.freq[-1])) settings.setValue('dut_size', self.dut.freq.size) for i in range(len(FigureTab.cursors)): settings.setValue('cursor_%d' % i, FigureTab.cursors[i]) data = self.open.data for i in range(self.open.freq.size): settings.setValue('open_real_%d' % i, float(data.real[i])) settings.setValue('open_imag_%d' % i, float(data.imag[i])) data = self.short.data for i in range(self.short.freq.size): settings.setValue('short_real_%d' % i, float(data.real[i])) settings.setValue('short_imag_%d' % i, float(data.imag[i])) data = self.load.data for i in range(self.load.freq.size): settings.setValue('load_real_%d' % i, float(data.real[i])) settings.setValue('load_imag_%d' % i, float(data.imag[i])) data = self.dut.data for i in range(self.dut.freq.size): settings.setValue('dut_real_%d' % i, float(data.real[i])) settings.setValue('dut_imag_%d' % i, float(data.imag[i])) def read_cfg_settings(self, settings): self.addrValue.setText(settings.value('addr', '192.168.1.100')) self.rateValue.setCurrentIndex(settings.value('rate', 0, type = int)) self.corrValue.setValue(settings.value('corr', 0, type = int)) self.phase1Value.setValue(settings.value('phase_1', 0, type = int)) self.phase2Value.setValue(settings.value('phase_2', 0, type = int)) self.level1Value.setValue(settings.value('level_1', 0, type = int)) self.level2Value.setValue(settings.value('level_2', -90, type = int)) open_start = settings.value('open_start', 10, type = int) open_stop = settings.value('open_stop', 60000, type = int) open_size = settings.value('open_size', 6000, type = int) short_start = settings.value('short_start', 10, type = int) short_stop = settings.value('short_stop', 60000, type = int) short_size = settings.value('short_size', 6000, type = int) load_start = settings.value('load_start', 10, type = int) load_stop = settings.value('load_stop', 60000, type = int) load_size = settings.value('load_size', 6000, type = int) dut_start = settings.value('dut_start', 10, type = int) dut_stop = settings.value('dut_stop', 60000, type = int) dut_size = settings.value('dut_size', 6000, type = int) self.startValue.setValue(dut_start) self.stopValue.setValue(dut_stop) self.sizeValue.setValue(dut_size) for i in range(len(FigureTab.cursors)): FigureTab.cursors[i] = settings.value('cursor_%d' % i, FigureTab.cursors[i], type = int) self.open.freq = np.linspace(open_start, open_stop, open_size) self.open.data = np.zeros(open_size, np.complex64) for i in range(open_size): real = settings.value('open_real_%d' % i, 0.0, type = float) imag = settings.value('open_imag_%d' % i, 0.0, type = float) self.open.data[i] = real + 1.0j * imag self.short.freq = np.linspace(short_start, short_stop, short_size) self.short.data = np.zeros(short_size, np.complex64) for i in range(short_size): real = settings.value('short_real_%d' % i, 0.0, type = float) imag = settings.value('short_imag_%d' % i, 0.0, type = float) self.short.data[i] = real + 1.0j * imag self.load.freq = np.linspace(load_start, load_stop, load_size) self.load.data = np.zeros(load_size, np.complex64) for i in range(load_size): real = settings.value('load_real_%d' % i, 0.0, type = float) imag = settings.value('load_imag_%d' % i, 0.0, type = float) self.load.data[i] = real + 1.0j * imag self.dut.freq = np.linspace(dut_start, dut_stop, dut_size) self.dut.data = np.zeros(dut_size, np.complex64) for i in range(dut_size): real = settings.value('dut_real_%d' % i, 0.0, type = float) imag = settings.value('dut_imag_%d' % i, 0.0, type = float) self.dut.data[i] = real + 1.0j * imag def write_csv(self): dialog = QFileDialog(self, 'Write csv file', '.', '*.csv') dialog.setDefaultSuffix('csv') dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setOptions(QFileDialog.DontConfirmOverwrite) if dialog.exec() == QDialog.Accepted: name = dialog.selectedFiles() fh = open(name[0], 'w') f = self.dut.freq o = self.interp(f, self.open) s = self.interp(f, self.short) l = self.interp(f, self.load) d = self.dut.data fh.write('frequency;open.real;open.imag;short.real;short.imag;load.real;load.imag;dut.real;dut.imag\n') for i in range(f.size): fh.write('0.0%.8d;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f\n' % (f[i] * 1000, o.real[i], o.imag[i], s.real[i], s.imag[i], l.real[i], l.imag[i], d.real[i], d.imag[i])) fh.close() def write_s1p(self): dialog = QFileDialog(self, 'Write s1p file', '.', '*.s1p') dialog.setDefaultSuffix('s1p') dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setOptions(QFileDialog.DontConfirmOverwrite) if dialog.exec() == QDialog.Accepted: name = dialog.selectedFiles() fh = open(name[0], 'w') freq = self.dut.freq gamma = self.gamma(freq) fh.write('# GHz S MA R 50\n') for i in range(freq.size): fh.write('0.0%.8d %8.6f %7.2f\n' % (freq[i] * 1000, np.absolute(gamma[i]), np.angle(gamma[i], deg = True))) fh.close() def write_s2p(self, gain): dialog = QFileDialog(self, 'Write s2p file', '.', '*.s2p') dialog.setDefaultSuffix('s2p') dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setOptions(QFileDialog.DontConfirmOverwrite) if dialog.exec() == QDialog.Accepted: name = dialog.selectedFiles() fh = open(name[0], 'w') freq = self.dut.freq gamma = self.gamma(freq) fh.write('# GHz S MA R 50\n') for i in range(freq.size): fh.write('0.0%.8d %8.6f %7.2f %8.6f %7.2f 0.000000 0.00 0.000000 0.00\n' % (freq[i] * 1000, np.absolute(gamma[i]), np.angle(gamma[i], deg = True), np.absolute(gain[i]), np.angle(gain[i], deg = True))) fh.close() def write_s2p_short(self): self.write_s2p(self.gain_short(self.dut.freq)) def write_s2p_open(self): self.write_s2p(self.gain_open(self.dut.freq))
def __init__(self): super(VNA, self).__init__() self.setupUi(self) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variable self.idle = True # sweep parameters self.sweep_start = 100 self.sweep_stop = 60000 self.sweep_size = 600 self.xaxis, self.sweep_step = np.linspace(self.sweep_start, self.sweep_stop, self.sweep_size, retstep = True) self.xaxis *= 1000 # buffer and offset for the incoming samples self.buffer = bytearray(32 * VNA.max_size) self.offset = 0 self.data = np.frombuffer(self.buffer, np.complex64) self.adc1 = np.zeros(VNA.max_size, np.complex64) self.adc2 = np.zeros(VNA.max_size, np.complex64) self.dac1 = np.zeros(VNA.max_size, np.complex64) self.open = np.zeros(VNA.max_size, np.complex64) self.short = np.zeros(VNA.max_size, np.complex64) self.load = np.zeros(VNA.max_size, np.complex64) self.dut = np.zeros(VNA.max_size, np.complex64) self.mode = 'dut' # create figure self.figure = Figure() self.figure.set_facecolor('none') self.canvas = FigureCanvas(self.figure) self.plotLayout.addWidget(self.canvas) # create navigation toolbar self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False) # remove subplots action actions = self.toolbar.actions() self.toolbar.removeAction(actions[7]) self.plotLayout.addWidget(self.toolbar) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from buttons and boxes self.sweepFrame.setEnabled(False) self.dutSweep.setEnabled(False) self.connectButton.clicked.connect(self.start) self.writeButton.clicked.connect(self.write_cfg) self.readButton.clicked.connect(self.read_cfg) self.openSweep.clicked.connect(self.sweep_open) self.shortSweep.clicked.connect(self.sweep_short) self.loadSweep.clicked.connect(self.sweep_load) self.dutSweep.clicked.connect(self.sweep_dut) self.s1pButton.clicked.connect(self.write_s1p) self.startValue.valueChanged.connect(self.set_start) self.stopValue.valueChanged.connect(self.set_stop) self.sizeValue.valueChanged.connect(self.set_size) self.openPlot.clicked.connect(self.plot_open) self.shortPlot.clicked.connect(self.plot_short) self.loadPlot.clicked.connect(self.plot_load) self.dutPlot.clicked.connect(self.plot_dut) self.smithPlot.clicked.connect(self.plot_smith) self.impPlot.clicked.connect(self.plot_imp) self.rcPlot.clicked.connect(self.plot_rc) self.swrPlot.clicked.connect(self.plot_swr) self.rlPlot.clicked.connect(self.plot_rl) # create timer self.startTimer = QTimer(self) self.startTimer.timeout.connect(self.timeout)
def __connectNetwork(self, name, connect, silent=False): """ Private slot to connect to or disconnect from the given network. @param name name of the network to connect to (string) @param connect flag indicating to connect (boolean) @keyparam silent flag indicating a silent connect/disconnect (boolean) """ if connect: network = self.__ircNetworkManager.getNetwork(name) if network: self.__server = network.getServer() self.__identityName = network.getIdentityName() identity = self.__ircNetworkManager.getIdentity( self.__identityName) self.__userName = identity.getIdent() self.__quitMessage = identity.getQuitMessage() if self.__server: useSSL = self.__server.useSSL() if useSSL and not SSL_AVAILABLE: E5MessageBox.critical( self, self.tr("SSL Connection"), self.tr( """An encrypted connection to the IRC""" """ network was requested but SSL is not""" """ available. Please change the server""" """ configuration.""")) return if useSSL: # create SSL socket self.__socket = QSslSocket(self) self.__socket.encrypted.connect(self.__hostConnected) self.__socket.sslErrors.connect(self.__sslErrors) else: # create TCP socket self.__socket = QTcpSocket(self) self.__socket.connected.connect(self.__hostConnected) self.__socket.hostFound.connect(self.__hostFound) self.__socket.disconnected.connect(self.__hostDisconnected) self.__socket.readyRead.connect(self.__readyRead) self.__socket.error.connect(self.__tcpError) self.__connectionState = IrcWidget.ServerConnecting if useSSL: self.networkWidget.addServerMessage( self.tr("Info"), self.tr("Looking for server {0} (port {1})" " using an SSL encrypted connection" "...").format(self.__server.getName(), self.__server.getPort())) self.__socket.connectToHostEncrypted( self.__server.getName(), self.__server.getPort()) else: self.networkWidget.addServerMessage( self.tr("Info"), self.tr( "Looking for server {0} (port {1})...").format( self.__server.getName(), self.__server.getPort())) self.__socket.connectToHost(self.__server.getName(), self.__server.getPort()) else: if silent: ok = True else: ok = E5MessageBox.yesNo( self, self.tr("Disconnect from Server"), self.tr("""<p>Do you really want to disconnect from""" """ <b>{0}</b>?</p><p>All channels will be""" """ closed.</p>""") .format(self.__server.getName())) if ok: self.networkWidget.addServerMessage( self.tr("Info"), self.tr("Disconnecting from server {0}...").format( self.__server.getName())) self.__closeAllChannels() self.__send("QUIT :" + self.__quitMessage) self.__socket and self.__socket.flush() self.__socket and self.__socket.close() self.__userName = "" self.__identityName = "" self.__quitMessage = ""
class Client(QDialog): def __init__(self, parent=None): super(Client, self).__init__(parent) self.networkSession = None self.blockSize = 0 self.currentFortune = "" hostLabel = QLabel("&Server name:") portLabel = QLabel("S&erver port:") self.hostCombo = QComboBox() self.hostCombo.setEditable(True) name = QHostInfo.localHostName() if name != "": self.hostCombo.addItem(name) domain = QHostInfo.localDomainName() if domain != "": self.hostCombo.addItem(name + "." + domain) if name != "localhost": self.hostCombo.addItem("localhost") ipAddressesList = QNetworkInterface.allAddresses() for ipAddress in ipAddressesList: if not ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) for ipAddress in ipAddressesList: if ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) hostLabel.setBuddy(self.hostCombo) portLabel.setBuddy(self.portLineEdit) self.statusLabel = QLabel("This examples requires that you run " "the Fortune Server example as well.") self.getFortuneButton = QPushButton("Get Fortune") self.getFortuneButton.setDefault(True) self.getFortuneButton.setEnabled(False) quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.tcpSocket = QTcpSocket(self) self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.tcpSocket.readyRead.connect(self.readFortune) self.tcpSocket.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostCombo, 0, 1) mainLayout.addWidget(portLabel, 1, 0) mainLayout.addWidget(self.portLineEdit, 1, 1) mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2) mainLayout.addWidget(buttonBox, 3, 0, 1, 2) self.setLayout(mainLayout) self.setWindowTitle("Fortune Client") self.portLineEdit.setFocus() manager = QNetworkConfigurationManager() if manager.capabilities() & QNetworkConfigurationManager.NetworkSessionRequired: settings = QSettings(QSettings.UserScope, "QtProject") settings.beginGroup("QtNetwork") id = settings.value("DefaultNetworkConfiguration") settings.endGroup() config = manager.configurationFromIdentifier(id) if config.state() & QNetworkConfiguration.Discovered == 0: config = manager.defaultConfiguration() self.networkSession = QNetworkSession(config, self) self.networkSession.opened.connect(self.sessionOpened) self.getFortuneButton.setEnabled(False) self.statusLabel.setText("Opening network session.") self.networkSession.open() def requestNewFortune(self): self.getFortuneButton.setEnabled(False) self.blockSize = 0 self.tcpSocket.abort() self.tcpSocket.connectToHost(self.hostCombo.currentText(), int(self.portLineEdit.text())) def readFortune(self): instr = QDataStream(self.tcpSocket) instr.setVersion(QDataStream.Qt_4_0) if self.blockSize == 0: if self.tcpSocket.bytesAvailable() < 2: return self.blockSize = instr.readUInt16() if self.tcpSocket.bytesAvailable() < self.blockSize: return nextFortune = instr.readQString() if nextFortune == self.currentFortune: QTimer.singleShot(0, self.requestNewFortune) return self.currentFortune = nextFortune self.statusLabel.setText(self.currentFortune) self.getFortuneButton.setEnabled(True) def displayError(self, socketError): if socketError == QAbstractSocket.RemoteHostClosedError: pass elif socketError == QAbstractSocket.HostNotFoundError: QMessageBox.information( self, "Fortune Client", "The host was not found. Please check the host name and " "port settings." ) elif socketError == QAbstractSocket.ConnectionRefusedError: QMessageBox.information( self, "Fortune Client", "The connection was refused by the peer. Make sure the " "fortune server is running, and check that the host name " "and port settings are correct.", ) else: QMessageBox.information( self, "Fortune Client", "The following error occurred: %s." % self.tcpSocket.errorString() ) self.getFortuneButton.setEnabled(True) def enableGetFortuneButton(self): self.getFortuneButton.setEnabled( (self.networkSession is None or self.networkSession.isOpen()) and self.hostCombo.currentText() != "" and self.portLineEdit.text() != "" ) def sessionOpened(self): config = self.networkSession.configuration() if config.type() == QNetworkConfiguration.UserChoice: id = self.networkSession.sessionProperty("UserChoiceConfiguration") else: id = config.identifier() settings = QSettings(QSettings.UserScope, "QtProject") settings.beginGroup("QtNetwork") settings.setValue("DefaultNetworkConfiguration", id) settings.endGroup() self.statusLabel.setText("This examples requires that you run the " "Fortune Server example as well.") self.enableGetFortuneButton()
def __init__(self): super(VNA, self).__init__() self.setupUi(self) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variables self.idle = True self.reading = False self.auto = False # sweep parameters self.sweep_start = 10 self.sweep_stop = 60000 self.sweep_size = 6000 # buffer and offset for the incoming samples self.buffer = bytearray(16 * 32768) self.offset = 0 self.data = np.frombuffer(self.buffer, np.complex64) # create measurements self.open = Measurement(self.sweep_start, self.sweep_stop, self.sweep_size) self.short = Measurement(self.sweep_start, self.sweep_stop, self.sweep_size) self.load = Measurement(self.sweep_start, self.sweep_stop, self.sweep_size) self.dut = Measurement(self.sweep_start, self.sweep_stop, self.sweep_size) self.mode = 'open' # create figures self.tabs = {} for i in range(len(self.graphs)): layout = getattr(self, '%sLayout' % self.graphs[i]) self.tabs[i] = FigureTab(layout, self) # configure widgets self.rateValue.addItems(['10000', '5000', '1000', '500', '100', '50', '10', '5', '1']) self.rateValue.lineEdit().setReadOnly(True) self.rateValue.lineEdit().setAlignment(Qt.AlignRight) for i in range(self.rateValue.count()): self.rateValue.setItemData(i, Qt.AlignRight, Qt.TextAlignmentRole) self.set_enabled(False) self.stopSweep.setEnabled(False) # read settings settings = QSettings('vna.ini', QSettings.IniFormat) self.read_cfg_settings(settings) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from widgets self.connectButton.clicked.connect(self.start) self.writeButton.clicked.connect(self.write_cfg) self.readButton.clicked.connect(self.read_cfg) self.openSweep.clicked.connect(partial(self.sweep, 'open')) self.shortSweep.clicked.connect(partial(self.sweep, 'short')) self.loadSweep.clicked.connect(partial(self.sweep, 'load')) self.singleSweep.clicked.connect(partial(self.sweep, 'dut')) self.autoSweep.clicked.connect(self.sweep_auto) self.stopSweep.clicked.connect(self.cancel) self.csvButton.clicked.connect(self.write_csv) self.s1pButton.clicked.connect(self.write_s1p) self.s2pshortButton.clicked.connect(self.write_s2p_short) self.s2popenButton.clicked.connect(self.write_s2p_open) self.startValue.valueChanged.connect(self.set_start) self.stopValue.valueChanged.connect(self.set_stop) self.sizeValue.valueChanged.connect(self.set_size) self.rateValue.currentIndexChanged.connect(self.set_rate) self.corrValue.valueChanged.connect(self.set_corr) self.phase1Value.valueChanged.connect(self.set_phase1) self.phase2Value.valueChanged.connect(self.set_phase2) self.level1Value.valueChanged.connect(self.set_level1) self.level2Value.valueChanged.connect(self.set_level2) self.tabWidget.currentChanged.connect(self.update_tab) # create timers self.startTimer = QTimer(self) self.startTimer.timeout.connect(self.timeout) self.sweepTimer = QTimer(self) self.sweepTimer.timeout.connect(self.sweep_timeout)
class IrcWidget(QWidget, Ui_IrcWidget): """ Class implementing the IRC window. @signal autoConnected() emitted after an automatic connection was initiated """ autoConnected = pyqtSignal() ServerDisconnected = 1 ServerConnected = 2 ServerConnecting = 3 def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super(IrcWidget, self).__init__(parent) self.setupUi(self) from .IrcNetworkManager import IrcNetworkManager self.__ircNetworkManager = IrcNetworkManager(self) self.__leaveButton = QToolButton(self) self.__leaveButton.setIcon( UI.PixmapCache.getIcon("ircCloseChannel.png")) self.__leaveButton.setToolTip( self.tr("Press to leave the current channel")) self.__leaveButton.clicked.connect(self.__leaveChannel) self.__leaveButton.setEnabled(False) self.channelsWidget.setCornerWidget( self.__leaveButton, Qt.BottomRightCorner) self.channelsWidget.setTabsClosable(False) if not isMacPlatform(): self.channelsWidget.setTabPosition(QTabWidget.South) height = self.height() self.splitter.setSizes([height * 0.6, height * 0.4]) self.__channelList = [] self.__channelTypePrefixes = "" self.__userName = "" self.__identityName = "" self.__quitMessage = "" self.__nickIndex = -1 self.__nickName = "" self.__server = None self.__registering = False self.__connectionState = IrcWidget.ServerDisconnected self.__sslErrorLock = False self.__buffer = "" self.__userPrefix = {} self.__socket = None if SSL_AVAILABLE: self.__sslErrorHandler = E5SslErrorHandler(self) else: self.__sslErrorHandler = None self.__patterns = [ # :[email protected] PRIVMSG bar_ :some long message (re.compile(r":([^!]+)!([^ ]+)\sPRIVMSG\s([^ ]+)\s:(.*)"), self.__query), # :foo.bar.net COMMAND some message (re.compile(r""":([^ ]+)\s+([A-Z]+)\s+(.+)"""), self.__handleNamedMessage), # :foo.bar.net 123 * :info (re.compile(r""":([^ ]+)\s+(\d{3})\s+(.+)"""), self.__handleNumericMessage), # PING :ping message (re.compile(r"""PING\s+:(.*)"""), self.__ping), ] self.__prefixRe = re.compile(r""".*\sPREFIX=\((.*)\)([^ ]+).*""") self.__chanTypesRe = re.compile(r""".*\sCHANTYPES=([^ ]+).*""") ircPic = UI.PixmapCache.getPixmap("irc128.png") self.__emptyLabel = QLabel() self.__emptyLabel.setPixmap(ircPic) self.__emptyLabel.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter) self.channelsWidget.addTab(self.__emptyLabel, "") # all initialized, do connections now self.__ircNetworkManager.dataChanged.connect(self.__networkDataChanged) self.networkWidget.initialize(self.__ircNetworkManager) self.networkWidget.connectNetwork.connect(self.__connectNetwork) self.networkWidget.editNetwork.connect(self.__editNetwork) self.networkWidget.joinChannel.connect(self.__joinChannel) self.networkWidget.nickChanged.connect(self.__changeNick) self.networkWidget.sendData.connect(self.__send) self.networkWidget.away.connect(self.__away) self.networkWidget.autoConnected.connect(self.autoConnected) def shutdown(self): """ Public method to shut down the widget. @return flag indicating successful shutdown (boolean) """ if self.__server: if Preferences.getIrc("AskOnShutdown"): ok = E5MessageBox.yesNo( self, self.tr("Disconnect from Server"), self.tr( """<p>Do you really want to disconnect from""" """ <b>{0}</b>?</p><p>All channels will be closed.""" """</p>""").format(self.__server.getName())) else: ok = True if ok: self.__socket.blockSignals(True) self.__send("QUIT :" + self.__quitMessage) self.__socket.flush() self.__socket.close() self.__socket.deleteLater() self.__socket = None else: ok = True if ok: self.__ircNetworkManager.close() return ok def autoConnect(self): """ Public method to initiate the IRC auto connection. """ self.networkWidget.autoConnect() def __connectNetwork(self, name, connect, silent=False): """ Private slot to connect to or disconnect from the given network. @param name name of the network to connect to (string) @param connect flag indicating to connect (boolean) @keyparam silent flag indicating a silent connect/disconnect (boolean) """ if connect: network = self.__ircNetworkManager.getNetwork(name) if network: self.__server = network.getServer() self.__identityName = network.getIdentityName() identity = self.__ircNetworkManager.getIdentity( self.__identityName) self.__userName = identity.getIdent() self.__quitMessage = identity.getQuitMessage() if self.__server: useSSL = self.__server.useSSL() if useSSL and not SSL_AVAILABLE: E5MessageBox.critical( self, self.tr("SSL Connection"), self.tr( """An encrypted connection to the IRC""" """ network was requested but SSL is not""" """ available. Please change the server""" """ configuration.""")) return if useSSL: # create SSL socket self.__socket = QSslSocket(self) self.__socket.encrypted.connect(self.__hostConnected) self.__socket.sslErrors.connect(self.__sslErrors) else: # create TCP socket self.__socket = QTcpSocket(self) self.__socket.connected.connect(self.__hostConnected) self.__socket.hostFound.connect(self.__hostFound) self.__socket.disconnected.connect(self.__hostDisconnected) self.__socket.readyRead.connect(self.__readyRead) self.__socket.error.connect(self.__tcpError) self.__connectionState = IrcWidget.ServerConnecting if useSSL: self.networkWidget.addServerMessage( self.tr("Info"), self.tr("Looking for server {0} (port {1})" " using an SSL encrypted connection" "...").format(self.__server.getName(), self.__server.getPort())) self.__socket.connectToHostEncrypted( self.__server.getName(), self.__server.getPort()) else: self.networkWidget.addServerMessage( self.tr("Info"), self.tr( "Looking for server {0} (port {1})...").format( self.__server.getName(), self.__server.getPort())) self.__socket.connectToHost(self.__server.getName(), self.__server.getPort()) else: if silent: ok = True else: ok = E5MessageBox.yesNo( self, self.tr("Disconnect from Server"), self.tr("""<p>Do you really want to disconnect from""" """ <b>{0}</b>?</p><p>All channels will be""" """ closed.</p>""") .format(self.__server.getName())) if ok: self.networkWidget.addServerMessage( self.tr("Info"), self.tr("Disconnecting from server {0}...").format( self.__server.getName())) self.__closeAllChannels() self.__send("QUIT :" + self.__quitMessage) self.__socket and self.__socket.flush() self.__socket and self.__socket.close() self.__userName = "" self.__identityName = "" self.__quitMessage = "" def __editNetwork(self, name): """ Private slot to edit the network configuration. @param name name of the network to edit (string) """ from .IrcNetworkListDialog import IrcNetworkListDialog dlg = IrcNetworkListDialog(self.__ircNetworkManager, self) dlg.exec_() def __networkDataChanged(self): """ Private slot handling changes of the network and identity definitions. """ identity = self.__ircNetworkManager.getIdentity(self.__identityName) if identity: partMsg = identity.getPartMessage() for channel in self.__channelList: channel.setPartMessage(partMsg) def __joinChannel(self, name, key=""): """ Private slot to join a channel. @param name name of the channel (string) @param key key of the channel (string) """ # step 1: check, if this channel is already joined for channel in self.__channelList: if channel.name() == name: return from .IrcChannelWidget import IrcChannelWidget channel = IrcChannelWidget(self) channel.setName(name) channel.setUserName(self.__nickName) identity = self.__ircNetworkManager.getIdentity(self.__identityName) channel.setPartMessage(identity.getPartMessage()) channel.setUserPrivilegePrefix(self.__userPrefix) channel.initAutoWho() channel.sendData.connect(self.__send) channel.sendCtcpReply.connect(self.__sendCtcpReply) channel.channelClosed.connect(self.__closeChannel) channel.openPrivateChat.connect(self.__openPrivate) self.channelsWidget.addTab(channel, name) self.__channelList.append(channel) self.channelsWidget.setCurrentWidget(channel) joinCommand = ["JOIN", name] if key: joinCommand.append(key) self.__send(" ".join(joinCommand)) self.__send("MODE " + name) emptyIndex = self.channelsWidget.indexOf(self.__emptyLabel) if emptyIndex > -1: self.channelsWidget.removeTab(emptyIndex) self.__leaveButton.setEnabled(True) self.channelsWidget.setTabsClosable(True) def __query(self, match): """ Private method to handle a new private connection. @param match reference to the match object @return flag indicating, if the message was handled (boolean) """ # group(1) sender user name # group(2) sender user@host # group(3) target nick # group(4) message if match.group(4).startswith("\x01"): return self.__handleCtcp(match) self.__openPrivate(match.group(1)) # the above call sets the new channel as the current widget channel = self.channelsWidget.currentWidget() channel.addMessage(match.group(1), match.group(4)) channel.setPrivateInfo( "{0} - {1}".format(match.group(1), match.group(2))) return True @pyqtSlot(str) def __openPrivate(self, name): """ Private slot to open a private chat with the given user. @param name name of the user (string) """ from .IrcChannelWidget import IrcChannelWidget channel = IrcChannelWidget(self) channel.setName(self.__nickName) channel.setUserName(self.__nickName) identity = self.__ircNetworkManager.getIdentity(self.__identityName) channel.setPartMessage(identity.getPartMessage()) channel.setUserPrivilegePrefix(self.__userPrefix) channel.setPrivate(True, name) channel.addUsers([name, self.__nickName]) channel.sendData.connect(self.__send) channel.sendCtcpReply.connect(self.__sendCtcpReply) channel.channelClosed.connect(self.__closeChannel) self.channelsWidget.addTab(channel, name) self.__channelList.append(channel) self.channelsWidget.setCurrentWidget(channel) @pyqtSlot() def __leaveChannel(self): """ Private slot to leave a channel and close the associated tab. """ channel = self.channelsWidget.currentWidget() channel.requestLeave() def __closeAllChannels(self): """ Private method to close all channels. """ while self.__channelList: channel = self.__channelList.pop() self.channelsWidget.removeTab(self.channelsWidget.indexOf(channel)) channel.deleteLater() channel = None self.channelsWidget.addTab(self.__emptyLabel, "") self.__emptyLabel.show() self.__leaveButton.setEnabled(False) self.channelsWidget.setTabsClosable(False) def __closeChannel(self, name): """ Private slot handling the closing of a channel. @param name name of the closed channel (string) """ for channel in self.__channelList: if channel.name() == name: self.channelsWidget.removeTab( self.channelsWidget.indexOf(channel)) self.__channelList.remove(channel) channel.deleteLater() if self.channelsWidget.count() == 0: self.channelsWidget.addTab(self.__emptyLabel, "") self.__emptyLabel.show() self.__leaveButton.setEnabled(False) self.channelsWidget.setTabsClosable(False) @pyqtSlot(int) def on_channelsWidget_tabCloseRequested(self, index): """ Private slot to close a channel by pressing the close button of the channels widget. @param index index of the tab to be closed (integer) """ channel = self.channelsWidget.widget(index) channel.requestLeave() def __send(self, data): """ Private slot to send data to the IRC server. @param data data to be sent (string) """ if self.__socket: self.__socket.write( QByteArray("{0}\r\n".format(data).encode("utf-8"))) def __sendCtcpReply(self, receiver, text): """ Private slot to send a CTCP reply. @param receiver nick name of the receiver (string) @param text text to be sent (string) """ self.__send("NOTICE {0} :\x01{1}\x01".format(receiver, text)) def __hostFound(self): """ Private slot to indicate the host was found. """ self.networkWidget.addServerMessage( self.tr("Info"), self.tr("Server found,connecting...")) def __hostConnected(self): """ Private slot to log in to the server after the connection was established. """ self.networkWidget.addServerMessage( self.tr("Info"), self.tr("Connected,logging in...")) self.networkWidget.setConnected(True) self.__registering = True serverPassword = self.__server.getPassword() if serverPassword: self.__send("PASS " + serverPassword) nick = self.networkWidget.getNickname() if not nick: self.__nickIndex = 0 try: nick = self.__ircNetworkManager.getIdentity( self.__identityName).getNickNames()[self.__nickIndex] except IndexError: nick = "" if not nick: nick = self.__userName self.__nickName = nick self.networkWidget.setNickName(nick) realName = self.__ircNetworkManager.getIdentity( self.__identityName).getRealName() if not realName: realName = "eric IDE chat" self.__send("NICK " + nick) self.__send("USER " + self.__userName + " 0 * :" + realName) def __hostDisconnected(self): """ Private slot to indicate the host was disconnected. """ if self.networkWidget.isConnected(): self.__closeAllChannels() self.networkWidget.addServerMessage( self.tr("Info"), self.tr("Server disconnected.")) self.networkWidget.setRegistered(False) self.networkWidget.setConnected(False) self.__server = None self.__nickName = "" self.__nickIndex = -1 self.__channelTypePrefixes = "" self.__socket.deleteLater() self.__socket = None self.__connectionState = IrcWidget.ServerDisconnected self.__sslErrorLock = False def __readyRead(self): """ Private slot to read data from the socket. """ if self.__socket: self.__buffer += str( self.__socket.readAll(), Preferences.getSystem("IOEncoding"), 'replace') if self.__buffer.endswith("\r\n"): for line in self.__buffer.splitlines(): line = line.strip() if line: logging.debug("<IRC> " + line) handled = False # step 1: give channels a chance to handle the message for channel in self.__channelList: handled = channel.handleMessage(line) if handled: break else: # step 2: try to process the message ourselves for patternRe, patternFunc in self.__patterns: match = patternRe.match(line) if match is not None: if patternFunc(match): break else: # Oops, the message wasn't handled self.networkWidget.addErrorMessage( self.tr("Message Error"), self.tr( "Unknown message received from server:" "<br/>{0}").format(line)) self.__updateUsersCount() self.__buffer = "" def __handleNamedMessage(self, match): """ Private method to handle a server message containing a message name. @param match reference to the match object @return flag indicating, if the message was handled (boolean) """ name = match.group(2) if name == "NOTICE": try: msg = match.group(3).split(":", 1)[1] except IndexError: msg = match.group(3) if "!" in match.group(1): name = match.group(1).split("!", 1)[0] msg = "-{0}- {1}".format(name, msg) self.networkWidget.addServerMessage(self.tr("Notice"), msg) return True elif name == "MODE": self.__registering = False if ":" in match.group(3): # :detlev_ MODE detlev_ :+i name, modes = match.group(3).split(" :") sourceNick = match.group(1) if not self.isChannelName(name): if name == self.__nickName: if sourceNick == self.__nickName: msg = self.tr( "You have set your personal modes to" " <b>[{0}]</b>.").format(modes) else: msg = self.tr( "{0} has changed your personal modes to" " <b>[{1}]</b>.").format(sourceNick, modes) self.networkWidget.addServerMessage( self.tr("Mode"), msg, filterMsg=False) return True elif name == "PART": nick = match.group(1).split("!", 1)[0] if nick == self.__nickName: channel = match.group(3).split(None, 1)[0] self.networkWidget.addMessage( self.tr("You have left channel {0}.").format(channel)) return True elif name == "QUIT": # don't do anything with it here return True elif name == "NICK": # :[email protected] NICK :newnick oldNick = match.group(1).split("!", 1)[0] newNick = match.group(3).split(":", 1)[1] if oldNick == self.__nickName: self.networkWidget.addMessage( self.tr("You are now known as {0}.").format(newNick)) self.__nickName = newNick self.networkWidget.setNickName(newNick) else: self.networkWidget.addMessage( self.tr("User {0} is now known as {1}.").format( oldNick, newNick)) return True elif name == "ERROR": self.networkWidget.addErrorMessage( self.tr("Server Error"), match.group(3).split(":", 1)[1]) return True return False def __handleNumericMessage(self, match): """ Private method to handle a server message containing a numeric code. @param match reference to the match object @return flag indicating, if the message was handled (boolean) """ code = int(match.group(2)) if code < 400: return self.__handleServerReply( code, match.group(1), match.group(3)) else: return self.__handleServerError( code, match.group(1), match.group(3)) def __handleServerError(self, code, server, message): """ Private slot to handle a server error reply. @param code numerical code sent by the server (integer) @param server name of the server (string) @param message message sent by the server (string) @return flag indicating, if the message was handled (boolean) """ if code == 433: if self.__registering: self.__handleNickInUseLogin() else: self.__handleNickInUse() else: self.networkWidget.addServerMessage(self.tr("Error"), message) return True def __handleServerReply(self, code, server, message): """ Private slot to handle a server reply. @param code numerical code sent by the server (integer) @param server name of the server (string) @param message message sent by the server (string) @return flag indicating, if the message was handled (boolean) """ # determine message type if code in [1, 2, 3, 4]: msgType = self.tr("Welcome") elif code == 5: msgType = self.tr("Support") elif code in [250, 251, 252, 253, 254, 255, 265, 266]: msgType = self.tr("User") elif code in [372, 375, 376]: msgType = self.tr("MOTD") elif code in [305, 306]: msgType = self.tr("Away") else: msgType = self.tr("Info ({0})").format(code) # special treatment for some messages if code == 375: message = self.tr("Message of the day") elif code == 376: message = self.tr("End of message of the day") elif code == 4: parts = message.strip().split() message = self.tr( "Server {0} (Version {1}), User-Modes: {2}," " Channel-Modes: {3}")\ .format(parts[1], parts[2], parts[3], parts[4]) elif code == 265: parts = message.strip().split() message = self.tr( "Current users on {0}: {1}, max. {2}").format( server, parts[1], parts[2]) elif code == 266: parts = message.strip().split() message = self.tr( "Current users on the network: {0}, max. {1}").format( parts[1], parts[2]) elif code == 305: message = self.tr("You are no longer marked as being away.") elif code == 306: message = self.tr("You have been marked as being away.") else: first, message = message.split(None, 1) if message.startswith(":"): message = message[1:] else: message = message.replace(":", "", 1) self.networkWidget.addServerMessage(msgType, message) if code == 1: # register with services after the welcome message self.__connectionState = IrcWidget.ServerConnected self.__registerWithServices() self.networkWidget.setRegistered(True) QTimer.singleShot(1000, self.__autoJoinChannels) elif code == 5: # extract the user privilege prefixes # ... PREFIX=(ov)@+ ... m = self.__prefixRe.match(message) if m: self.__setUserPrivilegePrefix(m.group(1), m.group(2)) # extract the channel type prefixes # ... CHANTYPES=# ... m = self.__chanTypesRe.match(message) if m: self.__setChannelTypePrefixes(m.group(1)) return True def __registerWithServices(self): """ Private method to register to services. """ identity = self.__ircNetworkManager.getIdentity(self.__identityName) service = identity.getServiceName() password = identity.getPassword() if service and password: self.__send("PRIVMSG " + service + " :identify " + password) def __autoJoinChannels(self): """ Private slot to join channels automatically once a server got connected. """ for channel in self.networkWidget.getNetworkChannels(): if channel.autoJoin(): name = channel.getName() key = channel.getKey() self.__joinChannel(name, key) def __tcpError(self, error): """ Private slot to handle errors reported by the TCP socket. @param error error code reported by the socket (QAbstractSocket.SocketError) """ if error == QAbstractSocket.RemoteHostClosedError: # ignore this one, it's a disconnect if self.__sslErrorLock: self.networkWidget.addErrorMessage( self.tr("SSL Error"), self.tr( """Connection to server {0} (port {1}) lost while""" """ waiting for user response to an SSL error.""") .format(self.__server.getName(), self.__server.getPort())) self.__connectionState = IrcWidget.ServerDisconnected elif error == QAbstractSocket.HostNotFoundError: self.networkWidget.addErrorMessage( self.tr("Socket Error"), self.tr( "The host was not found. Please check the host name" " and port settings.")) elif error == QAbstractSocket.ConnectionRefusedError: self.networkWidget.addErrorMessage( self.tr("Socket Error"), self.tr( "The connection was refused by the peer. Please check the" " host name and port settings.")) elif error == QAbstractSocket.SslHandshakeFailedError: self.networkWidget.addErrorMessage( self.tr("Socket Error"), self.tr("The SSL handshake failed.")) else: if self.__socket: self.networkWidget.addErrorMessage( self.tr("Socket Error"), self.tr( "The following network error occurred:<br/>{0}") .format(self.__socket.errorString())) else: self.networkWidget.addErrorMessage( self.tr("Socket Error"), self.tr("A network error occurred.")) def __sslErrors(self, errors): """ Private slot to handle SSL errors. @param errors list of SSL errors (list of QSslError) """ ignored, defaultChanged = self.__sslErrorHandler.sslErrors( errors, self.__server.getName(), self.__server.getPort()) if ignored == E5SslErrorHandler.NotIgnored: self.networkWidget.addErrorMessage( self.tr("SSL Error"), self.tr( """Could not connect to {0} (port {1}) using an SSL""" """ encrypted connection. Either the server does not""" """ support SSL (did you use the correct port?) or""" """ you rejected the certificate.""") .format(self.__server.getName(), self.__server.getPort())) self.__socket.close() else: if defaultChanged: self.__socket.setSslConfiguration( QSslConfiguration.defaultConfiguration()) if ignored == E5SslErrorHandler.UserIgnored: self.networkWidget.addErrorMessage( self.tr("SSL Error"), self.tr( """The SSL certificate for the server {0} (port {1})""" """ failed the authenticity check. SSL errors""" """ were accepted by you.""") .format(self.__server.getName(), self.__server.getPort())) if self.__connectionState == IrcWidget.ServerConnecting: self.__socket.ignoreSslErrors() def __setUserPrivilegePrefix(self, prefix1, prefix2): """ Private method to set the user privilege prefix. @param prefix1 first part of the prefix (string) @param prefix2 indictors the first part gets mapped to (string) """ # PREFIX=(ov)@+ # o = @ -> @ircbot , channel operator # v = + -> +userName , voice operator for i in range(len(prefix1)): self.__userPrefix["+" + prefix1[i]] = prefix2[i] self.__userPrefix["-" + prefix1[i]] = "" def __ping(self, match): """ Private method to handle a PING message. @param match reference to the match object @return flag indicating, if the message was handled (boolean) """ self.__send("PONG " + match.group(1)) return True def __handleCtcp(self, match): """ Private method to handle a CTCP command. @param match reference to the match object @return flag indicating, if the message was handled (boolean) """ # group(1) sender user name # group(2) sender user@host # group(3) target nick # group(4) message if match.group(4).startswith("\x01"): ctcpCommand = match.group(4)[1:].split("\x01", 1)[0] if " " in ctcpCommand: ctcpRequest, ctcpArg = ctcpCommand.split(" ", 1) else: ctcpRequest, ctcpArg = ctcpCommand, "" ctcpRequest = ctcpRequest.lower() if ctcpRequest == "version": if Version.startswith("@@"): vers = "" else: vers = " " + Version msg = "Eric IRC client{0}, {1}".format(vers, Copyright) self.networkWidget.addServerMessage( self.tr("CTCP"), self.tr("Received Version request from {0}.").format( match.group(1))) self.__sendCtcpReply(match.group(1), "VERSION " + msg) elif ctcpRequest == "ping": self.networkWidget.addServerMessage( self.tr("CTCP"), self.tr( "Received CTCP-PING request from {0}," " sending answer.").format(match.group(1))) self.__sendCtcpReply( match.group(1), "PING {0}".format(ctcpArg)) elif ctcpRequest == "clientinfo": self.networkWidget.addServerMessage( self.tr("CTCP"), self.tr( "Received CTCP-CLIENTINFO request from {0}," " sending answer.").format(match.group(1))) self.__sendCtcpReply( match.group(1), "CLIENTINFO CLIENTINFO PING VERSION") else: self.networkWidget.addServerMessage( self.tr("CTCP"), self.tr( "Received unknown CTCP-{0} request from {1}.") .format(ctcpRequest, match.group(1))) return True return False def __updateUsersCount(self): """ Private method to update the users count on the channel tabs. """ for channel in self.__channelList: index = self.channelsWidget.indexOf(channel) self.channelsWidget.setTabText( index, self.tr("{0} ({1})", "channel name, users count").format( channel.name(), channel.getUsersCount())) def __handleNickInUseLogin(self): """ Private method to handle a 443 server error at login. """ self.__nickIndex += 1 try: nick = self.__ircNetworkManager.getIdentity(self.__identityName)\ .getNickNames()[self.__nickIndex] self.__nickName = nick except IndexError: self.networkWidget.addServerMessage( self.tr("Critical"), self.tr( "No nickname acceptable to the server configured" " for <b>{0}</b>. Disconnecting...") .format(self.__userName), filterMsg=False) self.__connectNetwork("", False, silent=True) self.__nickName = "" self.__nickIndex = -1 return self.networkWidget.setNickName(nick) self.__send("NICK " + nick) def __handleNickInUse(self): """ Private method to handle a 443 server error. """ self.networkWidget.addServerMessage( self.tr("Critical"), self.tr("The given nickname is already in use.")) def __changeNick(self, nick): """ Private slot to use a new nick name. @param nick nick name to use (str) """ if nick and nick != self.__nickName: self.__send("NICK " + nick) def __setChannelTypePrefixes(self, prefixes): """ Private method to set the channel type prefixes. @param prefixes channel prefix characters (string) """ self.__channelTypePrefixes = prefixes def isChannelName(self, name): """ Public method to check, if the given name is a channel name. @param name name to check (string) @return flag indicating a channel name (boolean) """ if not name: return False if self.__channelTypePrefixes: return name[0] in self.__channelTypePrefixes else: return name[0] in "#&" def __away(self, isAway): """ Private slot handling the change of the away state. @param isAway flag indicating the current away state (boolean) """ if isAway and self.__identityName: identity = self.__ircNetworkManager.getIdentity( self.__identityName) if identity.rememberAwayPosition(): for channel in self.__channelList: channel.setMarkerLine()
class MainWindow(QtWidgets.QMainWindow): def __init__(self, args): super().__init__() self.socket = QTcpSocket() self.socket.connectToHost('localhost', args.port) self.socket.readyRead.connect(self.readFromEmotool) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("EmoTool - {}".format(version())) self.main_widget = QtWidgets.QTabWidget(self) plot_tab = QtWidgets.QWidget(self.main_widget) self.main_widget.addTab(plot_tab, "plot") l = QtWidgets.QVBoxLayout(plot_tab) self.plot_widget = plot_widget = pg.PlotWidget() l.addWidget(plot_widget) self.plot_widget = plot_widget # TODO - make a menu action, not open by default c = pg.console.ConsoleWidget(namespace=globals(), text="test console") self.main_widget.addTab(c, "debug") self.main_widget.setFocus() self.setCentralWidget(self.main_widget) self.statusBar().showMessage("Starting", 2000) self.ticks = defaultdict(list) self.vals = defaultdict(list) self.data_items = defaultdict(pg.PlotDataItem) self.incoming = b'' self.next_message_size = None @coalesce_meth(10) # Limit refreshes, they can be costly def log_variables(self, msgs): """ Show points on log window. both @ticks and @vars are arrays :param msgs: [(ticks_scalar, [(name, value)])] :return: """ new_ticks, new_vals = to_dicts(msgs) # TODO - better logic. Right now just shows last second, no zoom in possible. Plus second[ticks] is fixed last_tick = msgs[-1][0] cutoff_tick = last_tick - 8000 for name in set(self.ticks.keys()) | set(new_ticks.keys()): if name not in self.data_items: item = self.data_items[name] self.plot_widget.addItem(item) else: item = self.data_items[name] ticks = self.ticks[name] vals = self.vals[name] i_cutoff = bisect_left(ticks, cutoff_tick) del ticks[:i_cutoff] del vals[:i_cutoff] ticks.extend(new_ticks[name]) vals.extend(new_vals[name]) item.setData(ticks, vals) first_tick = min([ticks[0] for ticks in self.ticks.values()]) self.plot_widget.setXRange(first_tick, last_tick) def readFromEmotool(self): """ This is a temporary measure - instead of the better solution: serial2tcp process <-> app We have serial2tcp process <-> emotool <-> app Just to avoid rewriting the emotool parts to drop asyncio support so they can be reused for app and emotool. Quick transport costs calculation (copy cost): 20000 msg/second msg size < 100 bytes < 2 MB /second """ self.incoming += self.socket.readAll() N = len(self.incoming) i = 0 messages = [] while i < N: if self.next_message_size is None: if N - i < SIZEOF_UINT32: break self.next_message_size, = unpack('<i', self.incoming[i : i + SIZEOF_UINT32]) i += SIZEOF_UINT32 if self.next_message_size > N - i: break data = self.incoming[i : i + self.next_message_size] i += self.next_message_size messages.extend(loads(data)) self.next_message_size = None self.incoming = self.incoming[i:] if len(messages) > 0: self.log_variables(messages) def fileQuit(self): self.close() def closeEvent(self, ce): self.fileQuit()
class Scanner(QMainWindow, Ui_Scanner): def __init__(self): super(Scanner, self).__init__() self.setupUi(self) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variable self.idle = True # number of samples to show on the plot self.size = 512 * 512 self.freq = 143.0 # buffer and offset for the incoming samples self.buffer = bytearray(8 * self.size) self.offset = 0 self.data = np.frombuffer(self.buffer, np.int32) # create figure figure = Figure() figure.set_facecolor('none') self.axes = figure.add_subplot(111) self.canvas = FigureCanvas(figure) self.plotLayout.addWidget(self.canvas) self.axes.axis((0.0, 512.0, 0.0, 512.0)) x, y = np.meshgrid(np.linspace(0.0, 512.0, 513), np.linspace(0.0, 512.0, 513)) z = x / 512.0 + y * 0.0 self.mesh = self.axes.pcolormesh(x, y, z, cmap = cm.plasma) # create navigation toolbar self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False) # remove subplots action actions = self.toolbar.actions() if int(matplotlib.__version__[0]) < 2: self.toolbar.removeAction(actions[7]) else: self.toolbar.removeAction(actions[6]) self.plotLayout.addWidget(self.toolbar) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from buttons and boxes self.connectButton.clicked.connect(self.start) self.scanButton.clicked.connect(self.scan) self.periodValue.valueChanged.connect(self.set_period) self.trgtimeValue.valueChanged.connect(self.set_trgtime) self.trginvCheck.stateChanged.connect(self.set_trginv) self.shdelayValue.valueChanged.connect(self.set_shdelay) self.shtimeValue.valueChanged.connect(self.set_shtime) self.shinvCheck.stateChanged.connect(self.set_shinv) self.acqdelayValue.valueChanged.connect(self.set_acqdelay) self.samplesValue.valueChanged.connect(self.set_samples) self.pulsesValue.valueChanged.connect(self.set_pulses) # create timers self.startTimer = QTimer(self) self.startTimer.timeout.connect(self.timeout) self.meshTimer = QTimer(self) self.meshTimer.timeout.connect(self.update_mesh) # set default values self.periodValue.setValue(200.0) def start(self): if self.idle: self.connectButton.setEnabled(False) self.socket.connectToHost(self.addrValue.text(), 1001) self.startTimer.start(5000) else: self.stop() def stop(self): self.idle = True self.socket.abort() self.offset = 0 self.connectButton.setText('Connect') self.connectButton.setEnabled(True) self.scanButton.setEnabled(True) def timeout(self): self.display_error('timeout') def connected(self): self.startTimer.stop() self.idle = False self.set_period(self.periodValue.value()) self.set_trgtime(self.trgtimeValue.value()) self.set_trginv(self.trginvCheck.checkState()) self.set_shdelay(self.shdelayValue.value()) self.set_shtime(self.shtimeValue.value()) self.set_shinv(self.shinvCheck.checkState()) self.set_acqdelay(self.acqdelayValue.value()) self.set_samples(self.samplesValue.value()) self.set_pulses(self.pulsesValue.value()) # start pulse generators self.socket.write(struct.pack('<I', 9<<28)) self.connectButton.setText('Disconnect') self.connectButton.setEnabled(True) self.scanButton.setEnabled(True) def read_data(self): size = self.socket.bytesAvailable() if self.offset + size < 8 * self.size: self.buffer[self.offset:self.offset + size] = self.socket.read(size) self.offset += size else: self.meshTimer.stop() self.buffer[self.offset:8 * self.size] = self.socket.read(8 * self.size - self.offset) self.offset = 0 self.update_mesh() self.scanButton.setEnabled(True) def display_error(self, socketError): self.startTimer.stop() if socketError == 'timeout': QMessageBox.information(self, 'Scanner', 'Error: connection timeout.') else: QMessageBox.information(self, 'Scanner', 'Error: %s.' % self.socket.errorString()) self.stop() def set_period(self, value): # set maximum delays and times to half period maximum = int(value * 5.0 + 0.5) / 10.0 self.trgtimeValue.setMaximum(maximum) self.shdelayValue.setMaximum(maximum) self.shtimeValue.setMaximum(maximum) self.acqdelayValue.setMaximum(maximum) # set maximum number of samples per pulse maximum = int(value * 500.0 + 0.5) / 10.0 if maximum > 256.0: maximum = 256.0 self.samplesValue.setMaximum(maximum) shdelay = value * 0.25 samples = value * 0.5 if self.idle: return self.socket.write(struct.pack('<I', 0<<28 | int(value * self.freq))) def set_trgtime(self, value): if self.idle: return self.socket.write(struct.pack('<I', 1<<28 | int(value * self.freq))) def set_trginv(self, checked): if self.idle: return self.socket.write(struct.pack('<I', 2<<28 | int(checked == Qt.Checked))) def set_shdelay(self, value): if self.idle: return self.socket.write(struct.pack('<I', 3<<28 | int(value * self.freq))) def set_shtime(self, value): if self.idle: return self.socket.write(struct.pack('<I', 4<<28 | int(value * self.freq))) def set_shinv(self, checked): if self.idle: return self.socket.write(struct.pack('<I', 5<<28 | int(checked == Qt.Checked))) def set_acqdelay(self, value): if self.idle: return self.socket.write(struct.pack('<I', 6<<28 | int(value * self.freq))) def set_samples(self, value): if self.idle: return self.socket.write(struct.pack('<I', 7<<28 | int(value))) def set_pulses(self, value): if self.idle: return self.socket.write(struct.pack('<I', 8<<28 | int(value))) def scan(self): if self.idle: return self.scanButton.setEnabled(False) self.data[:] = np.zeros(2 * 512 * 512, np.int32) self.update_mesh() self.socket.write(struct.pack('<I', 10<<28)) self.meshTimer.start(1000) def update_mesh(self): self.mesh.set_array(self.data[0::2]/(self.samplesValue.value() * self.pulsesValue.value() * 8192.0)) self.canvas.draw()
class VNA(QMainWindow, Ui_VNA): max_size = 16383 formatter = matplotlib.ticker.FuncFormatter(lambda x, pos: '%1.1fM' % (x * 1e-6) if abs(x) >= 1e6 else '%1.1fk' % (x * 1e-3) if abs(x) >= 1e3 else '%1.1f' % x if abs(x) >= 1e0 else '%1.1fm' % (x * 1e+3) if abs(x) >= 1e-3 else '%1.1fu' % (x * 1e+6) if abs(x) >= 1e-6 else '%1.1f' % x) def __init__(self): super(VNA, self).__init__() self.setupUi(self) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variable self.idle = True # sweep parameters self.sweep_start = 100 self.sweep_stop = 60000 self.sweep_size = 600 self.xaxis, self.sweep_step = np.linspace(self.sweep_start, self.sweep_stop, self.sweep_size, retstep = True) self.xaxis *= 1000 # buffer and offset for the incoming samples self.buffer = bytearray(32 * VNA.max_size) self.offset = 0 self.data = np.frombuffer(self.buffer, np.complex64) self.adc1 = np.zeros(VNA.max_size, np.complex64) self.adc2 = np.zeros(VNA.max_size, np.complex64) self.dac1 = np.zeros(VNA.max_size, np.complex64) self.open = np.zeros(VNA.max_size, np.complex64) self.short = np.zeros(VNA.max_size, np.complex64) self.load = np.zeros(VNA.max_size, np.complex64) self.dut = np.zeros(VNA.max_size, np.complex64) self.mode = 'dut' # create figure self.figure = Figure() self.figure.set_facecolor('none') self.canvas = FigureCanvas(self.figure) self.plotLayout.addWidget(self.canvas) # create navigation toolbar self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False) # remove subplots action actions = self.toolbar.actions() self.toolbar.removeAction(actions[7]) self.plotLayout.addWidget(self.toolbar) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from buttons and boxes self.sweepFrame.setEnabled(False) self.dutSweep.setEnabled(False) self.connectButton.clicked.connect(self.start) self.writeButton.clicked.connect(self.write_cfg) self.readButton.clicked.connect(self.read_cfg) self.openSweep.clicked.connect(self.sweep_open) self.shortSweep.clicked.connect(self.sweep_short) self.loadSweep.clicked.connect(self.sweep_load) self.dutSweep.clicked.connect(self.sweep_dut) self.s1pButton.clicked.connect(self.write_s1p) self.startValue.valueChanged.connect(self.set_start) self.stopValue.valueChanged.connect(self.set_stop) self.sizeValue.valueChanged.connect(self.set_size) self.openPlot.clicked.connect(self.plot_open) self.shortPlot.clicked.connect(self.plot_short) self.loadPlot.clicked.connect(self.plot_load) self.dutPlot.clicked.connect(self.plot_dut) self.smithPlot.clicked.connect(self.plot_smith) self.impPlot.clicked.connect(self.plot_imp) self.rcPlot.clicked.connect(self.plot_rc) self.swrPlot.clicked.connect(self.plot_swr) self.rlPlot.clicked.connect(self.plot_rl) # create timer self.startTimer = QTimer(self) self.startTimer.timeout.connect(self.timeout) def start(self): if self.idle: self.connectButton.setEnabled(False) self.socket.connectToHost(self.addrValue.text(), 1001) self.startTimer.start(5000) else: self.stop() def stop(self): self.idle = True self.socket.abort() self.offset = 0 self.connectButton.setText('Connect') self.connectButton.setEnabled(True) self.sweepFrame.setEnabled(False) self.selectFrame.setEnabled(True) self.dutSweep.setEnabled(False) def timeout(self): self.display_error('timeout') def connected(self): self.startTimer.stop() self.idle = False self.set_start(self.startValue.value()) self.set_stop(self.stopValue.value()) self.set_size(self.sizeValue.value()) self.connectButton.setText('Disconnect') self.connectButton.setEnabled(True) self.sweepFrame.setEnabled(True) self.dutSweep.setEnabled(True) def read_data(self): size = self.socket.bytesAvailable() if self.offset + size < 32 * self.sweep_size: self.buffer[self.offset:self.offset + size] = self.socket.read(size) self.offset += size else: self.buffer[self.offset:32 * self.sweep_size] = self.socket.read(32 * self.sweep_size - self.offset) self.offset = 0 self.adc1 = self.data[0::4] self.adc2 = self.data[1::4] self.dac1 = self.data[2::4] getattr(self, self.mode)[0:self.sweep_size] = self.adc1[0:self.sweep_size] / self.dac1[0:self.sweep_size] self.sweepFrame.setEnabled(True) self.selectFrame.setEnabled(True) getattr(self, 'plot_%s' % self.mode)() def display_error(self, socketError): self.startTimer.stop() if socketError == 'timeout': QMessageBox.information(self, 'VNA', 'Error: connection timeout.') else: QMessageBox.information(self, 'VNA', 'Error: %s.' % self.socket.errorString()) self.stop() def set_start(self, value): self.sweep_start = value self.xaxis, self.sweep_step = np.linspace(self.sweep_start, self.sweep_stop, self.sweep_size, retstep = True) self.xaxis *= 1000 if self.idle: return self.socket.write(struct.pack('<I', 0<<28 | int(value * 1000))) def set_stop(self, value): self.sweep_stop = value self.xaxis, self.sweep_step = np.linspace(self.sweep_start, self.sweep_stop, self.sweep_size, retstep = True) self.xaxis *= 1000 if self.idle: return self.socket.write(struct.pack('<I', 1<<28 | int(value * 1000))) def set_size(self, value): self.sweep_size = value self.xaxis, self.sweep_step = np.linspace(self.sweep_start, self.sweep_stop, self.sweep_size, retstep = True) self.xaxis *= 1000 if self.idle: return self.socket.write(struct.pack('<I', 2<<28 | int(value))) def sweep(self): if self.idle: return self.sweepFrame.setEnabled(False) self.selectFrame.setEnabled(False) self.socket.write(struct.pack('<I', 3<<28)) def sweep_open(self): self.mode = 'open' self.sweep() def sweep_short(self): self.mode = 'short' self.sweep() def sweep_load(self): self.mode = 'load' self.sweep() def sweep_dut(self): self.mode = 'dut' self.sweep() def impedance(self): return 50.0 * (self.open[0:self.sweep_size] - self.load[0:self.sweep_size]) * (self.dut[0:self.sweep_size] - self.short[0:self.sweep_size]) / ((self.load[0:self.sweep_size] - self.short[0:self.sweep_size]) * (self.open[0:self.sweep_size] - self.dut[0:self.sweep_size])) def gamma(self): z = self.impedance() return (z - 50.0)/(z + 50.0) def plot_magphase(self, data): matplotlib.rcdefaults() self.figure.clf() self.figure.subplots_adjust(top = 0.98, right = 0.88) axes1 = self.figure.add_subplot(111) axes1.cla() axes1.xaxis.set_major_formatter(VNA.formatter) axes1.yaxis.set_major_formatter(VNA.formatter) axes1.tick_params('y', color = 'blue', labelcolor = 'blue') axes1.yaxis.label.set_color('blue') axes1.plot(self.xaxis, np.absolute(data), color = 'blue') axes2 = axes1.twinx() axes2.spines['left'].set_color('blue') axes2.spines['right'].set_color('red') axes1.set_xlabel('Hz') axes1.set_ylabel('Magnitude') axes2.set_ylabel('Phase angle') axes2.tick_params('y', color = 'red', labelcolor = 'red') axes2.yaxis.label.set_color('red') axes2.plot(self.xaxis, np.angle(data, deg = True), color = 'red') self.canvas.draw() def plot_open(self): self.plot_magphase(self.open[0:self.sweep_size]) def plot_short(self): self.plot_magphase(self.short[0:self.sweep_size]) def plot_load(self): self.plot_magphase(self.load[0:self.sweep_size]) def plot_dut(self): self.plot_magphase(self.dut[0:self.sweep_size]) def plot_smith(self): matplotlib.rcdefaults() self.figure.clf() self.figure.subplots_adjust(top = 0.90, right = 0.90) axes = self.figure.add_subplot(111, projection = 'smith', axes_radius = 0.55, axes_scale = 50.0) axes.cla() axes.plot(self.impedance()) self.canvas.draw() def plot_imp(self): self.plot_magphase(self.impedance()) def plot_rc(self): self.plot_magphase(self.gamma()) def plot_swr(self): matplotlib.rcdefaults() self.figure.clf() self.figure.subplots_adjust(top = 0.98, right = 0.88) axes1 = self.figure.add_subplot(111) axes1.cla() axes1.xaxis.set_major_formatter(VNA.formatter) axes1.yaxis.set_major_formatter(VNA.formatter) axes1.set_xlabel('Hz') axes1.set_ylabel('SWR') magnitude = np.absolute(self.gamma()) swr = np.maximum(1.0, np.minimum(100.0, (1.0 + magnitude) / np.maximum(1.0e-20, 1.0 - magnitude))) axes1.plot(self.xaxis, swr, color = 'blue') self.canvas.draw() def plot_rl(self): matplotlib.rcdefaults() self.figure.clf() self.figure.subplots_adjust(top = 0.98, right = 0.88) axes1 = self.figure.add_subplot(111) axes1.cla() axes1.xaxis.set_major_formatter(VNA.formatter) axes1.set_xlabel('Hz') axes1.set_ylabel('Return loss, dB') magnitude = np.absolute(self.gamma()) axes1.plot(self.xaxis, 20.0 * np.log10(magnitude), color = 'blue') self.canvas.draw() def write_cfg(self): name = QFileDialog.getSaveFileName(self, 'Write configuration settings', '.', '*.ini') settings = QSettings(name[0], QSettings.IniFormat) self.write_cfg_settings(settings) def read_cfg(self): name = QFileDialog.getOpenFileName(self, 'Read configuration settings', '.', '*.ini') settings = QSettings(name[0], QSettings.IniFormat) self.read_cfg_settings(settings) def write_cfg_settings(self, settings): settings.setValue('start', self.startValue.value()) settings.setValue('stop', self.stopValue.value()) size = self.sizeValue.value() settings.setValue('size', size) for i in range(0, size): settings.setValue('open_real_%d' % i, float(self.open.real[i])) settings.setValue('open_imag_%d' % i, float(self.open.imag[i])) for i in range(0, size): settings.setValue('short_real_%d' % i, float(self.short.real[i])) settings.setValue('short_imag_%d' % i, float(self.short.imag[i])) for i in range(0, size): settings.setValue('load_real_%d' % i, float(self.load.real[i])) settings.setValue('load_imag_%d' % i, float(self.load.imag[i])) for i in range(0, size): settings.setValue('dut_real_%d' % i, float(self.dut.real[i])) settings.setValue('dut_imag_%d' % i, float(self.dut.imag[i])) def read_cfg_settings(self, settings): self.startValue.setValue(settings.value('start', 100, type = int)) self.stopValue.setValue(settings.value('stop', 60000, type = int)) size = settings.value('size', 600, type = int) self.sizeValue.setValue(size) for i in range(0, size): real = settings.value('open_real_%d' % i, 0.0, type = float) imag = settings.value('open_imag_%d' % i, 0.0, type = float) self.open[i] = real + 1.0j * imag for i in range(0, size): real = settings.value('short_real_%d' % i, 0.0, type = float) imag = settings.value('short_imag_%d' % i, 0.0, type = float) self.short[i] = real + 1.0j * imag for i in range(0, size): real = settings.value('load_real_%d' % i, 0.0, type = float) imag = settings.value('load_imag_%d' % i, 0.0, type = float) self.load[i] = real + 1.0j * imag for i in range(0, size): real = settings.value('dut_real_%d' % i, 0.0, type = float) imag = settings.value('dut_imag_%d' % i, 0.0, type = float) self.dut[i] = real + 1.0j * imag def write_s1p(self): name = QFileDialog.getSaveFileName(self, 'Write s1p file', '.', '*.s1p') fh = open(name[0], 'w') gamma = self.gamma() size = self.sizeValue.value() fh.write('# GHz S MA R 50\n') for i in range(0, size): fh.write('0.0%.8d %8.6f %7.2f\n' % (self.xaxis[i], np.absolute(gamma[i]), np.angle(gamma[i], deg = True))) fh.close()
def __init__(self, parent=None): super(Client, self).__init__(parent) self.networkSession = None self.blockSize = 0 self.currentFortune = "" hostLabel = QLabel("&Server name:") portLabel = QLabel("S&erver port:") self.hostCombo = QComboBox() self.hostCombo.setEditable(True) name = QHostInfo.localHostName() if name != "": self.hostCombo.addItem(name) domain = QHostInfo.localDomainName() if domain != "": self.hostCombo.addItem(name + "." + domain) if name != "localhost": self.hostCombo.addItem("localhost") ipAddressesList = QNetworkInterface.allAddresses() for ipAddress in ipAddressesList: if not ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) for ipAddress in ipAddressesList: if ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) hostLabel.setBuddy(self.hostCombo) portLabel.setBuddy(self.portLineEdit) self.statusLabel = QLabel("This examples requires that you run " "the Fortune Server example as well.") self.getFortuneButton = QPushButton("Get Fortune") self.getFortuneButton.setDefault(True) self.getFortuneButton.setEnabled(False) quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.tcpSocket = QTcpSocket(self) self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.tcpSocket.readyRead.connect(self.readFortune) self.tcpSocket.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostCombo, 0, 1) mainLayout.addWidget(portLabel, 1, 0) mainLayout.addWidget(self.portLineEdit, 1, 1) mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2) mainLayout.addWidget(buttonBox, 3, 0, 1, 2) self.setLayout(mainLayout) self.setWindowTitle("Fortune Client") self.portLineEdit.setFocus() manager = QNetworkConfigurationManager() if manager.capabilities() & QNetworkConfigurationManager.NetworkSessionRequired: settings = QSettings(QSettings.UserScope, "QtProject") settings.beginGroup("QtNetwork") id = settings.value("DefaultNetworkConfiguration") settings.endGroup() config = manager.configurationFromIdentifier(id) if config.state() & QNetworkConfiguration.Discovered == 0: config = manager.defaultConfiguration() self.networkSession = QNetworkSession(config, self) self.networkSession.opened.connect(self.sessionOpened) self.getFortuneButton.setEnabled(False) self.statusLabel.setText("Opening network session.") self.networkSession.open()
def run(self): self.mutex.lock() serverName = self.hostName serverPort = self.port self.mutex.unlock() while not self.quit: Timeout = 5 * 1000 socket = QTcpSocket() socket.connectToHost(serverName, serverPort) if not socket.waitForConnected(Timeout): self.error.emit(socket.error(), socket.errorString()) return while socket.bytesAvailable() < 2: if not socket.waitForReadyRead(Timeout): self.error.emit(socket.error(), socket.errorString()) return instr = QDataStream(socket) instr.setVersion(QDataStream.Qt_4_0) blockSize = instr.readUInt16() while socket.bytesAvailable() < blockSize: if not socket.waitForReadyRead(Timeout): self.error.emit(socket.error(), socket.errorString()) return self.mutex.lock() fortune = instr.readQString() self.newFortune.emit(fortune) self.cond.wait(self.mutex) serverName = self.hostName serverPort = self.port self.mutex.unlock()
class Main(QMainWindow): def __init__(self, *args): super(Main, self).__init__(*args) loadUi('mainwindow.ui', self) self.host.setText("localhost") self.port.setText("11010") self.prompt.setText("M114") self.conn = QTcpSocket(self) self.conn.readyRead.connect(self.readSocket) self.conn.error.connect(self.socketError) self.conn.connected.connect(self.socketConnect) self.conn.disconnected.connect(self.socketDisconnect) self.connected = False self.actionSave.triggered.connect(self.save) self.prompt.setFocus() self.do_connect() def append(self, text): self.text.append(text) if self.autoscroll.isChecked(): c = self.text.textCursor() c.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) self.text.setTextCursor(c) def readSocket(self): r = self.conn.readAll() if r: r = str(r).strip() for chunk in r.splitlines(): if chunk: if chunk[0] == '<': self.text.setTextColor(QColor(200, 0, 0)) elif chunk[0] == '>': self.text.setTextColor(QColor(0, 200, 0)) else: self.text.setTextColor(QColor(0, 0, 200)) self.append(chunk) def info(self, errtext): self.text.setTextColor(QColor(20, 20, 20)) self.append(errtext) def err(self, errtext): self.text.setTextColor(QColor(100, 0, 0)) self.append(errtext) def socketDisconnect(self): self.connected = False self.err("Disconnected") def socketConnect(self): self.connected = True self.info("Connected") def socketError(self, socketError): if socketError == QAbstractSocket.RemoteHostClosedError: pass elif socketError == QAbstractSocket.HostNotFoundError: self.err("The host was not found. Please check the host name and " "port settings.") elif socketError == QAbstractSocket.ConnectionRefusedError: self.err("The connection was refused by the peer. Make sure the " "server is running, and check that the host name " "and port settings are correct.") else: self.err("The following error occurred: {0}" .format(self.conn.errorString())) def save(self): fname, sel = QFileDialog.getSaveFileName( self, 'Save Log',) #'/path/to/default/directory', FIXME: lastused #selectedFilter='*.txt') if fname: with open(fname, 'w+') as f: f.write(self.text.toPlainText()) def do_connect(self): self.conn.abort() self.conn.connectToHost(self.host.text(), int(self.port.text())) @pyqtSlot() def on_connect_clicked(self): self.do_connect() self.prompt.setFocus() @pyqtSlot() def on_send_clicked(self): if not self.connected: self.err("Not connected") return out = (self.prompt.text() + '\n').encode('ascii') self.conn.write(out) @pyqtSlot() def on_right_on_clicked(self): self.action("e1")
class PulsedNMR(QMainWindow, Ui_PulsedNMR): rates = {0:25.0e3, 1:50.0e3, 2:250.0e3, 3:500.0e3, 4:2500.0e3} def __init__(self): super(PulsedNMR, self).__init__() self.setupUi(self) self.rateValue.addItems(['25', '50', '250', '500', '2500']) # IP address validator rx = QRegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue)) # state variable self.idle = True # number of samples to show on the plot self.size = 50000 # buffer and offset for the incoming samples self.buffer = bytearray(8 * self.size) self.offset = 0 # create figure figure = Figure() figure.set_facecolor('none') self.axes = figure.add_subplot(111) self.canvas = FigureCanvas(figure) self.plotLayout.addWidget(self.canvas) # create navigation toolbar self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False) # remove subplots action actions = self.toolbar.actions() self.toolbar.removeAction(actions[7]) self.plotLayout.addWidget(self.toolbar) # create TCP socket self.socket = QTcpSocket(self) self.socket.connected.connect(self.connected) self.socket.readyRead.connect(self.read_data) self.socket.error.connect(self.display_error) # connect signals from buttons and boxes self.startButton.clicked.connect(self.start) self.freqValue.valueChanged.connect(self.set_freq) self.awidthValue.valueChanged.connect(self.set_awidth) self.deltaValue.valueChanged.connect(self.set_delta) self.rateValue.currentIndexChanged.connect(self.set_rate) # set rate self.rateValue.setCurrentIndex(2) # create timer for the repetitions self.timer = QTimer(self) self.timer.timeout.connect(self.fire) def start(self): if self.idle: self.startButton.setEnabled(False) self.socket.connectToHost(self.addrValue.text(), 1001) else: self.idle = True self.timer.stop() self.socket.close() self.offset = 0 self.startButton.setText('Start') self.startButton.setEnabled(True) def connected(self): self.idle = False self.set_freq(self.freqValue.value()) self.set_rate(self.rateValue.currentIndex()) self.set_awidth(self.awidthValue.value()) self.fire() self.timer.start(self.deltaValue.value()) self.startButton.setText('Stop') self.startButton.setEnabled(True) def read_data(self): size = self.socket.bytesAvailable() if self.offset + size < 8 * self.size: self.buffer[self.offset:self.offset + size] = self.socket.read(size) self.offset += size else: self.buffer[self.offset:8 * self.size] = self.socket.read(8 * self.size - self.offset) self.offset = 0 # plot the signal envelope data = np.frombuffer(self.buffer, np.complex64) self.curve.set_ydata(np.abs(data)) self.canvas.draw() def display_error(self, socketError): if socketError == QAbstractSocket.RemoteHostClosedError: pass else: QMessageBox.information(self, 'PulsedNMR', 'Error: %s.' % self.socket.errorString()) self.startButton.setText('Start') self.startButton.setEnabled(True) def set_freq(self, value): if self.idle: return self.socket.write(struct.pack('<I', 0<<28 | int(1.0e6 * value))) def set_rate(self, index): # time axis rate = float(PulsedNMR.rates[index]) time = np.linspace(0.0, (self.size - 1) * 1000.0 / rate, self.size) # reset toolbar self.toolbar.home() self.toolbar._views.clear() self.toolbar._positions.clear() # reset plot self.axes.clear() self.axes.grid() # plot zeros and get store the returned Line2D object self.curve, = self.axes.plot(time, np.zeros(self.size)) x1, x2, y1, y2 = self.axes.axis() # set y axis limits self.axes.axis((x1, x2, -0.1, 0.4)) self.axes.set_xlabel('time, ms') self.canvas.draw() # set repetition time minimum = self.size / rate * 2000.0 if minimum < 100.0: minimum = 100.0 self.deltaValue.setMinimum(minimum) self.deltaValue.setValue(minimum) if self.idle: return self.socket.write(struct.pack('<I', 1<<28 | index)) def set_awidth(self, value): if self.idle: return self.socket.write(struct.pack('<I', 2<<28 | int(1.0e1 * value))) def set_delta(self, value): if self.idle: return self.timer.stop() self.timer.start(value) def fire(self): if self.idle: return self.socket.write(struct.pack('<I', 3<<28))
class Client(QDialog): def __init__(self): super().__init__() self.tcpSocket = QTcpSocket(self) self.blockSize = 0 self.makeRequest() self.tcpSocket.waitForConnected(1000) # send any message you like it could come from a widget text. self.tcpSocket.write(b'hello') self.tcpSocket.readyRead.connect(self.dealCommunication) self.tcpSocket.error.connect(self.displayError) def makeRequest(self): HOST = '127.0.0.1' PORT = 8000 self.tcpSocket.connectToHost(HOST, PORT, QIODevice.ReadWrite) def dealCommunication(self): instr = QDataStream(self.tcpSocket) instr.setVersion(QDataStream.Qt_5_0) if self.blockSize == 0: if self.tcpSocket.bytesAvailable() < 2: return self.blockSize = instr.readUInt16() if self.tcpSocket.bytesAvailable() < self.blockSize: return # Print response to terminal, we could use it anywhere else we wanted. print(str(instr.readString(), encoding='ascii')) def displayError(self, socketError): if socketError == QAbstractSocket.RemoteHostClosedError: pass else: print(self, "The following error occurred: %s." % self.tcpSocket.errorString())