### Complete Workflow Example Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mcp-tools.md Example sequence of tool calls to control a device, starting from listing devices to setting specific properties. ```text Claude 用户指令: "请帮我打开卧室台灯,把亮度设置到60%,色温调到暖白色" Claude 将调用: 1. list_devices() - 获取设备列表找到"卧室台灯" 2. get_device_spec("yeelink.light.lamp4") - 查看设备支持的属性 3. set_device_property("brightness", "60", dev_name="卧室台灯") 4. set_device_property("color_temp", "2700", dev_name="卧室台灯") ``` -------------------------------- ### Install from Source Source: https://github.com/do1e/mijia-api/blob/main/docs/guide/installation.md Clone the repository and install locally, with options for editable mode or direct git installation. ```bash git clone https://github.com/Do1e/mijia-api.git cd mijia-api pip install . # Or `pip install -e .` for editable mode # Or `pip install git+https://github.com/Do1e/mijia-api.git` for direct install # Or `uv add git+https://github.com/Do1e/mijia-api.git` for uv users ``` -------------------------------- ### Install via PyPI Source: https://github.com/do1e/mijia-api/blob/main/docs/guide/installation.md Recommended method for standard installations using pip or uv. ```bash pip install mijiaAPI # Or `uv add mijiaAPI` for uv users ``` -------------------------------- ### mijiaAPI Initialization Examples Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md Examples showing different ways to provide the authentication data path. ```python # 使用默认路径 api = mijiaAPI() # 使用自定义文件路径 api = mijiaAPI(auth_data_path="/custom/path/auth.json") # 使用目录路径(自动使用 auth.json) api = mijiaAPI(auth_data_path="/custom/config/dir") ``` -------------------------------- ### mijiaDevice Initialization Examples Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md Examples showing device creation using ID, name, and custom sleep intervals. ```python from mijiaAPI import mijiaAPI, mijiaDevice api = mijiaAPI() api.login() # 通过设备名称创建 device = mijiaDevice(api, dev_name="我的台灯") # 通过设备 ID 创建 device = mijiaDevice(api, did="1234567890") # 自定义延迟 device = mijiaDevice(api, dev_name="我的台灯", sleep_time=1.0) ``` -------------------------------- ### Set Device Property Example Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mcp-tools.md Example usage for setting device properties via Claude. ```text 使用方式(Claude): 把"卧室台灯"的亮度设置为50% 把"客厅台灯"的色温调到暖白色(2700K) 开启"浴室灯" ``` -------------------------------- ### Scene Management Execution Example Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mcp-tools.md Natural language usage examples for running manual scenes via Claude. ```text 使用方式(Claude): 执行"离家模式"场景 运行"睡眠模式" ``` -------------------------------- ### Device Specification Query Example Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mcp-tools.md Example usage for querying device specifications via Claude. ```text 使用方式(Claude): 查看米家台灯1S(yeelink.light.lamp4)支持的所有属性 ``` -------------------------------- ### Device Action Execution Example Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mcp-tools.md Natural language usage examples for triggering device actions via Claude. ```text 使用方式(Claude): 打开"卧室台灯" 让"宠物喂食器"喂食2份 ``` -------------------------------- ### Device Properties Query Example Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mcp-tools.md Example usage for querying specific device properties via Claude. ```text 使用方式(Claude): 查看"卧室台灯"的亮度和色温 ``` -------------------------------- ### Example: Fetching Consumable Items Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaAPI.md Demonstrates initializing the API and iterating through retrieved consumable items. ```python api = mijiaAPI() api.login() items = api.get_consumable_items() for item in items: print(f"设备 {item['name']} 的 {item['details']['description']}: {item['details']['value']}") ``` -------------------------------- ### Install opencode skill Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/skill.md Download the SKILL.md file to the project-specific or global opencode configuration directory. ```bash # 下载到项目内 mkdir -p .opencode/skills/mijia-api && curl -fsSL https://raw.githubusercontent.com/Do1e/mijia-api/main/skills/SKILL.md -o .opencode/skills/mijia-api/SKILL.md # 下载到全局 mkdir -p ~/.config/opencode/skills/mijia-api && curl -fsSL https://raw.githubusercontent.com/Do1e/mijia-api/main/skills/SKILL.md -o ~/.config/opencode/skills/mijia-api/SKILL.md ``` -------------------------------- ### Example: Fetching Device Statistics Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaAPI.md Demonstrates querying monthly power consumption statistics for a specific device. ```python import time from mijiaAPI import mijiaAPI api = mijiaAPI() api.login() # 获取 lumi.acpartner.mcn04 (米家空调伴侣Pro 万能遥控版) 过去 6 个月的月度耗电量统计 ret = api.get_statistics({ "did": "123456", "key": "7.1", "data_type": "stat_month_v3", "limit": 6, "time_start": int(time.time() - 24 * 3600 * 30 * 6), "time_end": int(time.time()), }) for item in ret: value = eval(item['value'])[0] # 解析统计值 ts = item['time'] date = time.strftime('%Y-%m-%d', time.localtime(ts)) print(f'{date}: {value} kWh') ``` -------------------------------- ### Login Tool Return Data Example Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mcp-tools.md Example output returned by the login tool when generating a QR code for authentication. ```text 二维码已生成,请在2分钟内用米家APP扫码完成登录。 二维码图片链接: https://... 扫码后请调用 login_status 查询登录结果。 ``` -------------------------------- ### Install uv package manager Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/skill.md Install the uv tool required to run mijia-api CLI commands. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```bash powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Install via AUR Source: https://github.com/do1e/mijia-api/blob/main/docs/guide/installation.md Installation method for Arch Linux users using the yay package manager. ```bash yay -S python-mijia-api ``` -------------------------------- ### Login Status Tool Usage Example Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mcp-tools.md Example of how to invoke the login status check within an AI assistant like Claude. ```text 使用方式(Claude): 查询登录状态 ``` -------------------------------- ### Start the MCP Server Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/mcp.md Commands to launch the MCP server using uvx, with an optional path for the authentication file. ```bash uvx mijiaAPI mcp # 或指定认证文件路径 uvx mijiaAPI mcp -p /path/to/auth.json ``` -------------------------------- ### Xiaoai Speaker Command Example Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mcp-tools.md Natural language usage examples for controlling devices via Xiaoai speakers. ```text 使用方式(Claude): 用小爱音箱打开客厅的灯 让小爱音箱把温度设置为26度 ``` -------------------------------- ### Install Codex skill Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/skill.md Download the SKILL.md file to the project-specific or global .codex directory. ```bash # 下载到项目内 mkdir -p .codex/skills/mijia-api && curl -fsSL https://raw.githubusercontent.com/Do1e/mijia-api/main/skills/SKILL.md -o .codex/skills/mijia-api/SKILL.md # 下载到全局 mkdir -p ~/.codex/skills/mijia-api && curl -fsSL https://raw.githubusercontent.com/Do1e/mijia-api/main/skills/SKILL.md -o ~/.codex/skills/mijia-api/SKILL.md ``` -------------------------------- ### Statistics Retrieval Example Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mcp-tools.md Natural language usage example for querying device statistics via Claude. ```text 使用方式(Claude): 查看"空调伴侣"过去6个月的耗电量统计 ``` -------------------------------- ### Retrieve scene lists Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaAPI.md Examples of fetching scenes for all homes or a specific home ID. ```python api = mijiaAPI() api.login() # 获取所有场景 all_scenes = api.get_scenes_list() # 获取指定家庭的场景 home_id = "123456" home_scenes = api.get_scenes_list(home_id=home_id) for scene in home_scenes: print(f"场景: {scene['name']}, ID: {scene['scene_id']}") ``` -------------------------------- ### Execute device actions Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaAPI.md Examples of performing single and batch device operations using run_action. ```python api = mijiaAPI() api.login() # yeelink.light.lamp4 (米家台灯 1S) result = api.run_action({ "did": "1234567890", "siid": 2, "aiid": 1 # 开/关灯 }) print(f"执行结果: {result['message']}") # xiaomi.feeder.pi2001 (米家智能宠物喂食器 2) result = api.run_action({ "did": "0987654321", "siid": 2, "aiid": 1, "value": [2] # 喂食 2 份 }) # 批量操作 results = api.run_action([ {"did": "1234567890", "siid": 2, "aiid": 1}, {"did": "0987654321", "siid": 2, "aiid": 1, "value": [1]} ]) ``` -------------------------------- ### Trigger a manual scene Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaAPI.md Example of executing a specific scene using its ID and home ID. ```python api = mijiaAPI() api.login() scene_id = "9876543210" home_id = "123456" if api.run_scene(scene_id, home_id): print("场景执行成功") else: print("场景执行失败") ``` -------------------------------- ### 获取设备属性 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaDevice.md 使用 get() 方法读取设备的当前状态属性。 ```python device = mijiaDevice(api, dev_name="我的台灯") # 获取灯的开关状态 power = device.get("power") print(f"灯的电源状态: {power}") # 获取灯的亮度 brightness = device.get("brightness") print(f"灯的亮度: {brightness}%") ``` -------------------------------- ### Install Claude Code skill Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/skill.md Download the SKILL.md file to the project-specific or global .claude directory to enable the /mijia-api command. ```bash # 下载到项目内 mkdir -p .claude/skills/mijia-api && curl -fsSL https://raw.githubusercontent.com/Do1e/mijia-api/main/skills/SKILL.md -o .claude/skills/mijia-api/SKILL.md # 下载到全局 mkdir -p ~/.claude/skills/mijia-api && curl -fsSL https://raw.githubusercontent.com/Do1e/mijia-api/main/skills/SKILL.md -o ~/.claude/skills/mijia-api/SKILL.md ``` -------------------------------- ### Get and Set Device Properties Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/skill.md Read or modify specific device properties such as brightness or power state. ```bash uvx mijiaAPI get --dev_name "卧室台灯" --prop_name "brightness" uvx mijiaAPI set --dev_name "卧室台灯" --prop_name "brightness" --value 60 uvx mijiaAPI set --dev_name "卧室台灯" --prop_name "on" --value True ``` -------------------------------- ### 使用属性魔法方法 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaDevice.md 通过直接访问对象属性来读写设备状态,无需显式调用 get() 或 set()。 ```python device = mijiaDevice(api, dev_name="我的台灯") # 读取属性(等同于 device.get("power")) power = device.power print(f"灯的电源状态: {power}") # 设置属性(等同于 device.set("brightness", 60)) device.brightness = 60 # 组合操作 device.power = True device.brightness = 80 device.color_temp = 2700 ``` -------------------------------- ### Configure Authentication Path for Subcommands Source: https://github.com/do1e/mijia-api/blob/main/skills/SKILL.md Specify the authentication file path when executing specific subcommands like getting or setting device properties. ```bash uvx mijiaAPI get -p /path --dev_name "台灯" --prop_name "brightness" ``` -------------------------------- ### mijiaAPI get Source: https://github.com/do1e/mijia-api/blob/main/docs/reference/cli-args.md Retrieves specific properties from a Mi Home device. ```APIDOC ## mijiaAPI get ### Description Fetches the value of a specific device property. ### Parameters - **--did** (string) - Optional - Device ID (takes precedence over --dev_name) - **--dev_name** (string) - Optional - Device name as set in the Mi Home app - **--prop_name** (string) - Required - The property name to retrieve ``` -------------------------------- ### Get Device Information Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/skill.md Query device specifications to identify available properties and actions without requiring login. ```bash uvx mijiaAPI --get_device_info yeelink.light.lamp4 ``` -------------------------------- ### Get Device Properties Source: https://github.com/do1e/mijia-api/blob/main/skills/SKILL.md Retrieves the value of a specific property for a device. ```APIDOC ## Get Device Properties ### Description Retrieves the value of a specific property for a device. ### Command `uvx mijiaAPI get --dev_name --prop_name ` ### Parameters - **--prop_name** (string) - Required - Property name - **--dev_name** (string) - Optional (Required if did not provided) - Device name - **--did** (string) - Optional (Required if dev_name not provided) - Device ID - **-p** (path) - Optional - Path to auth.json file ``` -------------------------------- ### CLI 设置设备属性 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 修改设备属性值。 ```bash mijiaAPI set [--did DID | --dev_name DEV_NAME] --prop_name PROP_NAME --value VALUE [-p AUTH_PATH] ``` ```bash # 设置灯的亮度 mijiaAPI set --dev_name "我的台灯" --prop_name "brightness" --value "60" # 打开设备 mijiaAPI set --did "1234567890" --prop_name "power" --value "true" ``` -------------------------------- ### CLI 登录命令 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 使用 login 命令进行二维码登录。 ```bash mijiaAPI login [-p AUTH_PATH] ``` ```bash # 使用默认路径登录 mijiaAPI login # 指定自定义路径登录 mijiaAPI login -p ~/.mijia-api/auth.json ``` -------------------------------- ### Use mijiaAPI via CLI Source: https://github.com/do1e/mijia-api/blob/main/README.md Perform authentication, list devices, and set properties using the command line. ```bash mijiaAPI login # 扫码登录 mijiaAPI -l # 列出所有设备 mijiaAPI set --dev_name "台灯" --prop_name "brightness" --value 60 ``` -------------------------------- ### Control a single device by name Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/README.md Demonstrates initializing the API and setting a device property using the device name. ```python from mijiaAPI import mijiaAPI, mijiaDevice api = mijiaAPI() api.login() # 通过名称获取设备(推荐) device = mijiaDevice(api, dev_name="卧室台灯") device.brightness = 50 ``` -------------------------------- ### CLI 获取设备规格信息 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 根据设备模型获取规格详情。 ```bash mijiaAPI --get_device_info DEVICE_MODEL ``` ```bash # 获取米家台灯 1S 的规格信息 mijiaAPI --get_device_info yeelink.light.lamp4 ``` -------------------------------- ### 获取设备属性 Source: https://github.com/do1e/mijia-api/blob/main/docs/reference/cli-args.md 使用 get 子命令获取指定设备的属性。 ```text usage: mijiaAPI get [-h] [-p AUTH_PATH] [--did DID] [--dev_name DEV_NAME] --prop_name PROP_NAME ``` -------------------------------- ### mijiaAPI.__init__(auth_data_path: Optional[str] = None) Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaAPI.md Initializes the mijiaAPI instance. If no path is provided, it defaults to ~/.config/mijia-api/auth.json. ```APIDOC ## Constructor ### Signature `mijiaAPI(auth_data_path: Optional[str] = None)` ### Parameters - **auth_data_path** (Optional[str]) - Optional - Path to the authentication data file. Defaults to `~/.config/mijia-api/auth.json` if None. ``` -------------------------------- ### get() Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaDevice.md Retrieves the current value of a specific device property. ```APIDOC ## Method: get(name) ### Description Fetches the value of a readable device property. ### Parameters - **name** (str) - Required - The name of the property to retrieve. ### Returns - `Union[bool, int, float, str]` - The current value of the property. ### Exceptions - `ValueError`: If the property is unsupported or not readable. - `DeviceGetError`: If the retrieval fails. ``` -------------------------------- ### mijiaDevice.__init__ Source: https://github.com/do1e/mijia-api/blob/main/docs/reference/mijia-device.md Initializes a new mijiaDevice instance to control a specific Mi Home device. ```APIDOC ## mijiaDevice(api, did=None, dev_name=None, sleep_time=0.5) ### Description Initializes the device controller. You must provide either a `did` or a `dev_name` to identify the target device. ### Parameters - **api** (mijiaAPI) - Required - An authenticated mijiaAPI instance. - **did** (Optional[str]) - Optional - The device ID. - **dev_name** (Optional[str]) - Optional - The device name as set in the Mi Home app. - **sleep_time** (float) - Optional - Sleep duration in seconds after each operation to prevent rate limiting. ``` -------------------------------- ### mijiaAPI get Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md Retrieves the current value of a specific device property. ```APIDOC ## mijiaAPI get ### Description Fetches a specific property value from a device. ### Parameters - **--prop_name** (str) - Required - The name of the property to retrieve - **--did** (str) - Optional - Device ID (mutually exclusive with --dev_name) - **--dev_name** (str) - Optional - Device name (mutually exclusive with --did) - **-p, --auth_path** (Path) - Optional - Path to the authentication file ### Example mijiaAPI get --dev_name "我的台灯" --prop_name "brightness" ``` -------------------------------- ### CLI 认证路径参数使用 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 使用 -p 参数指定自定义认证文件路径或目录。 ```bash # 使用自定义认证文件 mijiaAPI -p /path/to/auth.json -l # 使用目录路径(自动查找 auth.json) mijiaAPI -p /path/to/config/dir -l ``` -------------------------------- ### CLI 执行自然语言指令 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 通过小爱音箱执行自然语言指令。 ```bash mijiaAPI run PROMPT [--wifispeaker_name SPEAKER_NAME] [--quiet] [-p AUTH_PATH] ``` ```bash # 通过小爱音箱执行指令 mijiaAPI run "打开卧室台灯" # 指定音箱并静默执行 mijiaAPI run "把亮度调到 50%" --wifispeaker_name "卧室音箱" --quiet ``` -------------------------------- ### Catching GetDeviceInfoError Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/errors.md Example of catching the GetDeviceInfoError exception when requesting device information. ```python from mijiaAPI import get_device_info, GetDeviceInfoError try: info = get_device_info("invalid.model") except GetDeviceInfoError as e: print(f"获取设备信息失败: {e}") # 获取设备型号 'invalid.model' 的设备信息失败 ``` -------------------------------- ### CLI 获取设备统计数据 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 查询设备的统计信息,如耗电量等。 ```bash mijiaAPI statistics --did DID --key KEY --data_type DATA_TYPE [--limit LIMIT] [--time_start TIME_START] [--time_end TIME_END] [-p AUTH_PATH] ``` ```bash # 获取过去 6 个月的月度耗电量 mijiaAPI statistics --did "123456" --key "7.1" --data_type "stat_month_v3" --limit 6 ``` -------------------------------- ### CLI 列表查询命令 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 列出设备、家庭、场景或耗材信息。 ```bash mijiaAPI -l mijiaAPI --list_homes mijiaAPI --list_scenes mijiaAPI --list_consumable_items ``` -------------------------------- ### Initialize and Control Devices with Python Source: https://github.com/do1e/mijia-api/blob/main/README.md Authenticate via QR code and control devices by name. Authentication files are stored in ~/.config/mijia-api/auth.json by default. ```python from mijiaAPI import mijiaAPI, mijiaDevice # 初始化并扫码登录(认证文件默认保存在 ~/.config/mijia-api/auth.json) api = mijiaAPI() api.login() # 通过设备名称控制设备(推荐) device = mijiaDevice(api, dev_name="我的台灯") device.on = True # 打开设备 device.brightness = 60 # 设置亮度为 60% # 查看设备支持的所有属性和动作 print(device) ``` -------------------------------- ### 使用 CLI 命令行控制设备 Source: https://github.com/do1e/mijia-api/blob/main/docs/guide/quickstart.md 通过命令行工具执行登录、列出设备或设置属性,支持使用 uvx 免安装运行。 ```bash # 扫码登录 mijiaAPI login # 列出所有设备 mijiaAPI -l # 设置设备属性 mijiaAPI set --dev_name "台灯" --prop_name "brightness" --value 60 # 使用 uvx 免安装运行 uvx mijiaAPI -l ``` -------------------------------- ### CLI 版本查询 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 查看当前安装的 mijiaAPI 版本。 ```bash mijiaAPI --version # 输出: mijiaAPI 4.2.1 ``` -------------------------------- ### Layered Error Handling Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/errors.md Example of handling errors at different layers of device control logic. ```python def control_device(dev_name: str, prop_name: str, value): try: device = mijiaDevice(api, dev_name=dev_name) except DeviceNotFoundError: return False, "设备不存在" except MultipleDevicesFoundError as e: return False, str(e) try: device.set(prop_name, value) except ValueError as e: return False, f"参数无效: {e}" except DeviceSetError as e: return False, f"设置失败: {e}" except APIError as e: return False, f"API 错误: {e}" return True, "设置成功" ``` -------------------------------- ### 查看 CLI 帮助信息 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/cli.md 显示 mijiaAPI 的主命令帮助文档。 ```bash mijiaAPI --help ``` -------------------------------- ### List Devices Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/skill.md Retrieve a list of available devices including their names and models. ```bash uvx mijiaAPI -l ``` -------------------------------- ### Catching Specific Exceptions Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/errors.md Best practice for catching specific exceptions during login, device initialization, and property setting. ```python from mijiaAPI import ( mijiaAPI, mijiaDevice, LoginError, DeviceNotFoundError, DeviceSetError, APIError, ) api = mijiaAPI() try: api.login() except LoginError as e: print(f"登录失败: {e}") exit(1) try: device = mijiaDevice(api, dev_name="台灯") except DeviceNotFoundError as e: print(f"设备未找到: {e}") exit(1) try: device.set("brightness", 50) except DeviceSetError as e: print(f"设置失败: {e}") # 继续执行其他操作 except ValueError as e: print(f"参数验证失败: {e}") # 参数错误,不会发送 API 请求 ``` -------------------------------- ### 执行二维码登录 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaAPI.md 使用 QRlogin() 方法进行二维码登录,该方法与 login() 功能相同。 ```python api = mijiaAPI() auth_data = api.QRlogin() ``` -------------------------------- ### Implementing Retry Mechanism Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/errors.md Example of implementing a retry loop for device operations that might fail due to transient errors. ```python import time from mijiaAPI import DeviceSetError, APIError def set_with_retry(device, prop_name, value, max_retries=3): for attempt in range(max_retries): try: device.set(prop_name, value) return True except DeviceSetError as e: if attempt < max_retries - 1: print(f"设置失败,{1}秒后重试... ({attempt + 1}/{max_retries})") time.sleep(1) else: print(f"设置失败,已达到最大重试次数") raise except (ValueError, APIError) as e: print(f"不可重试的错误: {e}") raise ``` -------------------------------- ### CLI 命令行操作示例 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/README.md 通过命令行工具进行登录、设备列表查询、属性读写及操作执行。 ```bash # 登录 mijiaAPI login # 列出所有设备 mijiaAPI -l # 获取设备属性 mijiaAPI get --dev_name "我的台灯" --prop_name "brightness" # 设置设备属性 mijiaAPI set --dev_name "我的台灯" --prop_name "brightness" --value "60" # 执行设备操作 mijiaAPI action --dev_name "我的台灯" --action_name "toggle" # 获取设备规格信息 mijiaAPI --get_device_info yeelink.light.lamp4 ``` -------------------------------- ### CLI MCP 服务启动 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 启动 MCP server 并指定认证文件路径。 ```bash mijiaAPI mcp [-p AUTH_PATH] ``` ```bash # 启动 MCP server mijiaAPI mcp -p ~/.config/mijia-api/auth.json ``` -------------------------------- ### Initialize mijiaDevice Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md Basic initialization of the mijiaDevice class. ```python from mijiaAPI import mijiaDevice device = mijiaDevice( api: mijiaAPI, did: Optional[str] = None, dev_name: Optional[str] = None, sleep_time: float = 0.5, ) ``` -------------------------------- ### 常用 CLI 命令示例 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/cli.md 列出设备、场景管理及自然语言控制等常用操作。 ```bash # 列出所有设备(首先需要这个来获取设备名称) mijiaAPI -l # 列出所有家庭 mijiaAPI --list_homes # 列出所有场景 mijiaAPI --list_scenes # 执行场景 mijiaAPI --run_scene "睡眠模式" "晚安" # 获取设备规格信息 mijiaAPI --get_device_info yeelink.light.lamp4 # 列出耗材 mijiaAPI --list_consumable_items # 执行设备动作 mijiaAPI action --dev_name "卧室台灯" --action_name toggle # 获取统计数据 mijiaAPI statistics --did 123456 --key 7.1 --data_type stat_month_v3 # 使用小爱音箱执行自然语言命令 mijiaAPI run "打开卧室台灯" mijiaAPI run "把亮度调到50%" --wifispeaker_name "卧室小爱" mijiaAPI run "关闭所有灯" --quiet ``` -------------------------------- ### Authenticate and Configure via CLI Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md Authenticate the Mijia API using the CLI and provide the corresponding configuration for Claude Desktop. ```bash # 首先登录获取认证文件 uvx mijiaAPI login -p /path/to/auth.json # 在 Claude Desktop 配置中使用 { "mcpServers": { "mijia-api": { "command": "uvx", "args": ["mijiaAPI", "mcp", "-p", "/path/to/auth.json"] } } } ``` -------------------------------- ### 查看设备属性和动作列表 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/mijia-device.md 遍历 prop_list 和 action_list 以获取设备支持的功能详情。 ```python # 查看所有支持的属性 for prop_name, prop_obj in device.prop_list.items(): print(f"属性: {prop_name} ({prop_obj.desc})") print(f" 类型: {prop_obj.type}, 读写: {prop_obj.rw}") # 查看所有支持的动作 for action_name, action_obj in device.action_list.items(): print(f"动作: {action_name} ({action_obj.desc})") ``` -------------------------------- ### Configure Authentication Path for Global Parameters Source: https://github.com/do1e/mijia-api/blob/main/skills/SKILL.md Specify the authentication file path when using global flags like listing devices or homes. ```bash uvx mijiaAPI -p /path --list_devices ``` -------------------------------- ### CLI 获取设备属性 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 通过设备名称或 ID 获取指定属性。 ```bash mijiaAPI get [--did DID | --dev_name DEV_NAME] --prop_name PROP_NAME [-p AUTH_PATH] ``` ```bash # 通过设备名称获取属性 mijiaAPI get --dev_name "我的台灯" --prop_name "brightness" # 通过设备 ID 获取属性 mijiaAPI get --did "1234567890" --prop_name "power" ``` -------------------------------- ### 执行设备操作 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaDevice.md 使用 run_action() 方法触发设备支持的特定功能或方法。 ```python device = mijiaDevice(api, dev_name="我的台灯") # 简单操作 device.run_action("toggle") # 开关灯 # 带参数的操作 device = mijiaDevice(api, dev_name="我的宠物喂食器") device.run_action("feed", value=[2]) # 喂食 2 份 # 使用 kwargs 传递参数 device.run_action("execute-text-directive", _in=["打开台灯", 0]) ``` -------------------------------- ### 获取设备统计数据 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/cli.md 查询设备的统计信息,支持指定时间范围和数据类型。 ```bash # 默认查询最近 30 天,最多返回 6 条 mijiaAPI statistics --did 123456 --key 7.1 --data_type stat_month_v3 # 指定条数和时间范围(Unix 时间戳,秒) mijiaAPI statistics --did 123456 --key 7.1 --data_type stat_day_v3 \ --limit 30 --time_start 1700000000 --time_end 1702592000 ``` -------------------------------- ### mijiaDevice Constructor Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaDevice.md Initializes a new mijiaDevice instance. Requires an authenticated mijiaAPI instance and either a device ID (did) or a device name (dev_name). ```APIDOC ## Constructor: mijiaDevice(api, did=None, dev_name=None, sleep_time=0.5) ### Description Initializes the device controller. One of `did` or `dev_name` must be provided. ### Parameters - **api** (mijiaAPI) - Required - An initialized mijiaAPI instance. - **did** (Optional[str]) - Optional - The device ID. - **dev_name** (Optional[str]) - Optional - The device name as set in the Mi Home app. - **sleep_time** (float) - Optional - Delay in seconds between operations to prevent rate limiting (default: 0.5). ### Exceptions - `ValueError`: If both `did` and `dev_name` are missing. - `DeviceNotFoundError`: If the device cannot be found. - `MultipleDevicesFoundError`: If multiple devices share the same name. ``` -------------------------------- ### Configure MCP Server Source: https://github.com/do1e/mijia-api/blob/main/README.md Integrate with MCP clients by adding the server configuration to the client settings after logging in. ```json { "mcpServers": { "mijia-api": { "command": "uvx", "args": ["mijiaAPI", "mcp", "-p", "/path/to/auth.json"] } } } ``` -------------------------------- ### 列出设备 Source: https://github.com/do1e/mijia-api/blob/main/skills/SKILL.md 列出所有设备及其基本信息,支持通过指定认证文件路径进行查询。 ```bash uvx mijiaAPI -l uvx mijiaAPI --list_devices uvx mijiaAPI -p /path/to/auth.json -l ``` -------------------------------- ### Perform batch operations on multiple devices Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/README.md Shows how to filter a list of devices and apply property changes to multiple devices in a loop. ```python from mijiaAPI import mijiaAPI api = mijiaAPI() api.login() # 获取所有灯类设备 devices = api.get_devices_list() lights = [d for d in devices if 'light' in d['model'].lower()] # 批量设置 for light in lights: api.set_devices_prop({ "did": light['did'], "siid": 2, "piid": 1, "value": True # 打开所有灯 }) ``` -------------------------------- ### 设置设备属性 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/cli.md 修改设备属性值,例如亮度或开关状态。 ```bash # 查看帮助 mijiaAPI set --help # 设置设备属性 mijiaAPI set --dev_name "卧室台灯" --prop_name "brightness" --value 60 # 打开设备 mijiaAPI set --dev_name "卧室台灯" --prop_name "on" --value True ``` -------------------------------- ### 运行自然语言指令 Source: https://github.com/do1e/mijia-api/blob/main/skills/SKILL.md 通过小爱音箱执行自然语言指令,可指定音箱名称或静默执行。 ```bash uvx mijiaAPI run "打开卧室台灯" uvx mijiaAPI run "把亮度调到50%" --wifispeaker_name "卧室小爱" uvx mijiaAPI run "关闭所有灯" --quiet ``` -------------------------------- ### Logging Configuration Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md How to access and use the library's logging system. ```APIDOC ## Logging ### Description Access the library's logging system to track application events. ### Usage ```python from mijiaAPI.logger import get_logger, logger # Use global logger logger.info("Info message") # Get custom logger custom_logger = get_logger("my_app") ``` ``` -------------------------------- ### Execute Device Action Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/skill.md Trigger a specific action on a device by name. ```bash uvx mijiaAPI action --dev_name "卧室台灯" --action_name toggle ``` -------------------------------- ### 配置认证文件路径 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/best-practices.md 自定义认证文件的存储位置,支持项目目录或指定文件夹路径。 ```python from pathlib import Path # 默认方式(推荐,认证文件保存在 ~/.config/mijia-api/auth.json) api = mijiaAPI() # 方案1:保存在项目目录 auth_path = Path(__file__).parent / ".mijia-api" / "auth.json" api = mijiaAPI(str(auth_path)) # 方案2:直接传入目录,自动创建 auth.json api = mijiaAPI(".mijia-api-data") ``` -------------------------------- ### 获取和设置设备属性 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/mijia-device.md 使用 get/set 方法或属性赋值方式操作设备状态。属性名中的连字符应替换为下划线,重名属性会追加 siid 或 piid。 ```python # 获取属性值 brightness = device.get('brightness') print(f"当前亮度: {brightness}%") # 设置属性值 device.set('brightness', 60) # 设置亮度为60% device.set('on', True) # 打开设备 device.set('color-temperature', 5000) # 设置色温 ``` ```python print(f"当前亮度: {device.brightness}%") device.brightness = 60 # 设置亮度为60% device.on = True # 打开设备 device.color_temperature = 5000 # 设置色温 # 多键开关 device.on_2 = True # 设置 siid=2 的按键 ``` -------------------------------- ### Initialize mijiaAPI Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md Basic initialization of the mijiaAPI class. ```python from mijiaAPI import mijiaAPI # 完整参数 api = mijiaAPI(auth_data_path: Optional[str] = None) ``` -------------------------------- ### 获取统计数据 Source: https://github.com/do1e/mijia-api/blob/main/skills/SKILL.md 获取设备的统计信息,需指定统计键和数据类型。 ```bash uvx mijiaAPI statistics --did 123456 --key 7.1 --data_type stat_month_v3 uvx mijiaAPI statistics --did 123456 --key 7.1 --data_type stat_day_v3 --limit 30 --time_start 1700000000 --time_end 1702592000 ``` -------------------------------- ### mijiaDevice.run_action Source: https://github.com/do1e/mijia-api/blob/main/docs/reference/mijia-device.md Executes a defined action on the device. ```APIDOC ## run_action(name: str, value: Optional[Union[list, tuple]] = None, **kwargs) ### Description Triggers an action on the device. ### Parameters - **name** (str) - Required - The name of the action. - **value** (Optional[Union[list, tuple]]) - Optional - Parameters required for the action. ``` -------------------------------- ### mijia-api CLI Operations Source: https://github.com/do1e/mijia-api/blob/main/skills/SKILL.md Overview of available CLI commands for interacting with Xiaomi smart home devices. ```APIDOC ## CLI Commands ### List Operations - `uvx mijiaAPI --list_devices`: List all devices (including shared). - `uvx mijiaAPI --list_homes`: List homes, rooms, and devices. - `uvx mijiaAPI --list_scenes`: List scenes for each home. - `uvx mijiaAPI --list_consumable_items`: List consumables for each home. ### Device Interaction - `uvx mijiaAPI get --dev_name [name] --prop_name [prop]`: Read a device property. - `uvx mijiaAPI set --dev_name [name] --prop_name [prop] --value [val]`: Set a device property. - `uvx mijiaAPI action --dev_name [name] --action_name [action]`: Execute a device action. - `uvx mijiaAPI statistics --dev_name [name]`: Get device statistics. ### Automation & Utilities - `uvx mijiaAPI --run_scene [name/ID]`: Run one or more scenes. - `uvx mijiaAPI run [command]`: Execute natural language commands via Xiaoai speaker. - `uvx mijiaAPI --get_device_info [MODEL]`: Get device specifications by model (No authentication required). ### Authentication - Use `-p /path/to/auth.json` to specify a custom authentication file path. - Note: Do not call `login` or `mcp` commands as they are blocking. ``` -------------------------------- ### 获取家庭和设备列表 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/basic-api.md 初始化 mijiaAPI 并获取家庭、设备及共享设备列表。需先调用 login() 方法进行身份验证。 ```python from mijiaAPI import mijiaAPI api = mijiaAPI() api.login() # 获取所有家庭 homes = api.get_homes_list() print(homes) # 获取所有设备(不包含共享设备) devices = api.get_devices_list() for device in devices: print(f"设备名称: {device['name']}, Model: {device['model']}, Did: {device['did']}") # 获取指定家庭的设备 home_id = homes[0]['id'] devices_in_home = api.get_devices_list(home_id=home_id) # 获取共享设备列表(无法指定家庭ID) shared_devices = api.get_shared_devices_list() ``` -------------------------------- ### 执行登录操作 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaAPI.md 使用 login() 方法进行二维码登录,并处理可能抛出的 LoginError 异常。 ```python from mijiaAPI import mijiaAPI, LoginError api = mijiaAPI() try: auth_data = api.login() print(f"登录成功,用户ID: {auth_data['userId']}") except LoginError as e: print(f"登录失败: {e}") ``` -------------------------------- ### 获取设备属性 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/cli.md 查询设备当前属性值,支持指定认证文件路径。 ```bash # 查看帮助 mijiaAPI get --help # 获取设备属性 mijiaAPI get --dev_name "卧室台灯" --prop_name "brightness" # 指定认证文件路径 mijiaAPI get -p /path/to/auth.json --dev_name "卧室台灯" --prop_name "on" ``` -------------------------------- ### 查询设备规格信息 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/best-practices.md 利用 get_device_info 或 mijiaDevice 实例查看设备支持的属性和动作。 ```python from mijiaAPI import get_device_info # 从米家规格平台获取设备信息 device_info = get_device_info('yeelink.light.lamp4') # 查看原始信息 import json print(json.dumps(device_info, ensure_ascii=False, indent=2)) # 或者使用 mijiaDevice 类查看 device = mijiaDevice(api, dev_name="我的台灯") print(device) # 会列出所有支持的属性和动作 ``` -------------------------------- ### 获取米家设备列表 Source: https://github.com/do1e/mijia-api/blob/main/docs/guide/quickstart.md 登录后调用 get_devices_list 获取所有设备信息,包括共享设备。 ```python from mijiaAPI import mijiaAPI api = mijiaAPI() api.login() # 获取所有设备(包含共享设备) devices = api.get_devices_list() for device in devices: print(f"设备名称: {device['name']}, Model: {device['model']}, Did: {device['did']}") ``` -------------------------------- ### Retrieve Device List Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaAPI.md Fetches devices for all homes or a specific home ID. ```python def get_devices_list(self, home_id: Optional[str] = None) -> list: ``` ```python api = mijiaAPI() api.login() # 获取所有设备 all_devices = api.get_devices_list() # 获取指定家庭的设备 home_id = "123456" home_devices = api.get_devices_list(home_id=home_id) for device in home_devices: print(f"设备: {device['name']}, 型号: {device['model']}, 在线: {device['isOnline']}") ``` -------------------------------- ### 设置日志级别环境变量 Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/configuration.md 通过设置 MIJIA_LOG_LEVEL 环境变量来控制日志输出级别。 ```bash # 设置调试级别 export MIJIA_LOG_LEVEL=DEBUG python your_script.py # 设置错误级别(减少日志输出) export MIJIA_LOG_LEVEL=ERROR python your_script.py ``` -------------------------------- ### Define run_action method Source: https://github.com/do1e/mijia-api/blob/main/_autodocs/api-reference/mijiaAPI.md Method signature for executing device actions or methods. ```python def run_action(self, data: Union[list, dict]) -> Union[list, dict]: ``` -------------------------------- ### CLI Command Reference Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/skill.md A summary of available CLI commands for interacting with the Mijia API. ```APIDOC ## CLI Commands | Command | Description | Auth Required | |---|---|---| | `--list_devices` | List all devices (including shared) | Yes | | `--list_homes` | List homes, rooms, and devices | Yes | | `--list_scenes` | List scenes for each home | Yes | | `--list_consumable_items` | List consumable items for each home | Yes | | `--run_scene` | Run one or more scenes | Yes | | `--get_device_info` | Get device specifications by model | No | | `get` | Read device properties | Yes | | `set` | Set device properties | Yes | | `action` | Execute device action by name | Yes | | `statistics` | Get device statistics | Yes | | `run` | Execute natural language command via Xiaoai speaker | Yes | ``` -------------------------------- ### 配置环境变量 Source: https://github.com/do1e/mijia-api/blob/main/docs/usage/cli.md 通过环境变量设置日志级别,支持全局设置或在单条命令前临时指定。 ```bash # 设置为 DEBUG 级别查看详细日志 export MIJIA_LOG_LEVEL=DEBUG mijiaAPI --list_devices # 或直接在命令前指定 MIJIA_LOG_LEVEL=WARNING mijiaAPI get --dev_name "卧室台灯" --prop_name "brightness" ```