From f0b7040a870ef0fe711e0b4a7cfa5270f4db3fa4 Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 16 Mar 2020 17:04:48 -0400 Subject: [PATCH 1/2] Ran black, updated to pylint 2.x --- .pylintrc | 2 +- adafruit_rplidar.py | 235 +++++++++++++++++++++++--------------------- docs/conf.py | 120 +++++++++++++--------- setup.py | 52 ++++------ 4 files changed, 218 insertions(+), 191 deletions(-) diff --git a/.pylintrc b/.pylintrc index 039eaec..d8f0ee8 100644 --- a/.pylintrc +++ b/.pylintrc @@ -52,7 +52,7 @@ confidence= # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" # disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call -disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error +disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option diff --git a/adafruit_rplidar.py b/adafruit_rplidar.py index 8b2d61b..6927659 100644 --- a/adafruit_rplidar.py +++ b/adafruit_rplidar.py @@ -48,23 +48,23 @@ import time import struct -#pylint:disable=invalid-name,undefined-variable,global-variable-not-assigned -#pylint:disable=too-many-arguments +# pylint:disable=invalid-name,undefined-variable,global-variable-not-assigned +# pylint:disable=too-many-arguments __version__ = "0.0.1-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RPLIDAR.git" -SYNC_BYTE = b'\xA5' -SYNC_BYTE2 = b'\x5A' +SYNC_BYTE = b"\xA5" +SYNC_BYTE2 = b"\x5A" -GET_INFO_BYTE = b'\x50' -GET_HEALTH_BYTE = b'\x52' +GET_INFO_BYTE = b"\x50" +GET_HEALTH_BYTE = b"\x52" -STOP_BYTE = b'\x25' -RESET_BYTE = b'\x40' +STOP_BYTE = b"\x25" +RESET_BYTE = b"\x40" -SCAN_BYTE = b'\x20' -FORCE_SCAN_BYTE = b'\x21' +SCAN_BYTE = b"\x20" +FORCE_SCAN_BYTE = b"\x21" DESCRIPTOR_LEN = 7 INFO_LEN = 20 @@ -74,49 +74,49 @@ HEALTH_TYPE = 6 SCAN_TYPE = 129 -#Constants & Command to start A2 motor +# Constants & Command to start A2 motor MAX_MOTOR_PWM = 1023 DEFAULT_MOTOR_PWM = 660 -SET_PWM_BYTE = b'\xF0' +SET_PWM_BYTE = b"\xF0" _HEALTH_STATUSES = { - 0: 'Good', - 1: 'Warning', - 2: 'Error', + 0: "Good", + 1: "Warning", + 2: "Error", } class RPLidarException(Exception): - '''Basic exception class for RPLidar''' + """Basic exception class for RPLidar""" def _process_scan(raw): - '''Processes input raw data and returns measurment data''' + """Processes input raw data and returns measurment data""" new_scan = bool(raw[0] & 0b1) inversed_new_scan = bool((raw[0] >> 1) & 0b1) quality = raw[0] >> 2 if new_scan == inversed_new_scan: - raise RPLidarException('New scan flags mismatch') + raise RPLidarException("New scan flags mismatch") check_bit = raw[1] & 0b1 if check_bit != 1: - raise RPLidarException('Check bit not equal to 1') - angle = ((raw[1] >> 1) + (raw[2] << 7)) / 64. - distance = (raw[3] + (raw[4] << 8)) / 4. + raise RPLidarException("Check bit not equal to 1") + angle = ((raw[1] >> 1) + (raw[2] << 7)) / 64.0 + distance = (raw[3] + (raw[4] << 8)) / 4.0 return new_scan, quality, angle, distance -class RPLidar(object): - '''Class for communicating with RPLidar rangefinder scanners''' +class RPLidar: + """Class for communicating with RPLidar rangefinder scanners""" - motor_pin = None #: DigitalInOut instance controlling the motor - _serial_port = None #: Serial port (or UART) instance + motor_pin = None #: DigitalInOut instance controlling the motor + _serial_port = None #: Serial port (or UART) instance port = None #: Serial port name, e.g. /dev/ttyUSB0 timeout = 1 #: Serial port timeout motor = False #: Is motor running? baudrate = 115200 #: Baudrate for serial port def __init__(self, motor_pin, port, baudrate=115200, timeout=1, logging=False): - '''Initilize RPLidar object for communicating with the sensor. + """Initilize RPLidar object for communicating with the sensor. Parameters @@ -127,7 +127,7 @@ def __init__(self, motor_pin, port, baudrate=115200, timeout=1, logging=False): timeout : float, optional Serial port connection timeout in seconds (the default is 1) logging : whether to output logging information - ''' + """ self.motor_pin = motor_pin self.port = port self.baudrate = baudrate @@ -140,59 +140,64 @@ def __init__(self, motor_pin, port, baudrate=115200, timeout=1, logging=False): if self.is_CP: _serial_port = port else: - global serial - import serial + global serial # pylint: disable=global-statement + import serial # pylint: disable=import-outside-toplevel self.connect() self.start_motor() def log(self, level, msg): - '''Output the level and a message if logging is enabled.''' + """Output the level and a message if logging is enabled.""" if self.logging: - sys.stdout.write('{0}: {1}\n'.format(level, msg)) + sys.stdout.write("{0}: {1}\n".format(level, msg)) def log_bytes(self, level, msg, ba): - '''Log and output a byte array in a readable way.''' - bs = ['%02x' % b for b in ba] - self.log(level, msg + ' '.join(bs)) + """Log and output a byte array in a readable way.""" + bs = ["%02x" % b for b in ba] + self.log(level, msg + " ".join(bs)) def connect(self): - '''Connects to the serial port named by the port instance var. If it was - connected to another serial port disconnects from it first.''' + """Connects to the serial port named by the port instance var. If it was + connected to another serial port disconnects from it first.""" if not self.is_CP: if self._serial_port is not None: self.disconnect() try: self._serial_port = serial.Serial( - self.port, self.baudrate, - parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, - timeout=self.timeout, dsrdtr=True) + self.port, + self.baudrate, + parity=serial.PARITY_NONE, + stopbits=serial.STOPBITS_ONE, + timeout=self.timeout, + dsrdtr=True, + ) except serial.SerialException as err: - raise RPLidarException('Failed to connect to the sensor ' - 'due to: %s' % err) + raise RPLidarException( + "Failed to connect to the sensor " "due to: %s" % err + ) def disconnect(self): - '''Disconnects from the serial port''' + """Disconnects from the serial port""" if self._serial_port is None: return self._serial_port.close() def set_pwm(self, pwm): - '''Set the motor PWM''' + """Set the motor PWM""" assert 0 <= pwm <= MAX_MOTOR_PWM payload = struct.pack(" max_buf_meas*dsize: - self.log('warning', - 'Too many measurments in the input buffer: %d/%d. ' - 'Clearing buffer...' % - (data_in_buf//dsize, max_buf_meas)) - self._serial_port.read(data_in_buf//dsize*dsize) + if data_in_buf > max_buf_meas * dsize: + self.log( + "warning", + "Too many measurments in the input buffer: %d/%d. " + "Clearing buffer..." % (data_in_buf // dsize, max_buf_meas), + ) + self._serial_port.read(data_in_buf // dsize * dsize) yield _process_scan(raw) def iter_scans(self, max_buf_meas=500, min_len=5): - '''Iterate over scans. Note that consumer must be fast enough, + """Iterate over scans. Note that consumer must be fast enough, otherwise data will be accumulated inside buffer and consumer will get data with increasing lag. @@ -401,7 +412,7 @@ def iter_scans(self, max_buf_meas=500, min_len=5): List of the measurments. Each measurment is tuple with following format: (quality, angle, distance). For values description please refer to `iter_measurments` method's documentation. - ''' + """ scan = [] iterator = self.iter_measurments(max_buf_meas) for new_scan, quality, angle, distance in iterator: diff --git a/docs/conf.py b/docs/conf.py index 598a51c..e751d7f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -2,7 +2,8 @@ import os import sys -sys.path.insert(0, os.path.abspath('..')) + +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ------------------------------------------------ @@ -10,10 +11,10 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.napoleon', - 'sphinx.ext.todo', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx.ext.todo", ] # TODO: Please Read! @@ -23,29 +24,40 @@ # autodoc_mock_imports = ["digitalio", "busio"] -intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None),'Register': ('https://circuitpython.readthedocs.io/projects/register/en/latest/', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} +intersphinx_mapping = { + "python": ("https://docs.python.org/3.4", None), + "BusDevice": ( + "https://circuitpython.readthedocs.io/projects/busdevice/en/latest/", + None, + ), + "Register": ( + "https://circuitpython.readthedocs.io/projects/register/en/latest/", + None, + ), + "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), +} # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'Adafruit_circuitpython RPLIDAR Library' -copyright = u'2019 Dave Astels' -author = u'Dave Astels' +project = "Adafruit_circuitpython RPLIDAR Library" +copyright = "2019 Dave Astels" +author = "Dave Astels" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = u'1.0' +version = "1.0" # The full version, including alpha/beta/rc tags. -release = u'1.0' +release = "1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -57,7 +69,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -69,7 +81,7 @@ add_function_parentheses = True # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -84,59 +96,62 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get('READTHEDOCS', None) == 'True' +on_rtd = os.environ.get("READTHEDOCS", None) == "True" if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme - html_theme = 'sphinx_rtd_theme' - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] + + html_theme = "sphinx_rtd_theme" + html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] except: - html_theme = 'default' - html_theme_path = ['.'] + html_theme = "default" + html_theme_path = ["."] else: - html_theme_path = ['.'] + html_theme_path = ["."] # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # -html_favicon = '_static/favicon.ico' +html_favicon = "_static/favicon.ico" # Output file base name for HTML help builder. -htmlhelp_basename = 'AdafruitRplidarLibrarydoc' +htmlhelp_basename = "AdafruitRplidarLibrarydoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'AdafruitRPLIDARLibrary.tex', u'AdafruitRPLIDAR Library Documentation', - author, 'manual'), + ( + master_doc, + "AdafruitRPLIDARLibrary.tex", + "AdafruitRPLIDAR Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -144,8 +159,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'AdafruitRPLIDARlibrary', u'Adafruit RPLIDAR Library Documentation', - [author], 1) + ( + master_doc, + "AdafruitRPLIDARlibrary", + "Adafruit RPLIDAR Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -154,7 +174,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AdafruitRPLIDARLibrary', u'Adafruit RPLIDAR Library Documentation', - author, 'AdafruitRPLIDARLibrary', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "AdafruitRPLIDARLibrary", + "Adafruit RPLIDAR Library Documentation", + author, + "AdafruitRPLIDARLibrary", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/setup.py b/setup.py index 2fb437d..db707e6 100644 --- a/setup.py +++ b/setup.py @@ -6,6 +6,7 @@ """ from setuptools import setup, find_packages + # To use a consistent encoding from codecs import open from os import path @@ -13,51 +14,40 @@ here = path.abspath(path.dirname(__file__)) # Get the long description from the README file -with open(path.join(here, 'README.rst'), encoding='utf-8') as f: +with open(path.join(here, "README.rst"), encoding="utf-8") as f: long_description = f.read() setup( - name='adafruit-circuitpython-rplidar', - + name="adafruit-circuitpython-rplidar", use_scm_version=True, - setup_requires=['setuptools_scm'], - - description='RPLidar support', + setup_requires=["setuptools_scm"], + description="RPLidar support", long_description=long_description, - long_description_content_type='text/x-rst', - + long_description_content_type="text/x-rst", # The project's main homepage. - url='https://github.com/adafruit/Adafruit_CircuitPython_rplidar', - + url="https://github.com/adafruit/Adafruit_CircuitPython_rplidar", # Author details - author='Adafruit Industries', - author_email='circuitpython@adafruit.com', - - install_requires=[ - 'Adafruit-Blinka' - ], - + author="Adafruit Industries", + author_email="circuitpython@adafruit.com", + install_requires=["Adafruit-Blinka"], # Choose your license - license='MIT', - + license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Topic :: Software Development :: Libraries', - 'Topic :: System :: Hardware', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: System :: Hardware", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", ], - # What does your project relate to? - keywords='adafruit blinka circuitpython micropython rplidar lidar sensors', - + keywords="adafruit blinka circuitpython micropython rplidar lidar sensors", # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, # CHANGE `py_modules=['...']` TO `packages=['...']` - py_modules=['adafruit_rplidar'], + py_modules=["adafruit_rplidar"], ) From a76ca5b4e661e248f90c8464b72c0d491cbe7a3a Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 16 Mar 2020 17:08:54 -0400 Subject: [PATCH 2/2] Fixed build.yml --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fff3aa9..1dad804 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,7 +40,7 @@ jobs: source actions-ci/install.sh - name: Pip install pylint, black, & Sphinx run: | - pip install --force-reinstall pylint==1.9.2 black==19.10b0 Sphinx sphinx-rtd-theme + pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme - name: Library version run: git describe --dirty --always --tags - name: PyLint