Ejemplo n.º 1
0
 def retrieve(self, cycle):
     try:
         if self.tado_connection.init_home():
             data = self.tado_connection.query_home("zones/%d/state" %
                                                    self.zone)
             self.data = data
             if data is not None:
                 if "sensorDataPoints" in data:
                     self.temperature = data["sensorDataPoints"][
                         "insideTemperature"]["celsius"]
                     self.humidity = data["sensorDataPoints"]["humidity"][
                         "percentage"]
                 else:
                     self.temperature = None
                     self.humidity = None
                 if "setting" in data:
                     self.temp_setting = None if data["setting"][
                         "power"] == "OFF" else data["setting"][
                             "temperature"]["celsius"]
                 else:
                     self.temp_setting = None
                 if "openWindow" in data:
                     self.window_open = data["openWindow"] is not None
                     if self.window_open:
                         self.window_last_open = datetime.datetime.now()
                 else:
                     self.window_open = False
     except Exception as e:
         logger.warning("Cannot retrieve RoomWidget: " + (
             e.message if hasattr(e, 'message') else type(e).__name__))
Ejemplo n.º 2
0
 def retrieve(self, office_widget, cycle):
     scope = ['https://www.googleapis.com/auth/calendar.readonly']
     credentials = ServiceAccountCredentials.from_json_keyfile_name(
         self.auth_file, scope)
     now = datetime.datetime.utcnow().isoformat() + 'Z'
     next_week = (datetime.datetime.utcnow() +
                  datetime.timedelta(hours=24 * 7)).replace(
                      tzinfo=tz.tzlocal())
     try:
         service = build('calendar', 'v3', credentials=credentials)
         data = service.events().list(calendarId=self.calender_id,
                                      timeMin=now,
                                      maxResults=20,
                                      singleEvents=True,
                                      orderBy='startTime').execute()
         day = datetime.datetime.now()
         office_widget.ordered_times = []
         office_widget.flags = {}
         office_widget.is_error = False
         office_widget.published = None
         for item in data.get('items', []):
             item_datetime = dateutil.parser.parse(item['start'].get(
                 'dateTime',
                 item['start'].get('date'))).replace(tzinfo=tz.tzlocal())
             if item_datetime.date() >= day.date(
             ) and item_datetime <= next_week:
                 office_widget.ordered_times.append(item_datetime)
                 office_widget.flags[item_datetime] = False
                 day = item_datetime + datetime.timedelta(hours=24)
     except Exception as e:
         logger.warning("Cannot retrieve GcalOfficeStrategy: " + (
             e.message if hasattr(e, 'message') else type(e).__name__))
Ejemplo n.º 3
0
 def query(self, url):
     try:
         headers = {"Authorization": "Bearer %s" % self.get_access_token()}
         response = requests.get(url=url, headers=headers)
         return json.loads(response.text)
     except Exception as e:
         logger.warning("Cannot query Tado: " + (
             e.message if hasattr(e, 'message') else type(e).__name__))
         return None
Ejemplo n.º 4
0
 def update(self, display, cycle):
     try:
         scope = ['https://www.googleapis.com/auth/drive']
         credentials = ServiceAccountCredentials.from_json_keyfile_name(
             self.auth_file, scope)
         service = build('drive', 'v3', credentials=credentials)
         media_body = MediaFileUpload(self.file_locally, resumable=True)
         updated_file = service.files().update(
             fileId=self.file_id, media_body=media_body).execute()
     except Exception as e:
         logger.warning("Cannot update image on GdriveScreen: " + (
             e.message if hasattr(e, 'message') else type(e).__name__))
Ejemplo n.º 5
0
 def retrieve(self, commute_widget):
     start_time = datetime.datetime.now()
     known_departure = None if len(commute_widget.routes) == 0 \
         else commute_widget.routes[0]["bus"] if commute_widget.routes[0]["bus"] is not None else commute_widget.routes[0]["train"]
     if known_departure is not None and known_departure > start_time:
         return
     try:
         commute_widget.data = []
         commute_widget.routes = []
         routes_found = 0
         trials = 0
         too_late = False
         fallback_route = None
         while routes_found < commute_widget.num_routes and trials < 10 and not too_late:
             trials += 1
             data = self.gmaps.directions(self.from_loc,
                                          self.to_loc,
                                          mode="transit",
                                          departure_time=start_time)
             routes = [
                 GoogleCommuteStrategy._parse_route(route["legs"])
                 for route in data
             ]
             commute_widget.data.append(data)
             for route in routes:
                 if route is not None and route["train"] is not None:
                     if routes_found == commute_widget.num_routes - 1:
                         if sum([
                                 1 for route in commute_widget.routes +
                             [route] if route["bus"] is not None
                         ]) > 0:
                             append_route = True
                         else:
                             fallback_route = route
                             append_route = False
                     else:
                         append_route = True
                     if append_route:
                         routes_found += 1
                         commute_widget.routes.append(route)
                     new_start_time = route["bus"] if route[
                         "bus"] is not None else route["train"]
                     if new_start_time != start_time:
                         start_time = new_start_time
                     else:
                         too_late = True
         if routes_found < commute_widget.num_routes and fallback_route is not None:
             self.routes.append(fallback_route)
     except Exception as e:
         logger.warning("Cannot retrieve GoogleStrategy: " + (
             e.message if hasattr(e, 'message') else type(e).__name__))
Ejemplo n.º 6
0
 def retrieve(self, cycle):
     try:
         self.washing_state = self.washing_machine.get_state()
     except Exception as e:
         logger.warning("Cannot retrieve LaundryWidget.washing_state: " + (
             e.message if hasattr(e, 'message') else type(e).__name__))
         try:
             self.washing_machine.reconnect()
             self.washing_state = self.washing_machine.get_state()
         except Exception as ee:
             logger.warning(
                 "After resetting connection, still cannot retrieve LaundryWidget.washing_state: "
                 + (ee.message if hasattr(ee, 'message') else type(ee).
                    __name__))
     try:
         self.drying_state = self.drying_machine.get_state()
     except Exception as e:
         logger.warning("Cannot retrieve LaundryWidget.drying_state: " + (
             e.message if hasattr(e, 'message') else type(e).__name__))
         try:
             self.drying_machine.reconnect()
             self.drying_state = self.drying_machine.get_state()
         except Exception as ee:
             logger.warning(
                 "After resetting connection, still cannot retrieve LaundryWidget.drying_state: "
                 + (ee.message if hasattr(ee, 'message') else type(ee).
                    __name__))
Ejemplo n.º 7
0
 def retrieve(self, office_widget, cycle):
     scope = [
         'https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive'
     ]
     try:
         credentials = ServiceAccountCredentials.from_json_keyfile_name(
             self.auth_file, scope)
         gsheets = gspread.authorize(credentials)
         workbook = gsheets.open(self.sheet_name).get_worksheet(0)
         value = workbook.acell(self.data_cell).value
         if value is None or value == "":
             self.data = None
         else:
             self.data = json.loads(value)
         if self.data is None or "Error" in self.data:
             office_widget.is_error = (self.data is not None
                                       and "Error" in self.data)
             office_widget.published = None
             office_widget.ordered_times = None
             office_widget.flags = None
         else:
             office_widget.is_error = False
             office_widget.published = datetime.datetime.strptime(
                 self.data["published"],
                 "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz.tzutc())
             office_widget.ordered_times = []
             office_widget.flags = {}
             for ymd in self.data["day_starts"]:
                 hms = self.data["day_starts"][ymd][0]
                 utc = datetime.datetime.strptime("%s %s" % (ymd, hms),
                                                  "%Y-%m-%d %H:%M:%S")
                 utc = utc.replace(tzinfo=tz.tzutc())
                 event = utc.astimezone(tz.tzlocal())
                 recently = datetime.datetime.now(
                     tz.tzlocal()) - datetime.timedelta(
                         hours=self.lookbehind_hours)
                 latest = datetime.datetime.now(
                     tz.tzlocal()) + datetime.timedelta(
                         days=self.lookahead_days)
                 if event > recently and event < latest:
                     office_widget.ordered_times.append(event)
                     office_widget.flags[event] = self.data["day_starts"][
                         ymd][1]
             office_widget.ordered_times.sort()
     except Exception as e:
         logger.warning("Cannot retrieve GsheetsOfficeWidget: " + (
             e.message if hasattr(e, 'message') else type(e).__name__))
Ejemplo n.º 8
0
 def _parse_route(self, route):
     arrival = None
     arrival_delay = None
     result = {
         "bus": None,
         "train": None,
         "city": None,
         "bus_station": None,
         "train_station": None
     }
     for leg in route["legs"]:
         is_bus = "line" in leg and leg["line"]["mode"] == "bus"
         is_train = "line" in leg and leg["line"]["mode"] == "train"
         departure = dateutil.parser.parse(leg["departure"])
         if is_bus and result["bus"] is None:
             result["bus"] = departure
             result["bus_station"] = self.bus_stations.get(
                 leg["origin"]["name"], "*")
             if result["bus_station"] == "*":
                 logger.warning("Unknown bus station found: %s" %
                                leg["origin"]["name"])
             result["bus_delay"] = int(
                 leg["departureDelay"]
             ) / 60 if "departureDelay" in leg else 0
         elif is_train and result["train"] is None:
             result["train"] = departure
             result["train_station"] = self.train_stations.get(
                 leg["origin"]["name"], "*")
             if result["train_station"] == "*":
                 logger.warning("Unknown train station found: %s" %
                                leg["origin"]["name"])
             result["train_delay"] = int(
                 leg["departureDelay"]
             ) / 60 if "departureDelay" in leg else 0
         arrival = dateutil.parser.parse(leg["arrival"])
         arrival_delay = int(
             leg["arrivalDelay"]) / 60 if "arrivalDelay" in leg else 0
     if result["train"] is not None:
         result["city"] = arrival
         result["city_delay"] = arrival_delay
     return result
Ejemplo n.º 9
0
 def retrieve(self, commute_widget):
     try:
         start = datetime.datetime.now()
         vals = [
             self.from_address, self.from_latitude, self.from_longitude,
             self.to_address, self.to_latitude, self.to_longitude,
             str(int(start.timestamp())),
             str(commute_widget.num_routes)
         ]
         args = [urllib.parse.quote(val.encode('utf-8')) for val in vals]
         suffix = "?from_address={}&from_latitude={}&from_longitude={}&to_address={}&to_latitude={}&to_longitude={}&departure={}&num_routes={}"
         hafas_url = self.hafas_glue_service + suffix.format(*args)
         with urllib.request.urlopen(hafas_url) as hafas_call:
             commute_widget.data = json.loads(hafas_call.read().decode())
             routes = [
                 self._parse_route(route) for route in commute_widget.data
             ]
             commute_widget.routes = [
                 route for route in routes if route["city"] is not None
             ]
     except Exception as e:
         logger.warning("Cannot retrieve HafasCommuteStrategy: " + (
             e.message if hasattr(e, 'message') else type(e).__name__))
Ejemplo n.º 10
0
 def retrieve(self, cycle):
     try:
         self.weather = requests.get(
             "http://api.openweathermap.org/data/2.5/weather",
             params={
                 "appid": self.api_key,
                 "zip": self.zip_location
             }).json()
         self.forecast = requests.get(
             "http://api.openweathermap.org/data/2.5/forecast",
             params={
                 "appid": self.api_key,
                 "zip": self.zip_location
             }).json()
         self.weather_icon = QP_WEATHER_ICONS_MAP[self.weather["weather"][0]
                                                  ["icon"]]
         self.forecast_icon = QP_WEATHER_ICONS_MAP[self.forecast["list"][0]
                                                   ["weather"][0]["icon"]]
         self.weather_bad = self.weather_icon in QP_WEATHER_ICONS_BAD
         self.forecast_bad = self.forecast_icon in QP_WEATHER_ICONS_BAD
         self.temp = "%d°C" % (int(self.weather["main"]["temp"]) - 273)
     except Exception as e:
         logger.warning("Cannot retrieve WeatherWidget: " + (
             e.message if hasattr(e, 'message') else type(e).__name__))
Ejemplo n.º 11
0
 def retrieve(self, cycle):
     try:
         self.data = requests.get('http://www.stuttgart.de/feinstaubalarm/widget/xtrasmall').text
         self.is_smog = BeautifulSoup(self.data, 'html.parser').find('div', {'class': 'alarm-on'})
     except Exception as e: 
         logger.warning("Cannot retrieve SmogWidget: " + (e.message if hasattr(e, 'message') else type(e).__name__))