Xiaomi Mijia bluetooth temperature & humidity sensor compatibility

in my case, unfortunately, only reboot helped

Have you tried hciconfig hci0 reset? That seemed to work for me.

1 Like

No, just tried hciconfig hci0 down and up. You probably mean hciconfig reset. Thanks for tip!

1 Like

I did this setup and it worked beautifully for a couple of days… Until it seems I’ve run out of memory… Running on a Raspberry Pi 3B w/ 1GB RAM using Hassio on docker over a Raspbian setup.

Mon Sep 09 2019 10:21:11 GMT-0300 (-03)

Error doing job: Future exception was never retrieved
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/config/custom_components/mitemp_bt/sensor.py", line 169, in update_ble
    devs = discover_ble_devices()
  File "/config/custom_components/mitemp_bt/sensor.py", line 160, in discover_ble_devices
    scanner.start()
  File "/config/custom_components/mitemp_bt/sensor.py", line 87, in start
    self.hcitool = subprocess.Popen(['hcitool', 'lescan', '--duplicates'], stdout = DEVNULL)
  File "/usr/local/lib/python3.7/subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "/usr/local/lib/python3.7/subprocess.py", line 1453, in _execute_child
    restore_signals, start_new_session, preexec_fn)
OSError: [Errno 12] Out of memory

Any ideas on how to solve this? It runs for a while when I restart HA, but then it happens again…

Hello!

  1. Please try the current code from my gist - it has many bugs fixed and something has been redone (as I see, you have a rather old version). In addition, while HA is running, it is worth checking how many hcitool and hcidump processes are running (I usually do this using the htop cli-program, where I enable the filter by the string ‘hci’).
  2. Try not to restart HA from the web interface, but stop HA, and then run it from the command line - I noticed that restarting from the web interface spawns zombie processes (I do not know how to deal with it yet).
  3. In addition, if I understand everything correctly, such an error does not mean that a memory leak is caused by a process that failed. It is worth using htop to monitor the processes, sorting the list by memory consumption.

Hi,

I’ve just updated the component to the last code and restarted from cli… Currently htop show only 1 hcidump process… I’ll keep monitoring and let you know.

Thanks for the quick response.

On hassio kinda hard to do theese things :frowning:

Since I run my hassio instance inside a virtual machine, I have a raspberry pi zero that runs a script polling the sensor and then publishes the results over MQTT. I run it by cron every minute, and it’s been completely reliable for months.

temp

Its probably very very ugly, but here’s the code.

import logging
import urllib.request
import base64
import time
import datetime
from threading import Lock, current_thread
import re
import signal
import os
from subprocess import PIPE, Popen, TimeoutExpired
import paho.mqtt.client as paho
import json
from bluepy.btle import Scanner, DefaultDelegate

MI_TEMPERATURE = "temperature"
MI_HUMIDITY = "humidity"
MI_BATTERY = "battery"
MI_UPDATE = "updated"
mac = "4c:65:a8:d9:44:07"
handle = "0x010"
batthandle = "0x18"
value = "0100"
adapter = "hci0"
timeout = 10
text = "nothing here"
broker = "127.0.0.1"
port = 8989

def myconverter(o):
    if isinstance(o, datetime.datetime):
        return o.__str__()

def _on_publish(client,userdata,result):
   print("data published \n")
   pass

def _parse_data(a):
   data = a
   temp,humid = "".join(map(chr, data)).replace("T=", "").replace("H=", "").rstrip(' \t\r\n\0').split(" ")
   res = {}
   res[MI_TEMPERATURE] = temp
   res[MI_HUMIDITY] = humid
   res[MI_BATTERY] = _get_battery()
   res[MI_UPDATE] = datetime.datetime.now()
   return res
   
def _get_battery():
     cmd = "gatttool --device={} --char-read -a {} --adapter={}".format(mac, batthandle, adapter)
     with Popen(cmd,shell=True,stdout=PIPE,preexec_fn=os.setsid) as process:
       try:
         result = process.communicate(timeout=timeout)[0]
       except TimeoutExpired:
         os.killpg(process.pid, signal.SIGINT)
         result = process.communicate()[0]
     result = result.decode("utf-8").strip(' \n\t')
     result2 = re.search("( [0-9a-fA-F][0-9a-fA-F])+", result)
     a = [int(x, 16) for x in result2.group(0).split()]
     return a[0]

def _get_information():
    cmd = "gatttool --device={} --char-write-req -a {} -n {} --adapter={} --listen".format(mac,handle,value,adapter)
    with Popen(cmd,shell=True,stdout=PIPE,preexec_fn=os.setsid) as process:
      try:
        result = process.communicate(timeout=timeout)[0]
        result = result.decode("utf-8").strip(' \n\t')
      except TimeoutExpired:
        os.killpg(process.pid, signal.SIGINT)
        result = process.communicate()[0]
        result = result.decode("utf-8").strip(' \n\t')
        res = re.search("( [0-9a-fA-F][0-9a-fA-F])+", result)
        a = [int(x, 16) for x in res.group(0).split()]
        mydata = _parse_data(a)
        publish(mydata)

def publish(mydata):
    client1 = paho.Client("control1", transport='websockets')
    client1.on_publish = _on_publish
    client1.connect(broker, port)
    json_string = json.dumps(mydata, default = myconverter)
    ret = client1.publish("bluetooth/climate",json_string)
        
_get_information()

Is there a plan to have this newest/working version distributed directly in the hassio package?

According to this conversation it seems that there still is some work to do on the reliability. Therefore I am wondering wether it would worthwhile to test ESPHome option for this sensor? Any comments?

It’s hard to say … Personally, I connect my hopes for good HA integration with the appearance of a programmer here who is ready to do this. My level is not enough for this yet. As i remember, @tsymbaliuk wrote in his first posts that he would not be able to work with this component for the next few months. I can not speak for him, but think, that we should not expect news from him before the end of autumn : man_shrugging:

Can you change the display to show Fahrenheit instead of Celsius?

Are your sensors report temperature as Celsius or Fahrenheit? In other words, do I just need to change the unit of measurement, or must do the conversion from Celsius to Fahrenheit?

i mean the actual display on the device, i haven’t purchased one but if i want the wife approval factor i need it to display fahrenheit on the actual device

It seems that on my device there is no way to switch to degrees Fahrenheit … I see neither the corresponding option in the Mihome application, nor the ability to switch on the device itself. I do not exclude, however, that it can be delivered to different countries in different configurations, and there may be several modifications of the sensor…

Running ESPHome esp32_ble_tracker w/platform: xiaomi_mijia on ESP32 NodeMCU makes my router loose its 2.4GHz bands and requires a router restart.

Seems like the BLE is interfering with my Wi-Fi. Anyone having this issue / Any way to limit the BLE scan?

I see no other way out here, except for finding a solution to the problem from the router side. The only thing that comes to mind is to check for updated firmware for the router. In the worst case, I would think about replacing the router. Personally, I have quite a few wifi devices with quite a lot of traffic, and I do not experience any problems in this regard. The only thing is, if some wifi client with serious traffic appears near the sensor, the number of packets received from the sensor is only slightly reduced:


(every dot here represents the number of received packets per minute.)

I would like to add different solution for different approach. I have used script from git project with some modification. Then communicate using Curl and OpenHAB API. But I think it should be easy to adapt it to HomeAssistant.

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.