Code Monkey home page Code Monkey logo

mi-home's Introduction

C# Library for using xiaomi smart gateway in your automation scenarious

Build project Tests Nuget License

This library provides simple and flexible C# API for Xiaomi smart devices.

Currently supports only Gateway version 2 (DGNWG02LM), Gateway version 3 (ZNDMWG03LM), Air Humidifier (zhimi.humidifier.v1), Mi Robot vacuum (rockrobo.vacuum.v1) and several sensors. See table below.

xiaomi-gateway-2

Supported gateway devices/sensors

Device Gateway 2 support Gateway 3 support
Xiaomi Door/Window Sensor

MCCGQ01LM
yes yes
Xiaomi Door/Window Sensor 2

MCCGQ02HL
no yes
Aqara Door/Window Sensor

MCCGQ11LM
yes yes
Xiaomi TH Sensor

WSDCGQ01LM
yes yes
Xiaomi TH Sensor 2

LYWSD03MMC
no yes
Aqara TH Sensor

WSDCGQ11LM
yes yes
Aqara Water Leak Sensor

SJCGQ11LM
yes yes
Xiaomi Motion Sensor

RTCGQ01LM
yes yes
Xiaomi Motion Sensor 2

RTCGQ02LM
no yes
Aqara Relay T1 EU (with N)

SSM-U01
no yes
Aqara Relay CN

LLKZMK11LM
no yes
Aqara Opple Switch (2 buttons)

WXCJKG11LM
no yes
Aqara Opple Switch (4 buttons)

WXCJKG12LM
no yes
Honeywell Smoke Sensor

JTYJ-GD-01LM/BW
yes yes
Honeywell Smoke Alarm

JTYJ-GD-03MI
no yes
Xiaomi Wireless Button

WXKG01LM
yes yes
Xiaomi Plug CN

ZNCZ02LM
yes yes
Aqara Double Wall Switch (no N)

QBKG03LM
yes no
Aqara Double Wall Button CN

WXKG02LM
yes no
Aqara Cube EU

MFKZQ01LM
yes no

via nuget package manager

Install-Package MiHomeLib

or

dotnet add package MiHomeLib

or install via GitHub packages

Before using this library you should setup development mode on your gateway, instructions how to do this.
This mode allows to work with the gateway via UDP multicast protocol.

Warning 1: If you bought a newer revision of Mi Home Gateway (labels in a circle)

It could be possible that ports on your gateway required for UDP multicast traffic are closed.
Before using this library ports must be opened. Check this instruction.

Warning 2: Mi Home Gateway uses udp multicast for messages handling, so your app must be hosted in the same LAN as your gateway. If it is not you have to use multicast routers like udproxy or igmpproxy or vpn bridging.

Warning 3: If your app is running on windows machine, make sure that you disabled virtual network adapters like VirtualBox, Hyper-V, Npcap, pcap etc. Because these adapters may prevent proper work of multicast traffic between your machine and gateway

Before using this library:

  1. Open telnet on your gateway
  2. Expose MQTT broker to the world
  3. Extract token to work with your gateway

The easisest way is to setup/configure this HA integration (it does all aforementioned things automatically).

The way of warrior:

  1. Enable telnet on your gateway
  2. Download this openmiio_agent and upload it to your gateway (for example to /data/openmiio_agent) via telnet
  3. Login to your gateway via telnet telnet <gateway ip> 23 (login: admin, pwd: empty)
  4. Kill embedded mosquitto mqtt broker and run openmiio_agent (it will expose mqtt port 1883 to the world) kill -9 <pid of mosquitto> && /data/openmiio_agent mqtt &
  5. Check that mosquitto is binded to 0.0.0.0 1883 netstat -ntlp | grep mosquitto
  6. Extract token instructions

Get all devices in the network from the Xiaomi Gateway 2

public static void Main(string[] args)
{
    // gateway password is optional, needed only to send commands to your devices
    // gateway sid is optional, use only when you have 2 gateways in your LAN
    // using var gw2 = new XiaomiGateway2("gateway password", "gateway sid");
    using var gw2 = new XiaomiGateway2();
   
    gw2.OnAnyDevice += (_, device) =>
    {
        Console.WriteLine($"{device.Sid}, {device.GetType()}, {device}"); // all discovered devices
    };

    Console.ReadLine();
}

Get all devices in the network from the Xiaomi Gateway 3

public static void Main(string[] args)
{
    using var gw3 = new XiaomiGateway3("<gateway ip>", "<gateway token>");

    gw3.OnDeviceDiscovered += gw3SubDevice =>
    {
        Console.WriteLine(gw3SubDevice.ToString()); // all discovered devices
    };

    gw3.DiscoverDevices();

    Console.ReadLine();
}

Check detailed documentation on how to work with different devices in the project's WIKI

Your pull requests are welcome to replenish the database of supported devices

mi-home's People

Contributors

dependabot[bot] avatar iberisoft avatar jurgen-kluft avatar niksan321 avatar pachman avatar sergey-brutsky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mi-home's Issues

MiHome._devicesList is not thread-safe

I have encountered an exception related to the device list that is owned by the class MiHome. After digging through the behaviour of this class and the async task(s) that add items to the list it is clear that exposing this list as public is dangerous. I have changed the code on my machine to use a ConcurrentDictionary<string, MiHomeDevice> where the key is the SID of the MiHomeDevice (which should be unique). So now adding devices is thread-safe when other places are using this collection.
Also the GetDevices() function returns a List which i construct from the concurrent dictionary before giving the list to the caller, like so:
List<MiHomeDevice> devices = _devicesList.Values.ToList()

No problems so far.

Gateway and Temperature and humidity sensor

Hi,
I have a Xiaomi Mi Home Gateway and two Temperature and humidity sensors that I would like to read using a script in C#.

Could you please provide an example of how to do that?

I followed the guide in https://www.domoticz.com/wiki/Xiaomi_Gateway_(Aqara) and I can get the readings from Domoticz but I cannot make it working using your library in a C# Visual Studio script.
Do I need to specify the IP address of the gateway?
What am I missing?

I am very new on this and I really appreciate some help.
Thanks!

Wireless Switch

Here is the code for the Wireless Switch, have one at home and are running your library with this added Switch, works nicely.

using System;
using Newtonsoft.Json.Linq;

namespace MiHomeLib.Devices
{
    public class WirelessSwitch : MiHomeDevice
    {
        public event EventHandler OnClick;
        public event EventHandler OnDoubleClick;
        public event EventHandler OnLongClickRelease;
        public event EventHandler OnLongClickPress;

        public WirelessSwitch(string sid) : base(sid, "switch") 
        {
            Status = "idle";
        }

        public float? Voltage { get; set; }

        public string Status { get; private set; }

        public override void ParseData(string command)
        {
            var jObject = JObject.Parse(command);

            if (jObject["status"] != null)
            {
                Status = jObject["status"].ToString();

                if (Status == "click")
                {
                    OnClick?.Invoke(this, EventArgs.Empty);
                }
                else if (Status == "double_click")
                {
                    OnDoubleClick?.Invoke(this, EventArgs.Empty);
                }
                else if (Status == "long_click_press")
                {
                    OnLongClickPress?.Invoke(this, EventArgs.Empty);
                }
                else if (Status == "long_click_release")
                {
                    OnLongClickRelease?.Invoke(this, EventArgs.Empty);
                }
            }

            if (jObject["voltage"] != null && float.TryParse(jObject["voltage"].ToString(), out float v))
            {
                Voltage = v / 1000;
            }
        }
        public override string ToString()
        {
            return $"Status: {Status}, Voltage: {Voltage}V";
        }
    }
}

Method Named

Hi, how do I discover which available methods there are for any given device please?
E.g gateway?.EnableLight() is one that you mention in your resdme but how do I find all methods that can be used? I am thinking about trying to use this for my Roborock s5 max vacuum.
Thanks Ben

Gateway version 2.61.3

After updating gateway to the latest avaible version (2.61.3) I can't find any device anymore... I tryed controlling if lan mode was still active, but there's no way to have the 2 more menus tapping on the version number. Any idea?

Unable to Connect to Mi gateway

Hi. I tried your code example from MiHomeConsole. And it is not working for me.
miHome.GetGateway() is always null and miHome.GetDevices() is always empty. I tried both ways - with password and SSID and without them.

Here is my HUB info
photo_2020-02-15_00-32-53 (2)
photo_2020-02-15_00-32-53

I tried to connect to router via Ethernet cable and via Wi-Fi.
IPTV router setting is enabled:
image

I do not have Hyper-V/Virtual box network adapters:
image

My firewall and antivirus are disabled.
I created 4 firewall rules to allow TCP and UDP ingoing and outgoing connection on 9898 port.

I created the forwarding rule for my router:
image

Domoticz is also not working for me. It stuck on http://127.0.0.1:8080/#/Devices page:
image

Have you any more suggestions?
Thank you in advance!

Can't reach any device

Hi,

I tried your example code snippets but nothing happened. I tried to search for all devices, also tried to reach my gateway, but can't see anything (though I have a switch, a cube and a plug). How should these events work? For example when should the OnSocketPlug event fire exactly?
I checked your python script which you mentioned at an other issue, and I receive my gateway's heartbeats, so I guess I should reach it.

Thank you very much in advance,
Peter

Get Error at first time initial

it will get 0 devices first time,
and get error message when dispose miHome object, error:

The given key 'ctrl_ln2.aq1' was not present in the dictionary.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at MiHomeLib.MiHome.GetOrAddDeviceByCommand(ResponseCommand cmd)
   at MiHomeLib.MiHome.ProcessReport(ResponseCommand cmd)
   at MiHomeLib.MiHome.StartReceivingMessages(CancellationToken ct)

but if i use debugger go back to new MiHome, it will get devices (but not aqua wall switch)

And the above error will continue display.

Please help, thanks.

Не отрабатывают EventHandler'ы

Здравствуйте!
Имеется следующая проблема. Инициализирую объект MiHome c паролем и сидом гейта.
Определяются все подключенные к нему устройства. После подписки по сиду датчика влажности и температуры на события ничего не происходит.
miHome = new MiHome("j3kvvz9x4ufgvyzr", "7c49eb88ce6f"); Task.Delay(10000).Wait(); var thSensor = miHome.GetDeviceBySid<ThSensor>("158d0002b54977"); thSensor.OnHumidityChange += ThSensor_OnHumidityChange; thSensor.OnTemperatureChange += ThSensor_OnTemperatureChange;
события не файрятся =(
Помогите пожалуйста разобраться с проблемой. В какую сторону копать.

Unable to Connect to Mi gateway

I tried to connect to mi gateway which locates at the same LAN. However, i didn't see any multicast message located in 224.0.0.50:9898, instead, i saw the multicast on 224.0.0.251:9898. When I send the discover message get_id_list to 224.0.0.251, the returned message is not received by the program, the socket is not able to connect. Here is the error: SocketException: The socket is not connected
System.Net.Sockets.Socket.Shutdown (System.Net.Sockets.SocketShutdown how) (at <3845a180c26b4889bc2d47593a665814>:0)

Can this be used as a relay?

Hi Sergey,
I was wondering if this could be used to relay events from xiaomi devices to somewhere like Hubitat or WebCore? I use Xiaomi devices connected directly to Hubitat and SmartThings hubs but find that the xiaomi devices always drop their connections and the devices do not report back to the hubs in a timely enough manner. It would be more stable to use the actual Xiaomi Gateway hub and then relay the events from the devices to my other hubs. Do you think this would work?

thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.