mijiaAPI 1.3.4__tar.gz → 1.3.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: mijiaAPI
3
- Version: 1.3.4
3
+ Version: 1.3.5
4
4
  Summary: A Python API for Xiaomi Mijia
5
5
  License: GPLv3
6
6
  Author: Do1e
@@ -1,51 +1,51 @@
1
- # mijiaAPI
2
- 小米米家设备的api,可以使用代码直接控制米家设备的功能,[Github link](https://github.com/Do1e/mijia-api),[PyPI link](https://pypi.org/project/mijiaAPI/)。
3
-
4
- ## 安装
5
- ```bash
6
- poetry install
7
- ```
8
- 或者
9
- ```bash
10
- pip install mijiaAPI
11
- ```
12
-
13
- ## 使用
14
- 使用实例可以参考`demos`文件夹下的示例代码,以下是简单的使用说明
15
-
16
- 有三个类分别用于登录和API调用
17
-
18
- * `mijiaLogin`:登录小米账号,获取控制设备必须的`userId`, `ssecurity`, `deviceId`, `serviceToken`,方法列表
19
- * `login(username: str, password: str) -> dict`:账号密码登录,返回上述信息
20
- * `QRlogin() -> dict`:扫描二维码登录,返回上述信息(会在支持tty的终端打印二维码,若打印识别可查看当前文件夹下的`qr.png`)
21
-
22
- * `mijiaAPI`:API的实现,使用`mijiaLogin`登录后返回的信息进行初始化
23
- * `__init__(auth_data: dict)`:初始化
24
- * `available -> bool`:传入的`auth_data`是否有效
25
- * `get_devices_list() -> list`:获取设备列表
26
- * `get_homes_list() -> list`:获取家庭列表,家庭字典中包含房间列表
27
- * `get_scenes_list(home_id: str) -> list`:获取手动场景列表,在 *米家->添加->手动控制* 中设置
28
- * `run_scene(scene_id: str) -> bool`:运行手动场景
29
- * `get_consumable_items(home_id: str) -> list`:获取设备的耗材信息
30
- * `get_devices_prop(data: list) -> list`:获取设备的属性
31
- * `set_devices_prop(data: list) -> list`:设置设备的属性
32
- * `data`为一个字典的列表,字典需要包含`did`, `siid`, `piid`,后面两个键可从 *https://home.miot-spec.com/spec/{model}* 中获取,其中`model`为设备的model,在设备列表中获取,如[米家台灯 1S](https://home.miot-spec.com/spec/yeelink.light.lamp4)。
33
- * 网站上的方法并非全部可用,需要自行测试
34
- * `run_action(data: dict) -> dict`:执行设备的action
35
- * `data`为一个字典,需要包含`did`, `siid`, `aiid`,获取方法同上
36
-
37
-
38
- * `mijiaDevices`:使用`mijiaAPI`和设备属性字典初始化,以便更方便地调用设备属性
39
- * `__init__(api: mijiaAPI, dev_info: dict. did: str = None, sleep_time: float = 0.5)`:初始化,`dev_info`为设备属性,参考[demos/dev_info_example](demos/dev_info_example),`sleep_time`为每次调用设备属性的间隔时间(注:设置属性后立刻获取属性会不符合预期,需要延迟一段时间)
40
- * `set(name: str, did: str, value: Union[bool, int]) -> Union[bool, int]`:设置设备属性
41
- * `get(name: str, did: str) -> Union[bool, int]`:获取设备属性
42
- * v1.2.0 新增直接通过名称设置/获取属性,需要在初始化时传入`did`,详见[demos/test_devices_v2_light.py](demos/test_devices_v2_light.py)。名称中包含`-`的属性需要替换为`_`。
43
- * **欢迎大家把自己编写的设备属性字典分享到Issues中,方便大家使用**
44
- * 也可以调用`get_device_info(device_model: str) -> dict`函数从[米家设备列表](https://home.miot-spec.com/)在线获取设备属性字典,详见[demos/test_get_device_info.py](demos/test_get_device_info.py)
45
-
46
- ## 致谢
47
- * [janzlan/mijia-api](https://gitee.com/janzlan/mijia-api/tree/master)
48
-
49
- ## 声明
50
- * 本项目仅供学习交流使用,不得用于商业用途,如有侵权请联系删除。
51
- * 本项目作者不对使用本项目产生的任何后果负责,请用户自行承担使用本项目的风险。
1
+ # mijiaAPI
2
+ 小米米家设备的api,可以使用代码直接控制米家设备的功能,[Github link](https://github.com/Do1e/mijia-api),[PyPI link](https://pypi.org/project/mijiaAPI/)。
3
+
4
+ ## 安装
5
+ ```bash
6
+ poetry install
7
+ ```
8
+ 或者
9
+ ```bash
10
+ pip install mijiaAPI
11
+ ```
12
+
13
+ ## 使用
14
+ 使用实例可以参考`demos`文件夹下的示例代码,以下是简单的使用说明
15
+
16
+ 有三个类分别用于登录和API调用
17
+
18
+ * `mijiaLogin`:登录小米账号,获取控制设备必须的`userId`, `ssecurity`, `deviceId`, `serviceToken`,方法列表
19
+ * `login(username: str, password: str) -> dict`:账号密码登录,返回上述信息
20
+ * `QRlogin() -> dict`:扫描二维码登录,返回上述信息(会在支持tty的终端打印二维码,若打印识别可查看当前文件夹下的`qr.png`)
21
+
22
+ * `mijiaAPI`:API的实现,使用`mijiaLogin`登录后返回的信息进行初始化
23
+ * `__init__(auth_data: dict)`:初始化
24
+ * `available -> bool`:传入的`auth_data`是否有效
25
+ * `get_devices_list() -> list`:获取设备列表
26
+ * `get_homes_list() -> list`:获取家庭列表,家庭字典中包含房间列表
27
+ * `get_scenes_list(home_id: str) -> list`:获取手动场景列表,在 *米家->添加->手动控制* 中设置
28
+ * `run_scene(scene_id: str) -> bool`:运行手动场景
29
+ * `get_consumable_items(home_id: str) -> list`:获取设备的耗材信息
30
+ * `get_devices_prop(data: list) -> list`:获取设备的属性
31
+ * `set_devices_prop(data: list) -> list`:设置设备的属性
32
+ * `data`为一个字典的列表,字典需要包含`did`, `siid`, `piid`,后面两个键可从 *https://home.miot-spec.com/spec/{model}* 中获取,其中`model`为设备的model,在设备列表中获取,如[米家台灯 1S](https://home.miot-spec.com/spec/yeelink.light.lamp4)。
33
+ * 网站上的方法并非全部可用,需要自行测试
34
+ * `run_action(data: dict) -> dict`:执行设备的action
35
+ * `data`为一个字典,需要包含`did`, `siid`, `aiid`,获取方法同上
36
+
37
+
38
+ * `mijiaDevices`:使用`mijiaAPI`和设备属性字典初始化,以便更方便地调用设备属性
39
+ * `__init__(api: mijiaAPI, dev_info: dict. did: str = None, sleep_time: float = 0.5)`:初始化,`dev_info`为设备属性,参考[demos/dev_info_example](demos/dev_info_example),`sleep_time`为每次调用设备属性的间隔时间(注:设置属性后立刻获取属性会不符合预期,需要延迟一段时间)
40
+ * `set(name: str, did: str, value: Union[bool, int]) -> Union[bool, int]`:设置设备属性
41
+ * `get(name: str, did: str) -> Union[bool, int]`:获取设备属性
42
+ * v1.2.0 新增直接通过名称设置/获取属性,需要在初始化时传入`did`,详见[demos/test_devices_v2_light.py](demos/test_devices_v2_light.py)。名称中包含`-`的属性需要替换为`_`。
43
+ * **欢迎大家把自己编写的设备属性字典分享到Issues中,方便大家使用**
44
+ * 也可以调用`get_device_info(device_model: str) -> dict`函数从[米家设备列表](https://home.miot-spec.com/)在线获取设备属性字典,详见[demos/test_get_device_info.py](demos/test_get_device_info.py)
45
+
46
+ ## 致谢
47
+ * [janzlan/mijia-api](https://gitee.com/janzlan/mijia-api/tree/master)
48
+
49
+ ## 声明
50
+ * 本项目仅供学习交流使用,不得用于商业用途,如有侵权请联系删除。
51
+ * 本项目作者不对使用本项目产生的任何后果负责,请用户自行承担使用本项目的风险。
@@ -1,155 +1,163 @@
1
- from typing import Tuple
2
- import hashlib
3
- import json
4
- import os
5
- import random
6
- import string
7
- import time
8
- from urllib import parse
9
-
10
- from qrcode import QRCode
11
- import requests
12
-
13
- from .urls import msgURL, loginURL, qrURL
14
- from .utils import defaultUA
15
-
16
- class LoginError(Exception):
17
- def __init__(self, code: int, message: str):
18
- self.code = code
19
- self.message = message
20
- super().__init__(f'Error code: {code}, message: {message}')
21
-
22
- class mijiaLogin(object):
23
- def __init__(self):
24
- self.deviceId = ''.join(random.sample(string.digits + string.ascii_letters, 16))
25
- self.session = requests.Session()
26
- self.session.headers.update({
27
- 'User-Agent': defaultUA,
28
- 'Accept': '*/*',
29
- 'Accept-Encoding': 'gzip, deflate, br, zstd',
30
- 'Accept-Language': 'zh-CN,zh;q=0.9',
31
- 'Cookie': f'deviceId={self.deviceId}; sdkVersion=3.4.1'
32
- })
33
-
34
- def _get_index(self) -> Tuple[requests.Session, dict]:
35
- ret = self.session.get(msgURL)
36
- if ret.status_code != 200:
37
- raise LoginError(ret.status_code, f'Failed to get index page, {ret.text}')
38
- ret_data = json.loads(ret.text[11:])
39
- data = {'deviceId': self.deviceId}
40
- data.update({
41
- k: v for k, v in ret_data.items() \
42
- if k in ['qs', '_sign', 'callback', 'location']
43
- })
44
- return data
45
-
46
- def login(self, username: str, password: str) -> dict:
47
- """login with username and password
48
- mijiaLogin.login(username: str, password: str) -> dict
49
- -------
50
- @param
51
- username: str, xiaomi account username(email/phone number/xiaomi id)
52
- password: str, xiaomi account password
53
- -------
54
- @return
55
- dict, data for authorization, including userId, ssecurity, deviceId, serviceToken
56
- """
57
- data = self._get_index()
58
- post_data = {
59
- 'qs': data['qs'],
60
- '_sign': data['_sign'],
61
- 'callback': data['callback'],
62
- 'sid': 'xiaomiio',
63
- '_json': 'true',
64
- 'user': username,
65
- 'hash': (hashlib.md5(password.encode()).hexdigest().upper() + '0' * 32)[:32],
66
- }
67
- ret = self.session.post(loginURL, data=post_data)
68
- if ret.status_code != 200:
69
- raise LoginError(ret.status_code, f'Failed to post login page, {ret.text}')
70
- ret_data = json.loads(ret.text[11:])
71
- if ret_data['code'] != 0:
72
- raise LoginError(ret_data['code'], ret_data['desc'])
73
- if 'location' not in ret_data:
74
- raise LoginError(-1, 'Failed to get location')
75
- auth_data = {
76
- 'userId': ret_data['userId'],
77
- 'ssecurity': ret_data['ssecurity'],
78
- 'deviceId': data['deviceId'],
79
- }
80
- ret = self.session.get(ret_data['location'])
81
- if ret.status_code != 200:
82
- raise LoginError(ret.status_code, f'Failed to get location, {ret.text}')
83
- cookies = self.session.cookies.get_dict()
84
- auth_data['serviceToken'] = cookies['serviceToken']
85
- self.auth_data = auth_data
86
- return auth_data
87
-
88
- @staticmethod
89
- def _print_qr(loginurl: str, box_size: int = 10) -> None:
90
- print('Scan the QR code below with Mi Home app')
91
- qr = QRCode(border=1, box_size=box_size)
92
- qr.add_data(loginurl)
93
- qr.make_image().save('qr.png')
94
- try:
95
- qr.print_ascii(invert=True, tty=True)
96
- except OSError:
97
- print('Failed to print QR code to terminal, please use the qr.png file in the current directory.')
98
-
99
- def QRlogin(self) -> dict:
100
- """login with QR code
101
- mijiaLogin.QRlogin() -> dict
102
- -------
103
- @return
104
- dict, data for authorization, including userId, ssecurity, deviceId, serviceToken
105
- """
106
- data = self._get_index()
107
- location = data['location']
108
- location_parsed = parse.parse_qs(parse.urlparse(location).query)
109
- params = {
110
- '_qrsize': 240,
111
- 'qs': data['qs'],
112
- 'bizDeviceType': '',
113
- 'callback': data['callback'],
114
- '_json': 'true',
115
- 'theme': '',
116
- 'sid': 'xiaomiio',
117
- 'needTheme': 'false',
118
- 'showActiveX': 'false',
119
- 'serviceParam': location_parsed['serviceParam'][0],
120
- '_local': 'zh_CN',
121
- '_sign': data['_sign'],
122
- '_dc': str(int(time.time() * 1000)),
123
- }
124
- url = qrURL + '?' + parse.urlencode(params)
125
- ret = self.session.get(url)
126
- if ret.status_code != 200:
127
- raise LoginError(ret.status_code, f'Failed to get QR code URL, {ret.text}')
128
- ret_data = json.loads(ret.text[11:])
129
- if ret_data['code'] != 0:
130
- raise LoginError(ret_data['code'], ret_data['desc'])
131
- loginurl = ret_data['loginUrl']
132
- self._print_qr(loginurl)
133
- try:
134
- ret = self.session.get(ret_data['lp'], timeout=60, headers={'Connection': 'keep-alive'})
135
- except requests.exceptions.Timeout:
136
- raise LoginError(-1, 'Timeout, please try again')
137
- if ret.status_code != 200:
138
- raise LoginError(ret.status_code, f'Failed to wait for login, {ret.text}')
139
- ret_data = json.loads(ret.text[11:])
140
- if ret_data['code'] != 0:
141
- raise LoginError(ret_data['code'], ret_data['desc'])
142
- auth_data = {
143
- 'userId': ret_data['userId'],
144
- 'ssecurity': ret_data['ssecurity'],
145
- 'deviceId': data['deviceId'],
146
- }
147
- ret = self.session.get(ret_data['location'])
148
- if ret.status_code != 200:
149
- raise LoginError(ret.status_code, f'Failed to get location, {ret.text}')
150
- cookies = self.session.cookies.get_dict()
151
- auth_data['serviceToken'] = cookies['serviceToken']
152
- self.auth_data = auth_data
153
- if os.path.exists('qr.png'):
154
- os.remove('qr.png')
155
- return auth_data
1
+ from typing import Tuple
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import random
6
+ import string
7
+ import sys
8
+ import time
9
+ from urllib import parse
10
+
11
+ from qrcode import QRCode
12
+ import requests
13
+
14
+ from .urls import msgURL, loginURL, qrURL
15
+ from .utils import defaultUA
16
+
17
+ class LoginError(Exception):
18
+ def __init__(self, code: int, message: str):
19
+ self.code = code
20
+ self.message = message
21
+ super().__init__(f'Error code: {code}, message: {message}')
22
+
23
+ class mijiaLogin(object):
24
+ def __init__(self):
25
+ self.deviceId = ''.join(random.sample(string.digits + string.ascii_letters, 16))
26
+ self.session = requests.Session()
27
+ self.session.headers.update({
28
+ 'User-Agent': defaultUA,
29
+ 'Accept': '*/*',
30
+ 'Accept-Encoding': 'gzip, deflate, br, zstd',
31
+ 'Accept-Language': 'zh-CN,zh;q=0.9',
32
+ 'Cookie': f'deviceId={self.deviceId}; sdkVersion=3.4.1'
33
+ })
34
+
35
+ def _get_index(self) -> Tuple[requests.Session, dict]:
36
+ ret = self.session.get(msgURL)
37
+ if ret.status_code != 200:
38
+ raise LoginError(ret.status_code, f'Failed to get index page, {ret.text}')
39
+ ret_data = json.loads(ret.text[11:])
40
+ data = {'deviceId': self.deviceId}
41
+ data.update({
42
+ k: v for k, v in ret_data.items() \
43
+ if k in ['qs', '_sign', 'callback', 'location']
44
+ })
45
+ return data
46
+
47
+ def login(self, username: str, password: str) -> dict:
48
+ """login with username and password
49
+ mijiaLogin.login(username: str, password: str) -> dict
50
+ -------
51
+ @param
52
+ username: str, xiaomi account username(email/phone number/xiaomi id)
53
+ password: str, xiaomi account password
54
+ -------
55
+ @return
56
+ dict, data for authorization, including userId, ssecurity, deviceId, serviceToken
57
+ """
58
+ warning_msg = 'WARNING: there is a high probability of verification code with account and password. Please try other login methods'
59
+ if sys.stdout.isatty():
60
+ print(f'\033[33;1m{warning_msg}\033[0m')
61
+ else:
62
+ print(warning_msg)
63
+ data = self._get_index()
64
+ post_data = {
65
+ 'qs': data['qs'],
66
+ '_sign': data['_sign'],
67
+ 'callback': data['callback'],
68
+ 'sid': 'xiaomiio',
69
+ '_json': 'true',
70
+ 'user': username,
71
+ 'hash': (hashlib.md5(password.encode()).hexdigest().upper() + '0' * 32)[:32],
72
+ }
73
+ ret = self.session.post(loginURL, data=post_data)
74
+ if ret.status_code != 200:
75
+ raise LoginError(ret.status_code, f'Failed to post login page, {ret.text}')
76
+ ret_data = json.loads(ret.text[11:])
77
+ if ret_data['code'] != 0:
78
+ raise LoginError(ret_data['code'], ret_data['desc'])
79
+ if 'location' not in ret_data:
80
+ raise LoginError(-1, 'Failed to get location')
81
+ if 'notificationUrl' in ret_data:
82
+ raise LoginError(-1, 'Verification code required, please try other login methods')
83
+ auth_data = {
84
+ 'userId': ret_data['userId'],
85
+ 'ssecurity': ret_data['ssecurity'],
86
+ 'deviceId': data['deviceId'],
87
+ }
88
+ ret = self.session.get(ret_data['location'])
89
+ if ret.status_code != 200:
90
+ raise LoginError(ret.status_code, f'Failed to get location, {ret.text}')
91
+ cookies = self.session.cookies.get_dict()
92
+ auth_data['serviceToken'] = cookies['serviceToken']
93
+ self.auth_data = auth_data
94
+ return auth_data
95
+
96
+ @staticmethod
97
+ def _print_qr(loginurl: str, box_size: int = 10) -> None:
98
+ print('Scan the QR code below with Mi Home app')
99
+ qr = QRCode(border=1, box_size=box_size)
100
+ qr.add_data(loginurl)
101
+ qr.make_image().save('qr.png')
102
+ try:
103
+ qr.print_ascii(invert=True, tty=True)
104
+ except OSError:
105
+ print('Failed to print QR code to terminal, please use the qr.png file in the current directory.')
106
+
107
+ def QRlogin(self) -> dict:
108
+ """login with QR code
109
+ mijiaLogin.QRlogin() -> dict
110
+ -------
111
+ @return
112
+ dict, data for authorization, including userId, ssecurity, deviceId, serviceToken
113
+ """
114
+ data = self._get_index()
115
+ location = data['location']
116
+ location_parsed = parse.parse_qs(parse.urlparse(location).query)
117
+ params = {
118
+ '_qrsize': 240,
119
+ 'qs': data['qs'],
120
+ 'bizDeviceType': '',
121
+ 'callback': data['callback'],
122
+ '_json': 'true',
123
+ 'theme': '',
124
+ 'sid': 'xiaomiio',
125
+ 'needTheme': 'false',
126
+ 'showActiveX': 'false',
127
+ 'serviceParam': location_parsed['serviceParam'][0],
128
+ '_local': 'zh_CN',
129
+ '_sign': data['_sign'],
130
+ '_dc': str(int(time.time() * 1000)),
131
+ }
132
+ url = qrURL + '?' + parse.urlencode(params)
133
+ ret = self.session.get(url)
134
+ if ret.status_code != 200:
135
+ raise LoginError(ret.status_code, f'Failed to get QR code URL, {ret.text}')
136
+ ret_data = json.loads(ret.text[11:])
137
+ if ret_data['code'] != 0:
138
+ raise LoginError(ret_data['code'], ret_data['desc'])
139
+ loginurl = ret_data['loginUrl']
140
+ self._print_qr(loginurl)
141
+ try:
142
+ ret = self.session.get(ret_data['lp'], timeout=60, headers={'Connection': 'keep-alive'})
143
+ except requests.exceptions.Timeout:
144
+ raise LoginError(-1, 'Timeout, please try again')
145
+ if ret.status_code != 200:
146
+ raise LoginError(ret.status_code, f'Failed to wait for login, {ret.text}')
147
+ ret_data = json.loads(ret.text[11:])
148
+ if ret_data['code'] != 0:
149
+ raise LoginError(ret_data['code'], ret_data['desc'])
150
+ auth_data = {
151
+ 'userId': ret_data['userId'],
152
+ 'ssecurity': ret_data['ssecurity'],
153
+ 'deviceId': data['deviceId'],
154
+ }
155
+ ret = self.session.get(ret_data['location'])
156
+ if ret.status_code != 200:
157
+ raise LoginError(ret.status_code, f'Failed to get location, {ret.text}')
158
+ cookies = self.session.cookies.get_dict()
159
+ auth_data['serviceToken'] = cookies['serviceToken']
160
+ self.auth_data = auth_data
161
+ if os.path.exists('qr.png'):
162
+ os.remove('qr.png')
163
+ return auth_data
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "mijiaAPI"
3
- version = "1.3.4"
3
+ version = "1.3.5"
4
4
  description = "A Python API for Xiaomi Mijia"
5
5
  authors = ["Do1e <dpj.email@qq.com>"]
6
6
  license = "GPLv3"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes