def configure_endomondo(conf): endomondoapi = MobileApi() email = '' password = '' while not email: email = raw_input('Please enter your endomondo email: ') while not password: password = getpass.getpass() if not password: print 'Password can\'t be empty' auth_token = '' try: auth_token = endomondoapi.request_auth_token(email=email, password=password) except: pass if not auth_token: print 'Did not receive valid authentication token. Try one more time.' else: conf['endomondo'] = True conf['email'] = email keyring.set_password("endomondo", email, auth_token) print 'Configured!'
def setup(hass, config): """Setup component.""" yr_precipitation = {} nowcast_precipitation = None news_rss = [] workout_text = None last_workout_time = None auth_token = config[DOMAIN].get("token") endomondo = MobileApi(auth_token=auth_token) def _get_text(message_type=None): news = "" now = dt_util.now() if message_type == 2: news = news + "Sov godt " elif now.hour < 4: news = news + "God natt " elif now.hour < 10: news = news + "God morgen " elif now.hour < 18: news = news + "Hei " else: news = news + "God kveld " persons = [] state = hass.states.get('group.tracker') if state: tracker = state.attributes.get('entity_id') for person in tracker: person = hass.states.get(person) if not person: continue if not person.state == 'home': continue persons.append(person.attributes.get('friendly_name')) if len(persons) > 1: persons.insert(-1, "og") news = news + ' '.join(persons) + '. ' if message_type == 0: news = news + "Velkommen hjem. " nonlocal workout_text if workout_text and 'daniel' in news.lower(): news = news + workout_text workout_text = None if yr_precipitation: res = 0 for time, value in yr_precipitation.items(): # print(time, value) if time < now and time > now - timedelta(hours=3): res += value precipitation = num2str(res) news = news + "De siste 3 timene har det kommet " + precipitation + " mm nedbør " temp = hass.states.get('sensor.ute_veranda_temperature') if temp and temp.state != "unknown": news = news + "og temperaturen er nå " + num2str( temp.state) + " grader ute. " if nowcast_precipitation and nowcast_precipitation > 0: news = news + "Den neste timen er det ventet " + num2str( nowcast_precipitation) + " mm nedbør. " if message_type == 2: alarm_state = hass.states.get('automation.wake_me_up') if alarm_state and alarm_state.state == "on": time_to_alarm = float( hass.states.get('sensor.relative_alarm_time').state) alarm_time_hour = int(time_to_alarm / 60) alarm_time_min = int(time_to_alarm - alarm_time_hour * 60) news = news + "Vekkerklokken ringer om " + str( alarm_time_hour) + " timer og " + str( alarm_time_min) + " minutter." if message_type in [0, 1, 2]: return news news = news + "Her kommer siste nytt: " if False: _news_rss = news_rss else: _news_rss = news_rss[:2] for case in _news_rss: news = news + case + " " return news @asyncio.coroutine def _read_news(service): message_type = int(service.data.get("message_type", -1)) news = _get_text(message_type) data = {} if service and service.data.get(ATTR_ENTITY_ID): data[ATTR_ENTITY_ID] = service.data.get(ATTR_ENTITY_ID) data['message'] = news data['cache'] = False autoradio = True if service.data.get("entity_id_radio") else False yield from hass.services.async_call('tts', 'google_say', data, blocking=autoradio) return if not autoradio: return # if vekking: data = {} data[ATTR_ENTITY_ID] = service.data.get("entity_id_radio") if service.data.get("radio_option"): data['option'] = service.data.get("radio_option") else: data['option'] = "P3" hass.services.call('input_select', 'select_option', data) def _rss_news(time=None): nonlocal news_rss resource = "https://www.nrk.no/nyheter/" method = 'GET' payload = auth = headers = None rest = RestData(method, resource, auth, headers, payload, verify_ssl=True) rest.update() news_rss = [] if rest.data is None: return raw_data = BeautifulSoup(rest.data, 'html.parser') prew_text = "" for raw_text in raw_data.select("p"): text = strip_tags(str(raw_text)) if text == prew_text: continue prew_text = text news_rss.append(text) if len(news_rss) > 2: break _feed = feedparser.parse( "http://www.yr.no/sted/Norge/S%C3%B8r-Tr%C3%B8ndelag/Trondheim/Trondheim/varsel.xml" ) summary = _feed.feed.get("summary") if summary is None: return news_rss.append("Værvarsel " + strip_tags(summary).replace( "<strong>", "").replace("</strong>", "")) @asyncio.coroutine def _yr_precipitation(*_): url = "http://api.met.no/weatherapi/nowcast/0.9/" urlparams = { 'lat': str(hass.config.latitude), 'lon': str(hass.config.longitude) } #print(url, urlparams) now = dt_util.utcnow() try: websession = async_get_clientsession(hass) with async_timeout.timeout(10, loop=hass.loop): resp = yield from websession.get(url, params=urlparams) if resp.status != 200: async_track_point_in_utc_time(hass, _yr_precipitation, now + timedelta(minutes=2)) return text = yield from resp.text() except (asyncio.TimeoutError, aiohttp.ClientError) as err: async_track_point_in_utc_time(hass, _yr_precipitation, now + timedelta(minutes=2)) return nonlocal nowcast_precipitation nonlocal yr_precipitation nowcast_precipitation = 0 try: data = xmltodict.parse(text)['weatherdata'] model = data['meta']['model'] if '@nextrun' not in model: model = model[0] nextrun = dt_util.parse_datetime(model['@nextrun']) #print(nextrun, model['@nextrun']) nextrun = nextrun if ( nextrun > now) else now + timedelta(minutes=2) for time_entry in data['product']['time']: loc_data = time_entry['location'] time = dt_util.parse_datetime(time_entry['@to']) #print(loc_data['precipitation']['@value']) #print(dt_util.as_local(time)) value = float(loc_data['precipitation']['@value']) if time > now and time < now + timedelta(hours=1): nowcast_precipitation += value yr_precipitation[time] = value for time in yr_precipitation.copy().keys(): if time < now - timedelta(hours=3): del yr_precipitation[time] except (ExpatError, IndexError) as err: async_track_point_in_utc_time(hass, _yr_precipitation, now + timedelta(minutes=2)) return #print(data['product']['time'], nextrun) # print(nowcast_precipitation) #print(yr_precipitation) async_track_point_in_utc_time(hass, _yr_precipitation, nextrun + timedelta(seconds=2)) def _workout_text(now=None): nonlocal workout_text nonlocal last_workout_time last_workout = endomondo.get_workouts()[0] if not now: now = dt_util.utcnow() now = dt_util.as_local(now) if (now - dt_util.as_local( last_workout.start_time)).total_seconds() > 3600 * 24: workout_text = None return last_workout_time = last_workout.start_time workout_text = "Bra jobbet Daniel! I dag har du trent i " + str( int(last_workout.duration / 3600)) + " timer og " + str( int((last_workout.duration - int(last_workout.duration / 3600) * 3600) / 60)) + " minutter. Distanse " + num2str( last_workout.distance ) + " kilometer. Du har forbrent " + num2str( last_workout.burgers_burned) + " burgere. \n" if last_workout.live: track_point_in_utc_time(hass, _workout_text, now + timedelta(seconds=30)) _rss_news() _workout_text() hass.bus.listen_once(EVENT_HOMEASSISTANT_START, _yr_precipitation) # track_time_change(hass, _yr_precipitation, minute=[31], second=0) track_time_change(hass, _rss_news, minute=[10, 26, 41, 56], second=0) track_time_change(hass, _workout_text, minute=[11, 26, 41, 56], second=0) hass.services.register(DOMAIN, "read_news", _read_news) #print(_get_text()) workout_text = None return True
parser.set_defaults(configure=False) args = parser.parse_args() conf = shelve.open('./.conf') if not conf.has_key('endomondo'): conf['endomondo'] = False if args.configure: print 'Configure' configure_endomondo(conf); conf.close() sys.exit() files = timex.read('/dev/timex') activities = map(file_to_activity, files) map(create_tcx_file, activities) if not conf['endomondo']: conf.close() sys.exit() # Endomondo upload endomondoapi = MobileApi() auth_token = keyring.get_password('endomondo', conf['email']) endomondoapi.set_auth_token(auth_token) workouts = map(partial(upload_file, endomondoapi), files) conf.close()
def setup(hass, config): """Setup example component.""" yr_precipitation = [] nowcast_precipitation = [] news_rss = [] workout_text = None last_workout_time = None auth_token = config[DOMAIN].get("token") endomondo = MobileApi(auth_token=auth_token) def _get_text(message_type=None): news = "" now = dt_util.now() if now.hour < 10: news = news + "God morgen " elif now.hour < 18: news = news + "Hei " else: news = news + "God kveld " persons = [] state = hass.states.get('group.tracker') if state: tracker = state.attributes.get('entity_id') for person in tracker: person = hass.states.get(person) if not person: continue if not person.state == 'home': continue persons.append(person.attributes.get('friendly_name')) if len(persons) > 1: persons.insert(-1, "og") news = news + ' '.join(persons) + '. ' if message_type == "0": news = news + "Velkommen hjem. " nonlocal workout_text if workout_text and 'daniel' in news.lower(): news = news + workout_text workout_text = None if message_type == "0": return news if yr_precipitation: precipitation = str(sum(yr_precipitation)).replace(".", " komma ") news = news + "De siste 3 timene har det kommet " + precipitation + " mm nedbør " temp = hass.states.get('sensor.ute_veranda_temperature') if temp and temp.state != "unknown": news = news + "og temperaturen er nå " + str( round(float(temp.state), 1)).replace( ".", " komma ") + " grader ute. " if nowcast_precipitation: precipitation = str(round(sum(nowcast_precipitation), 1)).replace(".", " komma ") news = news + "Den neste timen er det ventet " + precipitation + " mm nedbør. " news = news + "Her kommer siste nytt: " for case in news_rss: news = news + case + " " return news def _read_news(service=None): message_type = None if service: message_type = service.data.get("message_type") news = _get_text(message_type) data = {} if service and service.data.get(ATTR_ENTITY_ID): data[ATTR_ENTITY_ID] = service.data.get(ATTR_ENTITY_ID) data['message'] = news print(data) hass.services.call('tts', 'google_say', data) def _rss_news(time=None): nonlocal news_rss resource = "https://www.nrk.no/nyheter/" method = 'GET' payload = auth = headers = None rest = RestData(method, resource, auth, headers, payload, verify_ssl=True) rest.update() news_rss = [] if rest.data is None: return raw_data = BeautifulSoup(rest.data, 'html.parser') prew_text = "" for raw_text in raw_data.select("p"): text = strip_tags(str(raw_text)) if text == prew_text: continue prew_text = text news_rss.append(text) if len(news_rss) > 2: break _feed = feedparser.parse( "http://www.yr.no/sted/Norge/S%C3%B8r-Tr%C3%B8ndelag/Trondheim/Trondheim/varsel.xml" ) news_rss.append("Værvarsel " + strip_tags(_feed.feed.summary).replace( "<strong>", "").replace("</strong>", "")) def _yr_precipitation(now=None): state = hass.states.get('sensor.yr_precipitation').state nonlocal yr_precipitation yr_precipitation.append(float(state)) if len(yr_precipitation) > 3: yr_precipitation.pop(0) def _yr_precipitation2(now=None): url = "http://api.met.no/weatherapi/nowcast/0.9/" urlparams = { 'lat': str(hass.config.latitude), 'lon': str(hass.config.longitude) } try: with requests.Session() as sess: response = sess.get(url, params=urlparams) except requests.RequestException: return if response.status_code != 200: return text = response.text nonlocal nowcast_precipitation try: data = xmltodict.parse(text)['weatherdata'] model = data['meta']['model'] if '@nextrun' not in model: model = model[0] nextrun = dt_util.parse_datetime(model['@nextrun']) precipitation = [] for time_entry in data['product']['time']: loc_data = time_entry['location'] nowcast_precipitation.append( float(loc_data['precipitation']['@value'])) if len(precipitation) > 7: break except (ExpatError, IndexError) as err: track_point_in_utc_time(hass, _workout_text, now + timedelta(minutes=2)) return print(nowcast_precipitation) track_point_in_utc_time(hass, _workout_text, nextrun + timedelta(seconds=2)) def _workout_text(now=None): nonlocal workout_text nonlocal last_workout_time last_workout = endomondo.get_workouts()[0] print(last_workout) if not now: now = dt_util.utcnow() now = dt_util.as_local(now) if last_workout_time == last_workout.start_time or ( now - dt_util.as_local( last_workout.start_time)).total_seconds() > 3600 * 24: return last_workout_time = last_workout.start_time workout_text = "Bra jobbet Daniel! I dag har du trent i " + str( int(last_workout.duration / 3600)) + " timer og " + str( int((last_workout.duration - int(last_workout.duration / 3600) * 3600) / 60)) + " minutter. Distanse " + str( round(last_workout.distance, 1)) + " kilometer. Du har forbrent " + str( round(last_workout.burgers_burned, 1)) + " burgere. \n" if last_workout.live: track_point_in_utc_time(hass, _workout_text, now + timedelta(seconds=30)) _rss_news() _workout_text() _yr_precipitation() _yr_precipitation2() track_time_change(hass, _yr_precipitation, minute=[31], second=0) track_time_change(hass, _rss_news, minute=[10, 26, 41, 56], second=0) track_time_change(hass, _workout_text, minute=[11, 26, 41, 56], second=0) hass.services.register(DOMAIN, "read_news", _read_news) print(_get_text()) return True
if __name__ == '__main__': logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) try: opts, args = getopt.getopt(sys.argv[1:], '', ['email=', 'pw=']) except getopt.error, msg: print 'python %s --email=[email] --pw=[password]' % sys.argv[0] sys.exit(2) email = '' pw = '' auth_token = '' endomondoapi = MobileApi() for option, arg in opts: if option == '--email': email = arg elif option == '--pw': pw = arg while not email: email = raw_input('Please enter your endomondo email: ') auth_token = None if not pw: auth_token = keyring.get_password("endomondo", email) pprint(endomondoapi.device_info)