Skip to content

Commit

Permalink
chore: improve get_rand_int
Browse files Browse the repository at this point in the history
  • Loading branch information
Lash-L committed Oct 28, 2024
1 parent afcaa7f commit d26727f
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 14 deletions.
4 changes: 2 additions & 2 deletions roborock/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
RoborockMessage,
)
from .roborock_typing import RoborockCommand
from .util import RoborockLoggerAdapter, get_rand_int, get_running_loop_or_create_one
from .util import RoborockLoggerAdapter, get_next_int, get_running_loop_or_create_one

_LOGGER = logging.getLogger(__name__)
KEEPALIVE = 60
Expand Down Expand Up @@ -114,7 +114,7 @@ def _async_response(
) -> Coroutine[Any, Any, tuple[Any, VacuumError | None]]:
queue = RoborockFuture(protocol_id)
if request_id in self._waiting_queue:
new_id = get_rand_int(10000, 32767)
new_id = get_next_int(10000, 32767)
_LOGGER.warning(
f"Attempting to create a future with an existing request_id... New id is {new_id}. "
f"Code may not function properly."
Expand Down
6 changes: 3 additions & 3 deletions roborock/roborock_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from dataclasses import dataclass

from roborock import RoborockEnum
from roborock.util import get_rand_int
from roborock.util import get_next_int


class RoborockMessageProtocol(RoborockEnum):
Expand Down Expand Up @@ -155,9 +155,9 @@ class MessageRetry:
class RoborockMessage:
protocol: RoborockMessageProtocol
payload: bytes | None = None
seq: int = get_rand_int(100000, 999999)
seq: int = get_next_int(100000, 999999)
version: bytes = b"1.0"
random: int = get_rand_int(10000, 99999)
random: int = get_next_int(10000, 99999)
timestamp: int = math.floor(time.time())
message_retry: MessageRetry | None = None

Expand Down
13 changes: 6 additions & 7 deletions roborock/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import datetime
import functools
import logging
import random
from asyncio import AbstractEventLoop, TimerHandle
from collections.abc import Callable, Coroutine, MutableMapping
from typing import Any, TypeVar
Expand Down Expand Up @@ -111,13 +110,13 @@ def process(self, msg: str, kwargs: MutableMapping[str, Any]) -> tuple[str, Muta
return f"[{self.prefix}] {msg}", kwargs


cached_numbers: dict[tuple[int, int], list[int]] = {}
counter_map: dict[tuple[int, int], int] = {}


def get_rand_int(min_val: int, max_val: int):
def get_next_int(min_val: int, max_val: int):
"""Gets a random int in the range, precached to help keep it fast."""
if (min_val, max_val) not in cached_numbers or len(cached_numbers[(min_val, max_val)]) < 25:
if (min_val, max_val) not in counter_map:
# If we have never seen this range, or if the cache is getting low, make a bunch of preshuffled values.
cached_numbers[(min_val, max_val)] = list(range(min_val, max_val + 1))
random.shuffle(cached_numbers[(min_val, max_val)])
return cached_numbers[(min_val, max_val)].pop()
counter_map[(min_val, max_val)] = min_val
counter_map[(min_val, max_val)] += 1
return counter_map[(min_val, max_val)] % max_val + min_val
4 changes: 2 additions & 2 deletions roborock/version_1_apis/roborock_client_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
RoborockMessage,
RoborockMessageProtocol,
)
from roborock.util import RepeatableTask, get_rand_int, unpack_list
from roborock.util import RepeatableTask, get_next_int, unpack_list

COMMANDS_SECURED = [
RoborockCommand.GET_MAP_V1,
Expand Down Expand Up @@ -333,7 +333,7 @@ def _get_payload(
secured=False,
):
timestamp = math.floor(time.time())
request_id = get_rand_int(10000, 32767)
request_id = get_next_int(10000, 32767)
inner = {
"id": request_id,
"method": method,
Expand Down

0 comments on commit d26727f

Please sign in to comment.