Metadata-Version: 2.4
Name: smarthomeconnect
Version: 0.10.1
Summary: The Smart Home Connect home automation framework based on AsyncIO
Author-email: Michael Thies <mail@mhthies.de>
License: 
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Documentation, https://smarthomeconnect.readthedocs.org/
Project-URL: Source, https://github.com/mhthies/smarthomeconnect
Project-URL: Tracker, https://github.com/mhthies/smarthomeconnect/issues
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Topic :: Home Automation
Classifier: Framework :: AsyncIO
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: aiohttp<4,>=3.6
Requires-Dist: jinja2<4,>=2.11
Requires-Dist: MarkupSafe<4,>=1.1
Provides-Extra: mysql
Requires-Dist: aiomysql<=0.4.0,>=0.0.21; extra == "mysql"
Provides-Extra: knx
Requires-Dist: knxdclient<2,>=0.4.0; extra == "knx"
Provides-Extra: dmx
Requires-Dist: pyserial-asyncio<0.7,>=0.3; extra == "dmx"
Provides-Extra: midi
Requires-Dist: mido<2,>=1.2.9; extra == "midi"
Requires-Dist: python-rtmidi<2,>=1.4.6; extra == "midi"
Provides-Extra: mqtt
Requires-Dist: aiomqtt<3,>=2.0.0; extra == "mqtt"
Provides-Extra: pulse
Requires-Dist: pulsectl_asyncio<2,>=1.0.0; extra == "pulse"
Provides-Extra: telegram
Requires-Dist: aiogram<4,>=3.0; extra == "telegram"
Provides-Extra: file-persistence
Requires-Dist: aiofile<4,>=3.7.4; extra == "file-persistence"
Dynamic: license-file


# Smart Home Connect

[![GitHub Actions CI Status](https://github.com/mhthies/smarthomeconnect/workflows/build/badge.svg)](https://github.com/mhthies/smarthomeconnect/actions?query=workflow%3Abuild)
[![codecov](https://codecov.io/gh/mhthies/smarthomeconnect/branch/master/graph/badge.svg)](https://codecov.io/gh/mhthies/smarthomeconnect)
[![Documentation Status at readthedocs.io](https://readthedocs.org/projects/smarthomeconnect/badge/?version=latest)](https://smarthomeconnect.readthedocs.io/en/latest/?badge=latest)
[![Latest PyPI version](https://badge.fury.io/py/smarthomeconnect.svg)](https://pypi.org/project/smarthomeconnect/)

<img align="right" height="100" src="etc/logo.svg">

*Smart Home Connect* (SHC) is yet another Python home automation framework—in line with [Home Assistant](https://www.home-assistant.io/), [SmartHome.py](https://mknx.github.io/smarthome/), [SmartHomeNG](https://www.smarthomeng.de/) and probably many more.
Its purpose is to connect "smart home" devices via different communication protocols, provide means for creating automation rules/scripts and a web interface for controling the devices via browser.

In contrast to most other home automation frameworks, SHC is completely based on Python's asynchronous coroutines (asyncio) and configured via pure Python scripts instead of YAML files or a fancy web engineering tool.
Its configuration is based on instantiating *Connectable* objects (like state variables, User Interface Buttons, KNX Group Addresses, etc.) and interconnecting them with simple Read/Subscribe patterns.
Thus, it is quite simple but really powerful, allowing on-the-fly type conversion, expressions for calculating derived values, handling stateless events, ….
Read more about SHC's base concepts [in the documentation](https://smarthomeconnect.readthedocs.io/en/latest/base.html).


## Features

* interfaces
    * KNX bus via KNXD
    * DMX (via Enttec DMX USB Pro and compatible interfaces)
    * HTTP/REST API + websocket API
    * SHC client (connecting to another SHC instance via websocket API)
    * MIDI (esp. for Hardware MIDI controllers)
    * MQTT
    * [Tasmota](https://github.com/arendst/tasmota/) (currently: relais, RGB+CCW lights, IR receiver, power sensors; more features will be added on demand)
    * Pulseaudio
    * Telegram Bot
* websocket-based web user interface (using *aiohttp*, *Jinja2* and *Semantic UI*)
    * widgets: buttons, text display, text/number inputs, dropdowns, images with placeable buttons, charts, etc., … 
* configuration of data points/variables and automation rules in plain Python
    * full power of Python + intuitive representation and interconnection of different interfaces 
    * type checking and extensible type conversion system
    * connecting objects via Python expressions
* chronological and periodic timers for triggering rules 
* Logging/Persistence (no really stable in API yet)
    * to MySQL

### Roadmap

* Stabilize logging API
* Logging to Influx-DB
* More web widgets
    * Gauges
    * timeline/"stripe" charts


## Getting started

0. (Optional) Create a virtual environment to keep your Python package repositories clean:
   ```bash
   python3 -m virtualenv -p python3 venv
   . venv/bin/activate
   ```
   Read more about virtual environments [in the offical Python docs](https://docs.python.org/3/tutorial/venv.html).
  
1. Install the `smarthomeconnect` Python distribution from PyPI:
   ```bash
   pip3 install smarthomeconnect
   ```
   It will be only install smarthomeconnect and the dependencies of its core features.
   Additional dependencies are required for certain interface modules and can be installed via pip's/setuptool's 'extras' feature.
   See [Depdencies section](#Dependencies) of this readme for a complete list.
   If you install SHC from a source distribution (in contrast to a "binary" package, such as a "wheel" package from PyPI), you'll need NodeJS and npm installed on your machine, which are used to download the web UI assets during the Python package building process. 

2. Create a Python script (let's call it `my_home_automation.py`) which imports and starts Smart Home Connect:
   ```python
   #!/usr/bin/env python3
   import shc

   # TODO add interfaces and Variables
  
   shc.main()
   ```
   When running this script (`python3 my_home_authomation.py`), SHC should start up and run idle until you terminate it (e.g. with Ctrl+C).
   See the code below for an example with the Web UI and the KNX interface.

3. Read about the basic concepts of SHC and available interfaces in the [SHC documentation](https://smarthomeconnect.readthedocs.io/en/latest/).
   Extend your script to create interfaces and Variables, *connect* connectable objects, define logic handlers and let them be triggered.


## Simple Usage Example

```python
import datetime
import shc
import shc.web
import shc.web.widgets
import shc.interfaces.knx

# Configure interfaces
knx_connection = shc.interfaces.knx.KNXConnector()
web_interface = shc.web.WebServer("localhost", 8080, "index")

web_index_page = web_interface.page('index')


# Simple On/Off Variable, connected to KNX Group Address (initialized per Group Read telegram),
# with a switch widget in the web user interface
ceiling_lights = shc.Variable(bool, "ceiling lights")\
    .connect(knx_connection.group(shc.interfaces.knx.KNXGAD(1, 2, 3), dpt="1", init=True))

web_index_page.add_item(shc.web.widgets.Switch("Ceiling Lights")
                        .connect(ceiling_lights))


# Store timestamp of last change of the ceiling lights in a Variable (via logic handler) and show
# it in the web user interface
ceiling_lights_last_change = shc.Variable(
    datetime.datetime, "ceiling lights last change",
    initial_value=datetime.datetime.fromtimestamp(0))

@ceiling_lights.trigger
@shc.handler()
async def update_lastchange():
    await ceiling_lights_last_change.write(datetime.datetime.now())

web_index_page.add_item(
    shc.web.widgets.TextDisplay(datetime.datetime, "{:%c}", "Last Change of Ceiling Lights")
    .connect(ceiling_lights_last_change))


# close shutters via button in the web user interface (stateless event, so no Variable required) 
web_index_page.add_item(
    shc.web.widgets.ButtonGroup(
        "Shutters",
        [
            shc.web.widgets.StatelessButton(shc.interfaces.knx.KNXUpDown.DOWN,
                                            shc.web.widgets.icon("arrow down"))
                .connect(knx_connection.group(shc.interfaces.knx.KNXGAD(3, 2, 1), dpt="1.008"))
        ]
    ))

# use expression syntax to switch on fan when temperature is over 25 degrees 
temperature = shc.Variable(float, "temperature")\
    .connect(knx_connection.group(shc.interfaces.knx.KNXGAD(0, 0, 1), dpt="9", init=True))
fan = shc.Variable(bool, "fan")\
    .connect(knx_connection.group(shc.interfaces.knx.KNXGAD(0, 0, 2), dpt="1"))\
    .connect(temperature.EX > 25.0)

# Start up SHC
shc.main()
```


## License

Smart Home Connect is published under the terms of the Apache License 2.0.

It's bundled with multiple third party works:

* [“Prism”](https://www.toptal.com/designers/subtlepatterns/prism/) – Subtle Patterns by Toptal Designers (Creative Commons BY-SA 3.0)

See `LICENSE` and `NOTICE` file for further information.


## Dependencies

SHC depends on the following Python packages:

* `aiohttp` and its dependencies (Apache License 2.0, MIT License, Python Software Foundation License, LGPL 2.1, 3-Clause BSD License)
* `jinja2` and `MarkupSafe` (BSD-3-Clause License)

Additional dependencies are required for some of SHC's interfaces.
They can be installed automatically via pip, by specifying the relevant 'extras' flag, e.g. `pip install smarthomeconnect[mysql]` for mysql logging support. 
 
* Logging via MySQL `[mysql]`:
    * `aiomysql` and `PyMySQL` (MIT License)
* KNX interface `[knx]`:
    * `knxdclient` (Apache License 2.0)
* DMX interface `[dmx]`:
    * `pyserial-asyncio` & `pySerial` (BSD-3-Clause License)
* MIDI interface `[midi]`:
    * `mido` (MIT License)
    * `python-rtmidi` (MIT License) incl. RTMidi (modified MIT License)
* MQTT interface `[mqtt]`:
    * `paho-mqtt` (Eclipse Public License v1.0 *or* Eclipse Distribution License v1.0)
    * `asyncio-mqtt` (BSD-3-Clause License)
* Pulseaudio interface `[pulse]`:
    * `pulsectl` and `pulsectl-asyncio` (MIT License)
* Telegram Bot interface `[telegram]`:
    * `aiogram` (MIT License) + its dependencies (BSD-3-Clause License + MPL 2.0)
* file-based persistence storage `[file_persistence]`:
    * `aiofile` & `caio` (Apache License 2.0)

In addition, the following Javascript libraries from NPM are required for the web UI frontend.
They are not included in this repository or in source distribution packages of SHC.
Instead they are downloaded and packed during Python package build and bundled in the "binary" Python packages (including "wheel" packages) of SHC:

* [Fomantic UI CSS framework](https://fomantic-ui.com/) (MIT License)
* [jQuery](https://jquery.com/) (MIT License)
* [iro.js](https://iro.js.org/) (Mozilla Public License 2.0)
* [Chart.js](https://www.chartjs.org//) (MIT License)


## Development

Feel free to open an issue on GitHub if you miss a feature or find an unexpected behaviour or bug. 
Please, consult the [documentation](https://smarthomeconnect.readthedocs.io/en/latest/) on the relevant topic and search the GitHub issues for existing reports of the issue first.

If you want to help with the development of *Smart Home Connect*, your Pull Requests are always appreciated.

### Development setup

Setting up a dev environment for SHC is simple:
Clone the git repository and install the development dependencies.
```bash
git clone https://github.com/mhthies/smarthomeconnect
cd smarthomeconnect
pip3 install -e . --group dev
```
To install additional dependencies, listed in [Dependencies](#dependencies), e.g. use:  
```bash
pip3 install -e ".[mysql,knxdclient,midi]"
```
You may want to use a virtual environment to avoid messing up your Python packages.


### Web UI Frontend Assets

Additionally, you'll need NodeJS and NPM on your machine for downloading and packing the web UI frontend asset  files.
Use the following commands to download all frontend dependencies from NPM and package them into `/shc/web/static` (using Parcel.js):
```bash
npm install
npm run build
```
When working on the web UI source files themselves (which are located in `web_ui_src`), you'll probably want to run Parcel.js in monitor mode, providing automatic re-packing and reload on every change:
```bash
npx parcel web_ui_src/main.js --dist-dir shc/web/static/pack --public-url ./
```


### Tests and Code Style

Please make sure that all the unittests are passing, when submitting a Pull Request:
```bash
pip3 install -e . --group test
python3 -m unittest
```
The web tests require Firefox and `geckodriver` to be installed on your system and the frontend assets. 

Additionally, I'd like to keep the test coverage on a high level.
To check it, you may want to determine it locally, using the `coverage` tool:
```bash
coverage run -m unittest
coverage html
# open htmlcov/index.html
``` 

We also enforce static type correctness with MyPy and Python codestyle rules with ruff.
To run the static type checks and codestyle checks locally, simply install MyPy and execute the `mypy` command in the shc project repository.

To run code linting and formating checks, using `ruff`:
```bash
ruff check .           # for linting checks
ruff format --check .  # for formating checks
``` 
All these checks are also performed by the GitHub Actions CI for Pull Requests and the master branch.

To fix errors using `ruff` use these commands:  
```bash
ruff check . --fix   # for fixing linting errors
ruff format .        # for fixing formating errors
``` 
Note that not all errors can be fixed automatically but may need your attentions.

