Source

ExerciseTracker / et.py

Full commit
import curses
from db.Local import Local
from sensors.SensorTag import SensorTag

###########
## SETUP ##
###########
screen = curses.initscr()
display = True

######################
## HELPER FUNCTIONS ##
######################
def setup():
    curses.noecho()
    screen.keypad(1)
    screen.border(0)

def refresh():
    screen.refresh()

def display(message,y=2,x=2):
    screen.addstr(y, x, message) 
    refresh()

def cleanup(handle=""):
    curses.nocbreak()
    screen.keypad(0)
    curses.echo()
    curses.endwin()
    if handle:
        handle.disable()

def enable():
    data = SensorTag()
    error = data.get_error()
    if error != "":
        print error
        cleanup()
        exit(-1) 
    data.connect()
    data.enable()
    home("Logging data. Press q to stop.")
    return data


def print_banner(message):
    height, width = screen.getmaxyx()
    center_width = width/2 - (len(message))/2
    center_width = int(center_width)
    if center_width < 0:
        center_width = 0
    display(message,0,center_width)

def home(update_message=""):
    screen.clear()
    screen.border(0)
    print_banner("Cleveland State University Exercise Tutor")
    display("")
    display("Please select from the following options: ")
    display("e - Enable Sensor(s)",4,4)
    display("",5,4)
    display("a - Administrative Options",6,4)
    display("q - Quit",7,4)
    display("",8,4)
    display("Selection: ",9,4)

    if update_message != "":
        display(update_message,13,4)

    option = screen.getch()
    handle = ""
    if option == ord('e'): 
        handle = enable() 
    elif option == ord('a'):
        admin()
    elif option == ord('q'): 
        cleanup(handle)
        exit()

def admin(update_message=""):
    screen.clear()
    screen.border(0)
    print_banner("Administrative Menu")
    display("")
    display("Please select from the following options: ")
    display("0 - Setup Database",4,4)
    display("",5,4)
    display("b - Previous Menu",6,4)
    display("",7,4)
    display("Selection: ",8,4)

    if update_message != "":
        display(update_message,13,4)
    
    option = screen.getch()
    if option == ord('0'): 
        try:
            with open("db/et.db"):
                admin("Database already exists. Press ENTER")
        except IOError:
            database = Local()
            database.init()
            admin("Database setup complete! Press ENTER")
    elif option == ord('b'):
        home()

################
## MAIN BLOCK ##
################
setup()
while display:
    home()