Jack Jansen | 0e4033a | 1998-02-25 15:43:57 +0000 | [diff] [blame] | 1 | # |
| 2 | # mactty module - Use a terminal line as communications channel. |
| 3 | # |
| 4 | # Note that this module is not very complete or well-designed, but it |
| 5 | # will have to serve until I have time to write something better. A unix |
| 6 | # module with the same API is available too, contact me (jack@cwi.nl) |
| 7 | # if you need it. |
| 8 | # |
| 9 | # Usage: |
| 10 | # t = Tty(toolname) |
| 11 | # t.raw() Set in raw/no-echo mode |
| 12 | # t.baudrate(rate) Set baud rate |
| 13 | # t.reset() Back to normal |
| 14 | # t.read(len) Read up to 'len' bytes (but often reads less) |
| 15 | # t.readall(len) Read 'len' bytes |
| 16 | # t.timedread(len,tout) Read upto 'len' bytes, or until 'tout' seconds idle |
| 17 | # t.getmode() Get parameters as a string |
| 18 | # t.setmode(args) Set parameters |
| 19 | # |
| 20 | # Jack Jansen, CWI, January 1997 |
| 21 | # |
| 22 | import ctb |
| 23 | DEBUG=1 |
| 24 | |
| 25 | class Tty: |
| 26 | def __init__(self, name=None): |
| 27 | self.connection = ctb.CMNew('Serial Tool', (10000, 10000, 0, 0, 0, 0)) |
| 28 | #self.orig_data = self.connection.GetConfig() |
| 29 | #if name: |
| 30 | # self.connection.SetConfig(self.orig_data + ' Port "%s"'%name) |
| 31 | self.connection.Open(10) |
| 32 | sizes, status = self.connection.Status() |
| 33 | |
| 34 | def getmode(self): |
| 35 | return self.connection.GetConfig() |
| 36 | |
| 37 | def setmode(self, mode): |
| 38 | length = self.connection.SetConfig(mode) |
| 39 | if length != 0 and length != len(mode): |
| 40 | raise 'SetConfig Error', (mode[:length], mode[length:]) |
| 41 | |
| 42 | def raw(self): |
| 43 | pass |
| 44 | |
| 45 | def baudrate(self, rate): |
| 46 | self.setmode(self.getmode()+' baud %d'%rate) |
| 47 | |
| 48 | def reset(self): |
| 49 | self.setmode(self.orig_data) |
| 50 | |
| 51 | def readall(self, length): |
| 52 | data = '' |
| 53 | while len(data) < length: |
| 54 | data = data + self.read(length-len(data)) |
| 55 | return data |
| 56 | |
| 57 | def timedread(self,length, timeout): |
| 58 | self.connection.Idle() |
| 59 | data, eom = self.connection.Read(length, ctb.cmData, timeout*10) |
| 60 | if DEBUG: |
| 61 | print 'Timedread(%d, %d)->%s'%(length, timeout, `data`) |
| 62 | return data |
| 63 | |
| 64 | def read(self, length): |
| 65 | return self.timedread(length, 0x3fffffff) |
| 66 | |
| 67 | def write(self, data): |
| 68 | if DEBUG: |
| 69 | print 'Write(%s)'%`data` |
| 70 | while data: |
| 71 | self.connection.Idle() |
| 72 | done = self.connection.Write(data, ctb.cmData, 0x3fffffff, 0) |
| 73 | self.connection.Idle() |
| 74 | data = data[done:] |