#!/usr/bin/env python
"""Sets up pexpect to test amforth interactively."""

import cmd, serial, time, sys
import fdpexpect

debug = False

def send_line(ffd,line):
    global debug
    # interactive prompt: 'ok\x00\r\n> '
    # compiling prompt: 'ok\x00'
    # error prompt: ' ??\x00 '
    ffd.send(line)
    print "+",
    sys.stdout.flush()
    r = ffd.expect(['ok\x00', 'ok\x00\r\n> ', ' \?\?\x00 ', fdpexpect.TIMEOUT, fdpexpect.EOF])
    if (r == 0 or r == 1):
      pass
      #print ffd.match.group()
    elif r == 2:
      print "ERROR!!"
      print ffd.before
    elif r == 3:
      print "TIMEOUT"
      print ffd.before
    elif r == 4:
      print "done"
    return r


def interactive(ffd):
    """Direct interactive console"""
    # set up pexpect
    ffd.timeout=5
    print "^] to exit interactive"
    ffd.interact()

def ftdiopen(s):
    """Open the serial port, e.g.:\nopen /dev/tty.usbserial-A3000PrP"""
    sp=serial.Serial()
    sp.port = s
    sp.baudrate = 19200
    sp.timeout = 5
    sp.open()
    print 'Opening serial port: %s' % s
    return sp

def start_pexpect(sp):
    ffd=fdpexpect.fdspawn(sp.fd)
    return ffd

def upload(ffd,s):
    """Upload a .frt file"""
    # set up pexpect
    ffd.timeout=5
    # now send file
    f=open(s,'r')
    for line in f:
        if debug: print ("sending: %s" %(line))
        send_line(ffd,line)
    f.close()

def help():
    print 'use sp.write("cold\\n")'
    print 's.readline() or s.read()'


if __name__ == '__main__':
    # automatically open a known device
    sp=ftdiopen('/dev/tty.usbserial-A3000PrP')
    ffd=start_pexpect(sp)



