#   Copyright (c) 2009 Axel Wachtler
#   All rights reserved.
#
#   Redistribution and use in source and binary forms, with or without
#   modification, are permitted provided that the following conditions
#   are met:
#
#   * Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the authors nor the names of its contributors
#     may be used to endorse or promote products derived from this software
#     without specific prior written permission.
#
#   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
#   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#   POSSIBILITY OF SUCH DAMAGE.
# $Id$
"""ROSE - The rocket sensor host client software.

Usage:
    python -i rose.py [OPTIONS] [userscript.py [userscript1.py [...]]]

Options:
    -h show help
    -v show version
    -p name of serial port
"""

# === import ==================================================================
import cStringIO, serial, threading, time, getopt, sys

try:
    import readline, rlcompleter, atexit
    readline.parse_and_bind("tab:complete")
except:
    print "No libreadline support"

# === globals =================================================================
VERSION = "0.9"
SERIAL_PORT = None
SERIAL_IO = None
LAST_DATA = None

# === functions ===============================================================

def start_thread_serial_interface(port, baud=115200):
    global SERIAL_PORT, SERIAL_IO
    SERIAL_PORT = serial.Serial(port, baud)
    SERIAL_PORT.close()
    SERIAL_PORT.open()
    SERIAL_IO = cStringIO.StringIO()
    time.sleep(1)
    rx_thread = threading.Thread(target = __thread_read_serial__)
    rx_thread.setDaemon(1)
    rx_thread.start()

def __thread_read_serial__():
    global SERIAL_PORT, SERIAL_IO
    time.sleep(1)
    x = ''
    while 1:
        x += SERIAL_PORT.read(1)
        n = SERIAL_PORT.inWaiting()
        if n:
            x += SERIAL_PORT.read(n)
        if len(x) > 512:
            SERIAL_IO.write(x)
            x = ''

def io_get():
    SERIAL_IO.flush()
    return SERIAL_IO.getvalue()

def io_reset():
    SERIAL_IO.seek(0,0)
    SERIAL_IO.truncate()

def io_info():
    x = SERIAL_IO.getvalue()
    print "Bytes:",len(x)
    print "Lines:",len(x.split("\n"))

def io_parse(ln):
    d={}
    try:
        for tpl in ln.strip().split(' '):
            k,v = tpl.split('=')
            i = int(v,16)
            if i > 32767: i=i-65536
            d.update({k:i})
    except:
        pass
    return d

def fast_mode(self, mode=1):
    SERIAL_PORT.write(str(mode))

def run(wait=1, mode=1, logfile="dump.txt"):
    global LAST_DATA
    io_reset()
    fast_mode(mode)
    try:
        time.sleep(wait * 60 )
    except KeyboardInterrupt:
        # catch Ctrl-C
        print "Measurement Canceled"
    # safe file
    data = io_get()
    f = open(logfile,"w")
    f.write(data)
    f.close()
    LAST_DATA = [io_parse(x) for x in data.split("\n")]

# === init ====================================================================
if __name__ == "__main__":
    opts, args = getopt.getopt(sys.argv[1:],"hvp:")
    port_name = "/dev/ttyUSB0"
    for o,v in opts:
        if o == "-h":
            print __doc__
        elif o == "-v":
            print sys.argv[0], "version", VERSION
        elif o == "-p":
            port_name = v
        else:
            print "Unknown Option ",o,v

    start_thread_serial_interface(port_name)

    for a in args:
        print "execute file %s" % a
        execfile(a)

#    rose = Rose(port='COM13')
# EOF
