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
Exemple #2
0
 def close(self):
     """close port"""
     if self.hComPort:
         #Restore original timeout values:
         win32file.SetCommTimeouts(self.hComPort, self.orgTimeouts)
         #Close COM-Port:
         win32file.CloseHandle(self.hComPort)
         self.hComPort = None
Exemple #3
0
 def _reconfigureTimeout(self):
     if self._timeout is None:
         timeouts = (0, 0, 0, 0, 0)
     elif self._timeout == 0:
         timeouts = (win32con.MAXDWORD, 0, 0, 0, 0)
     else:
         timeouts = (0, 0, int(self._timeout * 1000), 0, 0)
     if self._writeTimeout is None:
         pass
     elif self._writeTimeout == 0:
         timeouts = timeouts[:-2] + (0, win32con.MAXDWORD)
     else:
         timeouts = timeouts[:-2] + (0, int(self._writeTimeout * 1000))
     win32file.SetCommTimeouts(self.hComPort, timeouts)
 def sendbyte(self, byte, WRtimeout):
     """write string to serial port"""
     if not self.hComPort: raise portNotOpenError
     timeouts = (0, 0, 0, 0, int(WRtimeout * 100)
                 )  # timeouts in 100 ms units...
     win32file.SetCommTimeouts(self.hComPort, timeouts)
     err, n = win32file.WriteFile(self.hComPort, byte,
                                  self._overlappedWrite)
     if err == 0:  #will be ERROR_IO_PENDING:
         # Wait for the write to complete? Or give up and return error?
         # win32event.WaitForSingleObject(self._overlappedWrite.hEvent, win32event.INFINITE)
         return -1
     else:
         return 1
Exemple #5
0
 def close(self):
     """Close port"""
     if self._isOpen:
         if self.hComPort:
             try:
                 # Restore original timeout values:
                 win32file.SetCommTimeouts(self.hComPort, self._orgTimeouts)
             except win32file.error:
                 # ignore errors. can happen for unplugged USB serial devices
                 pass
             # Close COM-Port:
             win32file.CloseHandle(self.hComPort)
             win32file.CloseHandle(self._overlappedRead.hEvent)
             win32file.CloseHandle(self._overlappedWrite.hEvent)
             self.hComPort = None
         self._isOpen = False
    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)

                # Bugfix: #1520357. Close event handles.
                win32file.CloseHandle(self._overlappedRead.hEvent)
                win32file.CloseHandle(self._overlappedWrite.hEvent)
                # End bugfix #1520357.

                self.hComPort = None
            self._isOpen = False
        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 readbyte(self):
        """read a byte from serial port what's in it..."""
        if not self.hComPort: raise portNotOpenError
        timeouts = (win32con.MAXDWORD, 0, 0, 0, 0)
        win32file.SetCommTimeouts(self.hComPort, timeouts)

        win32event.ResetEvent(self._overlappedRead.hEvent)
        flags, comstat = win32file.ClearCommError(self.hComPort)
        n = comstat.cbInQue
        if n > 0:
            rc, buf = win32file.ReadFile(self.hComPort,
                                         win32file.AllocateReadBuffer(1),
                                         self._overlappedRead)
            win32event.WaitForSingleObject(self._overlappedRead.hEvent,
                                           win32event.INFINITE)
            read = buf[0]
        else:
            read = -1
        return read
    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)
Exemple #11
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)
Exemple #12
0
    def _reconfigurePort(self):
        """Set communication parameters on opened port."""
        if not self.hComPort:
            raise SerialException("Can only operate on a valid port handle")
        
        #Set Windows timeout values
        #timeouts is a tuple with the following items:
        #(ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
        # ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
        # WriteTotalTimeoutConstant)
        if self._timeout is None:
            timeouts = (0, 0, 0, 0, 0)
        elif self._timeout == 0:
            timeouts = (win32con.MAXDWORD, 0, 0, 0, 0)
        else:
            timeouts = (0, 0, int(self._timeout*1000), 0, 0)
        if self._timeout != 0 and self._interCharTimeout is not None:
            timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
            
        if self._writeTimeout is None:
            pass
        elif self._writeTimeout == 0:
            timeouts = timeouts[:-2] + (0, win32con.MAXDWORD)
        else:
            timeouts = timeouts[:-2] + (0, int(self._writeTimeout*1000))
        win32file.SetCommTimeouts(self.hComPort, timeouts)

        win32file.SetCommMask(self.hComPort, win32file.EV_ERR)

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

        if self._bytesize == FIVEBITS:
            comDCB.ByteSize     = 5
        elif self._bytesize == SIXBITS:
            comDCB.ByteSize     = 6
        elif self._bytesize == SEVENBITS:
            comDCB.ByteSize     = 7
        elif self._bytesize == EIGHTBITS:
            comDCB.ByteSize     = 8
        else:
            raise ValueError("Unsupported number of data bits: %r" % self._bytesize)

        if self._parity == PARITY_NONE:
            comDCB.Parity       = win32file.NOPARITY
            comDCB.fParity      = 0 # Dis/Enable Parity Check
        elif self._parity == PARITY_EVEN:
            comDCB.Parity       = win32file.EVENPARITY
            comDCB.fParity      = 1 # Dis/Enable Parity Check
        elif self._parity == PARITY_ODD:
            comDCB.Parity       = win32file.ODDPARITY
            comDCB.fParity      = 1 # Dis/Enable Parity Check
        elif self._parity == PARITY_MARK:
            comDCB.Parity       = win32file.MARKPARITY
            comDCB.fParity      = 1 # Dis/Enable Parity Check
        elif self._parity == PARITY_SPACE:
            comDCB.Parity       = win32file.SPACEPARITY
            comDCB.fParity      = 1 # Dis/Enable Parity Check
        else:
            raise ValueError("Unsupported parity mode: %r" % self._parity)

        if self._stopbits == STOPBITS_ONE:
            comDCB.StopBits     = win32file.ONESTOPBIT
        elif self._stopbits == STOPBITS_TWO:
            comDCB.StopBits     = win32file.TWOSTOPBITS
        else:
            raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
            
        comDCB.fBinary          = 1 # Enable Binary Transmission
        # Char. w/ Parity-Err are replaced with 0xff (if fErrorChar is set to TRUE)
        if self._rtscts:
            comDCB.fRtsControl  = win32file.RTS_CONTROL_HANDSHAKE
        else:
            comDCB.fRtsControl  = self._rtsState
        if self._dsrdtr:
            comDCB.fDtrControl  = win32file.DTR_CONTROL_HANDSHAKE
        else:
            comDCB.fDtrControl  = self._dtrState
        comDCB.fOutxCtsFlow     = self._rtscts
        comDCB.fOutxDsrFlow     = self._dsrdtr
        comDCB.fOutX            = self._xonxoff
        comDCB.fInX             = self._xonxoff
        comDCB.fNull            = 0
        comDCB.fErrorChar       = 0
        comDCB.fAbortOnError    = 0
        comDCB.XonChar          = XON
        comDCB.XoffChar         = XOFF

        try:
            win32file.SetCommState(self.hComPort, comDCB)
        except win32file.error, e:
            raise ValueError("Cannot configure port, some setting was wrong. Original message: %s" % e)
 def mSetCommTimeouts(self, tCommTimeouts):
     win32file.SetCommTimeouts(self._oFd, tCommTimeouts)
Exemple #14
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)