예제 #1
0
    def __init__(self, protocol, deviceNameOrPortNumber, reactor, 
        baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE,
        stopbits = STOPBITS_ONE, xonxoff = 0, rtscts = 0):
        self._serial = self._serialFactory(
            deviceNameOrPortNumber, baudrate=baudrate, bytesize=bytesize,
            parity=parity, stopbits=stopbits, timeout=None,
            xonxoff=xonxoff, rtscts=rtscts)
        self.flushInput()
        self.flushOutput()
        self.reactor = reactor
        self.protocol = protocol
        self.outQueue = []
        self.closed = 0
        self.closedNotifies = 0
        self.writeInProgress = 0

        self.protocol = protocol
        self._overlappedRead = win32file.OVERLAPPED()
        self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
        self._overlappedWrite = win32file.OVERLAPPED()
        self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None)

        self.reactor.addEvent(self._overlappedRead.hEvent, self, 'serialReadEvent')
        self.reactor.addEvent(self._overlappedWrite.hEvent, self, 'serialWriteEvent')

        self.protocol.makeConnection(self)
        self._finishPortSetup()
예제 #2
0
    def open(self):
        """
        Open named-pipe, starts up reading/writing

        :return: a deferred firing when the named pipe is opened
        :rtype: twisted.internet.deferred.Deferred
        """
        self._olapped_io = win32file.OVERLAPPED()
        if 'w' in self.mode:
            self._olapped_io.hEvent = win32event.CreateEvent(
                None, False, False, None)
            self.reactor.addEvent(self._olapped_io.hEvent, self, 'pipeWrite')
        else:
            self._olapped_io.hEvent = win32event.CreateEvent(
                None, True, False, None)
            self.reactor.addEvent(self._olapped_io.hEvent, self, 'pipeRead')

        self._olapped_connect = win32file.OVERLAPPED()
        self._olapped_connect.hEvent = win32event.CreateEvent(
            None, True, False, None)

        self._connect_deferred = defer.Deferred()
        win32pipe.ConnectNamedPipe(self._handle, self._olapped_connect)
        self.reactor.addEvent(self._olapped_connect.hEvent, self, '_connected')
        yield self._connect_deferred
        self.reactor.removeEvent(self._olapped_connect.hEvent)

        if 'r' in self.mode:
            self._read_buffer = win32file.AllocateReadBuffer(8192)
            win32file.ReadFile(self._handle, self._read_buffer,
                               self._olapped_io)
    def __init__(self, protocol, deviceNameOrPortNumber, reactor, 
        baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE,
        stopbits = STOPBITS_ONE, xonxoff = 0, rtscts = 0):
        self._serial = serial.Serial(deviceNameOrPortNumber, baudrate=baudrate,
                                     bytesize=bytesize, parity=parity,
                                     stopbits=stopbits, timeout=None,
                                     xonxoff=xonxoff, rtscts=rtscts)
        self.flushInput()
        self.flushOutput()
        self.reactor = reactor
        self.protocol = protocol
        self.outQueue = []
        self.closed = 0
        self.closedNotifies = 0
        self.writeInProgress = 0
        
        self.protocol = protocol
        self._overlappedRead = win32file.OVERLAPPED()
        self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
        self._overlappedWrite = win32file.OVERLAPPED()
        self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None)
        
        self.reactor.addEvent(self._overlappedRead.hEvent, self, 'serialReadEvent')
        self.reactor.addEvent(self._overlappedWrite.hEvent, self, 'serialWriteEvent')

        self.protocol.makeConnection(self)

        flags, comstat = win32file.ClearCommError(self._serial.hComPort)
        rc, self.read_buf = win32file.ReadFile(self._serial.hComPort,
                                               win32file.AllocateReadBuffer(1),
                                               self._overlappedRead)
예제 #4
0
    def open(self):
        self._olapped_io = win32file.OVERLAPPED()
        if 'w' in self.mode:
            self._olapped_io.hEvent = win32event.CreateEvent(
                None, False, False, None)
            self.reactor.addEvent(self._olapped_io.hEvent, self, 'pipeWrite')
        else:
            self._olapped_io.hEvent = win32event.CreateEvent(
                None, True, False, None)
            self.reactor.addEvent(self._olapped_io.hEvent, self, 'pipeRead')

        self._olapped_connect = win32file.OVERLAPPED()
        self._olapped_connect.hEvent = win32event.CreateEvent(
            None, True, False, None)

        self._connect_deferred = defer.Deferred()
        win32pipe.ConnectNamedPipe(self._handle, self._olapped_connect)
        self.reactor.addEvent(self._olapped_connect.hEvent, self, '_connected')
        yield self._connect_deferred
        self.reactor.removeEvent(self._olapped_connect.hEvent)

        if 'r' in self.mode:
            self._read_buffer = win32file.AllocateReadBuffer(8192)
            win32file.ReadFile(self._handle, self._read_buffer,
                               self._olapped_io)
예제 #5
0
class Serial(SerialBase):
    """Serial port implemenation for Win32. This implemenatation requires a 
       win32all installation."""

    BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
                 9600, 19200, 38400, 57600, 115200)

    def open(self):
        """Open port with current settings. This may throw a SerialException
           if the port cannot be opened."""
        if self._port is None:
            raise SerialException(
                "Port must be configured before it can be used.")
        self.hComPort = None
        # the "\\.\COMx" format is required for devices other than COM1-COM8
        # not all versions of windows seem to support this properly
        # so that the first few ports are used with the DOS device name
        port = self.portstr
        if port.upper().startswith('COM') and int(port[3:]) > 8:
            port = '\\\\.\\' + port
        try:
            self.hComPort = win32file.CreateFile(
                port,
                win32con.GENERIC_READ | win32con.GENERIC_WRITE,
                0,  # exclusive access
                None,  # no security
                win32con.OPEN_EXISTING,
                win32con.FILE_FLAG_OVERLAPPED,
                None)
        except Exception, msg:
            self.hComPort = None  #'cause __del__ is called anyway
            raise SerialException("could not open port %s: %s" %
                                  (self.portstr, msg))
        # Setup a 4k buffer
        win32file.SetupComm(self.hComPort, 4096, 4096)

        #Save original timeout values:
        self._orgTimeouts = win32file.GetCommTimeouts(self.hComPort)

        self._rtsState = win32file.RTS_CONTROL_ENABLE
        self._dtrState = win32file.DTR_CONTROL_ENABLE

        self._reconfigurePort()

        # Clear buffers:
        # Remove anything that was there
        win32file.PurgeComm(
            self.hComPort, win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT
            | win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)

        self._overlappedRead = win32file.OVERLAPPED()
        self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
        self._overlappedWrite = win32file.OVERLAPPED()
        #~ self._overlappedWrite.hEvent = win32event.CreateEvent(None, 1, 0, None)
        self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None)
        self._isOpen = True
예제 #6
0
class Serial(SerialBase):
    """Serial port implemenation for Win32. This implemenatation requires a
       win32all installation."""

    BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
                 9600, 19200, 38400, 57600, 115200)

    def open(self):
        """Open port with current settings. This may throw a SerialException
           if the port cannot be opened."""
        if self._port is None:
            raise SerialException(
                "Port must be configured before it can be used.")
        self.hComPort = None
        try:
            self.hComPort = win32file.CreateFile(
                self.portstr,
                win32con.GENERIC_READ | win32con.GENERIC_WRITE,
                0,  # exclusive access
                None,  # no security
                win32con.OPEN_EXISTING,
                win32con.FILE_ATTRIBUTE_NORMAL | win32con.FILE_FLAG_OVERLAPPED,
                None)
        except Exception, msg:
            self.hComPort = None  #'cause __del__ is called anyway
            raise SerialException("could not open port: %s" % msg)
        # Setup a 4k buffer
        win32file.SetupComm(self.hComPort, 4096, 4096)

        #Save original timeout values:
        self._orgTimeouts = win32file.GetCommTimeouts(self.hComPort)

        self._rtsState = win32file.RTS_CONTROL_ENABLE
        self._dtrState = win32file.RTS_CONTROL_ENABLE

        self._reconfigurePort()

        # Clear buffers:
        # Remove anything that was there
        win32file.PurgeComm(
            self.hComPort, win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT
            | win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)

        self._overlappedRead = win32file.OVERLAPPED()
        self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
        self._overlappedWrite = win32file.OVERLAPPED()
        #~ self._overlappedWrite.hEvent = win32event.CreateEvent(None, 1, 0, None)
        self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None)
        self._isOpen = True
예제 #7
0
    def conn_loop(self):
        self.file_handle = win32file.CreateFile(
            self.ipc_path, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0,
            None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_OVERLAPPED,
            None)
        if self.file_handle == win32file.INVALID_HANDLE_VALUE:
            err = win32api.FormatMessage(win32api.GetLastError())
            logging.error(f"Failed to connect to pipe: {err}")
            self.file_handle = None
            return

        # needed for blocking on read
        overlapped = win32file.OVERLAPPED()
        overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)

        # needed for transactions
        win32pipe.SetNamedPipeHandleState(self.file_handle,
                                          win32pipe.PIPE_READMODE_MESSAGE,
                                          None, None)
        self.is_running = True
        while self.is_running:
            val = self._call(win32file.ReadFile, self.file_handle,
                             self._read_buf, overlapped)
            if not self.is_running:
                break
            err, data = val
            if err != 0 and err != ERROR_IO_PENDING:
                logger.warning(f"Unexpected read result {err}. Quitting.")
                logger.debug(f"data={bytes(data)}")
                self.is_running = False
                break
            if err == ERROR_IO_PENDING:
                err = win32event.WaitForSingleObject(overlapped.hEvent,
                                                     self.read_timeout)

            if err == win32event.WAIT_OBJECT_0:  # data is available
                data = bytes(data)
                line = data[:data.find(b"\n")]
                self.on_line(line)

            while not self.write_queue.empty():
                # first see if mpv sent some data that needs to be read
                data = self._call(self._read_all_data)
                if not self.is_running:
                    break
                if data:
                    self.on_data(data)
                # cancel all remaining reads/writes. Should be benign
                win32file.CancelIo(self.file_handle)

                write_data = self.write_queue.get_nowait()
                data = self._call(self._transact, write_data)
                if not self.is_running:
                    break
                self.on_line(data[:-1])

        self.is_running = False
        self.file_handle.close()
        self.file_handle = None
        logger.debug('Pipe closed.')
예제 #8
0
    def write(self, data):
        overlap = win32file.OVERLAPPED()
        overlap.hEvent = win32event.CreateEvent(None, 0, 0, None)

        err, n = win32file.WriteFile(self.handle, data, overlap)
        if err:
            win32event.WaitForSingleObject(overlap.hEvent, win32event.INFINITE)
예제 #9
0
 def read(self, size=1):
     "read num bytes from serial port"
     if not self.hComPort: raise portNotOpenError
     read = ''
     if size > 0:
         overlapped = win32file.OVERLAPPED()
         overlapped.hEvent = win32event.CreateEvent(None, 1, 0, None)
         if self.timeout == 0:
             flags, comstat = win32file.ClearCommError(self.hComPort)
             n = min(comstat.cbInQue, size)
             if n > 0:
                 rc, buf = win32file.ReadFile(
                     self.hComPort, win32file.AllocateReadBuffer(n),
                     overlapped)
                 win32event.WaitForSingleObject(overlapped.hEvent,
                                                win32event.INFINITE)
                 read = str(buf)
         else:
             flags, comstat = win32file.ClearCommError(self.hComPort)
             rc, buf = win32file.ReadFile(
                 self.hComPort, win32file.AllocateReadBuffer(size),
                 overlapped)
             n = win32file.GetOverlappedResult(self.hComPort, overlapped, 1)
             read = str(buf[:n])
     return read
예제 #10
0
    def readuntil(self, char):
        "read bytes from serial port until char is hit"

        if not self.hComPort: raise portNotOpenError
        print thetime(), "readuntil entered"
        overlapped = win32file.OVERLAPPED()
        overlapped.hEvent = win32event.CreateEvent(None, 1, 0, None)
        dcb = win32file.GetCommState(self.hComPort)
        oldevt = dcb.EvtChar
        dcb.EvtChar = char
        rc = win32file.SetCommState(self.hComPort, dcb)
        print thetime(), "setcommstate returned", rc
        oldmask = win32file.GetCommMask(self.hComPort)
        rc = win32file.SetCommMask(self.hComPort, win32file.EV_RXFLAG)
        print thetime(), "setcommmask returned", rc
        rc, mask = win32file.WaitCommEvent(self.hComPort, overlapped)
        print thetime(), "waitcommevent returned", rc, mask
        rc = win32event.WaitForSingleObject(overlapped.hEvent, 10000)
        print thetime(), "waitforsingleobject returned", rc
        n = win32file.GetOverlappedResult(self.hComPort, overlapped, 0)
        print thetime(), "getoverlappedresult returned", n
        win32file.SetCommMask(self.hComPort, oldmask)
        flags, comstat = win32file.ClearCommError(self.hComPort)
        print thetime(), "clearcommerror", flags, comstat.cbInQue
        rc, buf = win32file.ReadFile(
            self.hComPort, win32file.AllocateReadBuffer(comstat.cbInQue),
            overlapped)
        print thetime(), "readfile retrurned", rc
        n = win32file.GetOverlappedResult(self.hComPort, overlapped, 1)
        print thetime(), "getoverlappedresult returned", n
        read = str(buf[:n])
        return read
예제 #11
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")
예제 #12
0
 def enqueue_recv(self, size):
     overlapped = win32file.OVERLAPPED()
     buf = win32file.AllocateReadBuffer(size)
     rc, _ = win32file.WSARecv(self.fileno(), buf, overlapped, 0)
     self._recv_buffers[overlapped] = buf
     overlapped.object = self.recv_done
     self.keep(overlapped.object)
     self.keep(overlapped)
예제 #13
0
 def write(self, s):
     "write string to serial port"
     if not self.hComPort: raise portNotOpenError
     #print repr(s),
     overlapped = win32file.OVERLAPPED()
     overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
     win32file.WriteFile(self.hComPort, s, overlapped)
     # Wait for the write to complete.
     win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE)
 def Transmit(self, transmitData):
     """
     This will be called to detect available IR Blasters.
     """
     if not self.file:
         return False
     writeOvlap = win32file.OVERLAPPED()
     writeOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
     win32file.WriteFile(self.file, transmitData, writeOvlap)
     win32event.WaitForSingleObject(writeOvlap.hEvent, win32event.INFINITE)
     return True
예제 #15
0
def _get_overlapped_offset():
    global _overlapped_offset
    if _overlapped_offset is not None:
        return _overlapped_offset
    ov = win32file.OVERLAPPED()
    MAGIC = 0xff314159  # use a very high number that couldn't possibly be a pointer
    ov.Internal = MAGIC  # this is the first DWORD of the struct
    raw = struct.pack("L", MAGIC)
    s = ctypes.string_at(id(ov), 40)
    _overlapped_offset = s.find(raw)
    assert _overlapped_offset > 0
    return _overlapped_offset
예제 #16
0
 def Stop(self):
     """
     This will be called to stop the thread.
     """
     if self.file:
         writeOvlap = win32file.OVERLAPPED()
         writeOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
         msg = "q".encode("ascii")
         win32file.WriteFile(self.file, msg, writeOvlap)
         win32file.CloseHandle(self.file)
         self.file = None
     self.keepRunning = False
예제 #17
0
 def TestIR(self):
     """
     This will be called to Transmit a known signal to verify blaster capability.
     """
     if not self.file:
         return None
     writeOvlap = win32file.OVERLAPPED()
     writeOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
     self.deviceTestEvent = win32event.CreateEvent(None, 0, 0, None)
     win32file.WriteFile(self.file, "t".encode("ascii"), writeOvlap)
     if win32event.WaitForSingleObject(self.deviceTestEvent, 250) == win32event.WAIT_OBJECT_0:
         return True
     return None
예제 #18
0
 def GetDeviceInfo(self):
     """
     This will be called to detect IR device info.
     """
     if not self.file:
         return None
     writeOvlap = win32file.OVERLAPPED()
     writeOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
     self.deviceInfoEvent = win32event.CreateEvent(None, 0, 0, None)
     win32file.WriteFile(self.file, "b".encode("ascii"), writeOvlap)
     if win32event.WaitForSingleObject(self.deviceInfoEvent, 250) == win32event.WAIT_OBJECT_0:
         return self.deviceInfo
     return None
예제 #19
0
 def ChangeReceiveMode(self, mode):
     """
     This will be called to detect available IR Blasters.
     """
     if not (mode == "l" or mode == "n"):
         return False  #needs to be normal or learn
     if not self.file:
         return False
     writeOvlap = win32file.OVERLAPPED()
     writeOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
     win32file.WriteFile(self.file, mode, writeOvlap)
     win32event.WaitForSingleObject(writeOvlap.hEvent, win32event.INFINITE)
     return True
예제 #20
0
 def __init__(self, path):
     if not isinstance(path, basestring):
         raise TypeError("Path argument must be a basestring; instead"
                         " received %r" % (path, ))
     self.path = path
     self.handle = win32file.CreateFile(
         self.path,
         0x0001,  # FILE_LIST_DIRECTORY
         win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
         None,
         win32con.OPEN_EXISTING,
         win32con.FILE_FLAG_BACKUP_SEMANTICS
         | win32con.FILE_FLAG_OVERLAPPED,
         None,
     )
     self.overlapped = win32file.OVERLAPPED()
     self.overlapped.hEvent = win32event.CreateEvent(None, True, 0, None)
예제 #21
0
 def __init__(self, deviceName, devicePath, threadName=None):
     self.lockObject = threading.Lock()
     self.lockObject.acquire()
     self.handle = None
     self.text = Text
     self.deviceName = deviceName
     self.devicePath = devicePath
     self.abort = False
     self.initialized = False
     self._overlappedRead = win32file.OVERLAPPED()
     self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
     self._overlappedWrite = None
     self.RawCallback = None
     self.ButtonCallback = None
     self.ValueCallback = None
     self.StopCallback = None
     threading.Thread.__init__(
         self, name=threadName if threadName else self.devicePath)
예제 #22
0
 def enqueue_recv(self, size):
     overlapped = win32file.OVERLAPPED()
     buf = win32file.AllocateReadBuffer(size)
     rc, buf = win32file.WSARecv(self.handle, buf, overlapped, 0)
     self._recv_buffer.append(buf)
     overlapped.object = self
예제 #23
0
 def enqueue_send(self, size):
     overlapped = win32file.OVERLAPPED()
     buf = win32file.AllocateReadBuffer(size)
     rc, buf = win32file.WSASend(self.handle, buf, overlapped, 0)
     overlapped.object = self
예제 #24
0
    def __init__(self, plugin, helper, enduringEvents, noOtherPort, devicePath,
                 vendorID, vendorString, productID, productString,
                 versionNumber, useFirstDevice):
        self.plugin = plugin
        self.text = Text
        self.deviceName = vendorString + " " + productString
        self.abort = False
        self._overlappedRead = win32file.OVERLAPPED()
        self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)

        self.xbcdrc_mapping = {
            '006d50a': 'DISPLAY',
            '0066a05': 'DISPLAY',
            '0066afd': 'DISPLAY',
            '006e20a': 'REVERSE',
            '00671f5': 'REVERSE',
            '006710d': 'REVERSE',
            '006ea0a': 'PLAY',
            '00675f5': 'PLAY',
            '006750d': 'PLAY',
            '006e30a': 'FORWARD',
            '0067105': 'FORWARD',
            '00671fd': 'FORWARD',
            '006dd0a': 'SKIP-',
            '0066e05': 'SKIP-',
            '0066efd': 'SKIP-',
            '006e00a': 'STOP',
            '00670f5': 'STOP',
            '006700d': 'STOP',
            '006e60a': 'PAUSE',
            '00673f5': 'PAUSE',
            '006730d': 'PAUSE',
            '006df0a': 'SKIP+',
            '0066f05': 'SKIP+',
            '0066ffd': 'SKIP+',
            '006e50a': 'TITLE',
            '0067205': 'TITLE',
            '00672fd': 'TITLE',
            '006c30a': 'INFO',
            '0066105': 'INFO',
            '00661fd': 'INFO',
            '006a60a': 'UP',
            '00653f5': 'UP',
            '006530d': 'UP',
            '006a70a': 'DOWN',
            '0065305': 'DOWN',
            '00653fd': 'DOWN',
            '006a90a': 'LEFT',
            '0065405': 'LEFT',
            '00654fd': 'LEFT',
            '006a80a': 'RIGHT',
            '00654f5': 'RIGHT',
            '006540d': 'RIGHT',
            '0060b0a': 'SELECT',
            '0060505': 'SELECT',
            '00605fd': 'SELECT',
            '006f70a': 'MENU',
            '0067b05': 'MENU',
            '0067bfd': 'MENU',
            '006d80a': 'BACK',
            '0066cf5': 'BACK',
            '0066c0d': 'BACK',
            '006ce0a': '1',
            '00667f5': '1',
            '006670d': '1',
            '006cd0a': '2',
            '0066605': '2',
            '00666fd': '2',
            '006cc0a': '3',
            '00666f5': '3',
            '006660d': '3',
            '006cb0a': '4',
            '0066505': '4',
            '00665fd': '4',
            '006ca0a': '5',
            '00665f5': '5',
            '006650d': '5',
            '006c90a': '6',
            '0066405': '6',
            '00664fd': '6',
            '006c80a': '7',
            '00664f5': '7',
            '006640d': '7',
            '006c70a': '8',
            '0066305': '8',
            '00663fd': '8',
            '006c60a': '9',
            '00663f5': '9',
            '006630d': '9',
            '006cf0a': '0',
            '0066705': '0',
            '00667fd': '0',
            '0064f0a': 'AUDIO',
            '006af0a': 'ENT.',
            '006d100': 'LT',
            '006890a': 'LAST',
            '006c000': 'MUTE',
            '006e70a': 'A*B',
            '006f90a': 'EXIT',
            '0067f0a': 'D',
            '0068c0a': 'REC'
        }

        #getting devicePath
        self.devicePath = helper.GetDevicePath(noOtherPort, devicePath,
                                               vendorID, productID,
                                               versionNumber, useFirstDevice)
        plugin.devicePath = self.devicePath

        if not self.devicePath:
            plugin.PrintError(self.text.errorFind)
            self.plugin.status = 2
            return

        threading.Thread.__init__(self, name=self.devicePath)

        #setting members
        self.helper = helper
        self.enduringEvents = enduringEvents
        self.start()
예제 #25
0
    def __init__(self,
                 port,                  #number of device, numbering starts at
                                        #zero. if everything fails, the user
                                        #can specify a device string, note
                                        #that this isn't portable anymore
                 baudrate=9600,         #baudrate
                 bytesize=EIGHTBITS,    #number of databits
                 parity=PARITY_NONE,    #enable parity checking
                 stopbits=STOPBITS_ONE, #number of stopbits
                 timeout=None,          #set a timeout value, None for waiting forever
                 xonxoff=0,             #enable software flow control
                 rtscts=0,              #enable RTS/CTS flow control
                 ):
        """initialize comm port"""

        self.timeout = timeout

        if type(port) == type(''):       #strings are taken directly
            self.portstr = port
        else:
            self.portstr = 'COM%d' % (port+1) #numbers are transformed to a string
            #self.portstr = '\\\\.\\COM%d' % (port+1) #WIN NT format??

        self.hComPort = win32file.CreateFile(self.portstr,
               win32con.GENERIC_READ | win32con.GENERIC_WRITE,
               0, # exclusive access
               None, # no security
               win32con.OPEN_EXISTING,
               win32con.FILE_ATTRIBUTE_NORMAL | win32con.FILE_FLAG_OVERLAPPED,
               None)
        # Setup a 4k buffer
        win32file.SetupComm(self.hComPort, 4096, 4096)

        #Save original timeout values:
        self.orgTimeouts = win32file.GetCommTimeouts(self.hComPort)

        #Set Windows timeout values
        #timeouts is a tuple with the following items:
        #(ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
        # ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
        # WriteTotalTimeoutConstant)
        if timeout:
            timeouts = (timeout*1000, 0, timeout*1000, 0, 0)
        else:
            #timeouts = (win32con.MAXDWORD, 1, 0, 1, 0)
            timeouts = (win32con.MAXDWORD, 0, 0, 0, 1000)
        win32file.SetCommTimeouts(self.hComPort, timeouts)

        #win32file.SetCommMask(self.hComPort, win32file.EV_RXCHAR | win32file.EV_TXEMPTY |
        #    win32file.EV_RXFLAG | win32file.EV_ERR)
        win32file.SetCommMask(self.hComPort,
                win32file.EV_RXCHAR | win32file.EV_RXFLAG | win32file.EV_ERR)
        #win32file.SetCommMask(self.hComPort, win32file.EV_ERR)

        # Setup the connection info.
        # Get state and modify it:
        comDCB = win32file.GetCommState(self.hComPort)
        comDCB.BaudRate = baudrate

        if bytesize == FIVEBITS:
            comDCB.ByteSize     = 5
        elif bytesize == SIXBITS:
            comDCB.ByteSize     = 6
        elif bytesize == SEVENBITS:
            comDCB.ByteSize     = 7
        elif bytesize == EIGHTBITS:
            comDCB.ByteSize     = 8

        if parity == PARITY_NONE:
            comDCB.Parity       = win32file.NOPARITY
            comDCB.fParity      = 0 # Dis/Enable Parity Check
        elif parity == PARITY_EVEN:
            comDCB.Parity       = win32file.EVENPARITY
            comDCB.fParity      = 1 # Dis/Enable Parity Check
        elif parity == PARITY_ODD:
            comDCB.Parity       = win32file.ODDPARITY
            comDCB.fParity      = 1 # Dis/Enable Parity Check

        if stopbits == STOPBITS_ONE:
            comDCB.StopBits     = win32file.ONESTOPBIT
        elif stopbits == STOPBITS_TWO:
            comDCB.StopBits     = win32file.TWOSTOPBITS
        comDCB.fBinary          = 1 # Enable Binary Transmission
        # Char. w/ Parity-Err are replaced with 0xff (if fErrorChar is set to TRUE)
        if rtscts:
            comDCB.fRtsControl  = win32file.RTS_CONTROL_HANDSHAKE
            comDCB.fDtrControl  = win32file.DTR_CONTROL_HANDSHAKE
        else:
            comDCB.fRtsControl  = win32file.RTS_CONTROL_ENABLE
            comDCB.fDtrControl  = win32file.DTR_CONTROL_ENABLE
        comDCB.fOutxCtsFlow     = rtscts
        comDCB.fOutxDsrFlow     = rtscts
        comDCB.fOutX            = xonxoff
        comDCB.fInX             = xonxoff
        comDCB.fNull            = 0
        comDCB.fErrorChar       = 0
        comDCB.fAbortOnError    = 0

        win32file.SetCommState(self.hComPort, comDCB)

        # Clear buffers:
        # Remove anything that was there
        win32file.PurgeComm(self.hComPort,
                            win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT |
                            win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)

        #print win32file.ClearCommError(self.hComPort) #flags, comState =

        self.overlapped = win32file.OVERLAPPED()
        self.overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
예제 #26
0
# Test
#===============================================================================
if __name__ == "__main__":

    print repr(inet_pton(socket.AF_INET, "127.0.0.1"))
    print repr(inet_pton(socket.AF_INET, "localhost"))
    exit()

    import threading
    from iocp import IOCP

    receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    receiver.bind(("0.0.0.0", 12345))

    pyov = win32file.OVERLAPPED()
    port = IOCP()
    port.register(receiver.fileno())
    data, sockaddr, _ = WSARecvFromSocket(receiver, 1000, pyov)

    def tfunc():
        ov2 = win32file.OVERLAPPED()
        WSASendToSocket(sender, "dkfdsfjdsl", ("127.0.0.1", 12345), ov2)

    thd = threading.Thread(target=tfunc)
    thd.start()

    print "waiting for data"
    [(size, _)] = port.get_events(20)
    print "got", repr(data[:size]), "from", sockaddr
예제 #27
0
        else:
            break


def read_win_tun(handle, tun_s_port):

    # Connect to the server
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(('127.0.0.1', tun_s_port))
    except BaseException, exc:
        print str(exc)
        return

    while True:
        overlap = win32file.OVERLAPPED()
        overlap.hEvent = win32event.CreateEvent(None, 1, 0, None)
        read_buf = win32file.AllocateReadBuffer(4096)
        read_bytes = ''

        rc, buf = win32file.ReadFile(handle,
                                     win32file.AllocateReadBuffer(4096),
                                     overlap)
        win32event.WaitForSingleObject(overlap.hEvent, win32event.INFINITE)
        read_cnt = win32file.GetOverlappedResult(handle, overlap, 0)

        #read = str(buf)
        #print "Sending %d bytes" % read_cnt
        s.send(buf[:read_cnt])

예제 #28
0
파일: sockets.py 프로젝트: pombreda/tangled
 def _get_overlapped(self, callback, *args):
     overlapped = win32file.OVERLAPPED()
     overlapped.object = self._handler
     self._overlapped_callbacks[overlapped] = (callback, args)
예제 #29
0
 def HandleData(self):
     """
     This runs once a connection to the named pipe is made.  It receives the ir data and passes it to the plugins IRDecoder.
     """
     #if self.sentMessageOnce:
     #    eg.PrintNotice("MCE_Vista: Connected to MceIr pipe, started handling IR events")
     #    self.plugin.TriggerEvent("Connected")
     nMax = 2048
     self.result = []
     self.freqs = [0]
     self.readOvlap = win32file.OVERLAPPED()
     self.readOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
     handles = [self.plugin.hFinishedEvent, self.readOvlap.hEvent]
     self.timeout = win32event.INFINITE
     while self.keepRunning:
         try:
             (hr, data) = win32file.ReadFile(self.file, nMax,
                                             self.readOvlap)
         except:
             win32file.CloseHandle(self.file)
             self.file = None
             break
         self.receivingTimeout = eg.scheduler.AddTask(
             0.3, self.SetReceiving, False)
         rc = win32event.WaitForMultipleObjects(handles, False,
                                                self.timeout)
         self.SetReceiving(True)
         if rc == win32event.WAIT_OBJECT_0:  #Finished event
             self.keepRunning = False
             break
         elif rc == win32event.WAIT_TIMEOUT:  #Learn timeout
             #eg.PrintNotice("LearnTimeout: Sending ir code %s"%str(self.result))
             self.learnDialog.GotCode(self.freqs, self.result)
             self.result = []
             self.timeout = win32event.INFINITE
             rc = win32event.WaitForMultipleObjects(handles, False,
                                                    self.timeout)
             if rc == win32event.WAIT_OBJECT_0:  #Finished event
                 self.keepRunning = False
                 break
         try:
             nGot = self.readOvlap.InternalHigh
             if nGot == 0:
                 continue
             if nGot % ptr_len == 1:  #Query result, not ir code data
                 if data[0] == "b".encode("ascii"):
                     self.deviceInfo = unpack_from(6 * ptr_fmt,
                                                   data[1:nGot])
                     win32event.SetEvent(self.deviceInfoEvent)
                 elif data[0] == "t".encode("ascii"):
                     win32event.SetEvent(self.deviceTestEvent)
                 continue
             #pull of the header data
             while nGot > 0:
                 header = unpack_from(3 * ptr_fmt, data)
                 if header[0] == 1 and header[2] > 0:
                     self.freqs.append(header[2])
                 dataEnd = nGot
                 if nGot > 100 + 3 * ptr_len:
                     dataEnd = 100 + 3 * ptr_len
                 nGot -= dataEnd
                 val_data = data[3 * ptr_len:dataEnd]
                 dataEnd = dataEnd - 3 * ptr_len
                 vals = unpack_from((dataEnd / 4) * "i", val_data)
                 data = data[100 + 3 * ptr_len:]
                 for i, v in enumerate(vals):
                     a = abs(v)
                     self.result.append(a)
                     if self.learnDialog is None:  #normal mode
                         if a > 6500:  #button held?
                             if self.CodeValid(self.result):
                                 #eg.PrintNotice("Sending ir code %s"%str(self.result))
                                 self.plugin.irDecoder.Decode(
                                     self.result, len(self.result))
                             self.result = []
                 if not self.learnDialog is None:  #learn mode
                     if header[0] == 1:  #one "learn" chunk
                         self.timeout = self.learnTimeout
         except:
             pass
     self.SetReceiving(False)
예제 #30
0
 def tfunc():
     ov2 = win32file.OVERLAPPED()
     WSASendToSocket(sender, "dkfdsfjdsl", ("127.0.0.1", 12345), ov2)