Skip to content

Commit

Permalink
feat: Added service for spinning wheel of fortune
Browse files Browse the repository at this point in the history
  • Loading branch information
BottlecapDave committed Nov 12, 2023
1 parent 6273784 commit effcc21
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 12 deletions.
32 changes: 32 additions & 0 deletions custom_components/octopus_energy/api_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,14 @@
}}
}}'''

wheel_of_fortune_mutation = '''mutation {{
spinWheelOfFortune(input: {{ accountNumber: "{account_id}", supplyType: {supply_type}, termsAccepted: true }}) {{
spinResult {{
prizeAmount
}}
}}
}}'''

def get_valid_from(rate):
return rate["valid_from"]

Expand Down Expand Up @@ -1016,6 +1024,30 @@ async def async_get_wheel_of_fortune_spins(self, account_id: str) -> WheelOfFort
_LOGGER.error("Failed to retrieve wheel of fortune spins")

return None

async def async_spin_wheel_of_fortune(self, account_id: str, is_electricity: bool) -> int:
"""Get the user's wheel of fortune spins"""
await self.async_refresh_token()

async with aiohttp.ClientSession(timeout=self.timeout) as client:
url = f'{self._base_url}/v1/graphql/'
payload = { "query": wheel_of_fortune_mutation.format(account_id=account_id, supply_type="ELECTRICITY" if is_electricity == True else "GAS") }
headers = { "Authorization": f"JWT {self._graphql_token}" }
async with client.post(url, json=payload, headers=headers) as response:
response_body = await self.__async_read_response__(response, url)
_LOGGER.debug(f'async_spin_wheel_of_fortune: {response_body}')

if (response_body is not None and
"data" in response_body and
"spinWheelOfFortune" in response_body["data"] and
"spinResult" in response_body["data"]["spinWheelOfFortune"] and
"prizeAmount" in response_body["data"]["spinWheelOfFortune"]["spinResult"]):

return int(response_body["data"]["spinWheelOfFortune"]["spinResult"]["prizeAmount"])
else:
_LOGGER.error("Failed to spin wheel of fortune")

return None

def __get_interval_end(self, item):
return item["interval_end"]
Expand Down
23 changes: 18 additions & 5 deletions custom_components/octopus_energy/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import logging

from homeassistant.util.dt import (utcnow)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv, entity_platform, issue_registry as ir
from homeassistant.core import HomeAssistant, SupportsResponse
from homeassistant.helpers import entity_platform, issue_registry as ir

from .electricity.current_consumption import OctopusEnergyCurrentElectricityConsumption
from .electricity.current_accumulative_consumption import OctopusEnergyCurrentAccumulativeElectricityConsumption
Expand Down Expand Up @@ -56,6 +56,7 @@
CONFIG_MAIN_LIVE_GAS_CONSUMPTION_REFRESH_IN_MINUTES,
CONFIG_MAIN_PREVIOUS_ELECTRICITY_CONSUMPTION_DAYS_OFFSET,
CONFIG_MAIN_PREVIOUS_GAS_CONSUMPTION_DAYS_OFFSET,
DATA_ACCOUNT_ID,
DOMAIN,

CONFIG_MAIN_API_KEY,
Expand Down Expand Up @@ -92,6 +93,18 @@ async def async_setup_entry(hass, entry, async_add_entities):
"async_refresh_previous_consumption_data",
)

platform.async_register_entity_service(
"spin_wheel_of_fortune",
vol.All(
vol.Schema(
{},
extra=vol.ALLOW_EXTRA,
),
),
"async_spin_wheel",
# supports_response=SupportsResponse.OPTIONAL
)

async def async_setup_default_sensors(hass: HomeAssistant, entry, async_add_entities):
config = dict(entry.data)

Expand All @@ -104,14 +117,14 @@ async def async_setup_default_sensors(hass: HomeAssistant, entry, async_add_enti
await saving_session_coordinator.async_config_entry_first_refresh()

account_info = hass.data[DOMAIN][DATA_ACCOUNT]
account_id = account_info["id"]
account_id = hass.data[DOMAIN][DATA_ACCOUNT_ID]

wheel_of_fortune_coordinator = await async_setup_wheel_of_fortune_spins_coordinator(hass, account_id)

entities = [
OctopusEnergyOctoplusPoints(hass, client, account_id),
OctopusEnergyWheelOfFortuneElectricitySpins(hass, wheel_of_fortune_coordinator, account_id),
OctopusEnergyWheelOfFortuneGasSpins(hass, wheel_of_fortune_coordinator, account_id)
OctopusEnergyWheelOfFortuneElectricitySpins(hass, wheel_of_fortune_coordinator, client, account_id),
OctopusEnergyWheelOfFortuneGasSpins(hass, wheel_of_fortune_coordinator, client, account_id)
]

now = utcnow()
Expand Down
9 changes: 8 additions & 1 deletion custom_components/octopus_energy/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,11 @@ join_octoplus_saving_session_event:
name: Event code
description: The code of the event that is to be joined.
selector:
text:
text:
spin_wheel_of_fortune:
name: Spin wheel of fortune
description: Spins the wheel of fortune for a given energy type
target:
entity:
integration: octopus_energy
domain: sensor
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging

from homeassistant.core import HomeAssistant
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity import generate_entity_id
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
Expand All @@ -11,17 +11,19 @@
)
from ..utils import account_id_to_unique_key
from ..coordinators.wheel_of_fortune import WheelOfFortuneSpinsCoordinatorResult
from ..api_client import OctopusEnergyApiClient

_LOGGER = logging.getLogger(__name__)

class OctopusEnergyWheelOfFortuneElectricitySpins(CoordinatorEntity, RestoreSensor):
"""Sensor for current wheel of fortune spins for electricity"""

def __init__(self, hass: HomeAssistant, coordinator, account_id: str):
def __init__(self, hass: HomeAssistant, coordinator, client: OctopusEnergyApiClient, account_id: str):
"""Init sensor."""
CoordinatorEntity.__init__(self, coordinator)

self._account_id = account_id
self._client = client
self._state = None
self._attributes = {
"last_evaluated": None
Expand Down Expand Up @@ -76,4 +78,13 @@ async def async_added_to_hass(self):
for x in state.attributes.keys():
self._attributes[x] = state.attributes[x]

_LOGGER.debug(f'Restored OctopusEnergyWheelOfFortuneElectricitySpins state: {self._state}')
_LOGGER.debug(f'Restored OctopusEnergyWheelOfFortuneElectricitySpins state: {self._state}')

@callback
async def async_spin_wheel(self):
"""Spin the wheel of fortune"""

result = await self._client.async_spin_wheel_of_fortune(self._account_id, True)
return {
"amount_won_in_pence": result
}
17 changes: 14 additions & 3 deletions custom_components/octopus_energy/wheel_of_fortune/gas_spins.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging

from homeassistant.core import HomeAssistant
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity import generate_entity_id
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
Expand All @@ -11,17 +11,19 @@
)
from ..utils import account_id_to_unique_key
from ..coordinators.wheel_of_fortune import WheelOfFortuneSpinsCoordinatorResult
from ..api_client import OctopusEnergyApiClient

_LOGGER = logging.getLogger(__name__)

class OctopusEnergyWheelOfFortuneGasSpins(CoordinatorEntity, RestoreSensor):
"""Sensor for current wheel of fortune spins for gas"""

def __init__(self, hass: HomeAssistant, coordinator, account_id: str):
def __init__(self, hass: HomeAssistant, coordinator, client: OctopusEnergyApiClient, account_id: str):
"""Init sensor."""
CoordinatorEntity.__init__(self, coordinator)

self._account_id = account_id
self._client = client
self._state = None
self._attributes = {
"last_evaluated": None
Expand Down Expand Up @@ -76,4 +78,13 @@ async def async_added_to_hass(self):
for x in state.attributes.keys():
self._attributes[x] = state.attributes[x]

_LOGGER.debug(f'Restored OctopusEnergyWheelOfFortuneGasSpins state: {self._state}')
_LOGGER.debug(f'Restored OctopusEnergyWheelOfFortuneGasSpins state: {self._state}')

@callback
async def async_spin_wheel(self):
"""Spin the wheel of fortune"""

result = await self._client.async_spin_wheel_of_fortune(self._account_id, False)
return {
"amount_won_in_pence": result
}

0 comments on commit effcc21

Please sign in to comment.