def __init__(self, parent): QThread.__init__(self, parent) self.prnt = parent self.udp = QUdpSocket() addr = QHostAddress(QHostAddress.Any) print 'bind to:', addr.toString() self.udp.bind(addr, 34001) self.udp.error.connect(self.errorAnalyser) self.udp.readyRead.connect(self.readUdp) print "Binding..." self.STOP = False self.locker = QMutex()
def readUdp(self): while ( self.udp.hasPendingDatagrams() ): data = QByteArray() addr = QHostAddress() port = 0 try : datagramSize = self.udp.pendingDatagramSize() if datagramSize > 0 : (data, addr, port) = self.udp.readDatagram(datagramSize) #print "Datagram: [%s] from %s:%i" % (QString().fromUtf8(data), addr.toString(), port) self.prnt.contactMessage.emit(QString().fromUtf8(data), addr.toString()) except socket.error, err : print '[in readUdp() UdpClient] SocketError1 : ', err except socket.timeout, err : print '[in readUdp() UdpClient] SocketError2 : ', err
class RobotVisClient(QUdpSocket): def __init__(self, hostname, port): super(RobotVisClient, self).__init__() self._hostname = QHostAddress(hostname) self._port = port self._logger = logging.getLogger("vis_client") def send_update(self, vis_update): if self._logger.isEnabledFor('DEBUG'): self._logger.debug("Sending VisState message, host: %s, port: %d" % (self._hostname.toString(), self._port)) try: str_data = cPickle.dumps(vis_update) if self.writeDatagram(str_data, self._hostname, self._port) < 0: self._logger.error("Error sending VisState message: %s" % (self.errorString(), )) except cPickle.PickleError as e: self._logger.error("PickleError: %s" % (e, ))
class RobotVisClient(QUdpSocket): def __init__(self, hostname, port): super(RobotVisClient, self).__init__() self._hostname = QHostAddress(hostname) self._port = port self._logger = logging.getLogger("vis_client") self._logger.debug("hostname: %s" % (hostname)) def send_update(self, vis_update): if self._logger.isEnabledFor('DEBUG'): self._logger.debug("Sending VisState message, host: %s, port: %d" % (self._hostname.toString(), self._port)) try: str_data = cPickle.dumps(vis_update) if self.writeDatagram(str_data, self._hostname, self._port) < 0: self._logger.error("Error sending VisState message: %s" % (self.errorString(), )) except cPickle.PickleError as e: self._logger.error("PickleError: %s" % (e, ))
class ServerApp(FreeseerApp): STATUS = ["Offline", "Online"] status = STATUS[0] clients = [] passPhrase = '' ipAddress = None def __init__(self): FreeseerApp.__init__(self) self.resize(400, 300) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/freeseer/logo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setWindowIcon(icon) configdir = os.path.abspath(os.path.expanduser('~/.freeseer/')) self.logger = Logger(configdir) logging.info("Logger initialized") self.server = QTcpServer(self) logging.info("Starting Freeseer Server") # Setup Widget self.mainWidget = ControllerServerWidget() self.setCentralWidget(self.mainWidget) self.mainWidget.hostCombo.addItem(QtCore.QString("0.0.0.0")) #Connections self.connect(self.server, QtCore.SIGNAL('newConnection()'), self.acceptConnection) self.connect(self.mainWidget.startButton, QtCore.SIGNAL('pressed()'), self.startServer) self.connect(self.mainWidget.hostCombo, QtCore.SIGNAL('currentIndexChanged(int)'), self.ipComboBoxHandler) self.connect(self.mainWidget.passEdit, QtCore.SIGNAL('textChanged(QString)'), self.onPassChanged) # Initialize Passphrase Field self.mainWidget.passEdit.setPlaceholderText("Passphrase required to start server") self.mainWidget.startButton.setEnabled(False) # Client Control self.connect(self.mainWidget.clientStartButton, QtCore.SIGNAL('pressed()'), self.sendRecordCommand) self.connect(self.mainWidget.clientStopButton, QtCore.SIGNAL('pressed()'), self.sendStopCommand) self.connect(self.mainWidget.clientDisconnectButton, QtCore.SIGNAL('pressed()'), self.disconnectClients) self.connect(self.mainWidget.clientList, QtCore.SIGNAL('itemSelectionChanged()'), self.updateClientButtons) self.load_settings() self.updateStatus(self.status) ### ### Translation Related ### def retranslate(self): self.setWindowTitle(self.uiTranslator.translate("ControllerServerApp", "Controller Server")) # # Reusuable Strings # self.serverStatusString = self.uiTranslator.translate("ControllerServerApp", "Server status") self.startServerString = self.uiTranslator.translate("ControllerServerApp", "Start Server") self.stopServerString = self.uiTranslator.translate("ControllerServerApp", "Stop Server") self.startRecordingString = self.uiTranslator.translate("ControllerServerApp", "Start Recording") self.stopRecordingString = self.uiTranslator.translate("ControllerServerApp", "Stop Recording") self.pauseRecordingString = self.uiTranslator.translate("ControllerServerApp", "Pause Recording") self.resumeRecordingString = self.uiTranslator.translate("ControllerServerApp", "Resume Recording") # --- End Reusable Strings # # Server Settings # self.mainWidget.toolBox.setItemText(0, self.uiTranslator.translate("ControllerServerApp", "Server Settings")) self.mainWidget.hostLabel.setText(self.uiTranslator.translate("ControllerServerApp", "IP Address")) self.mainWidget.portLabel.setText(self.uiTranslator.translate("ControllerServerApp", "Port")) self.mainWidget.passLabel.setText(self.uiTranslator.translate("ControllerServerApp", "Passphrase")) # Button if self.status == self.STATUS[0]: self.mainWidget.startButton.setText(self.startServerString) else: self.mainWidget.startButton.setText(self.stopServerString) # --- End Server Settings # # Control Clients # self.mainWidget.toolBox.setItemText(1, self.uiTranslator.translate("ControllerServerApp", "Control Clients")) self.updateClientButtons() self.mainWidget.clientDisconnectButton.setText(self.uiTranslator.translate("ControllerServerApp", "Disconnect")) # --- End Control Clients ### ### Server Methods ### def load_settings(self): logging.info('Loading settings...') configdir = os.path.abspath(os.path.expanduser('~/.freeseer/')) self.config = Config(configdir) # Load default language. actions = self.menuLanguage.actions() for action in actions: if action.data().toString() == self.config.default_language: action.setChecked(True) self.translate(action) break def startServer(self): if self.status == self.STATUS[0]: # Check if status is Offline if self.ipAddress is None: self.ipAddress = QHostAddress(self.mainWidget.hostCombo.currentText()) self.server.listen(self.ipAddress, PORT) self.status = self.STATUS[1] # Set Running self.mainWidget.hostCombo.setEnabled(False) logging.info("Started server %s: %s", self.server.serverAddress().toString(), str(self.server.serverPort())) elif self.status == self.STATUS[1]: # Check if status is Online self.server.close() self.status = self.STATUS[0] # Set status Offline self.disconnectAllClients() self.mainWidget.hostCombo.setEnabled(True) self.ipAddress = None self.updateStatus(self.status) self.setPassPhrase() self.setConnectionLabel() self.retranslate() def updateStatus(self, status): self.mainWidget.statusLabel.setText("%s: %s" % (self.serverStatusString, status)) def setConnectionLabel(self): text = "%s:%s" % (self.mainWidget.hostCombo.currentText(), self.mainWidget.portEdit.text()) self.mainWidget.settingsEdit.setText(text) if self.mainWidget.passEdit.text(): self.mainWidget.settingsEdit.setText("%s@%s" % (self.mainWidget.passEdit.text(), text)) ''' This function is for changing the passphrase. It saves the new passphrase in the self.passPhrase after encoding it. ''' def setPassPhrase(self): self.passphrase = self.mainWidget.passEdit.text() logging.info ("Passphrase set to %s", self.passphrase) #self.passPhrase = base64.b64encode(self.passPhrase) self.passphrase = str(self.passphrase) self.passphrase = pwd_context.encrypt(self.passphrase) ''' This function reads the passphrase sent from the client. It decodes the saved passphrase and the one that client sent and compares. Client is accepted if the passphrases match. Otherwise client is rejected ''' def readPassPhrase(self): client = QtCore.QObject.sender(self) message = client.read(client.bytesAvailable()) logging.info("Client said: %s", message) if pwd_context.verify(message, self.passphrase) is False: client.disconnectFromHost() logging.info("Client rejected") else: self.clients.append(client) self.updateList() logging.info("Client accepted") self.disconnect(client, QtCore.SIGNAL('readyRead()'), self.readPassPhrase) self.connect(client, QtCore.SIGNAL('readyRead()'), self.startRead) def onPassChanged(self): """Disable 'Start' button only when the passphrase field is empty.""" if self.mainWidget.passEdit.text(): self.mainWidget.startButton.setEnabled(True) else: self.mainWidget.startButton.setEnabled(False) def ipComboBoxHandler(self): self.ipAddress = QHostAddress(self.ipComboBox.itemText(self.ipComboBox.currentIndex())) logging.info("Server IP changed to: %s", self.ipAddress.toString()) ### ### Messaging ### def startRead(self): client = QtCore.QObject.sender(self) message = client.read(client.bytesAvailable()) logging.info("Client said: %s", message) return message def sendMessage(self, client, message): block = QtCore.QByteArray() block.append(message) client.write(block) ### ### Client List Methods ### ''' This is the function to handle a new connection. ''' def acceptConnection(self): client = self.server.nextPendingConnection() self.connect(client, QtCore.SIGNAL("disconnected()"), self.clientDisconnected) self.connect(client, QtCore.SIGNAL('readyRead()'), self.readPassPhrase) def clientDisconnected(self): client = QtCore.QObject.sender(self) logging.info("Client disconnected") self.clients.remove(client) self.updateList() self.updateClientButtons() ''' This method is to update the list ''' def updateList(self): self.mainWidget.clientList.clear() for i in range(0, len(self.clients)): client = self.clients[i] listItem = ClientListItem(client) self.mainWidget.clientList.addItem(listItem) clientLabel = QtGui.QLabel('F1', self) clientLabel.move(5 + (i * 20), 150) def addClientToList(self, client): self.clients.append(object) listItem = ClientListItem(client) self.mainWidget.clientList.addItem(listItem) def removeClientFromTheList(self, client): self.clients.remove(client) self.updateList() ''' Sends a record command to the selected clients ''' def sendRecordCommand (self): buttonText = self.mainWidget.clientStartButton.text() # Find out what command to send if buttonText == self.startRecordingString or buttonText == self.resumeRecordingString: command = COMMANDS[1] # Set Record elif buttonText == self.pauseRecordingString: command = COMMANDS[2] # Set Pause # Send command for i in range(0, len(self.mainWidget.clientList.selectedItems())): c_item = self.mainWidget.clientList.selectedItems()[i] client = c_item.client self.sendMessage(client, command) if command == COMMANDS[1]: # Check if command is Record c_item.changeStatus(CLIENT_STATUS[1]) # Set Recording elif command == COMMANDS[2]: # Check if command is Pause c_item.changeStatus(CLIENT_STATUS[2]) # Set Paused logging.info("Sent %s command to %s" % (command, c_item.address)) self.updateClientButtons() ''' Sends a stop command to selected clients ''' def sendStopCommand (self): command = COMMANDS[0] # Set Stop command for i in range(0, len(self.mainWidget.clientList.selectedItems())): c_item = self.mainWidget.clientList.selectedItems()[i] client = c_item.client self.sendMessage(client, command) c_item.changeStatus(CLIENT_STATUS[3]) # Set Idle logging.info("Sent %s command to %s" % (command, c_item.address)) self.updateClientButtons() ''' Method to disconnect all clients selected from the list ''' def disconnectClients(self): for i in range(0, len(self.mainWidget.clientList.selectedItems())): client = self.mainWidget.clientList.selectedItems()[i].client client.disconnectFromHost() ''' Method to disconnect all clients that are connected ''' def disconnectAllClients(self): for i in range(0, self.mainWidget.clientList.count()): client = self.mainWidget.clientList.item(i).client client.disconnectFromHost() def updateClientButtons(self): if len(self.mainWidget.clientList.selectedItems()) > 0: self.mainWidget.clientDisconnectButton.setEnabled(True) self.mainWidget.clientStartButton.setEnabled(True) for i in range(0, len(self.mainWidget.clientList.selectedItems())): clientStatus = self.mainWidget.clientList.selectedItems()[i].status logging.debug("Client status: %s", clientStatus) if clientStatus == CLIENT_STATUS[1]: # Client is Recording self.mainWidget.clientStartButton.setText(self.pauseRecordingString) self.mainWidget.clientStopButton.setEnabled(True) elif clientStatus == CLIENT_STATUS[3]: # Client is Idle self.mainWidget.clientStartButton.setText(self.startRecordingString) self.mainWidget.clientStopButton.setEnabled(False) elif clientStatus == CLIENT_STATUS[2]: # Client is Paused self.mainWidget.clientStartButton.setText(self.resumeRecordingString) self.mainWidget.clientStopButton.setEnabled(True) else: self.mainWidget.clientDisconnectButton.setEnabled(False) self.mainWidget.clientStartButton.setEnabled(False) self.mainWidget.clientStartButton.setText(self.startRecordingString) self.mainWidget.clientStopButton.setEnabled(False) self.mainWidget.clientStopButton.setText(self.stopRecordingString)
class MainWindow(QtGui.QWidget): def __init__(self): super(MainWindow, self).__init__() self.serverIP = QHostAddress() self.port = 8010 self.super_Vlayout = QtGui.QVBoxLayout() # value_layout self.value_layout = QtGui.QHBoxLayout() self.speed_value_lable = QtGui.QLabel(u"速度(step/s):") self.speed_value_text = QtGui.QLineEdit() self.step_value_lable = QtGui.QLabel(u" 步值(step):") self.step_value_text = QtGui.QLineEdit() self.value_layout.addWidget(self.speed_value_lable) self.value_layout.addWidget(self.speed_value_text) self.value_layout.addWidget(self.step_value_lable) self.value_layout.addWidget(self.step_value_text) # send_layout self.send_layout = QtGui.QHBoxLayout() self.send_button = QtGui.QPushButton(u"发送") self.send_button.setEnabled(False) self.send_button.setFixedWidth(100) self.send_layout.addStretch() self.send_layout.addWidget(self.send_button) self.send_layout.addStretch() # ip_layout self.ip_layout = QtGui.QHBoxLayout() self.ip_lable = QtGui.QLabel(u"IP地址: ") self.ip_value_text = QtGui.QLineEdit("192.168.1.128") self.ip_layout.addWidget(self.ip_lable) self.ip_layout.addWidget(self.ip_value_text) # port_layout self.port_layout = QtGui.QHBoxLayout() self.port_lable = QtGui.QLabel(u"端口号: ") self.port_value_text = QtGui.QLineEdit("8080") self.port_layout.addWidget(self.port_lable) self.port_layout.addWidget(self.port_value_text) # connect_layout self.connect_layout = QtGui.QHBoxLayout() self.connect_button = QtGui.QPushButton(u"连接") self.connect_button.setFixedWidth(100) self.connect_layout.addStretch() self.connect_layout.addWidget(self.connect_button) self.connect_layout.addStretch() self.super_Vlayout.addLayout(self.value_layout) self.super_Vlayout.addLayout(self.send_layout) self.super_Vlayout.addLayout(self.ip_layout) self.super_Vlayout.addLayout(self.port_layout) self.super_Vlayout.addLayout(self.connect_layout) self.setLayout(self.super_Vlayout) self.setWindowTitle("Client") self.setGeometry(700, 300, 300, 300) self.my_tcp_socket = QtNetwork.QTcpSocket(self) self.set_signal() def set_signal(self): self.send_button.clicked.connect(self.send_button_Handler) self.connect_button.clicked.connect(self.connect_button_Handler) self.connect(self.my_tcp_socket, SIGNAL("connected()"), self.slotConnected) self.connect(self.my_tcp_socket, SIGNAL("disconnected()"), self.slotDisconnected) self.connect(self.my_tcp_socket, SIGNAL("readyRead()"), self.dataReceived) def send_button_Handler(self): msg = self.speed_value_text.text() + ":" + self.step_value_text.text() self.my_tcp_socket.writeData(msg.toUtf8()) def connect_button_Handler(self): if self.connect_button.text() == u"连接": self.serverIP.setAddress(self.ip_value_text.text()) self.my_tcp_socket.connectToHost(self.serverIP.toString(), int(self.port_value_text.text())) else: self.my_tcp_socket.disconnectFromHost() def dataReceived(self): while self.my_tcp_socket.bytesAvailable() > 0: length = self.my_tcp_socket.bytesAvailable() msg = QString(self.my_tcp_socket.read(length)) msg = msg.fromUtf8(msg) # self.ListWidgetContent.addItem(msg.fromUtf8(msg)) def slotConnected(self): self.send_button.setEnabled(True) self.connect_button.setText(u"断开连接") # self.PushButtonLeave.setText(self.tr(u"断开链接")) # msg = self.userName + ":" + self.tr("进入聊天室") # length = self.tcpSocket.writeData(msg.toUtf8()) # if length != msg.toUtf8().length(): # return def slotDisconnected(self): self.send_button.setEnabled(False) self.connect_button.setText(u"连接") def paintEvent(self, e): qp = QPainter() qp.begin(self) self.drawLines(qp) qp.end() def drawLines(self, qp): # mySize = self.size() pen = QPen(Qt.black, 2, Qt.SolidLine) myLocation = self.geometry() pen.setWidth(1) pen.setStyle(Qt.CustomDashLine) pen.setDashPattern([1, 2, 1, 2]) pen.setColor(QColor(55, 55, 55)) qp.setPen(pen) qp.drawLine(0, myLocation.height()*0.4+4, myLocation.width(), myLocation.height()*0.4+4) qp.drawLine(0, myLocation.height()*0.4+3, myLocation.width(), myLocation.height()*0.4+3) qp.drawLine(0, myLocation.height()*0.4+2, myLocation.width(), myLocation.height()*0.4+2) pen.setWidth(3) pen.setDashPattern([1, 1, 1, 1]) qp.setPen(pen) qp.drawLine(0, myLocation.height()*0.4-2, 5, myLocation.height()*0.4+3) qp.drawLine(0, myLocation.height()*0.4, 3, myLocation.height()*0.4+3) qp.drawLine(0, myLocation.height()*0.4+8, 5, myLocation.height()*0.4+3) qp.drawLine(0, myLocation.height()*0.4+6, 3, myLocation.height()*0.4+3) qp.drawLine(myLocation.width()-6, myLocation.height()*0.4+3, myLocation.width(), myLocation.height()*0.4-2) qp.drawLine(myLocation.width()-3, myLocation.height()*0.4+3, myLocation.width(), myLocation.height()*0.4) qp.drawLine(myLocation.width()-6, myLocation.height()*0.4+3, myLocation.width(), myLocation.height()*0.4+8) qp.drawLine(myLocation.width()-3, myLocation.height()*0.4+3, myLocation.width(), myLocation.height()*0.4+6)
def _send_mcast(data, address = QHostAddress.Broadcast): udpSocket = QUdpSocket() addr = QHostAddress(address) print "Sending :", unicode(data), ' to:', addr.toString(), ':34001' return udpSocket.writeDatagram(QString(data).toUtf8().data(), addr, 34001)