├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── docs ├── Makefile ├── make.bat └── source │ ├── conf.py │ └── index.rst ├── fritzhome ├── __init__.py ├── __main__.py ├── actor.py └── fritz.py ├── requirements.txt ├── setup.cfg └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | bin/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | venv/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # Installer logs 27 | pip-log.txt 28 | pip-delete-this-directory.txt 29 | 30 | # Unit test / coverage reports 31 | htmlcov/ 32 | .tox/ 33 | .coverage 34 | .cache 35 | nosetests.xml 36 | coverage.xml 37 | 38 | # Translations 39 | *.mo 40 | 41 | # Mr Developer 42 | .mr.developer.cfg 43 | .project 44 | .pydevproject 45 | 46 | # Rope 47 | .ropeproject 48 | 49 | # Django stuff: 50 | *.log 51 | *.pot 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | logs 57 | LOG_*.txt 58 | .env 59 | 60 | # PyCharm files 61 | .idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Michael Mayr 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | .PHONY:: dist up 3 | 4 | dist: 5 | # If bdist_wheel does not work: 6 | # pip install wheel twine 7 | python setup.py sdist bdist_wheel 8 | 9 | testup: 10 | twine upload -r pypitest dist/* 11 | 12 | up: 13 | twine upload dist/* 14 | 15 | init: 16 | python3 -m venv ./venv 17 | ./venv/bin/pip install -U pip wheel 18 | ./venv/bin/pip install -U -r requirements.txt 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | fritzbox-smarthome 2 | ================== 3 | 4 | **(DE) Bitte beachten**: Diese Bibliothek wird nicht mehr weiterentwickelt. 5 | 6 | **(EN) Please note:** This library is no longer being developed. 7 | 8 | Python-Bibliothek um FRITZ!Box SmartHome-Geräte (DECT 200, PowerLine 546E, ...) zu steuern und die Energiewerte auszulesen. 9 | 10 | Getestet mit: 11 | 12 | * FRITZ!Box 7390 (Firmware 06.23, 06.50+) 13 | * FRITZ!DECT 200 14 | * FRITZ!Powerline 546E 15 | 16 | Installation 17 | ------------ 18 | 19 | Es ist empfehlenswert, ein eigenes virtualenv zur Verwendung anzulegen. Unter macOS kann dieses Tool vorher mit `brew install virtualenv` installiert werden, unter Linux-Systemen hängt dies von der Distribution ab. Windows wird nicht offiziell unterstützt. 20 | 21 | ``` 22 | virtualenv ~/fritzenv 23 | . ~/fritzenv/bin/activate 24 | git clone https://github.com/DerMitch/fritzbox-smarthome.git 25 | cd fritzbox-smarthome 26 | pip install . 27 | ``` 28 | 29 | **Hinweis:** Das PyPi-Paket `fritzhome` wird nur selten aktualisiert, daher ist die Verwendung des git-Masters zu bevorzugen. 30 | 31 | SmartHome-Benutzer 32 | ------------------ 33 | 34 | Aus Sicherheisgründen ist es empfehlenswert, einen eigenen Benutzer zum SmartHome-Zugriff zu verwenden. Dazu in der FRITZ!Box: 35 | 36 | 1. Die Benutzer-basierte Anmeldung aktivieren (unter "System" -> "FRITZ!Box Benutzer") 37 | 2. Und einen neuen Benutzer Benutzer "smarthome" erstellen. Dieser braucht nur Rechte auf den Bereich "Smart Home". 38 | 39 | 40 | Verwendung 41 | ---------- 42 | 43 | Beispiele zur Verwendung der API befindet sich in der Datei `__main__.py`. 44 | 45 | Nach der Installation steht das `fritzhome` Tool zur Verfügung, mit dem die Energiedaten auf der CLI angezeigt und nach Graphite exportiert werden können. 46 | 47 | Befehle: 48 | 49 | ``` 50 | $ fritzhome [--server fritz.box] energy 51 | 52 | PowerEingang (087600000000): 35.76 Watt current, 91.500 wH total 53 | SmartHome Wohnzimmer (24:65:11:00:00:00): 56.21 Watt current, 1122.840 wH total 54 | ``` 55 | 56 | ``` 57 | $ fritzhome [--server fritz.box] [switch-on|switch-off] 24:65:11:00:00:00 58 | Switching SmartHome Wohnzimmer on 59 | ``` 60 | 61 | ``` 62 | $ fritzhome [--server ip] graphite localhost [--port 2003] [--interval 10] [--prefix smarthome] 63 | ``` 64 | 65 | Aufruf außerhalb des virtualenv 66 | ------------------------------- 67 | 68 | Das `fritzhome` kann mit Hilfe seines absoluten Pfades innerhalb des virtualenv ausgeführt werden: 69 | 70 | ``` 71 | ~/fritzenv/bin/fritzhome --help 72 | ``` 73 | 74 | Referenzen 75 | ---------- 76 | 77 | * [AHA-HTTP-Interface](https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/AHA-HTTP-Interface.pdf) 78 | * [PHP AHA Reader](http://www.tdressler.net/ipsymcon/download/fritz_aha_reader2.phps) 79 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/FRITZBoxSmarthome.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/FRITZBoxSmarthome.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/FRITZBoxSmarthome" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/FRITZBoxSmarthome" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source 10 | set I18NSPHINXOPTS=%SPHINXOPTS% source 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\FRITZBoxSmarthome.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\FRITZBoxSmarthome.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # FRITZ!Box Smarthome documentation build configuration file, created by 4 | # sphinx-quickstart on Fri Jan 30 14:46:18 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | #sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [] 32 | 33 | # Add any paths that contain templates here, relative to this directory. 34 | templates_path = ['_templates'] 35 | 36 | # The suffix of source filenames. 37 | source_suffix = '.rst' 38 | 39 | # The encoding of source files. 40 | #source_encoding = 'utf-8-sig' 41 | 42 | # The master toctree document. 43 | master_doc = 'index' 44 | 45 | # General information about the project. 46 | project = u'FRITZ!Box Smarthome' 47 | copyright = u'2015, Michael Mayr' 48 | 49 | # The version info for the project you're documenting, acts as replacement for 50 | # |version| and |release|, also used in various other places throughout the 51 | # built documents. 52 | # 53 | # The short X.Y version. 54 | version = '0.1.0' 55 | # The full version, including alpha/beta/rc tags. 56 | release = '0.1.0' 57 | 58 | # The language for content autogenerated by Sphinx. Refer to documentation 59 | # for a list of supported languages. 60 | language = 'de' 61 | 62 | # There are two options for replacing |today|: either, you set today to some 63 | # non-false value, then it is used: 64 | #today = '' 65 | # Else, today_fmt is used as the format for a strftime call. 66 | #today_fmt = '%B %d, %Y' 67 | 68 | # List of patterns, relative to source directory, that match files and 69 | # directories to ignore when looking for source files. 70 | exclude_patterns = [] 71 | 72 | # The reST default role (used for this markup: `text`) to use for all 73 | # documents. 74 | #default_role = None 75 | 76 | # If true, '()' will be appended to :func: etc. cross-reference text. 77 | #add_function_parentheses = True 78 | 79 | # If true, the current module name will be prepended to all description 80 | # unit titles (such as .. function::). 81 | #add_module_names = True 82 | 83 | # If true, sectionauthor and moduleauthor directives will be shown in the 84 | # output. They are ignored by default. 85 | #show_authors = False 86 | 87 | # The name of the Pygments (syntax highlighting) style to use. 88 | pygments_style = 'sphinx' 89 | 90 | # A list of ignored prefixes for module index sorting. 91 | #modindex_common_prefix = [] 92 | 93 | # If true, keep warnings as "system message" paragraphs in the built documents. 94 | #keep_warnings = False 95 | 96 | 97 | # -- Options for HTML output ---------------------------------------------- 98 | 99 | # The theme to use for HTML and HTML Help pages. See the documentation for 100 | # a list of builtin themes. 101 | html_theme = 'default' 102 | 103 | # Theme options are theme-specific and customize the look and feel of a theme 104 | # further. For a list of options available for each theme, see the 105 | # documentation. 106 | #html_theme_options = {} 107 | 108 | # Add any paths that contain custom themes here, relative to this directory. 109 | #html_theme_path = [] 110 | 111 | # The name for this set of Sphinx documents. If None, it defaults to 112 | # " v documentation". 113 | #html_title = None 114 | 115 | # A shorter title for the navigation bar. Default is the same as html_title. 116 | #html_short_title = None 117 | 118 | # The name of an image file (relative to this directory) to place at the top 119 | # of the sidebar. 120 | #html_logo = None 121 | 122 | # The name of an image file (within the static path) to use as favicon of the 123 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 124 | # pixels large. 125 | #html_favicon = None 126 | 127 | # Add any paths that contain custom static files (such as style sheets) here, 128 | # relative to this directory. They are copied after the builtin static files, 129 | # so a file named "default.css" will overwrite the builtin "default.css". 130 | html_static_path = ['_static'] 131 | 132 | # Add any extra paths that contain custom files (such as robots.txt or 133 | # .htaccess) here, relative to this directory. These files are copied 134 | # directly to the root of the documentation. 135 | #html_extra_path = [] 136 | 137 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 138 | # using the given strftime format. 139 | #html_last_updated_fmt = '%b %d, %Y' 140 | 141 | # If true, SmartyPants will be used to convert quotes and dashes to 142 | # typographically correct entities. 143 | #html_use_smartypants = True 144 | 145 | # Custom sidebar templates, maps document names to template names. 146 | #html_sidebars = {} 147 | 148 | # Additional templates that should be rendered to pages, maps page names to 149 | # template names. 150 | #html_additional_pages = {} 151 | 152 | # If false, no module index is generated. 153 | #html_domain_indices = True 154 | 155 | # If false, no index is generated. 156 | #html_use_index = True 157 | 158 | # If true, the index is split into individual pages for each letter. 159 | #html_split_index = False 160 | 161 | # If true, links to the reST sources are added to the pages. 162 | #html_show_sourcelink = True 163 | 164 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 165 | #html_show_sphinx = True 166 | 167 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 168 | #html_show_copyright = True 169 | 170 | # If true, an OpenSearch description file will be output, and all pages will 171 | # contain a tag referring to it. The value of this option must be the 172 | # base URL from which the finished HTML is served. 173 | #html_use_opensearch = '' 174 | 175 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 176 | #html_file_suffix = None 177 | 178 | # Output file base name for HTML help builder. 179 | htmlhelp_basename = 'FRITZBoxSmarthomedoc' 180 | 181 | 182 | # -- Options for LaTeX output --------------------------------------------- 183 | 184 | latex_elements = { 185 | # The paper size ('letterpaper' or 'a4paper'). 186 | #'papersize': 'letterpaper', 187 | 188 | # The font size ('10pt', '11pt' or '12pt'). 189 | #'pointsize': '10pt', 190 | 191 | # Additional stuff for the LaTeX preamble. 192 | #'preamble': '', 193 | } 194 | 195 | # Grouping the document tree into LaTeX files. List of tuples 196 | # (source start file, target name, title, 197 | # author, documentclass [howto, manual, or own class]). 198 | latex_documents = [ 199 | ('index', 'FRITZBoxSmarthome.tex', u'FRITZ!Box Smarthome Documentation', 200 | u'Michael Mayr', 'manual'), 201 | ] 202 | 203 | # The name of an image file (relative to this directory) to place at the top of 204 | # the title page. 205 | #latex_logo = None 206 | 207 | # For "manual" documents, if this is true, then toplevel headings are parts, 208 | # not chapters. 209 | #latex_use_parts = False 210 | 211 | # If true, show page references after internal links. 212 | #latex_show_pagerefs = False 213 | 214 | # If true, show URL addresses after external links. 215 | #latex_show_urls = False 216 | 217 | # Documents to append as an appendix to all manuals. 218 | #latex_appendices = [] 219 | 220 | # If false, no module index is generated. 221 | #latex_domain_indices = True 222 | 223 | 224 | # -- Options for manual page output --------------------------------------- 225 | 226 | # One entry per manual page. List of tuples 227 | # (source start file, name, description, authors, manual section). 228 | man_pages = [ 229 | ('index', 'fritzboxsmarthome', u'FRITZ!Box Smarthome Documentation', 230 | [u'Michael Mayr'], 1) 231 | ] 232 | 233 | # If true, show URL addresses after external links. 234 | #man_show_urls = False 235 | 236 | 237 | # -- Options for Texinfo output ------------------------------------------- 238 | 239 | # Grouping the document tree into Texinfo files. List of tuples 240 | # (source start file, target name, title, author, 241 | # dir menu entry, description, category) 242 | texinfo_documents = [ 243 | ('index', 'FRITZBoxSmarthome', u'FRITZ!Box Smarthome Documentation', 244 | u'Michael Mayr', 'FRITZBoxSmarthome', 'One line description of project.', 245 | 'Miscellaneous'), 246 | ] 247 | 248 | # Documents to append as an appendix to all manuals. 249 | #texinfo_appendices = [] 250 | 251 | # If false, no module index is generated. 252 | #texinfo_domain_indices = True 253 | 254 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 255 | #texinfo_show_urls = 'footnote' 256 | 257 | # If true, do not generate a @detailmenu in the "Top" node's menu. 258 | #texinfo_no_detailmenu = False 259 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. FRITZ!Box Smarthome documentation master file, created by 2 | sphinx-quickstart on Fri Jan 30 14:46:18 2015. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to FRITZ!Box Smarthome's documentation! 7 | =============================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | 15 | 16 | Indices and tables 17 | ================== 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | * :ref:`search` 22 | 23 | -------------------------------------------------------------------------------- /fritzhome/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | AVM Fritz!BOX SmartHome Client 3 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | """ 5 | 6 | from .fritz import FritzBox 7 | -------------------------------------------------------------------------------- /fritzhome/__main__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | """ 3 | FRITZ!Box SmartHome Client 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | """ 6 | 7 | 8 | from __future__ import print_function, division 9 | 10 | import re 11 | import time 12 | import json 13 | import socket 14 | 15 | import click 16 | 17 | from .fritz import FritzBox 18 | 19 | 20 | @click.group() 21 | @click.option('--host', default='169.254.1.1') # fritzbox "emergency" IP 22 | @click.option('--username', default='smarthome') 23 | @click.option('--password', default='smarthome') 24 | @click.pass_context 25 | def cli(context, host, username, password): 26 | """ 27 | FritzBox SmartHome Tool 28 | 29 | \b 30 | Provides the following functions: 31 | - A easy to use library for querying SmartHome actors 32 | - This CLI tool for testing 33 | - A carbon client for pipeing data into graphite 34 | """ 35 | context.obj = FritzBox(host, username, password) 36 | 37 | 38 | @cli.command() 39 | @click.pass_context 40 | def actors(context): 41 | """Display a list of actors""" 42 | fritz = context.obj 43 | fritz.login() 44 | 45 | for actor in fritz.get_actors(): 46 | click.echo("{} ({} {}; AIN {} )".format( 47 | actor.name, 48 | actor.manufacturer, 49 | actor.productname, 50 | actor.actor_id, 51 | )) 52 | if actor.has_temperature: 53 | click.echo("Temp: act {} target {}; battery (low): {}".format( 54 | actor.temperature, 55 | actor.target_temperature, 56 | actor.battery_low, 57 | )) 58 | 59 | click.echo("Temp (via get): act {} target {}".format( 60 | actor.get_temperature(), 61 | actor.get_target_temperature(), 62 | )) 63 | 64 | 65 | @cli.command() 66 | @click.option('--features', type=bool, default=False, help="Show device features") 67 | @click.pass_context 68 | def energy(context, features): 69 | """Display energy stats of all actors""" 70 | fritz = context.obj 71 | fritz.login() 72 | 73 | for actor in fritz.get_actors(): 74 | if actor.temperature is not None: 75 | click.echo("{} ({}): {:.2f} Watt current, {:.3f} wH total, {:.2f} °C".format( 76 | actor.name.encode('utf-8'), 77 | actor.actor_id, 78 | (actor.get_power() or 0.0) / 1000, 79 | (actor.get_energy() or 0.0) / 100, 80 | actor.temperature 81 | )) 82 | else: 83 | click.echo("{} ({}): {:.2f} Watt current, {:.3f} wH total, offline".format( 84 | actor.name.encode('utf-8'), 85 | actor.actor_id, 86 | (actor.get_power() or 0.0) / 1000, 87 | (actor.get_energy() or 0.0) / 100 88 | )) 89 | if features: 90 | click.echo(" Features: PowerMeter: {}, Temperatur: {}, Switch: {}".format( 91 | actor.has_powermeter, actor.has_temperature, actor.has_switch 92 | )) 93 | 94 | 95 | @cli.command() 96 | @click.argument('server') 97 | @click.option('--port', type=int, default=2003) 98 | @click.option('--interval', type=int, default=10) 99 | @click.option('--prefix', default="smarthome") 100 | @click.pass_context 101 | def graphite(context, server, port, interval, prefix): 102 | """Display energy stats of all actors""" 103 | fritz = context.obj 104 | fritz.login() 105 | sid_ttl = time.time() + 600 106 | 107 | # Find actors and create carbon keys 108 | click.echo(" * Requesting actors list") 109 | simple_chars = re.compile('[^A-Za-z0-9]+') 110 | actors = fritz.get_actors() 111 | keys = {} 112 | for actor in actors: 113 | keys[actor.name] = "{}.{}".format( 114 | prefix, 115 | simple_chars.sub('_', actor.name) 116 | ) 117 | 118 | # Connect to carbon 119 | click.echo(" * Trying to connect to carbon") 120 | timeout = 2 121 | sock = socket.socket() 122 | sock.settimeout(timeout) 123 | try: 124 | sock.connect((server, port)) 125 | except socket.timeout: 126 | raise Exception("Took over {} second(s) to connect to {}".format( 127 | timeout, server 128 | )) 129 | except Exception as error: 130 | raise Exception("unknown exception while connecting to {} - {}".format( 131 | server, error 132 | )) 133 | 134 | def send(key, value): 135 | """Send a key-value-pair to carbon""" 136 | now = int(time.time()) 137 | payload = "{} {} {}\n".format(key, value, now) 138 | sock.sendall(payload) 139 | 140 | while True: 141 | if time.time() > sid_ttl: 142 | click.echo(" * Requesting new SID") 143 | fritz.login() 144 | sid_ttl = time.time() + 600 145 | 146 | click.echo(" * Requesting statistics") 147 | for actor in actors: 148 | power = actor.get_power() 149 | total = actor.get_energy() 150 | click.echo(" -> {}: {:.2f} Watt current, {:.3f} wH total".format( 151 | actor.name, power / 1000, total / 100 152 | )) 153 | 154 | send(keys[actor.name] + '.current', power) 155 | send(keys[actor.name] + '.total', total) 156 | 157 | time.sleep(interval) 158 | 159 | 160 | @cli.command(name="switch-on") 161 | @click.argument('ain') 162 | @click.pass_context 163 | def switch_on(context, ain): 164 | """Switch an actor's power to ON""" 165 | context.obj.login() 166 | actor = context.obj.get_actor_by_ain(ain) 167 | if actor: 168 | click.echo("Switching {} on".format(actor.name)) 169 | actor.switch_on() 170 | else: 171 | click.echo("Actor not found: {}".format(ain)) 172 | 173 | 174 | @cli.command(name="switch-off") 175 | @click.argument('ain') 176 | @click.pass_context 177 | def switch_off(context, ain): 178 | """Switch an actor's power to OFF""" 179 | context.obj.login() 180 | actor = context.obj.get_actor_by_ain(ain) 181 | if actor: 182 | click.echo("Switching {} off".format(actor.name)) 183 | actor.switch_off() 184 | else: 185 | click.echo("Actor not found: {}".format(ain)) 186 | 187 | 188 | @cli.command(name="switch-state") 189 | @click.argument('ain') 190 | @click.pass_context 191 | def switch_state(context, ain): 192 | """Get an actor's power state""" 193 | context.obj.login() 194 | actor = context.obj.get_actor_by_ain(ain) 195 | if actor: 196 | click.echo("State for {} is: {}".format(ain,'ON' if actor.get_state() else 'OFF')) 197 | else: 198 | click.echo("Actor not found: {}".format(ain)) 199 | 200 | 201 | @cli.command(name="switch-toggle") 202 | @click.argument('ain') 203 | @click.pass_context 204 | def switch_toggle(context, ain): 205 | """Toggle an actor's power state""" 206 | context.obj.login() 207 | actor = context.obj.get_actor_by_ain(ain) 208 | if actor: 209 | if actor.get_state(): 210 | actor.switch_off() 211 | click.echo("State for {} is now OFF".format(ain)) 212 | else: 213 | actor.switch_on() 214 | click.echo("State for {} is now ON".format(ain)) 215 | else: 216 | click.echo("Actor not found: {}".format(ain)) 217 | 218 | 219 | @cli.command() 220 | @click.option('--format', type=click.Choice(['plain', 'json']), 221 | default='plain') 222 | @click.pass_context 223 | def logs(context, format): 224 | """Show system logs since last reboot""" 225 | fritz = context.obj 226 | fritz.login() 227 | 228 | messages = fritz.get_logs() 229 | if format == "plain": 230 | for msg in messages: 231 | merged = "{} {} {}".format(msg.date, msg.time, msg.message.encode("UTF-8")) 232 | click.echo(merged) 233 | 234 | if format == "json": 235 | entries = [msg._asdict() for msg in messages] 236 | click.echo(json.dumps({ 237 | "entries": entries, 238 | })) 239 | 240 | 241 | if __name__ == '__main__': 242 | cli() 243 | -------------------------------------------------------------------------------- /fritzhome/actor.py: -------------------------------------------------------------------------------- 1 | """ 2 | AVM SmartHome Actor 3 | ~~~~~~~~~~~~~~~~~~~ 4 | """ 5 | 6 | import logging 7 | logger = logging.getLogger(__name__) 8 | 9 | 10 | class Actor(object): 11 | """ 12 | Represents a single SmartHome actor. 13 | You usally don't create that class yourself, use FritzBox.get_actors 14 | instead. 15 | """ 16 | 17 | def __init__(self, fritzbox, device): 18 | self.box = fritzbox 19 | 20 | self.actor_id = device.attrib['identifier'] 21 | self.device_id = device.attrib['id'] 22 | self.name = device.find('name').text 23 | self.fwversion = device.attrib['fwversion'] 24 | self.productname = device.attrib['productname'] 25 | self.manufacturer = device.attrib['manufacturer'] 26 | self.functionbitmask = int(device.attrib['functionbitmask']) 27 | 28 | self.has_powermeter = self.functionbitmask & (1 << 7) > 0 29 | self.has_temperature = self.functionbitmask & (1 << 8) > 0 30 | self.has_switch = self.functionbitmask & (1 << 9) > 0 31 | self.has_heating_controller = self.functionbitmask & (1 << 6) > 0 32 | 33 | self.temperature = 0.0 34 | if self.has_temperature: 35 | if device.find("temperature").find("celsius").text is not None: 36 | self.temperature = int(device.find("temperature").find("celsius").text) / 10 37 | else: 38 | logger.info("Actor " + self.name + " seems offline. Returning None as temperature.") 39 | self.temperature = None 40 | 41 | self.target_temperature = 0.0 42 | self.target_temperature = 0.0 43 | self.battery_low = True 44 | if self.has_heating_controller: 45 | hkr = device.find("hkr") 46 | if hkr is not None: 47 | for child in hkr: 48 | if child.tag == 'tist': 49 | self.temperature = self.__get_temp(child.text) 50 | elif child.tag == 'tsoll': 51 | self.target_temperature = self.__get_temp(child.text) 52 | elif child.tag == 'batterylow': 53 | self.battery_low = (child.text == '1') 54 | 55 | def switch_on(self): 56 | """ 57 | Set the power switch to ON. 58 | """ 59 | return self.box.set_switch_on(self.actor_id) 60 | 61 | def switch_off(self): 62 | """ 63 | Set the power switch to OFF. 64 | """ 65 | return self.box.set_switch_off(self.actor_id) 66 | 67 | def get_state(self): 68 | """ 69 | Get the current switch state. 70 | """ 71 | return bool( 72 | int(self.box.homeautoswitch("getswitchstate", self.actor_id)) 73 | ) 74 | 75 | def get_present(self): 76 | """ 77 | Check if the registered actor is currently present (reachable). 78 | """ 79 | return bool( 80 | int(self.box.homeautoswitch("getswitchpresent", self.actor_id)) 81 | ) 82 | 83 | def get_power(self): 84 | """ 85 | Returns the current power usage in milliWatts. 86 | Attention: Returns None if the value can't be queried or is unknown. 87 | """ 88 | value = self.box.homeautoswitch("getswitchpower", self.actor_id) 89 | return int(value) if value.isdigit() else None 90 | 91 | def get_energy(self): 92 | """ 93 | Returns the consumed energy since the start of the statistics in Wh. 94 | Attention: Returns None if the value can't be queried or is unknown. 95 | """ 96 | value = self.box.homeautoswitch("getswitchenergy", self.actor_id) 97 | return int(value) if value.isdigit() else None 98 | 99 | def get_temperature(self): 100 | """ 101 | Returns the current environment temperature. 102 | Attention: Returns None if the value can't be queried or is unknown. 103 | """ 104 | #raise NotImplementedError("This should work according to the AVM docs, but don't...") 105 | value = self.box.homeautoswitch("gettemperature", self.actor_id) 106 | if value.isdigit(): 107 | self.temperature = float(value)/10 108 | else: 109 | self.temperature = None 110 | return self.temperature 111 | 112 | def __get_temp(self, value): 113 | # Temperature is send from fritz.box a little weird 114 | if value.isdigit(): 115 | value = float(value) 116 | if value == 253: 117 | return 0 118 | elif value == 254: 119 | return 30 120 | else: 121 | return value / 2 122 | else: 123 | return None 124 | 125 | def get_target_temperature(self): 126 | """ 127 | Returns the actual target temperature. 128 | Attention: Returns None if the value can't be queried or is unknown. 129 | """ 130 | value = self.box.homeautoswitch("gethkrtsoll", self.actor_id) 131 | self.target_temperature = self.__get_temp(value) 132 | return self.target_temperature 133 | 134 | def set_temperature(self, temp): 135 | """ 136 | Sets the temperature in celcius 137 | """ 138 | 139 | # Temperature is send to fritz.box a little weird 140 | param = 16 + ( ( temp - 8 ) * 2 ) 141 | if param < 16: 142 | param = 253 143 | logger.info("Actor " + self.name + ": Temperature control set to off") 144 | elif param >= 56: 145 | param = 254 146 | logger.info("Actor " + self.name + ": Temperature control set to on") 147 | else: 148 | logger.info("Actor " + self.name + ": Temperature control set to " + str(temp)) 149 | 150 | return self.box.homeautoswitch("sethkrtsoll", self.actor_id, param) 151 | 152 | def get_consumption(self, timerange="10"): 153 | """ 154 | Return the energy report for the device. 155 | """ 156 | return self.box.get_consumption(self.device_id, timerange) 157 | 158 | def reset_consumption(self): 159 | """ 160 | Resets the energy data stored on fritzbox for reports. 161 | """ 162 | return self.box.reset_consumption(self.device_id) 163 | 164 | def __repr__(self): 165 | return u"".format(self.name) 166 | -------------------------------------------------------------------------------- /fritzhome/fritz.py: -------------------------------------------------------------------------------- 1 | """ 2 | AVM Fritz!BOX SmartHome Client 3 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | 5 | Dokumentation zum Login-Verfahren: 6 | http://www.avm.de/de/Extern/files/session_id/AVM_Technical_Note_-_Session_ID.pdf 7 | 8 | Smart Home Interface: 9 | http://www.avm.de/de/Extern/files/session_id/AHA-HTTP-Interface.pdf 10 | """ 11 | 12 | from __future__ import print_function, division 13 | 14 | import re 15 | import hashlib 16 | from collections import namedtuple 17 | from xml.etree import ElementTree as ET 18 | 19 | from requests import Session 20 | try: 21 | from bs4 import BeautifulSoup 22 | except ImportError: 23 | BeautifulSoup = None 24 | 25 | from .actor import Actor 26 | 27 | 28 | Device = namedtuple("Device", "deviceid connectstate switchstate") 29 | LogEntry = namedtuple("LogEntry", "date time message hash") 30 | 31 | 32 | class FritzBox(object): 33 | """ 34 | Provides easy access to a FritzBOX's SmartHome functions, 35 | which are poorly documented by AVM... 36 | 37 | A note about SIDs: 38 | They expire after some time. If you have a long-running daemon, 39 | you should call login() every 10 minutes or so else you'll get 40 | nice 403 errors. 41 | """ 42 | 43 | def __init__(self, ip, username, password, use_tls=False): 44 | if use_tls: 45 | self.base_url = 'https://' + ip 46 | else: 47 | self.base_url = 'http://' + ip 48 | self.username = username 49 | self.password = password 50 | self.sid = None 51 | 52 | self.session = Session() 53 | 54 | def login(self): 55 | """ 56 | Try to login and set the internal session id. 57 | 58 | Please note: 59 | - Any failed login resets all existing session ids, even of 60 | other users. 61 | - SIDs expire after some time 62 | """ 63 | response = self.session.get(self.base_url + '/login_sid.lua', timeout=10) 64 | xml = ET.fromstring(response.text) 65 | if xml.find('SID').text == "0000000000000000": 66 | challenge = xml.find('Challenge').text 67 | url = self.base_url + "/login_sid.lua" 68 | response = self.session.get(url, params={ 69 | "username": self.username, 70 | "response": self.calculate_response(challenge, self.password), 71 | }, timeout=10) 72 | xml = ET.fromstring(response.text) 73 | sid = xml.find('SID').text 74 | if xml.find('SID').text == "0000000000000000": 75 | blocktime = int(xml.find('BlockTime').text) 76 | exc = Exception("Login failed, please wait {} seconds".format( 77 | blocktime 78 | )) 79 | exc.blocktime = blocktime 80 | raise exc 81 | self.sid = sid 82 | return sid 83 | 84 | def calculate_response(self, challenge, password): 85 | """Calculate response for the challenge-response authentication""" 86 | to_hash = (challenge + "-" + password).encode("UTF-16LE") 87 | hashed = hashlib.md5(to_hash).hexdigest() 88 | return "{0}-{1}".format(challenge, hashed) 89 | 90 | # 91 | # Useful public methods 92 | # 93 | 94 | def get_actors(self): 95 | """ 96 | Returns a list of Actor objects for querying SmartHome devices. 97 | 98 | This is currently the only working method for getting temperature data. 99 | """ 100 | devices = self.homeautoswitch("getdevicelistinfos") 101 | xml = ET.fromstring(devices) 102 | 103 | actors = [] 104 | for device in xml.findall('device'): 105 | actors.append(Actor(fritzbox=self, device=device)) 106 | 107 | return actors 108 | 109 | def get_actor_by_ain(self, ain): 110 | """ 111 | Return a actor identified by it's ain or return None 112 | """ 113 | for actor in self.get_actors(): 114 | if actor.actor_id == ain: 115 | return actor 116 | 117 | # 118 | # "Private" methods 119 | # 120 | 121 | def homeautoswitch(self, cmd, ain=None, param=None): 122 | """ 123 | Call a switch method. 124 | Should only be used by internal library functions. 125 | """ 126 | assert self.sid, "Not logged in" 127 | params = { 128 | 'switchcmd': cmd, 129 | 'sid': self.sid, 130 | } 131 | if param is not None: 132 | params['param'] = param 133 | if ain: 134 | params['ain'] = sanitize_ain(ain) 135 | 136 | url = self.base_url + '/webservices/homeautoswitch.lua' 137 | response = self.session.get(url, params=params, timeout=10) 138 | response.raise_for_status() 139 | return response.text.strip().encode('utf-8') 140 | 141 | def get_switch_actors(self): 142 | """ 143 | Get information about all actors 144 | 145 | This needs 1+(5n) requests where n = number of actors registered 146 | 147 | Deprecated, use get_actors instead. 148 | 149 | Returns a dict: 150 | [ain] = { 151 | 'name': Name of actor, 152 | 'state': Powerstate (boolean) 153 | 'present': Connected to server? (boolean) 154 | 'power': Current power consumption in mW 155 | 'energy': Used energy in Wh since last energy reset 156 | 'temperature': Current environment temperature in celsius 157 | } 158 | """ 159 | actors = {} 160 | for ain in self.homeautoswitch("getswitchlist").split(','): 161 | actors[ain] = { 162 | 'name': self.homeautoswitch("getswitchname", ain), 163 | 'state': bool(self.homeautoswitch("getswitchstate", ain)), 164 | 'present': bool(self.homeautoswitch("getswitchpresent", ain)), 165 | 'power': self.homeautoswitch("getswitchpower", ain), 166 | 'energy': self.homeautoswitch("getswitchenergy", ain), 167 | 'temperature': self.homeautoswitch("getswitchtemperature", ain), 168 | } 169 | return actors 170 | 171 | def set_switch_on(self, ain): 172 | """Switch the power of a actor ON""" 173 | return self.homeautoswitch('setswitchon', ain) 174 | 175 | def set_switch_off(self, ain): 176 | """Switch the power of a actor OFF""" 177 | return self.homeautoswitch('setswitchoff', ain) 178 | 179 | def set_switch_toggle(self, ain): 180 | """Toggle a power switch and return the new state""" 181 | return self.homeautoswitch('setswitchtoggle', ain) 182 | 183 | # 184 | # DeviceID based methods 185 | # 186 | # Inspired by: 187 | # https://github.com/valpo/fritzbox/blob/master/fritzbox/fritzautohome.py 188 | # 189 | 190 | def get_devices(self): 191 | """ 192 | Return a list of devices. 193 | Deprecated, use get_actors instead. 194 | """ 195 | url = self.base_url + '/net/home_auto_query.lua' 196 | response = self.session.get(url, params={ 197 | 'sid': self.sid, 198 | 'command': 'AllOutletStates', 199 | 'xhr': 0, 200 | }, timeout=15) 201 | response.raise_for_status() 202 | data = response.json() 203 | count = int(data["Outlet_count"]) 204 | devices = [] 205 | for i in range(1, count + 1): 206 | device = Device( 207 | int(data["DeviceID_{0}".format(i)]), 208 | int(data["DeviceConnectState_{0}".format(i)]), 209 | int(data["DeviceSwitchState_{0}".format(i)]) 210 | ) 211 | devices.append(device) 212 | return devices 213 | 214 | def get_consumption(self, deviceid, timerange="10"): 215 | """ 216 | Return all available energy consumption data for the device. 217 | You need to divice watt_values by 100 and volt_values by 1000 218 | to get the "real" values. 219 | 220 | :return: dict 221 | """ 222 | tranges = ("10", "24h", "month", "year") 223 | if timerange not in tranges: 224 | raise ValueError( 225 | "Unknown timerange. Possible values are: {0}".format(tranges) 226 | ) 227 | 228 | url = self.base_url + "/net/home_auto_query.lua" 229 | response = self.session.get(url, params={ 230 | 'sid': self.sid, 231 | 'command': 'EnergyStats_{0}'.format(timerange), 232 | 'id': deviceid, 233 | 'xhr': 0, 234 | }, timeout=15) 235 | response.raise_for_status() 236 | 237 | data = response.json() 238 | result = {} 239 | 240 | # Single result values 241 | values_map = { 242 | 'MM_Value_Amp': 'mm_value_amp', 243 | 'MM_Value_Power': 'mm_value_power', 244 | 'MM_Value_Volt': 'mm_value_volt', 245 | 246 | 'EnStats_average_value': 'enstats_average_value', 247 | 'EnStats_max_value': 'enstats_max_value', 248 | 'EnStats_min_value': 'enstats_min_value', 249 | 'EnStats_timer_type': 'enstats_timer_type', 250 | 251 | 'sum_Day': 'sum_day', 252 | 'sum_Month': 'sum_month', 253 | 'sum_Year': 'sum_year', 254 | } 255 | for avm_key, py_key in values_map.items(): 256 | result[py_key] = int(data[avm_key]) 257 | 258 | # Stats counts 259 | count = int(data["EnStats_count"]) 260 | watt_values = [None for i in range(count)] 261 | volt_values = [None for i in range(count)] 262 | for i in range(1, count + 1): 263 | watt_values[i - 1] = int(data["EnStats_watt_value_{}".format(i)]) 264 | volt_values[i - 1] = int(data["EnStats_volt_value_{}".format(i)]) 265 | 266 | result['watt_values'] = watt_values 267 | result['volt_values'] = volt_values 268 | 269 | return result 270 | 271 | def reset_consumption(self, deviceid): 272 | """ 273 | Resets the energy data stored on fritzbox for reports. 274 | 275 | Atention: User needs permissions for "Alle Einstellungen der FRITZ!Box sehen und bearbeiten" 276 | 277 | :return: bool 278 | """ 279 | 280 | url = self.base_url + "/net/home_auto_query.lua" 281 | response = self.session.post(url, data={ 282 | 'sid': self.sid, 283 | 'command': 'ResetEnergyData', 284 | 'id': deviceid, 285 | 'xhr': 0, 286 | }, headers={ 287 | 'Content-Type': 'application/x-www-form-urlencoded' 288 | }, timeout=15) 289 | response.raise_for_status() 290 | 291 | if response.text == "": 292 | raise Exception("consumption reset failed, missing user permission to change settings ?") 293 | 294 | return response.json()["RequestResult"] == True 295 | 296 | def get_logs(self): 297 | """ 298 | Return the system logs since the last reboot. 299 | """ 300 | assert BeautifulSoup, "Please install bs4 to use this method" 301 | 302 | url = self.base_url + "/system/syslog.lua" 303 | response = self.session.get(url, params={ 304 | 'sid': self.sid, 305 | 'stylemode': 'print', 306 | }, timeout=15) 307 | response.raise_for_status() 308 | 309 | entries = [] 310 | tree = BeautifulSoup(response.text) 311 | rows = tree.find('table').find_all('tr') 312 | for row in rows: 313 | columns = row.find_all("td") 314 | date = columns[0].string 315 | time = columns[1].string 316 | message = columns[2].find("a").string 317 | 318 | merged = "{} {} {}".format(date, time, message.encode("UTF-8")) 319 | msg_hash = hashlib.md5(merged).hexdigest() 320 | entries.append(LogEntry(date, time, message, msg_hash)) 321 | return entries 322 | 323 | 324 | def sanitize_ain(ain): 325 | """ 326 | Remove invalid characters from an AIN. 327 | """ 328 | return re.sub('[^0-9]', '', ain) 329 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | click 3 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | 2 | from setuptools import setup, find_packages 3 | 4 | from codecs import open 5 | from os import path 6 | 7 | here = path.abspath(path.dirname(__file__)) 8 | 9 | try: 10 | with open(path.join(here, "README.md"), encoding="utf-8") as f: 11 | long_description = f.read() 12 | except FileNotFoundError: 13 | long_description = "(README.md not found)" 14 | 15 | setup( 16 | name="fritzhome", 17 | version="1.0.5", 18 | 19 | description="Query information from your FRITZ!Box (mostly energy)", 20 | long_description=long_description, 21 | 22 | url="https://github.com/DerMitch/fritzbox-smarthome", 23 | 24 | author="Michael Mayr", 25 | author_email="michael@dermitch.de", 26 | 27 | license="MIT", 28 | 29 | classifiers=[ 30 | 'Development Status :: 4 - Beta', 31 | 'License :: OSI Approved :: MIT License', 32 | 'Programming Language :: Python :: 2', 33 | 'Programming Language :: Python :: 2.7', 34 | 'Programming Language :: Python :: 3', 35 | 'Programming Language :: Python :: 3.5', 36 | 'Programming Language :: Python :: 3.6', 37 | ], 38 | 39 | keywords="fritzbox smarthome avm energy", 40 | 41 | packages=["fritzhome"], 42 | 43 | install_requires=[ 44 | 'requests>=2.12.0', 45 | 'click>=6.0.0', 46 | ], 47 | 48 | entry_points={ 49 | 'console_scripts': [ 50 | 'fritzhome=fritzhome.__main__:cli', 51 | ], 52 | } 53 | ) 54 | --------------------------------------------------------------------------------