Xiaomi zigbee smart plug

To clarify it: There is a “wifi version” and a “zigbee” version. The zigbee version works fine with the xiaomi component, because it’s zigbee and paired like any other device. The wifi version needs another protocol and must be integrated separately into home assistant. f.e. by the xiaomiplug custom component (https://github.com/syssi/xiaomiplug).There is no official support of the wifi plug so far.

Furthermore: The wifi version cannot measure power consumption / load / is used. The zigbee version reports this values. If you want to buy one of these devices: Take the zigbee one.

Hi syssi,

Thank you for the help! I bough the zigbee according gearbest but i never had the measuring working, and indeed it connects using wifi. But it was a while ago and I cannot return it.

I’ve installed your module, and already set the configuration. Everything seems to be OK, however my main problem is that i cannot find the token. I’ve read multiple posts where they say that the token can be extracted with “miio --discover” however this command runs in one second and gives me not output. I’m in the same subnet as the plug. Any alternative to get this ID? (already explored the xiaomi app, but no luck either getting de 32 chars token).

Thank you!

Do you own a rooted android device and are you familiar with adb? There is a simple way to extract the token from the sqlite database of the mi home app. I can explain it if you like.

Tks for the quick response! Coincidence because I was already doing this.

I got the token from the sqlite file, and worked on the first execution:
image

Tks for the support and the excellent work!

I check my gearbest purchase order and after all i bought the wireless version (half of the price) because the measuring was not important for that appliance. Know i regret a bit, however thanks to you I can have the included in the platform!

Tks!

1 Like

Perfect! I can recommend the zigbee version. The wifi plug is less responsive and needs to be polled.

Two references for people with the same problem (extract the token from sqlite):


me@laptop:~ $ ./adb connect 192.168.xx.yy
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
connected to 192.168.xx.yy:5555
me@laptop:~ $ ./adb shell
rpi3:/ $ su
rpi3:/data/data # cd com.xiaomi.smarthome/databases/
rpi3:/data/data/com.xiaomi.smarthome/databases # sqlite3
SQLite version 3.9.2 2015-11-02 18:31:45
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open miio2.db
sqlite> .tables
android_metadata  devicerecord
sqlite> select * from devicerecord;

Here you get all the settings along with the token.

sqlite> .quit
rpi3:/data/data/com.xiaomi.smarthome/databases # exit
rpi3:/ $ exit
me@laptop:~ $

There is a column called “token”. A token looks like this: b051cd82786f85996283d82ccf9d27bd2db

What is your config for the socket? I’m confused, because the zigbee version hasn’t IP address, I have the token but I don’t know how to configure it with the gateway. Thanks.

UPDATE:
I found the right conf:

switch:

  • platform: xiaomi_aqara
    name: Socket1
    host: !secret xiaomi_socket_host (Xiaomi Gateway IP)
    key: !secret xiaomi_socket_key (Xiaomi Socket token)

A token isn’t needed for the xiaomi gateway & zigbee sub-devices.

So, If you have two sockets connected, how does hass know each one?

The xiaomi zigbee plugs are enumerated by an unique hardware id.

I’m trying to access the in_use and load_power attributes as triggers for an automation - I want to send a notification if power is on (ie the socket hasn’t been unplugged or turned off at the switch), but the `load_power’ is under some threshold (say 20). I’ve been told that to do this I need to setup 2 template sensors to access these attributes and have code in my configuration.yaml as follows:

sensors:
  - platform: template
    sensors:
      mydevice_power:
        value_template: '{{ states.switch.plug_158d0001xxxxxx.load_power|int }}'
  - platform: template
    sensors:
      mydevice_inuse:
        value_template: '{{ states.switch.plug_158d0001xxxxxx.in_use|default(0) }}'

I’ve played around with various formulations and must admit I can’t fully understand the template after the pipe ‘|’, except it determines the format of what is returned. The sensors show up at the top of my home page, but don’t show values. They are available via the ‘States’ page within HA, so the switches are working and sending values to HA, I just can’t figure out how to access them.

Any pointers appreciated.

Hello.

Try the following instead:

sensors:
  - platform: template
    sensors:
      mydevice_power:
        value_template: '{{ states.switch.plug_158d0001xxxxxx.attributes.load_power|int }}'
  - platform: template
    sensors:
      mydevice_inuse:
        value_template: '{{ states.switch.plug_158d0001xxxxxx.attributes.in_use|default(0) }}'

That should do the trick.

3 Likes

Thanks. That does the job perfectly!

Hi @syssi, I’ve been using the Xiaomi gateway for a month or two and generally it works fine.

I’m running a few movement sensors etc off it and it was pretty much plug and play.

My only issue is with the Plug aka Socket (Zigbee version). When I try to turn it on/off from Homeassistant, it doesn’t work.

Basically, I just turn the switch on/ff via the interface, and the switch moves and after a few seconds reverts back to the original position.
If I use the MiHome app to turn on/off the switch, I see the switch mode within HA changes accordingly. I also get to see the power utilisation etc as it should. See below.

Here’s the log;

2017-10-28 06:05:41 ERROR (MainThread) [homeassistant.core] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
    result = coro.throw(exc)
  File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/core.py", line 1026, in _event_to_service_call
    yield from service_handler.func(service_call)
  File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/components/switch/__init__.py", line 117, in async_handle_switch_service
    yield from switch.async_turn_off()
  File "/usr/lib/python3.5/asyncio/futures.py", line 380, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/lib/python3.5/asyncio/tasks.py", line 304, in _wakeup
    future.result()
  File "/usr/lib/python3.5/asyncio/futures.py", line 293, in result
    raise self._exception
  File "/usr/lib/python3.5/concurrent/futures/thread.py", line 55, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/components/switch/xiaomi_aqara.py", line 106, in turn_off
    if self._write_to_hub(self._sid, **{self._data_key: 'off'}):
  File "/srv/homeassistant/lib/python3.5/site-packages/PyXiaomiGateway/__init__.py", line 290, in write_to_hub
    data['key'] = self._get_key()
  File "/srv/homeassistant/lib/python3.5/site-packages/PyXiaomiGateway/__init__.py", line 320, in _get_key
    encryptor = AES.new(self.key.encode(), AES.MODE_CBC, IV=init_vector)
  File "/srv/homeassistant/lib/python3.5/site-packages/Crypto/Cipher/AES.py", line 95, in new
    return AESCipher(key, *args, **kwargs)
  File "/srv/homeassistant/lib/python3.5/site-packages/Crypto/Cipher/AES.py", line 59, in __init__
    blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
  File "/srv/homeassistant/lib/python3.5/site-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__
    self._cipher = factory.new(key, *args, **kwargs)
ValueError: Key cannot be the null string 

Any thoughts?

Thx
JP

Please post you configuration, too. Do you use a proper key? How did you obtain the key (iOS or android app)? Your backtrace shows the component was unable to encrypt the “turn_off” command because of missing requirements.

Hi @syssi

Here it is. I’ve commented out the key just today. Until then it was running with the key. Either way the other sensors work, and the Plug behaves the same.

xiaomi_aqara:
  gateways:
  #  - mac:
  #    key: 6050E5E0E9594A31

I use the iOS instructions in the docs to obtain the key.

Thx
James

A key is needed to control the device. I think you should regenerate the key with the android app. Take a look here: https://community.home-assistant.io/t/pyxiaomigateway-problem-error-invalid-key/

I’m a rare breed with no access to any android devices - only iOS, MACOS or Windows. Any other thoughts?
Thx
JP

hi, did you manage to solve ir?i have the same isue, im using hass.io, and the discovery found the gateway and plug, but the plug doesnt work just like your problem, besides i cant control the light of the gateway

I had the same issue as you both, managed to fix it by generating a new key in the MiHome app, putting the new key in the config yaml, then it worked

1 Like