def __init__(self, sDevice, aMode):
     oDCB = win32file.GetCommState(self._oFd)
     dParity = {
         'N': win32file.NOPARITY,
         'E': win32file.EVENPARITY,
         'O': win32file.ODDPARITY
     }
     dStop = {1: win32file.ONESTOPBIT, 2: win32file.TWOSTOPBITS}
     oDCB.BaudRate = aMode[0]
     oDCB.Parity = dParity[aMode[1]]
     oDCB.ByteSize = aMode[2]
     oDCB.StopBits = dStop[aMode[3]]
     oDCB.fBinary = 1
     oDCB.fParity = 1
     oDCB.fOutxCtsFlow = 0
     oDCB.fOutxDsrFlow = 0
     oDCB.fDtrControl = win32file.DTR_CONTROL_DISABLE
     oDCB.fDsrSensitivity = 0
     oDCB.fTXContinueOnXoff = 0
     oDCB.fOutX = 0
     oDCB.fInX = 0
     oDCB.fErrorChar = 0
     oDCB.fNull = 0
     oDCB.fRtsControl = win32file.RTS_CONTROL_ENABLE
     oDCB.fAbortOnError = 0
     win32file.SetCommState(self._oFd, oDCB)
     self.RxTimeOut = 1000
     self.TxTimeOut = 1000
    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
Beispiel #3
0
 def setBaudrate(self, baudrate):
     """change baudrate after port is open"""
     if not self.hComPort: raise portNotOpenError
     # Setup the connection info.
     # Get state and modify it:
     comDCB = win32file.GetCommState(self.hComPort)
     comDCB.BaudRate = baudrate
     win32file.SetCommState(self.hComPort, comDCB)
Beispiel #4
0
 def setDTR(self,level=1):
     if not self.hComPort: raise portNotOpenError
     comDCB = win32file.GetCommState(self.hComPort)
     if level:
         comDCB.fDtrControl = win32file.DTR_CONTROL_ENABLE;
     else:
         comDCB.fDtrControl = win32file.DTR_CONTROL_DISABLE;
     win32file.SetCommState(self.hComPort, comDCB)
Beispiel #5
0
 def setRTS(self,level=1):
     """set terminal status line"""
     if not self.hComPort: raise portNotOpenError
     comDCB = win32file.GetCommState(self.hComPort)
     if level:
         comDCB.fRtsControl = win32file.RTS_CONTROL_ENABLE;
     else:
         comDCB.fRtsControl = win32file.RTS_CONTROL_DISABLE;
     win32file.SetCommState(self.hComPort, comDCB)
    def applyCharFormat(self):
        # Setup the connection info.
        # Get state and modify it:
        comDCB = win32file.GetCommState(self.hComPort)
        # comDCB.BaudRate = 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

        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

        if self.stopbits == STOPBITS_ONE:
            comDCB.StopBits = win32file.ONESTOPBIT
        elif self.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 self.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     = self.rtscts
        #comDCB.fOutxDsrFlow     = self.rtscts
        #comDCB.fOutX            = self.xonxoff
        #comDCB.fInX             = self.xonxoff
        #comDCB.fNull            = 0
        #comDCB.fErrorChar       = 0
        #comDCB.fAbortOnError    = 0

        win32file.SetCommState(self.hComPort, comDCB)
Beispiel #7
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)
Beispiel #8
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 SetBaudrate(self, Baudrate):
     oDCB = win32file.GetCommState(self._oFd)
     oDCB.BaudRate = Baudrate
     win32file.SetCommState(self._oFd, oDCB)
 def mEnableRTS(self):
     oDCB = win32file.GetCommState(self._oFd)
     oDCB.fRtsControl = win32file.RTS_CONTROL_ENABLE
     win32file.SetCommState(self._oFd, oDCB)
Beispiel #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)