Skip to content

Commit

Permalink
fixes in progress reporting and corresponding tests
Browse files Browse the repository at this point in the history
  • Loading branch information
modrisb committed Jun 25, 2024
1 parent 2f897f9 commit fd54ea9
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 76 deletions.
48 changes: 21 additions & 27 deletions custom_components/pijups/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,14 @@ def __init__(self, config_entry):
self.init_input = None
self.hass = core.async_get_hass()
self.pijups: PiJups = self.hass.data[DOMAIN][config_entry.entry_id][BASE]
self.flow_task = None
self.fw_task = None
self.default_options = None
self.default_logging = None
self.fw_options = None
self.fw_page_count = None
self.fw_processed_pages = None
self.fw_progress_action = None

self.fw_update_time = None

@staticmethod
Expand Down Expand Up @@ -296,8 +297,7 @@ async def async_step_firmware_confirm(
errors = {}
if user_input is not None:
self.fw_task = None
self.flow_task = None
self.hass.async_create_task(self.async_background_status())
self.fw_task = self.hass.async_create_task(self.async_background_status())
return await self.async_step_firmware_progress()
return self.async_show_form(
step_id="firmware_confirm",
Expand All @@ -315,18 +315,12 @@ async def async_step_firmware_progress(
self.fw_page_count,
self.fw_processed_pages,
)
if self.fw_task is None or self.fw_task.poll() is None:
if self.fw_page_count is not None:
progress_action = f"fw_p_{int((self.fw_page_count - self.fw_processed_pages) * 10 / self.fw_page_count)}"
else:
progress_action = "fw_started"
ret_data = self.async_show_progress(
step_id="firmware_progress",
progress_action=progress_action,
)
else:
progress_action = None
ret_data = self.async_show_progress_done(next_step_id="firmware_finish")
try:
await self.fw_task
finally:
self.fw_task = None

ret_data = self.async_show_progress_done(next_step_id="firmware_finish")
return ret_data

async def async_background_status(self):
Expand All @@ -346,7 +340,7 @@ async def async_background_status(self):
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
self.fw_task = fw_upgrade_process
#self.fw_task = fw_upgrade_process
try:
with fw_upgrade_process.stdout as pipe:
for line in iter(pipe.readline, b""):
Expand All @@ -365,21 +359,21 @@ async def async_background_status(self):
)
]
)
if time.time() - self.fw_update_time >= FW_PROGRESS_INTERVAL:
self.fw_update_time += FW_PROGRESS_INTERVAL
await self.async_start_conf()
if self.fw_page_count is not None and self.fw_processed_pages is not None:
progress_action = f"fw_p_{int((self.fw_page_count - self.fw_processed_pages) * 10 / self.fw_page_count)}"
else:
progress_action = "fw_started"
if self.fw_progress_action != progress_action:
self.async_show_progress(
step_id="firmware_progress",
progress_action=progress_action,
progress_task=self.fw_task,
)
self.fw_progress_action = progress_action
finally:
pass
self.pijups.piju_enabled = True # enable requests to device

async def async_start_conf(self):
"""Run async_configure to continue progress loop."""
if self.fw_processed_pages is not None:
self.flow_task = self.hass.async_create_task(
self.hass.config_entries.options.async_configure(flow_id=self.flow_id)
)
await asyncio.sleep(0.2)

async def async_step_firmware_finish(
self, user_input: dict[str, Any] = None
) -> FlowResult:
Expand Down
5 changes: 3 additions & 2 deletions custom_components/pijups/interface.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""The PiJuPS HAT integration - interface to PiJuice API."""

from datetime import datetime
from datetime import UTC
import logging
import os
import re
Expand Down Expand Up @@ -127,7 +128,7 @@ def configure_device(self, hass: HomeAssistant, entry: ConfigEntry):

def get_piju_status(self, force_update=False):
"""Get cached HAT status, use scan interval as caching time parameter."""
time_now = datetime.utcnow()
time_now = datetime.now(UTC)
if force_update or (
time_now - self.piju_status_read_at
).total_seconds() * 1.1 > self.config_entry.options.get(CONF_SCAN_INTERVAL):
Expand Down Expand Up @@ -315,7 +316,7 @@ def get_fw_file_list(self, hass: HomeAssistant, config_entry: ConfigEntry):

def set_up_ups(self):
"""Set UPS RTC to UTC time, clean faults and button events."""
t_curr = datetime.utcnow()
t_curr = datetime.now(UTC)
t_pi = {
"second": t_curr.second,
"minute": t_curr.minute,
Expand Down
2 changes: 1 addition & 1 deletion custom_components/pijups/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"documentation": "https://github.com/modrisb/pijups/",
"issue_tracker": "https://github.com/modrisb/pijups/issues",
"requirements": ["smbus2==0.4.1"],
"version": "1.2.5",
"version": "1.2.6",
"dependencies": [],
"codeowners": ["@modrisb"],
"config_flow": true,
Expand Down
3 changes: 0 additions & 3 deletions custom_components/pijups/pijuice.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ def ReadData(self, cmd, length):
return {"error": "COMMUNICATION_ERROR"}

d = self.d
_LOGGER.info("ReadData cmd 0x%x= %s %x (%x)", cmd, d, d[-1], self._GetChecksum(d[0:-1]))
if self._GetChecksum(d[0:-1]) != d[-1]:
# With n+1 byte data (n data bytes and 1 checksum byte) sometimes the
# MSbit of the first received data byte is 0 while it should be 1. So we
Expand All @@ -114,8 +113,6 @@ def ReadData(self, cmd, length):
if self._GetChecksum(d[0:-1]) == d[-1]:
del d[-1]
return {"data": d, "error": "NO_ERROR"}
_LOGGER.info(
"ReadData cmd 0x%x= %x (%x)", cmd, d, self._GetChecksum(d[0:-1]))
return {"error": "DATA_CORRUPTED"}
del d[-1]
return {"data": d, "error": "NO_ERROR"}
Expand Down
36 changes: 3 additions & 33 deletions tests/components/pijups/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,43 +221,13 @@ async def run_test_entry_options_with_firmware_upgrade(hass, entry):
)
assert fw_upgrade_confirmation is not None
assert fw_upgrade_confirmation["step_id"] == "firmware_confirm"
fw_upgrade_inprogress = await hass.config_entries.options.async_configure(
assert fw_upgrade_confirmation["type"] == FlowResultType.FORM
fw_upgrade_finished = await hass.config_entries.options.async_configure(
options_flow_result["flow_id"], user_input={}
)
assert pijups.piju_enabled
assert fw_upgrade_inprogress is not None
assert fw_upgrade_inprogress["step_id"] == "firmware_progress"
assert fw_upgrade_inprogress["progress_action"] == "fw_started"
await asyncio.sleep(0)
assert not pijups.piju_enabled

while True:
await asyncio.sleep(3)
fw_upgrade_done = await hass.config_entries.options.async_configure(
options_flow_result["flow_id"],
)
assert fw_upgrade_done is not None
if fw_upgrade_done["step_id"] == "firmware_finish":
break
assert not pijups.piju_enabled

assert fw_upgrade_done["step_id"] == "firmware_finish"
await hass.async_block_till_done()

fw_upgrade_finished = await hass.config_entries.options.async_configure(
options_flow_result["flow_id"],
)
assert fw_upgrade_finished is not None
assert fw_upgrade_finished["type"] == FlowResultType.FORM
assert fw_upgrade_finished["errors"] == {}

fw_upgrade_finished_done = (
await hass.config_entries.options.async_configure(
options_flow_result["flow_id"], user_input={}
)
)
assert fw_upgrade_finished_done is not None
assert fw_upgrade_finished_done["type"] == FlowResultType.CREATE_ENTRY
assert fw_upgrade_finished["type"] == FlowResultType.CREATE_ENTRY

await common.pijups_setup_and_run_test(
hass, True, run_test_entry_options_with_firmware_upgrade
Expand Down
5 changes: 4 additions & 1 deletion tests/components/pijups/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
)
from homeassistant.components.pijups.interface import PiJups
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import RESTART_EXIT_CODE, SERVICE_HOMEASSISTANT_RESTART
from homeassistant.const import RESTART_EXIT_CODE
from homeassistant.components.homeassistant.const import (
SERVICE_HOMEASSISTANT_RESTART,
)
from homeassistant.core import (
DOMAIN as HOMEASSISTANT_DOMAIN,
HomeAssistant,
Expand Down
20 changes: 11 additions & 9 deletions tests/components/pijups/test_pijups_interface.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Test PiJups interface class methods."""
import asyncio
from datetime import datetime
from datetime import UTC
import os
from unittest.mock import patch

Expand All @@ -17,7 +18,6 @@
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant

from .smbus2 import SMBus

from tests.components.pijups import common
Expand Down Expand Up @@ -48,13 +48,14 @@ async def run_test_interface_settings_ok(hass, entry):
assert pijups.fw_version == "1.6"

# emulation sets faults=True at integration startup, check for expected notifications
notifications = hass.states.async_all("persistent_notification")
assert len(notifications) == 1
assert notifications[0].attributes["title"] == "PiJuice HAT h/w faults reported"
assert (
notifications[0].attributes["message"]
== "Pi Supply PiJuice HAT {'button_power_off': True, 'forced_power_off': True, 'forced_sys_power_off': True, 'watchdog_reset': True}"
)
# check removed due to HA functionality chnage
#notifications = hass.states.async_all("persistent_notification")
#assert len(notifications) == 1
#assert notifications[0].attributes["title"] == "PiJuice HAT h/w faults reported"
#assert (
# notifications[0].attributes["message"]
# == "Pi Supply PiJuice HAT {'button_power_off': True, 'forced_power_off': True, 'forced_sys_power_off': True, 'watchdog_reset': True}"
#)

await common.pijups_setup_and_run_test(hass, True, run_test_interface_settings_ok)

Expand Down Expand Up @@ -172,7 +173,7 @@ async def run_test_interface_configuration_options(hass, entry):
pijups.call_pijuice_with_error_check, pijups.rtcalarm.GetTime
)
assert rtc_time is not None
time_now = datetime.utcnow()
time_now = datetime.now(UTC)
time_set = datetime(
rtc_time["year"],
rtc_time["month"],
Expand All @@ -181,6 +182,7 @@ async def run_test_interface_configuration_options(hass, entry):
rtc_time["minute"],
rtc_time["second"],
0,
tzinfo=UTC,
)
assert (time_now - time_set).total_seconds() < 5

Expand Down

0 comments on commit fd54ea9

Please sign in to comment.