* Fix Google Calendar caching when offline Events from Google Calendar were not firing under the following circumstances: 1. Start ha as normal with Google Calendar configured as per instructions. 2. ha loses network connectivity to Google 3. ha attempts update of Google Calendar 4. calendar/google component throws uncaught Exception causing update method to not return 5. (cached) Google Calendar event does not fire, remains "Off" Catching the Exception and returning False from the update() method causes the correct behavior (i.e., the calendar component firing the event as scheduled using cached data). * Add requirements * Revert code cleanup * Remove explicit return value from update() * Revert "Remove explicit return value from update()" This reverts commit 7cd77708af658ccea855de47a32ce4ac5262ac30. * Use MockDependency decorator No need to whitelist google-python-api-client for a single unit test at this point.
85 lines
2.8 KiB
Python
85 lines
2.8 KiB
Python
"""
|
|
Support for Google Calendar Search binary sensors.
|
|
|
|
For more details about this platform, please refer to the documentation at
|
|
https://home-assistant.io/components/binary_sensor.google_calendar/
|
|
"""
|
|
# pylint: disable=import-error
|
|
import logging
|
|
from datetime import timedelta
|
|
|
|
from homeassistant.components.calendar import CalendarEventDevice
|
|
from homeassistant.components.google import (
|
|
CONF_CAL_ID, CONF_ENTITIES, CONF_TRACK, TOKEN_FILE,
|
|
GoogleCalendarService)
|
|
from homeassistant.util import Throttle, dt
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
DEFAULT_GOOGLE_SEARCH_PARAMS = {
|
|
'orderBy': 'startTime',
|
|
'maxResults': 1,
|
|
'singleEvents': True,
|
|
}
|
|
|
|
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15)
|
|
|
|
|
|
def setup_platform(hass, config, add_devices, disc_info=None):
|
|
"""Set up the calendar platform for event devices."""
|
|
if disc_info is None:
|
|
return
|
|
|
|
if not any(data[CONF_TRACK] for data in disc_info[CONF_ENTITIES]):
|
|
return
|
|
|
|
calendar_service = GoogleCalendarService(hass.config.path(TOKEN_FILE))
|
|
add_devices([GoogleCalendarEventDevice(hass, calendar_service,
|
|
disc_info[CONF_CAL_ID], data)
|
|
for data in disc_info[CONF_ENTITIES] if data[CONF_TRACK]])
|
|
|
|
|
|
class GoogleCalendarEventDevice(CalendarEventDevice):
|
|
"""A calendar event device."""
|
|
|
|
def __init__(self, hass, calendar_service, calendar, data):
|
|
"""Create the Calendar event device."""
|
|
self.data = GoogleCalendarData(calendar_service, calendar,
|
|
data.get('search', None))
|
|
super().__init__(hass, data)
|
|
|
|
|
|
class GoogleCalendarData(object):
|
|
"""Class to utilize calendar service object to get next event."""
|
|
|
|
def __init__(self, calendar_service, calendar_id, search=None):
|
|
"""Set up how we are going to search the google calendar."""
|
|
self.calendar_service = calendar_service
|
|
self.calendar_id = calendar_id
|
|
self.search = search
|
|
self.event = None
|
|
|
|
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
|
def update(self):
|
|
"""Get the latest data."""
|
|
from httplib2 import ServerNotFoundError
|
|
|
|
try:
|
|
service = self.calendar_service.get()
|
|
except ServerNotFoundError:
|
|
_LOGGER.warning("Unable to connect to Google, using cached data")
|
|
return False
|
|
|
|
params = dict(DEFAULT_GOOGLE_SEARCH_PARAMS)
|
|
params['timeMin'] = dt.now().isoformat('T')
|
|
params['calendarId'] = self.calendar_id
|
|
if self.search:
|
|
params['q'] = self.search
|
|
|
|
events = service.events() # pylint: disable=no-member
|
|
result = events.list(**params).execute()
|
|
|
|
items = result.get('items', [])
|
|
self.event = items[0] if len(items) == 1 else None
|
|
return True
|