Skip to content

Commit

Permalink
v1.6.1, wifi switch fix #48 + awaiting config_entries.async_forward_e…
Browse files Browse the repository at this point in the history
…ntry_setup(
  • Loading branch information
myTselection committed Jul 13, 2024
1 parent 60e91e5 commit 89f3863
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 106 deletions.
5 changes: 1 addition & 4 deletions custom_components/telenet_telemeter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,7 @@ async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry):

async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Set up component as config entry."""
for platform in PLATFORMS:
hass.async_create_task(
await hass.config_entries.async_forward_entry_setup(config_entry, platform)
)
await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
_LOGGER.info(f"{DOMAIN} register_services")
internet = config_entry.data.get("internet")
if internet:
Expand Down
91 changes: 18 additions & 73 deletions custom_components/telenet_telemeter/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,10 @@ def __init__(self, hass, config):
self._username = config.get('username')
self._password = config.get('password')
self._wifiState = False
self._wifreeState = False
self._session = TelenetSession()
self._update_required = False

async def handle_switch_wireless(self, enableWifi, enableWifree):
async def handle_switch_wireless(self, enableWifi):
"""Handle the service call."""

if not(self._session):
Expand Down Expand Up @@ -79,33 +78,32 @@ async def handle_switch_wireless(self, enableWifi, enableWifree):
if option.get('specurl'):
urlDetails = await self._hass.async_add_executor_job(lambda: self._session.urldetails(option.get('specurl')))

wifiDetails = await self._hass.async_add_executor_job(lambda: self._session.wifidetails(internetProductIdentifier, modemMac))
# wifiDetails = await self._hass.async_add_executor_job(lambda: self._session.wifidetails(internetProductIdentifier, modemMac))
# wifiEnabled = wifiDetails.get('wirelessEnabled')
wifiEnabled = wifiDetails.get("wirelessInterfaces")[0].get('active')
wifreeEnabled = wifiDetails.get('homeSpotEnabled')
_LOGGER.debug(f"wifidetails switch handle: {wifiDetails}")
# wifiEnabled = wifiDetails.get("wirelessInterfaces")[0].get('active')
wifiStatus = await self._hass.async_add_executor_job(lambda: self._session.wifiStatus(internetProductIdentifier, modemMac))
_LOGGER.debug(f"wifiStatus switch handle: {wifiStatus}")
wifiEnabled = wifiStatus.get('cos') == 'WSO_SHARING'
# _LOGGER.debug(f"wifidetails switch handle: {wifiDetails}")

if enableWifi is None:
enableWifi = wifiEnabled
if enableWifree is None:
enableWifree = wifreeEnabled

# if wifiEnabled and enableWifi and wifreeEnabled == enableWifree:
# _LOGGER.debug(f"no wifi change required: wifiEnabled: {wifiEnabled}, enableWifi: {enableWifi}, wifreeEnabled: {wifreeEnabled}, enableWifree: {enableWifree}")
# return
# else:
_LOGGER.debug(f"wifi change required: wifiEnabled: {wifiEnabled}, enableWifi: {enableWifi}, wifreeEnabled: {wifreeEnabled}, enableWifree: {enableWifree}")
_LOGGER.debug(f"wifi change required: wifiEnabled: {wifiEnabled}, enableWifi: {enableWifi}")


await self._hass.async_add_executor_job(lambda: self._session.switchWifi(enableWifree, enableWifi, internetProductIdentifier, modemMac, customerLocationId))
await self._hass.async_add_executor_job(lambda: self._session.switchWifi(enableWifi, internetProductIdentifier, modemMac, customerLocationId))

_LOGGER.debug(f"{NAME} handle_switch_wifi switch executed, old state: wifiEnabled: {wifiEnabled}, wifreeEnabled: {wifreeEnabled}, new state: enableWifi: {enableWifi}, enableWifree: {enableWifree}")
_LOGGER.debug(f"{NAME} handle_switch_wifi switch executed, old state: wifiEnabled: {wifiEnabled}, new state: enableWifi: {enableWifi}")


wifiDetails = await self._hass.async_add_executor_job(lambda: self._session.wifidetails(internetProductIdentifier, modemMac))
# wifiEnabled = wifiDetails.get('wirelessEnabled')
self._wifiState = enableWifi
self._wifreeState = (enableWifree == "Yes")
self._update_required = True
return

Expand Down Expand Up @@ -147,11 +145,13 @@ async def force_update(self):
if option.get('specurl'):
urlDetails = await self._hass.async_add_executor_job(lambda: self._session.urldetails(option.get('specurl')))

wifiDetails = await self._hass.async_add_executor_job(lambda: self._session.wifidetails(internetProductIdentifier, modemMac))
# wifiDetails = await self._hass.async_add_executor_job(lambda: self._session.wifidetails(internetProductIdentifier, modemMac))
# wifiEnabled = wifiDetails.get('wirelessEnabled')
_LOGGER.debug(f"wifidetails switch update: {wifiDetails}")
self._wifiState = bool(wifiDetails.get("wirelessInterfaces")[0].get('active'))
self._wifreeState = (wifiDetails.get('homeSpotEnabled') == "Yes")
# _LOGGER.debug(f"wifidetails switch update: {wifiDetails}")
wifiStatus = await self._hass.async_add_executor_job(lambda: self._session.wifiStatus(internetProductIdentifier, modemMac))
_LOGGER.debug(f"wifiStatus switch handle: {wifiStatus}")
wifiEnabled = wifiStatus.get('cos') == 'WSO_SHARING'
self._wifiState = wifiEnabled
self._update_required = False
return

Expand All @@ -169,22 +169,12 @@ async def update(self):
async def turn_on_wifi(self):
# response = await self.handle_switch_wireless(True, None)
# return response.get("wifiEnabled")
await self.handle_switch_wireless(True, None)
await self.handle_switch_wireless(True)

async def turn_off_wifi(self):
# response = await self.handle_switch_wireless(False, None)
# return response.get("wifiEnabled")
await self.handle_switch_wireless(False, None)

async def turn_on_wifree(self):
# response = await self.handle_switch_wireless(None, True)
# return response.get("wifreeEnabled")
await self.handle_switch_wireless(None, True)

async def turn_off_wifree(self):
# response = await self.handle_switch_wireless(None, False)
# return response.get("wifreeEnabled")
await self.handle_switch_wireless(None, False)
await self.handle_switch_wireless(False)

class WifiSwitch(SwitchEntity):
"""Representation of a Audi switch."""
Expand Down Expand Up @@ -231,48 +221,3 @@ async def async_turn_on(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Turn the switch off."""
await self._data.turn_off_wifi()

class WifreeSwitch(SwitchEntity):
"""Representation of a Audi switch."""
def __init__(self, data):
self._data = data

@property
def name(self) -> str:
return self.unique_id

@property
def icon(self) -> str:
"""Shows the correct icon for container."""
return "mdi:wifi-star"

@property
def unique_id(self) -> str:
"""Return the name of the sensor."""
return (
f"{NAME} Wi-free"
)

@property
def device_info(self) -> dict:
"""Return the device info."""
return {
"identifiers": {(NAME, self._data.unique_id)},
"name": self._data.name,
"manufacturer": NAME,
}
async def async_update(self):
await self._data.update()

@property
def is_on(self):
"""Return true if switch is on."""
return self._data._wifreeState

async def async_turn_on(self, **kwargs):
"""Turn the switch on."""
await self._data.turn_on_wifree()

async def async_turn_off(self, **kwargs):
"""Turn the switch off."""
await self._data.turn_off_wifree()
84 changes: 55 additions & 29 deletions custom_components/telenet_telemeter/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,27 +58,49 @@ def __init__(self):
self.s.headers["x-alt-referer"] = "https://www2.telenet.be/residential/nl/mijn-telenet"

def callTelenet(self, url, caller = "Not set", expectedStatusCode = 200, data = None, printResponse = False, method : HttpMethod = HttpMethod.GET):
if method == HttpMethod.GET:
_LOGGER.debug(f"[{caller}] Calling GET {url}")
response = self.s.get(url,timeout=30)
elif method == HttpMethod.POST:
# self.s.headers["Content-Type"] = "application/json;charset=UTF-8"
_LOGGER.debug(f"[{caller}] Calling POST {url} with data {data}")
response = self.s.post(url,data,timeout=30)
elif method == HttpMethod.PATCH:
self.s.headers["Content-Type"] = "application/json;charset=UTF-8"
_LOGGER.debug(f"[{caller}] Calling PATCH {url} with data: {data}")
response = self.s.patch(url,json=data,timeout=60)
elif method == HttpMethod.OPTIONS:
self.s.headers["Content-Type"] = "application/json;charset=UTF-8"
_LOGGER.debug(f"[{caller}] Calling OPTIONS {url} with data: {data}")
response = self.s.options(url,timeout=60)
_LOGGER.debug(f"[{caller}] http status code = {response.status_code} (expecting {expectedStatusCode})")
if printResponse:
_LOGGER.debug(f"[{caller}] Response: {response.text}")
if expectedStatusCode != None:
assert response.status_code == expectedStatusCode

try:
if method == HttpMethod.GET:
_LOGGER.debug(f"[{caller}] Calling GET {url}")
response = self.s.get(url,timeout=30)
elif method == HttpMethod.POST:
# self.s.headers["Content-Type"] = "application/json;charset=UTF-8"
_LOGGER.debug(f"[{caller}] Calling POST {url} with data {data}")
response = self.s.post(url,data,timeout=30)
elif method == HttpMethod.PATCH:
self.s.headers["Content-Type"] = "application/json;charset=UTF-8"
_LOGGER.debug(f"[{caller}] Calling PATCH {url} with data: {data}")
response = self.s.patch(url,json=data,timeout=60)
elif method == HttpMethod.OPTIONS:
self.s.headers["Content-Type"] = "application/json;charset=UTF-8"
_LOGGER.debug(f"[{caller}] Calling OPTIONS {url} with data: {data}")
response = self.s.options(url,timeout=60)
_LOGGER.debug(f"[{caller}] http status code = {response.status_code} (expecting {expectedStatusCode})")
if printResponse:
_LOGGER.debug(f"[{caller}] Response: {response.text}")
if expectedStatusCode != None:
assert response.status_code == expectedStatusCode
except Exception as e:
_LOGGER.error(f"callTelenet failed, trying once more: {e}")
if method == HttpMethod.GET:
_LOGGER.debug(f"[{caller}] Calling GET {url}")
response = self.s.get(url,timeout=30)
elif method == HttpMethod.POST:
# self.s.headers["Content-Type"] = "application/json;charset=UTF-8"
_LOGGER.debug(f"[{caller}] Calling POST {url} with data {data}")
response = self.s.post(url,data,timeout=30)
elif method == HttpMethod.PATCH:
self.s.headers["Content-Type"] = "application/json;charset=UTF-8"
_LOGGER.debug(f"[{caller}] Calling PATCH {url} with data: {data}")
response = self.s.patch(url,json=data,timeout=60)
elif method == HttpMethod.OPTIONS:
self.s.headers["Content-Type"] = "application/json;charset=UTF-8"
_LOGGER.debug(f"[{caller}] Calling OPTIONS {url} with data: {data}")
response = self.s.options(url,timeout=60)
_LOGGER.debug(f"[{caller}] http status code = {response.status_code} (expecting {expectedStatusCode})")
if printResponse:
_LOGGER.debug(f"[{caller}] Response: {response.text}")
if expectedStatusCode != None:
assert response.status_code == expectedStatusCode
return response

def login(self, username, password):
Expand Down Expand Up @@ -120,19 +142,23 @@ def wifidetails(self, productIdentifier, modemMac):
response = self.callTelenet(f"https://api.prd.telenet.be/ocapi/public/api/resource-service/v1/modems/{modemMac}/wireless-settings?withmetadata=true&withwirelessservice=true&productidentifier={productIdentifier}","wifidetails")
return response.json()

def wifiStatus(self, productIdentifier, modemMac):
response = self.callTelenet(f"https://api.prd.telenet.be/ocapi/public/api/resource-service/v1/modems/{modemMac}/wireless-status?productidentifier={productIdentifier}","wifiStatus")
return response.json()

def urldetails(self, url):
response = self.callTelenet(url,"urldetails")
return response.json()

def switchWifi(self, homeSpotEnabled, wirelessEnabled: bool, productIdentifier: bool, modemMac, locationId):
if homeSpotEnabled:
homeSpotEnabled = "Yes"
def switchWifi(self, wirelessEnabled: bool, productIdentifier: bool, modemMac, locationId):
# data = {"productIdentifier":productIdentifier,"homeSpotEnabled":homeSpotEnabled,"wirelessEnabled":"Yes","locationId":locationId,"patchOperations":[{"op":"replace","path":"/wirelessInterfaces/2.4GHZ/ssids/PRIMARY/active","value":wirelessEnabled},{"op":"replace","path":"/wirelessInterfaces/5GHZ/ssids/PRIMARY/active","value":wirelessEnabled}]}
if wirelessEnabled:
data = {"cos": "WSO_SHARING"}
else:
homeSpotEnabled = "No"

data = {"productIdentifier":productIdentifier,"homeSpotEnabled":homeSpotEnabled,"wirelessEnabled":"Yes","locationId":locationId,"patchOperations":[{"op":"replace","path":"/wirelessInterfaces/2.4GHZ/ssids/PRIMARY/active","value":wirelessEnabled},{"op":"replace","path":"/wirelessInterfaces/5GHZ/ssids/PRIMARY/active","value":wirelessEnabled}]}
self.callTelenet(f"https://api.prd.telenet.be/ocapi/public/api/resource-service/v1/modems/{modemMac}/wireless-settings","optionswifi", 200, None, True, HttpMethod.OPTIONS)
self.callTelenet(f"https://api.prd.telenet.be/ocapi/public/api/resource-service/v1/modems/{modemMac}/wireless-settings","patchwifi", 200, data, True, HttpMethod.PATCH)
data = {"cos":"WSO_OFF"}
# self.callTelenet(f"https://api.prd.telenet.be/ocapi/public/api/resource-service/v1/modems/{modemMac}/wireless-settings","optionswifi", 200, None, True, HttpMethod.OPTIONS)
# self.callTelenet(f"https://api.prd.telenet.be/ocapi/public/api/resource-service/v1/modems/{modemMac}/wireless-settings","patchwifi", 200, data, True, HttpMethod.PATCH)
self.callTelenet(f"https://api.prd.telenet.be/ocapi/public/api/resource-service/v1/modems/{modemMac}/wireless-status","patchwifi", 200, data, True, HttpMethod.PATCH)
return

def reboot(self, modemMac):
Expand Down

0 comments on commit 89f3863

Please sign in to comment.