示例#1
0
 def __init__(self, inqueue, outqueue):
     self.addtestaction("WorkerThreadTestClass.__init__()")
     self.gpioOutputQueue = Queue.Queue()
     self.sensorQueue = Queue.Queue()
     self.testSensorReadings = {}
     WorkerBaseTestClass.__init__(self)
     WorkerThread.__init__(self, inqueue, outqueue)
示例#2
0
    def serve(self):
        """
        サーバーを起動する
        """

        print("=== Server: サーバーを起動します ===")

        try:
            # socketを生成
            server_socket = self.create_server_socket()

            while True:
                # 外部からの接続を待ち、接続があったらコネクションを確立する
                print("=== Server: クライアントからの接続を待ちます ===")
                (client_socket, address) = server_socket.accept()
                print(
                    f"=== Server: クライアントとの接続が完了しました remote_address: {address} ==="
                )

                # クライアントを処理するスレッドを作成
                thread = WorkerThread(client_socket, address)
                # スレッドを実行
                thread.start()

        finally:
            print("=== Server: サーバーを停止します。 ===")
示例#3
0
 def openSocket(self):
     self.addMessage("Starting server thread.")
     self.workerthread = WorkerThread()
     self.scriptText.connect(self.workerthread, SIGNAL("evaluateCall()"),
                             self.evaluateCall)
     self.scriptText.connect(self.workerthread,
                             SIGNAL("addMessage(QString)"),
                             self.threadMessage)
     self.workerthread.start()
示例#4
0
文件: app.py 项目: agateau/deveba
    def startSync(self, groups):
        self.success = True
        self.workerThread = WorkerThread(groups)
        self.workerThread.logCalled.connect(self.addLog, Qt.QueuedConnection)

        self.sni.setIconByName("task-ongoing")
        self.workerThread.start()
        self.workerThread.finished.connect(self.slotSyncFinished)
示例#5
0
class SocketTaskView(gui3d.TaskView):
    def __init__(self, category):
        self.human = gui3d.app.selectedHuman
        gui3d.TaskView.__init__(self, category, 'Socket')

        box = self.addLeftWidget(gui.GroupBox('Server'))

        self.aToggleButton = box.addWidget(gui.CheckBox('Accept connections'))

        @self.aToggleButton.mhEvent
        def onClicked(event):
            if self.aToggleButton.selected:
                self.openSocket()
            else:
                self.closeSocket()

        self.scriptText = self.addTopWidget(gui.DocumentEdit())
        self.scriptText.setText('')
        self.scriptText.setLineWrapMode(gui.DocumentEdit.NoWrap)

        self.dirops = SocketDirOps(self)
        self.meshops = SocketMeshOps(self)
        self.modops = SocketModifierOps(self)

    def threadMessage(self, message):
        self.addMessage(str(message))

    def evaluateCall(self):
        ops = None
        data = self.workerthread.jsonCall
        conn = self.workerthread.currentConnection

        if self.meshops.hasOp(data.function):
            ops = self.meshops

        if self.dirops.hasOp(data.function):
            ops = self.dirops

        if self.modops.hasOp(data.function):
            ops = self.modops

        if ops:
            jsonCall = ops.evaluateOp(conn, data)
        else:
            jsonCall = data
            jsonCall.error = "Unknown command"

        self.addMessage("About to serialize JSON. This might take some time.")
        response = jsonCall.serialize()

        print "About to send:\n\n" + response
        conn.send(response)
        conn.close()

    def addMessage(self, message, newLine=True):
        if newLine:
            message = message + "\n"
        self.scriptText.addText(message)

    def openSocket(self):
        self.addMessage("Starting server thread.")
        self.workerthread = WorkerThread()
        self.scriptText.connect(self.workerthread, SIGNAL("evaluateCall()"),
                                self.evaluateCall)
        self.scriptText.connect(self.workerthread,
                                SIGNAL("addMessage(QString)"),
                                self.threadMessage)
        self.workerthread.start()
        #start_new_thread(self.serverThread,(None,))

    def closeSocket(self):
        #self.addMessage("Closing socket.")
        if not self.workerthread is None:
            self.workerthread.stopListening()
        self.workerthread = None
示例#6
0
文件: app.py 项目: agateau/deveba
class App(KApplication):
    def __init__(self):
        KApplication.__init__(self)
        self.setQuitOnLastWindowClosed(False)

        self.sni = KStatusNotifierItem()
        self.sni.setTitle(i18n("Deveba"))
        self.sni.setCategory(KStatusNotifierItem.SystemServices)
        self.sni.setStatus(KStatusNotifierItem.Active)

        self.sni.setIconByName("task-accepted")

        self.sni.setToolTipTitle(i18n("Deveba"))

        self.window = Window(self)
        self.window.hide()
        self.window.finished.connect(self.slotWindowClosed)
        self.sni.setAssociatedWidget(self.window)

        self.logMessages = []
        self.success = True
        self.workerThread = None

    @staticmethod
    def options():
        options = KCmdLineOptions()
        options.add("log <file>", ki18n("Write log to file"), "-")
        options.add("c").add("config <file>", ki18n("Config file to use"), core.CONFIG_FILE)
        options.add("+[group]", ki18n("Start backup of $group"))
        return options

    def exec_(self):
        args = KCmdLineArgs.parsedArgs()

        core.setup_logger(str(args.getOption("log")))

        config_file = args.getOption("config")
        config = core.load_config(config_file)

        if args.count() > 0:
            group_names = [str(args.arg(x)) for x in range(args.count())]
            groups = core.get_group_list(config, group_names)
            self.startSync(groups)
        else:
            self.window.show()

        return KApplication.exec_()

    def startSync(self, groups):
        self.success = True
        self.workerThread = WorkerThread(groups)
        self.workerThread.logCalled.connect(self.addLog, Qt.QueuedConnection)

        self.sni.setIconByName("task-ongoing")
        self.workerThread.start()
        self.workerThread.finished.connect(self.slotSyncFinished)

    def slotSyncFinished(self):
        if self.success:
            self.sni.setIconByName("task-accepted")
        self.workerThread = None
        QTimer.singleShot(2 * 60 * 1000, self.quitIfNoWindow)

    def slotWindowClosed(self):
        if self.workerThread is None:
            self.quit()

    def quitIfNoWindow(self):
        if not self.window.isVisible():
            self.quit()

    def addLog(self, level, msg):
        if level < UserInterface.LOG_INFO:
            return

        timestamp = time.localtime()
        message = LogMessage(timestamp, level, msg)
        self.logMessages.append(message)

        texts = [x.formatted() for x in self.logMessages[-MAX_TEXTS_LENGTH:]]
        html = "<ul>" + "".join(["<li>%s</li>" % x for x in texts]) + "</ul>"
        self.sni.setToolTipSubTitle(html)

        if level >= UserInterface.LOG_WARNING:
            self.success = False
            self.sni.setIconByName("dialog-error")

        self.window.addLog(message)
示例#7
0
 def _create_worker_thread(self):
     """initialzes the workerthread """
     q = queue.Queue()
     self.wt = WorkerThread(q)
示例#8
0
class DeviceWrapper():
    """Wrapper class for device object
    
    Class provides framework to directly call device functions and attributes
    while device is part of a worker thread in the background.
    
    Example::
        >>> d = SomeDevice()
        >>> d.some_function()
        5
        >>> dw = DeviceWrapper(d)
        >>> dw.some_function()
        5
        
        
    """
    def __init__(self, device):
        self.d = device
        self._create_worker_thread()

    def __getattr__(self, name):
        """redirects method and attribute calls to device object
        
        
        """
        if hasattr(self.d, name):
            if self.thread_is_alive():
                self.func_name = getattr(self.d, name)
                return self._send_worker_task
            else:
                return getattr(self.d, name)
        else:
            raise AttributeError

    def _create_worker_thread(self):
        """initialzes the workerthread """
        q = queue.Queue()
        self.wt = WorkerThread(q)

    def start(self):
        """starts workerthread"""
        if not self.thread_is_alive():
            self.wt.start()
        else:
            raise DeviceWrapperException('Thread runs already.')

    def stop(self):
        """stops workerthread"""
        if self.thread_is_alive():
            self.wt.stop()
        else:
            raise DeviceWrapperException('Thread is not running.')

    def thread_is_alive(self):
        return self.wt.is_alive()

    def _send_worker_task(self, *args, **kwargs):
        w = WorkerTaskBase(func=self.func_name,
                           args=args,
                           kwargs=kwargs,
                           callback=self._callback)
        self.wt.put(w)
        self.wait_for_callback = True

        while self.wait_for_callback:
            time.sleep(0.1)
        return self.rtn

    def _callback(self, return_args):
        """helper function to retrieve return value from WorkTask object
        
        This function is part of the callback mechanism to retrieve the return
        value from the WorkerTask object function call initiated by the _
        send_worker_task function
        
        """
        self.rtn = return_args
        self.wait_for_callback = False