blob: d79187dbe244338c4d99249820ecb24c5945344e [file] [log] [blame]
#!/usr/bin/python -S
# Copyright 2012 Google Inc. All Rights Reserved.
#
"""An extremely basic stty implementation for people who don't have it."""
__author__ = 'apenwarr@google.com (Avery Pennarun)'
import optparse
import os
import pprint
import sys
import termios
import tty
def Usage():
sys.stderr.write('usage: %s [raw|sane|[no]echo|selftest|<baud>|status>\n'
' sets the tty mode\n' % sys.argv[0])
sys.exit(99)
def SetSane(tc):
"""Returns a variant of tc with changes made by 'stty sane'."""
tc = list(tc)
tc[0] &= ~(termios.IGNBRK |
termios.INLCR |
termios.IGNCR |
termios.IXOFF |
termios.IUCLC |
termios.IXANY)
tc[0] |= (termios.BRKINT |
termios.ICRNL |
termios.IMAXBEL |
termios.IXON)
tc[1] &= ~(termios.NLDLY |
termios.CRDLY |
termios.TABDLY |
termios.BSDLY |
termios.VTDLY |
termios.FFDLY |
termios.OLCUC |
termios.OCRNL |
termios.ONOCR |
termios.ONLRET |
termios.OFILL |
termios.OFDEL)
tc[1] |= (termios.NL0 |
termios.CR0 |
termios.TAB0 |
termios.BS0 |
termios.VT0 |
termios.FF0 |
termios.OPOST |
termios.ONLCR)
tc[2] &= ~(0)
tc[2] |= (termios.CREAD)
tc[3] &= ~(termios.ECHONL |
termios.NOFLSH |
termios.XCASE |
termios.TOSTOP |
termios.ECHOPRT)
tc[3] |= (termios.ICANON |
termios.ISIG |
termios.ECHO |
termios.ECHOE |
termios.ECHOK |
termios.ECHOCTL |
termios.ECHOKE)
return tc
# lifted from /usr/include/asm-generic/termbits.h:
baud_map = {
'1200': 0000011,
'2400': 0000013,
'4800': 0000014,
'9600': 0000015,
'19200': 0000016,
'38400': 0000017,
'57600': 0010001,
'115200': 0010002,
}
def main():
parser = optparse.OptionParser()
parser.add_option("-F" , "--file", dest="DEVICE")
(options, args) = parser.parse_args()
if len(args) != 1:
Usage()
fd = 0
if options.DEVICE:
fd = os.open(options.DEVICE, os.O_RDWR)
if args[0] == 'raw':
tty.setraw(0)
elif args[0] == 'sane':
tc = termios.tcgetattr(fd)
tc = SetSane(tc)
termios.tcsetattr(fd, termios.TCSADRAIN, tc)
elif args[0] == 'echo':
tc = termios.tcgetattr(fd)
tc[3] |= termios.ECHO
termios.tcsetattr(fd, termios.TCSADRAIN, tc)
elif args[0] == 'noecho':
tc = termios.tcgetattr(fd)
tc[3] &= ~termios.ECHO
termios.tcsetattr(fd, termios.TCSADRAIN, tc)
elif args[0] == 'selftest':
os.system('stty sane')
tc_orig = termios.tcgetattr(fd)
tty.setraw(fd)
tc_raw = termios.tcgetattr(fd)
tc_sane = SetSane(tc_raw)
termios.tcsetattr(fd, termios.TCSANOW, tc_orig)
print 'orig: %r' % [oct(i) for i in tc_orig[:4]]
print 'sane: %r' % [oct(i) for i in tc_sane[:4]]
print 'raw: %r' % [oct(i) for i in tc_raw[:4]]
assert tc_orig != tc_raw
assert tc_raw != tc_sane
tc_orig[0] |= termios.IXON
tc_orig[3] &= 0xfff
tc_sane[3] &= 0xfff
assert tc_orig[:4] == tc_sane[:4]
elif baud_map.get(args[0]):
tc = termios.tcgetattr(fd)
tc[4] = tc[5] = baud_map[args[0]]
termios.tcsetattr(fd, termios.TCSADRAIN, tc)
elif args[0] == 'status':
tc = termios.tcgetattr(fd)
pprint.pprint(tc)
else:
Usage()
if __name__ == '__main__':
main()