├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── doc ├── architecture.odg ├── architecture.png ├── overview.md └── screenshot.png ├── plantgateway ├── plantgw.yaml ├── plantgw ├── __init__.py └── plantgw.py ├── pylintrc ├── requirements.txt ├── setup.cfg ├── setup.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | ### Python template 2 | # Byte-compiled / optimized / DLL files 3 | __pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | env/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | # Created by .ignore support plugin (hsz.mobi) 62 | .idea/ 63 | MANIFEST 64 | venv/ 65 | *.swp 66 | release.sh -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: python 3 | install: pip install -U tox 4 | matrix: 5 | fast_finish: true 6 | include: 7 | - python: '3.6' 8 | env: TOXENV=flake8 9 | - python: '3.6' 10 | env: TOXENV=pylint 11 | script: travis_wait tox 12 | deploy: 13 | provider: pypi 14 | user: christian.kuehnel 15 | password: 16 | secure: lpVC2QzACm5JicuhmxVeareZHLH4IPQsjpiMpUS6+OybZkGnIQyHI4qhcJ7TAgh4w5miwIXCNz1XFcPEZJKfpAC6WyuHiEeMZv4X2moCrFBTJZVmeBsO3UUIF+aixxeRYhR6ZX17VZczxfqF6K51L2twDmLbItzWS9mM998xOeHKqP48cSkiuU0ER8dXwZObLpLjitzxYvrtLRxpX6r5+A67rgwmsLHQyQAEMzlFURFaP7vMngEjGqIFUxXw4wEFsCXnfL4WWIo0awsJf2fYRZpYUUY4Hv2ZlspIZDojALKaRKjrEjyoxCXHG0rKmT7oPTJCPWJ+lIEMxJsZRGc7ZjDZt0GePvGDPNfaneqeQo1eBg5OqHrFe9IXlVDjNs/pV0dEJCv7fGsYHUXB5GHPLCioplT4HkDNTP9kpxAqBKMWVKCeAhB9+sLAmeuUkiH0vcZZhEJI370i5tFb3mzamdhZXIKUUHLaNgFN/XuohPPK9APYIjJl6AmtgysRgqWkpmETbTl3BrC4sMqdWPjLkUAepwGyuhL/kRKzxW0V0npwAWX9GnQdOi1dYuD50GlZOyjfxSTfFUs8ijIWEndwIeM3AiIP1OxKxTqsfY8zBwc58AMVArCGvsvjQb6PWt3JnDtcfex5GromiVzYguk04z2NGAPmqO9tDsEM8GnDM4g= 17 | on: 18 | tags: true 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # plantgateway 2 | Bluetooth LE to mqtt gateway for Xiaomi Mi plant sensors. For more details see the [documentation overview](doc/overview.md). 3 | 4 | # Use case 5 | For many setups the Xiaomi Mi plant sensors are too far away from your 6 | home server to connect directly via Bluetooth LE. 7 | In such a scenario the plantgatway will poll the data from a list of 8 | Xiaomi Mi plant sensors via Bluetooth LE using 9 | [miflora](https://github.com/open-homeautomation/miflora). 10 | The data is then published via mqtt to your home automation server. 11 | 12 | The plantgateway is intended to be run on a small Linux machine (e.g. 13 | [Raspberry Pi](https://www.raspberrypi.org/) 14 | or a [C.H.I.P](https://getchip.com/)) that has both Bluetooth LE and WiFi. 15 | 16 | # installation & update 17 | * install [python 3.4](https://www.python.org/) (or above) 18 | and [pip](https://pip.pypa.io/en/stable/installing/) 19 | ``` 20 | sudo apt-get install python3-pip build-essential libglib2.0-dev libyaml-dev 21 | ``` 22 | * install the plant gateway from pypi: 23 | ``` 24 | sudo pip install --upgrade plantgateway 25 | ``` 26 | or if you have multiple python and pip installations: 27 | ``` 28 | sudo pip3 install --upgrade plantgateway 29 | ``` 30 | * To update your installation just run pip again. 31 | 32 | If you have problems with the PyYaml installation, update your pip version 33 | with `sudo pip3 install --upgrade pip` and try again. 34 | 35 | # configuration 36 | Copy the [plantgw.yaml](plantgw.yaml) (in this repository) to your home directory and 37 | rename it to ".plantgw.yaml". 38 | Then change this file to match your requirements. 39 | 40 | # execution 41 | After the installation with pip you can simply run the tool from the command line: 42 | ``` 43 | plantgateway 44 | ``` 45 | There are no command line parameters and there is no interaction required. 46 | You probably want to add the script to your cron tab to be executed 47 | in regular intervals (e.q. every hour). 48 | 49 | # integration in home automation 50 | 51 | ## HomeAssistant 52 | If you enable the [MQTT discovery](https://www.home-assistant.io/docs/mqtt/discovery/) 53 | feature by setting the `discovery_prefix` parameter in 54 | the config file, all configured sensors are automatically available in HomeAssistant. 55 | To monitor the state of your plants, you can use the 56 | ["plant" component](https://www.home-assistant.io/components/plant/). 57 | 58 | 59 | ## fhem 60 | To check your plants in the home automation tool [fhem](http://fhem.de/), 61 | you can use the 62 | [gardener](https://github.com/ChristianKuehnel/fhem-gardener) module. 63 | The installation is explained on the github page of the module. 64 | 65 | If you haven't done so, you need to configure your MQTT server in fhem with 66 | a [MQTT](http://fhem.de/commandref.html#MQTT) module. 67 | For each sensor you have, set up a [MQTT_Device](http://fhem.de/commandref.html#MQTT_DEVICE) 68 | and make it auto subscribe to the topic 69 | you configured in the plantgateway: 70 | ``` 71 | define MQTT_Device 72 | attr autoSubscribeReadings //+ 73 | ``` 74 | 75 | After that configure the gardener to match your requirements 76 | 77 | # Security 78 | A remark on security: 79 | Before running your MQTT server on the internet make sure that you enable 80 | SSL/TLS encryption and client authentication. 81 | 82 | # Problem analysis 83 | In case you have any problem with plantgateway, please check: 84 | 85 | - Is you configuration file a valid YAML file? 86 | - Does your Bluetooth dongle support Bluetooh Low Energy? Check with `sudo hcitool lescan`, this should list all Low Energy devices. 87 | - If you have connection issues, please try a system update `sudo apt update; sudo apt dist-upgrade`. This fixes these issues usually. 88 | 89 | If all this does not help, please file a bug ticket in github. 90 | 91 | # License 92 | Unless stated otherwise all software in this repository is licensed under the Apache License 2.0 93 | http://www.apache.org/licenses/LICENSE-2.0 94 | -------------------------------------------------------------------------------- /doc/architecture.odg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChristianKuehnel/plantgateway/1be6d51a7193134db50bfc23a7d460e65dd6f5df/doc/architecture.odg -------------------------------------------------------------------------------- /doc/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChristianKuehnel/plantgateway/1be6d51a7193134db50bfc23a7d460e65dd6f5df/doc/architecture.png -------------------------------------------------------------------------------- /doc/overview.md: -------------------------------------------------------------------------------- 1 | # Goal 2 | 3 | * Get an email when my plants need water and/or fertilizer. 4 | * Make my plants happy. 5 | * Collect some data for the sake of data colleciton. 6 | 7 | # Architecture 8 | 9 | The basic idea for the plantgateway is to read the sensor data from the Xiaomi Mi plant sensors via Bluetooth LE and send it via MQTT to the home automation server. 10 | 11 | ![architecture](architecture.png) 12 | 13 | This should help to word around the limited range of Bluetooth LE. It will also allow to collect the sensor data from different location in one single home automation system. 14 | 15 | # Hardware 16 | Here's the list of hardware components I'm using. 17 | 18 | ## Sensors 19 | 20 | I'm using the [Xiaomi Mi plant sensors](http://www.gearbest.com/other-garden-supplies/pp_373947.html). The cost about 12 EUR when ordering from China. 21 | 22 | Note: If you order it from China, you might have to pay for import tax. 23 | 24 | ![Sensor](https://ae01.alicdn.com/kf/HTB1RjLXKVXXXXXyXpXXq6xXFXXX5/Original-Xiaomi-Mi-Plant-Flowers-Tester-Pot-Soil-Moisture-Humidity-Temperature-Light-Garden-Monitor-Garden-Testing.jpg) 25 | 26 | Features: 27 | 28 | * Bluetooth LE interface 29 | * integrated coin cell battery, should last a year 30 | * It can measure these values 31 | * moisture in % 32 | * conductivity in us/cm (which is somehow related to fertilizer) 33 | * temperature in °C 34 | * brightness in lux 35 | * security 36 | * None. 37 | * Seariously, none. 38 | * Really anyone in range can read the sensors. 39 | 40 | 41 | ## Bluetooth LE adapter 42 | 43 | For the machines that do not have an integrated Bluetooth LE adapter, I'm using a [LogiLink BT0015 USB bluetooth V4.0 EDR Class1 Micro](https://www.amazon.de/gp/product/B0096Y2HFW/ref=ox_sc_act_title_2?ie=UTF8&psc=1&smid=A3JWKAKR8XB7XF 44 | Gateway). But basically any Bluetooth LE adapter that is supported by the linux kernel should do. 45 | 46 | ## Gateway 47 | 48 | Since the range of Bluetooth LE is quite limited. In my apartment the range is about 5 meters and might go through one wall if I'm lucky. So I need some gateway near the sensors. 49 | 50 | In my current solution I'm using a Rasberry Pi to read the sensor data via Bluetooth LE. 51 | 52 | In my planned solution I want to use a [C.H.I.P](https://getchip.com/pages/chip) to do the same thing in a smaller and cheaper way. 53 | 54 | * ARM chip, runs Linux 55 | * Has WiFi and Bluetooth LE integrated 56 | * Costs only 9 $ 57 | * But these devices out of stock at the moment, so I'll have to wait 58 | 59 | ## Home Automation server 60 | 61 | Use whatever you want, I have a [Turris Omnia](https://omnia.turris.cz/en/) router running [OpenWRT](https://openwrt.org/). 62 | 63 | # Software 64 | 65 | And this is the software setup for the hardeware mentioned above. 66 | 67 | ## plantgateway 68 | 69 | The [plantgateway](https://github.com/ChristianKuehnel/plantgateway) (this project) reads the sensor data via Bluetooth LE and sends it via MQTT to the home automation server. 70 | 71 | 72 | ## Home Automation solution 73 | 74 | I'm running [Home Assistant](https://home-assistant.io/) on [Alpine Linux](https://alpinelinux.org/) inside a LXC container. Alpine Linux has a very small footprint and is well suited to be used in containers. 75 | 76 | About Home Assistant: 77 | 78 | * Like: 79 | * Python based 80 | * Many plugins available 81 | * Easier to set up and maintain than FHEM (what I used before) 82 | * does what it's supposed to do 83 | * Dislike: 84 | * no real complaints so far... 85 | 86 | There is now the component [plant monitor](https://home-assistant.io/components/plant/) available as part of Home Assistant. It will monitor the status of your plants and you can trigger notifications in case of problems. 87 | 88 | ## MQTT server 89 | 90 | I'm using [mosquitto](https://mosquitto.org/), again running on Alpine Linux inside a LXC container) 91 | 92 | Security: 93 | 94 | * available as package in Alpine Linux 95 | * authentication via username and password 96 | * TLS encryption, based on certificates from [Let's Encrypt](https://letsencrypt.org/) 97 | * The ACME client is also available as [package](https://pkgs.alpinelinux.org/package/v3.3/community/x86/letsencrypt) on Alpine Linux and works out of the box 98 | * remark: some MQTT clients (e.g. from FHEM) do not support client certificates, but all do support TLS and username/password 99 | 100 | If you are running MQTT for critical applications, you might want to [monitor the MQTT server from Nagios/Icinga2](https://github.com/jpmens/check-mqtt). 101 | 102 | 103 | # Devleopment tools / libraries 104 | 105 | To help with the devleopment I can recommend these tools: 106 | 107 | ## Debugging MQTT 108 | 109 | To debug mqtt related things, I'm using [MQTT.fx](http://mqttfx.jfx4ee.org/). This tool allows you to send and receive messages via MQTT. It helps to figure out, if you really did what you wanted to do. 110 | 111 | ## reverse engineering the bluetooth communication 112 | 113 | You can reverse engieer the protocol by just watching the Xiaomi Plant app: 114 | 115 | 1. Enable the Bluetooth HCI logging on your phone (On your Android phone go to settings -> developer options -> enable bluetooth HCI logging) 116 | 1. Install and run the [Flower care App](https://play.google.com/store/apps/details?id=com.huahuacaocao.flowercare) and perform the operations you want to reverse engineer. 117 | 1. Download the /sdcard/hci.log file from the phone to a PC 118 | 1. Open the log file in [Wireshark](https://www.wireshark.org/) and guess what's going on 119 | 1. Implement the operations yourself to see if you got the right commands 120 | 1. Then implement a nice API around that for everyone to use and publish it :) 121 | 122 | A lot of valueable information about the sensor and the protocol can be found here in this [blog post](https://www.open-homeautomation.com/de/2016/08/23/reverse-engineering-the-mi-plant-sensor/). 123 | 124 | ## bluepy 125 | 126 | For the communication via Bluetooth LE I'm using [bluepy](https://github.com/IanHarvey/bluepy). It offers access to the GATT protocol in a straight forward way. This is much more convenient than writing a command line wrapper for the linux command gatttool. 127 | 128 | ## paho-mqtt 129 | 130 | For the communication with the MQTT server there is also a very convenient library for python: [paho-mqtt](https://eclipse.org/paho/clients/python/docs/) It also offers a very easy solution for publishing data. 131 | -------------------------------------------------------------------------------- /doc/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChristianKuehnel/plantgateway/1be6d51a7193134db50bfc23a7d460e65dd6f5df/doc/screenshot.png -------------------------------------------------------------------------------- /plantgateway: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ############################################## 3 | # 4 | # This is open source software licensed under the Apache License 2.0 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | ############################################## 8 | 9 | from plantgw.plantgw import PlantGateway, SensorConfig 10 | import sys 11 | 12 | 13 | def main(): 14 | pg = PlantGateway() 15 | failed_sensors = pg.process_all() 16 | if len(failed_sensors) > 0: 17 | print('Could not get data from {}sensor(s): {}.'.format( 18 | len(failed_sensors), 19 | SensorConfig.get_name_string(failed_sensors))) 20 | pg.stop_client() 21 | # only count the sensors that are NOT fail silent 22 | num_failed = len([s for s in failed_sensors if not s.fail_silent]) 23 | sys.exit(num_failed) 24 | 25 | 26 | if __name__ == '__main__': 27 | main() 28 | -------------------------------------------------------------------------------- /plantgw.yaml: -------------------------------------------------------------------------------- 1 | # Template for configuration file of the plant gateway 2 | # copy this file to your home directory and rename it to ".plantgw.yaml" (starting with a "."). 3 | 4 | # mqtt configuration, replace this with the configuration of your mqtt server 5 | mqtt: 6 | #url of your mqtt server, madatory 7 | server: my-mqtt-server 8 | 9 | # If this is enabled, plantgateway will announce all plants via the MQTT Discovery 10 | # feature of Home Assistant in this MQTT prefix. For details see: 11 | # https://www.home-assistant.io/docs/mqtt/discovery/ 12 | discovery_prefix: homeassistant 13 | 14 | #prefix of the topic where the sensor data will be published, mandatory 15 | prefix: some/prefix/my/plants 16 | #terminate topic with a trailing slash, optional as defaults to True 17 | #trailing_slash: False 18 | 19 | #port of the mqtt server, optional if using 8883 20 | #port: 8883 21 | #client_id to use with the mqtt server, optional as defaults to unique numeric identifier 22 | #client_id: PlantGateway 23 | 24 | #credentials for the mqtt server, optional if you do not use authentication 25 | #user: 26 | #password: 27 | 28 | #path to ssl/tls ca file 29 | #ca_cert: /etc/ssl/certs/ 30 | 31 | #format for timestamp string using strftime(), optional as defaults to ISO8601 format 32 | #timestamp_format: "%d/%m/%y %H:%M:%S" 33 | 34 | # Select the bluetooth interface to be used. 35 | # If this parameter is not defined, interface 0 will be used. 36 | # 0 = /dev/hci0 37 | # 1 = /dev/hci1 38 | # ... 39 | # interface: 0 40 | 41 | # sensor configuration, replace this with the configuration of your sensors 42 | sensors: 43 | # bluetooth mac of the sensor, mandatory 44 | - mac: 11:22:33:44:55:66 45 | # alias to be used for the sensor, optional 46 | alias: myplant 47 | - mac: 22:33:44:55:66:77 48 | alias: otherplant 49 | # If the "fail_silent" flag is set, there will NOT be an error, if the data cannot be 50 | # read from this sensor. This is useful, if you have some sensors that are really far 51 | # away and may fail some times. 52 | fail_silent: 53 | 54 | # path where log file shall be stored, optional 55 | #logfile: plantgw.log 56 | 57 | # option for debug logging, optional 58 | #debug: 59 | -------------------------------------------------------------------------------- /plantgw/__init__.py: -------------------------------------------------------------------------------- 1 | """Plantgateway version number.""" 2 | 3 | __version__ = '0.7.1-dev' 4 | -------------------------------------------------------------------------------- /plantgw/plantgw.py: -------------------------------------------------------------------------------- 1 | """Forward measurements from Xiaomi Mi plant sensor via MQTT. 2 | 3 | See https://github.com/ChristianKuehnel/plantgateway for more details. 4 | """ 5 | 6 | ############################################## 7 | # 8 | # This is open source software licensed under the Apache License 2.0 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | ############################################## 12 | 13 | 14 | from enum import Enum 15 | import os 16 | import logging 17 | import json 18 | import time 19 | from datetime import datetime 20 | from typing import List, Optional 21 | import yaml 22 | import paho.mqtt.client as mqtt 23 | from miflora.miflora_poller import MiFloraPoller, MI_BATTERY, MI_LIGHT, MI_CONDUCTIVITY, MI_MOISTURE, MI_TEMPERATURE 24 | from btlewrap.bluepy import BluepyBackend 25 | 26 | from plantgw import __version__ 27 | 28 | 29 | class MQTTAttributes(Enum): 30 | """Attributes sent in the json dict.""" 31 | BATTERY = 'battery' 32 | TEMPERATURE = 'temperature' 33 | BRIGHTNESS = 'brightness' 34 | MOISTURE = 'moisture' 35 | CONDUCTIVITY = 'conductivity' 36 | TIMESTAMP = 'timestamp' 37 | 38 | 39 | # unit of measurement for the different attributes 40 | UNIT_OF_MEASUREMENT = { 41 | MQTTAttributes.BATTERY: '%', 42 | MQTTAttributes.TEMPERATURE: '°C', 43 | MQTTAttributes.BRIGHTNESS: 'lux', 44 | MQTTAttributes.MOISTURE: '%', 45 | MQTTAttributes.CONDUCTIVITY: 'µS/cm', 46 | MQTTAttributes.TIMESTAMP: 's', 47 | } 48 | 49 | 50 | # home assistant device classes for the different attributes 51 | DEVICE_CLASS = { 52 | MQTTAttributes.BATTERY: 'battery', 53 | MQTTAttributes.TEMPERATURE: 'temperature', 54 | MQTTAttributes.BRIGHTNESS: 'illuminance', 55 | MQTTAttributes.MOISTURE: None, 56 | MQTTAttributes.CONDUCTIVITY: None, 57 | MQTTAttributes.TIMESTAMP: 'timestamp', 58 | } 59 | 60 | 61 | # pylint: disable-msg=too-many-instance-attributes 62 | class Configuration: 63 | """Stores the program configuration.""" 64 | 65 | def __init__(self, config_file_path): 66 | with open(config_file_path, 'r') as config_file: 67 | config = yaml.load(config_file, Loader=yaml.FullLoader) 68 | 69 | self._configure_logging(config) 70 | 71 | self.interface = 0 72 | if 'interface' in config: 73 | self.interface = config['interface'] 74 | 75 | self.mqtt_port = 8883 # type: int 76 | self.mqtt_user = None # type: Optional[str] 77 | self.mqtt_password = None # type: Optional[str] 78 | self.mqtt_ca_cert = None # type: Optional[str] 79 | self.mqtt_client_id = None # type: Optional[str] 80 | self.mqtt_trailing_slash = True # type:bool 81 | self.mqtt_timestamp_format = None # type: Optional[str] 82 | self.mqtt_discovery_prefix = None # type: Optional[str] 83 | self.sensors = [] # type: List[SensorConfig] 84 | 85 | if 'port' in config['mqtt']: 86 | self.mqtt_port = config['mqtt']['port'] 87 | 88 | if 'user' in config['mqtt']: 89 | self.mqtt_user = config['mqtt']['user'] 90 | 91 | if 'password' in config['mqtt']: 92 | self.mqtt_password = config['mqtt']['password'] 93 | 94 | if 'ca_cert' in config['mqtt']: 95 | self.mqtt_ca_cert = config['mqtt']['ca_cert'] 96 | 97 | if 'client_id' in config['mqtt']: 98 | self.mqtt_client_id = config['mqtt']['client_id'] 99 | 100 | if 'trailing_slash' in config['mqtt'] and not config['mqtt']['trailing_slash']: 101 | self.mqtt_trailing_slash = False 102 | 103 | if 'timestamp_format' in config['mqtt']: 104 | self.mqtt_timestamp_format = config['mqtt']['timestamp_format'] 105 | 106 | self.mqtt_server = config['mqtt']['server'] 107 | self.mqtt_prefix = config['mqtt']['prefix'] 108 | 109 | for sensor_config in config['sensors']: 110 | fail_silent = 'fail_silent' in sensor_config 111 | self.sensors.append(SensorConfig(sensor_config['mac'], sensor_config['alias'], fail_silent)) 112 | 113 | if 'discovery_prefix' in config['mqtt']: 114 | self.mqtt_discovery_prefix = config['mqtt']['discovery_prefix'] 115 | 116 | @staticmethod 117 | def _configure_logging(config): 118 | timeform = '%a, %d %b %Y %H:%M:%S' 119 | logform = '%(asctime)s %(levelname)-8s %(message)s' 120 | loglevel = logging.INFO 121 | if 'debug' in config: 122 | loglevel = logging.DEBUG 123 | 124 | if 'logfile' in config: 125 | logfile = os.path.abspath(os.path.expanduser(config['logfile'])) 126 | logging.basicConfig(filename=logfile, level=loglevel, datefmt=timeform, format=logform) 127 | else: 128 | logging.basicConfig(level=loglevel, datefmt=timeform, format=logform) 129 | 130 | 131 | class SensorConfig: 132 | """Stores the configuration of a sensor.""" 133 | 134 | def __init__(self, mac: str, alias: str = None, fail_silent: bool = False): 135 | if mac is None: 136 | msg = 'mac of sensor must not be None' 137 | logging.error(msg) 138 | raise Exception('mac of sensor must not be None') 139 | self.mac = mac 140 | self.alias = alias 141 | self.fail_silent = fail_silent 142 | 143 | def get_topic(self) -> str: 144 | """Get the topic name for the sensor.""" 145 | if self.alias is not None: 146 | return self.alias 147 | return self.mac 148 | 149 | def __str__(self) -> str: 150 | if self.alias: 151 | result = self.alias 152 | else: 153 | result = self.mac 154 | if self.fail_silent: 155 | result += ' (fail silent)' 156 | return result 157 | 158 | @property 159 | def short_mac(self): 160 | """Get the sensor mac without ':' in it.""" 161 | return self.mac.replace(':', '') 162 | 163 | @staticmethod 164 | def get_name_string(sensor_list) -> str: 165 | """Convert a list of sensor objects to a nice string.""" 166 | return ', '.join([str(sensor) for sensor in sensor_list]) 167 | 168 | 169 | class PlantGateway: 170 | """Main class of the module.""" 171 | 172 | def __init__(self, config_file_path: str = '~/.plantgw.yaml'): 173 | config_file_path = os.path.abspath(os.path.expanduser(config_file_path)) 174 | self.config = Configuration(config_file_path) # type: Configuration 175 | logging.info('PlantGateway version %s', __version__) 176 | logging.info('loaded config file from %s', config_file_path) 177 | self.mqtt_client = None 178 | self.connected = False # type: bool 179 | 180 | def start_client(self): 181 | """Start the mqtt client.""" 182 | if not self.connected: 183 | self._start_client() 184 | 185 | def stop_client(self): 186 | """Stop the mqtt client.""" 187 | if self.connected: 188 | self.mqtt_client.disconnect() 189 | self.connected = False 190 | self.mqtt_client.loop_stop() 191 | logging.info('Disconnected MQTT connection') 192 | 193 | def _start_client(self): 194 | self.mqtt_client = mqtt.Client(self.config.mqtt_client_id) 195 | if self.config.mqtt_user is not None: 196 | self.mqtt_client.username_pw_set(self.config.mqtt_user, self.config.mqtt_password) 197 | if self.config.mqtt_ca_cert is not None: 198 | self.mqtt_client.tls_set(self.config.mqtt_ca_cert, cert_reqs=mqtt.ssl.CERT_REQUIRED) 199 | 200 | def _on_connect(client, _, flags, return_code): 201 | self.connected = True 202 | logging.info("MQTT connection returned result: %s", mqtt.connack_string(return_code)) 203 | self.mqtt_client.on_connect = _on_connect 204 | 205 | self.mqtt_client.connect(self.config.mqtt_server, self.config.mqtt_port, 60) 206 | self.mqtt_client.loop_start() 207 | 208 | def _publish(self, sensor_config: SensorConfig, poller: MiFloraPoller): 209 | self.start_client() 210 | state_topic = self._get_state_topic(sensor_config) 211 | 212 | data = { 213 | MQTTAttributes.BATTERY.value: poller.parameter_value(MI_BATTERY), 214 | MQTTAttributes.TEMPERATURE.value: '{0:.1f}'.format(poller.parameter_value(MI_TEMPERATURE)), 215 | MQTTAttributes.BRIGHTNESS.value: poller.parameter_value(MI_LIGHT), 216 | MQTTAttributes.MOISTURE.value: poller.parameter_value(MI_MOISTURE), 217 | MQTTAttributes.CONDUCTIVITY.value: poller.parameter_value(MI_CONDUCTIVITY), 218 | MQTTAttributes.TIMESTAMP.value: datetime.now().isoformat(), 219 | } 220 | for key, value in data.items(): 221 | logging.debug("%s: %s", key, value) 222 | if self.config.mqtt_timestamp_format is not None: 223 | data['timestamp'] = datetime.now().strftime(self.config.mqtt_timestamp_format) 224 | json_payload = json.dumps(data) 225 | self.mqtt_client.publish(state_topic, json_payload, qos=1, retain=True) 226 | logging.info('sent data to topic %s', state_topic) 227 | 228 | def _get_state_topic(self, sensor_config: SensorConfig) -> str: 229 | prefix_fmt = '{}/{}' 230 | if self.config.mqtt_trailing_slash: 231 | prefix_fmt += '/' 232 | prefix = prefix_fmt.format(self.config.mqtt_prefix, 233 | sensor_config.get_topic()) 234 | return prefix 235 | 236 | def process_mac(self, sensor_config: SensorConfig): 237 | """Get data from one Sensor.""" 238 | logging.info('Getting data from sensor %s', sensor_config.get_topic()) 239 | poller = MiFloraPoller(sensor_config.mac, BluepyBackend) 240 | self.announce_sensor(sensor_config) 241 | self._publish(sensor_config, poller) 242 | 243 | def process_all(self): 244 | """Get data from all sensors.""" 245 | next_list = self.config.sensors 246 | timeout = 1 # initial timeout in seconds 247 | max_retry = 6 # number of retries 248 | retry_count = 0 249 | 250 | while retry_count < max_retry and next_list: 251 | # if this is not the first try: wait some time before trying again 252 | if retry_count > 0: 253 | logging.info('try %d of %d: could not process sensor(s) %s. Waiting %d sec for next try', 254 | retry_count, max_retry, SensorConfig.get_name_string(next_list), timeout) 255 | time.sleep(timeout) 256 | timeout *= 2 # exponential backoff-time 257 | 258 | current_list = next_list 259 | retry_count += 1 260 | next_list = [] 261 | for sensor in current_list: 262 | try: 263 | self.process_mac(sensor) 264 | # pylint: disable=bare-except, broad-except 265 | except Exception as exception: 266 | next_list.append(sensor) # if it failed, we'll try again in the next round 267 | msg = "could not read data from {} ({}) with reason: {}".format( 268 | sensor.mac, sensor.alias, str(exception)) 269 | if sensor.fail_silent: 270 | logging.error(msg) 271 | logging.warning('fail_silent is set for sensor %s, so not raising an exception.', sensor.alias) 272 | else: 273 | logging.exception(msg) 274 | print(msg) 275 | 276 | # return sensors that could not be processed after max_retry 277 | return next_list 278 | 279 | def announce_sensor(self, sensor_config: SensorConfig): 280 | """Announce the sensor via Home Assistant MQTT Discovery. 281 | 282 | see https://www.home-assistant.io/docs/mqtt/discovery/ 283 | """ 284 | if self.config.mqtt_discovery_prefix is None: 285 | return 286 | self.start_client() 287 | device_name = 'plant_{}'.format(sensor_config.short_mac) 288 | for attribute in MQTTAttributes: 289 | topic = '{}/sensor/{}_{}/config'.format(self.config.mqtt_discovery_prefix, device_name, attribute.value) 290 | payload = { 291 | 'state_topic': self._get_state_topic(sensor_config), 292 | 'unit_of_measurement': UNIT_OF_MEASUREMENT[attribute], 293 | 'value_template': '{{value_json.'+attribute.value+'}}', 294 | } 295 | if sensor_config.alias is not None: 296 | payload['name'] = '{}_{}'.format(sensor_config.alias, attribute.value) 297 | 298 | if DEVICE_CLASS[attribute] is not None: 299 | payload['device_class'] = DEVICE_CLASS[attribute] 300 | 301 | json_payload = json.dumps(payload) 302 | self.mqtt_client.publish(topic, json_payload, qos=1, retain=False) 303 | logging.info('sent sensor config to topic %s', topic) 304 | -------------------------------------------------------------------------------- /pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | ignore=yaml 3 | 4 | [MESSAGES CONTROL] 5 | disable=too-few-public-methods, unused-argument, locally-disabled 6 | max-line-length=120 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | bluepy==1.3.0 2 | paho-mqtt 3 | pyyaml>=5.1 4 | miflora==0.6 5 | typing>=3,<4 6 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ############################################## 4 | # 5 | # This is open source software licensed under the Apache License 2.0 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | ############################################## 9 | """Setup for plantgateway.""" 10 | from setuptools import setup 11 | from plantgw import __version__ 12 | 13 | 14 | def readme(): 15 | """Load the readme file.""" 16 | with open('README.md', 'r') as readme_file: 17 | return readme_file.read() 18 | 19 | 20 | setup( 21 | name='plantgateway', 22 | version=__version__, 23 | description='Bluetooth to mqtt gateway for Xiaomi Mi plant sensors', 24 | long_description=readme(), 25 | long_description_content_type='text/markdown', 26 | author='Christian Kühnel', 27 | author_email='christian.kuehnel@gmail.com', 28 | url='https://www.python.org/sigs/distutils-sig/', 29 | packages=['plantgw'], 30 | install_requires=['bluepy==1.3.0', 'paho-mqtt', 'pyyaml>=5.1', 'miflora==0.6', 'typing>=3,<4'], 31 | scripts=['plantgateway'], 32 | ) 33 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = pylint, flake8 3 | skip_missing_interpreters = True 4 | 5 | [testenv:flake8] 6 | basepython = python3 7 | commands = flake8 plantgw setup.py 8 | deps= 9 | flake8 10 | -r{toxinidir}/requirements.txt 11 | 12 | [testenv:pylint] 13 | basepython = python3 14 | commands = pylint plantgw setup.py 15 | deps= 16 | pylint 17 | -r{toxinidir}/requirements.txt 18 | 19 | [flake8] 20 | max-line-length=120 21 | 22 | --------------------------------------------------------------------------------