Xiaomi Air Purifier - Show all sensors and Switches in UI and HomeKit

Hello, I have 3 days experience in Home Assistant and this was my hardest yet device to integrate, so I want to give back to the community as there’s much confusion in this subject. I’m not a programmer I just built it by copy and paste from the forum.

Do not use the visual interface to integrate the Air Purifier! (I have done this and it managed to mess up the name of the “entity” and the configuration had to change and some other things, lost a lot of time with this)
Use this integration to get the Token directly in Home Assistant without any other android or IOS method.

  1. add this configuration to configuration.yaml
 fan:
  - platform: xiaomi_miio
    host: IP OF THE Air Purifier
    token: YOUR TOKEN
    name: "WHAT NAME YOU WANT FOR THE DEVICE"

Check config using the interface and restart Home Assistant
2. After restart check in the “Entities” section for your Home assistant for an Fan entity, note the “Entity ID” you can check if is working by clicking on it and pushing the icon on the top-right corner.


3. add configuration to “configuration.yaml” and automations to automations.yaml REPLACE the “Entity ID” in all the code, if you have different entity ID. In my example is “fan.xiaomi_air_purifier_pro”
configuration.yaml

sensor:
  # Xiaomi Air Purifier PRO
  - platform: template
    sensors:
      xiaomi_airpurifier_temp:
        friendly_name: "Air Purifier Temperature"
        value_template: "{{ state_attr('fan.xiaomi_air_purifier_pro', 'temperature') }}"
        unit_of_measurement: "°C"
        device_class: "temperature"
        icon_template: "mdiThermometerLines"
      xiaomi_airpurifier_humidity:
        friendly_name: "Air Purifier Humidity"
        value_template: "{{ state_attr('fan.xiaomi_air_purifier_pro', 'humidity') }}"
        unit_of_measurement: "%"
        device_class: "humidity"
        icon_template: "mdiWaterPercent"
      xiaomi_airpurifier_air_quality_pm25:
        friendly_name: "Air Purifier Air quality"
        value_template: "{{ state_attr('fan.xiaomi_air_purifier_pro', 'aqi') }}"
        unit_of_measurement: "μg/m³"
        icon_template: "mdi:weather-fog"
      xiaomi_airpurifier_speed:
        friendly_name: "Air Purifier Fan Speed"
        value_template: "{{ state_attr('fan.xiaomi_air_purifier_pro', 'motor2_speed') }}"
        unit_of_measurement: "rpm"
        icon_template: "mdi:speedometer"
      xiaomi_airpurifier_filter_remaining:
        friendly_name: "Air Purifier Filter Remaining"
        value_template: "{{ state_attr('fan.xiaomi_air_purifier_pro', 'filter_life_remaining') }}"
        unit_of_measurement: "%"
        icon_template: "mdiAirFilter"
      xiaomi_airpurifier_luminance:
        friendly_name: "Air Purifier Luminance"
        value_template: "{{ state_attr('fan.xiaomi_air_purifier_pro', 'illuminance') }}"
        unit_of_measurement: "Lux"
        icon_template: "mdiLightbulbOutline"

switch:
  # Xiaomi Air Purifier PRO
  - platform: template
    switches:
      xiaomi_airpurifier_led:
        friendly_name: "Air Purifier Display"
        value_template: "{{ is_state_attr('fan.xiaomi_air_purifier_pro', 'led', true) }}"
        turn_on:
          service: xiaomi_miio.fan_set_led_on
          data:
            entity_id: fan.xiaomi_air_purifier_pro
        turn_off:
          service: xiaomi_miio.fan_set_led_off
          data:
            entity_id: fan.xiaomi_air_purifier_pro
        icon_template: "mdi:lightbulb-outline"
      xiaomi_airpurifier_child_lock:
        friendly_name: "Air Purifier Child lock"
        value_template: "{{ is_state_attr('fan.xiaomi_air_purifier_pro', 'child_lock', true) }}"
        turn_on:
          service: xiaomi_miio.fan_set_child_lock_on
          data:
            entity_id: fan.xiaomi_air_purifier_pro
        turn_off:
          service: xiaomi_miio.fan_set_child_lock_off
          data:
            entity_id: fan.xiaomi_air_purifier_pro
        icon_template: "mdi:lock-outline"

input_select:
  xiaomi_airpurifier_mode:
    name: Mode
    options:
      - Auto
      - Silent
      - Favorite
    icon: "mdi:animation-outline"

input_number:
  xiaomi_airpurifier_favorite_level:
    name: "Favorite Level"
    initial: 3
    min: 0
    max: 16
    step: 1
    icon: "mdi:weather-windy"

automations.yaml

- alias: Air Purifier mode change
  trigger:
    entity_id: input_select.xiaomi_airpurifier_mode
    platform: state
  action:
    service: fan.set_speed
    data_template:
      entity_id: fan.xiaomi_air_purifier_pro
      speed: '{{ states.input_select.xiaomi_airpurifier_mode.state }}'
- alias: Air Purifier mode changed
  trigger:
    platform: state
    entity_id: fan.xiaomi_air_purifier_pro
  action:
    service: input_select.select_option
    entity_id: input_select.xiaomi_airpurifier_mode
    data_template:
      option: '{{ states.fan.xiaomi_air_purifier_pro.attributes.speed }}'
- alias: Air Purifier favorite level change
  trigger:
    entity_id: input_number.xiaomi_airpurifier_favorite_level
    platform: state
  action:
    service: xiaomi_miio.fan_set_favorite_level
    data_template:
      entity_id: fan.xiaomi_air_purifier_pro
      level: '{{ states.input_number.xiaomi_airpurifier_favorite_level.state | int
        }}'
- alias: Air Purifier favorite level changed
  trigger:
    platform: state
    entity_id: fan.xiaomi_air_purifier_pro
  action:
    service: input_number.set_value
    entity_id: input_number.xiaomi_airpurifier_favorite_level
    data_template:
      value: '{{ states.fan.xiaomi_air_purifier_pro.attributes.favorite_level }}'

Check and restart HA
You can create your Lovelace dashboard using the visual editor once all the Entities are present
What I have changed in the code is:

  • added Luminance sensor (can be used for other automations)
  • changed parameter, motor_speed to motor2_speed (this is now reporting main fan speed correctly)
  • changed to “service: fan.set_speed” in the Air Purifier mode change automation because the original code was not working.

What I want to add:

  • Sound, On/Off button (the Xiaomi aplication has it) managed to add the button but can’t figure out how to make it work.
  • The icons are not shown for filter and luminance (used official mdi but no luck, not important for now)
8 Likes

THANK YOU SOOOOOOOOOOOOO MUCH FOR THAT. Finally I got mine to work (2H)

Hi, Nice to see that you have got it working. I’m fiddling atm with getting my Air purifier integrated. But one thing that is REALLY not clear to me is whether it is necessary to add the xiaomi miio gateway integration from the integrations menu before I can add my air purfier? - it doesn’t say in the documentation, but you must know since you just made it work.

I have added exactly like you

 fan:
  - platform: xiaomi_miio
    host: IP OF THE Air Purifier
    token: YOUR TOKEN
    name: "WHAT NAME YOU WANT FOR THE DEVICE"

to my configuration.yaml

Restarted my server, with no errors, but the fan wont show up in the entities menu… Did you setup a gateway before you did everything that you describe? I’m really not interested in buying a gateway just to have my air purifier connected as it really doesn’t need one, it connects directly over wifi, not through a gateway.

Cheers

As I specified to my first post, do not add the integration from the interface. Remove any old configuration if you added it by the interface, it will mess up the entity creation.
If you added correctly the IP and token the in the configuration YAML it will show up as an fan entity. Check your IP and token, in your case I think that is the issue.

Thanks for the fast reply! :slight_smile: No, I didn’t use the interface integration as it very clearly wants a gateway.
How did you restart you system? Do I need to do a full reboot of the server machine ?

Modify the code and put your IP and token there, save and then go to HA settings and check config and restart.

  1. I add the “fan” with host IP, token and name property
    image
  2. I then reboot my server
  3. I wait 5 minutes… And check back on entities

Still no Air Purifier added. I have also looked through the whole list, not a single one with fan icon, and also nothing when i search “miio”

:thinking: :weary:

Anyone any ideas what could be wrong ? Are there any debugging steps? Any logs that will show failed handshake between device an HA or something like that ?

Everything looks good, from your pictures.
What to check:

  • can you ping the ip address of the purifier? Check the mi home app from for the IP of the purifier.
  • how did you get the token, using the method I discribed or some other way?
  • Check the log of HA after restart, from the visual inyerface
  • do you have some type of firewall that can block the communication?
  • is HA working correctly do you have other sensors connected in LAN?

Thanks for spending so much time with my problem, that’s very generous of you!
I’m using Advanced IP scanne to locate the IP, but I have double checked with the MI Home app, and I have reserved the IP in my route so that it will always be x.x.x.28 whenever the lease is renewed :slight_smile:

  • I got token from NOX player, installing the old version 4.49 something, and extricting the token from the logs. I have done this the same way half a year ago when I was integrating same air purifier with smartthings which worked just fine, so my guess is that the token is good.
  • ping also looks OK.
    image
  • I did not create any firewall rules in my router.
  • I hope HA is working correctly, I have tons of devices connected, only two other over wifi however, two sonos speakers. everything else are zigbee devices connected via either IKEA or smartthings hub.
  • Regarding the logs on the other had, I just found this… which is most likely part of the problem:

Logger: homeassistant.components.fan
Source: helpers/entity_platform.py:208
Integration: Fan (documentation, issues)
First occurred: 5:50:11 PM (24 occurrences)
Last logged: 6:51:42 PM

  • Platform xiaomi_miio not ready yet. Retrying in 60 seconds.
  • Platform xiaomi_miio not ready yet. Retrying in 90 seconds.
  • Platform xiaomi_miio not ready yet. Retrying in 120 seconds.
  • Platform xiaomi_miio not ready yet. Retrying in 150 seconds.
  • Platform xiaomi_miio not ready yet. Retrying in 180 seconds.

But unfortunately it’s a bit cheap on infomation :confused:

I managed to solve the problem. The issue was the token. I’m having two air purfiers, and the tokens got mixed up :relieved: :grimacing: :clown_face: … I dont know how this happened but after swapping the tokens it was added

Hi,
i currently buy a Xiaomi Air Purifier 2H and test the MIIO Integration but don’t get it work.
The following settings are testet in the configuration.yaml.
I double checked the token with the old android app and the Integration from AlexxIT
Do you have any Ideas? I know the 2H Modell is currently not officially supported.

Thanks!

- platform: xiaomi_miio
host: ###hidden###
token: ###hidden###
#model: zhimi.airpurifier.ma2
name: “Air Purifier 2H”

Name: Mi Air Purifier 2H
Model: zhimi.airpurifier.mc2

I have the exact same air purifier, and though it is not officialy supported, it works perfektly when configured right.

image

This is how my configuration.yaml looks. Remember to restart server after adding and wait a bit. Go into logs if still not appearing and see if it says anything about miio integration timeout.

Hello,

Is this still fully functional? For me, “favorite level” and “mode” are not working anymore.

Regards

Same here… can’t figure out what is wrong, my log is clear.

Solved here… Try this:

input_select:
  airpurifier_mode:
    name: Operation mode
    options:
     - Auto
     - Silent
     - Favorite

input_number:
  airpurifier_favorite_level:
    name: Favorite Level
    initial: 1
    min: 0
    max: 16
    step: 1
1 Like

Unfortunately does not work for me…
I will check once again everything.
Thx

Can someone please make a Blueprint for air purifier Pro V7
Please

Everything seems to be working just fine using all the switches, sensors and automations from OP. Still, I’m getting this error when the device is turned off. Any ideas what this is about?

2020-12-16 11:21:09 INFO (MainThread) [homeassistant.components.automation.air_purifier_mode_changed] Air Purifier mode changed: Running automation actions
2020-12-16 11:21:09 INFO (MainThread) [homeassistant.components.automation.air_purifier_mode_changed] Air Purifier mode changed: Executing step call service
2020-12-16 11:21:09 INFO (MainThread) [homeassistant.components.automation.air_purifier_favorite_level_changed] Air Purifier favorite level changed: Running automation actions
2020-12-16 11:21:09 INFO (MainThread) [homeassistant.components.automation.air_purifier_favorite_level_changed] Air Purifier favorite level changed: Executing step call service
2020-12-16 11:21:09 ERROR (MainThread) [homeassistant.components.automation.air_purifier_mode_changed] Air Purifier mode changed: Error executing script. Invalid data for call_service at pos 1: string value is None for dictionary value @ data[‘option’]
2020-12-16 11:21:09 ERROR (MainThread) [homeassistant.components.automation.air_purifier_mode_changed] While executing automation automation.air_purifier_mode_changed
Traceback (most recent call last):
File “/usr/src/homeassistant/homeassistant/components/automation/init.py”, line 433, in async_trigger
await self.action_script.async_run(
File “/usr/src/homeassistant/homeassistant/helpers/script.py”, line 1010, in async_run
await asyncio.shield(run.async_run())
File “/usr/src/homeassistant/homeassistant/helpers/script.py”, line 245, in async_run
await self._async_step(log_exceptions=False)
File “/usr/src/homeassistant/homeassistant/helpers/script.py”, line 253, in _async_step
await getattr(
File “/usr/src/homeassistant/homeassistant/helpers/script.py”, line 460, in _async_call_service_step
await service_task
File “/usr/src/homeassistant/homeassistant/core.py”, line 1405, in async_call
processed_data = handler.schema(service_data)
File “/usr/local/lib/python3.8/site-packages/voluptuous/validators.py”, line 218, in call
return self._exec((Schema(val) for val in self.validators), v)
File “/usr/local/lib/python3.8/site-packages/voluptuous/validators.py”, line 340, in _exec
raise e if self.msg is None else AllInvalid(self.msg, path=path)
File “/usr/local/lib/python3.8/site-packages/voluptuous/validators.py”, line 336, in _exec
v = func(v)
File “/usr/local/lib/python3.8/site-packages/voluptuous/schema_builder.py”, line 272, in call
return self._compiled(, data)
File “/usr/local/lib/python3.8/site-packages/voluptuous/schema_builder.py”, line 817, in validate_callable
return schema(data)
File “/usr/local/lib/python3.8/site-packages/voluptuous/schema_builder.py”, line 272, in call
return self._compiled(, data)
File “/usr/local/lib/python3.8/site-packages/voluptuous/schema_builder.py”, line 594, in validate_dict
return base_validate(path, iteritems(data), out)
File “/usr/local/lib/python3.8/site-packages/voluptuous/schema_builder.py”, line 432, in validate_mapping
raise er.MultipleInvalid(errors)
voluptuous.error.MultipleInvalid: string value is None for dictionary value @ data[‘option’]

1 Like

The error is caused by the device’s speed attribute being null when off, with no corresponding input select option. The solution is to change the automation to ignore updating the mode when the device is turned off:

- id: '43'
  alias: Xiaomi Air Purifier Mode Changed
  trigger:
    entity_id: fan.xiaomi_miio_device
    platform: state
  condition:
    condition: not
    conditions:
      - condition: state
        entity_id: fan.xiaomi_miio_device
        attribute: speed
        state: null
  action:
    service: input_select.select_option
    data_template:
      option: "{{ state_attr('fan.xiaomi_miio_device', 'speed') }}"
    entity_id: input_select.xiaomi_mode
6 Likes

Third day here too. It worked like a charm! Thank you. I used Visual Studio Code add-on and things went smooth with replacing the Entity ID.