python-miio 是一个由第三方实现的开源 miIO / MIoT 协议库,兼容大多数小米IoT智能家居设备,python-miio 还附带提供了基于命令行的调试工具 miiocli,供感兴趣的终端用户直接进行调用,本文将作为重点进行讲解。

先决条件

局域网内一台安装python环境的主机。

下面是我的配置

  • 主机:nanopc-t4

  • 系统:unbuntu18.04

  • Python版本:3.6.8

安装python-miio库

1sudo pip3 install python-miio

如果没有pip3工具请先安装python-pip3

1sudo apt-get install python-pip3

安装完成后,输入miiocli,如图所示即可。

获取设备信息

点击下载token_extractor

按照命令行提示输入你的账号密码以及国家即可。

开始操作

米家台灯属于wifi直连的米家设备,可以通过plug指令进行控制,目前我只尝试过三种指令,获取设备状态,开灯,关灯。 根据miio plug --help的提示信息,plug类型设备支持下列操作:

1Commands:
2  info          Get miIO protocol information from the device.
3  off           Power off.
4  on            Power on.
5  raw_command   Send a raw command to the device.
6  set_wifi_led  Set the wifi led on/off.
7  status        Retrieve properties.
8  usb_off       Power off.
9  usb_on        Power on.

更新

针对于米家的灯系列–yeelight,其实有更详细的的操作 miiocli yeelight

 1Options:
 2  --ip TEXT     [required]
 3  --token TEXT  [required]
 4  --model TEXT
 5  --help        Show this message and exit.
 6
 7Commands:
 8  dump_ble_debug            Dump the BLE debug table, defaults to...
 9  info                      Get (and cache) miIO protocol information...
10  off                       Power off.
11  on                        Power on.
12  raw_command               Send a raw command to the device.
13  set_brightness            Set brightness.
14  set_color_temp            Set color temp in kelvin.
15  set_default               Set current state as default.
16  set_developer_mode        Enable or disable the developer mode.
17  set_name                  Set an internal name for the bulb.
18  set_rgb                   Set color in RGB.
19  set_save_state_on_change  Enable or disable saving the state on changes.
20  status                    Retrieve properties.
21  test_properties           Helper to test device properties.
22  toggle                    Toggle bulb state.

查看状态

 1root@NanoPC-T4:~# miiocli yeelight --ip 192.168.0.107 --token f01db26e5eca9669f72abb5a9d92998e status
 2/usr/local/lib/python3.6/dist-packages/miio/protocol.py:37: CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography. The next release of cryptography will remove support for Python 3.6.
 3  from cryptography.hazmat.backends import default_backend
 4Name: 
 5Update default on change: False
 6Delay in minute before off: 0
 7Main light
 8   Power: True
 9   Brightness: 100
10   Color mode: ColorTemperature
11   Temperature: 3900
12   Color flowing mode: False

通过上面的设置指令以及对应状态,即可设置开关,亮度,色温等。

查看设备状态

miiocli plug –ip 192.168.0.107 –token f01db26e5eca9669f72abb5a9d92998e status

开灯

miiocli plug –ip 192.168.0.107 –token f01db26e5eca9669f72abb5a9d92998e on

关灯

miiocli plug –ip 192.168.0.107 –token f01db26e5eca9669f72abb5a9d92998e off

于是,我们就可以这样控制