1 """Coordinator to fetch data from the Picnic API."""
4 from contextlib
import suppress
6 from datetime
import timedelta
9 from python_picnic_api
import PicnicAPI
10 from python_picnic_api.session
import PicnicAuthError
18 from .const
import ADDRESS, CART_DATA, LAST_ORDER_DATA, NEXT_DELIVERY_DATA, SLOT_DATA
22 """The coordinator to fetch data from the Picnic API at a set interval."""
27 picnic_api_client: PicnicAPI,
28 config_entry: ConfigEntry,
30 """Initialize the coordinator with the given Picnic API client."""
35 logger = logging.getLogger(__name__)
39 name=
"Picnic coordinator",
44 """Fetch data from API endpoint."""
48 async
with asyncio.timeout(10):
49 data = await self.
hasshass.async_add_executor_job(self.
fetch_datafetch_data)
53 except ValueError
as error:
54 raise UpdateFailed(f
"API response was malformed: {error}")
from error
55 except PicnicAuthError
as error:
56 raise ConfigEntryAuthFailed
from error
62 """Fetch the data from the Picnic API and return a flat dict with only needed sensor data."""
65 raise UpdateFailed(
"API response doesn't contain expected data.")
74 NEXT_DELIVERY_DATA: next_delivery,
75 LAST_ORDER_DATA: last_order,
79 """Get the address that identifies the Picnic service."""
82 self.
_user_address_user_address = f
'{address["street"]} {address["house_number"]}{address["house_number_ext"]}'
88 """Get the selected slot, if it's explicitly selected."""
89 selected_slot = cart.get(
"selected_slot", {})
90 available_slots = cart.get(
"delivery_slots", [])
92 if selected_slot.get(
"state") ==
"EXPLICIT":
94 lambda slot: slot.get(
"slot_id") == selected_slot.get(
"slot_id"),
98 return next(slot_data)
103 """Get data of the last order from the list of deliveries."""
105 deliveries = self.
picnic_api_clientpicnic_api_client.get_deliveries(summary=
True)
111 next_deliveries =
list(
112 filter(
lambda d: d[
"status"] ==
"CURRENT", deliveries)
115 copy.deepcopy(next_deliveries[-1])
if next_deliveries
else {}
117 last_order = copy.deepcopy(deliveries[0])
if deliveries
else {}
118 except (KeyError, TypeError):
123 delivery_position = {}
124 if next_delivery
and not next_delivery.get(
"delivery_time"):
126 with suppress(ValueError):
127 delivery_position = self.
picnic_api_clientpicnic_api_client.get_delivery_position(
128 next_delivery[
"delivery_id"]
133 next_delivery[
"eta"] = delivery_position.get(
134 "eta_window", next_delivery.get(
"eta2", {})
136 if "eta2" in next_delivery:
137 del next_delivery[
"eta2"]
141 for order
in last_order.get(
"orders", []):
142 total_price += order.get(
"total_price", 0)
143 last_order[
"total_price"] = total_price
146 last_order.setdefault(
"delivery_time", {})
148 return next_delivery, last_order
152 """Set the updated authentication token."""
tuple[dict, dict] _get_order_data(self)
def _update_auth_token(self)
dict _async_update_data(self)
dict _get_slot_data(dict cart)
None __init__(self, HomeAssistant hass, PicnicAPI picnic_api_client, ConfigEntry config_entry)