Skip to content

Instantly share code, notes, and snippets.

@noahp
Last active March 23, 2016 12:34
Show Gist options
  • Save noahp/1761fb414cd6fb8e8627 to your computer and use it in GitHub Desktop.
Save noahp/1761fb414cd6fb8e8627 to your computer and use it in GitHub Desktop.
'''
Scans for serial ports, launches putty (default install path) if you pick
one.
'''
try:
from serial.tools import list_ports
except:
print 'Plz install pyserial, "pip install pyserial"'
exit(-1)
try:
import colorama
from colorama import Back, Style
except:
print 'Plz install colorama, "pip install colorama"'
exit(-1)
import time
import sys, os, subprocess
import exceptions
import json
import argparse
class PuttyLauncher(object):
def __init__(self, puttydir, saveBaudsFile):
self.puttydir = puttydir
self.saveBaudsFile = saveBaudsFile
# freshen save file if necessary
if self.saveBaudsFile:
if not os.path.exists(self.saveBaudsFile):
with open(self.saveBaudsFile, 'w') as f:
pass
# get bauds from file
self.bauds = self.loadBauds()
def loadBauds(self):
''' Load bauds from save file. If save file is bad, wipe it. '''
bauds = {}
if self.saveBaudsFile:
with open(self.saveBaudsFile, 'r') as f:
dats = f.read()
if len(dats.strip()):
try:
bauds = json.loads(dats)
except ValueError:
# wipe the file, something's wrong
with open(self.saveBaudsFile, 'w') as f:
pass
return bauds
def storeBauds(self):
''' Save current baud settings (self.bauds) to save file. '''
if self.saveBaudsFile:
# 1. read already saved bauds
rates = self.loadBauds()
# 2. update already saved values with new ones
rates.update(self.bauds)
with open(self.saveBaudsFile, 'w') as f:
f.write(json.dumps(rates, sort_keys=True, indent=4, separators=(',', ': ')))
f.write('\n')
def cls(self):
''' Eww, look at this hack >_< . Utility function to clear screen on refresh. '''
os.system('cls' if os.name=='nt' else 'clear')
def run(self):
# start colorizing terminal text
colorama.init()
try:
while True:
# read saved baud rates
self.bauds = self.loadBauds()
self.cls()
print 'Choose a serial port! ENTER to refresh, ctrl-c to exit'
print '#\tPort\t\tBaud\t\tName'
colors = [
Back.RED,
Back.GREEN,
Back.YELLOW,
Back.BLUE,
Back.MAGENTA,
Back.CYAN,
]
ports = [x for x in list_ports.comports()]
# update baud listing with current ports
for p in ports:
if p[0] not in self.bauds:
self.bauds[p[0]] = 115200
for idx,y in enumerate([x[0] + '\t\t%d\t\t'%(self.bauds[x[0]]) + x[1] for x in ports]):
print colors[idx%len(colors)] + '%d\t'%(idx+1) + y
print Style.RESET_ALL,
try:
choice = raw_input("Choice + ENTER: ")
if not len(choice.strip()):
continue
portnum = int(choice.strip().split()[0])
if portnum > 0 and portnum - 1 < len(ports):
baud = self.bauds[ports[portnum - 1][0]]
if len(choice.strip().split()) > 1:
baud = int(choice.strip().split()[1])
self.bauds[ports[portnum - 1][0]] = baud
cmd = '"%s\\putty.exe" -serial %s -sercfg %d'%(self.puttydir, ports[portnum - 1][0], baud)
# print cmd
# raw_input('pause')
subprocess.Popen(cmd, close_fds=True)
# write new bauds back
self.storeBauds()
except ValueError:
pass
except exceptions.EOFError:
pass
except KeyboardInterrupt:
pass
def getArgs():
argp = argparse.ArgumentParser()
argp.add_argument('-s', default=False, action='store_true', help='Enable storing port settins to file.')
argp.add_argument('-f', default=os.path.splitext(sys.argv[0])[0] + '.savedbauds', metavar='<FILE>',
help='If -s option enabled, save port settings to this file. Default is "%(default)s".')
argp.add_argument('-p', default='C:\\Program Files (x86)\\PuTTY', metavar='<DIR>',
help='Specify PuTTY directory. Default is "%(default)s".')
args = argp.parse_args()
return args
if __name__ == '__main__':
# gimme args
args = getArgs()
# kick off the launcher
p = PuttyLauncher(args.p, args.f if args.s else None)
p.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment