mijiaAPI 1.4.3__tar.gz → 1.4.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.4.3
3
+ Version: 1.4.5
4
4
  Summary: A Python API for Xiaomi Mijia
5
5
  License: GPLv3
6
6
  Author: Do1e
@@ -271,6 +271,19 @@ def set(args):
271
271
 
272
272
  def main(args):
273
273
  args = parse_args(args)
274
+
275
+ if args.get_device_info:
276
+ device_info = get_device_info(args.get_device_info)
277
+ print(json.dumps(device_info, indent=2, ensure_ascii=False))
278
+ if not (args.list_devices or
279
+ args.list_homes or
280
+ args.list_scenes or
281
+ args.list_consumable_items or
282
+ args.run_scene or
283
+ args.run or
284
+ hasattr(args, 'func') and args.func is not None):
285
+ return
286
+
274
287
  api = init_api(args.auth_path)
275
288
  device_mapping = None
276
289
  home_mapping = None
@@ -287,9 +300,6 @@ def main(args):
287
300
  if args.run_scene:
288
301
  for scene_id in args.run_scene:
289
302
  run_scene(api, scene_id, scene_mapping=scenes_mapping)
290
- if args.get_device_info:
291
- device_info = get_device_info(args.get_device_info)
292
- print(json.dumps(device_info, indent=2, ensure_ascii=False))
293
303
  if args.run:
294
304
  if device_mapping is None:
295
305
  device_mapping = get_devices_list(api, verbose=False)
@@ -7,7 +7,9 @@ from time import sleep
7
7
  from .apis import mijiaAPI
8
8
  from .code import ERROR_CODE
9
9
  from .urls import deviceURL
10
- from .logger import logger
10
+ from .logger import get_logger
11
+
12
+ logger = get_logger(__name__)
11
13
 
12
14
  class DevProp(object):
13
15
  def __init__(self, prop_dict: dict):
@@ -227,6 +229,7 @@ class mijiaDevices(object):
227
229
  f"message: {ERROR_CODE.get(str(result['code']), 'Unknown error')}"
228
230
  )
229
231
  sleep(self.sleep_time)
232
+ logger.debug(f"Set property: {self.name} -> {name}, value: {value}, result: {result}")
230
233
  return result['code'] == 0
231
234
 
232
235
  def set_v2(self, name: str, value: Union[bool, int, float, str], did: Optional[str] = None) -> bool:
@@ -285,6 +288,7 @@ class mijiaDevices(object):
285
288
  f"message: {ERROR_CODE.get(str(result['code']), 'Unknown error')}"
286
289
  )
287
290
  sleep(self.sleep_time)
291
+ logger.debug(f"Get property: {self.name} -> {name}, result: {result}")
288
292
  return result['value']
289
293
 
290
294
  def __setattr__(self, name: str, value: Union[bool, int, float, str]) -> None:
@@ -368,6 +372,7 @@ class mijiaDevices(object):
368
372
  f"message: {ERROR_CODE.get(str(result['code']), 'Unknown error')}"
369
373
  )
370
374
  sleep(self.sleep_time)
375
+ logger.debug(f"Run action: {self.name} -> {name}, result: {result}")
371
376
  return result['code'] == 0
372
377
 
373
378
 
@@ -427,7 +432,7 @@ def get_device_info(device_model: str, cache_path: Optional[str] = os.path.join(
427
432
  prop_type = prop['format']
428
433
  item = {
429
434
  'name': prop['name'],
430
- 'description': prop['description'],
435
+ 'description': f"{prop.get('description', '')} / {prop.get('desc_zh_cn', '')}",
431
436
  'type': prop_type,
432
437
  'rw': ''.join([
433
438
  'r' if 'read' in prop['access'] else '',
@@ -453,7 +458,7 @@ def get_device_info(device_model: str, cache_path: Optional[str] = os.path.join(
453
458
  actions_name.append(act['name'])
454
459
  result['actions'].append({
455
460
  'name': act['name'],
456
- 'description': act['description'],
461
+ 'description': f"{act.get('description', '')} / {act.get('desc_zh_cn', '')}",
457
462
  'method': {
458
463
  'siid': int(siid),
459
464
  'aiid': int(aiid)
@@ -22,16 +22,24 @@ class ColorFormatter(logging.Formatter):
22
22
  return f"{color_code}{log_message}{self.COLORS['RESET']}"
23
23
  return log_message
24
24
 
25
- logger = logging.getLogger('mijiaAPI')
26
- logger.setLevel(logging.INFO)
25
+ def get_logger(name: str) -> logging.Logger:
26
+ """
27
+ 获取指定名称的日志记录器。
27
28
 
28
- console_handler = logging.StreamHandler()
29
- console_handler.setLevel(logging.INFO)
29
+ Args:
30
+ name (str): 日志记录器的名称。
30
31
 
31
- formatter = ColorFormatter(
32
- '%(asctime)s - %(name)s - %(levelname)s: %(message)s',
33
- datefmt='%Y-%m-%d %H:%M:%S',
34
- )
35
- console_handler.setFormatter(formatter)
32
+ Returns:
33
+ logging.Logger: 日志记录器对象。
34
+ """
35
+ logger = logging.getLogger(name)
36
36
 
37
- logger.addHandler(console_handler)
37
+ console_handler = logging.StreamHandler()
38
+
39
+ formatter = ColorFormatter(
40
+ '%(asctime)s - %(name)s - %(levelname)s: %(message)s',
41
+ datefmt='%Y-%m-%d %H:%M:%S',
42
+ )
43
+ console_handler.setFormatter(formatter)
44
+ logger.addHandler(console_handler)
45
+ return logger
@@ -12,10 +12,11 @@ from urllib import parse
12
12
  import requests
13
13
  from qrcode import QRCode
14
14
 
15
- from .logger import logger
15
+ from .logger import get_logger
16
16
  from .urls import msgURL, loginURL, qrURL, accountURL
17
17
  from .utils import defaultUA
18
18
 
19
+ logger = get_logger(__name__)
19
20
 
20
21
  class LoginError(Exception):
21
22
  def __init__(self, code: int, message: str):
@@ -73,7 +74,7 @@ class mijiaLogin(object):
73
74
  })
74
75
  return data
75
76
 
76
- def _get_account(self, user_id: str) -> dict[str, str]:
77
+ def _get_account_info(self, user_id: str) -> dict[str, str]:
77
78
  """
78
79
  获取账户信息。
79
80
 
@@ -86,18 +87,17 @@ class mijiaLogin(object):
86
87
  Raises:
87
88
  LoginError: 获取账户信息失败时抛出。
88
89
  """
89
- ret = self.session.get(accountURL + str(user_id))
90
- if ret.status_code != 200:
91
- raise LoginError(ret.status_code, f'Failed to get account page, {ret.text}')
92
- ret_data = json.loads(ret.text[11:])['data']
93
- data = {
94
- k: v for k, v in ret_data.items()
95
- if k in ['account', 'gender', 'nickName', 'icon']
96
- }
90
+ try:
91
+ ret = self.session.get(accountURL + str(user_id))
92
+ if ret.status_code != 200:
93
+ raise LoginError(ret.status_code, f'Failed to get account page, {ret.text}')
94
+ data = json.loads(ret.text[11:])['data']
95
+ except (KeyError, json.JSONDecodeError) as e:
96
+ data = {}
97
97
  return data
98
98
 
99
99
  @staticmethod
100
- def extract_latest_gmt_datetime(data: dict) -> datetime:
100
+ def _extract_latest_gmt_datetime(data: dict) -> datetime:
101
101
  """
102
102
  提取过期时间并转换为中国时区。
103
103
 
@@ -157,8 +157,7 @@ class mijiaLogin(object):
157
157
  Raises:
158
158
  LoginError: 登录失败时抛出。
159
159
  """
160
- logger.warning(
161
- 'There is a high probability of verification code with account and password. Please try other login methods')
160
+ logger.warning('There is a high probability of verification code with account and password. Please try `QRlogin` method.')
162
161
  data = self._get_index()
163
162
  post_data = {
164
163
  'qs': data['qs'],
@@ -178,7 +177,7 @@ class mijiaLogin(object):
178
177
  if 'location' not in ret_data:
179
178
  raise LoginError(-1, 'Failed to get location')
180
179
  if 'notificationUrl' in ret_data:
181
- raise LoginError(-1, 'Verification code required, please try other login methods')
180
+ raise LoginError(-1, 'Verification code required, please try `QRlogin` method')
182
181
  ret = self.session.get(ret_data['location'])
183
182
  if ret.status_code != 200:
184
183
  raise LoginError(ret.status_code, f'Failed to get location, {ret.text}')
@@ -189,8 +188,8 @@ class mijiaLogin(object):
189
188
  'ssecurity': ret_data['ssecurity'],
190
189
  'deviceId': data['deviceId'],
191
190
  'serviceToken': cookies['serviceToken'],
192
- 'expireTime': self.extract_latest_gmt_datetime(cookies).strftime('%Y-%m-%d %H:%M:%S'),
193
- **self._get_account(ret_data['userId'])
191
+ 'expireTime': self._extract_latest_gmt_datetime(cookies).strftime('%Y-%m-%d %H:%M:%S'),
192
+ 'account_info': self._get_account_info(ret_data['userId'])
194
193
  }
195
194
 
196
195
  self._save_auth()
@@ -274,8 +273,8 @@ class mijiaLogin(object):
274
273
  'ssecurity': ret_data['ssecurity'],
275
274
  'deviceId': data['deviceId'],
276
275
  'serviceToken': cookies['serviceToken'],
277
- 'expireTime': self.extract_latest_gmt_datetime(cookies).strftime('%Y-%m-%d %H:%M:%S'),
278
- **self._get_account(ret_data['userId'])
276
+ 'expireTime': self._extract_latest_gmt_datetime(cookies).strftime('%Y-%m-%d %H:%M:%S'),
277
+ 'account_info': self._get_account_info(ret_data['userId'])
279
278
  }
280
279
 
281
280
  self._save_auth()
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mijiaAPI"
3
- version = "1.4.3"
3
+ version = "1.4.5"
4
4
  description = "A Python API for Xiaomi Mijia"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.9,<4.0"
@@ -15,7 +15,7 @@ mijiaAPI = "mijiaAPI.__main__:cli"
15
15
 
16
16
  [tool.poetry]
17
17
  name = "mijiaAPI"
18
- version = "1.4.3"
18
+ version = "1.4.5"
19
19
  description = "A Python API for Xiaomi Mijia"
20
20
  authors = ["Do1e <dpj.email@qq.com>"]
21
21
  license = "GPLv3"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes