Esempio n. 1
0
    def serialReadEvent(self):
        #get that character we set up
        n = win32file.GetOverlappedResult(self._serial.hComPort,
                                          self._overlappedRead, 0)
        if n:
            first = str(self.read_buf[:n])
            #now we should get everything that is already in the buffer
            flags, comstat = win32file.ClearCommError(self._serial.hComPort)
            if comstat.cbInQue:
                win32event.ResetEvent(self._overlappedRead.hEvent)
                rc, buf = win32file.ReadFile(
                    self._serial.hComPort,
                    win32file.AllocateReadBuffer(comstat.cbInQue),
                    self._overlappedRead)
                n = win32file.GetOverlappedResult(self._serial.hComPort,
                                                  self._overlappedRead, 1)
                #handle all the received data:
                self.protocol.dataReceived(first + str(buf[:n]))
            else:
                #handle all the received data:
                self.protocol.dataReceived(first)

        #set up next one
        win32event.ResetEvent(self._overlappedRead.hEvent)
        rc, self.read_buf = win32file.ReadFile(self._serial.hComPort,
                                               win32file.AllocateReadBuffer(1),
                                               self._overlappedRead)
Esempio n. 2
0
 def testResetEvent(self):
     event = win32event.CreateEvent(None, True, True, None)
     self.assertSignaled(event)
     res = win32event.ResetEvent(event)
     assert res == None
     self.assertNotSignaled(event)
     event.close()
     with pytest.raises(pywintypes.error):
         win32event.ResetEvent(event)
Esempio n. 3
0
 def __init__(self, tagName='trader_msg', size=1024 * 1024):
     self.fm = mmap.mmap(-1,
                         size,
                         access=mmap.ACCESS_WRITE,
                         tagname=tagName)
     self.eventAu = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS, 0,
                                         "aauto_trigger")
     self.eventPy = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS, 0,
                                         "python_trigger")
     self.timeOut = 0xFFFFFFFF  #无穷等待
     win32event.ResetEvent(self.eventAu)
     win32event.ResetEvent(self.eventPy)
Esempio n. 4
0
    def __wait_for_child(self):
        # kick off threads to read from stdout and stderr of the child process
        threading.Thread(target=self.__do_read,
                         args=(self.__child_stdout, )).start()
        threading.Thread(target=self.__do_read,
                         args=(self.__child_stderr, )).start()

        while True:
            # block waiting for the process to finish or the interrupt to happen
            handles = (self.wake_up_event, self.h_process)
            val = win32event.WaitForMultipleObjects(handles, 0,
                                                    win32event.INFINITE)

            if val >= win32event.WAIT_OBJECT_0 and val < win32event.WAIT_OBJECT_0 + len(
                    handles):
                handle = handles[val - win32event.WAIT_OBJECT_0]
                if handle == self.wake_up_event:
                    win32api.TerminateProcess(self.h_process, 1)
                    win32event.ResetEvent(self.wake_up_event)
                    return False
                elif handle == self.h_process:
                    # the process has ended naturally
                    return True
                else:
                    assert False, "Unknown handle fired"
            else:
                assert False, "Unexpected return from WaitForMultipleObjects"
Esempio n. 5
0
    def run(self):
        continueloop = True
        n = 1
        waitingOnRead = False
        buf = win32file.AllocateReadBuffer(n)

        while continueloop:
            if self.EVENT.isSet():
                win32event.SetEvent(self.stopevent)

            if not waitingOnRead:
                win32event.ResetEvent(self.serial._overlappedRead.hEvent)
                hr, _ = win32file.ReadFile(self.serial.hComPort, buf, self.serial._overlappedRead)
                if hr == 997: waitingOnRead = True
                elif hr == 0: pass
                else: raise

            rc = win32event.MsgWaitForMultipleObjects((self.serial._overlappedRead.hEvent, self.stopevent),
                                                        0, 1000, win32event.QS_ALLINPUT)
            if rc == win32event.WAIT_OBJECT_0:
                n = win32file.GetOverlappedResult(self.serial.hComPort, self.serial._overlappedRead, 1)
                if n and not self.EVENT.isSet(): self.plugin.Decode(ord(buf[0]))
                waitingOnRead = False

            elif rc == win32event.WAIT_OBJECT_0+1: continueloop = False
            elif rc == win32event.WAIT_TIMEOUT: pass
            else: pass

        self.serial.close()
Esempio n. 6
0
    def get_latest_array(self, copy=False, timeout=None):
        '''
        takes the most recent buffer in the queue, waits for it to be finished,
        then resets its event, saves the frame as the latest, and adds the buffer
        to the end of the queue, effectively rotating the queue.
:
        param copy: copy the frame or not
         :param timeout: time in ms to wait before throwing an error
        :return: True if successful
        '''
        buf = self.queue[0]  # grab the "first" buffer
        timeout = win32event.INFINITE if timeout is None else max(0, timeout)
        ret = win32event.WaitForSingleObject(buf.event, int(timeout))
        if ret == win32event.WAIT_OBJECT_0:
            error, ret = self.__cam.get_buffer_status(buf.idx)
            drv_status = ret['drv_status']
            if error != 0:
                raise PcoCamError("Get Buffer Status Failed: ",
                                  self.__cam.get_error_text(error))
            if drv_status != 0:
                raise PcoCamError(self.__cam.get_error_text(drv_status))
            win32event.ResetEvent(buf.event)  # resent the buffer event
        elif ret == win32event.WAIT_TIMEOUT:
            raise TimeoutError("Wait for buffer timed out.")
        else:
            raise Exception("Failed to grab image.")
        latest_buffer = self.queue.popleft()
        self.add_buffer_to_queue(buf)
        self.latest_array = np.asarray(
            (ctypes.c_uint16 * (latest_buffer.size // 16)).from_address(
                latest_buffer.address)).newbyteorder().astype(dtype=np.uint8)
        if copy:
            return self.latest_array.reshape(self.yRes, self.xRes)[:]
        else:
            return self.latest_array.reshape(self.yRes, self.xRes)
Esempio n. 7
0
def Connect(entryName, bUseCallback):
    if bUseCallback:
        theCallback = Callback
        win32event.ResetEvent(callbackEvent)
    else:
        theCallback = None
    #       in order to *use* the username/password of a particular dun entry, one must
    #       explicitly get those params under win95....
    try:
        dp, b = win32ras.GetEntryDialParams( None, entryName )
    except:
        print("Couldn't find DUN entry: %s" % entryName)
    else:
        hras, rc = win32ras.Dial(None, None, (entryName, "", "", dp[ 3 ], dp[ 4 ], ""),theCallback)
    #       hras, rc = win32ras.Dial(None, None, (entryName, ),theCallback)
    #       print hras, rc
        if not bUseCallback and rc != 0:
            print("Could not dial the RAS connection:", win32ras.GetErrorString(rc))
            hras = HangUp( hras )
        #       don't wait here if there's no need to....
        elif bUseCallback and win32event.WaitForSingleObject(callbackEvent, 60000)!=win32event.WAIT_OBJECT_0:
            print("Gave up waiting for the process to complete!")
            #       sdk docs state one must explcitly hangup, even if there's an error....
            try:
                cs = win32ras.GetConnectStatus( hras )
            except:
                #       on error, attempt a hang up anyway....
                hras = HangUp( hras )
            else:
                if int( cs[ 0 ] ) == win32ras.RASCS_Disconnected:
                    hras = HangUp( hras )
    return hras, rc
Esempio n. 8
0
 def Write(self, data, timeout):
     if self.handle:
         try:
             self.lockObject.acquire()
             if eg.debugLevel:
                 print("writing " + str(len(data)) + " bytes to " +
                       self.getName())
             if not self._overlappedWrite:
                 self._overlappedWrite = win32file.OVERLAPPED()
             err, n = win32file.WriteFile(self.handle, data,
                                          self._overlappedWrite)
             if err:  #will be ERROR_IO_PENDING:
                 # Wait for the write to complete.
                 n = win32file.GetOverlappedResult(self.handle,
                                                   self._overlappedWrite, 1)
                 if n != len(data):
                     raise Exception("could not write full data")
             elif n != len(data):
                 raise Exception("could not write full data")
             if timeout:  #waits for response from device
                 win32event.ResetEvent(self._overlappedRead.hEvent)
                 res = win32event.WaitForSingleObject(
                     self._overlappedRead.hEvent, timeout)
                 if res == win32event.WAIT_TIMEOUT:
                     raise Exception(
                         "no response from device within timeout")
         finally:
             self.lockObject.release()
     else:
         raise Exception("invalid handle")
Esempio n. 9
0
    def receivebyte(self, RDtimeout=0):
        """read num bytes from serial port"""
        if not self.hComPort: raise portNotOpenError

        timeouts = (win32con.MAXDWORD, win32con.MAXDWORD, int(RDtimeout * 100),
                    0, 0)  # timeouts in 100 ms units...
        win32file.SetCommTimeouts(self.hComPort, timeouts)

        win32event.ResetEvent(self._overlappedRead.hEvent)
        flags, comstat = win32file.ClearCommError(self.hComPort)

        n = comstat.cbInQue
        if n > 0:  # there is data in buffer
            rc, buf = win32file.ReadFile(self.hComPort,
                                         win32file.AllocateReadBuffer(1),
                                         self._overlappedRead)
            win32event.WaitForSingleObject(self._overlappedRead.hEvent,
                                           win32event.INFINITE)
            read = buf[0]
        else:
            rc, buf = win32file.ReadFile(self.hComPort,
                                         win32file.AllocateReadBuffer(1),
                                         self._overlappedRead)
            n = win32file.GetOverlappedResult(self.hComPort,
                                              self._overlappedRead, 1)
            if n > 0:
                read = buf[0]
            else:
                read = -1
        return read
Esempio n. 10
0
 def read(self, size=1):
     """Read size bytes from the serial port. If a timeout is set it may
        return less characters as requested. With no timeout it will block
        until the requested number of bytes is read."""
     if not self.hComPort: raise portNotOpenError
     if size > 0:
         win32event.ResetEvent(self._overlappedRead.hEvent)
         flags, comstat = win32file.ClearCommError(self.hComPort)
         if self.timeout == 0:
             n = min(comstat.cbInQue, size)
             if n > 0:
                 rc, buf = win32file.ReadFile(
                     self.hComPort, win32file.AllocateReadBuffer(n),
                     self._overlappedRead)
                 win32event.WaitForSingleObject(self._overlappedRead.hEvent,
                                                win32event.INFINITE)
                 read = str(buf)
             else:
                 read = ''
         else:
             rc, buf = win32file.ReadFile(
                 self.hComPort, win32file.AllocateReadBuffer(size),
                 self._overlappedRead)
             n = win32file.GetOverlappedResult(self.hComPort,
                                               self._overlappedRead, 1)
             read = str(buf[:n])
     else:
         read = ''
     return read
Esempio n. 11
0
 def wait(self, timeout=60):
     '''等待消息同步
     '''
     if self._syncwnd == 0:
         return
     win32event.ResetEvent(self._eventobj)
     
     try:
         win32gui.PostMessage(self._syncwnd, win32con.WM_TIMER, 0, 0)
     except pywintypes.error as e:
         if e.winerror == winerror.ERROR_INVALID_WINDOW_HANDLE:
             return
         raise e
     
     start_time = time.time()
     end_time = start_time
     while end_time - start_time <= timeout:
         if win32gui.IsWindow(self._syncwnd):
             ret = win32event.WaitForSingleObject(self._eventobj, 500)
             if ret == win32con.WAIT_OBJECT_0:
                 break
             else:
                 end_time = time.time()
         else:
             win32api.CloseHandle(self._eventobj)
             del MsgSyncer.pid_event_map[self._pid]
             break
     if end_time - start_time > timeout:
         raise RuntimeError('消息同步超时(%d秒)'%timeout)
Esempio n. 12
0
    def wait_for_frame(self, timeout=None):
        if self._double_img is not None:
            return True

        timeout = win32event.INFINITE if timeout is None else max(
            0, timeout.m_as('ms'))

        buf_i = (self._buf_i) % self._nbufs  # Most recently triggered buffer
        ret = win32event.WaitForSingleObject(int(self._buf_events[buf_i]),
                                             int(timeout))

        if ret != win32event.WAIT_OBJECT_0:
            return False  # Object is not signaled

        win32event.ResetEvent(int(self._buf_events[buf_i]))
        self._dev.PCC_RESETEVENT(buf_i)
        status = self._dev.GETBUFFER_STATUS(self._bufnums[buf_i], 0)

        #if px.PCC_BUF_STAT_ERROR(ptr):
        if status[0] & 0xF000:
            uptr = ffi.cast('DWORD *', status)
            raise Exception(
                "Buffer error 0x{:08X} 0x{:08X} 0x{:08X} 0x{:08X}".format(
                    uptr[0], uptr[1], uptr[2], uptr[3]))

        if self._shutter == 'video':
            self._dev.ADD_BUFFER_TO_LIST(self._bufnums[self._buf_i],
                                         self._frame_size(), 0, 0)
        self._buf_i = (self._buf_i + 1) % self._nbufs

        return True
Esempio n. 13
0
    def wait_for_frame(self, timeout=None):
        """wait_for_frame(self, timeout=None')"""
        ptr = ffi.new('int[4]')
        buf_i = (self._buf_i -
                 1) % self._nbufs  # Most recently triggered buffer
        ret = win32event.WaitForSingleObject(int(self._buf_events[buf_i]),
                                             int(timeout.m_as('ms')))

        if ret != win32event.WAIT_OBJECT_0:
            return False  # Object is not signaled

        win32event.ResetEvent(int(self._buf_events[buf_i]))
        px.PCC_RESETEVENT(self._hcam, buf_i)
        px.GETBUFFER_STATUS(self._hcam, self._bufnums[buf_i], 0, ptr,
                            ffi.sizeof('DWORD') * 1)

        if px.PCC_BUF_STAT_ERROR(ptr):
            uptr = ffi.cast('DWORD *', ptr)
            raise Exception(
                "Buffer error 0x{:08X} 0x{:08X} 0x{:08X} 0x{:08X}".format(
                    uptr[0], uptr[1], uptr[2], uptr[3]))

        if self._shutter == 'video':
            px.ADD_BUFFER_TO_LIST(self._hcam, self._bufnums[self._buf_i],
                                  self._frame_size(), 0, 0)
            self._buf_i = (self._buf_i + 1) % self._nbufs

        return True
Esempio n. 14
0
    def __init__(self, cmd, shell=False):
        self.queue = Queue.Queue()
        self.is_terminated = False
        self.wake_up_event = win32event.CreateEvent(None, 0, 0, None)

        exec_dir = os.getcwd()
        comspec = os.environ.get("COMSPEC", "cmd.exe")
        cmd = comspec + ' /c ' + cmd

        win32event.ResetEvent(self.wake_up_event)

        currproc = win32api.GetCurrentProcess()

        sa = win32security.SECURITY_ATTRIBUTES()
        sa.bInheritHandle = 1

        child_stdout_rd, child_stdout_wr = win32pipe.CreatePipe(sa, 0)
        child_stdout_rd_dup = win32api.DuplicateHandle(
            currproc, child_stdout_rd, currproc, 0, 0,
            win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(child_stdout_rd)

        child_stderr_rd, child_stderr_wr = win32pipe.CreatePipe(sa, 0)
        child_stderr_rd_dup = win32api.DuplicateHandle(
            currproc, child_stderr_rd, currproc, 0, 0,
            win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(child_stderr_rd)

        child_stdin_rd, child_stdin_wr = win32pipe.CreatePipe(sa, 0)
        child_stdin_wr_dup = win32api.DuplicateHandle(
            currproc, child_stdin_wr, currproc, 0, 0,
            win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(child_stdin_wr)

        startup_info = win32process.STARTUPINFO()
        startup_info.hStdInput = child_stdin_rd
        startup_info.hStdOutput = child_stdout_wr
        startup_info.hStdError = child_stderr_wr
        startup_info.dwFlags = win32process.STARTF_USESTDHANDLES

        cr_flags = 0
        cr_flags = win32process.CREATE_NEW_PROCESS_GROUP

        env = os.environ.copy()
        self.h_process, h_thread, dw_pid, dw_tid = win32process.CreateProcess(
            None, cmd, None, None, 1, cr_flags, env, os.path.abspath(exec_dir),
            startup_info)

        win32api.CloseHandle(h_thread)

        win32file.CloseHandle(child_stdin_rd)
        win32file.CloseHandle(child_stdout_wr)
        win32file.CloseHandle(child_stderr_wr)

        self.__child_stdout = child_stdout_rd_dup
        self.__child_stderr = child_stderr_rd_dup
        self.__child_stdin = child_stdin_wr_dup

        self.exit_code = -1
Esempio n. 15
0
    def _read_events(self):
        """Reads the events from the system and formats as ``DirWatcherEvent``.

        :returns: List of ``(DirWatcherEvent, <path>)``
        """
        result = []

        while self._changed:
            info = self._changed.popleft()

            try:
                size = win32file.GetOverlappedResult(info.file,
                                                     info.overlapped,
                                                     False)
            except win32file.error as exc:
                win32event.ResetEvent(info.overlapped.hEvent)
                _LOGGER.warning(
                    'Failed to get directory changes for \'%s\': %s',
                    info.path, exc)

                if exc.winerror == winerror.ERROR_ACCESS_DENIED:
                    self._preempt_watch(info, result)
                continue

            notifications = win32file.FILE_NOTIFY_INFORMATION(info.buffer,
                                                              size)

            for action, path in notifications:
                action_name = _ACTION_NAMES.get(action)
                path = os.path.join(info.path, path)
                if action_name is None:
                    _LOGGER.error('Received unknown action (%s, \'%s\')',
                                  action, path)
                    continue

                _LOGGER.debug('Received event (%s, \'%s\')', action_name, path)

                event = _EVENTS.get(action_name)
                if event is not None:
                    result.append((event, path))

            win32event.ResetEvent(info.overlapped.hEvent)
            if not self._read_dir(info):
                self._preempt_watch(info, result)

        return result
Esempio n. 16
0
 def testResetEvent(self):
     event = win32event.CreateEvent(None, True, True, None)
     self.assertSignaled(event)
     res = win32event.ResetEvent(event)
     self.assertEquals(res, None)
     self.assertNotSignaled(event)
     event.close()
     self.assertRaises(pywintypes.error, win32event.ResetEvent, event)
Esempio n. 17
0
 def sleep(secs):
     win32event.ResetEvent(self.wake_up_event)
     timeout = int(1000 * secs)
     val = win32event.WaitForSingleObject(self.wake_up_event, timeout)
     if val == win32event.WAIT_TIMEOUT:
         return True
     else:
         # The wake_up_event must have been signalled
         return False
Esempio n. 18
0
    def run(self):
        old_cache = self.enum_values()
        while True:
            win32api.RegNotifyChangeKeyValue(
                self.key_handle,
                True,
                win32api.REG_NOTIFY_CHANGE_LAST_SET,
                self.event,
                True
            )

            # Check for event signal
            event_signal = win32event.WaitForSingleObject(
                self.event, 1
            )

            if event_signal == 0:
                # Event has been signalled
                new_cache = self.enum_values()
                this = old_cache.get_change(new_cache)

                for key, hash in this.items():
                    decoded_key = codecs.decode(key, 'rot-13')
                    record = {
                        "guid": self.name,
                        "timestamp": datetime.datetime.utcnow().time().strftime("%H:%M:%S"),
                        "key_name": self.key_path,
                        "value_name": key,
                        "value_decoded_name": decoded_key
                    }

                    value_data, value_type = win32api.RegQueryValueEx(
                        self.key_handle,
                        key
                    )

                    if len(value_data) >= 68:
                        user_assist = UserAssist(
                            value_data
                        )
                        record.update(
                            user_assist.as_dict()
                        )
                        self.callback(
                            Box(record)
                        )

                win32event.ResetEvent(self.event)
                win32api.RegNotifyChangeKeyValue(
                    self.key_handle,
                    True,
                    win32api.REG_NOTIFY_CHANGE_LAST_SET,
                    self.event,
                    True
                )

                old_cache = new_cache
Esempio n. 19
0
    def pipeRead(self):
        """
        Read some data
        """

        n = win32file.GetOverlappedResult(self._handle, self._olapped_io, 0)
        data = self._read_buffer[:n]
        self.dataReceived(data)
        win32event.ResetEvent(self._olapped_io.hEvent)
        win32file.ReadFile(self._handle, self._read_buffer, self._olapped_io)
Esempio n. 20
0
    def wait_for_frame(self, timeout=None):
        timeout_ms = win32event.INFINITE if timeout is None else int(timeout.m_as('ms'))
        ret = win32event.WaitForSingleObject(self._frame_event, timeout_ms)
        win32event.ResetEvent(self._frame_event)

        if ret == win32event.WAIT_TIMEOUT:
            return False
        elif ret != win32event.WAIT_OBJECT_0:
            raise Error("Failed to grab image: Windows event return code 0x{:x}".format(ret))

        return True
Esempio n. 21
0
 def sendCmd(self, cmd_id, arg=None):
     self.fm.seek(0)
     # 写入命令号
     cmd = struct.pack('i', cmd_id)
     self.fm.write(cmd)
     # 发送一个struct字节码
     if arg:
         self.fm.write(arg)
     # 触发AAuto信号
     win32event.ResetEvent(self.eventPy)
     win32event.SetEvent(self.eventAu)
Esempio n. 22
0
 def write(self, data):
     self.write_lock.acquire()
     writelen = 0
     try:
         win32event.ResetEvent(self.write_overlapped.hEvent)
         err, writelen = win32file.WriteFile(self.handle, data,
                                             self.write_overlapped)
         if err == 997:
             writelen = win32file.GetOverlappedResult(
                 self.handle, self.write_overlapped, True)
     finally:
         self.write_lock.release()
     return writelen
Esempio n. 23
0
def Command(code, dict):
    pymech.dict = dict
    pymech.code = code
    if not pymech.rthread:
        pymech.rthread = thread.start_new_thread(rthread, (1, 1))
    pymech.RESPONSE = 0
    pymech.inrun = 0
    if code == PYRun or code == PYReplay:
        pymech.inrun = 1
    blk = struct.pack('BBhi', 0x81, CMD, 8, code)
    pymech.pyacc.SendData(blk)
    logger('sent command %d' % code)
    win32event.ResetEvent(pymech.cmdresp)
    win32event.SetEvent(pymech.commander)
    logger('waiting for resp')
    win32event.WaitForSingleObject(pymech.cmdresp, win32event.INFINITE)
    win32event.ResetEvent(pymech.commander)

    win32event.ResetEvent(pymech.cmdresp)
    logger('got resp %d' % pymech.RESPONSE)

    return pymech.RESPONSE
Esempio n. 24
0
def Command(code,dict):
    py.FROMpy.CMDRESP=0xf0+code
    py.FROMpy.CMD=code
    py.interface=dict
    logger('in command %d'%code)
    msgrpt=1
    #print dict
    while 1:
        win32event.SetEvent(mech.commander)   # let command processor run
        if msgrpt:
            logger('set event commander')
        while 1:
            ans=win32event.WaitForSingleObject(mech.cmdresp,tout)
            if code == PYRun or code == PYReplay:
                time.sleep(1.0)
            else:
                time.sleep(0.1)
            if ans == win32event.WAIT_TIMEOUT:
                if thread_enable == 0:
                    return 0
                if code == PYGameTerminate:
                    thread_enable=0
                    return 0
                continue
            rsp=py.FROMpy.CMDRESP
            if rsp != 0xF0+code:
                break
        # if win32event.WaitForSingleObject(py.sema,win32event.INFINITE)
        # if py.eeger.DICTQ != 0:
        #     handle_dictq()
        # else:
        msgrpt=1
        logger('outa command %d'%rsp)
        win32event.ResetEvent(mech.commander)
        logger('reset commander')
        win32event.ResetEvent(mech.cmdresp)
        logger('reset cmdresp')
        return rsp
Esempio n. 25
0
 def _setCallbackThread(self):
     
     self._alive = True
     self._acquiring = False
     
     self._callbackHandle = event.CreateEvent(None, TRUE, False, "CallbackHandle")
     event.ResetEvent(self._callbackHandle)
     print self._callbackHandle
     
     assert camlib.SetDriverEvent(c_int(self._callbackHandle)) == consts.DRV_SUCCESS
           
     self._callbackThread = threading.Thread(target = self._waitForCallback)
     self._callbackThread.start()
     return
Esempio n. 26
0
    def _update_wsl_distros():
        global ctx, registry_key_handle, wsl_distros, registry_access_flags

        # make sure registry is open
        if not registry_key_handle:
            _initialize_key()

        distro_handle = None
        try:
            # check for registry changes
            result = win32event.WaitForSingleObjectEx(key_event, 0, False)
            # for testing
            if False:
                print(
                    f"WAIT - {result=} (looking for 'win32con.WAIT_OBJECT_0')")
                print(f'WAIT - {win32con.WAIT_OBJECT_0=})')
                print(f'WAIT - {win32con.WAIT_ABANDONED=})')
                print(f'WAIT - {win32con.WAIT_TIMEOUT=})')
            if result == win32con.WAIT_OBJECT_0:
                # registry has changed since we last read it, load the distros
                subkeys = win32api.RegEnumKeyEx(registry_key_handle)
                for subkey in subkeys:
                    #print(f'{subkey=}')

                    distro_handle = win32api.RegOpenKeyEx(
                        registry_key_handle, subkey[0], 0,
                        registry_access_flags)
                    #print(f"{distro_handle=}")

                    distro_name = win32api.RegQueryValueEx(
                        distro_handle, 'DistributionName')[0]
                    #print(f'{distro_name=}')
                    wsl_distros.append(distro_name)

                    win32api.RegCloseKey(distro_handle)

                # reset the event, will be set by system if reg key changes
                win32event.ResetEvent(key_event)

            elif result != win32con.WAIT_TIMEOUT:
                # something unexpected happened
                error = win32api.GetLastError()
                _close_key()
                raise Exception(
                    'failed while checking for wsl registry updates: {result=}: {error=}'
                )
        except WindowsError:
            if distro_handle:
                win32api.RegCloseKey(distro_handle)
            log_exception(f'[_update_wsl_distros()] {sys.exc_info()[1]}')
Esempio n. 27
0
 def read(self):
     self.read_lock.acquire()
     result = None
     try:
         win32event.ResetEvent(self.read_overlapped.hEvent)
         err, data = win32file.ReadFile(self.handle, self.buffer,
                                        self.read_overlapped)
         if err == 997:  #ERROR_IO_PENDING
             n = win32file.GetOverlappedResult(self.handle,
                                               self.read_overlapped, True)
             result = bytes(data[:n])
         else:
             result = bytes(data)
     finally:
         self.read_lock.release()
     return result
Esempio n. 28
0
    def flush(self):
        """
        This wil flush the usb channel. If the
        device handle is None it will try to open
        to flush
        Args:

        Returns:
            bytes: flushed data

        Raises:

        """
        if self.http_usb_handle != None:
            self.close()

        http_usb_handle = self.open(
            flags_and_attributes=win32file.FILE_FLAG_OVERLAPPED)

        buffer = bytes()
        overlapped = pywintypes.OVERLAPPED()
        overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
        try:
            while True:
                _, data = win32file.ReadFile(http_usb_handle, READ_BUFFER_SIZE,
                                             overlapped)
                rc2 = win32event.WaitForSingleObject(overlapped.hEvent, 60)
                if rc2 == win32event.WAIT_TIMEOUT or rc2 == win32event.WAIT_ABANDONED:
                    break
                elif rc2 == win32event.WAIT_FAILED:
                    log.debug("Error = {}".format(win32.GetLastError()))

                n = win32file.GetOverlappedResult(http_usb_handle, overlapped,
                                                  False)
                log.debug("n data = {}".format(n))
                if n:
                    buffer += data[:n]
                else:
                    # no data to read
                    break
                win32event.ResetEvent(overlapped.hEvent)
            win32file.CancelIo(http_usb_handle)
        finally:
            win32file.CloseHandle(http_usb_handle)
        self.http_usb_handle = self.open()
        return buffer
Esempio n. 29
0
def rthread(*args):
    logger('In rthread')
    win32event.ResetEvent(pymech.query)
    while 1:
        win32event.WaitForSingleObject(pymech.query, win32event.INFINITE)
        logger('after query event')
        #t=time.time()
        # while t+.1 > time.time():
        #     ans=mech.topyacc.CheckReceive()
        #     if not ans:
        #         continue
        # if not ans:
        #     logger('oops, no data')
        #     win32event.ResetEvent(mech.query)
        #     continue
        while 1:
            ans, dta = pymech.pyacc.GetData()
            if ans:
                cmdid, code, hwlen, other = struct.unpack('BBhi', dta[:8])
                if cmdid == 0x81:
                    break
        #ans,dta=mech.topyacc.GetData()
        #cmdid,code,hwlen,other=struct.unpack('BBhi',dta[:8])
        logger('code = %d' % code)
        if code == CMD:
            pymech.RESPONSE = 0
            pass  # only SEND this
        elif code == CMDRESP:
            pymech.RESPONSE = other
            win32event.SetEvent(pymech.cmdresp)
            continue
        elif code == DICTQ:
            handlequery(dta)
        elif code == DICTPUT:
            handleput(dta)
        elif code == DICTRESP:
            pass  # only SEND this
        elif code == DICTPART:
            pass  # only SEND this
        elif (code & 0xf0) == DICTINFO:
            handleinfo(code, dta)
        elif code == QUITTER:
            #????
            return
        else:
            continue
Esempio n. 30
0
File: util.py Progetto: zjp85/QTAF
    def wait(self, timeout=60):
        '''等待消息同步
        '''
        #11/04/01 banana    添加同步窗口消失时的处理
        #11/06/09 pear    在开发运维网退出时受Flash销毁影响会卡QQ,需更改timeout
        #12/11/27 pear    优化代码,WM_TIMER只需要发送一次,剩下的是轮询eventobj的状态
        #12/11/29 pear    tif处理完timer后,这边不需要ResetEvent
        #13/08/12 pear    增加处理QQ进程退出时,窗口已经不存在,不需要同步
        #13/08/12 pear    修改上一个问题的实现方案
        if self._syncwnd == 0:
            return
        win32event.ResetEvent(self._eventobj)

        try:
            win32gui.PostMessage(self._syncwnd, win32con.WM_TIMER, 0, 0)
        except pywintypes.error, e:
            if e[0] == 1400:
                return
            raise e