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 diff --git a/adafruit_sht31d.py b/adafruit_sht31d.py index 3a78216..d99a605 100644 --- a/adafruit_sht31d.py +++ b/adafruit_sht31d.py @@ -73,14 +73,14 @@ _SHT31_PERIODIC_FETCH = const(0xE000) _SHT31_PERIODIC_BREAK = const(0x3093) -MODE_SINGLE = 'Single' -MODE_PERIODIC = 'Periodic' +MODE_SINGLE = "Single" +MODE_PERIODIC = "Periodic" _SHT31_MODES = (MODE_SINGLE, MODE_PERIODIC) -REP_HIGH = 'High' -REP_MED = 'Medium' -REP_LOW = 'Low' +REP_HIGH = "High" +REP_MED = "Medium" +REP_LOW = "Low" _SHT31_REP = (REP_HIGH, REP_MED, REP_LOW) @@ -90,39 +90,47 @@ FREQUENCY_4 = 4 FREQUENCY_10 = 10 -_SHT31_FREQUENCIES = (FREQUENCY_0_5, FREQUENCY_1, FREQUENCY_2, FREQUENCY_4, FREQUENCY_10) - -_SINGLE_COMMANDS = ((REP_LOW, const(False), const(0x2416)), - (REP_MED, const(False), const(0x240B)), - (REP_HIGH, const(False), const(0x2400)), - (REP_LOW, const(True), const(0x2C10)), - (REP_MED, const(True), const(0x2C0D)), - (REP_HIGH, const(True), const(0x2C06))) - -_PERIODIC_COMMANDS = ((True, None, const(0x2B32)), - (REP_LOW, FREQUENCY_0_5, const(0x202F)), - (REP_MED, FREQUENCY_0_5, const(0x2024)), - (REP_HIGH, FREQUENCY_0_5, const(0x2032)), - (REP_LOW, FREQUENCY_1, const(0x212D)), - (REP_MED, FREQUENCY_1, const(0x2126)), - (REP_HIGH, FREQUENCY_1, const(0x2130)), - (REP_LOW, FREQUENCY_2, const(0x222B)), - (REP_MED, FREQUENCY_2, const(0x2220)), - (REP_HIGH, FREQUENCY_2, const(0x2236)), - (REP_LOW, FREQUENCY_4, const(0x2329)), - (REP_MED, FREQUENCY_4, const(0x2322)), - (REP_HIGH, FREQUENCY_4, const(0x2334)), - (REP_LOW, FREQUENCY_10, const(0x272A)), - (REP_MED, FREQUENCY_10, const(0x2721)), - (REP_HIGH, FREQUENCY_10, const(0x2737))) - -_DELAY = ((REP_LOW, .0045), - (REP_MED, .0065), - (REP_HIGH, .0155)) +_SHT31_FREQUENCIES = ( + FREQUENCY_0_5, + FREQUENCY_1, + FREQUENCY_2, + FREQUENCY_4, + FREQUENCY_10, +) + +_SINGLE_COMMANDS = ( + (REP_LOW, const(False), const(0x2416)), + (REP_MED, const(False), const(0x240B)), + (REP_HIGH, const(False), const(0x2400)), + (REP_LOW, const(True), const(0x2C10)), + (REP_MED, const(True), const(0x2C0D)), + (REP_HIGH, const(True), const(0x2C06)), +) + +_PERIODIC_COMMANDS = ( + (True, None, const(0x2B32)), + (REP_LOW, FREQUENCY_0_5, const(0x202F)), + (REP_MED, FREQUENCY_0_5, const(0x2024)), + (REP_HIGH, FREQUENCY_0_5, const(0x2032)), + (REP_LOW, FREQUENCY_1, const(0x212D)), + (REP_MED, FREQUENCY_1, const(0x2126)), + (REP_HIGH, FREQUENCY_1, const(0x2130)), + (REP_LOW, FREQUENCY_2, const(0x222B)), + (REP_MED, FREQUENCY_2, const(0x2220)), + (REP_HIGH, FREQUENCY_2, const(0x2236)), + (REP_LOW, FREQUENCY_4, const(0x2329)), + (REP_MED, FREQUENCY_4, const(0x2322)), + (REP_HIGH, FREQUENCY_4, const(0x2334)), + (REP_LOW, FREQUENCY_10, const(0x272A)), + (REP_MED, FREQUENCY_10, const(0x2721)), + (REP_HIGH, FREQUENCY_10, const(0x2737)), +) + +_DELAY = ((REP_LOW, 0.0045), (REP_MED, 0.0065), (REP_HIGH, 0.0155)) def _crc(data): - crc = 0xff + crc = 0xFF for byte in data: crc ^= byte for _ in range(8): @@ -133,18 +141,21 @@ def _crc(data): crc <<= 1 return crc + def _unpack(data): length = len(data) - crc = [None] * (length//3) - word = [None] * (length//3) - for i in range(length//6): - word[i*2], crc[i*2], word[(i*2)+1], crc[(i*2)+1] = struct.unpack('>HBHB', data[i*6:(i*6)+6]) - if crc[i*2] == _crc(data[i*6:(i*6)+2]): - length = (i+1)*6 - for i in range(length//3): - if crc[i] != _crc(data[i*3:(i*3)+2]): + crc = [None] * (length // 3) + word = [None] * (length // 3) + for i in range(length // 6): + word[i * 2], crc[i * 2], word[(i * 2) + 1], crc[(i * 2) + 1] = struct.unpack( + ">HBHB", data[i * 6 : (i * 6) + 6] + ) + if crc[i * 2] == _crc(data[i * 6 : (i * 6) + 2]): + length = (i + 1) * 6 + for i in range(length // 3): + if crc[i] != _crc(data[i * 3 : (i * 3) + 2]): raise RuntimeError("CRC mismatch") - return word[:length//3] + return word[: length // 3] class SHT31D: @@ -154,9 +165,10 @@ class SHT31D: :param i2c_bus: The `busio.I2C` object to use. This is the only required parameter. :param int address: (optional) The I2C address of the device. """ + def __init__(self, i2c_bus, address=_SHT31_DEFAULT_ADDRESS): if address not in _SHT31_ADDRESSES: - raise ValueError('Invalid address: 0x%x' % (address)) + raise ValueError("Invalid address: 0x%x" % (address)) self.i2c_device = I2CDevice(i2c_bus, address) self._mode = MODE_SINGLE self._repeatability = REP_HIGH @@ -170,7 +182,7 @@ def __init__(self, i2c_bus, address=_SHT31_DEFAULT_ADDRESS): def _command(self, command): with self.i2c_device as i2c: - i2c.write(struct.pack('>H', command)) + i2c.write(struct.pack(">H", command)) def _reset(self): """ @@ -179,51 +191,58 @@ def _reset(self): device will not respond to a soft reset when in 'Periodic' mode. """ self._command(_SHT31_PERIODIC_BREAK) - time.sleep(.001) + time.sleep(0.001) self._command(_SHT31_SOFTRESET) - time.sleep(.0015) + time.sleep(0.0015) def _periodic(self): for command in _PERIODIC_COMMANDS: - if self.art == command[0] or \ - (self.repeatability == command[0] and self.frequency == command[1]): + if self.art == command[0] or ( + self.repeatability == command[0] and self.frequency == command[1] + ): self._command(command[2]) - time.sleep(.001) + time.sleep(0.001) self._last_read = 0 def _data(self): if self.mode == MODE_PERIODIC: data = bytearray(48) - data[0] = 0xff + data[0] = 0xFF self._command(_SHT31_PERIODIC_FETCH) - time.sleep(.001) + time.sleep(0.001) elif self.mode == MODE_SINGLE: data = bytearray(6) - data[0] = 0xff + data[0] = 0xFF for command in _SINGLE_COMMANDS: - if self.repeatability == command[0] and self.clock_stretching == command[1]: + if ( + self.repeatability == command[0] + and self.clock_stretching == command[1] + ): self._command(command[2]) if not self.clock_stretching: for delay in _DELAY: if self.repeatability == delay[0]: time.sleep(delay[1]) else: - time.sleep(.001) + time.sleep(0.001) with self.i2c_device as i2c: i2c.readinto(data) word = _unpack(data) length = len(word) - temperature = [None] * (length//2) - humidity = [None] * (length//2) - for i in range(length//2): - temperature[i] = -45 + (175 * (word[i*2] / 65535)) - humidity[i] = 100 * (word[(i*2)+1] / 65535) + temperature = [None] * (length // 2) + humidity = [None] * (length // 2) + for i in range(length // 2): + temperature[i] = -45 + (175 * (word[i * 2] / 65535)) + humidity[i] = 100 * (word[(i * 2) + 1] / 65535) if (len(temperature) == 1) and (len(humidity) == 1): return temperature[0], humidity[0] return temperature, humidity def _read(self): - if self.mode == MODE_PERIODIC and time.time() > self._last_read+1/self.frequency: + if ( + self.mode == MODE_PERIODIC + and time.time() > self._last_read + 1 / self.frequency + ): self._cached_temperature, self._cached_humidity = self._data() self._last_read = time.time() elif self.mode == MODE_SINGLE: @@ -245,7 +264,7 @@ def mode(self, value): raise ValueError("Mode '%s' not supported" % (value)) if self._mode == MODE_PERIODIC and value != MODE_PERIODIC: self._command(_SHT31_PERIODIC_BREAK) - time.sleep(.001) + time.sleep(0.001) if value == MODE_PERIODIC and self._mode != MODE_PERIODIC: self._periodic() self._mode = value @@ -312,7 +331,9 @@ def frequency(self, value): if self.art: raise RuntimeError("Frequency locked to '4 Hz' when ART enabled") if not value in _SHT31_FREQUENCIES: - raise ValueError("Data acquisition frequency '%s Hz' not supported" % (value)) + raise ValueError( + "Data acquisition frequency '%s Hz' not supported" % (value) + ) if self.mode == MODE_PERIODIC and not self._frequency == value: self._frequency = value self._periodic() @@ -354,17 +375,17 @@ def heater(self): def heater(self, value=False): if value: self._command(_SHT31_HEATER_ENABLE) - time.sleep(.001) + time.sleep(0.001) else: self._command(_SHT31_HEATER_DISABLE) - time.sleep(.001) + time.sleep(0.001) @property def status(self): """Device status.""" data = bytearray(2) self._command(_SHT31_READSTATUS) - time.sleep(.001) + time.sleep(0.001) with self.i2c_device as i2c: i2c.readinto(data) status = data[0] << 8 | data[1] @@ -374,9 +395,9 @@ def status(self): def serial_number(self): """Device serial number.""" data = bytearray(6) - data[0] = 0xff + data[0] = 0xFF self._command(_SHT31_READSERIALNBR) - time.sleep(.001) + time.sleep(0.001) with self.i2c_device as i2c: i2c.readinto(data) word = _unpack(data) diff --git a/docs/conf.py b/docs/conf.py index 18307df..36f4bf3 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,9 +11,9 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.viewcode', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.viewcode", ] # Uncomment the below if you use native CircuitPython modules such as @@ -20,29 +21,40 @@ # autodoc module docs will fail to generate with a warning. # autodoc_mock_imports = ["micropython", "adafruit_bus_device"] -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 SHT31D Library' -copyright = u'2017 Jerry Needell' -author = u'Jerry Needell' +project = u"Adafruit SHT31D Library" +copyright = u"2017 Jerry Needell" +author = u"Jerry Needell" # 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 = u"1.0" # The full version, including alpha/beta/rc tags. -release = u'1.0' +release = u"1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -54,7 +66,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. @@ -66,7 +78,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 @@ -80,59 +92,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 = 'AdafruitSht31Librarydoc' +htmlhelp_basename = "AdafruitSht31Librarydoc" # -- 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, 'Adafruitsht31Library.tex', u'Adafruitsht31 Library Documentation', - author, 'manual'), + ( + master_doc, + "Adafruitsht31Library.tex", + u"Adafruitsht31 Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -140,8 +155,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'Adafruitsht31library', u'Adafruit sht31 Library Documentation', - [author], 1) + ( + master_doc, + "Adafruitsht31library", + u"Adafruit sht31 Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -150,7 +170,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'Adafruitsht31Library', u'Adafruit sht31 Library Documentation', - author, 'Adafruitsht31Library', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "Adafruitsht31Library", + u"Adafruit sht31 Library Documentation", + author, + "Adafruitsht31Library", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/examples/sht31d_periodic_mode.py b/examples/sht31d_periodic_mode.py index 84aa97a..a4835c3 100644 --- a/examples/sht31d_periodic_mode.py +++ b/examples/sht31d_periodic_mode.py @@ -8,24 +8,24 @@ i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c) -print('\033[1mSensor\033[0m = SHT31-D') -print('\033[1mSerial Number\033[0m = ', sensor.serial_number, '\n') +print("\033[1mSensor\033[0m = SHT31-D") +print("\033[1mSerial Number\033[0m = ", sensor.serial_number, "\n") sensor.frequency = adafruit_sht31d.FREQUENCY_1 sensor.mode = adafruit_sht31d.MODE_PERIODIC for i in range(3): - print('Please wait...', end='\r') + print("Please wait...", end="\r") if i == 2: sensor.heater = True if i == 1: time.sleep(4) - print('\033[91mCache half full.\033[0m') + print("\033[91mCache half full.\033[0m") else: time.sleep(8) if sensor.heater: - print('\033[1mHeater:\033[0m On ') + print("\033[1mHeater:\033[0m On ") sensor.heater = False - print('\033[1mTemperature:\033[0m ', sensor.temperature) + print("\033[1mTemperature:\033[0m ", sensor.temperature) if not sensor.heater: - print('\033[1mHeater:\033[0m Off') - print('\033[1mHumidity:\033[0m ', sensor.relative_humidity, '\n') + print("\033[1mHeater:\033[0m Off") + print("\033[1mHumidity:\033[0m ", sensor.relative_humidity, "\n") sensor.mode = adafruit_sht31d.MODE_SINGLE diff --git a/examples/sht31d_simple_mode.py b/examples/sht31d_simple_mode.py index b548809..20d327b 100644 --- a/examples/sht31d_simple_mode.py +++ b/examples/sht31d_simple_mode.py @@ -6,21 +6,21 @@ i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c) -print('\033[1mSensor\033[0m = SHT31-D') -print('\033[1mSerial Number\033[0m = ', sensor.serial_number, '\n') +print("\033[1mSensor\033[0m = SHT31-D") +print("\033[1mSerial Number\033[0m = ", sensor.serial_number, "\n") for i in range(3): if i == 0: sensor.repeatability = adafruit_sht31d.REP_LOW - print('\033[1m\033[36mLow Repeatability:\033[0m\n') + print("\033[1m\033[36mLow Repeatability:\033[0m\n") if i == 1: sensor.repeatability = adafruit_sht31d.REP_MED - print('\n\033[1m\033[36mMedium Repeatability:\033[0m\n') + print("\n\033[1m\033[36mMedium Repeatability:\033[0m\n") if i == 2: sensor.repeatability = adafruit_sht31d.REP_HIGH sensor.clock_stretching = True - print('\n\033[1m\033[36mHigh Repeatability:\033[0m') - print('\033[1m\033[95mClock Stretching:\033[0m \033[92mEnabled\033[0m\n') + print("\n\033[1m\033[36mHigh Repeatability:\033[0m") + print("\033[1m\033[95mClock Stretching:\033[0m \033[92mEnabled\033[0m\n") for itr in range(3): - print('\033[1mTemperature:\033[0m %0.3f ºC' % sensor.temperature) - print('\033[1mHumidity:\033[0m %0.2f %%' % sensor.relative_humidity, '\n') + print("\033[1mTemperature:\033[0m %0.3f ºC" % sensor.temperature) + print("\033[1mHumidity:\033[0m %0.2f %%" % sensor.relative_humidity, "\n") diff --git a/setup.py b/setup.py index f2d6088..20186de 100644 --- a/setup.py +++ b/setup.py @@ -7,6 +7,7 @@ # Always prefer setuptools over distutils from setuptools import setup, find_packages + # To use a consistent encoding from codecs import open from os import path @@ -14,48 +15,39 @@ 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-sht31d', - + name="adafruit-circuitpython-sht31d", use_scm_version=True, - setup_requires=['setuptools_scm'], - - description='CircuitPython library for SHT31-D temperature and humidity sensor.', + setup_requires=["setuptools_scm"], + description="CircuitPython library for SHT31-D temperature and humidity sensor.", 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_SHT31-D', - + url="https://github.com/adafruit/Adafruit_CircuitPython_SHT31-D", # Author details - author='Adafruit Industries', - author_email='circuitpython@adafruit.com', - - install_requires=['Adafruit-Blinka', 'adafruit-circuitpython-busdevice'], - + author="Adafruit Industries", + author_email="circuitpython@adafruit.com", + install_requires=["Adafruit-Blinka", "adafruit-circuitpython-busdevice"], # 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 sht31d sht31-d temperature humidity sensor' - 'hardware micropython circuitpython', - + keywords="adafruit sht31d sht31-d temperature humidity sensor" + "hardware micropython circuitpython", # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). - py_modules=['adafruit_sht31d'], + py_modules=["adafruit_sht31d"], )