Browse Source

more refining

kmpm 8 years ago
parent
commit
975d1d9d7d
6 changed files with 67 additions and 27 deletions
  1. 12 5
      README.md
  2. 2 1
      lib/__init__.py
  3. 29 10
      lib/main.py
  4. 3 1
      lib/term.py
  5. 20 10
      lib/uploader.py
  6. 1 0
      lib/utils.py

+ 12 - 5
README.md

@@ -18,12 +18,17 @@ Otherwise clone from github and run directly from there
 
     git clone https://github.com/kmpm/nodemcu-uploader
     cd nodemcu-uploader
-    ./run.py
+    python ./run.py
 
-Support
+### Notes for Windows
+This might work with 64 bit Python but is not tested.
+
+
+Issues
 -------
 Create a issue in github, https://github.com/kmpm/nodemcu-uploader/issues
 
+
 Disclaimer
 -----------
 
@@ -38,12 +43,14 @@ SOFTWARE.
 
 Usage (part of it)
 ------------------
---port and --baud are set to default /dev/ttyUSB0 and 9600 respectively.
+* --baud are set at a default of 9600
+* --port is by default __/dev/ttyUSB0__,
+  __/dev/tty.SLAB_USBtoUART__ if on Mac and __COM1__ on Windows
 
 ###Upload
 Uploading a number of files.
 Supports multiple files. If you want an alternate destination name, just
-add a colon ":" and the new destination filename. 
+add a colon ":" and the new destination filename.
 
 ```
 ./nodemcu-uploader.py upload init.lua README.md nodemcu-uploader.py [--compile] [--restart]
@@ -64,7 +71,7 @@ Uploading a number of files and verify successful uploading.
 ###Download
 Downloading a number of files.
 Supports multiple files. If you want an alternate destination name, just
-add a colon ":" and the new destination filename. 
+add a colon ":" and the new destination filename.
 ```
 ./nodemcu-uploader.py download init.lua README.md nodemcu-uploader.py
 ```

+ 2 - 1
lib/__init__.py

@@ -4,4 +4,5 @@
 
 """Library and util for uploading files to NodeMCU version 0.9.4 and later"""
 
-__version__ = '0.1.2'
+from .version import __version__
+from .uploader import Uploader

+ 29 - 10
lib/main.py

@@ -9,8 +9,15 @@ from .uploader import Uploader
 from .term import terminal
 
 log = logging.getLogger(__name__)
+from .version import __version__
 
 def destination_from_source(sources):
+    """
+    Split each of the sources in the array on ':'
+    First part will be source, second will be destination.
+    Modifies the the original array to contain only sources
+    and returns an array of destinations.
+    """
     destinations = []
     for i in range(0, len(sources)):
         sd = sources[i].split(':')
@@ -21,7 +28,9 @@ def destination_from_source(sources):
             destinations.append(sd[0])
     return destinations
 
+
 def operation_upload(uploader, sources, verify, do_compile, do_file, do_restart):
+    """The upload operation"""
     destinations = destination_from_source(sources)
     if len(destinations) == len(sources):
         uploader.prepare()
@@ -43,7 +52,9 @@ def operation_upload(uploader, sources, verify, do_compile, do_file, do_restart)
         uploader.node_restart()
     log.info('All done!')
 
+
 def operation_download(uploader, sources):
+    """The download operation"""
     destinations = destination_from_source(sources)
     if len(destinations) == len(sources):
         for f, d in zip(sources, destinations):
@@ -52,7 +63,9 @@ def operation_download(uploader, sources):
         raise Exception('You must specify a destination filename for each file you want to download.')
     log.info('All done!')
 
+
 def operation_file(uploader, cmd, filename=''):
+    """File operations"""
     if cmd == 'list':
         uploader.file_list()
     if cmd == 'do':
@@ -83,6 +96,13 @@ def main_func():
         action='store_true',
         default=False)
 
+    parser.add_argument(
+        '--version',
+        help='prints the version and exists',
+        action='version',
+        version='%(prog)s {version}'.format(version=__version__)
+    )
+
     parser.add_argument(
         '--port', '-p',
         help='Serial port device',
@@ -131,8 +151,6 @@ def main_func():
         default=False
         )
 
-
-
     upload_parser.add_argument(
         '--restart', '-r',
         help='If esp should be restarted',
@@ -158,10 +176,10 @@ def main_func():
         help='File functions')
 
     file_parser.add_argument(
-        'cmd', 
-        choices=('list', 'do', 'format', 'remove'), 
+        '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(
@@ -171,10 +189,10 @@ def main_func():
     node_parse.add_argument('ncmd', choices=('heap', 'restart'), help="heap=print heap memory, restart=restart nodemcu")
 
     terminal_parser = subparsers.add_parser(
-        'terminal', 
+        'terminal',
         help='Run pySerials miniterm'
     )
-    
+
     args = parser.parse_args()
 
     default_level = logging.INFO
@@ -188,6 +206,7 @@ def main_func():
     uploader = Uploader(args.port, args.baud)
 
 
+
     if args.operation == 'upload':
         operation_upload(uploader, args.filename, args.verify, args.compile, args.dofile,
                          args.restart)
@@ -208,12 +227,12 @@ def main_func():
             uploader.node_heap()
         elif args.ncmd == 'restart':
             uploader.node_restart()
-    #no uploader related commands after this point        
+    #no uploader related commands after this point
     uploader.close()
-    
+
     if args.operation == 'terminal':
         #uploader can not claim the port
         uploader.close()
         terminal(args.port)
 
-    
+

+ 3 - 1
lib/term.py

@@ -4,8 +4,10 @@
 from .utils import default_port
 try:
     from serial.tools.miniterm import Miniterm, console, NEWLINE_CONVERISON_MAP
+    import serial
     MINITERM_AVAILABLE=True
 except ImportError:
+    
     MINITERM_AVAILABLE=False
     
     
@@ -35,7 +37,7 @@ def terminal(port=default_port()):
     ## DTR = GPIO0
     sp.setRTS(False)
     sp.setDTR(False)
-    miniterm = MyMiniterm(sp)
+    miniterm = McuMiniterm(sp)
 
     log.info('Started terminal. Hit ctrl-] to leave terminal')
 

+ 20 - 10
lib/uploader.py

@@ -14,11 +14,11 @@ log = logging.getLogger(__name__)
 
 __all__ = ['Uploader', 'default_port']
 
-CHUNK_END = '\v'
-CHUNK_REPLY = '\v'
-
 
 class Uploader(object):
+    """Uploader is the class for communicating with the nodemcu and
+    that will allow various tasks like uploading files, formating the filesystem etc.
+    """
     BAUD = 9600
     TIMEOUT = 5
     PORT = default_port()
@@ -33,11 +33,13 @@ class Uploader(object):
         self._port.setRTS(False)
         self._port.setDTR(False)
 
-        # Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)
-        self.exchange(';') # Get a defined state
-        self.writeln('print("%sync%");')
-        self.expect('%sync%\r\n> ')
-
+        def sync():
+            # Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)
+            log.debug('getting in sync with LUA');
+            self.exchange(';') # Get a defined state
+            self.writeln('print("%sync%");')
+            self.expect('%sync%\r\n> ')
+        sync()
         if baud != Uploader.BAUD:
             log.info('Changing communication to %s baud', baud)
             self.writeln(UART_SETUP.format(baud=baud))
@@ -47,12 +49,12 @@ class Uploader(object):
             self._port.setBaudrate(baud)
 
             # Get in sync again
-            self.exchange('')
-            self.exchange('')
+            sync()
 
         self.line_number = 0
 
     def expect(self, exp='> ', timeout=TIMEOUT):
+        """will wait for exp to be returned from nodemcu or timeout"""
         timer = self._port.timeout
 
         # Checking for new data every 100us is fast enough
@@ -72,6 +74,8 @@ class Uploader(object):
         return data
 
     def write(self, output, binary=False):
+        """write data on the nodemcu port. If 'binary' is True the debug log
+        will show the intended output as hex, otherwise as string"""
         if not binary:
             log.debug('write: %s', output)
         else:
@@ -80,6 +84,7 @@ class Uploader(object):
         self._port.flush()
 
     def writeln(self, output):
+        """write, with linefeed"""
         self.write(output + '\n')
 
     def exchange(self, output):
@@ -87,10 +92,15 @@ class Uploader(object):
         return self.expect()
 
     def close(self):
+        """restores the nodemcu to default baudrate and then closes the port"""
         self.writeln(UART_SETUP.format(baud=Uploader.BAUD))
         self._port.close()
 
     def prepare(self):
+        """
+        This uploads the protocol functions nessecary to do binary
+        chunked transfer
+        """
         log.info('Preparing esp for transfer.')
 
         data = SAVE_LUA.format(baud=self._port.baudrate)

+ 1 - 0
lib/utils.py

@@ -5,6 +5,7 @@
 from platform import system
 
 def default_port():
+    """This returns the default port used for different systems"""
     return {
         'Windows': 'COM1',
         'Darwin': '/dev/tty.SLAB_USBtoUART'