Xiaomi Mijia bluetooth temperature & humidity sensor compatibility

Hi Magalex, sorry, I’m not a programmer, just a HA novice with two xiaomi ble temperture sensors with flat encephalogram.
May I ask you how to use your code? Shoud it replace some existing code in the config dir in hassio? or should it be added somewhere.
Thank you for any help.

Hi @corrado!

What you have do is follow the instructions here.

After that replace the sensor.py inside the mitemp_bt folder you dowloaded with the the code on @Magalex’s gist , but the file name has to stay sensor.py. Restart HA and voila!

Hope this helps! Huge thanks again to @Magalex @tsymbaliuk and everyone else :heart:

2 Likes

Thank you so much!
Just a small difference: I found the sensor.py file in custom_components, within hacs folder instead than mi_temp folder.
Anyway it looks like working. I’ll monitor for the next hours.
Thanks again @N-l1 and @Magalex

1 Like

Does any of you had issue where detecting range whent down. For now my device have to be less when 1meter to detect it with hcitool lescan before 4 meter away was not a problem.

anyway to have BLE turned off (really turned off) and only turned on for sensor reading and then turned off again?

Hi, i had problems with bt temp sensors not giving new temp updates. I have updated with @Magalex his code and restarted but same problem still happens:( I have HA running on a Pi3, is it mabye smarter to collect the bt data through a ESP32?

To help, we need more information about what is happening on your system (logs, bt interface status, etc.)

Personally, I ran into a problem that was not related to the work of the integration discussed here. My problem is probably related to the operation of drivers and/or hardware (I have mac mini 2011).

I will describe my workaround. It will suit you if the execution of the commands sudo modprobe -r btusb and then sudo modprobe btusb (instead of btusb in the case of the module built into raspberry pi this may be hci_uart, but I’m not sure) will bring bluetooth to working condition.

  1. Add a binary sensor to the configuration (mi_t_1 and mi_h_1 and mi_t_2 and mi_h_2 must be replaced with the names of your sensors). This sensor will go into the ON state when there are no readings from the bt-sensors for two minutes (you can change 120 to another value in seconds):
binary_sensor:
  - platform: template
    sensors:
      bt_stuck:
        friendly_name: "BT"
        value_template: >-
          {% set btvalues = [
            states.sensor.mi_t_1.last_updated,
            states.sensor.mi_t_2.last_updated,
            states.sensor.mi_h_1.last_updated,
            states.sensor.mi_h_2.last_updated]%}
          {{ (as_timestamp(now())-as_timestamp(btvalues | max)) > 120 }}
        device_class: problem
        icon_template: >-
          {% if is_state("binary_sensor.bt_stuck", "on") %}
            mdi:bluetooth-off
          {% else %}
            mdi:bluetooth
          {% endif %}
  1. Add the shell command to the configuration:
shell_command:
  restart_bt: touch ~/btrestart.txt
  1. Create the btdown.sh script in the home folder (check the path to the file from the (2) in the flagfile variable):
#!/bin/bash
flagfile="/home/homeassistant/btrestart.txt"
if [ -f "$flagfile" ]
then
	rm -rf $flagfile
        /usr/sbin/modprobe -r btusb
        /usr/sbin/modprobe btusb
else
        :
fi

exit 0
  1. Add the root cron job (change the /home/aleksey/btdown.sh to the path to script from (3)):
# m h  dom mon dow   command
* * * * * /home/aleksey/btdown.sh
  1. Add automation to the configuration, which, when the bt_stuck sensor is triggered, will notify us and create a text flag-file, caught by the cron job:
- alias: BT restart
  description: ''
  trigger:
  - entity_id: binary_sensor.bt_stuck
    from: 'off'
    platform: state
    to: 'on'
  condition: []
  action:
  - service: shell_command.restart_bt
  - data:
      message: BT restarted!
    service: persistent_notification.create

As a result, after 2-3 minutes after stopping the sensors, the kernel module reloads and my bluetooth restores working state.

Personally, I have no experience with ESP32.

4 Likes

Added the binary_sensor and shell_command.
For the script file, cron job i will need to go to where the Pi is installed(my parents).
Going to try it this weekend!

@Magalex Is it an idea to make a custom component that can be installed with HACS, with a readme how to get it running. People now have to look through this topic, and combine two gists to get all the files together. If you don’t have time to do this, I’m willing to do this. But as you (and others) did the hard work, I thought I first ask you.

Somebody can than later try to convert it to a standard component. But I think that’s still some work, as the communication will probably have to be moved to a pypi package.

So, let me know if you want me to setup a custom component for HACS.

This question has already been raised earlier, and I wrote that I do not know the Home Assistant structure well enough to make the component. I am often on business trips, so I can not yet devote enough time to this. In addition, I still expect that @tsymbaliuk as the source of the idea of ​​a passive method will finish this component himself (he wrote about this desire).

But since quite a long time has passed (3.5 months), I am inclined to support you, @Ernst, in your effort. Create a git repo, I will help than I can to do everything as expected.

Ok, I will do that coming week. I do have experience in creating an integration in home assistant, just finished my first (accepted) integration. But I’m not an experienced programmer, so it takes a bit more time. But it works well, even a config flow is included.

@tsymbaliuk If you have plans to set something up in a short time, let me know. I don’t want to interfere with your plans, of course. If you’re planning something, I will wait for that.

Hi, @Magalex!

Firstly, I would like to thank you for your component! Xiaomi Mijia works just great on Raspberry P4 with build-in Bluetooth. Though, the only problem which appears is Bluetooth tracking person stops working. Is there a possible way to fix it?

Thanks!

Are there any error messages in the log? I can not say anything about this problem. Which tracker do you use? bluetooth_le_tracker or bluetooth_tracker?

Thank you for your quick respond!

To your questions, no, i don’t have any errors in the log.
The tracked phone appears and disappears from time to time. With basic component there is no such problem. I’m using

bluetooth_tracker.

I’m afraid that this problem cannot be fixed at the moment … I suspect that since our component uses the bt-interface during all the time between measurements, and for this a low-level system utility with direct access to the interface is used, we are dealing with a certain conflict… I need to try to reproduce the problem, but now I’m on the road, and I have no opportunity for this. The plans have the task of looking for another method, but it will not be so soon. There is also the possibility that this conflict is fundamental, and will prove insoluble.

For now, I propose to ask the other participants if anyone uses our component in combination with a bluetooth-tracker? Are there anyone with such a combination that works without problems?

Hi Magalex, I followed tsymbaliuk instructions and I replaced sensor,py content with code from my gist. i have Raspberry PI 3 B+ with Raspbian+ Home Assistant (venv, virtual environment).
When I restart Home Assistant I have the following error:
Platform error: sensor
Traceback (most recent call last):
File “/srv/homeassistant/lib/python3.7/site-packages/homeassistant/config.py”, line 755, in async_process_component_config
platform = p_integration.get_platform(domain)
File “/srv/homeassistant/lib/python3.7/site-packages/homeassistant/loader.py”, line 232, in get_platform
f"{self.pkg_path}.{platform_name}"
File “/usr/lib/python3.7/importlib/init.py”, line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File “”, line 1006, in _gcd_import
File “”, line 983, in _find_and_load
File “”, line 967, in _find_and_load_unlocked
File “”, line 677, in _load_unlocked
File “”, line 728, in exec_module
File “”, line 219, in _call_with_frames_removed
File “/home/homeassistant/.homeassistant/custom_components/mitemp_bt/sensor.py”, line 17, in
import pexpect
ModuleNotFoundError: No module named ‘pexpect’
Can you help me understand the error and what to do to eliminate it, please?

Try to comment out this line of code (line 17) - import pexpect replace to #import pexpect and restart HA. There are several already unused imports that should be cleaned up … There will be an update soon.

I thank you for the quick reply. I have commented the line 17 and . I no longer have the error but there is no mi_XXXX sensors among the entities. What names should they have?

mi_t_xxxxxxxxxxxxx and mi_h_xxxxxxxxxxxxx. The first time the sensors appear after one or two measurement periods (60 seconds by default).
You can check for relevant processes using shell command ps -A | grep hci. If there is no hcidump process, then it makes sense to try shell command hcitool lescan --duplicates and then hcidump --raw hci, and then proceed based on the result of their execution.

Using shell command ps -A | grep hci, the answer is been:
Q1