Skip to content

Commit

Permalink
Merge pull request #11 from elad-bar/main
Browse files Browse the repository at this point in the history
Fixed #10 - Component trigger many internet calls
  • Loading branch information
rroller authored Mar 17, 2022
2 parents d3a2e7f + 6f97497 commit 554dc1a
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 44 deletions.
21 changes: 12 additions & 9 deletions custom_components/netgear_wax/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,24 +101,27 @@ async def async_stop(self, event: Any):

async def _async_update_data(self) -> DeviceState:
"""Reload information by fetching from the API"""
try:
self._state = await self.client.async_get_state()
self._ssids = await self.client.async_get_ssids()
self._initialized = True
except Exception as exception:
_LOGGER.debug("Failed to read current state", exc_info=exception)
raise UpdateFailed() from exception

# Only check for firmware updates every 6 hours
check_firmware = False
try:
if (time.time() - self._firmware_last_checked) > 21600:
check_firmware = (time.time() - self._firmware_last_checked) > 21600

if check_firmware:
self._firmware_last_checked = time.time()
await self.client.check_for_firmware_updates()
except Exception as exception:
# Not vital for this API to run so we'll pass on errors
_LOGGER.info("Failed to check for firmware updates", exc_info=exception)
pass

try:
self._state = await self.client.async_get_state(check_firmware)
self._ssids = await self.client.async_get_ssids()
self._initialized = True
except Exception as exception:
_LOGGER.debug("Failed to read current state", exc_info=exception)
raise UpdateFailed() from exception

return self._state

def on_receive(self, data_bytes: bytes):
Expand Down
4 changes: 2 additions & 2 deletions custom_components/netgear_wax/client.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Netgear API Client."""
import abc
from dataclasses import dataclass
from typing import List, Dict
from typing import List, Dict, Optional


@dataclass(unsafe_hash=True)
Expand Down Expand Up @@ -49,7 +49,7 @@ async def async_logout(self):
pass

@abc.abstractmethod
async def async_get_state(self) -> DeviceState:
async def async_get_state(self, check_firmware: Optional[bool] = False) -> DeviceState:
pass

@abc.abstractmethod
Expand Down
57 changes: 24 additions & 33 deletions custom_components/netgear_wax/client_wax.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
"""Netgear API Client."""
import json
import logging
import time

import aiohttp
from aiohttp import hdrs
from aiohttp.client_reqrep import ClientResponse
from typing import List
from typing import List, Optional

from custom_components.netgear_wax.client import NetgearClient, DeviceState, Ssid, Stat
from custom_components.netgear_wax.const import STATE_REQUEST_DATA
from custom_components.netgear_wax.utils import parse_human_string, safe_cast

_LOGGER: logging.Logger = logging.getLogger(__package__)
Expand All @@ -25,6 +27,8 @@ def __init__(self, username: str, password: str, address: str, port: int, sessio
self._base_url = "https://{0}:{1}".format(address, port)
self._lhttpdsid = ""
self._security_token = ""
self._internet_connectivity_check: Optional[float] = None

_LOGGER.debug("Creating client with username %s", username)

async def async_login(self):
Expand Down Expand Up @@ -64,42 +68,29 @@ async def async_logout(self):
cookies=self.get_auth_cookie(), headers=self.get_auth_header())
response.raise_for_status()

async def async_get_state(self) -> DeviceState:
async def async_get_state(self, check_firmware: Optional[bool] = False) -> DeviceState:
""" async_get_state gets the current state from the access point (mac address, name, firmware, etc) """
data = json.dumps({
"system": {
"FwUpdate": {
data = STATE_REQUEST_DATA.copy()

if (self._internet_connectivity_check is None or time.time() - self._internet_connectivity_check) > 3600:
system_data = data["system"]
monitor_data = system_data["monitor"]
monitor_data["internetConnectivityStatus"] = ""

self._internet_connectivity_check = time.time()

if check_firmware:
system_data = data["system"]
system_data["FwUpdate"] = {
"ImageAvailable": "",
"ImageVersion": ""},
"monitor": {
"productId": "",
"internetConnectivityStatus": "",
"totalNumberOfDevices": "",
"sysSerialNumber": "",
"ethernetMacAddress": "",
"sysVersion": "",
"FiveGhzSupport": {},
"stats": {
"lan": {
"traffic": "",
},
"wlan0": {
"traffic": "",
"channelUtil": "",
},
"wlan1": {
"traffic": "",
"channelUtil": "",
}
},
},
"basicSettings": {
"apName": "",
},
"ImageVersion": ""
}
})

result = await self.async_post(data)
self._firmware_update_check = time.time()

request_data = json.dumps(data)

result = await self.async_post(request_data)
system = result["system"]
monitor = system["monitor"]

Expand Down
29 changes: 29 additions & 0 deletions custom_components/netgear_wax/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,32 @@
{ISSUE_URL}
-------------------------------------------------------------------
"""

STATE_REQUEST_DATA = {
"system": {
"monitor": {
"productId": "",
"totalNumberOfDevices": "",
"sysSerialNumber": "",
"ethernetMacAddress": "",
"sysVersion": "",
"FiveGhzSupport": {},
"stats": {
"lan": {
"traffic": "",
},
"wlan0": {
"traffic": "",
"channelUtil": "",
},
"wlan1": {
"traffic": "",
"channelUtil": "",
}
},
},
"basicSettings": {
"apName": "",
},
}
}

0 comments on commit 554dc1a

Please sign in to comment.