Skip to content

Ran black, updated to pylint 2.x #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
43 changes: 27 additions & 16 deletions adafruit_dht.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,20 @@
import array
import time
from digitalio import DigitalInOut, Pull, Direction

_USE_PULSEIO = False
try:
from pulseio import PulseIn

_USE_PULSEIO = True
except ImportError:
pass # This is OK, we'll try to bitbang it!
pass # This is OK, we'll try to bitbang it!


__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_DHT.git"


class DHTBase:
""" base support for DHT11 and DHT22 devices
"""
Expand Down Expand Up @@ -88,7 +91,7 @@ def _pulses_to_binary(self, pulses, start, stop):
bit = 0
if pulses[bit_inx] > self.__hiLevel:
bit = 1
binary = binary<<1 | bit
binary = binary << 1 | bit

hi_sig = not hi_sig

Expand All @@ -104,7 +107,7 @@ def _get_pulses_pulseio(self):
transition times starting with a low transition time. Normally
pulses will have 81 elements for the DHT11/22 type devices.
"""
pulses = array.array('H')
pulses = array.array("H")
if _USE_PULSEIO:
# The DHT type device use a specialize 1-wire protocol
# The microprocessor first sends a LOW signal for a
Expand Down Expand Up @@ -133,7 +136,7 @@ def _get_pulses_bitbang(self):
transition times starting with a low transition time. Normally
pulses will have 81 elements for the DHT11/22 type devices.
"""
pulses = array.array('H')
pulses = array.array("H")
with DigitalInOut(self._pin) as dhtpin:
# we will bitbang if no pulsein capability
transitions = []
Expand All @@ -143,19 +146,19 @@ def _get_pulses_bitbang(self):
time.sleep(0.1)
dhtpin.value = False
time.sleep(0.001)
timestamp = time.monotonic() # take timestamp
dhtval = True # start with dht pin true because its pulled up
timestamp = time.monotonic() # take timestamp
dhtval = True # start with dht pin true because its pulled up
dhtpin.direction = Direction.INPUT
dhtpin.pull = Pull.UP
while time.monotonic() - timestamp < 0.25:
if dhtval != dhtpin.value:
dhtval = not dhtval # we toggled
transitions.append(time.monotonic()) # save the timestamp
transitions.append(time.monotonic()) # save the timestamp
# convert transtions to microsecond delta pulses:
# use last 81 pulses
transition_start = max(1, len(transitions) - 81)
for i in range(transition_start, len(transitions)):
pulses_micro_sec = int(1000000 * (transitions[i] - transitions[i-1]))
pulses_micro_sec = int(1000000 * (transitions[i] - transitions[i - 1]))
pulses.append(min(pulses_micro_sec, 65535))
return pulses

Expand All @@ -171,20 +174,24 @@ def measure(self):
# Initiate new reading if this is the first call or if sufficient delay
# If delay not sufficient - return previous reading.
# This allows back to back access for temperature and humidity for same reading
if (self._last_called == 0 or
(time.monotonic()-self._last_called) > delay_between_readings):
if (
self._last_called == 0
or (time.monotonic() - self._last_called) > delay_between_readings
):
self._last_called = time.monotonic()

if _USE_PULSEIO:
pulses = self._get_pulses_pulseio()
else:
pulses = self._get_pulses_bitbang()
#print(len(pulses), "pulses:", [x for x in pulses])
# print(len(pulses), "pulses:", [x for x in pulses])

if len(pulses) >= 80:
buf = array.array('B')
buf = array.array("B")
for byte_start in range(0, 80, 16):
buf.append(self._pulses_to_binary(pulses, byte_start, byte_start+16))
buf.append(
self._pulses_to_binary(pulses, byte_start, byte_start + 16)
)

if self._dht11:
# humidity is 1 byte
Expand All @@ -193,10 +200,10 @@ def measure(self):
self._temperature = buf[2]
else:
# humidity is 2 bytes
self._humidity = ((buf[0]<<8) | buf[1]) / 10
self._humidity = ((buf[0] << 8) | buf[1]) / 10
# temperature is 2 bytes
# MSB is sign, bits 0-14 are magnitude)
raw_temperature = (((buf[2] & 0x7f)<<8) | buf[3]) / 10
raw_temperature = (((buf[2] & 0x7F) << 8) | buf[3]) / 10
# set sign
if buf[2] & 0x80:
raw_temperature = -raw_temperature
Expand All @@ -207,7 +214,7 @@ def measure(self):
chk_sum += b

# checksum is the last byte
if chk_sum & 0xff != buf[4]:
if chk_sum & 0xFF != buf[4]:
# check sum failed to validate
raise RuntimeError("Checksum did not validate. Try again.")

Expand All @@ -217,6 +224,7 @@ def measure(self):
else:
# Probably a connection issue!
raise RuntimeError("DHT sensor not found, check wiring")

@property
def temperature(self):
""" temperature current reading. It makes sure a reading is available
Expand All @@ -237,11 +245,13 @@ def humidity(self):
self.measure()
return self._humidity


class DHT11(DHTBase):
""" Support for DHT11 device.

:param ~board.Pin pin: digital pin used for communication
"""

def __init__(self, pin):
super().__init__(True, pin, 18000)

Expand All @@ -251,5 +261,6 @@ class DHT22(DHTBase):

:param ~board.Pin pin: digital pin used for communication
"""

def __init__(self, pin):
super().__init__(False, pin, 1000)
121 changes: 72 additions & 49 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,47 +2,56 @@

import os
import sys
sys.path.insert(0, os.path.abspath('..'))

sys.path.insert(0, os.path.abspath(".."))

# -- General configuration ------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# 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",
]

autodoc_mock_imports = ["pulseio"]

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 DHT Library'
copyright = u'2017 Mike McWethy'
author = u'Mike McWethy'
project = u"Adafruit CircuitPython DHT Library"
copyright = u"2017 Mike McWethy"
author = u"Mike McWethy"

# 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.
Expand All @@ -54,7 +63,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.
Expand All @@ -66,7 +75,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
Expand All @@ -80,68 +89,76 @@
# 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 = 'AdafruitCircuitPythonDHTLibrarydoc'
htmlhelp_basename = "AdafruitCircuitPythonDHTLibrarydoc"

# -- 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, 'AdafruitCircuitPythonDHTLibrary.tex', u'Adafruit CircuitPython DHT Library Documentation',
author, 'manual'),
(
master_doc,
"AdafruitCircuitPythonDHTLibrary.tex",
u"Adafruit CircuitPython DHT Library Documentation",
author,
"manual",
),
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'adafruitCircuitPythonDHTlibrary', u'Adafruit CircuitPython DHT Library Documentation',
[author], 1)
(
master_doc,
"adafruitCircuitPythonDHTlibrary",
u"Adafruit CircuitPython DHT Library Documentation",
[author],
1,
)
]

# -- Options for Texinfo output -------------------------------------------
Expand All @@ -150,7 +167,13 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'AdafruitCircuitPythonDHTLibrary', u'Adafruit CircuitPython DHT Library Documentation',
author, 'AdafruitCircuitPythonDHTLibrary', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"AdafruitCircuitPythonDHTLibrary",
u"Adafruit CircuitPython DHT Library Documentation",
author,
"AdafruitCircuitPythonDHTLibrary",
"One line description of project.",
"Miscellaneous",
),
]
7 changes: 5 additions & 2 deletions examples/dht_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
print("Temp: {:.1f} F / {:.1f} C Humidity: {}% "
.format(temperature_f, temperature_c, humidity))
print(
"Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(
temperature_f, temperature_c, humidity
)
)

except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
Expand Down
Loading