def __init__(self, songbook="", parent=None): super(KaraokeServer, self).__init__(parent) self.songbook = songbook self.password = "" self.playlist = [] self.maxConnectedClients = 0 # The KaraokeServer consists of a WebSocketServer and a WebServer. self.webSocketServer = QtWebSockets.QWebSocketServer( "Karaoke Server", QtWebSockets.QWebSocketServer.NonSecureMode, self) self.webSocketServerPort = 0 self.WebSocketMethods = { 'getSongbook': self._getSongbook, 'getPlaylist': self._getPlaylist, 'updatePlaylist': self._updatePlaylist, 'addToPlaylist': self._addToPlaylist, 'play': self._play, 'nextSong': self._nextSong, 'stop': self._stop, 'playNow': self._playNow, 'playNext': self._playNext, 'submitPassword': self._submitPassword } self.webServer = WebServer() # Clients hold all clients connected to the WebSocketServer. Clients # are added when they connect and removed when they disconnect. # Admins holds IPs of clients who have administrative privileges. self.clients = {} self.admins = set()
def __init__(self, parent, settings, address="0.0.0.0", port=PORT): super(QtCore.QObject, self).__init__(parent) self.settings = settings self.server = QtWebSockets.QWebSocketServer(parent.serverName(), parent.secureMode(), parent) if self.server.listen(QtNetwork.QHostAddress(address), port): print('Listening: ' + self.server.serverName() + ' : ' + self.server.serverAddress().toString() + ':' + str(self.server.serverPort())) else: print('error') self.server.newConnection.connect(self.on_new_connection) self.clientConnection = None self.gui = None self.msg_responses = None self.msg_uuids = None self.users = {} self.self_name = None self.potions_disable_timer = QTimer() self.potions_disable_timer.timeout.connect(self.clear_effects) print(self.server.isListening())
def run(self): """Checking running simulations progresses.""" try: self.tc = ThreediCalls(self.threedi_api) if self.model_id: logger.debug( f"Fetching simulations list and filtering it on model id {self.model_id}" ) full_simulations_list = self.tc.fetch_simulations() logger.debug( f"Starting out with {len(full_simulations_list)} simulations" ) self.simulations_list = [ simulation for simulation in full_simulations_list if simulation.threedimodel_id == self.model_id ] logger.debug( f"We have {len(self.simulations_list)} simulations left") result = self.tc.fetch_simulations_progresses( self.simulations_list) self.progresses_fetched.emit(result) except ApiException as e: error_msg = extract_error_message(e) self.thread_failed.emit(error_msg) return self.ws_client = QtWebSockets.QWebSocket( "", QtWebSockets.QWebSocketProtocol.Version13, None) self.ws_client.textMessageReceived.connect( self.all_simulations_progress_web_socket) self.ws_client.error.connect(self.websocket_error) self.start_listening()
def __init__(self, parent): super().__init__(parent) self.client = QtWebSockets.QWebSocket( "", QtWebSockets.QWebSocketProtocol.Version13, None) self.client.connected.connect(self.connected) self.client.error.connect(self.error) self.client.textMessageReceived.connect(self.on_message) self.stored_vectors = np.empty((21, 3)) self.client.open(QUrl('ws://localhost:6437/v6.json'))
def __init__(self): super().__init__() self.client = QtWebSockets.QWebSocket("",QtWebSockets.QWebSocketProtocol.Version13,None) self.client.error.connect(self.error) self.client.connected.connect(self.connected) self.client.open(QUrl(f"ws://{HOSTNAME}:81")) self.client.textMessageReceived.connect(self.onText) self.client.binaryMessageReceived.connect(self.onBinary) self.manager = QtNetwork.QNetworkAccessManager()
def __init__(self, parent): super(QtCore.QObject, self).__init__(parent) self.clients = [] self.server = QtWebSockets.QWebSocketServer(parent.serverName(), parent.secureMode(), parent) if self.server.listen(QtNetwork.QHostAddress.LocalHost, 1302): print('Connected: ' + self.server.serverName() + ' : ' + self.server.serverAddress().toString() + ':' + str(self.server.serverPort())) else: print('error') self.server.newConnection.connect(self.onNewConnection)
def send_receive(): ws = QtWebSockets.QWebSocket() def onstatechanged(state): if state == Qt.QAbstractSocket.ConnectedState: ws.sendTextMessage("Hello") def onreceived(data): print(data) QtWidgets.qApp.quit() ws.stateChanged.connect(onstatechanged) ws.textMessageReceived.connect(onreceived) ws.open(Qt.QUrl("ws://localhost:8080/ws"))
def __init__(self): super().__init__() self.client = QtWebSockets.QWebSocket( "", QtWebSockets.QWebSocketProtocol.Version13, None) self.client.error.connect(self.error) self.client.connected.connect(self.connected) self.client.open(QUrl(f"ws://{HOSTNAME}:81")) self.client.pong.connect(self.onPong) self.client.textMessageReceived.connect(self.onText) self.client.binaryMessageReceived.connect(self.onBinary) self.request = QtNetwork.QNetworkRequest() url = QtCore.QUrl(f"http://{HOSTNAME}/command?commandText=?") self.request.setUrl(url) self.manager = QtNetwork.QNetworkAccessManager()
def __init__(self): super(QMainWindow, self).__init__() self.setupUi(self) self.listViewBox = listViewBox(self.widget) self.statusbar.showMessage("Connecting...") # Websocketクライアント作成 self.client = Qws.QWebSocket("", Qws.QWebSocketProtocol.Version13, None) self.client.textMessageReceived.connect(self.onMessageReceived) self.client.error.connect(self.onErrorOccurred) self.client.connected.connect(self.onConnected) self.client.open(QUrl(f"ws://{const.WS_URL}:{const.WS_PORT}")) self.clientID = ""
def __init__(self, parent): super().__init__(parent) self.parent = parent self.ip = None self.port = '8080' self.ping_server_timer = QTimer() self.ping_server_timer.setInterval(800) self.ping_server_timer.start() self.ping_server_timer.timeout.connect(lambda: self.ping_server()) self.client = QtWebSockets.QWebSocket( "", QtWebSockets.QWebSocketProtocol.Version13, None) self.client.error.connect(self.error) self.client.textMessageReceived.connect(self.decoding_json) self.client.pong.connect(self.onPong) self.parent.settings_widget.signal_ip_changed.connect( lambda ip: self.change_ip(ip))
def __init__(self, parent): super(QtCore.QObject, self).__init__(parent) self.clients = [] self.server = QtWebSockets.QWebSocketServer(parent.serverName(), parent.secureMode(), parent) if self.server.listen(QtNetwork.QHostAddress.Any, 0): global WS_PORT WS_PORT = self.server.serverPort() print(self.server.serverName() + ' : ' + self.server.serverAddress().toString() + ':' + str(self.server.serverPort())) else: print('error') self.serverThread = QThread() # self.server.moveToThread(self.serverThread) self.server.newConnection.connect(self.onNewConnection) print(self.server.isListening())
def __init__(self, parent): super().__init__(parent) self.client = QtWebSockets.QWebSocket( "", QtWebSockets.QWebSocketProtocol.Version13, None) ### self.client.textMessageReceived.connect(self.processTextMessage) # self.client.textFrameReceived.connect(self.processTextFrame) # # self.client.binaryMessageReceived.connect(self.processBinaryMessage) # self.client.disconnected.connect(self.socketDisconnected) ### self.client.error.connect(self.error) self.client.open(QUrl("ws://127.0.0.1:1302")) self.client.pong.connect(self.onPong)
def __init__(self, parent): super(QtCore.QObject, self).__init__(parent) self.timer = QTimer() self.timer.setInterval(50) self.timer.timeout.connect(self.send_data) self.clients = [] print("server name: {}".format(parent.serverName())) self.server = QtWebSockets.QWebSocketServer(parent.serverName(), parent.secureMode(), parent) if self.server.listen(QtNetwork.QHostAddress('127.0.0.1'), 8080): print('Listening: {}:{}:{}'.format( self.server.serverName(), self.server.serverAddress().toString(), str(self.server.serverPort()))) else: print('error') self.server.acceptError.connect(self.onAcceptError) self.server.newConnection.connect(self.onNewConnection) self.clientConnection = None print(self.server.isListening())
def __init__(self): super().__init__() # Инициализация QWebSocket и открытие экрана авторизации self.ws = QtWebSockets.QWebSocket( "", QtWebSockets.QWebSocketProtocol.Version13, None) self.routes = {} logging.info('Открытие authScreen') self.authScreen = AuthScreen(self) self.authScreen.show() self.chatScreen = ChatScreen(self) # Подключение всех websocket обработчиков self.ws.error.connect(self.error) self.ws.textMessageReceived.connect(self.message_handler) self.ws.pong.connect(self.on_pong) self.id = None self.url = None self.name = None self.password = None
def __init__(self, parent=None): QMainWindow.__init__(self) self.setupUi(self) self.logo_bit = QPixmap("image/logo.jpg") pixmap = self.logo_bit.scaled(448, 630) self.image_view.setPixmap(pixmap) self.musiclist = QMediaPlaylist() url = QUrl.fromLocalFile("music/starter.mp3") self.musiclist.addMedia(QMediaContent(url)) self.musiclist.setPlaybackMode(QMediaPlaylist.Loop) self.player = QMediaPlayer() self.player.setPlaylist(self.musiclist) self.player.play() self.client = QtWebSockets.QWebSocket( "", QtWebSockets.QWebSocketProtocol.Version13, None) self.client.error.connect(self.on_error) self.client.open(QUrl("ws://127.0.0.1:80")) self.client.connected.connect(self.on_connected) self.client.disconnected.connect(self.on_disconnected) self.client.textMessageReceived.connect(self.on_messages) self.button_left.clicked.connect(self.on_some_button_clicked) self.button_right.clicked.connect(self.on_some_button_clicked) self.default()
def __init__(self): super().__init__() self.ws = QtWebSockets.QWebSocket() self.initialize() self.initialize_menu()
data = [ { 'pos': (int(u['position']['x']), int(u['position']['z'])), 'data': u['name'], 'brush': mkBrush( 'g' ), #mkBrush("r" if u['name'] == self.server.self_name else "g"), 'symbol': ("s" if u['name'] == self.server.self_name else "o"), } for u in users.values() ] self.map_item.setData(data) #map(lambda x: "Red" if x['name'] == self.server.self_name else "Green", users.values()) # self.map_item.setData(x=[int(u['position']['x']) for u in users.values()], # y=[int(u['position']['z']) for u in users.values()], # data=[u['name'] for u in users.values()]) if __name__ == '__main__': import sys QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) app = QApplication(sys.argv) settings = QSettings("PositiveState", "MC Classroom") serverObject = QtWebSockets.QWebSocketServer( 'My Socket', QtWebSockets.QWebSocketServer.NonSecureMode) server = WSServer(serverObject, settings, address='0.0.0.0') gui = MCClassroom(settings, server) server.gui = gui serverObject.closed.connect(app.quit) app.exec_()
def buildSocket(app): serverObject = QtWebSockets.QWebSocketServer( 'My Socket', QtWebSockets.QWebSocketServer.NonSecureMode) server = MyServer(serverObject) serverObject.closed.connect(app.quit) return (server, serverObject)
def __init__(self, **kwargs): """ :param parent: The parent QObject for this connection. :param channel: The channel to connect to upon login. :param channels: A list of channels to connect to upon login. :param nick: The name to use during the login process. :param token: The OAuth token to use during the login process. :param host: The host server to connect to. :param port: The port to connect to. :param whisper_reset: The moment the account limit gets reset. """ # Super call super(Gateway, self).__init__(parent=kwargs.get('parent')) # Public attributes self.channels: typing.List[str] = [] self.whisper_reset: datetime.datetime = kwargs.get( 'whisper_reset', None) # Private attributes self.nick: str = kwargs.get('nick', 'justinfan2389') self.token: str = kwargs.get('token', 'foobar') self.host: str = kwargs.get('host', 'irc-ws.chat.twitch.tv') self.port: int = kwargs.get('port', 443) # Internal attributes self._socket = QtWebSockets.QWebSocket(parent=self) self._timer = QtCore.QTimer(parent=self) self._whisper_second_started: bool = False self._whisper_minute_started: bool = False self._whisper_daily_started: bool = False self._join_started: bool = False self._priv_started: bool = False self._should_reconnect: bool = True self._reset_join_limit_auto = functools.partial(self.reset_join_limit, automated=True) self._reset_priv_limit_auto = functools.partial(self.reset_priv_limit, automated=True) self._reset_w_second_auto = functools.partial( self.reset_whisper_seconds, automated=True) self._reset_w_minute_auto = functools.partial( self.reset_whisper_minutes, automated=True) self._reset_w_daily_auto = functools.partial(self.reset_whisper_daily, automated=True) # Ratelimiting attributes self._priv_sent: int = 0 self._priv_limit: int = 20 self._priv_period: int = 30 # Seconds self._join_sent: int = 0 self._join_limit: int = 50 self._join_period: int = 15 # Seconds self._whispers_this_second: int = 0 # Whispers sent this second self._whispers_this_minute: int = 0 # Whispers sent this minute self._whispered_accounts: typing.List[str] = [ ] # The accounts whispered. self._whisper_second_limit: int = 3 self._whisper_minute_limit: int = 200 # Messages per minute self._whisper_accounts_limit: int = 40 self._reconnect_attempts: int = 0 # Internal calls self._socket.error.connect(self.process_errors) self._socket.connected.connect(self.process_connection) self._socket.disconnected.connect(self.process_disconnection) self._socket.textMessageReceived.connect(self.process_message) self.qt_disconnect = super(Gateway, self).disconnect # Validation # if self.token != "foobar" and not self.token.startswith("oauth"): self.token = f'oauth:{self.token}'
def __init__(self): self.fluid_conversions = None self.dosing = None self.light_control = None self.schedule = None self.completed = '' self.fertz_prev_time = '' self.conditioner_prev_time = '' self.nam = QtNetwork.QNetworkAccessManager() self.timers = [] self.calibration_mode_on = True self.pause_on = False self.conversion_values = { "tank_size": {}, "co2_amount": {}, "co2_to_water": {}, "fertz_amount": {}, "fertz_to_water": {}, "conditioner_amount": {}, "conditioner_to_water": {}, "co2_dosage": {}, "fertz_dosage": {}, "conditioner_dosage": {}, } self.conversion_data = { "Tank Size": {}, "Co2 Ratio": {}, "Fertilizer Ratio": {}, "Water Conditioner Ratio": {}, } self.schedule_data = { "Co2 Schedule Data": {}, "Fertilizer Schedule Data": {}, "Tap Schedule Data": {}, "Water Cycle Schedule Data": {} } self.calibration_data = { "Co2 Calibration Data": {}, "Fertilizer Calibration Data": {}, "Water Conditioner Calibration Data": {}, } self.light_hour_data = { "Mode Hours": {}, } # Simple mapping for the combobox self.light_type_map = { 'default': 'off', 0: 'day', 1: 'night', 2: 'off', } self.temperature_data = { "Temperature Alert": {}, } self.dosage_data = { "Co2 Dosage": {}, } self.app = QtWidgets.QApplication(sys.argv) self.central = QtWidgets.QWidget() self.window = QtWidgets.QMainWindow() self.form = Ui_Form() self.window.setCentralWidget(self.central) self.form.setupUi(self.central) #self.app.setStyle("fusion") self.hour_btns = [ self.form.hours_0, self.form.hours_1, self.form.hours_2, self.form.hours_3, self.form.hours_4, self.form.hours_5, self.form.hours_6, self.form.hours_7, self.form.hours_8, self.form.hours_9, self.form.hours_10, self.form.hours_11, self.form.hours_12, self.form.hours_13, self.form.hours_14, self.form.hours_15, self.form.hours_16, self.form.hours_17, self.form.hours_18, self.form.hours_19, self.form.hours_20, self.form.hours_21, self.form.hours_22, self.form.hours_23, ] self.form.clear_log_button.clicked.connect(self.clear_log_button) self.form.pause_button.clicked.connect(self.pause_operation) self.form.day_hour_wheel.valueChanged.connect(self.log_day_hour_wheel) self.form.night_hour_wheel.valueChanged.connect( self.night_hour_wheel_changed) self.form.off_hour_wheel.valueChanged.connect(self.log_off_hour_wheel) self.form.saveDoses_pushButton.clicked.connect(self.save_doses) self.form.feed_pushButton.clicked.connect(self.feed_test) self.form.C02CalibrationButton.clicked.connect( lambda: self.enter_calibration_mode("co2")) self.form.c02_pushButton.clicked.connect( lambda: self.co2_manual_dose("Co2")) self.form.FertzCalibrationButton.clicked.connect( self.fertz_calibration) self.form.TapSafeCalibrationButton.clicked.connect( self.conditioner_calibration) self.form.c02_comboBox_2.currentIndexChanged.connect(self.save_doses) self.form.fertz_comboBox_2.currentIndexChanged.connect( self.fertz_dose_times_a_week) self.form.water_conditioner_comboBox.currentIndexChanged.connect( self.conditioner_dose_times_a_week) self.form.calendarWidget.selectionChanged.connect(self.dose_sch) self.form.co2_sch_pushButton.clicked.connect(self.set_co2_schedule) self.form.fertz_sch_pushButton.clicked.connect(self.set_fertz_schedule) self.form.conditioner__sch_pushButton.clicked.connect( self.set_conditioner_schedule) self.form.water_cycle_sch_pushButton.clicked.connect( self.set_water_cycle_schedule) self.form.del_events_pushButton.clicked.connect(self.del_events_sch) self.form.repeat_comboBox.currentIndexChanged.connect(self.repeat_sch) self.form.hour_save_button.clicked.connect(self.set_schedule) self.form.sunrise_sunset_radioButton.clicked.connect(self.sun_mode) self.form.manual_hour_mode_radioButton.clicked.connect( self.manual_hours_mode) self.form.light_mode_comboBox.currentTextChanged.connect( self.toggle_mode) self.form.ht_alert_edit.valueChanged.connect(self.set_temp_alert) self.form.lt_alert_edit.valueChanged.connect(self.set_temp_alert) self.conditioner_calibration_started = False self.fertz_calibration_started = False self.co2_calibration_started = False logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO) self.log = logging.getLogger('AquariumQT') self.log.handlers = [InfoHandler(self.form.textBrowser)] self.load_server() self.start_timers() self.update_timer() self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update_timer) self.timer.start(1000) self.client = QtWebSockets.QWebSocket( "", QtWebSockets.QWebSocketProtocol.Version13, None) self.client.error.connect(self.on_error) self.client.open(QUrl("ws://192.168.1.35:5000/temp")) self.client.pong.connect(self.ws_receive) self.client.textMessageReceived.connect(self.ws_receive)
from websocketclientwrapper import WebSocketClientWrapper if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) jsFileInfo = QtCore.QFileInfo( os.path.join(QtCore.QDir.currentPath(), "qwebchannel.js")) if not jsFileInfo.exists(): QtCore.QFile.copy(":/qtwebchannel/qwebchannel.js", jsFileInfo.absoluteFilePath()) server = QtWebSockets.QWebSocketServer( "QWebChannel Standalone Example Server", QtWebSockets.QWebSocketServer.NonSecureMode, ) if not server.listen(QtNetwork.QHostAddress.LocalHost, 12345): print("Failed to open web socket server.") sys.exit(-1) clientWrapper = WebSocketClientWrapper(server) channel = QtWebChannel.QWebChannel() clientWrapper.clientConnected.connect(channel.connectTo) dialog = Dialog() core = Core(dialog) channel.registerObject("core", core) file = os.path.join(os.path.dirname(os.path.realpath(__file__)),