├── .gitignore ├── const.py ├── manifest.json ├── translations ├── zh-Hans.json └── en.json ├── strings.json ├── coordinator.py ├── readme.md ├── __init__.py ├── button.py ├── config_flow.py ├── cover.py ├── switch.py ├── xiaodu.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ -------------------------------------------------------------------------------- /const.py: -------------------------------------------------------------------------------- 1 | """Constants for the xiaodu api integration.""" 2 | 3 | DOMAIN = "xiaodu" 4 | 5 | Cookie = 'cookie' 6 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "xiaodu", 3 | "name": "XiaoDu API", 4 | "config_flow": true, 5 | "documentation": "https://github.com/apgmer/hass-xiaodu", 6 | "requirements": [], 7 | "ssdp": [], 8 | "zeroconf": [], 9 | "homekit": {}, 10 | "dependencies": [], 11 | "codeowners": [ 12 | "@apgmer" 13 | ], 14 | "iot_class": "cloud_polling", 15 | "version": "0.1.0" 16 | } 17 | -------------------------------------------------------------------------------- /translations/zh-Hans.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "abort": { 4 | "already_configured": "Device is already configured" 5 | }, 6 | "error": { 7 | "cannot_connect": "Failed to connect", 8 | "invalid_auth": "Invalid authentication", 9 | "unknown": "Unexpected error" 10 | }, 11 | "step": { 12 | "user": { 13 | "title": "小度配置", 14 | "data": { 15 | "cookie": "百度Cookie" 16 | } 17 | } 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /translations/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "abort": { 4 | "already_configured": "Device is already configured" 5 | }, 6 | "error": { 7 | "cannot_connect": "Failed to connect", 8 | "invalid_auth": "Invalid authentication", 9 | "unknown": "Unexpected error" 10 | }, 11 | "step": { 12 | "user": { 13 | "title": "XiaoDu Configuration", 14 | "data": { 15 | "cookie": "baidu Cookie" 16 | } 17 | } 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /strings.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "step": { 4 | "user": { 5 | "title": "[%key:common::config_flow::title%]", 6 | "data": { 7 | "cookie": "[%key:common::config_flow::data::cookie%]" 8 | } 9 | } 10 | }, 11 | "error": { 12 | "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", 13 | "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", 14 | "unknown": "[%key:common::config_flow::error::unknown%]" 15 | }, 16 | "abort": { 17 | "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /coordinator.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | from datetime import timedelta 5 | 6 | import async_timeout 7 | 8 | from homeassistant.core import HomeAssistant 9 | from homeassistant.helpers.update_coordinator import ( 10 | DataUpdateCoordinator, 11 | ) 12 | from .xiaodu import XiaoDuHub 13 | 14 | _LOGGER = logging.getLogger(__name__) 15 | 16 | 17 | class XiaoDuCoordinator(DataUpdateCoordinator): 18 | 19 | def __init__(self, hass: HomeAssistant, hub: XiaoDuHub): 20 | super().__init__( 21 | hass, 22 | _LOGGER, 23 | name="xiaodu api", 24 | update_interval=timedelta(seconds=10), 25 | ) 26 | self.hub = hub 27 | 28 | async def _async_update_data(self): 29 | async with async_timeout.timeout(10): 30 | return await self.hub.deviceList() 31 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # homeassistant 自定义 integration 集成xiaodu 2 | 3 | ## 拉取xiaodu小度设备到ha中 4 | 5 | [https://xiaodu.baidu.com/saiya/smarthome/index.html](https://xiaodu.baidu.com/saiya/smarthome/index.html) 6 | 7 | ![img1](https://i.tiecode.xyz/20221012/img1.52mnkqh0v740.webp) 8 | 9 | ## 用法: 10 | 11 | clone 代码到 custom_components/xiaodu 12 | 13 | configuration.yaml xiaodu: 14 | 15 | 1. 添加继承 XiaoDu Api 16 | 2. 打开上述网站,登录百度账号,在接口调用中赋值request全部Cookie 17 | 3. 上述1中添加Cookie 18 | 19 | ## 支持设备类型 20 | 21 | 小度设备类型 对应 HA 设备类型 22 | 23 | - [x] `SWITCH`, `OUTLET` 解析为 `Platform.SWITCH` 开关/插座 24 | - [x] `SCENE_TRIGGER` 解析为 `Platform.BUTTON` 按钮 25 | - [x] `CURTAIN` 解析为 `Platform.COVER` 窗帘 26 | - 窗帘只能控制开/关/停 不能控制进度。 位置 > 50 执行关 否则执行开 27 | 28 | ## 其他 29 | 30 | 1. Cookie有失效时间 31 | 2. **在厂商的app中操作开关状态后无法,小度不会获取最新状态** 32 | 3. 边学边写可能有问题 33 | 34 | ## 另 35 | 以上仅在小度接入了`南京物联`的设备中测试,其他厂商的设备尚不清楚 36 | 37 | 有能力的大佬可以自己开发,有什么不同的可以一起交流,本人也是菜鸡一枚 38 | 39 | ![IMG_0805](https://github.com/apgmer/hass-xiaodu/assets/9553342/9cbd450f-c2ba-41c3-9403-c5a4d576aa8f) 40 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | """The xiaodu api integration.""" 2 | from __future__ import annotations 3 | 4 | import logging 5 | 6 | from homeassistant.config_entries import ConfigEntry 7 | from homeassistant.const import Platform 8 | from homeassistant.core import HomeAssistant 9 | from .const import DOMAIN 10 | from .coordinator import XiaoDuCoordinator 11 | from .xiaodu import XiaoDuHub 12 | 13 | _LOGGER = logging.getLogger(__name__) 14 | 15 | # TODO List the platforms that you want to support. 16 | # For your initial PR, limit it to 1 platform. 17 | PLATFORMS: list[Platform] = [Platform.SWITCH, Platform.COVER, Platform.BUTTON] 18 | 19 | 20 | async def async_setup_entry(hass, entry): 21 | """Set up xiaodu api from a config entry.""" 22 | 23 | hass.data.setdefault(DOMAIN, {}) 24 | # TODO 1. Create API instance 25 | # TODO 2. Validate the API connection (and authentication) 26 | # TODO 3. Store an API object for your platforms to access 27 | # hass.data[DOMAIN][entry.entry_id] = MyApi(...) 28 | 29 | hub = XiaoDuHub(entry.data['cookie'], hass) 30 | 31 | coordinator = XiaoDuCoordinator(hass, hub) 32 | hass.data[DOMAIN][entry.entry_id] = coordinator 33 | 34 | hass.data[DOMAIN]['hub'] = hub 35 | 36 | # await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) 37 | 38 | await coordinator.async_config_entry_first_refresh() 39 | 40 | await hass.config_entries.async_forward_entry_setups( 41 | entry, [platform for platform in PLATFORMS if platform != Platform.NOTIFY] 42 | ) 43 | 44 | # job_ = await hass.async_add_executor_job() 45 | # print("") 46 | return True 47 | 48 | 49 | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 50 | """Unload a config entry.""" 51 | 52 | if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): 53 | hass.data[DOMAIN].pop(entry.entry_id) 54 | 55 | return unload_ok 56 | -------------------------------------------------------------------------------- /button.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from homeassistant.components.button import ButtonEntity 4 | from homeassistant.config_entries import ConfigEntry 5 | from homeassistant.core import HomeAssistant 6 | from homeassistant.helpers.entity_platform import AddEntitiesCallback 7 | from .const import DOMAIN 8 | from .coordinator import XiaoDuCoordinator 9 | from .xiaodu import XiaoDuHub 10 | 11 | _LOGGER = logging.getLogger(__name__) 12 | 13 | # 场景 解析为按钮 14 | SUPPORT_TYPE = ['SCENE_TRIGGER'] 15 | 16 | 17 | async def async_setup_entry( 18 | hass: HomeAssistant, 19 | config_entry: ConfigEntry, 20 | async_add_entities: AddEntitiesCallback, 21 | ) -> None: 22 | coordinator: XiaoDuCoordinator = hass.data[DOMAIN][config_entry.entry_id] 23 | async_add_entities(parse_data(coordinator)) 24 | 25 | 26 | class XiaoDuScene(ButtonEntity): 27 | 28 | def press(self) -> None: 29 | hub: XiaoDuHub = self.hass.data[DOMAIN]['hub'] 30 | hub.exec_scene(self.unique_id) 31 | 32 | def __init__(self, application_id, appliance_type, name_type, bot_id, bot_name) -> None: 33 | self._appliance_type = appliance_type 34 | self._attr_unique_id = application_id 35 | self._attr_name = name_type 36 | self.bot_id = bot_id 37 | self.bot_name = bot_name 38 | self._attr_icon = 'mdi:button-pointer' 39 | 40 | 41 | def parse_data(coordinator: XiaoDuCoordinator) -> list[XiaoDuScene]: 42 | appliances = coordinator.data['data']['appliances'] 43 | l: list[XiaoDuScene] = [] 44 | if len(appliances) > 0: 45 | for app in appliances: 46 | appliance_type = app['applianceTypes'][0] 47 | if appliance_type in SUPPORT_TYPE: 48 | entity_id = app['applianceId'].replace('scene', 'thirdV1_scene') 49 | name_type = app['friendlyName'] 50 | bot_id = app['botId'] 51 | bot_name = app['botName'] 52 | l.append(XiaoDuScene(entity_id, appliance_type, name_type, bot_id, bot_name)) 53 | return l 54 | -------------------------------------------------------------------------------- /config_flow.py: -------------------------------------------------------------------------------- 1 | """Config flow for xiaodu api integration.""" 2 | from __future__ import annotations 3 | 4 | import logging 5 | from typing import Any 6 | 7 | import voluptuous as vol 8 | 9 | from homeassistant import config_entries 10 | from homeassistant.core import HomeAssistant 11 | from homeassistant.data_entry_flow import FlowResult 12 | from homeassistant.exceptions import HomeAssistantError 13 | from .xiaodu import XiaoDuHub 14 | 15 | from .const import DOMAIN, Cookie 16 | 17 | _LOGGER = logging.getLogger(__name__) 18 | 19 | # TODO adjust the data schema to the data that you need 20 | STEP_USER_DATA_SCHEMA = vol.Schema( 21 | { 22 | vol.Required("cookie"): str, 23 | } 24 | ) 25 | 26 | async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]: 27 | hub = XiaoDuHub(data[Cookie], hass) 28 | if not await hub.auth(): 29 | raise InvalidAuth 30 | 31 | 32 | class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): 33 | """Handle a config flow for xiaodu api.""" 34 | 35 | VERSION = 1 36 | 37 | async def async_step_user( 38 | self, user_input: dict[str, Any] | None = None 39 | ) -> FlowResult: 40 | """Handle the initial step.""" 41 | if user_input is None: 42 | return self.async_show_form( 43 | step_id="user", data_schema=STEP_USER_DATA_SCHEMA 44 | ) 45 | 46 | errors = {} 47 | try: 48 | await validate_input(self.hass, user_input) 49 | except CannotConnect: 50 | errors["base"] = "cannot_connect" 51 | except InvalidAuth: 52 | errors["base"] = "invalid_auth" 53 | except Exception: # pylint: disable=broad-except 54 | _LOGGER.exception("Unexpected exception") 55 | errors["base"] = "unknown" 56 | else: 57 | return self.async_create_entry(title='XiaoDuCookie', data=user_input) 58 | 59 | return self.async_show_form( 60 | step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors 61 | ) 62 | 63 | 64 | class CannotConnect(HomeAssistantError): 65 | """Error to indicate we cannot connect.""" 66 | 67 | 68 | class InvalidAuth(HomeAssistantError): 69 | """Error to indicate there is invalid auth.""" 70 | -------------------------------------------------------------------------------- /cover.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import Any 3 | 4 | from homeassistant.components.cover import CoverEntity, CoverDeviceClass, CoverEntityFeature 5 | from homeassistant.config_entries import ConfigEntry 6 | from homeassistant.core import HomeAssistant 7 | from homeassistant.helpers.entity_platform import AddEntitiesCallback 8 | from .const import DOMAIN 9 | from .coordinator import XiaoDuCoordinator 10 | from .xiaodu import XiaoDuHub 11 | 12 | _LOGGER = logging.getLogger(__name__) 13 | 14 | # 窗帘 15 | SUPPORT_TYPE = ['CURTAIN'] 16 | 17 | 18 | async def async_setup_entry( 19 | hass: HomeAssistant, 20 | config_entry: ConfigEntry, 21 | async_add_entities: AddEntitiesCallback, 22 | ) -> None: 23 | coordinator: XiaoDuCoordinator = hass.data[DOMAIN][config_entry.entry_id] 24 | async_add_entities(parse_data(coordinator)) 25 | 26 | 27 | class XiaoDuCurtain(CoverEntity): 28 | 29 | def open_cover(self, **kwargs: Any) -> None: 30 | hub: XiaoDuHub = self.hass.data[DOMAIN]['hub'] 31 | _LOGGER.info("open_cover") 32 | hub.curtain_toggle(self._attr_unique_id, "TurnOnRequest") 33 | 34 | def close_cover(self, **kwargs: Any) -> None: 35 | hub: XiaoDuHub = self.hass.data[DOMAIN]['hub'] 36 | hub.curtain_toggle(self._attr_unique_id, "TurnOffRequest") 37 | _LOGGER.info("close_cover") 38 | 39 | def set_cover_position(self, **kwargs: Any) -> None: 40 | if kwargs['position'] > 50: 41 | self.close_cover() 42 | else: 43 | self.open_cover() 44 | 45 | def stop_cover(self, **kwargs: Any) -> None: 46 | hub: XiaoDuHub = self.hass.data[DOMAIN]['hub'] 47 | hub.curtain_stop(self.unique_id) 48 | _LOGGER.info("stop_cover") 49 | 50 | def __init__(self, application_id, appliance_type, name_type, current_cover_position, bot_id, 51 | bot_name) -> None: 52 | self._appliance_type = appliance_type 53 | self._attr_unique_id = application_id 54 | self._attr_name = name_type 55 | self._attr_current_cover_position = current_cover_position 56 | self.bot_id = bot_id 57 | self.bot_name = bot_name 58 | self._attr_icon = 'mdi:curtains' 59 | if appliance_type == 'CURTAIN': 60 | self._attr_device_class = CoverDeviceClass.CURTAIN 61 | self._attr_supported_features = CoverEntityFeature.SET_POSITION 62 | self._attr_is_closed = current_cover_position == 100 63 | 64 | 65 | def parse_data(coordinator: XiaoDuCoordinator) -> list[XiaoDuCurtain]: 66 | appliances = coordinator.data['data']['appliances'] 67 | l: list[XiaoDuCurtain] = [] 68 | if len(appliances) > 0: 69 | for app in appliances: 70 | appliance_type = app['applianceTypes'][0] 71 | if appliance_type in SUPPORT_TYPE: 72 | entity_id = app['applianceId'] 73 | name_type = app['friendlyName'] 74 | bot_id = app['botId'] 75 | bot_name = app['botName'] 76 | # 无法获取当前位置 77 | current_position = 50 78 | l.append(XiaoDuCurtain(entity_id, appliance_type, name_type, current_position, bot_id, 79 | bot_name)) 80 | return l 81 | -------------------------------------------------------------------------------- /switch.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import Any 3 | 4 | from homeassistant.components.switch import SwitchEntity 5 | from homeassistant.config_entries import ConfigEntry 6 | from homeassistant.core import HomeAssistant 7 | from homeassistant.core import callback 8 | from homeassistant.helpers.entity_platform import AddEntitiesCallback 9 | from homeassistant.helpers.update_coordinator import ( 10 | CoordinatorEntity, 11 | ) 12 | from .const import DOMAIN 13 | from .coordinator import XiaoDuCoordinator 14 | from .xiaodu import XiaoDuHub 15 | 16 | _LOGGER = logging.getLogger(__name__) 17 | 18 | # 开关 、 插座 19 | SUPPORT_TYPE = ['SWITCH', 'OUTLET'] 20 | 21 | 22 | async def async_setup_entry( 23 | hass: HomeAssistant, 24 | config_entry: ConfigEntry, 25 | async_add_entities: AddEntitiesCallback, 26 | ) -> None: 27 | coordinator: XiaoDuCoordinator = hass.data[DOMAIN][config_entry.entry_id] 28 | async_add_entities(parse_data(coordinator)) 29 | 30 | 31 | class XiaoDuSwitch(CoordinatorEntity, SwitchEntity): 32 | 33 | def turn_on(self, **kwargs: Any) -> None: 34 | hub: XiaoDuHub = self.hass.data[DOMAIN]['hub'] 35 | hub.switch_toggle(self._attr_unique_id, "TurnOnRequest") 36 | self._if_on = True 37 | 38 | def turn_off(self, **kwargs: Any) -> None: 39 | hub: XiaoDuHub = self.hass.data[DOMAIN]['hub'] 40 | hub.switch_toggle(self._attr_unique_id, "TurnOffRequest") 41 | self._if_on = False 42 | 43 | async def async_turn_on(self, **kwargs: Any) -> None: 44 | await self.hass.async_add_executor_job(self.turn_on) 45 | await self.coordinator.async_request_refresh() 46 | 47 | async def async_turn_off(self, **kwargs: Any) -> None: 48 | await self.hass.async_add_executor_job(self.turn_off) 49 | await self.coordinator.async_request_refresh() 50 | 51 | @callback 52 | def _handle_coordinator_update(self) -> None: 53 | """Handle updated data from the coordinator.""" 54 | appliances = self.coordinator.data['data']["appliances"] 55 | if len(appliances) > 0: 56 | for app in appliances: 57 | if self._attr_unique_id == app['applianceId']: 58 | self._if_on = app['stateSetting']['turnOnState']['value'] == 'ON' 59 | self.async_write_ha_state() 60 | 61 | @property 62 | def is_on(self) -> bool | None: 63 | return self._if_on 64 | 65 | def __init__(self, coordinator, application_id, appliance_type, name_type, if_on, bot_id, bot_name) -> None: 66 | super().__init__(coordinator) 67 | self._appliance_type = appliance_type 68 | self._attr_unique_id = application_id 69 | self._attr_name = name_type 70 | self._if_on = if_on 71 | self.bot_id = bot_id 72 | self.bot_name = bot_name 73 | self._attr_icon = 'mdi:toggle-switch' 74 | self._attr_device_class = 'switch' 75 | if name_type and '灯' in name_type: 76 | self._attr_icon = 'mdi:lightbulb' 77 | if 'OUTLET' == appliance_type: 78 | self._attr_icon = 'mdi:power-socket-us' 79 | self._attr_device_class = 'outlet' 80 | 81 | 82 | def parse_data(coordinator: XiaoDuCoordinator) -> list[XiaoDuSwitch]: 83 | appliances = coordinator.data['data']['appliances'] 84 | l: list[XiaoDuSwitch] = [] 85 | if len(appliances) > 0: 86 | for app in appliances: 87 | appliance_type = app['applianceTypes'][0] 88 | if appliance_type in SUPPORT_TYPE: 89 | entity_id = app['applianceId'] 90 | if_on = app['stateSetting']['turnOnState']['value'] == 'ON' 91 | name_type = app['friendlyName'] 92 | bot_id = app['botId'] 93 | bot_name = app['botName'] 94 | l.append(XiaoDuSwitch(coordinator, entity_id, appliance_type, name_type, if_on, bot_id, bot_name)) 95 | return l 96 | -------------------------------------------------------------------------------- /xiaodu.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import requests 4 | 5 | HOST = 'https://xiaodu.baidu.com' 6 | 7 | _LOGGER = logging.getLogger(__name__) 8 | 9 | 10 | class XiaoDuHub: 11 | 12 | def __init__(self, cookie: str, hass) -> None: 13 | self.cookie = cookie 14 | self._hass = hass 15 | self._device_dict = None 16 | 17 | async def auth(self) -> bool: 18 | return True 19 | 20 | async def deviceList(self): 21 | return await self._hass.async_add_executor_job(self.doDeviceList) 22 | 23 | def doDeviceList(self): 24 | api = '/saiya/smarthome/devicelist?from=h5_control&withscene=1&generalscene=3' 25 | headers = self._common_header() 26 | _LOGGER.info("do query xiaodu device") 27 | response = requests.get(HOST + api, headers=headers) 28 | if response.status_code == 200: 29 | json = response.json() 30 | _LOGGER.info("request \n %s \n %s \n %s \t %s", HOST + api, '', response.status_code, response.json()) 31 | return json 32 | else: 33 | _LOGGER.error("请求小度出错", response) 34 | return {} 35 | 36 | def switch_toggle(self, unique_id, method): 37 | api = '/saiya/smarthome/directivesend?from=h5_control' 38 | param = { 39 | "header": { 40 | "namespace": "DuerOS.ConnectedHome.Control", 41 | "name": method, 42 | "payloadVersion": 3 43 | }, 44 | "payload": { 45 | "appliance": { 46 | "applianceId": [ 47 | unique_id 48 | ] 49 | }, 50 | "parameters": { 51 | "proxyConnectStatus": False 52 | } 53 | } 54 | } 55 | response = requests.post(HOST + api, headers=self._common_header(), json=param) 56 | _LOGGER.info("request \n %s \n %s \n %s \t %s", HOST + api, param, response.status_code, response.json()) 57 | return response.status_code == 200 58 | 59 | # 厂商无效果 60 | def curtain_set_position(self, unique_id, position: int): 61 | api = '/saiya/smarthome/directivesend?from=h5_control' 62 | param = { 63 | "header": { 64 | "namespace": "DuerOS.ConnectedHome.Control", 65 | "name": "TurnOnPercentRequest", 66 | "payloadVersion": 3 67 | }, 68 | "payload": { 69 | "appliance": 70 | {"applianceId": 71 | [unique_id] 72 | }, 73 | "degree": position, 74 | "parameters": { 75 | "attribute": "degree", 76 | "attributeValue": str(position), 77 | "proxyConnectStatus": False 78 | } 79 | } 80 | } 81 | response = requests.post(HOST + api, headers=self._common_header(), json=param) 82 | _LOGGER.info("request \n %s \n %s \n %s \t %s", HOST + api, param, response.status_code, response.json()) 83 | return response.status_code == 200 84 | 85 | def curtain_toggle(self, unique_id, method): 86 | api = '/saiya/smarthome/directivesend?from=h5_control' 87 | param = { 88 | "header": { 89 | "namespace": "DuerOS.ConnectedHome.Control", 90 | "name": method, 91 | "payloadVersion": 3 92 | }, 93 | "payload": { 94 | "appliance": { 95 | "applianceId": [ 96 | unique_id 97 | ] 98 | }, 99 | "parameters": { 100 | "proxyConnectStatus": False 101 | } 102 | } 103 | } 104 | response = requests.post(HOST + api, headers=self._common_header(), json=param) 105 | _LOGGER.info("request \n %s \n %s \n %s \t %s", HOST + api, param, response.status_code, response.json()) 106 | return response.status_code == 200 107 | 108 | 109 | def curtain_stop(self, unique_id): 110 | api = '/saiya/smarthome/directivesend?from=h5_control' 111 | param = { 112 | "header": { 113 | "namespace": "DuerOS.ConnectedHome.Control", 114 | "name": "PauseRequest", 115 | "payloadVersion": 3 116 | }, 117 | "payload": { 118 | "appliance": { 119 | "applianceId": [ 120 | unique_id 121 | ] 122 | }, 123 | "parameters": { 124 | "proxyConnectStatus": False 125 | } 126 | } 127 | } 128 | response = requests.post(HOST + api, headers=self._common_header(), json=param) 129 | _LOGGER.info("request \n %s \n %s \n %s \t %s", HOST + api, param, response.status_code, response.json()) 130 | return response.status_code == 200 131 | 132 | def exec_scene(self, unique_id): 133 | api = '/saiya/smarthome/unified' 134 | param = {"method": "triggerScene", "params": {"sceneId": unique_id}} 135 | response = requests.post(HOST + api, headers=self._common_header(), json=param) 136 | _LOGGER.info("request \n %s \n %s \n %s \t %s", HOST + api, param, response.status_code, response.json()) 137 | return response.status_code == 200 138 | 139 | def _common_header(self): 140 | return { 141 | "Cookie": self.cookie, 142 | "User-Agent": 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1', 143 | "Referer": 'https://xiaodu.baidu.com/saiya/smarthome/index.html?uid=&traceid=' 144 | } 145 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. --------------------------------------------------------------------------------