Skip to content

Commit

Permalink
Merge pull request #126 from jwillemsen/jwi-requestscleanup
Browse files Browse the repository at this point in the history
Cleanup of bearerrquest
  • Loading branch information
jwillemsen authored Mar 22, 2024
2 parents 1f8d7c7 + 4fd1071 commit 1a8b8aa
Show file tree
Hide file tree
Showing 9 changed files with 12,571 additions and 46 deletions.
24 changes: 12 additions & 12 deletions custom_components/daikin_onecta/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ async def async_set_temperature(self, **kwargs):
operationmode = self.operation_mode()
omv = operationmode["value"]
value = kwargs[ATTR_TEMPERATURE]
res = await self._device.set_path(
res = await self._device.patch(
self._device.id,
self._embedded_id,
"temperatureControl",
Expand Down Expand Up @@ -374,7 +374,7 @@ async def async_set_hvac_mode(self, hvac_mode):

# Only set the on/off to Daikin when we need to change it
if on_off_mode is not None:
result &= await self._device.set_path(self._device.id, self._embedded_id, "onOffMode", "", on_off_mode)
result &= await self._device.patch(self._device.id, self._embedded_id, "onOffMode", "", on_off_mode)
if result is False:
_LOGGER.warning(
"Device '%s' problem setting onOffMode to %s",
Expand All @@ -388,7 +388,7 @@ async def async_set_hvac_mode(self, hvac_mode):
# Only set the operationMode when it has changed, also prevents setting it when
# it is readOnly
if operation_mode != cc["operationMode"]["value"]:
result &= await self._device.set_path(
result &= await self._device.patch(
self._device.id,
self._embedded_id,
"operationMode",
Expand Down Expand Up @@ -473,7 +473,7 @@ async def async_set_fan_mode(self, fan_mode):
if not self._attr_fan_mode.isnumeric():
# Only set the currentMode to fixed when we currently don't have set
# a numeric mode
res = await self._device.set_path(
res = await self._device.patch(
self._device.id,
self._embedded_id,
"fanControl",
Expand All @@ -487,7 +487,7 @@ async def async_set_fan_mode(self, fan_mode):
)

new_fixed_mode = int(fan_mode)
res &= await self._device.set_path(
res &= await self._device.patch(
self._device.id,
self._embedded_id,
"fanControl",
Expand All @@ -501,7 +501,7 @@ async def async_set_fan_mode(self, fan_mode):
new_fixed_mode,
)
else:
res = await self._device.set_path(
res = await self._device.patch(
self._device.id,
self._embedded_id,
"fanControl",
Expand Down Expand Up @@ -622,7 +622,7 @@ async def async_set_swing_mode(self, swing_mode):
"floorHeatingAirflow and Horizontal",
):
new_h_mode = "swing"
res &= await self._device.set_path(
res &= await self._device.patch(
self._device.id,
self._embedded_id,
"fanControl",
Expand Down Expand Up @@ -650,7 +650,7 @@ async def async_set_swing_mode(self, swing_mode):
"Comfort Airflow and Horizontal",
):
new_v_mode = "windNice"
res &= await self._device.set_path(
res &= await self._device.patch(
self._device.id,
self._embedded_id,
"fanControl",
Expand Down Expand Up @@ -705,7 +705,7 @@ async def async_set_preset_mode(self, preset_mode):
current_mode,
)
else:
result &= await self._device.set_path(self._device.id, self._embedded_id, current_mode, "", "off")
result &= await self._device.patch(self._device.id, self._embedded_id, current_mode, "", "off")
if result is False:
_LOGGER.warning(
"Device '%s' problem setting %s to off",
Expand All @@ -727,7 +727,7 @@ async def async_set_preset_mode(self, preset_mode):
new_daikin_mode,
)
else:
result &= await self._device.set_path(self._device.id, self._embedded_id, new_daikin_mode, "", "on")
result &= await self._device.patch(self._device.id, self._embedded_id, new_daikin_mode, "", "on")
if result is False:
_LOGGER.warning(
"Device '%s' problem setting %s to on",
Expand Down Expand Up @@ -766,7 +766,7 @@ async def async_turn_on(self):
cc = self.climate_control()
result = True
if cc["onOffMode"]["value"] == "off":
result &= await self._device.set_path(self._device.id, self._embedded_id, "onOffMode", "", "on")
result &= await self._device.patch(self._device.id, self._embedded_id, "onOffMode", "", "on")
if result is False:
_LOGGER.error("Device '%s' problem setting onOffMode to on", self._device.name)
else:
Expand All @@ -786,7 +786,7 @@ async def async_turn_off(self):
cc = self.climate_control()
result = True
if cc["onOffMode"]["value"] == "on":
result &= await self._device.set_path(self._device.id, self._embedded_id, "onOffMode", "", "off")
result &= await self._device.patch(self._device.id, self._embedded_id, "onOffMode", "", "off")
if result is False:
_LOGGER.error("Device '%s' problem setting onOffMode to off", self._device.name)
else:
Expand Down
27 changes: 9 additions & 18 deletions custom_components/daikin_onecta/daikin_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ async def async_get_access_token(self) -> str:
await self.session.async_ensure_token_valid()
return self.session.token["access_token"]

async def doBearerRequest(self, resourceUrl, options=None):
async def doBearerRequest(self, method, resourceUrl, options=None):
async with self._cloud_lock:
token = await self.async_get_access_token()
if token is None:
Expand All @@ -71,21 +71,12 @@ async def doBearerRequest(self, resourceUrl, options=None):
headers = {"Accept-Encoding": "gzip", "Authorization": "Bearer " + token, "Content-Type": "application/json"}

_LOGGER.debug("BEARER REQUEST URL: %s", resourceUrl)
if options is not None and "method" in options and options["method"] == "PATCH":
_LOGGER.debug("BEARER PATCH JSON: %s", options["json"])
func = functools.partial(requests.patch, resourceUrl, headers=headers, data=options["json"])
elif options is not None and "method" in options and options["method"] == "POST":
_LOGGER.debug("BEARER POST JSON: %s", options["json"])
func = functools.partial(requests.post, resourceUrl, headers=headers, data=options["json"])
elif options is not None and "method" in options and options["method"] == "PUT":
_LOGGER.debug("BEARER POST JSON: %s", options["json"])
func = functools.partial(requests.put, resourceUrl, headers=headers, data=options["json"])
else:
func = functools.partial(requests.get, resourceUrl, headers=headers)
_LOGGER.debug("BEARER TYPE %s JSON: %s", method, options)
func = functools.partial(requests.request, url=resourceUrl, method=method, headers=headers, data=options)
try:
res = await self.hass.async_add_executor_job(func)
except Exception as e:
_LOGGER.error("REQUEST FAILED: %s", e)
_LOGGER.error("REQUEST TYPE %s FAILED: %s", method, e)
return []

self.rate_limits["minute"] = int(res.headers.get("X-RateLimit-Limit-minute", 0))
Expand All @@ -103,7 +94,7 @@ async def doBearerRequest(self, resourceUrl, options=None):

_LOGGER.debug("BEARER RESPONSE CODE: %s LIMIT: %s", res.status_code, self.rate_limits)

if res.status_code == 200:
if method == "GET" and res.status_code == 200:
try:
return res.json()
except Exception:
Expand Down Expand Up @@ -133,10 +124,10 @@ async def doBearerRequest(self, resourceUrl, options=None):
learn_more_url="https://developer.cloud.daikineurope.com/docs/b0dffcaa-7b51-428a-bdff-a7c8a64195c0/rate_limitation",
translation_key="day_rate_limit",
)
if options is not None and "method" in options and options["method"] == "PATCH":
return False
else:
if method == "GET":
return []
else:
return False
elif res.status_code == 204:
self._last_patch_call = datetime.now()
return True
Expand All @@ -145,4 +136,4 @@ async def doBearerRequest(self, resourceUrl, options=None):

async def getCloudDeviceDetails(self):
"""Get pure Device Data from the Daikin cloud devices."""
return await self.doBearerRequest("/v1/gateway-devices")
return await self.doBearerRequest("GET", "/v1/gateway-devices")
16 changes: 8 additions & 8 deletions custom_components/daikin_onecta/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,38 +79,38 @@ def setJsonData(self, desc):
"""Set a device description and parse/traverse data structure."""
self.merge_json(self.daikin_data, desc)

async def set_path(self, id, embeddedId, dataPoint, dataPointPath, value):
async def patch(self, id, embeddedId, dataPoint, dataPointPath, value):
setPath = "/v1/gateway-devices/" + id + "/management-points/" + embeddedId + "/characteristics/" + dataPoint
setBody = {"value": value}
if dataPointPath != "":
if dataPointPath:
setBody["path"] = dataPointPath
setOptions = {"method": "PATCH", "json": json.dumps(setBody)}
setOptions = json.dumps(setBody)

_LOGGER.info("Path: " + setPath + " , options: %s", setOptions)

res = await self.api.doBearerRequest(setPath, setOptions)
res = await self.api.doBearerRequest("PATCH", setPath, setOptions)
_LOGGER.debug("RES IS {}".format(res))

return res

async def post(self, id, embeddedId, dataPoint, value):
setPath = "/v1/gateway-devices/" + id + "/management-points/" + embeddedId + "/" + dataPoint
setOptions = {"method": "POST", "json": json.dumps(value)}
setOptions = json.dumps(value)

_LOGGER.info("Path: " + setPath + " , options: %s", setOptions)

res = await self.api.doBearerRequest(setPath, setOptions)
res = await self.api.doBearerRequest("POST", setPath, setOptions)
_LOGGER.debug("RES IS {}".format(res))

return res

async def put(self, id, embeddedId, dataPoint, value):
setPath = "/v1/gateway-devices/" + id + "/management-points/" + embeddedId + "/" + dataPoint
setOptions = {"method": "PUT", "json": json.dumps(value)}
setOptions = json.dumps(value)

_LOGGER.info("Path: " + setPath + " , options: %s", setOptions)

res = await self.api.doBearerRequest(setPath, setOptions)
res = await self.api.doBearerRequest("PUT", setPath, setOptions)
_LOGGER.debug("RES IS {}".format(res))

return res
4 changes: 2 additions & 2 deletions custom_components/daikin_onecta/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ async def async_select_option(self, option: str) -> None:
new_currentmode = "fixed"
if option in ("auto", "off"):
new_currentmode = option
res = await self._device.set_path(
res = await self._device.patch(
self._device.id,
self._embedded_id,
"demandControl",
Expand All @@ -122,7 +122,7 @@ async def async_select_option(self, option: str) -> None:
mode["value"] = new_currentmode

if new_currentmode == "fixed":
res = await self._device.set_path(
res = await self._device.patch(
self._device.id,
self._embedded_id,
"demandControl",
Expand Down
4 changes: 2 additions & 2 deletions custom_components/daikin_onecta/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ async def async_turn_on(self, **kwargs):
"""Turn the zone on."""
result = True
if not self.is_on:
result &= await self._device.set_path(self._device.id, self._embedded_id, self._value, "", "on")
result &= await self._device.patch(self._device.id, self._embedded_id, self._value, "", "on")
if result is False:
_LOGGER.warning("Device '%s' problem setting '%s' to on", self._device.name, self._value)
else:
Expand All @@ -159,7 +159,7 @@ async def async_turn_off(self, **kwargs):
"""Turn the zone off."""
result = True
if self.is_on:
result &= await self._device.set_path(self._device.id, self._embedded_id, self._value, "", "off")
result &= await self._device.patch(self._device.id, self._embedded_id, self._value, "", "off")
if result is False:
_LOGGER.warning(
"Device '%s' problem setting '%s' to off",
Expand Down
6 changes: 3 additions & 3 deletions custom_components/daikin_onecta/water_heater.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ async def async_set_tank_temperature(self, value):
self._device.name,
)
return None
res = await self._device.set_path(
res = await self._device.patch(
self._device.id,
self._embedded_id,
"temperatureControl",
Expand Down Expand Up @@ -249,10 +249,10 @@ async def async_set_operation_mode(self, operation_mode):

# Only set the on/off to Daikin when we need to change it
if on_off_mode != "":
result &= await self._device.set_path(self._device.id, self._embedded_id, "onOffMode", "", on_off_mode)
result &= await self._device.patch(self._device.id, self._embedded_id, "onOffMode", "", on_off_mode)
# Only set powerfulMode when it is set and supported by the device
if (powerful_mode != "") and (STATE_PERFORMANCE in self.operation_list):
result &= await self._device.set_path(
result &= await self._device.patch(
self._device.id,
self._embedded_id,
"powerfulMode",
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Start by going to Settings - Devices & Services and pressing the `+ ADD INTEGRAT

Follow the instructions, you have to login at Daikin and authorize the application. After pressing the "Submit" button, the integration will be added, and the Daikin devices connected to your cloud account will be created. See https://www.home-assistant.io/integrations/application_credentials for more information about application credentials within Home Assistant.

The `OAuth Client ID` and `OAuth Client Secret` need to be obtained from Daikin, see https://developer.cloud.daikineurope.com/docs/b0dffcaa-7b51-428a-bdff-a7c8a64195c0/getting_started for the id/secret keys which are valid Spring 2024. The `Name` is user defined, for example `Daikin`. You _must_ create a Daikin Developer account to obtain the id/secret.
The `OAuth Client ID` and `OAuth Client Secret` need to be obtained from Daikin, see https://developer.cloud.daikineurope.com/docs/b0dffcaa-7b51-428a-bdff-a7c8a64195c0/getting_started for the id/secret keys which are valid Spring 2024. The `Name` is user defined, for example `Daikin`. You _must_ create a Daikin Developer account to obtain the id/secret.

When you try to reinstall this integration check if you don't have an old client id and secret configured within Home Assistant, see [Application Credentials](https://www.home-assistant.io/integrations/application_credentials/) for more information.

Expand Down
Loading

0 comments on commit 1a8b8aa

Please sign in to comment.