async def ws_handle_edit_entity_bool_value( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Handle edit entity bool value command.""" if os.path.exists( hass.config.path("dwains-dashboard/configs/entities.yaml")): with open(hass.config.path( "dwains-dashboard/configs/entities.yaml")) as f: entities = yaml.safe_load(f) else: entities = OrderedDict() entity = entities.get(msg["entityId"]) if not entity: entities[msg["entityId"]] = OrderedDict() entities[msg["entityId"]].update({msg["key"]: msg["value"]}) if not os.path.exists(hass.config.path("dwains-dashboard/configs")): os.makedirs(hass.config.path("dwains-dashboard/configs")) with open(hass.config.path("dwains-dashboard/configs/entities.yaml"), 'w') as f: yaml.safe_dump(entities, f, default_flow_style=False) hass.bus.async_fire("dwains_dashboard_homepage_card_reload") hass.bus.async_fire("dwains_dashboard_devicespage_card_reload") connection.send_result( msg["id"], {"succesfull": "Entity bool value set succesfully"}, )
def ws_usercode_history(hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg): """History of usage of user code tags.""" manager = hass.data[DOMAIN] # type: LockHistory connection.send_result(msg['id'], { 'history': list(reversed(manager._history)), })
async def ws_handle_edit_more_page(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Handle edit more page command.""" if not msg["foldername"]: more_page_folder = slugify(msg["name"]) else: more_page_folder = msg["foldername"] filecontent = json.loads(msg["card_data"]) path_to_more_page = hass.config.path( "dwains-dashboard/configs/more_pages/" + more_page_folder + "/page.yaml") os.makedirs(os.path.dirname(path_to_more_page), exist_ok=True) #Create the folder if not exists if not msg["foldername"]: if os.path.exists(path_to_more_page): more_page_folder = more_page_folder + datetime.now().strftime( "%Y%m%d%H%M%S") path_to_more_page = hass.config.path( "dwains-dashboard/configs/more_pages/" + more_page_folder + "/page.yaml") os.makedirs(os.path.dirname(path_to_more_page), exist_ok=True) ff = open(path_to_more_page, 'w+') yaml.dump(yaml.safe_load(json.dumps(filecontent)), ff, default_flow_style=False) #config.yaml configFile = OrderedDict() configFile.update({ "name": msg["name"], "icon": msg["icon"], "show_in_navbar": msg["showInNavbar"], }) with open( hass.config.path("dwains-dashboard/configs/more_pages/" + more_page_folder + "/config.yaml"), 'w') as f: yaml.safe_dump(configFile, f, default_flow_style=False) #end config.yaml #call reload config to rebuild the yaml for pages too hass.bus.async_fire("dwains_dashboard_reload") hass.bus.async_fire("dwains_dashboard_navigation_card_reload") #hass.services.call(DOMAIN, "reload") reload_configuration(hass) connection.send_result( msg["id"], {"succesfull": "More page saved succesfully"}, )
async def ws_update_item( self, hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Update a item.""" data = dict(msg) msg_id = data.pop("id") item_id = data.pop(self.item_id_key) data.pop("type") try: item = await self.storage_collection.async_update_item(item_id, data) connection.send_result(msg_id, item) except ItemNotFound: connection.send_error( msg["id"], websocket_api.const.ERR_NOT_FOUND, f"Unable to find {self.item_id_key} {item_id}", ) except vol.Invalid as err: connection.send_error( msg["id"], websocket_api.const.ERR_INVALID_FORMAT, humanize_error(data, err), ) except ValueError as err: connection.send_error( msg_id, websocket_api.const.ERR_INVALID_FORMAT, str(err) )
def ws_ignore_issue(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Fix an issue.""" async_ignore_issue(hass, msg["domain"], msg["issue_id"], msg["ignore"]) connection.send_result(msg["id"])
async def ws_handle_edit_more_page_button( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Handle saving editing more page button.""" if (msg["more_page"]): if os.path.exists( hass.config.path("dwains-dashboard/configs/more_pages/" + msg["more_page"] + "/config.yaml")): with open( hass.config.path("dwains-dashboard/configs/more_pages/" + msg["more_page"] + "/config.yaml")) as f: configFile = yaml.safe_load(f) else: configFile = OrderedDict() configFile.update({ "name": msg["name"], "icon": msg["icon"], "show_in_navbar": msg["showInNavbar"], }) with open( hass.config.path("dwains-dashboard/configs/more_pages/" + msg["more_page"] + "/config.yaml"), 'w') as f: yaml.safe_dump(configFile, f, default_flow_style=False) hass.bus.async_fire("dwains_dashboard_homepage_card_reload") connection.send_result( msg["id"], {"succesfull": "More page button saved"}, )
def websocket_refresh_tokens(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg): """Return metadata of users refresh tokens.""" current_id = connection.refresh_token_id tokens = [] for refresh in connection.user.refresh_tokens.values(): if refresh.credential: auth_provider_type = refresh.credential.auth_provider_type else: auth_provider_type = None tokens.append({ "id": refresh.id, "client_id": refresh.client_id, "client_name": refresh.client_name, "client_icon": refresh.client_icon, "type": refresh.token_type, "created_at": refresh.created_at, "is_current": refresh.id == current_id, "last_used_at": refresh.last_used_at, "last_used_ip": refresh.last_used_ip, "auth_provider_type": auth_provider_type, }) connection.send_result(msg["id"], tokens)
def list_errors(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict): """List all possible diagnostic handlers.""" connection.send_result( msg["id"], hass.data[DOMAIN].records.to_list(), )
async def ws_delete_person(hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg): """Delete a person.""" manager = hass.data[DOMAIN] # type: PersonManager await manager.async_delete_person(msg['person_id']) connection.send_result(msg['id'])
async def ws_get_statistics_during_period( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Handle statistics websocket command.""" start_time_str = msg["start_time"] end_time_str = msg.get("end_time") start_time = dt_util.parse_datetime(start_time_str) if start_time: start_time = dt_util.as_utc(start_time) else: connection.send_error(msg["id"], "invalid_start_time", "Invalid start_time") return if end_time_str: end_time = dt_util.parse_datetime(end_time_str) if end_time: end_time = dt_util.as_utc(end_time) else: connection.send_error(msg["id"], "invalid_end_time", "Invalid end_time") return else: end_time = None statistics = await hass.async_add_executor_job( statistics_during_period, hass, start_time, end_time, msg.get("statistic_ids"), msg.get("period"), ) connection.send_result(msg["id"], statistics)
async def ws_validate( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict, ) -> None: """Handle validate command.""" connection.send_result(msg["id"], (await async_validate(hass)).as_dict())
async def ws_camera_web_rtc_offer(hass: HomeAssistant, connection: ActiveConnection, msg: dict) -> None: """Handle the signal path for a WebRTC stream. This signal path is used to route the offer created by the client to the camera device through the integration for negitioation on initial setup, which returns an answer. The actual streaming is handled entirely between the client and camera device. Async friendly. """ entity_id = msg["entity_id"] offer = msg["offer"] camera = _get_camera_from_entity_id(hass, entity_id) if camera.frontend_stream_type != STREAM_TYPE_WEB_RTC: connection.send_error( msg["id"], "web_rtc_offer_failed", f"Camera does not support WebRTC, frontend_stream_type={camera.frontend_stream_type}", ) return try: answer = await camera.async_handle_web_rtc_offer(offer) except (HomeAssistantError, ValueError) as ex: _LOGGER.error("Error handling WebRTC offer: %s", ex) connection.send_error(msg["id"], "web_rtc_offer_failed", str(ex)) except asyncio.TimeoutError: _LOGGER.error("Timeout handling WebRTC offer") connection.send_error(msg["id"], "web_rtc_offer_failed", "Timeout handling WebRTC offer") else: connection.send_result(msg["id"], {"answer": answer})
def ws_update_statistics_metadata(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Update statistics metadata for a statistic_id.""" hass.data[DATA_INSTANCE].async_update_statistics_metadata( msg["statistic_id"], msg["unit_of_measurement"]) connection.send_result(msg["id"])
def ws_update_statistics_metadata( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Update statistics metadata for a statistic_id.""" get_instance(hass).async_update_statistics_metadata( msg["statistic_id"], new_unit_of_measurement=msg["unit_of_measurement"] ) connection.send_result(msg["id"])
async def ws_get_statistics_metadata( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Get metadata for a list of statistic_ids.""" instance: Recorder = hass.data[DATA_INSTANCE] statistic_ids = await instance.async_add_executor_job( list_statistic_ids, hass, msg.get("statistic_ids")) connection.send_result(msg["id"], statistic_ids)
def ws_list_person( hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg ): """List persons.""" yaml, storage = hass.data[DOMAIN] connection.send_result( msg[ATTR_ID], {"storage": storage.async_items(), "config": yaml.async_items()} )
def ws_list_person(hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg): """List persons.""" manager = hass.data[DOMAIN] # type: PersonManager connection.send_result(msg['id'], { 'storage': manager.storage_persons, 'config': manager.config_persons, })
async def handle_remove( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict, ) -> None: """Remove a backup.""" manager: BackupManager = hass.data[DOMAIN] await manager.remove_backup(msg["slug"]) connection.send_result(msg["id"])
async def handle_create( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict, ) -> None: """Generate a backup.""" manager: BackupManager = hass.data[DOMAIN] backup = await manager.generate_backup() connection.send_result(msg["id"], backup)
async def ws_validate_statistics(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Fetch a list of available statistic_id.""" statistic_ids = await hass.async_add_executor_job( validate_statistics, hass, ) connection.send_result(msg["id"], statistic_ids)
async def ws_validate_statistics(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Fetch a list of available statistic_id.""" instance: Recorder = hass.data[DATA_INSTANCE] statistic_ids = await instance.async_add_executor_job( validate_statistics, hass, ) connection.send_result(msg["id"], statistic_ids)
def ws_clear_statistics(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Clear statistics for a list of statistic_ids. Note: The WS call posts a job to the recorder's queue and then returns, it doesn't wait until the job is completed. """ hass.data[DATA_INSTANCE].async_clear_statistics(msg["statistic_ids"]) connection.send_result(msg["id"])
def handle_info(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict): """List all possible diagnostic handlers.""" connection.send_result( msg["id"], [{ "domain": domain, "handlers": {key: val is not None for key, val in info.items()}, } for domain, info in hass.data[DOMAIN].items()], )
async def ws_save_prefs( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict, manager: EnergyManager, ) -> None: """Handle get prefs command.""" msg_id = msg.pop("id") msg.pop("type") await manager.async_update(cast(EnergyPreferencesUpdate, msg)) connection.send_result(msg_id, manager.data)
async def ws_backup_end(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Backup end notification.""" instance: Recorder = hass.data[DATA_INSTANCE] _LOGGER.info("Backup end notification, releasing write lock") if not instance.unlock_database(): connection.send_error(msg["id"], "database_unlock_failed", "Failed to unlock database.") connection.send_result(msg["id"])
async def ws_get_list_statistic_ids(hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict) -> None: """Fetch a list of available statistic_id.""" statistic_ids = await get_instance(hass).async_add_executor_job( list_statistic_ids, hass, None, msg.get("statistic_type"), ) connection.send_result(msg["id"], statistic_ids)
def ws_list_person(hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg): """List persons.""" manager: PersonManager = hass.data[DOMAIN] connection.send_result( msg["id"], { "storage": manager.storage_persons, "config": manager.config_persons }, )
def ws_get_prefs( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict, manager: EnergyManager, ) -> None: """Handle get prefs command.""" if manager.data is None: connection.send_error(msg["id"], websocket_api.ERR_NOT_FOUND, "No prefs") return connection.send_result(msg["id"], manager.data)
def ws_import_statistics( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Adjust sum statistics.""" metadata = msg["metadata"] stats = msg["stats"] if valid_entity_id(metadata["statistic_id"]): async_import_statistics(hass, metadata, stats) else: async_add_external_statistics(hass, metadata, stats) connection.send_result(msg["id"])
async def websocket_browse_media(hass: HomeAssistant, connection: ActiveConnection, msg: dict) -> None: """Browse available media.""" try: media = await async_browse_media(hass, msg.get("media_content_id", "")) connection.send_result( msg["id"], media.as_dict(), ) except BrowseError as err: connection.send_error(msg["id"], "browse_media_failed", str(err))
async def ws_create_person(hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg): """Create a person.""" manager = hass.data[DOMAIN] # type: PersonManager try: person = await manager.async_create_person( name=msg['name'], user_id=msg.get('user_id'), device_trackers=msg['device_trackers'] ) connection.send_result(msg['id'], person) except ValueError as err: connection.send_error( msg['id'], websocket_api.const.ERR_INVALID_FORMAT, str(err))
async def ws_update_person(hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg): """Update a person.""" manager = hass.data[DOMAIN] # type: PersonManager changes = {} for key in ('name', 'user_id', 'device_trackers'): if key in msg: changes[key] = msg[key] try: person = await manager.async_update_person(msg['person_id'], **changes) connection.send_result(msg['id'], person) except ValueError as err: connection.send_error( msg['id'], websocket_api.const.ERR_INVALID_FORMAT, str(err))