Xiaomi Gateway (Aqara)

From Domoticz
Jump to navigation Jump to search

Xiaomi Gateway

Xiaomi (Aqara) makes a smart home gateway/hub that has support for a variety of Xiaomi sensors. They can be purchased on Gearbest or AliExpress at very competitive prices. Protocol is Zigbee and WiFi, and the gateway and Domoticz need to be in the same network/subnet.

Multiple gateways are supported but only with limited functionality on the additional gateways.

If you experience problems and are connecting your Domoticz server through a LAN cable, try connecting Domoticz through WiFi instead.

Note that the gateway needs to be at least version 2 (DGNWG02LM). Radio support on the gateway indicates at least version 2. If you are unsure, please ask your supplier before purchasing

Also version V3 and M1S does not seem compatible with Domoticz. As an alternative you can use a Open Source Zigbee controller to connect with the aqara devices

French explanation can be found here : http://domo-attitude.fr/xiaomi-smart-home-presentation-inclusion-domoticz/

All links are to Gearbest, they are one of the cheapest and reliable. Note that when you are using the provided links domoticz got referral points. The idea is to earn something with the points and are giving that back to our community. So when you love domoticz use the links provided below.

Compatible Devices

Compatible Devices:

Xiaomi Gateway LED, Speaker/Alarm, Illumination Sensor Buy online (this one is needed in order for all other devices to work)

  1. Human Body Sensor (Motion Sensor) Buy online
  2. Wireless Smart Switch Buy online
  3. Door/Window Sensor Buy online
  4. Temperature and Humidity Sensor Buy online
  5. Smart Socket/Plug - Zigbee version (The WiFi version is not supported) Buy online
  6. Xiaomi Mi Smart Cube (Xiaomi Mi Magic Controller) Buy online
  7. Wireless Aqara Switch (Dual Button) Buy online
  8. Wireless Aqara Switch (Single Button) Buy online
  9. Wired Aqara Switch (Dual Button) Buy online (uses UK Wall Box)
  10. Wired Aqara Switch (Single Button) Buy online (uses UK Wall Box)
  11. Xiaomi Smoke Detector Buy online
  12. Xiaomi Gas Leak Detector Buy online
  13. Xiaomi Aqara Window Door Sensor Buy online
  14. Xiaomi Aqara Temperature Humidity Sensor Buy online
  15. Xiaomi Water Sensor Buy online
  16. Xiaomi Aqara Wireless Relay Controller (2 Channels) (LLKZMK11LM, relay.c2acn01)

Not Compatible:

Other Xiaomi devices that do not connect directly to the Xiaomi Gateway, such as the Robotic Vacuum, WiFi Power Sockets, Bluetooth Lights, Air Purifier, Kettle etc. Even though these devices may be available in the Mi Home App, they do not communicate directly with the Gateway and so are out of scope of this Domoticz plugin which is only for devices that connect through the Xiaomi Gateway. That is not to say these other devices will not work with Domoticz, only that the will need a different plugin, or script - check the forums for more information.

Xiaomi

Xiaomi Gateway LED, (besides a gateway also a Speaker/Alarm, Illumination Sensor This one is needed in order for all other devices to work Human Body Sensor (Motion Sensor) Wireless Smart Switch Door/Window Sensor
Temperature and Humidity Sensor Smart Socket/Plug - Zigbee version (The WiFi version is not supported) Xiaomi Mi Smart Cube (Xiaomi Mi Magic Controller) Wireless Aqara Switch (Dual Button)
Wireless Aqara Switch (Single Button) Wired Aqara Switch (Dual Button) (uses UK Wall Box) Wired Aqara Switch (Single Button) (uses UK Wall Box) Smoke Detector
Gas Leak Detector Window Door Sensor Temperature Humidity Sensor Water Sensor *this sensor currently requires the Beta version of Domoticz


Adding the Xiaomi Gateway to Domoticz

For Android: You first need to enable local network functions by using the Android Mi Home App https://play.google.com/store/apps/details?id=com.xiaomi.smarthome

  1. Install the App on a Android device
  2. Make sure you set your region to: Mainland China (Seems to be the longest line with Chines characters) under settings -> Locale - at time of writing this seems to be required.
  3. Mainland China and language can set on English
  4. Sign In/make an account
  5. Select your Gateway in Mi Home and with a short while
  6. Then the 3 dots at the top right of the screen
  7. Then click on about
  8. Tap the version (2.36 is the current Android version as of 7 October 2017) number at the bottom of the screen repeatedly
  9. You should see now 2 extra options listed in English (was Chinese in earlier versions)until you did now enable the developer mode. [ if not try all steps again!]
  10. Choose the first new option
  11. Then tap the first toggle switch to enable LAN functions. Note down the password (29p9i40jeypwck38 in the screenshot). Make sure you hit the OK button (to the right of the cancel button) to save your changes.
  12. If you change here something, you lose your password! [ this password you need in Domoticz ]



Now choose the second new menu option, and note down the IP address after "localIp", between all the Chinese text.
Make the IP static in your router!

For iOS: You first need to enable local network functions by using the iOS Mi Home App iosApp Mi

  1. Install the App on a iOS device
  2. Make sure you set your region to: Mainland China under settings -> Locale - required for the moment.
  3. Mainland China and language can set on English
  4. Select your Gateway in Mi Home
  5. Then the 3 dots at the top right of the screen
  6. Then click on about
  7. Tap under Tutorial menu(on the blank part) repeatedly
  8. You should see now 3 extra options listed in Chinese until you did now enable the developer mode. [ if not try all steps again!]
  9. Choose the second new option
  10. Then tap the first toggle switch to enable LAN functions. Note down the password (29p9i40jeypwck38 in the screenshot). Make sure you hit the OK button (to the right of the cancel button) to save your changes.
  11. If you change here something, you lose your password! [ this password you need in Domoticz ]



Now choose the third new menu option, and note down the IP address after "localIp".
Make the IP static in your router!


Then in Domoticz go to Setup -> Hardware, and choose the Xiaomi Gateway Type. Enter the following:

  1. Enable new hardware before the next steps in Domoticz
  2. Name: "Xiaomi Gateway" or anything you want to name it
  3. Remote Address: the IP address of your gateway
  4. Port: Use 9898 Note that you cannot have another service on your system already using port 9898
  5. Password: The password of your gateway

Note that you may need to clear your browser cache if you can't see the Xiaomi Gateway option and/or all the fields

  1. Then click the Add button.
  2. set in Domotic new hardware and devices active (Should be done earlier, I had to delete the gateway and add it again)
  3. Navigate to Setup -> Devices, and you should now see detected devices listed.

You should learn the new Xiaomi devices [ sensors you have ] first on the gateway with the Xiaomi app. When they are learned in the gateway, you will see the devices under new devices in Domoticz.

Playing Gateway Sound

Since FW 1.4.1_145.0141 we are able to play sounds stored on the Gateway (Already stored and personalised ones) for using them Domoticz creates 5 Switches :

  1. Xiaomi Gateway Alarm Ringtone : Off/Police siren 1/Police siren 2/Accident tone/Missle countdown/Ghost/Sniper/War/Air Strike/Barking dogs
  2. Xiaomi Gateway Alarm Clock : Off/MiMix/Enthusiastic/GuitarClassic/IceWorldPiano/LeisureTime/Childhood/MorningStreamlet/MusicBox/Orange/Thinker
  3. Xiaomi Gateway Doorbell : Off/Doorbell ring tone/Knock on door/Hilarious/Alarm clock
  4. Xiaomi Gateway MP3 : Will allow to play personalize sound that you store on the gateway using MiHome App, see below for more information
  5. Xiaomi Gateway Volume : Will allow to set Gateway Volume, each time this slider is triggered gateway will play last sound set from Domoticz


Each Sound can be triggered on Scene/Group/Lua/Blockly and Json Call

The following blockly example will show you how to use sounds. This works identical to selector switches. First check what percentage corresponds to your sound by clicking on the 'edit' button of the sound device, for example the doorbell :

You can use this value in the Blockly script:


About Xiaomi Gateway MP3

This switch allows you to play sound that you have stored on the gateway using the MiHome App. Each sound has a record number which starts with 100xx: 10000 : Is always stop 10001 : First personalise sound 10002 : Second personalise sound etc etc..

When Domoticz creates this Switch, it creates a User Variable : XiaomiMP3 with 10001 as a value : remember what is 10001 ? first sound recorded on the gateway ! Change it for 10002, click on Xiaomi Gateway MP3 switch and it will play sound 10002 which is your second personalised sound.

IMPORTANT : If you record a sound as 10001 and erase it after, 10001 value is no longer usable, each new sound value number growup. Actually, we don't know what is the limit, as on file size and on 100xx value

Easy Way to use personalise sound

To be more easy to use, we "offer" you a simple tweak who allow you to play 99 personalise sound.

First create a dummy Selector, and call it Mid Value, edit this brand new dummy and set it as a Dimmer.

Then Create a Device Lua Script who will react to this Dummy Slider and update XiaomiMP3 user variable

--script_device_Xiaomimp3.lua
--as each sound is recorded as 100+xx value the slider will update user variable to 10000+dimmer value and play sound
commandArray = {}

if devicechanged['Mid Value'] then
      DomValue = otherdevices_svalues['Mid Value'];
       NumericValue = tonumber(DomValue)
            Calcvalue = (NumericValue + 10000)
            
    commandArray['Variable:XiaomiMP3']=''..Calcvalue..''
    print('Xiaomi Gateway will play sound stored on bank '..Calcvalue)
    commandArray['Xiaomi Gateway MP3']='On'

end
return commandArray

On the dimmer pic : value is 3 that mean that Variable:XiaomiMP3 is set to 10003, gateway will play the 3rd sound I store on the gateway.

With this script each time you change value on the dimmer Gateway will automaticaly play sound, not easy to to on point and clik but really usefull on Scene/Group/Lua/Blockly and Json Call, have a try to record fonction from MiHome app, that an easy way to made some vocal notification with your favorite voice

Multiple gateways

You can use multiple gateways with Domoticz, however not all functions are supported. You will be able to control the functions of the additional gateways, such as playing sounds (except for the custom mp3) and using the light, however if you control the light from the Xiaomi Home App, the status change will not be reflected in Domoticz.

To use multiple gateways:

  1. Setup your first (Master) gateway as per normal in Domoticz.
  2. Disable the master gateway in Domoticz.
  3. Setup your second gateway as per normal in Domoticz. (repeat this for each additional gateways, only enabling the newest gateway added each time)
  4. Once all gateways are added, enable all gateways, and restart Domoticz.
  5. If you end up with the same device listed for more than one gateway, delete the additional devices in Domoticz.

Note that only the master gateway will listen for incoming messages (the master gateway is the hardware device in Domoticz with the lowest hardware Id). This is not a perfect solution, and if you have any questions or problems, post in the forum and I will try to address them.


Great job Corbin & Deennoo !!

lua scripts example

Using the Xiaomi round Switch:

commandArray = {}
-- Commande Selector Switch
    if (devicechanged['Xiaomi Switch Micro-onde'] == 'Click') then
        commandArray[1]={['Xiaomi Smart Plug']='On'}
        commandArray[2]={['Xiaomi Smart Plug']='Off AFTER 10'}
    end

    if (devicechanged['Xiaomi Switch Micro-onde'] == 'Double Click') then
        commandArray[1]={['Xiaomi Smart Plug']='On'}
        commandArray[2]={['Xiaomi Smart Plug']='Off AFTER 30'}
    end
    
    if (devicechanged['Xiaomi Switch Micro-onde'] == 'Long Click' ) then
        commandArray['Xiaomi Smart Plug']='On FOR 2'
    end
return commandArray

Xiaomi Motion Sensor to turn on Yeelights at night:

commandArray = {}

local minutesnow = os.date("%H") * 60 + os.date("%M")
local sunrise = timeofday['SunriseInMinutes']
local sunset = timeofday['SunsetInMinutes']

local nighttime = false
if (minutesnow < (sunrise + 25)) or (minutesnow > (sunset - 25)) then
    nighttime = true
end

motionLights = {}
table.insert(motionLights, {sensorName="Xiaomi Kitchen", lightName="YeeLight Kitchen"})
table.insert(motionLights, {sensorName="Xiaomi Bedroom", lightName="YeeLight Bedroom"})
table.insert(motionLights, {sensorName="Xiaomi Toilet", lightName="YeeLight Toilet"})

for deviceName,deviceValue in pairs(devicechanged) do
    if nighttime == true then
        for i, light in ipairs(motionLights) do
            if (deviceName==light["sensorName"]) then
                commandArray[light["lightName"]] = deviceValue
            end
        end
    else
        --need to make sure light turns off when outside of 'nighttime'
        if deviceValue == "Off" then
            for i, light in ipairs(motionLights) do
                if (deviceName==light["sensorName"]) then
                    commandArray[light["lightName"]] = "Off"
                end
            end
        end
    end
end

return commandArray

Blockly examples

Using the Xiaomi round Switch:

Devices Statuses (NOT COMPLETE)

Device Model Statuses
Xiaomi Door Sensor magnet open, close
Aqara Door Sensor sensor_magnet.aq2 status: open, close
no_close: discrette in seconds 120, 300, 600
Aqara Motion Sensor sensor_motion.aq2 status: motion
lux: 0..100
no_motion: discrette in seconds 120, 300, 600
Xiaomi Motion Sensor motion motion
Xiaomi Wireless Switch switch click, double_click
Aqara Wireless Switch sensor_switch.aq2 click, double_click
Aqara Wireless Switch sensor_switch.aq3 click, shake
Xiaomi Smart Plug plug statuses: on, off
inuse: 1, 0
power_consumed: double
load_power: double
Xiaomi Wired Single Wall Switch ctrl_neutral1 on, off
Xiaomi Wired Single Wall Switch ctrl_ln1 on, off
Xiaomi Wired Dual Wall Switch ctrl_neutral2 channel_0: on, off
channel_1: on, off
Xiaomi Wired Dual Wall Switch ctrl_ln2 channel_0: on, off
channel_1: on, off
Xiaomi Wireless Single Wall Switch 86sw1 click, double_click
Xiaomi Smoke Detector smoke status: on, off
alarm: 1, 0
density: 0..255
Xiaomi Gas Detector natgas status: on, off
alarm: 1, 0
density: 0..255
Aqara Water Leak Detector sensor_wleak.aq1 open, closed
Xiaomi Curtain curtain
Xiaomi Aqara Weather weather.v1 temperature, humidity, pressure
Xiaomi Temperature/Humidity sensor_ht temperature, humidity
Xiaomi Cube cube
Aqara Cube sensor_cube.aqgl01 status: flip90,flip180,move,tap_twice,shake_air,swing,alert,free_fall
rotate: integer
Xiaomi Smart Wall Plug 86plug on, off
Xiaomi Aqara Relay relay.c2acn01 channel_0: on, off
channel_1: on, off

Device support (workaround)

Version 2021.1 Beta: For certain devices like the Aqara Relay (LLKZMK11LM a.k.a. relay.c2acn01) the 'model' is not properly send by the Xiaomi Gateway. To work around this problem a DeviceSupport module is added where you can link a device ID to a model. To do so you have to create a user variable named 'XiaomiDeviceSupportRelais' and fill it with the ID string of the relay/relais. You can find this ID in the logfile when you turn on/off the relais manually with the button or with the Xiaomi app but waiting a while also brings up this device in the log.

All ID's for the Xiaomi relay are prefixed with the '158d00' for instance: '158d00045c25cf'. Fill in the link ID string in the user variable called 'XiaomiDeviceSupportRelais' (string type). If you have multiple you can separate them with a comma like this: '158d00045c25cf,158d0003cbe6e8' (but leave out the ').

Restart Domoticz after adding the user variable because the software will only check at startup for performance reasons.

Troubleshooting

Problem Solution
After adding the gateway, no devices are found in Domoticz OR devices do not update state Solution: You need to ensure the system Domoticz is running on can receive UDP Multicast packets.

On Linux, this can be done with

iptables -P OUTPUT ACCEPT

iptables -I INPUT -p udp -j ACCEPT

After adding the gateway, no devices are found in Domoticz OR devices do not update state Make sure the WiFi where your Xiaomi Gateway is connected is on the same subnet as your Domoticz server. Also have your Domoticz server connected directly to the same WiFi network, rather than a LAN cable (try disconnecting the LAN cable as well)
Unable to control devices (Smart Plug/Gateway Light/Alarm) Enter the correct IP address for your gateway. Be aware that if you restart your Xiaomi Gateway, it may get a new IP address and this will need to be updated in Domoticz. Note, devices will still be found if you have an incorrect IP address or password entered.
Error: XiaomiGateway: unable to write command - Invalid Key Enter the correct password for your gateway. Double check it is exact, with no extra spaces.

When you are sure that the password is correct but you are still getting the "Invalid Key" error, you may have multicast blocked in your local network. For TP-Link routers and access points you need to disable "IGMP Snooping"

Web UI -> Network -> uncheck IGMP Snooping

You have the devices discovered and can control them, but after a short time (1mn), you can't anymore. The log shows "Error: XiaomiGateway: unable to write command - Invalid Key" Solution: You need to ensure the system Domoticz is running on can receive UDP Multicast packets.

On Linux, this can be done with

iptables -P OUTPUT ACCEPT

iptables -I INPUT -p udp -j ACCEPT

On Windows add a firewall exception on incoming multicast packet (all profile) for the Domoticz executable

On Raspberry communication is working after setup into Hardware page but not anymore after reboot/restart Check that the option <Wait for Network at Boot> is enabled ( check here for details and screenshots )

You can enable the raw gateway messages to appear in the Domoticz log by creating a user variable 'XiaomiMessage' of type Integer and value 1. (Setup -> More Options -> User Variables). Then restart the Gateway hardware in Domoticz.

You can enable separate voltage devices by adding a user variable 'XiaomiVoltage'. This is not really needed as the battery level should be included with each device, but some users prefer to have the 2 separate devices for each sensor.