Beispiel #1
0
def FullTextQuery(calendar_service):
    print 'Full text query for events on Primary Calendar: \'%s\'' % (q)
    query = GServ.CalendarEventQuery('default', 'private', 'full', q)
    query.start_min = date  #  calling date to set the beginning of query range for the present day
    query.start_max = endDate  #  calling endDate to limit the query range to the next 14 days. change tmedelta(days) to set the range
    query.singleevents = 'true'  #  enables creation of repeating events
    query.orderBy = 'startTime'  #  sort by event start time
    query.sortorder = 'a'  #  sort order: ascending
    feed = calendar_service.CalendarQuery(query)
    for i, an_event in enumerate(feed.entry):
        for a_when in an_event.when:
            print " "
            print an_event.title.text, "Scheduled:", i, "For:", time.strftime(
                '%d-%m-%Y %H:%M',
                time.localtime(tf_from_timestamp(
                    a_when.start_time))), "Current Time:", time.strftime(
                        '%d-%m-%Y %H:%M')
            if time.strftime(
                    '%d-%m-%Y %H:%M',
                    time.localtime(tf_from_timestamp(
                        a_when.start_time))) == time.strftime(
                            '%d-%m-%Y %H:%M'):
                print "Waking you up!"
                print "---"
                songfile = random.choice(
                    os.listdir(mp3_path)
                )  #  choosing by random an .mp3 file from direcotry
                print "Now Playing:", songfile
                #  plays the MP3 in it's entierty. As long as the file is longer
                #  than a minute it will only be played once:
                command = "mpg321" + " " + mp3_path + "'" + songfile + "'" + " -g 100"
                print command
                os.system(command)  #  plays the song
            else:
                print "Wait for it..."  #  the event's start time is not the system's current time
def EventQuery(calendar_service):
    print "checking for events"
    start_date = datetime.now().date().isoformat()
    end_date = datetime.now() + timedelta(days=1)
    end_date = end_date.date().isoformat()
    query = gdata.calendar.service.CalendarEventQuery('default', 'private', 'full')
    query.start_min = start_date
    query.start_max = end_date
    feed = calendar_service.CalendarQuery(query)
    now = datetime.now()
    for i, an_event in enumerate(feed.entry):
        for a_when in an_event.when:
            # special for alarm clock
            if an_event.title.text == 'wake':
                if time.strftime('%d-%m-%Y %H:%M',time.localtime(tf_from_timestamp(a_when.start_time))) == time.strftime('%d-%m-%Y %H:%M'):
                    print "Alarm comparison pass"
                    wake_up.alarm_clock()
                    morning_report.report()
            else:
                delta = datetime.fromtimestamp(time.mktime(time.localtime(tf_from_timestamp(a_when.start_time)))) - now
                if delta.days < 0:
                    continue
                delta_in_min = int(delta.total_seconds() / 60)
                print str(an_event.title.text)
                print delta_in_min
                if delta_in_min <= 15 and delta_in_min >= 0:
                    print str(an_event.title.text)+ " occuring in "+str(delta_in_min)
                    if delta_in_min % 5 == 0:
                        quick_alert.cal_alert(str(an_event.title.text), delta_in_min)
Beispiel #3
0
def main():
    """Shows basic usage of the Google Calendar API.

    Creates a Google Calendar API service object and outputs a list of the next
    10 events on the user's calendar.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)

    now = datetime.datetime.utcnow().isoformat(
    ) + 'Z'  # 'Z' indicates UTC time
    print(now)
    print('Getting the upcoming 1 events')
    eventsResult = service.events().list(calendarId=CALENDAR_ID,
                                         timeMin=now,
                                         maxResults=1,
                                         singleEvents=True,
                                         orderBy='startTime').execute()
    events = eventsResult.get('items', [])

    if not events:
        print('No upcoming events found.')
        GPIO.output(25, GPIO.LOW)
    for event in events:
        #debut de l'evenement
        start = event['start'].get('dateTime', event['start'].get('date'))
        #fin de l'evenement
        end = event['end'].get('dateTime', event['end'].get('date'))
        #print(start, end, event['summary'])

        if time.strftime(
                '%d-%m-%Y %H:%M', time.localtime(tf_from_timestamp(start))
        ) <= time.strftime('%d-%m-%Y %H:%M') and time.strftime(
                '%d-%m-%Y %H:%M') < time.strftime(
                    '%d-%m-%Y %H:%M', time.localtime(tf_from_timestamp(end))):
            print("on")
            out = 1
            print(out)
        else:
            print("off")
            out = 0
            print(out)

        #gestion de la sortie
        if out == 1:
            print("GPIO")
            GPIO.output(25, GPIO.HIGH)
        else:
            GPIO.output(25, GPIO.LOW)
def PrintEntryDetails(entry):
  rss = """
<item>
  <guid isPermaLink="false">youtube:{yt_id}</guid>
  <title>{title_text}</title> 
  <pubDate>{timestamp}</pubDate>
  <description>
    <iframe width="560"
            height="315"
            src="https://www.youtube.com/embed/{yt_id}?rel=0"
            frameborder="0"
            allowfullscreen="true">
    </iframe>
  <div>{desc}</div>
  </description>
</item>
"""
  yt_id     = parse_qs(urlparse(entry.media.player.url).query)['v'][0]
  timestamp = rfc822.timestamp_from_tf(
      rfc3339.tf_from_timestamp(entry.published.text)
  )
  return rss.format(
      yt_id       = yt_id,
      title_text  = entry.media.title.text,
      timestamp   = timestamp,
      desc        = entry.media.description.text
  )
def FullTextQuery(calendar_service):
    print 'Full text query for events on Primary Calendar: \'%s\'' % (q)
    query = GServ.CalendarEventQuery(calendar, 'private', 'full', q)
    query.start_min = date       #  calling date to set the beginning of query range for the present day
    query.start_max = endDate    #  calling endDate to limit the query range to the next 14 days. change tmedelta(days) to set the range
    query.singleevents = 'true'  #  enables creation of repeating events
    query.orderBy = 'startTime'  #  sort by event start time
    query.sortorder = 'a'        #  sort order: ascending
    feed = calendar_service.CalendarQuery(query)
    for i, an_event in enumerate(feed.entry):
        for a_when in an_event.when:
            print " "
            print an_event.title.text ,"Scheduled:",i,"For:",time.strftime('%d-%m-%Y %H:%M',time.localtime(tf_from_timestamp(a_when.start_time))),"Current Time:",time.strftime('%d-%m-%Y %H:%M')
            if time.strftime('%d-%m-%Y %H:%M',time.localtime(tf_from_timestamp(a_when.start_time))) == time.strftime('%d-%m-%Y %H:%M'):
                print "Waking you up!"
                print "---" 
                songfile = random.choice(os.listdir(mp3_path)) #  choosing by random an .mp3 file from direcotry
                print "Now Playing:", songfile
                                                               #  plays the MP3 in it's entierty. As long as the file is longer 
                                                               #  than a minute it will only be played once:
                command ="mpg321" + " " + mp3_path + "'"+songfile+"'"+ " -g 100" 
                print command
                os.system(command)                             #  plays the song
            else:
                print "Wait for it..."                         #  the event's start time is not the system's current time
Beispiel #6
0
def time_to_wake(calendar_service,text_query="wake"):
    print "polling calendar"
    query = gdata.calendar.service.CalendarEventQuery('default', 'private', 'full', text_query)
    today=str(date.today())
    tomorrow=str(date.today()+datetime.timedelta(days=1))
    query.start_min = today
    query.start_max = tomorrow
    feed = calendar_service.CalendarQuery(query)
    for i, an_event in enumerate(feed.entry):
        for a_when in an_event.when:
            print "wake scheduled for: " + time.strftime('%H:%M',time.localtime(tf_from_timestamp(a_when.start_time)))
            if time.strftime('%d-%m-%Y %H:%M',time.localtime(tf_from_timestamp(a_when.start_time))) == time.strftime('%d-%m-%Y %H:%M'):
                print "That's now!"
                return True
            else:
                pass #the "wake" event's start time != the system's current time
    return False
Beispiel #7
0
def PrintEntryDetails(entry):
  YT_ID = parse_qs(urlparse(entry.media.player.url).query)['v'][0]
  rss = ''
  rss+= '<item>'
  rss+= "<guid isPermaLink='false'>youtube:%s</guid>" % YT_ID
  rss+= '<title>%s</title>' % entry.media.title.text
  rss+= '<pubDate>%s</pubDate>' % rfc822.timestamp_from_tf(
      rfc3339.tf_from_timestamp(entry.published.text)
      )
  rss+= '<description><iframe width="560" height="315" src="https://www.youtube.com/embed/%(url)s?rel=0" frameborder="0" allowfullscreen="true" ></iframe><div>%(desc)s</div></description>' % {"url" : YT_ID, "desc" : entry.media.description.text}
  rss+= '</item>'
  return rss
Beispiel #8
0
def FullTextQuery(calendar_service, text_query='wake'):
    query = gdata.calendar.service.CalendarEventQuery\
        ('default', 'private', 'full', text_query)
    init(query)

    feed = calendar_service.CalendarQuery(query)
    for i, an_event in enumerate(feed.entry):
        for a_when in an_event.when:
#            event_date = time.strftime('%d-%m-%Y %H:%M',\
#                time.localtime(tf_from_timestamp(a_when.start_time)))
#            current_date = time.strftime('%d-%m-%Y %H:%M')
#            CheckTime(event_date,current_date,180)
            CheckTime(time.localtime(tf_from_timestamp(a_when.start_time)),time.localtime(),180)
Beispiel #9
0
def PrintEntryDetails(entry):
    YT_ID = parse_qs(urlparse(entry.media.player.url).query)['v'][0]
    rss = ''
    rss += '<item>'
    rss += "<guid isPermaLink='false'>youtube:%s</guid>" % YT_ID
    rss += '<title>%s</title>' % entry.media.title.text
    rss += '<pubDate>%s</pubDate>' % rfc822.timestamp_from_tf(
        rfc3339.tf_from_timestamp(entry.published.text))
    rss += '<description><iframe width="560" height="315" src="https://www.youtube.com/embed/%(url)s?rel=0" frameborder="0" allowfullscreen="true" ></iframe><div>%(desc)s</div></description>' % {
        "url": YT_ID,
        "desc": entry.media.description.text
    }
    rss += '</item>'
    return rss
Beispiel #10
0
def main():
    """Fetches 10 upcoming events and plays spotify playlist if 1 occurs right now.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)

    now = datetime.datetime.utcnow().isoformat() + 'Z'  # 'Z' indicates UTC time
    print 'Fetch the next 10 upcoming events'
    eventsResult = service.events().list(
        calendarId=settings.get('Calendar', 'GOOGLE_CALENDAR_ID'), timeMin=now, maxResults=10, singleEvents=True,
        orderBy='startTime').execute()
    events = eventsResult.get('items', [])

    if not events:
        print 'No upcoming events found.'
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        upcoming_event_start = time.strftime('%d-%m-%Y %H:%M', time.localtime(tf_from_timestamp(start)))
        print upcoming_event_start, event['summary']
        current_time = time.strftime('%d-%m-%Y %H:%M')
        if upcoming_event_start == current_time:

            # Initial setup fading functionality
            if settings.getboolean('Music', 'VOLUMIO_ENABLE_VOLUME_FADING'):
                current_volume = settings.getint('Music', 'VOLUMIO_INITIAL_VOLUME')
                end_volume = settings.getint('Music', 'VOLUMIO_ENDING_VOLUME')
                fade_time = settings.getint('Music', 'VOLUMIO_VOLUME_FADING_SECONDS')
                fading_steps = abs(end_volume - current_volume)
                step = 1
                if (end_volume < current_volume):
                    step = -1
                seconds_per_step = int(fade_time / fading_steps)

                # Set initial volume
                call(["mpc", "volume", str(current_volume)])

            # Start playing
            spop_play.play_music(settings)

            # Fade volume
            if settings.getboolean('Music', 'VOLUMIO_ENABLE_VOLUME_FADING'):
                while fading_steps > 0:
                    time.sleep(seconds_per_step)
                    current_volume += step
                    call(["mpc", "volume", str(current_volume)])
                    fading_steps -= 1
Beispiel #11
0
def FullTextQuery(calendar_service, text_query='display'):
    print 'Full text query for events on Primary Calendar: \'%s\'' % ( text_query,)
    query = gdata.calendar.service.CalendarEventQuery('default', 'private', 'full', text_query)
    feed = calendar_service.CalendarQuery(query)
    for i, an_event in enumerate(feed.entry):
        for a_when in an_event.when:
            print "---"
            print an_event.title.text ,"Number:",i,"Event Time:",time.strftime('%d-%m-%Y %H:%M',time.localtime(tf_from_timestamp(a_when.start_time))),"Current Time:",time.strftime('%d-%m-%Y %H:%M')
 
            if time.strftime('%d-%m-%Y %H:%M',time.localtime(tf_from_timestamp(a_when.start_time))) == time.strftime('%d-%m-%Y %H:%M'):
                print "Comparison: Pass"
                print "---"
 
                picfile = random.choice(os.listdir("/home/pi/alarmclock/test_pics/")) #chooses the picture file
                print "File Selected:", picfile
                command ="fim -p -w /home/pi/alarmclock/test_pics/ '"+picfile+"'" #Displays an image
 
                print command
                os.system(command) #runs the bash command
            else:
                print "Comparison:Fail" #the "wake" event's start time != the system's current time
def FullTextQuery(calendar_service, text_query='wake'):
	print 'Full text query for events on Primary Calendar: \'%s\'' % ( text_query,)
	query = gdata.calendar.service.CalendarEventQuery('default', 'private', 'full', text_query)
	feed = calendar_service.CalendarQuery(query)
	for i, an_event in enumerate(feed.entry):
		for a_when in an_event.when:
			print "---"
			print an_event.title.text ,"Number:",i,"Event Time:",time.strftime('%d-%m-%Y %H:%M',time.localtime(tf_from_timestamp(a_when.start_time))),"Current Time:",time.strftime('%d-%m-%Y %H:%M')

			if time.strftime('%d-%m-%Y %H:%M',time.localtime(tf_from_timestamp(a_when.start_time))) == time.strftime('%d-%m-%Y %H:%M'):
				print "Comparison: Pass"
				print "---"

				#songfile = random.choice(os.listdir("/home/pi/alarmclock/test_MP3s/")) #chooses the .mp3 file
				#print "File Selected:", songfile
				#command ="mpg321" + " " + "/home/pi/alarmclock/test_MP3s/" + "'"+songfile+"'"+ " -g 100" #plays the MP3 in it's entierty. As long as the song is longer than a minute then will only trigger once in the minute that start of the "wake" event

				print "Sounding The Alarm: ", time
				execfile("sound_the_alarm.py")

				print command
				os.system(command) #runs the bash command
			else:
				print "Comparison:Fail" #the "wake" event's start time != the system's current time
Beispiel #13
0
def main():
   #Clear the at queue, if the script is running, then we'll re-add anything that is needed.
   ppproces = subprocess.Popen(["/bin/bash","/home/pi/SCRIPTS/coffee/addToQueue.sh","","ClearQueue"])
   ppproces.wait()
   print "1. Cleared"

   #Perform the Google Calendar query
   text_query='Make coffee' #The event title must match this string
   query = gdata.calendar.service.CalendarEventQuery('default', 'private', 'full', text_query)
   query.start_min = time.strftime('%Y-%m-%dT%H:%M:%S-05:00',time.localtime())
   max = dt.now() + datetime.timedelta(minutes = 120)
   query.start_max = max.strftime('%Y-%m-%dT%H:%M:%S-05:00')
   print "Querying for events between {0} and {1}.".format(query.start_min,query.start_max)
   print "Current time: ",time.strftime('%Y-%m-%dT%H:%M:%S-05:00',time.localtime())
   feed = objCal.CalendarQuery(query)
   print "2. Queried"

   #Parse the results
   for i, an_event in enumerate(feed.entry):
      print an_event
      for a_when in an_event.when:
         eTime = time.localtime(tf_from_timestamp(a_when.start_time)) #event time
         cTime = time.localtime() # current time
         delta = datetime.datetime.fromtimestamp(time.mktime(eTime)) - datetime.datetime.fromtimestamp(time.mktime(cTime)) #start time/ current time difference

         if delta.total_seconds() < 0:
            print "Event is in the past"
            proces = subprocess.Popen(["/bin/bash","/home/pi/SCRIPTS/coffee/addToQueue.sh","","ClearQueue"])
            proces.wait()
         elif delta.total_seconds() > 0:
            print "Event is in the future.  We'll add it to the queue."
            #Queue the coffee making
            proces = subprocess.Popen(["/bin/bash","/home/pi/SCRIPTS/coffee/addToQueue.sh",time.strftime("%H:%M %B %d", eTime),"AddToQueue"])
            proces.wait()
      break
   print "4. Finished"
Beispiel #14
0
def parse_date(datestr):
    return datetime.datetime.fromtimestamp(tf_from_timestamp(datestr))
def import_datetime(x):
    ret = (datetime.datetime.fromtimestamp(
        rfc3339.tf_from_timestamp(x))) if x != 'NULL' else None
    return ret
Beispiel #16
0
def from_rfc3339(rfc_time):
    tf = rfc3339.tf_from_timestamp(rfc_time)
    return datetime.datetime.fromtimestamp(tf)
Beispiel #17
0
service = build(serviceName='calendar', version='v3', http=http, developerKey='AIzaSyBrNYKWOzxV1NFN-TjhsP05ukHK2CQCmIE')

# Get Calendar summary
calendar = service.calendars().get(calendarId='primary').execute()
print('Calendar summary: ' + calendar['summary'])

# List events
page_token = None
timeNow = timestamp_from_tf(time.time())
timeMax = timestamp_from_tf(time.time()+60*60*24)
print("Now: " + timeNow + " max: " + timeMax)

while True:
	events = service.events().list(calendarId='primary', pageToken=page_token, q='wake', timeMin=timeNow, timeMax=timeMax).execute()
	for event in events['items']:
		eventTime = tf_from_timestamp(event['start']['dateTime'])
		eventTimeString = time.strftime('%d-%m-%Y %H:%M',time.localtime(eventTime))
		
		delta = datetime.fromtimestamp(eventTime) - datetime.now()
		
		print(event['summary'] + " " + eventTimeString + " happening in: " + str(delta.total_seconds()) + " seconds")
		print(timestamp_from_tf(eventTime))
		event['summary'] = 'wake planned'
		updated_event = service.events().update(calendarId='primary', eventId=event['id'], body=event).execute()
		# Print the updated date.
		print updated_event['updated']
		
	page_token = events.get('nextPageToken')
	if not page_token:
		print("Done")
		break
Beispiel #18
0
def Event_DailyControl(ressource):
    TZ_OFFSET = pytz.timezone('Europe/Paris').localize(
        datetime.now()).strftime('%z')

    # What the weather like ?
    forecast = get_forecast()

    WeatherString = ''
    print("===========Currently Data=========")

    WeatherString = WeatherString + "\n===========Hourly Data========="
    by_hour = forecast.hourly()
    data = forecast.hourly().data
    #                 WeatherString = WeatherString + "\nHourly Summary: %s" % (by_hour.summary)

    by_day = forecast.daily()

    #    for hourlyData in by_hour.data:
    startWeatherString = False  # Only to reset when daynumber=0
    for daynumber in range(0, 2):
        mean_CloudCover = 0
        timesunriseTime = time.strptime(
            '%s' % by_day.data[daynumber].sunriseTime, "%Y-%m-%d %H:%M:%S")
        timesunsetTime = time.strptime(
            '%s' % by_day.data[daynumber].sunsetTime, "%Y-%m-%d %H:%M:%S")
        timesunriseTime = time.strftime('%Y-%m-%dT%H:%M:%S', timesunriseTime)
        timesunsetTime = time.strftime('%Y-%m-%dT%H:%M:%S', timesunsetTime)

        timesunriseTime = tf_from_timestamp(
            timesunriseTime) + 10800  # +3H apres lever
        timesunsetTime = tf_from_timestamp(
            timesunsetTime) - 7200  # -2H avant coucher
        cmpt = 0
        for index in range(0, 48):
            timestart = time.strptime('%s' % data[index].time,
                                      "%Y-%m-%d %H:%M:%S")
            timestart = time.strftime('%Y-%m-%dT%H:%M:%S', timestart)
            timestart = tf_from_timestamp(timestart)
            if ((timestart > timesunriseTime)
                    and (timestart < timesunsetTime)):
                #                            print data[index].time
                print(data[index].time, " : ", data[index].cloudCover)
                cmpt = cmpt + 1
                mean_CloudCover = mean_CloudCover + data[index].cloudCover
                # On ouvre que quand cloudCover<0.5
                if (data[index].cloudCover <
                        0.5):  # or (startWeatherString==True):
                    if (daynumber == 0):
                        WeatherString = WeatherString + '\n%s Temp=%s precipProbability=%s  humidity=%s pressure=%s cloudCover=%s' % (
                            data[index].time, data[index].temperature,
                            data[index].precipProbability,
                            data[index].humidity, data[index].pressure,
                            data[index].cloudCover)
                        if (startWeatherString == False):
                            startOpenShutter1 = data[index].time
                            # Not used now !!! startWeatherString = True
        if cmpt != 0:
            by_day.data[daynumber].cloudCover = mean_CloudCover / cmpt
        else:
            by_day.data[daynumber].cloudCover = 1
        print("mean_CloudCover: ", by_day.data[daynumber].cloudCover)

#    for hourly_data_point in by_hour.data:
#        print hourly_data_point
    if (startWeatherString == True):
        #                     print startOpenShutter1
        timestart = time.strptime('%s' % startOpenShutter1,
                                  "%Y-%m-%d %H:%M:%S")
        #                     print timestart

        startShutter = time.strftime('%Y-%m-%dT%H:%M:%S', timestart)
        startShutter = startShutter + TZ_OFFSET
        #                     datetime.startShutter().strftime('%Y-%m-%dT')+'23:30:00+02:00'

        #                     print startShutter
        # !!!Pour ouverture volet roulant!!!

        eventShutter = {
            'summary': 'OpenShutter',
            'location': 'Cesson-Sevigne, France',
            'start': {
                'dateTime': startShutter,
                #                         'timeZone': 'Europe/Paris'
            },
            'end': {
                'dateTime':
                timestamp_from_tf(tf_from_timestamp(startShutter) +
                                  3600),  # startOpenShutter+1H
                #                        'timeZone': 'Europe/Paris'
            },
        }

        created_event = insert_event(ressource, param_body=eventShutter)

# cloudCover: A numerical value between 0 and 1 (inclusive) representing the percentage of sky occluded by clouds.
# A value of 0 corresponds to clear sky, 0.4 to scattered clouds,
# 0.75 to broken cloud cover,
# and 1 to completely overcast skies.

    WeatherString = WeatherString + "\n===========Daily Summary========="

    #                 for daily_data_point in by_day.data:
    for daynumber in range(0, 2):
        #        print daily_data_point
        WeatherString = WeatherString + '\nSunrise=%s  Sunset=%s' % (
            by_day.data[daynumber].sunriseTime,
            by_day.data[daynumber].sunsetTime)
        WeatherString = WeatherString + '\nTempMin=%s Apparent=%s\nTempMax=%s Apparent=%s\nprecipIntensity (mm)=%s humidity=%s\npressure=%s CloudCover= %s\n' % (
            #daily_data_point.temperatureMin, daily_data_point.temperatureMax, daily_data_point.precipIntensity, daily_data_point.humidity, daily_data_point.pressure, daily_data_point.cloudCover)
            by_day.data[daynumber].temperatureMin,
            by_day.data[daynumber].apparentTemperatureMin,
            by_day.data[daynumber].temperatureMax,
            by_day.data[daynumber].apparentTemperatureMax,
            by_day.data[daynumber].precipIntensity * 25.4,
            by_day.data[daynumber].humidity,
            by_day.data[daynumber].pressure,
            by_day.data[daynumber].cloudCover)
#       print daily_data_point.summary

#timestartAtLeast = datetime(year= timestart.tm_year, month= timestart.tm_mon, day= timestart.tm_mday, hour= timestart.tm_hour, minute= timestart.tm_min, tzinfo=None)
    timestartAtLeast = by_day.data[1].sunriseTime + timedelta(
        hours=2)  #delta +2H en ete +1H en hiver
    timestart = time.strptime('%s' % timestartAtLeast, "%Y-%m-%d %H:%M:%S")
    #print('"line:270 timestart OpenShutter:",timestart)

    #	if(((timestart.tm_hour<8) and (timestart.tm_min<30)) or (timestart.tm_hour<7)): # en hiver

    if (((timestart.tm_hour <= 7) and (timestart.tm_min < 30))
            or (timestart.tm_hour <= 7)):  # en ete
        #                     startShutter= time.strftime('%Y-%m-%dT', timestart)+'08:00:00'
        startShutter = time.strftime('%Y-%m-%dT',
                                     timestart) + '07:40:00'  # en ete
    else:
        startShutter = time.strftime('%Y-%m-%dT%H:%M:%S', timestart)
    startShutter = startShutter + TZ_OFFSET

    print("startShutter OpenShutter:", startShutter)

    #                 start_timestamp = tf_from_timestamp(startShutter) -2700  #45mn avant lever (45*60=2700)
    start_timestamp = tf_from_timestamp(startShutter)

    #                 print WeatherString
    eventShutter = {
        'summary': 'OpenShutter',
        'location': 'Cesson-Sevigne, France',
        'start': {
            'dateTime': timestamp_from_tf(start_timestamp),
        },
        'end': {
            'dateTime':
            timestamp_from_tf(start_timestamp + 3600),  # startOpenShutter+30mn
        },
    }

    #Pas pendant vacances
    created_event = insert_event(ressource, param_body=eventShutter)

    timestartAtLeast = by_day.data[1].sunsetTime + timedelta(
        hours=2)  #delta +1H en hiver +2H en ete
    timestart = time.strptime('%s' % timestartAtLeast, "%Y-%m-%d %H:%M:%S")

    startShutter = time.strftime('%Y-%m-%dT%H:%M:%S', timestart)
    startShutter = startShutter + TZ_OFFSET
    print("CloseShutter", by_day.data[1].sunsetTime)
    print("timestart:", timestart)
    print("startShutter:", startShutter)

    start_timestamp = tf_from_timestamp(
        startShutter) + 1200  # 0mn apres coucher (0*60=0s.)

    #                 if( (datetime.isoweekday(datetime.now())==1) ): #or (datetime.isoweekday(datetime.now())==3) ): # Only Tuesday
    #                     start_timestamp = start_timestamp-5200;

    #                 if( (datetime.isoweekday(datetime.now())==3) ): # Only Thursday
    #                     start_timestamp = start_timestamp-7200;

    print(timestamp_from_tf(start_timestamp))
    eventShutter = {
        'summary': 'CloseShutter',
        'location': 'Cesson-Sevigne, France',
        'start': {
            'dateTime': timestamp_from_tf(start_timestamp),
        },
        'end': {
            'dateTime': timestamp_from_tf(start_timestamp + 3600),  # +60mn
        },
    }

    created_event = insert_event(ressource, param_body=eventShutter)
    # END FROM FORECASTIO

    # ajustement fin chauffage
    # debut a 23H30 par defaut
    # fin = debut + 1/4H en dessous de 15
    delta = 60 * 60 * 2  # mini 2H LBR
    if (by_day.data[1].cloudCover >
            0.5):  # Si beaucoup de soleil le lendemain chauffe que 2H
        delta = delta + (18 - by_day.data[1].apparentTemperatureMin
                         ) * 20 * 60  # 20mn par degre
    print('by_day.data[1].apparentTemperatureMin=%s' %
          by_day.data[1].apparentTemperatureMin)
    #print 'Delta=%ss ou %s mn'%(delta,delta/60) #timestamp unit

    # If night heat more than 23:30 to 07:15, heat on afternoon
    if ((delta > (7 * 60 * 60 + 45 * 60)) and (by_day.data[0].cloudCover > 0.7)
            and (by_day.data[1].cloudCover > 0.7)):  # 7:45
        delta1 = delta - (7 * 60 * 60 + 45 * 60)
        delta = (7 * 60 * 60 + 45 * 60)
        print('delta1=%ss ou %s mn' % (delta1, delta1 / 60))  #timestamp unit
        today_start_off_peak_hour = datetime.now().strftime(
            '%Y-%m-%dT') + '16:00:00' + TZ_OFFSET
        start_time_timestamp = tf_from_timestamp(today_start_off_peak_hour)
        if (delta1 < (3 * 60 * 60)):  # 3:00
            delta1 = (3 * 60 * 60)
        today_end_off_peak_hour = timestamp_from_tf(start_time_timestamp +
                                                    delta1)  # +residus
        eventWakePAC = {
            'summary': 'WakePAC',
            'location': 'Cesson-Sevigne, France',
            'description': 'daylight wake',
            'start': {
                'dateTime': today_start_off_peak_hour,
            },
            'end': {
                'dateTime': today_end_off_peak_hour,
            },
        }

        created_event = insert_event(ressource, param_body=eventWakePAC)

#Arret a la fin de l'heure creuse 07h30
    today_end_off_peak_hour = datetime.now().strftime(
        '%Y-%m-%dT') + '07:15:00' + TZ_OFFSET
    end_time_timestamp = tf_from_timestamp(today_end_off_peak_hour)
    today_end_off_peak_hour = timestamp_from_tf(end_time_timestamp +
                                                24 * 60 * 60)  # +24H
    #Calcul duree chauffage
    today_start_off_peak_hour = timestamp_from_tf(end_time_timestamp +
                                                  24 * 60 * 60 - delta)
    print('today_start_off_peak_hour=%s' % today_start_off_peak_hour)
    print('today_end_off_peak_hour=%s' % today_end_off_peak_hour)

    eventWakePAC = {
        'summary': 'WakePAC',
        'location': 'Cesson-Sevigne, France',
        'description': WeatherString,
        'start': {
            'dateTime': today_start_off_peak_hour,
        },
        'end': {
            'dateTime': today_end_off_peak_hour,
        },
    }

    #LBR	eventWakePAC['start']['dateTime']=today_start_off_peak_hour
    #                 eventWakePAC['start']['timeZone']='Europe/Paris'

    #LBR	eventWakePAC['end']['dateTime']=today_end_off_peak_hour
    #                 eventWakePAC['end']['timeZone']='Europe/Paris'

    #LBR	eventWakePAC['description']=WeatherString

    #LBR	eventWakePAC['summary']='WakePAC'

    if (by_day.data[1].temperatureMax < 18):
        created_event = insert_event(ressource, param_body=eventWakePAC)
#LBR		updated_event = update_event(ressource, param_eventId=eventWakePAC['id'], param_event=eventWakePAC)
    else:
        eventWakePAC['start']['dateTime'] = timestamp_from_tf(
            end_time_timestamp + 24 * 60 * 60 - 60 * 60)
        eventWakePAC['summary'] = 'NoWakePAC'
        created_event = insert_event(ressource, param_body=eventWakePAC)


#LBR		updated_event = update_event(ressource, param_eventId=eventWakePAC['id'], param_event=eventWakePAC)
# Print the updated date.
    print('------------eventWakePAC UPDATED---------------')
def import_datetime(x):
    ret = (datetime.datetime.fromtimestamp(rfc3339.tf_from_timestamp(x))) if (x != 'NULL' and len(x)>0) else None
    return ret
Beispiel #20
0
print('Calendar summary: ' + calendar['summary'])

# List events
page_token = None
timeNow = timestamp_from_tf(time.time())
timeMax = timestamp_from_tf(time.time() + 60 * 60 * 24)
print("Now: " + timeNow + " max: " + timeMax)

while True:
    events = service.events().list(calendarId='primary',
                                   pageToken=page_token,
                                   q='wake',
                                   timeMin=timeNow,
                                   timeMax=timeMax).execute()
    for event in events['items']:
        eventTime = tf_from_timestamp(event['start']['dateTime'])
        eventTimeString = time.strftime('%d-%m-%Y %H:%M',
                                        time.localtime(eventTime))

        delta = datetime.fromtimestamp(eventTime) - datetime.now()

        print(event['summary'] + " " + eventTimeString + " happening in: " +
              str(delta.total_seconds()) + " seconds")
        print(timestamp_from_tf(eventTime))
        event['summary'] = 'wake planned'
        updated_event = service.events().update(calendarId='primary',
                                                eventId=event['id'],
                                                body=event).execute()
        # Print the updated date.
        print updated_event['updated']
def FullTextQuery():
    service_account_name = '*****@*****.**'

    creds = init_calendar()

    #We add TZ_OFFSET in timeMin/timeMax
    TZ_OFFSET = pytz.timezone('Europe/Paris').localize(
        datetime.now()).strftime('%z')

    timeMin = (datetime.now() +
               timedelta(minutes=-(wake_interval / 2))).isoformat() + TZ_OFFSET
    timeMax = (datetime.now() + timedelta(minutes=+(wake_interval / 2) +
                                          1)).isoformat() + TZ_OFFSET

    # add timezone
    print('timeMin=%s' % timeMin, 'ajouter offset\n')
    print('timeMax=%s' % timeMax, 'ajouter offset\n')

    print(' Getting all events from this calendar ID')
    #    pprint.pprint(events)

    # Accessing the response like a dict object with an 'items' key
    # returns a list of item objects (events).
    events_found = get_events(creds, timeMin, timeMax)
    for event in events_found:
        print('LBR' + event['summary'])

        if (event['summary'] == 'DailyControl'):
            print("!!!MATCH!!!   Title query=%s" % event['summary'])
            print("Debut : ", event['start'])
            print("Fin : ", event['end'])

            # What the weather like ?
            forecast = get_forecast()

            WeatherString = ''
            print("===========Currently Data=========")

            WeatherString = WeatherString + "\n===========Hourly Data========="
            by_hour = forecast.hourly()
            data = forecast.hourly().data
            #                 WeatherString = WeatherString + "\nHourly Summary: %s" % (by_hour.summary)

            by_day = forecast.daily()

            #    for hourlyData in by_hour.data:
            startWeatherString = False  # Only to reset when daynumber=0
            for daynumber in range(0, 2):
                mean_CloudCover = 0
                timesunriseTime = time.strptime(
                    '%s' % by_day.data[daynumber].sunriseTime,
                    "%Y-%m-%d %H:%M:%S")
                timesunsetTime = time.strptime(
                    '%s' % by_day.data[daynumber].sunsetTime,
                    "%Y-%m-%d %H:%M:%S")
                timesunriseTime = time.strftime('%Y-%m-%dT%H:%M:%S',
                                                timesunriseTime)
                timesunsetTime = time.strftime('%Y-%m-%dT%H:%M:%S',
                                               timesunsetTime)

                timesunriseTime = tf_from_timestamp(
                    timesunriseTime) + 10800  # +3H apres lever
                timesunsetTime = tf_from_timestamp(
                    timesunsetTime) - 7200  # -2H avant coucher
                cmpt = 0
                for index in range(0, 48):
                    timestart = time.strptime('%s' % data[index].time,
                                              "%Y-%m-%d %H:%M:%S")
                    timestart = time.strftime('%Y-%m-%dT%H:%M:%S', timestart)
                    timestart = tf_from_timestamp(timestart)
                    if ((timestart > timesunriseTime)
                            and (timestart < timesunsetTime)):
                        #                            print data[index].time
                        print(data[index].time, " : ", data[index].cloudCover)
                        cmpt = cmpt + 1
                        mean_CloudCover = mean_CloudCover + data[
                            index].cloudCover
                        # On ouvre que quand cloudCover<0.5
                        if (data[index].cloudCover <
                                0.5):  # or (startWeatherString==True):
                            if (daynumber == 0):
                                WeatherString = WeatherString + '\n%s Temp=%s precipProbability=%s  humidity=%s pressure=%s cloudCover=%s' % (
                                    data[index].time, data[index].temperature,
                                    data[index].precipProbability,
                                    data[index].humidity, data[index].pressure,
                                    data[index].cloudCover)
                                if (startWeatherString == False):
                                    startOpenShutter1 = data[index].time
                                    # Not used now !!! startWeatherString = True
                if cmpt != 0:
                    by_day.data[daynumber].cloudCover = mean_CloudCover / cmpt
                else:
                    by_day.data[daynumber].cloudCover = 1
                print("mean_CloudCover: ", by_day.data[daynumber].cloudCover)

#    for hourly_data_point in by_hour.data:
#        print hourly_data_point
            if (startWeatherString == True):
                #                     print startOpenShutter1
                timestart = time.strptime('%s' % startOpenShutter1,
                                          "%Y-%m-%d %H:%M:%S")
                #                     print timestart

                startShutter = time.strftime('%Y-%m-%dT%H:%M:%S', timestart)
                startShutter = startShutter + TZ_OFFSET
                #                     datetime.startShutter().strftime('%Y-%m-%dT')+'23:30:00+02:00'

                #                     print startShutter
                # !!!Pour ouverture volet roulant!!!

                eventShutter = {
                    'summary': 'OpenShutter',
                    'location': 'Cesson-Sevigne, France',
                    'start': {
                        'dateTime': startShutter,
                        #                         'timeZone': 'Europe/Paris'
                    },
                    'end': {
                        'dateTime':
                        timestamp_from_tf(
                            tf_from_timestamp(startShutter) +
                            3600),  # startOpenShutter+1H
                        #                        'timeZone': 'Europe/Paris'
                    },
                    #                       'attendees': [
                    #                         {
                    #                           'email': '*****@*****.**',
                    #                           # Other attendee's data...
                    #                         },
                    #                         # ...
                    #                       ],
                }

                created_event = insert_event(creds, param_body=eventShutter)

# cloudCover: A numerical value between 0 and 1 (inclusive) representing the percentage of sky occluded by clouds.
# A value of 0 corresponds to clear sky, 0.4 to scattered clouds,
# 0.75 to broken cloud cover,
# and 1 to completely overcast skies.

            WeatherString = WeatherString + "\n===========Daily Summary========="

            #                 for daily_data_point in by_day.data:
            for daynumber in range(0, 2):
                #        print daily_data_point
                WeatherString = WeatherString + '\nSunrise=%s  Sunset=%s' % (
                    by_day.data[daynumber].sunriseTime,
                    by_day.data[daynumber].sunsetTime)
                WeatherString = WeatherString + '\nTempMin=%s Apparent=%s\nTempMax=%s Apparent=%s\nprecipIntensity (mm)=%s humidity=%s\npressure=%s CloudCover= %s\n' % (
                    #daily_data_point.temperatureMin, daily_data_point.temperatureMax, daily_data_point.precipIntensity, daily_data_point.humidity, daily_data_point.pressure, daily_data_point.cloudCover)
                    by_day.data[daynumber].temperatureMin,
                    by_day.data[daynumber].apparentTemperatureMin,
                    by_day.data[daynumber].temperatureMax,
                    by_day.data[daynumber].apparentTemperatureMax,
                    by_day.data[daynumber].precipIntensity * 25.4,
                    by_day.data[daynumber].humidity,
                    by_day.data[daynumber].pressure,
                    by_day.data[daynumber].cloudCover)
#       print daily_data_point.summary

#timestartAtLeast = datetime(year= timestart.tm_year, month= timestart.tm_mon, day= timestart.tm_mday, hour= timestart.tm_hour, minute= timestart.tm_min, tzinfo=None)
            timestartAtLeast = by_day.data[1].sunriseTime + timedelta(
                hours=2)  #delta +2H en ete +1H en hiver
            timestart = time.strptime('%s' % timestartAtLeast,
                                      "%Y-%m-%d %H:%M:%S")
            #print('"line:270 timestart OpenShutter:",timestart)

            #                 if(((timestart.tm_hour<8) and (timestart.tm_min<30)) or (timestart.tm_hour<7)): # en hiver

            if (((timestart.tm_hour <= 7) and (timestart.tm_min < 30))
                    or (timestart.tm_hour <= 7)):  # en ete
                #                     startShutter= time.strftime('%Y-%m-%dT', timestart)+'08:00:00'
                startShutter = time.strftime('%Y-%m-%dT',
                                             timestart) + '07:40:00'  # en ete
            else:
                startShutter = time.strftime('%Y-%m-%dT%H:%M:%S', timestart)
            startShutter = startShutter + TZ_OFFSET

            print("startShutter OpenShutter:", startShutter)

            #                 start_timestamp = tf_from_timestamp(startShutter) -2700  #45mn avant lever (45*60=2700)
            start_timestamp = tf_from_timestamp(startShutter)

            #                 print WeatherString
            eventShutter = {
                'summary': 'OpenShutter',
                'location': 'Cesson-Sevigne, France',
                'start': {
                    'dateTime': timestamp_from_tf(start_timestamp),
                },
                'end': {
                    'dateTime':
                    timestamp_from_tf(start_timestamp +
                                      3600),  # startOpenShutter+30mn
                },
            }

            #Pas pendant vacances
            created_event = insert_event(creds, param_body=eventShutter)

            timestartAtLeast = by_day.data[1].sunsetTime + timedelta(
                hours=2)  #delta +1H en hiver +2H en ete
            timestart = time.strptime('%s' % timestartAtLeast,
                                      "%Y-%m-%d %H:%M:%S")

            startShutter = time.strftime('%Y-%m-%dT%H:%M:%S', timestart)
            startShutter = startShutter + TZ_OFFSET
            print("CloseShutter", by_day.data[1].sunsetTime)
            print("timestart:", timestart)
            print("startShutter:", startShutter)

            start_timestamp = tf_from_timestamp(
                startShutter) + 1200  # 0mn apres coucher (0*60=0s.)

            #                 if( (datetime.isoweekday(datetime.now())==1) ): #or (datetime.isoweekday(datetime.now())==3) ): # Only Tuesday
            #                     start_timestamp = start_timestamp-5200;

            #                 if( (datetime.isoweekday(datetime.now())==3) ): # Only Thursday
            #                     start_timestamp = start_timestamp-7200;

            print(timestamp_from_tf(start_timestamp))
            eventShutter = {
                'summary': 'CloseShutter',
                'location': 'Cesson-Sevigne, France',
                'start': {
                    'dateTime': timestamp_from_tf(start_timestamp),
                },
                'end': {
                    'dateTime':
                    timestamp_from_tf(start_timestamp + 3600),  # +60mn
                },
            }

            created_event = insert_event(creds, param_body=eventShutter)
            # END FROM FORECASTIO

            # ajustement fin chauffage
            # debut a 23H30 par defaut
            # fin = debut + 1/4H en dessous de 15
            delta = 60 * 60 * 2  # mini 2H LBR
            if (by_day.data[1].cloudCover >
                    0.5):  # Si beaucoup de soleil le lendemain chauffe que 2H
                delta = delta + (18 - by_day.data[1].apparentTemperatureMin
                                 ) * 20 * 60  # 20mn par degre
            print('by_day.data[1].apparentTemperatureMin=%s' %
                  by_day.data[1].apparentTemperatureMin)
            #print 'Delta=%ss ou %s mn'%(delta,delta/60) #timestamp unit

            # If night heat more than 23:30 to 07:15, heat on afternoon
            if ((delta >
                 (7 * 60 * 60 + 45 * 60)) and (by_day.data[0].cloudCover > 0.7)
                    and (by_day.data[1].cloudCover > 0.7)):  # 7:45
                delta1 = delta - (7 * 60 * 60 + 45 * 60)
                delta = (7 * 60 * 60 + 45 * 60)
                print('delta1=%ss ou %s mn' %
                      (delta1, delta1 / 60))  #timestamp unit
                today_start_off_peak_hour = datetime.now().strftime(
                    '%Y-%m-%dT') + '16:00:00' + TZ_OFFSET
                start_time_timestamp = tf_from_timestamp(
                    today_start_off_peak_hour)
                if (delta1 < (3 * 60 * 60)):  # 3:00
                    delta1 = (3 * 60 * 60)
                today_end_off_peak_hour = timestamp_from_tf(
                    start_time_timestamp + delta1)  # +residus
                eventWakePAC = {
                    'summary': 'WakePAC',
                    'location': 'Cesson-Sevigne, France',
                    'description': 'daylight wake',
                    'start': {
                        'dateTime': today_start_off_peak_hour,
                    },
                    'end': {
                        'dateTime': today_end_off_peak_hour,
                    },
                }

                created_event = insert_event(creds, param_body=eventWakePAC)

#Arret a la fin de l'heure creuse 07h30
            today_end_off_peak_hour = datetime.now().strftime(
                '%Y-%m-%dT') + '07:15:00' + TZ_OFFSET
            end_time_timestamp = tf_from_timestamp(today_end_off_peak_hour)
            today_end_off_peak_hour = timestamp_from_tf(
                end_time_timestamp + 24 * 60 * 60)  # +24H
            #Calcul duree chauffage
            today_start_off_peak_hour = timestamp_from_tf(end_time_timestamp +
                                                          24 * 60 * 60 - delta)
            print('today_start_off_peak_hour=%s' % today_start_off_peak_hour)
            print('today_end_off_peak_hour=%s' % today_end_off_peak_hour)

            event['start']['dateTime'] = today_start_off_peak_hour
            #                 event['start']['timeZone']='Europe/Paris'

            event['end']['dateTime'] = today_end_off_peak_hour
            #                 event['end']['timeZone']='Europe/Paris'

            event['description'] = WeatherString

            event['summary'] = 'WakePAC'

            if (by_day.data[1].temperatureMax < 18):
                updated_event = update_event(creds,
                                             param_eventId=event['id'],
                                             param_event=event)
            else:
                event['start']['dateTime'] = timestamp_from_tf(
                    end_time_timestamp + 24 * 60 * 60 - 60 * 60)
                event['summary'] = 'NoWakePAC'
                updated_event = update_event(creds,
                                             param_eventId=event['id'],
                                             param_event=event)
# Print the updated date.
            print('------------EVENT UPDATED---------------')

# the list_next method.
#			request = service.events().list_next(request, response)

    print(' Getting all events names WakePAC from this calendar ID')
    PACStateToSet = '0'

    #		while (request != None):
    # Get the next page
    #OLD      response = request.execute(http)
    #		response = request.execute()
    # Accessing the response like a dict object with an 'items' key
    # returns a list of item objects (events).
    events_found = get_events(creds, timeMin, timeMax)
    for event in events_found:
        if (event['summary'] == 'WakePAC'):
            print("!!!MATCH!!!   Title query=%s" % event['summary'])
            print("Debut : ", event['start'])
            print("Fin : ", event['end'])

            print('ALLUMAGE CHAUFFAGE DONE')
            PACStateToSet = '1'
            if (event.get('description')):
                event['description'] = event['description'] + ' \nPAC Started'
            else:
                event['description'] = '\nPAC Started'

            updated_event = update_event(creds,
                                         param_eventId=event['id'],
                                         param_event=event)

        if (event['summary'] == 'OpenShutter'):
            print("!!!MATCH!!!   Title query=%s" % event['summary'])
            print("Debut : ", event['start'])
            print("Fin : ", event['end'])

            OpenAllShutter()

            delete_event(creds, param_eventId=event['id'])

        if (event['summary'] == 'CloseShutter'):
            print("!!!MATCH!!!   Title query=%s" % event['summary'])
            print("Debut : ", event['start'])
            print("Fin : ", event['end'])

            CloseAllShutter()

            delete_event(creds, param_eventId=event['id'])


# the list_next method.
#	request = service.events().list_next(request, response)

# From web browser : http://192.168.0.14/domocan/www/php/CmdPAC.php?state=0
    url = 'http://localhost/domocan/www/php/CmdPAC.php?state=' + PACStateToSet
    print(url)
    try:
        url_response = urllib.request.urlopen(url, timeout=5)
    except urllib.error.URLError as e:
        print(e.reason)
    else:
        #    print url_response.info()
        html = url_response.read()
        # do something
        print(html)
        url_response.close()  # best practice to close the file
Beispiel #22
0
def get_todays_events(calendar_service):
    query = gdata.calendar.service.CalendarEventQuery('default', 'private', 'full')
    today=str(date.today())
    tomorrow=str(date.today()+datetime.timedelta(days=1))
    query.start_min = today
    query.start_max = tomorrow
    feed = calendar_service.CalendarQuery(query)
    to_return=""
    for i, an_event in enumerate(feed.entry):
        for a_when in an_event.when:
            to_return.append(an_event.title.text ,"at",time.strftime('%H:%M',time.localtime(tf_from_timestamp(a_when.start_time))))
    return to_return
Beispiel #23
0
new_ts = 0

json_key = json.load(open("password.conf"))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
gc = gspread.authorize(credentials)

scs = gc.openall()
for sc in scs:
    print sc.id

sh = gc.open_by_key("1ECdAfHs8Z-80gmt0Aj7dhHSuAyPndCS1LoEIsAGp3lo")
ws1 = sh.get_worksheet(1)
ws2 = sh.get_worksheet(2)
new_ts = max(tf_from_timestamp(ws1.updated),
             tf_from_timestamp(ws2.updated))
if new_ts > old_ts:
    csheet = ws1.get_all_values()
    ssheet = ws2.get_all_values()

    out = open("hikki_cards.json", "w")
    out.write(json.dumps(csheet, indent=2, separators=(',', ': ')))
    out.close()
    out = open("hikki_skills.json", "w")
    out.write(json.dumps(ssheet, indent=2, separators=(',', ': ')))
    out.close()
    tsfile = open("timestamp", "w")
    tsfile.write(str(new_ts))
    tsfile.close()
    def getNextAlarm(self):
        if not self.credentialsReceived:
            self.getCredentials()

        # Create an httplib2.Http object to handle our HTTP requests and authorize it
        # with our good Credentials.
        http = httplib2.Http()
        http = self.credentials.authorize(http)
        service = build(serviceName='calendar',
                        version='v3',
                        http=http,
                        developerKey=self.API_KEY)

        page_token = None
        timeNow = timestamp_from_tf(time.time())
        timeMax = timestamp_from_tf(time.time() + 60 * 60 * 24)

        firstEvent = None
        numberEvent = 0
        while True:
            events = service.events().list(calendarId='primary',
                                           pageToken=page_token,
                                           q='wake',
                                           timeMin=timeNow,
                                           timeMax=timeMax).execute()
            numberEvent = len(events['items'])
            for event in events['items']:
                eventTime = tf_from_timestamp(event['start']['dateTime'])
                eventTimeString = time.strftime('%d-%m-%Y %H:%M',
                                                time.localtime(eventTime))

                delta = datetime.fromtimestamp(eventTime) - datetime.now()

                logger.info(event['summary'] + " " + eventTimeString +
                            " happening @timestamp: " +
                            str(timestamp_from_tf(eventTime)) + " delta: " +
                            str(delta.total_seconds()) + " seconds")

                if delta.total_seconds() <= 0:
                    print("Negative difference!")
                    continue  # This is not correct!

                if firstEvent == None:
                    firstEvent = eventTime
                    event[
                        'summary'] = 'wake planned by timearc: ' + time.strftime(
                            "%H:%M:%S")
                    updated_event = service.events().update(
                        calendarId='primary', eventId=event['id'],
                        body=event).execute()

            page_token = events.get('nextPageToken')
            if not page_token:
                logger.debug("Done")
                break

        if firstEvent != None or numberEvent == 0:
            if self.callback != None:
                self.callback(firstEvent)  # send None when we have no events

        return firstEvent
Beispiel #25
0
def parse_date(datestr):
    return datetime.datetime.fromtimestamp(tf_from_timestamp(datestr))
Beispiel #26
0
    def get(self, mc, db, pkey):
        def check_encoding(string):
            data = string
            if string is not unicode:
                data = unicode(string)

            return ud.normalize('NFKD', data).encode('ascii', 'xmlcharrefreplace')

        h = HTMLParser.HTMLParser()
        try:
            # host URL
            urlparts = request.urlparts
            host_url = '%s://%s/feeds/%s' % (urlparts.scheme, urlparts.netloc, pkey)

            # get feed data
            cfg = self._app.config
            obj = FeedService.get_feed_activities(db, mc, cfg, pkey)
            activities = obj['activities']
            user_id = obj['user_id']

            # namespaces
            xmldoc, channel = new_xmldoc_echannel()
            xmldoc.root_element.attrs['xmlns:media'] = 'http://search.yahoo.com/mrss/'
            xmldoc.root_element.attrs['xmlns:atom'] = 'http://www.w3.org/2005/Atom'
            xmldoc.root_element.attrs['xmlns:geo'] = 'http://www.w3.org/2003/01/geo/wgs84_pos#'

            # compose items
            channel.title = 'Plus Channel feed'
            channel.description = 'Google+ List of Activities for %s' % obj['name']
            channel.generator = 'Plus Channel %s' % cfg.get('main.version')
            channel.link = 'http://plus.google.com/' + user_id
            channel.docs.text = ''
            channel.atom_link = AtomLink(host_url)
            if 'photo_url' in obj and obj['photo_url'] is not None:
                channel.image = Image(
                    url=obj['photo_url'],
                    title='Plus Channel feed',
                    link='http://plus.google.com/' + user_id,
                    width=cfg.get('feed.photo_size.database'),
                    height=cfg.get('feed.photo_size.database'))
            for activity in activities:

                title = activity['title']
                content = activity['content']
                url = activity['url']

                # check content
                if content is None or content == title:
                    content = ''

                # check title
                if title is None:
                    title = 'notitle'

                # reformat strings
                title = h.unescape(title)
                title = re.sub('<[^>]*>', '', title)
                title = escape(title)
                content = h.unescape(content)
                content = re.sub('<[^>]*>', '', content)
                content = escape(content)

                # log activity
                logging.debug('--- activity ---')
                logging.debug(title)
                logging.debug(content)
                logging.debug(url)
                logging.debug('----------------')

                # create item
                item = Item()
                item.title = check_encoding(title)
                updated = tf_from_timestamp(activity['datePublished'])
                updated = timestamp_from_tf(updated)
                item.pubDate = TextElement('pubDate', updated)

                # process content
                c_content = CDATA()
                c_content.text = check_encoding(content)
                item.description = str(c_content)

                # check image presence
                if 'imageUrl' in activity and activity['imageUrl'] != '':
                    image = TextElement('media:thumbnail')
                    image.attrs['url'] = activity['imageUrl']

                    # check size
                    if 'imageWidth' in activity and 'imageHeight' in activity:
                        image.attrs['width'] = activity['imageWidth']
                        image.attrs['height'] = activity['imageHeight']

                    item.thumbnail = image

                # check coordinates
                if activity['hasCoordinates']:
                    item.lat = TextElement('geo:lat', activity['latitude'])
                    item.long = TextElement('geo:long', activity['longitude'])

                # check link
                if url is None or url == '':
                    url = activity['url']
                item.link = escape(url)
                item.guid = escape(activity['id'])
                item.guid.attrs['isPermaLink'] = 'false'

                channel.items.append(item)

            # return created feed
            response.set_header('content-type', 'application/rss+xml; charset=utf-8')
            return unicode(xmldoc)

        except FeedService.FeedNotFoundException:
            abort(404)

        except FeedService.UserIdNotFoundException:
            abort(410)
Beispiel #27
0
def from_rfc3339(rfc_time):
    tf = rfc3339.tf_from_timestamp(rfc_time)
    return datetime.datetime.fromtimestamp(tf)