Skip to content

Commit

Permalink
No room_data_vacuum save anymore.
Browse files Browse the repository at this point in the history
camera.py removed room_data save reverted to original
types.py added class RoomSave
files_operations.py renaming of translation uses RoomSave
config_flow.py uses RoomSave
connector.py Store segments in RoomSave

Signed-off-by: [email protected] <[email protected]>
  • Loading branch information
sca075 committed Jul 19, 2024
1 parent 99e1c91 commit 4fded25
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 25 deletions.
10 changes: 0 additions & 10 deletions custom_components/mqtt_vacuum_camera/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@
from .utils.colors_man import ColorsManagment
from .utils.files_operations import (
async_get_active_user_language,
async_save_mqtt_room_data,
is_auth_updated,
)
from .valetudo.MQTT.connector import ValetudoConnector
Expand Down Expand Up @@ -360,15 +359,6 @@ async def async_update(self):
)
return self.Image

if self.startup:
if await async_save_mqtt_room_data(
self.hass, self._file_name, self._mqtt.get_segments()
):
_LOGGER.info(f"Rooms data saved for {self._file_name}.")
else:
_LOGGER.info(f"No rooms data save for {self._file_name}.")
self.startup = False

# If we have data from MQTT, we process the image.
self._shared.vacuum_battery = await self._mqtt.get_battery_level()
self._shared.vacuum_connection = await self._mqtt.get_vacuum_connection_state()
Expand Down
9 changes: 3 additions & 6 deletions custom_components/mqtt_vacuum_camera/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,8 @@
ROTATION_VALUES,
TEXT_SIZE_VALUES,
)
from .utils.files_operations import (
async_del_file,
async_get_rooms_count,
async_rename_room_description,
)
from .types import RoomStore
from .utils.files_operations import async_del_file, async_rename_room_description

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -347,7 +344,7 @@ async def async_step_init(self, user_input=None):
_LOGGER.info(f"{self.config_entry.unique_id}: Options Configuration Started.")
errors = {}

self.number_of_rooms = await async_get_rooms_count(self.hass, self.file_name)
self.number_of_rooms = RoomStore().get_rooms_count(self.file_name)
if (
not isinstance(self.number_of_rooms, int)
or self.number_of_rooms < DEFAULT_ROOMS
Expand Down
34 changes: 33 additions & 1 deletion custom_components/mqtt_vacuum_camera/types.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
"""
This module contains type aliases for the project.
Version 2024.07.1
Version 2024.07.4
"""

from dataclasses import dataclass
import logging
from typing import Any, Dict, Tuple, Union

from PIL import Image
import numpy as np

from .const import DEFAULT_ROOMS

_LOGGER = logging.getLogger(__name__)

Color = Union[Tuple[int, int, int], Tuple[int, int, int, int]]
Colors = Dict[str, Color]
CalibrationPoints = list[dict[str, Any]]
Expand Down Expand Up @@ -63,3 +68,30 @@ def from_list(data: list):
trim_right=data[2],
trim_down=data[3],
)


class RoomStore:
"""Store the room data for the vacuum."""

_instance = None

def __new__(cls):
if cls._instance is None:
cls._instance = super(RoomStore, cls).__new__(cls)
cls._instance.vacuums_data = {}
return cls._instance

def set_rooms_data(self, vacuum_id, rooms_data):
"""Set the room data for the vacuum."""
self.vacuums_data[vacuum_id] = rooms_data

def get_rooms_data(self, vacuum_id):
"""Get the room data for a vacuum."""
return self.vacuums_data.get(vacuum_id, {})

def get_rooms_count(self, vacuum_id):
"""Count the number of rooms for a vacuum."""
count = len(self.vacuums_data.get(vacuum_id, {}))
if count == 0:
return DEFAULT_ROOMS
return count
19 changes: 11 additions & 8 deletions custom_components/mqtt_vacuum_camera/utils/files_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from homeassistant.helpers.storage import STORAGE_DIR

from custom_components.mqtt_vacuum_camera.const import CAMERA_STORAGE, DEFAULT_ROOMS
from custom_components.mqtt_vacuum_camera.types import RoomStore

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -293,17 +294,19 @@ async def async_rename_room_description(
"""
Add room names to the room descriptions in the translations.
"""
room_json = await async_load_room_data(storage_path, vacuum_id)
room_data = room_json.get("rooms", {})
# Load the room data using the new MQTT-based function
room_data = RoomStore().get_rooms_data(vacuum_id)
_LOGGER.info(f"Room data loaded: {room_data}")
if not room_json:

if not room_data:
_LOGGER.warning(
f"Vacuum ID: {vacuum_id} do not support Rooms! Aborting room name addition."
f"Vacuum ID: {vacuum_id} does not support Rooms! Aborting room name addition."
)
return False

# Save the vacuum_id to a JSON file
await async_write_vacuum_id(hass, "rooms_colours_description.json", vacuum_id)

# Get the languages to modify
language = await async_load_languages(storage_path)
_LOGGER.info(f"Languages to modify: {language}")
Expand All @@ -328,10 +331,10 @@ async def async_rename_room_description(
end_index = 8 if i == 1 else 16
for j in range(start_index, end_index):
if j < len(room_data):
room_id, room_info = list(room_data.items())[j]
room_id, room_name = list(room_data.items())[j]
data["options"]["step"][room_key]["data_description"][
f"color_room_{j}"
] = f"### **RoomID {room_id} {room_info['name']}**"
] = f"### **RoomID {room_id} {room_name}**"

# Modify the "data" keys for alpha_2 and alpha_3
for data in data_list:
Expand All @@ -343,10 +346,10 @@ async def async_rename_room_description(
end_index = 8 if i == 2 else 16
for j in range(start_index, end_index):
if j < len(room_data):
room_id, room_info = list(room_data.items())[j]
room_id, room_name = list(room_data.items())[j]
data["options"]["step"][alpha_key]["data"][
f"alpha_room_{j}"
] = f"RoomID {room_id} {room_info['name']}"
] = f"RoomID {room_id} {room_name}"
# "**text**" is bold as in markdown

# Write the modified data back to the JSON files
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from homeassistant.helpers.storage import STORAGE_DIR
from isal import igzip, isal_zlib

from custom_components.mqtt_vacuum_camera.types import RoomStore
from custom_components.mqtt_vacuum_camera.utils.files_operations import (
async_write_file_to_disk,
)
Expand Down Expand Up @@ -348,6 +349,7 @@ async def async_message_received(self, msg) -> None:
await self._hass.async_create_task(self.rand256_handle_destinations(msg))
elif self._rcv_topic == f"{self._mqtt_topic}/MapData/segments":
self._mqtt_segments = json.loads(msg.payload)
RoomStore().set_rooms_data(self._file_name, self._mqtt_segments)
_LOGGER.debug(f"Segments: {self._mqtt_segments}")

async def async_subscribe_to_topics(self) -> None:
Expand Down

0 comments on commit 4fded25

Please sign in to comment.