aboutsummaryrefslogtreecommitdiff
path: root/forth/ff-shell.py
blob: 2e2018b8e12f8d740988fae419ef1dcab2d89753 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/python
#
# Upload & interpreter shell for FlashForth.
# Written for python 2.7
#
# Copyright 25.01.2015 Mikael Nordman (oh2aun@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import os
import sys
import argparse
import serial
import readline
import rlcompleter
import atexit
import logging
import signal
import string
from thread import start_new_thread, allocate_lock
from time import *

# Threading stuff, global flags
running = True
RECVR_STARTED = False
THR_LOCK = allocate_lock()
waitForNL = 0
uploadMode = 0

class Config(object):
  def __init__(self):
    self.serial_port  = '/dev/ttyACM0'
    self.rate = '38400'
    self.hw = False
    self.sw = False

def serial_open(config):
  print "Port:"+config.port+" Speed:"+config.rate+" hw:"+str(config.hw)+" sw:"+str(config.sw)
  try:
    config.ser = serial.Serial(config.port, config.rate, timeout=0.1, writeTimeout=1.0, rtscts=config.hw, xonxoff=config.sw)
  except serial.SerialException as e:
    print("Could not open serial port '{}': {}".format(com_port, e))
    raise e
  

# receive_thr() receives chars from FlashForth
def receive_thr(config, *args):
  global RECVR_STARTED, running, waitForNL, uploadMode
  RECVR_STARTED = True
  while running==True:
    try:
      while config.ser.inWaiting() > 0:
        try:
          THR_LOCK.acquire()
          char = config.ser.read()
          sys.stdout.write(char)
          sys.stdout.flush()
          if char == '\n':
            waitForNL = 0
          THR_LOCK.release()
        except Exception as e:
          THR_LOCK.release()
          running = True
          # print "Receive thread exception {0}".format(e)

    except Exception as e:
      print "Serial exception {0}".format(e)
      RECVR_STARTED = False
      running = False
      os.kill(os.getpid(), signal.SIGINT)      

  print "End of receive thread"
  RECVR_STARTED = False
  running = False

def parse_arg(config):
  parser = argparse.ArgumentParser(description="Small shell for FlashForth", 
           epilog="""Interact with FlashForth using commmand line editing and history. Send files to FlashForth with #send path/filename. Warm start with #warm.""")
  parser.add_argument("--port", "-p", action="store",
         type=str, default="/dev/cu.Elegoo-DevB", help="Serial port name")
  parser.add_argument("--hw", action="store_true",
         default=False, help="Serial port RTS/CTS enable")
  parser.add_argument("--sw", action="store_true",
         default=False, help="Serial port XON/XOFF enable")
  parser.add_argument("--speed", "-s", action="store",
         type=str, default=38400, help="Serial port speed")
  arg = parser.parse_args()
  config.port = arg.port
  config.hw = arg.hw
  config.sw = arg.sw
  config.rate = arg.speed

#main loop for sending and receiving
def main():
  global running, waitForNL, uploadMode
  
  config = Config() 
  parse_arg(config)
  serial_open(config)
  start_new_thread(receive_thr, (config, 1))
  # Wait for the thread to start
  while not RECVR_STARTED:
    pass
  # 
  # readline.parse_and_bind("tab: complete")
  histfn = os.path.join(os.path.expanduser("~"), ".ff.history")
  print histfn
  try:
    readline.read_history_file(histfn)
  except IOError, e:
    pass
  atexit.register(readline.write_history_file, histfn)
  running = True
  waitForNL = 0
  uploadMode = 0
  while running:
    try:
      if uploadMode == 0:
        try:
          line = raw_input()
        except KeyboardInterrupt:
          print "KeyboardInterrupt"
          raise Exception
        sys.stdout.write('\r\033\133\101')
        sys.stdout.flush()
      else:
        while waitForNL > 0:
          sleep(0.04)
          waitForNL = waitForNL - 1
          pass
        line = file.readline()
        if line == "":
          file.close()
          uploadMode = 0
          waitForNL = 0
          pass
        else:
          line = line.rstrip('\n')
          line = line.rstrip('\r')
          sys.stdout.write("> ")
 
      if line[:6] == "#send ":
        pathfile = line[6:]

        if pathfile.endswith(".txt") == False:
          pathfile = pathfile + ".txt"
        line = ""
        try:
          file = open(pathfile, "r")
          uploadMode = 1
        except IOError, e:
          print "\nFile not found: "+pathfile
      if line[:5] == "#warm":
        line = '\017'           # CTRL-O
      if line[:5] == "#esc":
        line = '\033'           # CTRL-O
      THR_LOCK.acquire()
      try:
        waitForNL = 10
        bytes = config.ser.write(line+'\n')
        config.ser.flush()       # Send the output buffer
      except Exception as e:
        THR_LOCK.release()
        print("Write error on serial port {0}, {1}".format(com_port, e))
        running = False
      THR_LOCK.release()

    except Exception as e:
      print "Transmission thread exception {0}".format(e) 
      running = False

  while RECVR_STARTED:
    pass
  config.ser.close()
  print "Exiting ff-shell.py, goodbye..."

try:
  sys.exit(main())
except Exception as e:
  print "sys.exit {0}".format(e)