def flushOutput(self):
     """Clear output buffer, aborting the current output and
     discarding all that is in the buffer."""
     if not self.hComPort:
         raise portNotOpenError
     win32file.PurgeComm(self.hComPort,
                         win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT)
 def flushInput(self):
     """
     Clear input buffer, discarding all that is in the buffer.
     """
     if not self.hComPort:
         raise portNotOpenError
     win32file.PurgeComm(self.hComPort,
                         win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)
示例#3
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
示例#4
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
        def __init__(self, sDevice, sMode):
            try:
                sDevice = '\\\\.\\' + sDevice
                self._oFd = win32file.CreateFile(
                    sDevice, win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0,
                    None, win32con.OPEN_EXISTING, 0, 0)
            except:
                print('Failed to open COM port ' + sDevice)
                self._oFd = 0
                raise CommException
                return

            tCommTimeouts = (sys.maxsize, 0, 1000, 0, 1000)
            win32file.SetCommTimeouts(self._oFd, tCommTimeouts)
            win32file.PurgeComm(
                self._oFd, win32file.PURGE_TXABORT | win32file.PURGE_RXABORT
                | win32file.PURGE_TXCLEAR | win32file.PURGE_RXCLEAR)
            cCommDeviceBase.__init__(self, sDevice, sMode)
            return
    def close(self):
        """close port"""
        if self.hComPort:
            #Wait until data is transmitted, but not too long... (Timeout-Time)
            #while 1:
            #    flags, comState = win32file.ClearCommError(hComPort)
            #    if comState.cbOutQue <= 0 or calcTimeout(startTime) > timeout:
            #        break

            self.setRTS(0)
            self.setDTR(0)
            #Clear buffers:
            win32file.PurgeComm(self.hComPort,
                                win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT |
                                win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)
            #Restore original timeout values:
            win32file.SetCommTimeouts(self.hComPort, self.orgTimeouts)
            #Close COM-Port:
            win32file.CloseHandle(self.hComPort)
            self.hComPort = None
        def __init__(self, sDevice, sMode):
            oSecurityAttributes = pywintypes.SECURITY_ATTRIBUTES()
            oSecurityAttributes.bInheritHandle = 1
            try:
                sDevice = '\\\\.\\' + sDevice
                self._oFd = win32file.CreateFile(
                    sDevice, win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0,
                    oSecurityAttributes, win32con.OPEN_EXISTING,
                    win32file.FILE_FLAG_OVERLAPPED, 0)
            except:
                print('Failed to open COM port' + sDevice)
                self._oFd = 0
                return

            win32file.SetCommMask(self._oFd, win32file.EV_RXCHAR)
            win32file.SetupComm(self._oFd, 4096, 4096)
            win32file.PurgeComm(
                self._oFd, win32file.PURGE_TXABORT | win32file.PURGE_RXABORT
                | win32file.PURGE_TXCLEAR | win32file.PURGE_RXCLEAR)
            tCommTimeouts = (1000, 2, 2000, 2, 1000)
            win32file.SetCommTimeouts(self._oFd, tCommTimeouts)
            cCommDeviceBase.__init__(self, sDevice, sMode)
示例#8
0
class Serial(serialutil.FileLike):
    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:
            # CSS 20040528 - open wasn't working for COM10 and greater, but by
            # chance the '\\.\COM10' format seems to work, yay!  But, only use
            # if for COM10 and greater in case it introduces some other
            # incompatibility.
            if port < 9:
                self.portstr = 'COM%d' % (
                    port + 1)  #numbers are transformed to a string
            else:
                self.portstr = '\\\\.\\COM%d' % (port + 1)  #WIN NT format??

        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 serialutil.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)

        #Set Windows timeout values
        #timeouts is a tuple with the following items:
        #(ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
        # ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
        # WriteTotalTimeoutConstant)
        if timeout is None:
            timeouts = (0, 0, 0, 0, 0)
        elif timeout == 0:
            timeouts = (win32con.MAXDWORD, 0, 0, 0, 0)
        else:
            #timeouts = (0, 0, 0, 0, 0) #timeouts are done with WaitForSingleObject
            #timeouts = (win32con.MAXDWORD, 0, 0, 0, 1000)   #doesn't works
            #timeouts = (timeout*1000, 0, timeout*1000, 0, 0)
            timeouts = (0, 0, timeout * 1000, 0, timeout * 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)
示例#9
0
 def flushOutput(self):
     if not self.hComPort: raise portNotOpenError
     win32file.PurgeComm(self.hComPort,
                         win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT)
 def mFlush(self):
     if self._oFd:
         win32file.PurgeComm(
             self._oFd,
             win32file.PURGE_TXABORT | win32file.PURGE_RXABORT
             | win32file.PURGE_TXCLEAR | win32file.PURGE_RXCLEAR)
示例#11
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)
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 __del__(self):
    #    self.close()

    def close(self):
        """
        Close port
        """
        if self._isOpen:
            if self.hComPort:
                #Restore original timeout values:
                win32file.SetCommTimeouts(self.hComPort, self._orgTimeouts)
                #Close COM-Port:
                win32file.CloseHandle(self.hComPort)
                self.hComPort = None
            self._isOpen = False

    def flushInput(self):
        """
        Clear input buffer, discarding all that is in the buffer.
        """
        if not self.hComPort:
            raise portNotOpenError
        win32file.PurgeComm(self.hComPort,
                            win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)

    def flushOutput(self):
        """Clear output buffer, aborting the current output and
        discarding all that is in the buffer."""
        if not self.hComPort:
            raise portNotOpenError
        win32file.PurgeComm(self.hComPort,
                            win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT)

    def getCD(self):
        """
        Read terminal status line: Carrier Detect
        """
        if not self.hComPort:
            raise portNotOpenError
        return MS_RLSD_ON & win32file.GetCommModemStatus(self.hComPort) != 0

    def getCTS(self):
        """
        Read terminal status line: Clear To Send
        """
        if not self.hComPort:
            raise portNotOpenError
        return MS_CTS_ON & win32file.GetCommModemStatus(self.hComPort) != 0

    def getDSR(self):
        """
        Read terminal status line: Data Set Ready
        """
        if not self.hComPort:
            raise portNotOpenError
        return MS_DSR_ON & win32file.GetCommModemStatus(self.hComPort) != 0

    def getRI(self):
        """
        Read terminal status line: Ring Indicator
        """
        if not self.hComPort:
            raise portNotOpenError
        return MS_RING_ON & win32file.GetCommModemStatus(self.hComPort) != 0

    def inWaiting(self):
        """
        Return the number of characters currently in the input buffer.
        """
        flags, comstat = win32file.ClearCommError(self.hComPort)
        return comstat.cbInQue

    def makeDeviceName(self, port):
        return device(port)

    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
示例#13
0
def clearcom1receivebuf(comhandle):
    # clear out unwanted data from previous transmissions to com1
    win32file.PurgeComm(comhandle, win32file.PURGE_RXCLEAR)