Problem with open()

Andrew M. Kuchling akuchlin at mems-exchange.org
Tue Dec 28 15:41:34 EST 1999


ckrohn at my-deja.com writes:
>   modem = open('/dev/ttyS1', 'w+')
>   print "Modem opened!"

I'd be really suspicious of using Python file objects to control a
serial port connection, because they're built on top of the C
library's FILE objects, which perform I/O buffering.  Try disabling
the buffering with open('/dev/ttyS1', 'w+', 0), or try the following
class (hard-wired to 9600 baud, 8N1).  Sample code would look something
like this:

p = SerialPort('/dev/ttyS1')
p.write('ATDT 5554543\n')
while 1:
    c = p.read(1)
    print repr(c),
    if c == '\n': break
p.close()

-- 
A.M. Kuchling			http://starship.python.net/crew/amk/
The world is governed more by appearances than realities, so that it is fully
as necessary to seem to know something as to know it.
    -- Daniel Webster


import os, termios
import FCNTL, TERMIOS

class SerialPort:
    """Basic serial port class.

    This simply encapsulates a file descriptor for the desired serial port. 
    """

    def __init__(self, dev):
        fd = self.fd = os.open(dev, FCNTL.O_RDWR)
	
	# Save the current state of the serial port
	self.original_state = termios.tcgetattr(fd)
        
	# Set connection parameters to 9600 baud, 8N1, two stop bits
	L = termios.tcgetattr(fd)
	iflag, oflag, cflag, lflag, ispeed, ospeed, chars = L
	ispeed = ospeed = TERMIOS.B9600
 	cflag = (cflag & ~TERMIOS.CSIZE) | TERMIOS.CS8 | TERMIOS.CSTOPB
	cflag = (cflag | TERMIOS.CLOCAL | TERMIOS.CREAD) & ~TERMIOS.CRTSCTS
	iflag = TERMIOS.IGNBRK
	lflag = 0
	oflag = 0
	chars[ TERMIOS.VMIN ] = 1
	chars[ TERMIOS.VTIME ] = 5
	iflag = iflag & ~(TERMIOS.IXON | TERMIOS.IXOFF | TERMIOS.IXANY)
	cflag = cflag & ~(TERMIOS.PARENB | TERMIOS.PARODD)
	L = [iflag, oflag, cflag, lflag, ispeed, ospeed, chars]
	termios.tcsetattr(fd, TERMIOS.TCSANOW, L)

    def write(self, string):
        "Write a string to the port"
	os.write(self.fd, string)
    def read(self, N=1):
        "Read a string from the port"
	return os.read(self.fd, N)
	
    def close(self):
	"Restore the port to its starting state and close the file descriptor."
	termios.tcsetattr(self.fd, TERMIOS.TCSANOW, self.original_state)
        if self.fd is None: return
	os.close( self.fd )
	self.fd = None



More information about the Python-list mailing list