Created
May 17, 2013 21:41
Arduino serial port monitor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
import serial | |
import time | |
PORT = "/dev/tty.usbmodemfd1121" | |
RECONNECT_SLEEP = 5 | |
MONITOR_SLEEP = 0.2 | |
def enum(*sequential, **named): | |
enums = dict(zip(sequential, range(len(sequential))), **named) | |
return type('Enum', (), enums) | |
states = enum("CONNECTING", "RUNNING") | |
class SerialMonitor(): | |
ser = None | |
state = None | |
def __init__(self, port): | |
self.port = port | |
self.state = states.CONNECTING | |
def connect(self): | |
try: | |
self.ser = serial.Serial(self.port, 9600, timeout=0) | |
self.ser.setRTS(True) | |
self.ser.setDTR(True) | |
except serial.serialutil.SerialException: | |
return False | |
return True | |
def monitor(self): | |
try: | |
data = self.ser.readline() | |
if len(data) > 0: | |
print data.strip() | |
except OSError: | |
print "Disconnected" | |
self.state = states.CONNECTING | |
time.sleep(1) | |
def run(self): | |
self.alive = True | |
try: | |
while self.alive: | |
if self.state == states.CONNECTING: | |
if self.connect(): | |
print "Connected" | |
self.state = states.RUNNING | |
else: | |
print "Failed to connect" | |
time.sleep(RECONNECT_SLEEP) | |
elif self.state == states.RUNNING: | |
self.monitor() | |
time.sleep(MONITOR_SLEEP) | |
except KeyboardInterrupt: | |
self.alive = False | |
finally: | |
if self.ser is not None: | |
self.ser.close() | |
if __name__ == "__main__": | |
sr = SerialMonitor(PORT) | |
sr.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment