Giter VIP home page Giter VIP logo

miflora's Introduction

miflora - Library for Xiaomi Mi plant sensor

PyPI PyPI PyPI GitHub Actions Coveralls github Plants healty and growing GitHub license

This repo used to live under the open-homeautomation/miflora namespace and was originally created by @open-homeautomation.

This library lets you read sensor data from a Xiaomi Mi Flora plant sensor.

Functionality

It supports reading the different measurements from the sensor

  • temperature
  • moisture
  • conductivity
  • brightness

To use this library you will need a Bluetooth Low Energy dongle attached to your computer. You will also need a Xiaomi Mi Flora plant sensor.

Backends

As there is unfortunately no universally working Bluetooth Low Energy library for Python, the project currently offers support for two Bluetooth implementations:

  • bluepy library
  • bluez tools (deprecated, via a wrapper around gatttool)
  • pygatt library

bluepy (recommended)

To use the bluepy library you have to install it on your machine, in most cases this can be done via: pip3 install bluepy

Example to use the bluepy backend:

from miflora.miflora_poller import MiFloraPoller
from btlewrap.bluepy import BluepyBackend

poller = MiFloraPoller("some mac address", BluepyBackend)

This is the backend library to be used.

bluez/gatttool wrapper (deprecated)

⚠️ The bluez team marked gatttool as deprecated. This solution may still work on some Linux distributions, but it is not recommended any more.

To use the bluez wrapper, you need to install the bluez tools on your machine. No additional python libraries are required. Some distributions moved the gatttool binary to a separate package. Make sure you have this binary available on your machine.

Example to use the bluez/gatttool wrapper:

from miflora.miflora_poller import MiFloraPoller
from btlewrap.gatttool import GatttoolBackend

poller = MiFloraPoller("some mac address", GatttoolBackend)

This backend should only be used, if your platform is not supported by bluepy.

pygatt

If you have a Blue Giga based device that is supported by pygatt, you have to install the bluepy library on your machine. In most cases this can be done via: pip3 install pygatt

Example to use the pygatt backend:

from miflora.miflora_poller import MiFloraPoller
from btlewrap.pygatt import PygattBackend

poller = MiFloraPoller("some mac address", PygattBackend)

Dependencies

miflora depends on the btlewrap library. If you install miflora via PIP btlewrap will automatically be installed. If not, you will have to install btlewrap manually:

pip3 install btlewrap

Troubleshooting

Users frequently have problems with the communication between their Bluetooth dongle and the sensors. Here are the usual things to try.

Battery empty

While the battery usually lasts about a year indoor, it may also fail for unknown reasons before that. So the first thing to check if the battery is still good: take out the battery, wait 3 secs and put it back in. The light on the sensor should be flashing. If it is not: get a new battery.

Range

The distance between Bluetooth dongle and sensor should be less than 5 meters. Try moving the sensor and dongle closer together and see if that solves the problem. If range is an issue, there are a few proxies/relays via MQTT available:

Outside

If you're operating your sensors outside, make sure the sensor is protected against rain. The power of the battery is decreasing blow -10°C. Sou you might not get readings at that temperature. Also make sure that you have a Bluetooth dongle close by.

Radio interference

The Bluetooth LE communication is not always reliable. There might be outages due to other radio interferences. The standard solution is to try again or poll your sensor more often that you really need it. It's also the hardest issue to analyse and debug.

Raspberry Pi

If you're using a Raspberry Pi, make sure, that you OS is up to date, including the latest kernel and firmware. There are sometimes useful Bluetooth fixes. Also make sure that you have a good power supply (3 A recommended) as this causes sporadic problems in many places.

Conttributing

please have a look at CONTRIBUTING.md

Projects Depending on miflora

The following shows a selected list of projects using this library:

miflora's People

Contributors

andywcoder avatar basnijholt avatar bbbenji avatar cdce8p avatar christiankuehnel avatar chrostek avatar cybe avatar danielhiversen avatar davidlp avatar fedalto avatar freol35241 avatar github-actions[bot] avatar goestao avatar growers12 avatar hifiberry avatar onkelbeh avatar paulannekov avatar thomdietrich avatar wolph avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

miflora's Issues

re-configure project in github to use TravisCI and Coverall

In other projects all pull requests are automatically built by TravisCI, so that you immediately see if the project is still working and all the coding conventions were followed. It would be nice to also have that here. I already provided an initial .travis.yml.

It would also be nice to have Coveralls report the code coverage of the tests.

⚠️ You probably need some special permissions in github to do this.

Deal with negative temperatures

As temperatures can be negative (at least in some countries 😉 ), we need to implement a conversion of negative temperatures to float.

Tasks:

  • figure out how negative temperatures are encoded (e.g. one's complement)
  • implement a solution
  • add tests for negative temperatures

A few questions on the flower mate

Hi there,

  1. do you know, if pairing of the flower mate is possible? So only my devices can request status and not my neighbors.
  2. How often are the sensor values updated? e.g If you poll twice within a minute, no changes are measured. Even if you water the plant in between.
  3. Is something like "broadcast values" available? So paired devices (if possible) would be notified.

Thank you.

Make windows compatible

I have written a small utility for windows that tries to mimic gatttool and it seems to work at least when i run it in a command line.
But when i try to run you python script on windows i get the following error:

  File "C:\Users\xbmc\AppData\Roaming\.homeassistant\deps\miflora\miflora_poller.py", line 249, in parameter_value
    self.fill_cache()
  File "C:\Users\xbmc\AppData\Roaming\.homeassistant\deps\miflora\miflora_poller.py", line 180, in fill_cache
    firmware_version = self.firmware_version()
  File "C:\Users\xbmc\AppData\Roaming\.homeassistant\deps\miflora\miflora_poller.py", line 221, in firmware_version
    res = read_ble(self._mac, '0x038', retries=self.retries, adapter=self._adapter)
  File "C:\Users\xbmc\AppData\Roaming\.homeassistant\deps\miflora\miflora_poller.py", line 117, in read_ble
    preexec_fn=os.setsid) as process:
AttributeError: module 'os' has no attribute 'setsid'

If i understand correctly the os.setsid does not exist on windows and i have no idea what it does.
But i tried to remove the preexec_fn=os.setsid and that seemed to solve the issue.

Any chance that you could release a new version that includes a better fix? (my guess is that you can't just remove it on Linux without breaking things).

Intended behavior upon connection error

Hello,
how is the library supposed to catch and propagate a connection problem?

Heres a minimal example:

flora_poller = MiFloraPoller(mac='11:22:33:44:55:66')
flora_poller.fill_cache()
print('Device name: "{}"'.format(flora_poller.name()))

This piece of code will produce:

Traceback (most recent call last):
  File "./mqtt-flora.py", line 85, in <module>
    print('Device name:  "{}"'.format(flora_poller.name()))
  File "/usr/local/lib/python3.4/dist-packages/miflora/miflora_poller.py", line 177, in name
    return ''.join(chr(n) for n in name)
TypeError: 'NoneType' object is not iterable

Other functions behave similarly. Shouldn't there be an exception thrown or a cache_available method or any other kind of error control mechanism?

When Temperature is below zero very high values are returned (<6553.5)

During these cold nights my sensor measure temperatures below zero. The MiFlora App gives the right temperature, while the miflora MQTT-daemon which is based on miflora returns
{"conductivity": 1397, "moisture": 35, "temperature": 6553.5, "light": 66, "battery": 98}

This is clearly due to the fact that the temperature is a SIGNED integer while the Miflora-daemon interprets it as an UNSIGNED integer.

When Lux is > 32768, returned value is negative

I changed the unpack data in miflora_poller.py, it seems work fine:

 def _parse_data(self):                                                                 
 """Parses the byte array returned by the sensor.                                   
                                                                                    
 The sensor returns 16 bytes in total. It's unclear what the meaning of these bytes 
 is beyond what is decoded in this method.                                          
                                                                                    
 semantics of the data (in little endian encoding):                                 
 bytes 0-1: temperature in 0.1 °C                                                   
 byte 2: unknown                                                                    
 bytes 3-4: brightness in Lux                                                       
 bytes 5-6: brightness in Lux                                                                  
 byte 7: Moisture                                                                   
 byte 8-9: Conductivity in µS/cm                                                       
 bytes 10-15: unknown                                                                                        
 """                                                                                
 data = self._cache                                                                 
 res = dict()                                                                       
 temp, res[MI_LIGHT], res[MI_MOISTURE], res[MI_CONDUCTIVITY] = \                    
     unpack('<hxiBhxxxxxx', data)                                                   
 res[MI_TEMPERATURE] = temp/10.0                                                    
 return res                                                                         

Unable to install using NPM

I am finding the following issue when trying to use NPM to install your library.

pi@raspberrypi:~/.node-red $ npm i https://github.com/open-homeautomation/miflora
npm ERR! addLocal Could not install /tmp/npm-3174-cbd0c9a8/git-cache-e9fd0e4fcfcf/3575b30e3b4e06d460a1088a8b96999dd328cbed
npm ERR! Linux 4.4.50-v7+
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "i" "https://github.com/open-homeautomation/miflora"
npm ERR! node v4.8.2
npm ERR! npm v2.15.11
npm ERR! code EISDIR
npm ERR! errno -21
npm ERR! syscall read

npm ERR! eisdir EISDIR: illegal operation on a directory, read
npm ERR! eisdir This is most likely not a problem with npm itself
npm ERR! eisdir and is related to npm not being able to find a package.json in
npm ERR! eisdir a package you are trying to install.

npm ERR! Please include the following file with any support request:
npm ERR! /home/pi/.node-red/npm-debug.log

I've checked the log and it seems to be a carbon copy of what is written above. I'm a bit of a noob with a lot of this so I could really do with a little help!

Please forgive me if I am pointing out an issue that is already raised or resolved elsewhere.

Exception in Home Assistant

Hi,

Some of my MiFloras are slow to respond or out of range. Getting many of these in the log:

2018-01-18 22:39:24 ERROR (MainThread) [homeassistant.helpers.entity] Update for sensor.stripe_conductivity fails
Traceback (most recent call last):
  File "/srv/homeassistant/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 199, in async_update_ha_state
    yield from self.async_device_update()
  File "/srv/homeassistant/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 306, in async_device_update
    yield from self.hass.async_add_job(self.update)
  File "/usr/local/lib/python3.6/asyncio/futures.py", line 332, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/local/lib/python3.6/asyncio/tasks.py", line 250, in _wakeup
    future.result()
  File "/usr/local/lib/python3.6/asyncio/futures.py", line 245, in result
    raise self._exception
  File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/srv/homeassistant/lib/python3.6/site-packages/homeassistant/components/sensor/miflora.py", line 135, in update
    data = self.poller.parameter_value(self.parameter)
  File "/srv/homeassistant/lib/python3.6/site-packages/miflora/miflora_poller.py", line 128, in parameter_value
    self.fill_cache()
  File "/srv/homeassistant/lib/python3.6/site-packages/miflora/miflora_poller.py", line 60, in fill_cache
    firmware_version = self.firmware_version()
  File "/srv/homeassistant/lib/python3.6/site-packages/miflora/miflora_poller.py", line 102, in firmware_version
    _HANDLE_READ_VERSION_BATTERY, self._format_bytes(res))
  File "/srv/homeassistant/lib/python3.6/site-packages/miflora/miflora_poller.py", line 170, in _format_bytes
    return ' '.join([format(c, "02x") for c in raw_data]).upper()
TypeError: 'NoneType' object is not iterable

Are there some way of handling these?

Support for historical data ?

Hi there,
Thanks for this great work,
It seems like the sensors actually store historical data, any plans to support querying these ?

Does not receive data or receives inaccurate data, a session break before data is received.

The problem is that when a query from the address 0x0035 where the readings are to be issued, either zero readings are given, or here are the readings: "aa bb cc dd ee ff 99 88 77 66 00 00 00 00 00 00"
This is due to the fact that the device does not know that it needs to give the readings in order to obtain data on the temperature readings, humidity, etc. it is necessary that at the address 0x0033 the value A01F
but the team
gatttool --device = C4: 7C: 8D: 66: 62: 47 --char-write-req -a 0x0033 -n A01F
not enough because with such a command the session with the device opens, the data at the specified address is written and the session is closed, when you try to read the data at address 0x0035 with the command
gatttool --device = C4: 7C: 8D: 66: 62: 47 --char-read -a 0x0035
the data will not be read due to the fact that a new session will be opened and the value at 0x0033 will be 00 00
To read the data it is necessary that after the session (connection) is closed, the data at address 0x0033 is not reset, I do not know how to do it, but you can get the correct data by running gatttool in interactive mode
gatttool -b C4: 7C: 8D: 66: 62: 47 -I
and already online to connect to the device, write data to the address 0x0033 and read the data at address 0x0033
by executing the following commands:
connect
char-write-req 0x0033 A01F
char-read-hnd 35
and you get the correct data from the sensors.
Developers of libraries should take this into account.

At me as after certain time there is a break of session, in the console at interactive start after a connection there is an error
(gatttool: 12258): GLib-WARNING **: Invalid file descriptor.
Perhaps this is due to the version of gatttool and when using a library that first gets the device name, then the firmware version (it is not clear why the firmware version is needed) and after that there is also a break, I guess that's why the demo script does not work, firmware and device name that reads from the sensor, which in my opinion are not needed.
python3 demo.py --backend gatttool poll C4: 7C: 8D: 66: 62: 47
Getting data from Mi Flora
FW: 3.1.8
Name: Flower care
Traceback (most recent last call last):
  File "demo.py", line 99, in
    main ()
  File "demo.py", line 95, in main
    args.func (args)
  File "demo.py", line 30, in poll
    print ("Temperature: {}" format (poller.parameter_value (MI_TEMPERATURE)))
  File "/root/miflora/miflora/miflora_poller.py", line 141, in parameter_value
    raise BluetoothBackendException ("Could not read data from Mi Flora sensor% s"% self._mac)
btlewrap.base.BluetoothBackendException: Could not read data from Mi Flora sensor C4: 7C: 8D: 66: 62: 47

original text:
Не получает данные или получает не верные данные, разрыв сессии до получения данных.

Проблема заключается в том, что при запросе из адреса 0x0035 где должны быть показания выдается либо нулевые показания, либо вот такие показания: "aa bb cc dd ee ff 99 88 77 66 00 00 00 00 00 00"
происходит это по причине того, что устройство не знает, что ему надо показания отдать, чтобы получить данные о показаниях температыры, влажности и т.д. надо чтобы по адресу 0x0033 было записано значение A01F
но команды
gatttool --device=C4:7C:8D:66:62:47 --char-write-req -a 0x0033 -n A01Ф
не достаточно поскольку при такой команде открывается сессия с устройством, данные по указанному адресу записываются и сессия закрывается, при попытке считать данные по адресу 0х0035 командой
gatttool --device=C4:7C:8D:66:62:47 --char-read -a 0x0035
данные не будут считываьбся по причине того, что будет открыта новая сессия и значение по адресу 0x0033 будет 00 00
Для считывания данные необходимо, чтобы после закрытия сессии (соединения) данные по адресу 0x0033 не сбрасывались, как это сделать я не знаю, но получить правильные данные можно, для этого необходимо запустить gatttool в интерактивном режиме
gatttool -b C4:7C:8D:66:62:47 -I
и уже в интерактивном режиме подключиться к устройству, записать данные по адресу 0x0033 и считать данные по адресу 0x0033
последовательно выполнив следующие команды:
connect
char-write-req 0x0033 A01F
char-read-hnd 35
и вы получите правильные данные с датчиков.
Разработчикам библиотек следует это учитывать.

У меня так же после определенного времени происходит разрыв сессии, в консоли при интерактивном запуске после коннекта происходит ошибка
(gatttool:12258): GLib-WARNING **: Invalid file descriptor.
возможно это связано с версией gatttool и при использовании библиотеки которая сначала получает имя устройства, потом версию прошивки (не понятно зачем нужна версия прошивки) и после этого происходит так же разрыв, пологаю именно по этому не работает например демо скрипт ,который успевает выдать только версию прошивки и имя устройства которые считывает из датчика, которые по моему мнению не нужны.
python3 demo.py --backend gatttool poll C4:7C:8D:66:62:47
Getting data from Mi Flora
FW: 3.1.8
Name: Flower care
Traceback (most recent call last):
File "demo.py", line 99, in
main()
File "demo.py", line 95, in main
args.func(args)
File "demo.py", line 30, in poll
print("Temperature: {}".format(poller.parameter_value(MI_TEMPERATURE)))
File "/root/miflora/miflora/miflora_poller.py", line 141, in parameter_value
raise BluetoothBackendException("Could not read data from Mi Flora sensor %s" % self._mac)
btlewrap.base.BluetoothBackendException: Could not read data from Mi Flora sensor C4:7C:8D:66:62:47

Live data

With the android app, theres the possibility to get live data from the sensor f.e. the moisture value every second. Guess ppl have to pair with the sensor to get the data. Will there be such functionality in the future?

Pygatt for additional platforms

Is there any chance of using pygatt as the BLE module so that both gatttool and BGAPI (i.e. linux and other computers with a BLED112 dongle) could be used to interface with the mi flora device?

Soil fertility instead of conductivity, bug when using brand new sensors.

Question Uno:

Is the conductivity returned mislabeled?
Looking at another reader it uses soil fertility instead of conductivity...

https://github.com/marcelrv/miflora/blob/master/miflora.py

Question Lasto:

I got a lot of these sensors, and two of them gave these errors when brand new from the package...

    print("Moisture: {}".format(poller.parameter_value(MI_MOISTURE)))
  File "/home/pi/miflora/miflora/miflora_poller.py", line 250, in parameter_value
    self._mac)
OSError: [Errno Could not read data from Mi Flora sensor %s] C4:7C:8D:62:2C:40

After placing them in soil for some time, it appears to work fine..., it only happens with new ones straight from the package...

Beacon stops advertising when reading Mi Flora data

Hi,

I am using a Raspberry Pi to read the data of the Mi Flora and it is working perfectly. I am now also trying to use the Raspberry Pi as an Beacon to monitor the presence of people in my house but I realised that whenever the Mi Flora data is read, my Raspberry Pi stops advertising and I have to run sudo hciconfig hci0 leadv 0 again to be able to see my beacon.

Would it be a behavior of the bluetooth not allowing Beacon advertising and connection to a bluetooth device or is it something that could be fixed?

Ben

AttributeError: 'Namespace' object has no attribute 'func'

I am trying to run demo.py, but I get error:

$ python3 ./demo.py --backend gatttool
Traceback (most recent call last):
  File "./demo.py", line 65, in <module>
    args.func(args, backend)
AttributeError: 'Namespace' object has no attribute 'func'

demo.py TimeoutExpired error

When running demo.py

from subprocess import PIPE, Popen, TimeoutExpired

ImportError: cannot import name TimeoutExpired

Exception handling broken

After investigating home-assistant/core#9048 (comment) I noticed, that the exception handling is broken.

What should happen in case of an exception in the Bluetooth communication:
All exceptions from the different backends are wrapped in BluetoothBackendException.

Current situation:
Each Bluetooth backend raises different types of exceptions, depending on the backend.

This needs to fixed and tested properly

Example output from gatttool?

Could you give me a example of the output from gatttool?

gatttool --device=[MAC] --char-write-req -a 0x33 -n A01F --adapter=hci0
gatttool --device=[MAC] --char-read -a 0x03 --adapter=hci0
gatttool --device=[MAC] --char-read -a 0x35 --adapter=hci0 
gatttool --device=[MAC] --char-read -a 0x038 --adapter=hci0

Question

Can I connect to multiple Miflora's with your library?
And put data from multiple Miflora's into a json.

Coveralls - disable comments

Hey @open-homeautomation,

can you please set "LEAVE COMMENTS?" in the coveralls configuration to disabled? This way we can avoid the many ugly postings on pull requests: #73 (comment)

Is this windows compatible?

Is this windows compatible?
Or is it Linux only the documentation says Define the bluetooth adapter to use (defaults to hci0). Run hciconfig to get a list of available adapters. and hciconfig is a linux utility if i understand correctly?

So is this windows compatible or not? and if not is there any thing i can help with to make it Windows compatible?

Proposals for improvements

After using miflora for a while I noticed some things that I was not happy with:

  • Invalid measurements: you can check if you get bad data (AA BB CC DD...) from the sensor and then just ignore it or retry.
  • If reading the data fails: try again a few times. The communication with the sensors is not 100% stable and retrying solves it most of the time.
  • The temperature can be negative, here you have to use the ones' complement to concert the bytes correctly.
  • Using the gattool is a nice abstraction above the platform details but has some drawbacks: error handling is more complicated, it's slower and you need to do a lot of parsing of the console output.

For these reasons I decided to create a new implementation on top of BluePy:
https://github.com/ChristianKuehnel/plantgateway/blob/master/plantgw/misensor.py

One comment on speed: Getting the data (battery + measurements) and forwarding it via MQTT takes <10sec per sensor.

If you're interested we could discuss merging my low-level parts with your high-level API...

Improve test coverage of miflora_poller.py

At the moment miflora_poller.py is not well tested. Please add more tests for this class. You probably need to extend the class MockBackend for that.

The goal is to have the main logic of the class properly tested

v0.1.15 missing from pypi

Thanks for merging my pr and making a new release, but it seams that the latest release is missing from pypi

ImportError: cannot import name TimeoutExpired

I found my ID using : sudo hcitool lescan)
C4:7C:8D:62:0C:81 Flower care

I edit demo.py with this but when I run it I get the following errors:
I edit demo.py with this but when I run it I get the following errors:
pi@domo1 ~ $ sudo /usr/bin/python3 /home/pi/domoticz/scripts/python/miflora/demo.py
pi@domo1 ~/domoticz/scripts/python/miflora/miflora/tests $ /usr/bin/python3 /home/pi/domoticz/scripts/python/miflora/demo.py
Traceback (most recent call last):
File "/home/pi/domoticz/scripts/python/miflora/demo.py", line 1, in
from miflora.miflora_poller import MiFloraPoller,
File "/home/pi/domoticz/scripts/python/miflora/miflora/miflora_poller.py", line 12, in
from subprocess import PIPE, Popen, TimeoutExpired
ImportError: cannot import name TimeoutExpired

I can connect with gatttool -I and Connect
pi@domo1 ~/domoticz/scripts/python $ gatttool -I
[ ][LE]> connect c4:7c:8d:62:0c:81
Attempting to connect to c4:7c:8d:62:0c:81
Connection successful
Notification handle = 0x0021 value: 00
Notification handle = 0x0021 value: 00
Notification handle = 0x0021 value: 00
[c4:7c:8d:62:0c:81][LE]>
(gatttool:9429): GLib-WARNING **: Invalid file descriptor.

Fix Coveralls setup

There is a Travis CI configuration for Coveralls but it does not yet collect any metrics. This should be fixed.

project stale?

Dear maintainers,

I have the impression, that there is not much progress going on and that pull requests take quite long to get processed. Is that impression correct?

If so, what can we do about that? There are already some forks in place to work on new features.

Are you willing to take new maintainers?

br Christian

Supported OS

It seems that gatttool is not available on macOS (10.12).
Are you only supporting Linux ?

thanks for the job !

Wrong negative Light Value above specific threshold

I don't know the exact treshold but the light value turns negative above a specific value..

11000 ok
22000 ok
33000 ok

-2461 when it really is 112k.something e.g.

In C I would say it's an overflow cause maybe the unsigned 16bit unsigned int ends here or something.. but there are no variable types in python, or? I couldn't find the cause looking in the code on my own :(

Actually I didn't get this working at all so I'm using https://github.com/ThomDietrich/miflora-mqtt-daemon/ bus this is based on your newest build and the problem seems to inherit from here

No values from device

I don't get any data from the device. When I try to get the values manually I only receive zeros:
pi@raspberrypi:~ $ gatttool --device=C4:7C:8D:60:BC:F6 --char-read -a 0x35 Characteristic value/descriptor: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

Any ideas why it is not working for me?

create new release

Hey @open-homeautomation ,

  1. Please review&merge this PR: #94. It fixes a bug with high brightness values: #93
  2. Can you please tag the version 0.3 in git? There is a release on pypi, but no tag on github.
  3. Please create another release. Please also check that the new long description appears properly on pypi from my change in #94.
  4. Disable the comments from Coveralls, see #76

Support for battery, other characteristics

I read your post on reverse engineering the BLE API, and noticed that the app is able to query the battery level of the sensor - would it be possible to query this, and potentially other things? Such as syncing the history of the sensor?

Support for -1 degrees and lower

I use this mi flora product outside. But when the temperature is under the 0 degrees the software gives a reading error. I think this product measure also lower than 0 degrees... Can anybody resolve this?

Getting No Route to host (113) when running homeassistant with miflora library.

Hi, I'm trying to reproduce this error, and here's what I've been able to do so far.
Please give me some hint of the direction to continue troubleshooting, if possible. Thanks.

root@home:~# gatttool -b C4:7C:8D:61:91:52 --char-read -a 0x35
connect: No route to host (113)
root@home:~# supervisorctl stop homeassistant
omeassistant: stopped
root@home:~# gatttool -b C4:7C:8D:61:91:52 --char-read -a 0x35
connect: No route to host (113)
root@home:~# hcitool lescan
LE Scan ...
...
C4:7C:8D:61:91:52 Flower care
...
root@home:~# gatttool -b C4:7C:8D:61:91:52 --char-read -a 0x35
Characteristic value/descriptor: aa bb cc dd ee ff 99 88 77 66 00 00 00 00 00 00

It almost feels like there is some 'read mode' that is not enabled properly. But after scanning again I can query the data.

Any thoughts?

Cross bug filed to home-assistant until we understand the nature of the problem home-assistant/core#5918

Invalid values are not being filtered out

I received very wild values for all outputted information, luxes going over 60,000 and temperatures such as shown in the attached graph. The homeassistant component has a possibility to averaging based on multiple checks but it would make sense to filter out values like these in the library.

miflora

Deal with invalid measurements reported from the sensor

Sometimes the reading of the measurements fails and then the sensor returns INVALID_DATA = b'\xaa\xbb\xcc\xdd\xee\xff\x99\x88wf\x00\x00\x00\x00\x00\x00'.

My guess is: this happens when this operation fails: connection.write_handle("0x33", "A01F"):

We need someone to investigate the issue further and implement a solution that solves this this issue. My idea would be to retry reading the data we get the INVALID_DATA.

See also the discussion in #40

Implement support for Windows

AFAIK this library does not really work on Windows at the moment as we do not support a Bluetooth backend that works on Windows. It would be nice to support windows as well

So that goal here is to implement a solution that can talk to some Bluetooth Library on Windows. If that does not exist, you might have to talk directly to the native Bluetooth API of Windows.

See also the discussion in #28

ESP32

Is it possible to port this interface to Arduino IDE for ESP32 ?
Do you plan this in the future ?

Project status and future development

I'd like to ask if this project is still active.
A project of mine is dependent on this one and I would need the additions provided in the trivial PRs #32 and #33. Sadly there was no reaction over the course of one week. If this project is not actively maintained any longer, I would be forced to create a fork, not the path I want to go down. If the project is still active and you are e.g. enjoying your vacation right now I can of course wait.

Looking forward to a positive answer. Best regards!

read_ble() modification

Hi, sorry this isn't really an issue, more a query. I am hacking read_ble() to query my Elgato Eve door and window sensor. i have a list of 150 handles which could return the state of the sensor. I am parsing the list using read_ble() and all goes well until the handle 0x3021 returns a NoneType. I assume you dealt with this when writing the script so wondering how to handle it? I am a bit mystified why this isn't handled by the final line of read_ble()
LOGGER.debug("Exit read_ble, no data (%s)", current_thread())
Cheers

`Running


0x1000


0x2000


0x2001
*


0x2002
Eve Door


0x2003
*


0x2004


0x3000
�Rv»&�U


0x3010
0Ñ �PªÓ�HY§]éæ


0x3011
f


0x3020

!0�Rv»&�O


0x3021
Characteristic value/descriptor read failed: Attribute can't be read
Characteristic value/descriptor read failed: Attribute can't be read
connect error: Transport endpoint is not connected (107)
Characteristic value/descriptor read failed: Attribute can't be read
Traceback (most recent call last):
File "test.py", line 94, in
print(''.join(chr(n) for n in name))
TypeError: 'NoneType' object is not iterable`

Implement backend for support BLED112 dongles

As we now have the refactoring in place, we one of the frequent requests was to support BLED112 dongles via the pygatt library. As we now have the architecture to support different backends, it should not be difficult to add this. This needs to be implemented and tested.

⚠️ You will need a matching Bluetooth dongle for this...

See also the discussion in #24

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.