Skip to content

Commit

Permalink
Update the battery and firmware version after lock operation (#178)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Jan 1, 2023
1 parent ebc5b7e commit c7f1228
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
4 changes: 2 additions & 2 deletions switchbot/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ class SwitchbotAuthenticationError(RuntimeError):

class SwitchbotAccountConnectionError(RuntimeError):
"""Raised when connection to Switchbot account fails.
This exception inherits from RuntimeError to avoid breaking existing code
but will be changed to Exception in a future release.
but will be changed to Exception in a future release.
"""


Expand Down
28 changes: 20 additions & 8 deletions switchbot/devices/lock.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
"""Library to handle connection with Switchbot Lock."""
from __future__ import annotations

import asyncio
import base64
import hashlib
import hmac
import json
import logging
import time
from typing import Any

import boto3
Expand Down Expand Up @@ -162,6 +162,13 @@ async def unlock(self) -> bool:
COMMAND_UNLOCK, {LockStatus.UNLOCKED, LockStatus.UNLOCKING}
)

def _parse_basic_data(self, basic_data: bytes) -> dict[str, Any]:
"""Parse basic data from lock."""
return {
"battery": basic_data[1],
"firmware": basic_data[2] / 10.0,
}

async def _lock_unlock(
self, command: str, ignore_statuses: set[LockStatus]
) -> bool:
Expand All @@ -174,9 +181,15 @@ async def _lock_unlock(

await self._enable_notifications()
result = await self._send_command(command)
if not self._check_command_result(result, 0, {1}):
return False
return True
status = self._check_command_result(result, 0, {1})

# Also update the battery and firmware version
if basic_data := await self._get_basic_info():
self._last_full_update = time.monotonic()
self._update_parsed_data(self._parse_basic_data(basic_data))
self._fire_callbacks()

return status

async def get_basic_info(self) -> dict[str, Any] | None:
"""Get device basic status."""
Expand All @@ -188,10 +201,9 @@ async def get_basic_info(self) -> dict[str, Any] | None:
if not basic_data:
return None

lock_data = self._parse_lock_data(lock_raw_data[1:])
lock_data.update(battery=basic_data[1], firmware=basic_data[2] / 10.0)

return lock_data
return self._parse_lock_data(lock_raw_data[1:]) | self._parse_basic_data(
basic_data
)

def is_calibrated(self) -> Any:
"""Return True if lock is calibrated."""
Expand Down

0 comments on commit c7f1228

Please sign in to comment.