diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fff3aa9..97fe64d 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 pylint black==19.10b0 Sphinx sphinx-rtd-theme - name: Library version run: git describe --dirty --always --tags - name: PyLint diff --git a/adafruit_hue.py b/adafruit_hue.py index 4799822..71b99da 100644 --- a/adafruit_hue.py +++ b/adafruit_hue.py @@ -49,58 +49,60 @@ __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Hue.git" + class Bridge: """ HTTP Interface for interacting with a Philips Hue Bridge. """ + def __init__(self, wifi_manager, bridge_ip=None, username=None): """ Creates an instance of the Philips Hue Bridge Interface. :param wifi_manager wifi_manager: WiFiManager from ESPSPI_WiFiManager/ESPAT_WiFiManager """ wifi_type = str(type(wifi_manager)) - if ('ESPSPI_WiFiManager' in wifi_type or 'ESPAT_WiFiManager' in wifi_type): + if "ESPSPI_WiFiManager" in wifi_type or "ESPAT_WiFiManager" in wifi_type: self._wifi = wifi_manager else: raise TypeError("This library requires a WiFiManager object.") self._ip = bridge_ip self._username = username if bridge_ip and username is not None: - self._bridge_url = 'http://{}/api'.format(self._ip) - self._username_url = self._bridge_url+'/'+ self._username + self._bridge_url = "http://{}/api".format(self._ip) + self._username_url = self._bridge_url + "/" + self._username @staticmethod def rgb_to_hsb(rgb): """Returns RGB values as a HSL tuple. :param list rgb: RGB Values """ - r = rgb[0]/255 - g = rgb[1]/255 - b = rgb[2]/255 + r = rgb[0] / 255 + g = rgb[1] / 255 + b = rgb[2] / 255 c_max = max(r, g, b) c_min = min(r, g, b) - delta = c_max-c_min - light = ((c_max+c_min)/2) + delta = c_max - c_min + light = (c_max + c_min) / 2 if delta == 0.0: hue = 0 sat = 0 else: if light < 0.5: - sat = (c_max-c_min)/(c_max+c_min) + sat = (c_max - c_min) / (c_max + c_min) else: - sat = (c_max-c_min)/(2.0-c_max-c_min) + sat = (c_max - c_min) / (2.0 - c_max - c_min) if c_max == r: - hue = (g-b)/(c_max-c_min) + hue = (g - b) / (c_max - c_min) elif c_max == g: - hue = 2.0 + (b-r)/(c_max-c_min) + hue = 2.0 + (b - r) / (c_max - c_min) else: - hue = 4.0 + (r-g)/(c_max-c_min) + hue = 4.0 + (r - g) / (c_max - c_min) hue *= 60 if hue < 0: hue += 360 hue = map_range(hue, 0, 360, 0, 65535) - sat = map_range(sat*100, 0, 100, 0, 254) - light = map_range(light*100, 0, 100, 0, 254) + sat = map_range(sat * 100, 0, 100, 0, 254) + light = map_range(light * 100, 0, 100, 0, 254) return round(hue), round(sat, 3), round(light, 2) # Hue Core API @@ -109,16 +111,18 @@ def discover_bridge(self): Returns the bridge's IP address. """ try: - resp = self._wifi.get('https://discovery.meethue.com') + resp = self._wifi.get("https://discovery.meethue.com") json_data = resp.json() - bridge_ip = json_data[0]['internalipaddress'] + bridge_ip = json_data[0]["internalipaddress"] resp.close() except: - raise TypeError('Ensure the Philips Bridge and CircuitPython device\ - are both on the same WiFi network.') + raise TypeError( + "Ensure the Philips Bridge and CircuitPython device\ + are both on the same WiFi network." + ) self._ip = bridge_ip # set up hue bridge address path - self._bridge_url = 'http://{}/api'.format(self._ip) + self._bridge_url = "http://{}/api".format(self._ip) return self._ip def register_username(self): @@ -126,17 +130,17 @@ def register_username(self): Provides a 30 second delay to press the link button on the bridge. Returns username or None. """ - self._bridge_url = 'http://{}/api'.format(self._ip) - data = {"devicetype":"CircuitPython#pyportal{0}".format(randint(0, 100))} + self._bridge_url = "http://{}/api".format(self._ip) + data = {"devicetype": "CircuitPython#pyportal{0}".format(randint(0, 100))} resp = self._wifi.post(self._bridge_url, json=data) connection_attempts = 1 username = None while username is None and connection_attempts > 0: resp = self._wifi.post(self._bridge_url, json=data) json = resp.json()[0] - if json.get('success'): - username = str(json['success']['username']) - self._username_url = self._bridge_url+'/'+ username + if json.get("success"): + username = str(json["success"]["username"]) + self._username_url = self._bridge_url + "/" + username connection_attempts -= 1 time.sleep(1) resp.close() @@ -147,7 +151,7 @@ def show_light_info(self, light_id): """Gets the attributes and state of a given light. :param int light_id: Light identifier. """ - resp = self._get('{0}/lights/{1}'.format(self._username_url, light_id)) + resp = self._get("{0}/lights/{1}".format(self._username_url, light_id)) return resp def set_light(self, light_id, **kwargs): @@ -160,7 +164,9 @@ def set_light(self, light_id, **kwargs): (more settings at: https://developers.meethue.com/develop/hue-api/lights-api/#set-light-state ) """ - resp = self._put('{0}/lights/{1}/state'.format(self._username_url, light_id), kwargs) + resp = self._put( + "{0}/lights/{1}/state".format(self._username_url, light_id), kwargs + ) return resp def toggle_light(self, light_id): @@ -168,7 +174,7 @@ def toggle_light(self, light_id): :param int light_id: Light identifier. """ light_state = self.get_light(light_id) - light_state = not light_state['state']['on'] + light_state = not light_state["state"]["on"] resp = self.set_light(light_id, on=light_state) return resp @@ -176,13 +182,13 @@ def get_light(self, light_id): """Gets the attributes and state of a provided light. :param int light_id: Light identifier. """ - resp = self._get('{0}/lights/{1}'.format(self._username_url, light_id)) + resp = self._get("{0}/lights/{1}".format(self._username_url, light_id)) return resp def get_lights(self): """Returns all the light resources available for a bridge. """ - resp = self._get(self._username_url+'/lights') + resp = self._get(self._username_url + "/lights") return resp # Groups API @@ -191,11 +197,8 @@ def create_group(self, lights, group_id): :param list lights: List of light identifiers. :param str group_id: Optional group name. """ - data = {'lights':lights, - 'name':group_id, - 'type':group_id - } - resp = self._post(self._username_url+'/groups', data) + data = {"lights": lights, "name": group_id, "type": group_id} + resp = self._post(self._username_url + "/groups", data) return resp def set_group(self, group_id, **kwargs): @@ -209,13 +212,15 @@ def set_group(self, group_id, **kwargs): (more settings at https://developers.meethue.com/develop/hue-api/lights-api/#set-light-state ) """ - resp = self._put('{0}/groups/{1}/action'.format(self._username_url, group_id), kwargs) + resp = self._put( + "{0}/groups/{1}/action".format(self._username_url, group_id), kwargs + ) return resp def get_groups(self): """Returns all the light groups available for a bridge. """ - resp = self._get(self._username_url+'/groups') + resp = self._get(self._username_url + "/groups") return resp # Scene API @@ -229,7 +234,7 @@ def set_scene(self, group_id, scene_id): def get_scenes(self): """Returns a list of all scenes currently stored in the bridge. """ - resp = self._get(self._username_url+'/scenes') + resp = self._get(self._username_url + "/scenes") return resp # HTTP Helpers for the Hue API @@ -238,10 +243,7 @@ def _post(self, path, data): :param str path: Formatted Hue API URL :param json data: JSON data to POST to the Hue API. """ - resp = self._wifi.post( - path, - json=data - ) + resp = self._wifi.post(path, json=data) resp_json = resp.json() resp.close() return resp_json @@ -251,10 +253,7 @@ def _put(self, path, data): :param str path: Formatted Hue API URL :param json data: JSON data to PUT to the Hue API. """ - resp = self._wifi.put( - path, - json=data - ) + resp = self._wifi.put(path, json=data) resp_json = resp.json() resp.close() return resp_json @@ -264,10 +263,7 @@ def _get(self, path, data=None): :param str path: Formatted Hue API URL :param json data: JSON data to GET from the Hue API. """ - resp = self._wifi.get( - path, - json=data - ) + resp = self._wifi.get(path, json=data) resp_json = resp.json() resp.close() return resp_json diff --git a/docs/conf.py b/docs/conf.py index fdb7799..97148c9 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,32 @@ # autodoc_mock_imports = ["digitalio", "busio"] -intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} +intersphinx_mapping = { + "python": ("https://docs.python.org/3.4", 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 Hue Library' -copyright = u'2019 Brent Rubell' -author = u'Brent Rubell' +project = "Adafruit Hue Library" +copyright = "2019 Brent Rubell" +author = "Brent Rubell" # 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 +61,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 +73,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 +88,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 = 'AdafruitHueLibrarydoc' +htmlhelp_basename = "AdafruitHueLibrarydoc" # -- 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, 'AdafruitHueLibrary.tex', u'AdafruitHue Library Documentation', - author, 'manual'), + ( + master_doc, + "AdafruitHueLibrary.tex", + "AdafruitHue Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -144,8 +151,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'AdafruitHuelibrary', u'Adafruit Hue Library Documentation', - [author], 1) + ( + master_doc, + "AdafruitHuelibrary", + "Adafruit Hue Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -154,7 +166,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AdafruitHueLibrary', u'Adafruit Hue Library Documentation', - author, 'AdafruitHueLibrary', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "AdafruitHueLibrary", + "Adafruit Hue Library Documentation", + author, + "AdafruitHueLibrary", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/examples/hue_simpletest.py b/examples/hue_simpletest.py index 022405f..d94a4bf 100644 --- a/examples/hue_simpletest.py +++ b/examples/hue_simpletest.py @@ -5,6 +5,7 @@ from adafruit_esp32spi import adafruit_esp32spi from adafruit_esp32spi import adafruit_esp32spi_wifimanager import neopixel + # Import Philips Hue Bridge from adafruit_hue import Bridge @@ -26,17 +27,21 @@ # Attempt to load bridge username and IP address from secrets.py try: - username = secrets['hue_username'] - bridge_ip = secrets['bridge_ip'] + username = secrets["hue_username"] + bridge_ip = secrets["bridge_ip"] my_bridge = Bridge(wifi, bridge_ip, username) except: # Perform first-time bridge setup my_bridge = Bridge(wifi) ip = my_bridge.discover_bridge() username = my_bridge.register_username() - print('ADD THESE VALUES TO SECRETS.PY: \ + print( + 'ADD THESE VALUES TO SECRETS.PY: \ \n\t"bridge_ip":"{0}", \ - \n\t"hue_username":"{1}"'.format(ip, username)) + \n\t"hue_username":"{1}"'.format( + ip, username + ) + ) raise # Enumerate all lights on the bridge diff --git a/setup.py b/setup.py index d553939..f6d4741 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,53 +14,44 @@ 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-hue', - + name="adafruit-circuitpython-hue", use_scm_version=True, - setup_requires=['setuptools_scm'], - - description='CircuitPython helper library for the Philips Hue', + setup_requires=["setuptools_scm"], + description="CircuitPython helper library for the Philips Hue", 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_Hue', - + url="https://github.com/adafruit/Adafruit_CircuitPython_Hue", # Author details - author='Adafruit Industries', - author_email='circuitpython@adafruit.com', - + author="Adafruit Industries", + author_email="circuitpython@adafruit.com", install_requires=[ - 'Adafruit-Blinka', - 'adafruit-circuitpython-esp32spi', - 'adafruit-circuitpython-simpleio' + "Adafruit-Blinka", + "adafruit-circuitpython-esp32spi", + "adafruit-circuitpython-simpleio", ], - # 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 hue philips bulb light bridge', - + keywords="adafruit blinka circuitpython micropython hue philips bulb light bridge", # 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_hue'], + py_modules=["adafruit_hue"], )