Browse Source

some more work and lint

kmpm 8 years ago
parent
commit
3864c861bd
13 changed files with 115 additions and 40 deletions
  1. BIN
      lib/__init__.pyc
  2. 9 3
      lib/luacode.py
  3. BIN
      lib/luacode.pyc
  4. 21 15
      lib/main.py
  5. BIN
      lib/main.pyc
  6. 49 0
      lib/term.py
  7. BIN
      lib/term.pyc
  8. 10 15
      lib/uploader.py
  9. BIN
      lib/uploader.pyc
  10. 12 0
      lib/utils.py
  11. BIN
      lib/utils.pyc
  12. 2 1
      run.py
  13. 12 6
      setup.py

BIN
lib/__init__.pyc


+ 9 - 3
lib/luacode.py

@@ -2,6 +2,11 @@
 # -*- coding: utf-8 -*-
 # Copyright (C) 2015-2016 Peter Magnusson <peter@birchroad.net>
 
+
+DOWNLOAD_FILE = "file.open('{filename}') print(file.seek('end', 0)) file.seek('set', {bytes_read}) uart.write(0, file.read({chunk_size}))file.close()"
+
+LIST_FILES = 'for key,value in pairs(file.list()) do print(key,value) end'
+
 SAVE_LUA = \
 r"""
 function recv_block(d)
@@ -13,15 +18,16 @@ function recv_block(d)
     else
       file.close()
       uart.on('data')
-      uart.setup(0,9600,8,0,1,1)
+      uart.setup(0,{baud},8,0,1,1)
     end
   else
     uart.write(0, '\021' .. d)
-    uart.setup(0,9600,8,0,1,1)
+    uart.setup(0,{baud},8,0,1,1)
     uart.on('data')
   end
 end
 function recv_name(d) d = string.gsub(d, '\000', '') file.remove(d) file.open(d, 'w') uart.on('data', 130, recv_block, 0) uart.write(0, '\006') end
-function recv() uart.setup(0,9600,8,0,1,0) uart.on('data', '\000', recv_name, 0) uart.write(0, 'C') end
+function recv() uart.setup(0,{baud},8,0,1,0) uart.on('data', '\000', recv_name, 0) uart.write(0, 'C') end
 function shafile(f) file.open(f, "r") print(crypto.toHex(crypto.hash("sha1",file.read()))) file.close() end
 """
+UART_SETUP = 'uart.setup(0,{baud},8,0,1,1)'

BIN
lib/luacode.pyc


+ 21 - 15
lib/main.py

@@ -6,6 +6,7 @@ import argparse
 import logging
 import os
 from .uploader import Uploader
+from .term import terminal
 
 log = logging.getLogger(__name__)
 
@@ -101,16 +102,6 @@ def main_func():
         'upload',
         help='Path to one or more files to be uploaded. Destination name will be the same as the file name.')
 
-    # upload_parser.add_argument(
-    #         '--filename', '-f',
-    #         help = 'File to upload. You can specify this option multiple times.',
-    #         action='append')
-
-    # upload_parser.add_argument(
-    #         '--destination', '-d',
-    #         help = 'Name to be used when saving in NodeMCU. You should specify one per file.',
-    #         action='append')
-
     upload_parser.add_argument(
         'filename',
         nargs='+',
@@ -166,16 +157,24 @@ def main_func():
         'file',
         help='File functions')
 
-    file_parser.add_argument('cmd', choices=('list', 'do', 'format', 'remove'))
-    file_parser.add_argument('filename', nargs='*', help='Lua file to run.')
+    file_parser.add_argument(
+        'cmd', 
+        choices=('list', 'do', 'format', 'remove'), 
+        help="list=list files, do=dofile given path, format=formate file area, remove=remove given path")
+        
+    file_parser.add_argument('filename', nargs='*', help='path for cmd')
 
     node_parse = subparsers.add_parser(
         'node',
         help='Node functions')
 
-    node_parse.add_argument('ncmd', choices=('heap', 'restart'))
-
+    node_parse.add_argument('ncmd', choices=('heap', 'restart'), help="heap=print heap memory, restart=restart nodemcu")
 
+    terminal_parser = subparsers.add_parser(
+        'terminal', 
+        help='Run pySerials miniterm'
+    )
+    
     args = parser.parse_args()
 
     default_level = logging.INFO
@@ -209,5 +208,12 @@ def main_func():
             uploader.node_heap()
         elif args.ncmd == 'restart':
             uploader.node_restart()
-
+    #no uploader related commands after this point        
     uploader.close()
+    
+    if args.operation == 'terminal':
+        #uploader can not claim the port
+        uploader.close()
+        terminal(args.port)
+
+    

BIN
lib/main.pyc


+ 49 - 0
lib/term.py

@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from .utils import default_port
+try:
+    from serial.tools.miniterm import Miniterm, console, NEWLINE_CONVERISON_MAP
+    MINITERM_AVAILABLE=True
+except ImportError:
+    MINITERM_AVAILABLE=False
+    
+    
+class McuMiniterm(Miniterm):
+    def __init__(self, serial):
+        if not MINITERM_AVAILABLE:
+            print "Miniterm is not available on this system"
+            return 
+        self.serial = serial
+        self.echo = False
+        self.convert_outgoing = 2
+        self.repr_mode = 1
+        self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
+        self.dtr_state = True
+        self.rts_state = True
+        self.break_state = False
+        
+        
+def terminal(port=default_port()):
+    if not MINITERM_AVAILABLE:
+        print "Miniterm is not available on this system"
+        return False
+    sp = serial.Serial(port, 9600)
+
+    # Keeps things working, if following conections are made:
+    ## RTS = CH_PD (i.e reset)
+    ## DTR = GPIO0
+    sp.setRTS(False)
+    sp.setDTR(False)
+    miniterm = MyMiniterm(sp)
+
+    log.info('Started terminal. Hit ctrl-] to leave terminal')
+
+    console.setup()
+    miniterm.start()
+    try:
+            miniterm.join(True)
+    except KeyboardInterrupt:
+            pass
+    miniterm.join()
+    sp.close()

BIN
lib/term.pyc


+ 10 - 15
lib/uploader.py

@@ -6,10 +6,9 @@ import time
 import logging
 import hashlib
 import os
-from platform import system
 import serial
-
-from .luacode import SAVE_LUA
+from .utils import default_port
+from .luacode import SAVE_LUA, LIST_FILES, UART_SETUP
 
 log = logging.getLogger(__name__)
 
@@ -18,11 +17,6 @@ __all__ = ['Uploader', 'default_port']
 CHUNK_END = '\v'
 CHUNK_REPLY = '\v'
 
-def default_port():
-    return {
-        'Windows': 'COM1',
-        'Darwin': '/dev/tty.SLAB_USBtoUART'
-    }.get(system(), '/dev/ttyUSB0')
 
 class Uploader(object):
     BAUD = 9600
@@ -30,6 +24,7 @@ class Uploader(object):
     PORT = default_port()
 
     def __init__(self, port=PORT, baud=BAUD):
+        log.info('opening port %s', port)
         self._port = serial.Serial(port, Uploader.BAUD, timeout=Uploader.TIMEOUT)
 
         # Keeps things working, if following conections are made:
@@ -45,7 +40,7 @@ class Uploader(object):
 
         if baud != Uploader.BAUD:
             log.info('Changing communication to %s baud', baud)
-            self.writeln('uart.setup(0,%s,8,0,1,1)' % baud)
+            self.writeln(UART_SETUP.format(baud=baud))
 
             # Wait for the string to be sent before switching baud
             time.sleep(0.1)
@@ -91,18 +86,18 @@ class Uploader(object):
         self.writeln(output)
         return self.expect()
 
-
-
     def close(self):
-        self.writeln('uart.setup(0,%s,8,0,1,1)' % Uploader.BAUD)
+        self.writeln(UART_SETUP.format(baud=Uploader.BAUD))
         self._port.close()
 
     def prepare(self):
         log.info('Preparing esp for transfer.')
 
-        data = SAVE_LUA.replace('9600', '%d' % self._port.baudrate)
+        data = SAVE_LUA.format(baud=self._port.baudrate)
+        ##change any \r\n to just \n and split on that
         lines = data.replace('\r', '').split('\n')
 
+        #remove some unneccesary spaces to conserve some bytes
         for line in lines:
             line = line.strip().replace(', ', ',').replace(' = ', '=')
 
@@ -120,7 +115,7 @@ class Uploader(object):
         bytes_read = 0
         data = ""
         while True:
-            d = self.exchange("file.open('" + filename + r"') print(file.seek('end', 0)) file.seek('set', %d) uart.write(0, file.read(%d))file.close()" % (bytes_read, chunk_size))
+            d = self.exchange(DOWNLOAD_FILE.format(filename=filename, bytes_read=bytes_read, chunk_size=chunk_size))
             cmd, size, tmp_data = d.split('\n', 2)
             data = data + tmp_data[0:chunk_size]
             bytes_read = bytes_read + chunk_size
@@ -243,7 +238,7 @@ class Uploader(object):
 
     def file_list(self):
         log.info('Listing files')
-        res = self.exchange('for key,value in pairs(file.list()) do print(key,value) end')
+        res = self.exchange(LIST_FILES)
         log.info(res)
         return res
 

BIN
lib/uploader.pyc


+ 12 - 0
lib/utils.py

@@ -0,0 +1,12 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Copyright (C) 2015-2016 Peter Magnusson <peter@birchroad.net>
+
+from platform import system
+
+def default_port():
+    return {
+        'Windows': 'COM1',
+        'Darwin': '/dev/tty.SLAB_USBtoUART'
+    }.get(system(), '/dev/ttyUSB0')
+

BIN
lib/utils.pyc


+ 2 - 1
run.py

@@ -2,4 +2,5 @@ from lib import main
 
 
 if __name__ == '__main__':
-    main.main_func()
+    main.main_func()
+    

+ 12 - 6
setup.py

@@ -1,20 +1,26 @@
-from setuptools import setup, find_packages
+from setuptools import setup
 
 setup(name='nodemcu-uploader',
       version='0.1.3',
       install_requires=[
-          'pyserial==2.7'
+          'pyserial'
       ],
-      packages = ['nodemcu_uploader'],
-      package_dir = {'nodemcu_uploader': 'lib'},
+      packages=['nodemcu_uploader'],
+      package_dir={'nodemcu_uploader': 'lib'},
       url='https://github.com/kmpm/nodemcu-uploader',
       author='kmpm',
       author_email='peter@birchroad.net',
       description='tool for uploading files to the filesystem of an ESP8266 running NodeMCU.',
       keywords=['esp8266', 'upload', 'nodemcu'],
-      entry_points = {
+      classifiers=[
+          'Development Status :: 4 - Beta',
+          'Intended Audience :: Developers',
+          'Programming Language :: Python :: 2.7'
+      ],
+      license='MIT',
+      entry_points={
           'console_scripts': [
               'nodemcu-uploader=nodemcu_uploader.main:main_func'
           ]
       }
-)
+     )