예제 #1
0
    def run(self):
        while True:

            # request NOAA weather data
            noaa_result = pywapi.get_weather_from_noaa('KOWD')
            print(noaa_result)

            # # PAGE 1
            # pull out string that I want
            if 'weather' in noaa_result:
                weather_string = string.lower(noaa_result['weather'])
            else:
                weather_string = 'n/a'

            if 'temperature_string' in noaa_result:
                temp_string = string.lower(noaa_result['temperature_string'])
            else:
                temp_string = 'n/a'

            # aquire write lock to queue and put messages on queue
            utils.queueLock.acquire()
            lcdQueueMessage = message.Message(
                self.threadID, weather_string + ',' + temp_string)
            utils.lcdQueue.enqueue(lcdQueueMessage)
            utils.queueLock.release()

            # every 10 minutes
            time.sleep(600)
예제 #2
0
    def Weather(self):
        for i in self.trying:
            i.Destroy()
            
        self.trying = []
        sizer = wx.GridBagSizer()
        temp_actuel=T.time()
        weather_com_result = pywapi.get_weather_from_weather_com('10001')
        yahoo_result = pywapi.get_weather_from_yahoo('10001')
        noaa_result = pywapi.get_weather_from_noaa('KJFK')
        weather1 = self.trying.append(wx.StaticText(self.BoxStock,-1,str("Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " +
         yahoo_result['condition']['temp'] + " C now "),pos=(50,50)))
       # labelStock = wx.StaticText(self.BoxStock,-1,label=weather1,pos=(30,30))
        #self.text.SetLabel(str(labelStock))
        #weather2 = "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + " C now "
        #labelStock = wx.StaticText(self.BoxStock,label=weather2,pos=(30,80))
        #self.text.SetLabel(str(labelStock))

        wx.CallLater(10000,self.Weather)
        message=string.lower(yahoo_result['condition']['text'])
        if message=="fair":
            #from PIL import Image
            #bidule = Image.open("image/nuage-noir-avec-de-la-pluie.jpg")
            #bidule.show()
            
            app= Application(redirect=True)
            app.MainLoop()
예제 #3
0
    def Weather(self):
        for i in self.trying:
            i.Destroy()

        self.trying = []
        sizer = wx.GridBagSizer()
        temp_actuel = T.time()
        weather_com_result = pywapi.get_weather_from_weather_com('10001')
        yahoo_result = pywapi.get_weather_from_yahoo('10001')
        noaa_result = pywapi.get_weather_from_noaa('KJFK')
        weather1 = self.trying.append(
            wx.StaticText(
                self.BoxStock,
                -1,
                str("Yahoo says: It is " +
                    string.lower(yahoo_result['condition']['text']) + " and " +
                    yahoo_result['condition']['temp'] + " C now "),
                pos=(50, 50)))
        # labelStock = wx.StaticText(self.BoxStock,-1,label=weather1,pos=(30,30))
        #self.text.SetLabel(str(labelStock))
        #weather2 = "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + " C now "
        #labelStock = wx.StaticText(self.BoxStock,label=weather2,pos=(30,80))
        #self.text.SetLabel(str(labelStock))

        wx.CallLater(10000, self.Weather)
        message = string.lower(yahoo_result['condition']['text'])
        if message == "fair":
            #from PIL import Image
            #bidule = Image.open("image/nuage-noir-avec-de-la-pluie.jpg")
            #bidule.show()

            app = Application(redirect=True)
            app.MainLoop()
예제 #4
0
    def get_weather_data(self):
        station_id = g15gconf.get_string_or_default(self.gconf_client, "%s/station_id" % self.gconf_key, "KPEO")
        p = pywapi.get_weather_from_noaa(station_id)

        tm = email.utils.parsedate_tz(p["observation_time_rfc822"])[:9]
        data = {
            "location": p["location"],
            "datetime": datetime.datetime.fromtimestamp(time.mktime(tm)),
            "current_conditions": {
                "wind_speed": g15pythonlang.to_int_or_none(weather.mph_to_kph(float(p["wind_mph"])))
                if "wind_mph" in p
                else None,
                "wind_direction": g15pythonlang.to_int_or_none(p["wind_degrees"]) if "wind_degrees" in p else None,
                "pressure": p["pressure_mb"] if "pressure_mb" in p else None,
                "humidity": p["relative_humidity"] if "relative_humidity" in p else None,
                "condition": p["weather"] if "weather" in p else None,
                "temp_c": p["temp_c"] if "temp_c" in p else None,
                "icon": self._get_icon(p["icon_url_name"]) if "icon_url_name" in p else None,
                "fallback_icon": "http://w1.weather.gov/images/fcicons/%s"
                % ("%s.jpg" % os.path.splitext(p["icon_url_name"])[0])
                if "icon_url_name" in p
                else None,
            },
        }

        return data
예제 #5
0
    def get_todays_weather(self, weather_service):
        """
        Says today's weather forecast with the selected weather service
        :author Robert Zeni:
        :name get_todays_weather:
        :param weather_service - the service to use for weather retrieval
        :date March 19, 2017
        :return: void
        """
        if weather_service == WeatherServices.OpenWeatherMap.value:
            return "Weather retrieval using open weather map is not implemented yet."

        if weather_service == WeatherServices.Yahoo.value:
            yahoo_result = pywapi.get_weather_from_yahoo('10001')
            return "It is " + yahoo_result['condition'][
                'text'] + " and " + yahoo_result['condition'][
                    'temp'] + "degrees celsius now in New York.\n\n"

        if weather_service == WeatherServices.Weather_com.value:
            weather_com_result = pywapi.get_weather_from_weather_com('10001')
            return "Weather.com says: It is " + weather_com_result[
                'current_conditions']['text'] + " and " + weather_com_result[
                    'current_conditions'][
                        'temperature'] + "degrees celsius  now in New York.\n\n"

        if weather_service == WeatherServices.NOAA.value:
            noaa_result = pywapi.get_weather_from_noaa('KJFK')
            return "NOAA says it is, " + noaa_result[
                'weather'] + " and " + noaa_result[
                    'temp_c'] + "degrees celsius right now.\n"
예제 #6
0
    def run(self):
        while True:

            # request NOAA weather data
            noaa_result = pywapi.get_weather_from_noaa('KOWD')
            print(noaa_result)

            # # PAGE 1
            # pull out string that I want
            if 'weather' in noaa_result:
                weather_string = string.lower(noaa_result['weather'])
            else:
                weather_string = 'n/a'

            if 'temperature_string' in noaa_result:
                temp_string = string.lower(noaa_result['temperature_string'])
            else:
                temp_string = 'n/a'

            # aquire write lock to queue and put messages on queue
            utils.queueLock.acquire()
            lcdQueueMessage = message.Message(self.threadID, weather_string+','+temp_string)
            utils.lcdQueue.enqueue(lcdQueueMessage)
            utils.queueLock.release()

            # every 10 minutes
            time.sleep(600)
예제 #7
0
def temperatureCallCycle():
    lastTemp = 10
    weatherCode = 0
    while 1:
      try:
        weatherCode = GetWeatherCondition(weatherCode)
        noaa_result = pywapi.get_weather_from_noaa(weatherStation)
        temp = Decimal(noaa_result['temp_f'])
        if lastTemp != temp:
          print datetime.now().ctime(), 
          if (temp <= 32):
              print temp
              print ' Freezing! Sent D.'
              shiftColor('D')
          elif  (temp < 40):
              print temp 
              print ' B\n'
              shiftColor('B')
          elif (temp < 45):
              print temp
              print ' G\n'
              shiftColor('G')
          else:
              print temp
              print ' R\n'
              shiftColor('R')
        lastTemp = temp
        time.sleep(callInterval)
      except (KeyboardInterrupt, SystemExit):
        print 'Quitting...'
        sys.exit()
      except:
        print "Unable to connect to the weather station."
예제 #8
0
파일: ex1.py 프로젝트: annonch/IRTTAE
def update(state,time):
    print('updating continuous variables')
    print time
    t=float(time)
    rst=''
    if state == 'a':
        beta = t * 2.2
        rst+= 'beta:float:%s '%beta
        if beta > 100:
            rst += 'charlie:int:1 '
        elif float(pywapi.get_weather_from_noaa('KORD')['temp_c']) > 5.0:
            rst += 'charlie:int:-1 '
        
    if state == 'b':
        delta = pywapi.get_weather_from_noaa('KORD')['wind_mph']
        rst+= 'delta:float:%s '% delta
    return rst
예제 #9
0
파일: ex1.py 프로젝트: annonch/IRTTAE
def update(state, time):
    print ("updating continuous variables")
    print time
    t = float(time)
    rst = ""
    if state == "a":
        beta = t * 2.2
        rst += "beta:float:%s " % beta
        if beta > 100:
            rst += "charlie:int:1 "
        elif pywapi.get_weather_from_noaa("KORD")["temp_c"] > 5:
            rst += "charlie:int:-1 "

    if state == "b":
        delta = pywapi.get_weather_from_noaa("KORD")["wind_mph"]
        rst += "delta:float:%s " % delta
    return rst
예제 #10
0
def update(state,time):
    print('updating continuous variables')
    print time
    t=float(time)
    rst=''
    if state == 'a':
        beta = t * 2.2
        rst+= 'beta:float:%s '%beta
        if beta > 100:
            rst += 'charlie:int:1 '
        elif pywapi.get_weather_from_noaa('KORD')['temp_c'] > 5:
            rst += 'charlie:int:-1 '
        
    if state == 'b':
        delta = pywapi.get_weather_from_noaa('KORD')['wind_mph']
        rst+= 'delta:float:%s '% delta
    return rst
예제 #11
0
def get_weather_data(station=None, location=None, stations=None, zipcodes=None):
    try:
        if location and not station:
            station = address2station(location, stations, zipcodes)
        noaa_result = pywapi.get_weather_from_noaa(station)
        return noaa_result
    except:
        print('weather error')
        sys.exit(0)
예제 #12
0
    def retrieveNOAAWeatherJson(self, cityCodes):
        # loop through city codes and append them to a list of 
        cityData = []

        # weather objects returned from pywapi
        for key, value in cityCodes.iteritems():
            cityData.append(pywapi.get_weather_from_noaa(value))

        # set the list of city json data 
        self.listOfCityData = cityData
예제 #13
0
 def _poll(self):
     """Refetch weather data if needed (based on time)"""
     if (datetime.datetime.now() - self.timestamp ) < self.timeout:
         return True
     logger.debug("Fetching Weather from %s", self.station)
     self.weather = pywapi.get_weather_from_noaa(self.station)
     self.timestamp = datetime.datetime.fromtimestamp(int(time.mktime(
                 email.utils.parsedate(
                     self.weather['observation_time_rfc822']))))
     return True
예제 #14
0
파일: orb.py 프로젝트: scarolan/weather_orb
def weather(interval):
    '''Fetches weather from NOAA XML feed, outputs the data to LCD and the 
    blinkM.  Update interval is specified in seconds.'''
    while True:
        printLCD('Weather Mode', 'Updating data...')
        sleep(1)
        # First fetch current weather from the NOAA feed
        noaa = pywapi.get_weather_from_noaa('KATT')
        conditions1 = noaa['weather']
        conditions2 = noaa['temp_f'] + 'F ' + noaa['pressure_mb'] + ' ' + noaa[
            'relative_humidity'] + '%'
        printLCD(conditions1, conditions2)
        # Now we set up the blinkM script
        blinkMStop()
        tempcolor = getTempRGB(float(noaa['temp_f']))
        checktime = time()
        # For manual testing
        #noaa['weather'] = 'Overcast'
        # Check for unusual weather conditions.
        if 'Tornado' in noaa['weather']:
            # The SOS script seems appropriate here
            os.system(blinkm + ' play-script -s 18')
            sleep(interval)
        elif 'Thunderstorm' in noaa['weather']:
            # We have a built-in thunderstorm script
            os.system(blinkm + ' play-script -s 16')
            sleep(interval)
        elif 'Rain' in noaa['weather'] or 'Drizzle' in noaa['weather']:
            # Gently fade between black and the temperature color
            while time() - checktime < interval:
                blinkMFade(*tempcolor, speed='16')
                sleep(2)
                blinkMFade(*rgb_black, speed='16')
                sleep(1)
        elif 'Snow' in noaa['weather'] or 'Hail' in noaa[
                'weather'] or 'Freezing' in noaa['weather']:
            # Gently fade between black and white
            while time() - checktime < interval:
                blinkMFade(*rgb_white, speed='16')
                sleep(2)
                blinkMFade(*rgb_black, speed='16')
                sleep(1)
        elif 'Mostly Cloudy' in noaa['weather'] or 'Overcast' in noaa[
                'weather'] or 'Fog' in noaa['weather']:
            # Gently fade between soft white and the temperature color
            while time() - checktime < interval:
                blinkMFade(*tempcolor, speed='4')
                sleep(4)
                blinkMFade('72', '72', '72', '4')
                sleep(2)
        else:
            # If none of the above apply, just set the temperature color
            blinkMFade(*tempcolor, speed='1')
            sleep(interval)
예제 #15
0
파일: weather.py 프로젝트: xe1gyq/NuupXe
    def noaa(self):

        print '[NuupXe] Weather NOAA'

        location = self.conf.get("weather", "location")
        result = pywapi.get_weather_from_noaa(location)

        message = "Reporte del Clima"
        message = message + ", Temperatura " + result['temp_c'] + " grados centigrados"
        message = message + ", Humedad " + result['relative_humidity'] + " por ciento"
        self.speaker.speechit(message)
        self.message = message
예제 #16
0
def get_weather_data(station=None,
                     location=None,
                     stations=None,
                     zipcodes=None):
    try:
        if location and not station:
            station = address2station(location, stations, zipcodes)
        noaa_result = pywapi.get_weather_from_noaa(station)
        return noaa_result
    except:
        print('weather error')
        sys.exit(0)
def fetchWeatherNoaa():
    """ every 300 calls check the weather """
    global g_noaa_result
    global g_noaa_cnt

    if g_noaa_cnt==0:
        try:
            tmp = pywapi.get_weather_from_noaa('KNYC')
            print "NOAA read: %s" % tmp
            g_noaa_result = tmp
        except:
            pass 
    g_noaa_cnt = (g_noaa_cnt+1) % 300   
예제 #18
0
파일: orb.py 프로젝트: scarolan/weather_orb
def weather(interval):
    '''Fetches weather from NOAA XML feed, outputs the data to LCD and the 
    blinkM.  Update interval is specified in seconds.'''
    while True:
        printLCD('Weather Mode','Updating data...')
        sleep(1)
        # First fetch current weather from the NOAA feed
        noaa = pywapi.get_weather_from_noaa('KATT')
        conditions1 = noaa['weather']
        conditions2 = noaa['temp_f']+'F '+noaa['pressure_mb']+' '+noaa['relative_humidity']+'%'
        printLCD(conditions1,conditions2)
        # Now we set up the blinkM script
        blinkMStop()
        tempcolor = getTempRGB(float(noaa['temp_f']))
        checktime = time()
        # For manual testing
        #noaa['weather'] = 'Overcast'
        # Check for unusual weather conditions.
        if 'Tornado' in noaa['weather']:
            # The SOS script seems appropriate here
            os.system(blinkm+' play-script -s 18')
            sleep(interval)
        elif 'Thunderstorm' in noaa['weather']:
            # We have a built-in thunderstorm script
            os.system(blinkm+' play-script -s 16')
            sleep(interval)
        elif 'Rain' in noaa['weather'] or 'Drizzle' in noaa['weather']:
            # Gently fade between black and the temperature color
            while time() - checktime < interval:
                blinkMFade(*tempcolor, speed='16')
                sleep(2)
                blinkMFade(*rgb_black, speed='16')
                sleep(1)
        elif 'Snow' in noaa['weather'] or 'Hail' in noaa['weather'] or 'Freezing' in noaa['weather']:
            # Gently fade between black and white
            while time() - checktime < interval:
                blinkMFade(*rgb_white, speed='16')
                sleep(2)
                blinkMFade(*rgb_black, speed='16')
                sleep(1)
        elif 'Mostly Cloudy' in noaa['weather'] or 'Overcast' in noaa['weather'] or 'Fog' in noaa['weather']:
            # Gently fade between soft white and the temperature color
            while time() - checktime < interval:
                blinkMFade(*tempcolor, speed='4')
                sleep(4)
                blinkMFade('72','72','72','4')
                sleep(2)
        else:
            # If none of the above apply, just set the temperature color
            blinkMFade(*tempcolor, speed='1')
            sleep(interval)
예제 #19
0
def main():
    pp = pprint.PrettyPrinter(indent=4)

    while True:
        result = pywapi.get_weather_from_noaa('KORD')
        pp.pprint(result['weather'])
        

        if (result['weather'] != 'Light Rain' or
            result['weather'] != 'Rain' or
            result['weather'] != 'Thunderstorm'):
                GPIO.output(25,GPIO.HIGH)
        sleep(10)
        GPIO.output(25,GPIO.LOW)
        sleep(2)
예제 #20
0
    def weather():
        """Backend function for weather proxy

        :return: A list of weather items
        """

        try:
            station = user.custom_data['wx']
        except:
            station = 'KMCN'

        # Construct weather

        weather_list = pywapi.get_weather_from_noaa(station)

        return weather_list
예제 #21
0
 def thread(self):
     """Thread for querying the weather."""
     initSleep = weather.initSleep
     weather.initSleep += 5
     time.sleep(initSleep)
     while True:
         try:
             noaa_result = pywapi.get_weather_from_noaa(self.station)
             self.forecast = noaa_result['temp_c'] + " C. " + \
                 noaa_result['weather']
             if DEBUG:
                 print "Forecast retrieved: %s" % self.forecast
         except Exception:
             self.forecast = "Failed to get forecast."
             if DEBUG:
                 print "Failed to get forecast."
         finally:
             time.sleep(weather.interval)
예제 #22
0
def temp(station_id):
    try:
        r = str(pywapi.get_weather_from_noaa(str(station_id)))
        x = r.find('temp_c')
        y = r.find('temp_f')
        if x != -1:
            c = r[x + 10:x + 14]
        if y != -1:
            f = r[y + 10:y + 14]
        else:
            return False
        # ts = time.time()
        ts = time.strftime("%b %d %H:%M:%S")
        t = {'ts': ts, 'C': c, 'F': f}
        return t
    except KeyboardInterrupt:
        exit
    except:
        print("Random Gen Error")
예제 #23
0
def get_weather(location_id='KSJC', weather_source='noaa'):
  if config.config['debug']:
    current_weather = parse_weather('cloudy rainy')
    current_weather.celcius = 30.0
    return current_weather

  if weather_source == 'noaa':
    noaa_result = pywapi.get_weather_from_noaa(location_id)
    current_weather = parse_weather(string.lower(noaa_result['weather']))
    current_weather.celcius = float(noaa_result['temp_c'])
  elif weather_source == 'yahoo':
    yahoo_result = pywapi.get_weather_from_yahoo(location_id)
    current_weather = parse_weather(string.lower(yahoo_result['condition']['text']))
    current_weather.celcius = float(yahoo_result['condition']['temp'])
  elif weather_source == 'weather_com':
    weather_com_result = pywapi.get_weather_from_weather_com(location_id)
    current_weather = parse_weather(string.lower(weather_com_result['current_conditions']['text']))
    current_weather.celcius = float(weather_com_result['current_conditions']['temperature'])
  return current_weather
def main():
    # prompt the user for a city
    user_input = input("Please input a city: ")
    # look up the code for that city
    noaa_code, zip_code = lookUpCityCode(user_input)

    # if the city is known, find the weather data
    if (noaa_code + zip_code):
        # gather data from both weather.com and noaa
        weather_com_result = pywapi.get_weather_from_weather_com(zip_code)
        noaa_result = pywapi.get_weather_from_noaa(noaa_code)
        
        # convert the weather.com temp from C to F
        weather_com_temp = celsiusToFahrenheit(float(weather_com_result['current_conditions']['temperature']))
        
        # output the results
        print ("Weather.com says the weather in "+ user_input + " is " + weather_com_result['current_conditions']['text'].lower() + " and the temperature is " + weather_com_temp + " F (" + weather_com_result['current_conditions']['temperature'] + " C).")

        print ("NOAA says the weather in "+ user_input + " is " + noaa_result['weather'].lower() + " and the temperature is " + noaa_result['temperature_string'] + ".")
예제 #25
0
def job():
    ACCOUNT_SID = ''
    AUTH_TOKEN = ''
    myNumber = ''
    twilioNumber = ''
    noaa_result = pywapi.get_weather_from_noaa('KPWT')

    from twilio.rest import TwilioRestClient
    import feedparser
    import json
    client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
    f = feedparser.parse('http://www.technewsworld.com/perl/syndication/rssfull.pl')

    newsload = json.loads(f)
    client.messages.create(
            to = myNumber,
            from_ = twilioNumber,
            body = "Good morning sir, I've went ahead and fetched you todays weather report\n" + "\n" + "Current Tech News: \n" + "\n" + repr(f.entries[0].summary_detail['value']) + "\n======================" + "\n""Current Weather\n " + "Weather is currently: " + noaa_result['weather'] + "\n" + "Temperature:" + noaa_result['temp_f'] +
                "F" + "\n" + noaa_result['wind_string']
        )
예제 #26
0
 def get_weather_data(self):
     station_id = g15gconf.get_string_or_default(self.gconf_client, "%s/station_id" % self.gconf_key, "KPEO")
     p = pywapi.get_weather_from_noaa(station_id)
     
     tm = email.utils.parsedate_tz(p["observation_time_rfc822"])[:9]
     data = {
         "location" : p["location"],
         "datetime" : datetime.datetime.fromtimestamp(time.mktime(tm)),
         "current_conditions" : {
             "wind_speed" : g15pythonlang.to_int_or_none(weather.mph_to_kph(float(p["wind_mph"]))) if "wind_mph" in p else None,
             "wind_direction" : g15pythonlang.to_int_or_none(p["wind_degrees"]) if "wind_degrees" in p else None,
             "pressure" : p["pressure_mb"] if "pressure_mb" in p else None,
             "humidity" : p["relative_humidity"] if "relative_humidity" in p else None,
             "condition" : p["weather"] if "weather" in p else None,
             "temp_c" : p["temp_c"] if "temp_c" in p else None,
             "icon" : self._get_icon(p["icon_url_name"]) if "icon_url_name" in p else None,
             "fallback_icon" : "http://w1.weather.gov/images/fcicons/%s" % ( "%s.jpg" % os.path.splitext(p["icon_url_name"])[0] ) if "icon_url_name" in p else None
         }
     }
             
     return data
예제 #27
0
def generateAndMailReport(recipient = 'default recipient', location = 'n2l6b6', airport = 'CYKF'):
  report = ""
  google_result = None
  yahoo_result = None
  noaa_result = None

  try:
    google_result = pywapi.get_weather_from_google(location)
  except:
    pass

  try:
    yahoo_result = pywapi.get_weather_from_yahoo(location)
  except:
    pass

  try:
    noaa_result = pywapi.get_weather_from_noaa(airport)
  except:
    pass

  report += "Current Conditions" + "\n"
  report += "------------------" + "\n"
  if google_result != None:
    report += "  Google: " + google_result['current_conditions']['temp_c'] + "C and " + google_result['current_conditions']['condition'] + "\n"
  if yahoo_result != None:
    report += "  Yahoo : " + yahoo_result['condition']['temp'] + "C and " + yahoo_result['condition']['text'] + "\n"
  if noaa_result != None:
    report += "  NOAA  : " + noaa_result['temp_c'] + "C and " + noaa_result['weather'] + "\n"
  report += "\n"

  for fore in google_result['forecasts']:
    report += "Google's Forecast (" + fore['day_of_week'] + ")" + "\n"
    report += "------------------" + "\n"
    report += "  High: %.1fC\n" % ((float(fore['high']) - 32.0) / (9.0/5.0))
    report += "  Low : %.1fC\n" % ((float(fore['low']) - 32.0) / (9.0/5.0))
    report += "  Cond: " + fore['condition'] + "\n"
    report += "\n"

  sendMail(recipient, '[WEATHER] Daily Weather Report for n2l6b6', report)
예제 #28
0
파일: thermo.py 프로젝트: mdarty/thermostat
def outdoor():
    """Retrieves weather from the airports"""
    global NOAA
    global ZIP
    try:
        w = pywapi.get_weather_from_noaa(NOAA)
        t = round(float(w[u'temp_f']), 1)
        h = round(float(w[u'relative_humidity']), 1)
        return t, h
    except:
        try:
            w = pywapi.get_weather_from_weather_com(ZIP)
            t = round(float(w[u'current_conditions'][u'temperature']), 1)
            h = round(float(w[u'current_conditions'][u'humidity']), 1)
            return t, h
        except:
            try:
                w = pywapi.get_weather_from_yahoo(ZIP)
                t = round(float(w[u'condition'][u'temp']), 1)
                h = round(float(w[u'atmosphere'][u'humidity']), 1)
                return t, h
            except:
                return 0, 0
예제 #29
0
 def update(self):
     noaa_result = pywapi.get_weather_from_noaa(self.noaa_city_code)
     self._celsius_temperature = float(noaa_result['temp_c'])
예제 #30
0
파일: getW4ny.py 프로젝트: gsadhas/SkyGraph
def noaany():
    rnoaany = pywapi.get_weather_from_noaa('KNYC')
    return rnoaany
예제 #31
0
파일: weather.py 프로젝트: bksg/weather
def getweathernoaa(loc):
    return pywapi.get_weather_from_noaa(loc)
예제 #32
0
파일: wxpoll.py 프로젝트: sodaphish/ptsh
import sys, urllib, time

sys.path.append('/home/hostedby/python/usr/lib/python2.4/site-packages')
import pywapi

sys.path.append('/home/hostedby/python/usr/lib64/python2.4/site-packages')
from pysqlite2 import dbapi2 as sqlite3

__debug = False

try:
    obs = pywapi.get_weather_from_noaa("KFSD")
except Exception, e:
    print "Weather retrieval error! (%s)" % e[0]

if __debug:
    for key in obs:
        print "%s: %s" % (key, obs[key])

try:
    # setup our database connection
    conn = sqlite3.connect('/home3/hostedby/public_html/mine/files/wx.db')
    sql = conn.cursor()
    sql.execute("CREATE TABLE IF NOT EXISTS observation \
		(date VARCHAR(32), \
		station VARCHAR(8), \
		temp NUMERIC(3,2), \
		dewpoint NUMERIC(3,2), \
		humidity NUMERIC(3,2), \
		pressure NUMERIC(3,2), \
		windir VARCHAR(16), \
예제 #33
0
            def Interface():
                '''
                The audio version, and the primary version of the interface.
                '''
                doss = os.getcwd()
                i=0
                n=0
                while (i<1):
                    r = sr.Recognizer()
                    with sr.Microphone() as source:
                        audio = r.adjust_for_ambient_noise(source)
                        n = (n+1)
                        audio = r.listen(source)
                        subprocess.call("sensors", shell=True)
                    '''
                    This uses the driver that is installed on the system
                    '''
                    try:
                        s = (r.recognize_google(audio))
                        print(s)
                        message = (s.lower())
                        # Paragon's main interface.
                        '''
                        Most of where this started was from a rather small github repo, in which I ammased this MONSTER code.
                        '''
                        if ('wikipedia') in message:
                            message = message.replace("wikipedia", "")
                            message = message.replace(" ", "_")
                            message = message.capitalize()
                            proxies = {
                            }
                            headers = {
                                "User-Agent": "Definitions/1.0"
                            }
                            params = {
                                'action':'query',
                                'prop':'extracts',
                                'format':'json',
                                'exintro':1,
                                'explaintext':1,
                                'generator':'search',
                                'gsrseParagonh':message,
                                'gsrlimit':1,
                                'continue':''
                            }
                            r = requests.get('http://en.wikipedia.org/w/api.php',
                                             params=params,
                                             headers=headers,
                                             proxies=proxies)
                            json1 = r.json1()
                            result = list(json1["query"]["pages"].items())[0][1]["extract"]
                            print(result)
                            rand = [(result) + '.']
                            Chrome = ("google-chrome %s")
                            webbrowser.get(Chrome)
                            webbrowser.open('https://en.wikipedia.org/wiki/' + message, new=2, autoraise=True)
                            Speech.say(rand,n,mixer)

                        if ('goodbye') in message:
                            rand = ['Goodbye ' + (datafile["Identity"][0]["pronouns"]), 'Paragon powering off']
                            Speech.say(rand,n,mixer)
                            break
                        if ('evening') in message:
                            rand = ['Good evening ' + (datafile["Identity"][0]["pronouns"])]
                            Speech.say(rand,n,mixer)

                        if ('morning') in message:
                            mTime = time.strftime('%B:%d:%Y')
                            rand = ['Good morning ' + (datafile["Identity"][0]["pronouns"]) + ', I grabbed the news for,' + mTime]
                            Chrome = ("google-chrome %s")
                            Speech.say(rand,n,mixer)
                            webbrowser.get(Chrome)
                            webbrowser.open('https://www.sciencenews.org/topic/math-technology', new=2, autoraise=True)
                            print ('')
                        if message == ('Paragon'):
                            rand = ['Yes Sir?', 'What can I, do for you ' + (datafile["Identity"][0]["pronouns"])]
                            Speech.say(rand,n,mixer)
                        if ('are we connected') in message:
                            REMOTE_SERVER = "www.google.com"
                            Speech.wifi()
                            rand = ['We are connected']
                            Speech.say(rand,n,mixer)
                        if ('.com') in message :
                            rand = ['Opening' + message]
                            Chrome = ("google-chrome %s")
                            Speech.say(rand,n,mixer)
                            webbrowser.get(Chrome).open('http://www.'+message)
                            print ('')
                        if ('.net') in message :
                            rand = ['Opening' + message]
                            Chrome = ("google-chrome %s")
                            Speech.say(rand,n,mixer)
                            webbrowser.get(Chrome).open('http://www.'+message)
                            print ('')
                        if ('.org') in message :
                            rand = ['Opening' + message]
                            Chrome = ("google-chrome %s")
                            Speech.say(rand,n,mixer)
                            webbrowser.get(Chrome).open('http://www.'+ message)
                            print ('')
                        if ('what is the time') in message or ('what time is it') in message or ('can you get me the current time') in message or ('can you tell me the time') in message:
                            lTime = time.strftime('%I:%M')
                            rand = ['the time is,' + lTime + ',sir.']
                            Speech.say(rand,n,mixer)
                        if ('what day is it') in message or ('what is the date') in message or ('date please') in message:
                            tDate = time.strftime('%B:%d:%Y')
                            rand = ['Today is,' + tDate + (datafile["Identity"][0]["pronouns"])]
                            Speech.say(rand,n,mixer)
                        if ('Paragon can you get me the weather') in message or ('can you get the weather') in message or ('Paragon weather please') in message or ('weather please') in message:
                            noaa_result = pywapi.get_weather_from_noaa('KPWT')
                            rand = ["I've fetched the weather for you." + "It is currently" + noaa_result['weather'] + '\n' + 'Current Temperature is: ' + noaa_result['temp_f'] +  'Degrees.'+ '\n' + 'Information grabbed from' + noaa_result['location']]
                            Speech.say(rand,n,mixer)
                        if ('can you get the news') in message or ('get the news please') in message or ('Paragon get the news please') in message:
                            rand = ['Fetching todays headlines, sir, please wait.']
                            Speech.say(rand,n,mixer)
                            time.sleep(5)
                            d = feedparser.parse('http://rss.nytimes.com/services/xml/rss/nyt/Science.xml')
                            rand = [d.feed['title'] + d.feed['description']]
                            Speech.say(rand,n,mixer)
                        if ('night mode') in message:
                            rand = ['Ok, sir, turning on your nightmode settings.']
                            Speech.say(rand,n,mixer)
                            subprocess.call("xbacklight -time 5000 -set 5", shell=True)
                            time.sleep(4)
                            rand = ['Ok sir, night mode is active.']
                            Speech.say(rand,n,mixer)
                        if ('day mode') in message:
                            rand = ['Ok,sir, turning on your daytime settings.']
                            Speech.say(rand,n,mixer)
                            subprocess.call("xbacklight -time 5000 -set 100", shell=True)
                            time.sleep(3)
                            rand = ['Ok sir, daytime mode is now active.']
                            Speech.say(rand,n,mixer)
                        if ('sleep mode') in message:
                            subprocess.call("xbacklight -time 5000 -set 0", shell=True)
                        if ('mute computer') in message or ('mute please') in message or ('mute') in message:
                            subprocess.call("pactl set-sink-mute 2 1", shell=True)
                        if ('unmute computer') in message or ('unmute please') in message or ('unmute') in message:
                            subprocess.call("pactl set-sink-mute 2 0", shell=True)
                        if ('Paragon log out') in message or ('log off') in message or ('log out protocol') in message or ('initiate logout protocol') in message:
                            rand = ['Logging out']
                            Speech.say(rand,n,mixer)
                            time.sleep(3)
                            subprocess.call("gnome-session-quit --no-prompt", shell=True)
                        if ('clean up your folder') in message or ("clean up protocol") in message or ('initiate cleanup protocol') in message:
                            rand = ['Ok sir, cleaning up my folders.']
                            Speech.say(rand,n,mixer)
                            subprocess.call("find . -name './Paragon/*.mp3' -delete", shell=True)
                        if ('monitor protocol') in message:
                            rand = ['Monitoring system functions, sir.']
                            Speech.say(rand,n,mixer)
                            time.sleep(1)
                            protocols.monitor_protocol()
                        if ('where is') in message:
                            rand = ['Searching for' + message + ', please wait.']
                            LocSrch_Message = message.replace("where is", "")
                            Chrome = ("google-chrome %s")
                            Speech.say(rand,n,mixer)
                            webbrowser.get(Chrome).open('http://www.'+ message)
                        if ('what is a') in message or ("what is an") in message:
                            if "an" in message:
                                message = message.replace("an ","")
                            if "a" in message:
                                message = message.replace("a ","")
                            spoken_def = Word(x).definitions
                            colist = str(len(spoken_def))
                            rand = ['Sir, there are ' + colist + 'entries, reading the first one: ' + spoken_def]
                            webbrowser.get(Chrome)
                            webbrowser.open("http://www.dictionary.com/browse/" + message)
                        if ('medical') in message:
                            #Searches the entire medical dictionary for a term of definition
                            term = message.replace("medical","")
                            import nltk.corpus
                            medical = open('./Paragon/Data/Databases/Medical_Dictionary.txt')
                            #Converts the text file into an actual corpus, the reason it isn't converted or loaded above,
                            #is because it would consume to many resources if it were constantly loaded.
                            text = medical.read()
                            text1 = text.split()
                            conc_term = nltk.corpus.nltk.Text(text1)
                            med_term = conc_term.concordance(term)
                            rand = [med_term]
                            Speech.say(rand,n,mixer)
                        wrdl1 = ['what city', 'address']
                        if wrdll in message
                            client = googlemaps.Client(key='register for a key here')
                            locaord = googlemaps.geolocation.geolocate(client, consider_ip=True)
                            lat = (locaord['location']['lat']);lng = (locaord['location']['lng'])
                            rgr = gmaps.reverse_geocode((lat, lng))
                            #Handle the index out of range error, since it will be thrown if there is not exactly
                            #ten completed iterations
                            try:
                                #There may be more then 10 results to returned, but the chances
                                #of them containing the correct result past that point is very low, the machine doesn't
                                #need to be concerned with accounting for them at that point.
                                for i in range(10):
                                    locsay = rgr[2]['address _components'][i]['long_name'])
                                    rand = [locsay]
                                    Speech.say(rand,n,mixer)
                            except IndexError:
                                print("")

                        else:
                            print(null_error)
                            #write message to a text file

                            #have the computer read that text file by checking for updated files, either by using time sleep and forcing an updated

                            #print that file readout here

                            #repeat using the else method

                    #exceptions
                    except (KeyboardInterrupt,SystemExit):
                        print("Goodbye, Paragon powering down now")
                        break
                    except sr.UnknownValueError:
                        print("error")
                    except sr.RequestError as e:
                        print("Error, no internet found.")
예제 #34
0
def mylocalweather():
    '''get current weather update for New York'''
    weather = pywapi.get_weather_from_noaa('KJFK')
    current = 'It is ' + weather['weather'] + ' and ' + weather[
        'temp_f'] + 'F right now in New York'
    return current
예제 #35
0
def getweather():
    data = pywapi.get_weather_from_noaa('KMDW')
    return data
예제 #36
0
#!/usr/bin/env python

import pywapi
import pprint
pp = pprint.PrettyPrinter(indent=4)

results = pywapi.get_weather_from_noaa("KIOW")
pp.pprint(results)
예제 #37
0
파일: test.py 프로젝트: annonch/IRTTAE
#!/usr/bin/python
##########################
#  [email protected]  #
##########################

import pywapi

delta = pywapi.get_weather_from_noaa('KORD')['wind_mph']
echo = pywapi.get_weather_from_noaa('KORD')['temp_c']
print delta
print echo
예제 #38
0
import pywapi
import string

google_result = pywapi.get_weather_from_google('10001')
yahoo_result = pywapi.get_weather_from_yahoo('10001')
noaa_result = pywapi.get_weather_from_noaa('KCLL')

#print ("Google says: It is " + (google_result['current_conditions']['condition']) + " and " + google_result['current_conditions']['temp_c'] + "C now in New York.\n\n")

#print ("Yahoo says: It is " + (yahoo_result['condition']['text']) + " and " + yahoo_result['condition']['temp'] + "C now in New York.\n\n")

print ("NOAA says: It is " + (noaa_result['weather']) + " and " + noaa_result['temp_f'] + "F in College Station.\n")
#!/usr/bin/env python

import pywapi
from temperature_logger import TemperatureLogger
from temperature_sensor import TemperatureSensor

# get area temperature
sensor = TemperatureSensor()
tempF = sensor.getTemperature()

# get outside temperature
noaaData = pywapi.get_weather_from_noaa('KCAK')
airportTempF = noaaData['temp_f']

# log temperature
logger = TemperatureLogger('garage')
logger.log(tempF, airportTempF)

예제 #40
0
파일: main.py 프로젝트: atedp/DisplayDemos
def main():
    epd = epd2in13b.EPD()
    epd.init()

    font = ImageFont.truetype(
        '/usr/share/fonts/truetype/freefont/FreeMono.ttf', 12)

    # weather stuff
    noaa_result = pywapi.get_weather_from_noaa('KBOS')
    temp = noaa_result['temp_f'] + " Degrees F"
    pressure = noaa_result['pressure_in'] + "inHg"
    wind_mph = noaa_result['wind_mph'] + ' mph'
    wind_dir = noaa_result['wind_dir']
    #wind = wind_mph + wind_dir
    weather = noaa_result['weather']
    obv_time = noaa_result['observation_time_rfc822']

    # clear the frame buffer
    frame_black = [0xFF] * (epd.width * epd.height / 8)
    frame_red = [0xFF] * (epd.width * epd.height / 8)

    # For simplicity, the arguments are explicit numerical coordinates
    epd.draw_filled_rectangle(frame_red, 1, 1, 102, 20, COLORED)
    #epd.draw_rectangle(frame_black, 1, 21, 102, 50, COLORED);
    epd.draw_rectangle(frame_red, 1, 150, 102, 220, COLORED)
    # Day of Week
    epd.draw_string_at(frame_black, 2, 22,
                       datetime.date.today().strftime("%A"), font, COLORED)
    # Day of Month
    epd.draw_string_at(frame_black, 2, 34,
                       datetime.date.today().strftime("%d"), font, COLORED)
    # Month
    epd.draw_string_at(frame_black, 20, 34,
                       datetime.date.today().strftime("%B"), font, COLORED)
    # Year
    # epd.draw_string_at(frame_black, 50, 34, datetime.date.today().strftime("%Y"), font, COLORED)

    # Display Weather Stuff
    epd.draw_string_at(frame_black, 2, 50, temp, font, COLORED)
    epd.draw_string_at(frame_black, 2, 70, wind_mph, font, COLORED)
    epd.draw_string_at(frame_black, 30, 90, wind_dir, font, COLORED)
    epd.draw_string_at(frame_black, 2, 110, pressure, font, COLORED)
    epd.draw_string_at(frame_black, 2, 130, weather, font, COLORED)
    #epd.draw_string_at(frame_red, 2, 150, obv_time, font, COLORED)
    #epd.draw_string_at(frame_red, 2, 170, temp, font, COLORED)

    epd.display_frame(frame_black, frame_red)
    """
    epd.draw_line(frame_black, 10, 60, 50, 100, COLORED);
    epd.draw_line(frame_black, 50, 60, 10, 100, COLORED);
    epd.draw_circle(frame_black, 80, 80, 15, COLORED);
    epd.draw_filled_rectangle(frame_red, 10, 120, 50, 180, COLORED);
    epd.draw_filled_rectangle(frame_red, 0, 6, 128, 26, COLORED);
    epd.draw_filled_circle(frame_red, 80, 150, 15, COLORED);
    """

    # write strings to the buffer
    """
    font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMono.ttf', 12)
    epd.draw_string_at(frame_black, 4, 30, "Saturday, June 30th", font, COLORED)
    epd.draw_string_at(frame_red, 6, 10, "Hi Caitie!!!", font, UNCOLORED)
    # display the frames
    epd.display_frame(frame_black, frame_red)
    """

    # display images
    """
    frame_black = epd.get_frame_buffer(Image.open('black.bmp'))
    frame_red = epd.get_frame_buffer(Image.open('red.bmp'))
    epd.display_frame(frame_black, frame_red)
    """
    # My Image Tests
    """
예제 #41
0
   while True:
      t, p, h = s.read_data(BME280.FARENHEIT, BME280.INHG)
      print("h={:.2f} p={:.1f} t={:.2f}".format(h, p/100.0, t))

      try:
        conn = MySQLdb.connect(host=MYSQL_DATABASE_HOST, user=MYSQL_DATABASE_USER, passwd=MYSQL_DATABASE_PASSWORD, db=MYSQL_DATABASE_DB)
        
        cursor = conn.cursor()
        cursor.execute("INSERT INTO SensorData SET location='%s', moduleID=%s, temperature=%f, humidity=%f, light=0, occupied=0"% (MODULENAME, MODULEID, round(t,1), round(h,2)))
        conn.commit()

        if cycleCount >= 5:
          cycleCount = 0
          # Get the outside weather and log it
          logger.info("Getting outside weather")
          weatherDict = pywapi.get_weather_from_noaa(WEATHER_ID)
          #print(weatherDict)
          temp_f = weatherDict['temp_f']
          humid = weatherDict['relative_humidity']

          cursor.execute("INSERT SensorData SET moduleID=%s, location='outside', temperature=%f, humidity=%f "%(OUTSIDE_ID,round(float(temp_f),1), round(float(humid),2)))

          conn.commit()

        cursor.close()
        conn.close()

        cycleCount = cycleCount + 1
      except Exception as err:
        logger.error("Error %s" % (err))
    time.sleep(4.5)
 
    lber = response.split('\n')[2].split('\t')[-1][:-1]
    lrsl = response.split('\n')[3].split('\t')[-1][:-1]

    if 'performance data is not available' in response:
        rber = 1
        rrsl = 0
    else:
        rber = response.split('\n')[11].split('\t')[-1][:-1]
        rrsl = response.split('\n')[12].split('\t')[-1][:-1]

    # update weather every 5 minutes (NOAA only updates every hour..)
    if (i % 60) == 0:
        print 'updating weather'
        noaa = pywapi.get_weather_from_noaa(noaastation)
        wind = noaa['wind_mph']
#wind_gust = noaa['wind_gust_mph']
        wind_gust = 0 #wind gust field doesn't work on PADQ 
        wind_deg = noaa['wind_degrees'] 
        weather = noaa['weather']
        temp = noaa['temp_f']

    print 'rber: ' + str(rber) + ' rrsl: ' + str(rrsl) + ' lber: ' + str(lber) + ' lrsl: ' + str(lrsl)
    print 'wind: ' + wind  
    csvwriter.writerow([time.asctime(time.localtime()), str(time.time()), str(lrsl), str(lber), str(rrsl), str(rber), wind, wind_gust, wind_deg, weather, temp])


tn.close()
csvfile.close()
예제 #43
0
        sys.exit()

if __name__ == '__main__':
    # Skip the first line which contains the version header.
    print_line(read_line())
    # The second line contains the start of the infinite array.
    print_line(read_line())
    while True:
        line, prefix = read_line(), ''
        # ignore comma at start of lines
        if line.startswith(','):
            line, prefix = line[1:], ','

        j = json.loads(line)
        # insert information into the start of the json, but could be anywhere
        # CHANGE THIS LINE TO INSERT SOMETHING ELSE
        try:
            noaa_result = pywapi.get_weather_from_noaa('KBCB')
            temp = string.lower(noaa_result['temp_c']) + "C"
            weather_cond = string.lower(noaa_result['weather'])
        except:
            temp = "DISCONNECTED"
            weather_cond = "DISCONNECTED"

        j.insert(0, {'full_text' : '%s' % get_room_temp(), 'name' : 'gov'})
        j.insert(0, {'full_text' : '%s' % temp, 'name' : 'gov'})
        j.insert(0, {'full_text' : '%s' % weather_cond, 'name' : 'gov'})
        # and echo back new encoded json
        print_line(prefix+json.dumps(j))

예제 #44
0
import pywapi
import pprint
import string
pp = pprint.PrettyPrinter(indent=4)

print "Google:"
google_result = pywapi.get_weather_from_google('07960')
pp.pprint(google_result)

print "\n\nNOAA:"
noaa_result = pywapi.get_weather_from_noaa('KMMU')
pp.pprint(noaa_result)

print "\n\nGoogle says: It is " + string.lower(google_result['current_conditions']['condition']) + " and " + google_result['current_conditions']['temp_c'] + "C now in Morristown."

print "NOAA says: It is " + string.lower(noaa_result['weather']) + " and " + noaa_result['temp_c'] + "C now in Morristown.\n"

# http://code.google.com/p/python-weather-api/ 
예제 #45
0
def weather():
	import pywapi
	wi = pywapi.get_weather_from_noaa('KFWA')
	print("Temperature : " + wi['temp_c']+" C"+"\nWeather Condition : " + wi['weather']+"\nRelative Humidity : " + wi['relative_humidity']+"\nPressure : " + wi['pressure_string']+"\nWindchill : " + wi['windchill_c']+" C"+"\nWind Direction : " + wi['wind_dir']+"\nWind Speed : " + wi['wind_mph']+" MPH")
#!/usr/bin/env python

import pywapi
import pprint
pp = pprint.PrettyPrinter(indent=4)

result = pywapi.get_weather_from_noaa('KJFK')
pp.pprint(result)
예제 #47
0
파일: getW4ho.py 프로젝트: gsadhas/SkyGraph
def noaaho():
    rnoaaho = pywapi.get_weather_from_noaa('KHOU')
    return rnoaaho
예제 #48
0
import pywapi
import string

weather_com_result = pywapi.get_weather_from_weather_com('10001')

filename = raw_input('Please enter a zipcode: ')
yahoo_result = pywapi.get_weather_from_yahoo(filename)
noaa_result = pywapi.get_weather_from_noaa('KJFK')

# print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York.\n\n"

print "Yahoo says: It is " + string.lower(
    yahoo_result['condition']['text']
) + " and " + yahoo_result['condition']['temp'] + "C now in New York.\n\n"
print "this is the city : " + string.lower(yahoo_result['location']['city'])
# print "NOAA says: It is " + string.lower(noaa_result['weather']) + " and " + noaa_result['temp_c'] + "C now in New York.\n"
예제 #49
0
파일: getW4sa.py 프로젝트: gsadhas/SkyGraph
def noaasa():
    rnoaasa = pywapi.get_weather_from_noaa('KMRY')
    return rnoaasa
예제 #50
0
def get_dewpoint_f():
        noaa_result = pywapi.get_weather_from_noaa('KHOU')
        return  float(noaa_result['dewpoint_f'])
예제 #51
0
# Pablo Sanchez
# Python version 2.7.16
# Weather API


# The wind direction and wind chill in Fahrenheit for the New York, La Guardia Airport.
# NOTE: replaced Wind Chill with Wind Speed as Wind Chill is no longer available.

import pywapi
import pprint

pp = pprint.PrettyPrinter(indent=4)
weather = pywapi.get_weather_from_noaa('KLGA')
loc1 = 'New York, La Guardia Airport'
loc2 = 'Bartlesville Municipal Airport'

print('Weather details for ' + loc1 + '.')
pp.pprint('Wind Direction: ' + weather['wind_dir'])
pp.pprint('Wind Speed: ' + weather['wind_mph'])
print ('-'*50)

# The longitude, latitude, and dew point in Fahrenheit for Bartlesville Municipal Airport.

weather = pywapi.get_weather_from_noaa('KBVO')
print('Weather details for ' + loc2 + '.')
pp.pprint('Latitude: ' + weather['latitude'])
pp.pprint('Longitude: ' + weather['longitude'])
pp.pprint('Dew Point: ' + weather['dewpoint_f'])
예제 #52
0
import sys
import pywapi
import string
import random
import math
sys.path.append("./osc")
from animations import FadeAnimation

weather = pywapi.get_weather_from_noaa('KCMI')
#Seattle- KBFI Phoenix- KPHX Urbana- KCMI
temp = weather['temp_f']
conditions = weather['weather']
#conditions = "Heavy Thunderstorm"



if conditions.find("Mostly") > -1:
	cloud = 0.5
elif conditions.find("Partly") > -1:
	cloud = 0.8
elif conditions.find("Few") > -1:
	cloud = 1.0
else:
	cloud = 0.4
if conditions.find("Heavy") > -1:
	severe = 0.02
elif conditions.find("Light") > -1:
	severe = 0.2
else:
	severe = 0.05
i = 0
예제 #53
0
    def today(self):

        #Grab weather data for College Station (Code is KCLL)
        noaa = pywapi.get_weather_from_noaa('KCLL')
        noaa_cond = noaa['weather']

        #Determine if day or night
        hour = int(datetime.datetime.now().strftime('%H'))
        hour_day = (hour >= 7 and hour < 20)

        #Comments displayed at bottom
        compliment_size = 40
        compliment_array = [('You look beautiful today!', 50),
                            ('You light up every room!', 50),
                            ('You are a force of nature!', 50),
                            ("Lookin' good as always!", 50),
                            ("No one can do this better than you!", 35),
                            ("#flawless", 70)]
        compliment = ""

        if ('Mostly Cloudy' in noaa_cond):
            if (hour_day):  #daytime
                img = PhotoImage(file='cloud_sun.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)
                compliment = "Be the ray of sunshine today!"

            else:  #nighttime
                img = PhotoImage(file='cloud_moon.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.place(x=0, y=0)

        elif ('Windy' in noaa_cond):
            compliment = "You blow me away!"
            compliment_size = 60

            if (hour_day):
                img = PhotoImage(file='windy_day.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)

            else:
                img = PhotoImage(file='windy_night.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)

        elif ('Fair' in noaa_cond or 'Clear' in noaa_cond):
            if (hour_day):
                img = PhotoImage(file='bright_sun.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)
                #compliment = "You shine brighter than the sun!"

            else:
                img = PhotoImage(file='moon.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)
                compliment = "You shine brighter than the moon!"

        elif ('A Few Clouds' in noaa_cond):
            if (hour_day):
                img = PhotoImage(file='cloud_sun.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)
                compliment = "Be the ray of sunshine today!"

            else:
                img = PhotoImage(file='cloud_moon.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)

        elif ('Partly Cloudy' in noaa_cond):
            if (hour_day):
                img = PhotoImage(file='cloud_sun.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)
                compliment = "Be the ray of sunshine today!"

            else:
                img = PhotoImage(file='cloud_moon.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)

        elif ('Overcast' in noaa_cond):
            img = PhotoImage(file='cloudy.png')
            panel = Tkinter.Label(self, image=img, fg='white', bg='black')
            panel.image = img
            panel.place(x=0, y=0)
            compliment = "You are sunshine on a cloudy day!"

        elif ('Fog' in noaa_cond):
            img = PhotoImage(file='fog.png')
            panel = Tkinter.Label(self, image=img, fg='white', bg='black')
            panel.image = img
            panel.place(x=0, y=0)

        elif ('Thunderstorm' in noaa_cond):
            compliment = "Your smile is striking!"
            compliment_size = 60

            if (hour_day):
                img = PhotoImage(file='thunder_sun.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)

            else:
                img = PhotoImage(file='thunder_moon.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)

        elif ('Rain' in noaa_cond or 'Drizzle' in noaa_cond):
            if (hour_day):
                img = PhotoImage(file='rain_sun.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)
                compliment = "Fo' drizzle, you looking good today!"
                compliment_size = 35

            else:
                img = PhotoImage(file='rain_moon.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)
                compliment = "Fo' drizzle, you looking good today!"
                compliment_size = 35

        else:
            if (hour_day):
                img = PhotoImage(file='bright_sun.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)

            else:
                img = PhotoImage(file='moon.png')
                panel = Tkinter.Label(self, image=img, fg='white', bg='black')
                panel.image = img
                panel.place(x=0, y=0)

        noaa_temp = noaa['temp_f']
        temp_display = Tkinter.Label(self,
                                     text=noaa_temp + ' F',
                                     font=('verdana', 60, 'bold'),
                                     fg='white',
                                     bg='black')
        temp_display.place(x=256, y=15)

        weather_com = pywapi.get_weather_from_weather_com('77840', 'imperial')
        today_data = weather_com['forecasts'][0]
        temp_high_display = Tkinter.Label(self,
                                          text=today_data['high'],
                                          font=('verdana', 40, 'bold'),
                                          fg='white',
                                          bg='black')
        temp_low_display = Tkinter.Label(self,
                                         text=today_data['low'],
                                         font=('verdana', 40, 'bold'),
                                         fg='white',
                                         bg='black')
        high_low_diff = Tkinter.Label(self,
                                      text="/",
                                      font=('verdana', 60, 'bold'),
                                      fg='white',
                                      bg='black')
        temp_high_display.place(x=305, y=135)
        temp_low_display.place(x=410, y=155)
        high_low_diff.place(x=380, y=130)

        today_condition_display = Tkinter.Label(self,
                                                text="Today: " + noaa_cond,
                                                font=('veranda', 20, 'bold'),
                                                fg='white',
                                                bg='black')
        today_condition_display.place(x=0, y=255)

        tomorrow_data = weather_com['forecasts'][1]
        tomorrow = "Tomorrow: " + tomorrow_data['day'][
            'text'] + ". High of " + tomorrow_data['high'] + " F"
        tomorrow_display = Tkinter.Label(self,
                                         text=tomorrow,
                                         font=('verdana', 20, 'bold'),
                                         fg='white',
                                         bg='black')
        tomorrow_display.place(x=0, y=290)

        if (compliment == ""):
            random_compliment = random.randint(0, 5)
            compliment = compliment_array[random_compliment][0]
            compliment_size = compliment_array[random_compliment][1]

        compliment_label = Tkinter.Label(self,
                                         text=compliment,
                                         font=('DejaVu Serif', compliment_size,
                                               'italic bold'),
                                         fg='white',
                                         bg='black')
        compliment_label.pack(side=BOTTOM, anchor=S, pady=30)
예제 #54
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import pywapi

# Get the current conditions for the given station.
noaa = pywapi.get_weather_from_noaa('KAPA')

# This is the list of output lines.
out = []

# Go through the dictionaries and construct a list of the desired output lines.
out.append(u'%.0f° F (%.0f° C)' % (float(noaa['temp_f']), float(noaa['temp_c'])))

# Print the output
print '\n'.join(out).encode('utf8')
예제 #55
0
import pywapi
import string

weather_com_result = pywapi.get_weather_from_weather_com('92120')
noaa_result = pywapi.get_weather_from_noaa('KSAN')

print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in San Diego.\n\n"

print "NOAA says: It is " + string.lower(noaa_result['weather']) + " and " + noaa_result['temp_f'] + "F now at Lindberg Field.\n" 
예제 #56
0
def today():

    root = tkinter.Tk()
    root.geometry('1050x1680')
    root.configure(background='black')
    root.attributes('-fullscreen', True)

    #CLOCK ###################################################################################
    clock = tkinter.Label(root,
                          font=('verdana', 100, 'bold'),
                          fg='white',
                          bg='black')
    clock.pack(anchor=NE, pady=.1)
    tick("", clock)

    ##########################################################################################

    #DATE ####################################################################################
    the_date = datetime.date.today().strftime(
        '%A') + ', ' + datetime.date.today().strftime(
            '%B') + " " + datetime.date.today().strftime('%d')
    input_date = tkinter.Label(root,
                               text=the_date,
                               font=('verdana', 31, 'bold'),
                               fg='white',
                               bg='black')
    input_date.pack(anchor=NE, pady=.5)

    ##########################################################################################

    #WEATHER #################################################################################
    noaa = pywapi.get_weather_from_noaa('KCLL')
    noaa_cond = noaa['weather']

    #noaa_cond = 'Thunderstorms' #test case
    print(noaa_cond)

    hour = int(datetime.datetime.now().strftime('%H'))
    #    hour = 22 #test case
    hour_day = (hour >= 7 and hour < 20)
    compliment_size = 40
    compliment_array = [('You look beautiful today!', 50),
                        ('You light up every room!', 50),
                        ('You are a force of nature!', 50),
                        ("Lookin' good as always!", 50),
                        ("No one can do this better than you!", 35),
                        ("#flawless", 70)]
    compliment = ""
    if ('Mostly Cloudy' in noaa_cond):
        if (hour_day):  #daytime
            img = PhotoImage(file='cloud_sun.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)
            compliment = "Be the ray of sunshine today!"
        else:
            img = PhotoImage(file='cloud_moon.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)

    elif ('Windy' in noaa_cond):
        compliment = "You blow me away!"
        compliment_size = 60
        if (hour_day):
            img = PhotoImage(file='windy_day.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)
        else:
            img = PhotoImage(file='windy_night.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)

    elif ('Fair' in noaa_cond or 'Clear' in noaa_cond):
        if (hour_day):
            img = PhotoImage(file='bright_sun.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)
            #compliment = "You shine brighter than the sun!"
        else:
            img = PhotoImage(file='moon.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)
            compliment = "You shine brighter than the moon!"

    elif ('A Few Clouds' in noaa_cond):
        if (hour_day):
            img = PhotoImage(file='cloud_sun.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)
            compliment = "Be the ray of sunshine today!"
        else:
            img = PhotoImage(file='cloud_moon.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)

    elif ('Partly Cloudy' in noaa_cond):
        if (hour_day):
            img = PhotoImage(file='cloud_sun.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)
            compliment = "Be the ray of sunshine today!"
        else:
            img = PhotoImage(file='cloud_moon.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)

    elif ('Overcast' in noaa_cond):
        img = PhotoImage(file='cloudy.png')
        panel = tkinter.Label(root, image=img, fg='white', bg='black')
        panel.place(x=0, y=0)
        compliment = "You are sunshine on a cloudy day!"

    elif ('Fog' in noaa_cond):
        img = PhotoImage(file='fog.png')
        panel = tkinter.Label(root, image=img, fg='white', bg='black')
        panel.place(x=0, y=0)

    elif ('Thunderstorm' in noaa_cond):
        compliment = "Your smile is striking!"
        compliment_size = 60
        if (hour_day):
            img = PhotoImage(file='thunder_sun.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)
        else:
            img = PhotoImage(file='thunder_moon.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)

    elif ('Rain' in noaa_cond or 'Drizzle' in noaa_cond):
        if (hour_day):
            img = PhotoImage(file='rain_sun.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)
            compliment = "Fo' drizzle, you looking good today!"
            compliment_size = 35
        else:
            img = PhotoImage(file='rain_moon.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)
            compliment = "Fo' drizzle, you looking good today!"
            compliment_size = 35

    else:
        if (hour_day):
            img = PhotoImage(file='bright_sun.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)
        else:
            img = PhotoImage(file='moon.png')
            panel = tkinter.Label(root, image=img, fg='white', bg='black')
            panel.place(x=0, y=0)

    noaa_temp = noaa['temp_f']
    temp_display = tkinter.Label(root,
                                 text=noaa_temp + ' F',
                                 font=('verdana', 60, 'bold'),
                                 fg='white',
                                 bg='black')
    #temp_display.pack(anchor=W)
    temp_display.place(x=256, y=15)

    weather_com = pywapi.get_weather_from_weather_com('77840', 'imperial')
    today_data = weather_com['forecasts'][0]
    temp_high_display = tkinter.Label(root,
                                      text=today_data['high'],
                                      font=('verdana', 40, 'bold'),
                                      fg='white',
                                      bg='black')
    temp_low_display = tkinter.Label(root,
                                     text=today_data['low'],
                                     font=('verdana', 40, 'bold'),
                                     fg='white',
                                     bg='black')
    high_low_diff = tkinter.Label(root,
                                  text="/",
                                  font=('verdana', 60, 'bold'),
                                  fg='white',
                                  bg='black')
    temp_high_display.place(x=305, y=135)
    temp_low_display.place(x=410, y=155)
    high_low_diff.place(x=380, y=130)

    today_condition_display = tkinter.Label(root,
                                            text="Today: " + noaa_cond,
                                            font=('veranda', 20, 'bold'),
                                            fg='white',
                                            bg='black')
    today_condition_display.place(x=0, y=255)

    tomorrow_data = weather_com['forecasts'][1]
    tomorrow = "Tomorrow: " + tomorrow_data['day'][
        'text'] + ". High of " + tomorrow_data['high'] + " F"
    tomorrow_display = tkinter.Label(root,
                                     text=tomorrow,
                                     font=('verdana', 20, 'bold'),
                                     fg='white',
                                     bg='black')
    tomorrow_display.place(x=0, y=290)

    if (compliment == ""):
        random_compliment = random.randint(0, 4)
        compliment = compliment_array[random_compliment][0]
        compliment_size = compliment_array[random_compliment][1]

    compliment_label = tkinter.Label(root,
                                     text=compliment,
                                     font=('DejaVu Serif', compliment_size,
                                           'italic bold'),
                                     fg='white',
                                     bg='black')
    compliment_label.pack(side=BOTTOM, anchor=S, pady=30)
    #lookupString.place(x=305,y=240)
    # city_display = tkinter.Label(root,text='College Station, TX',font=('verdana',30,'bold'),fg='white',bg='black')
    # city_display.place(x=0,y=325)

    ##########################################################################################

    root.mainloop()

    while (1):
        global MAT
        #print("YO")
        if (GPIO.input(MAT) == 1):
            root.quit()
            print("y")
예제 #57
0
#!/usr/bin/env python

import pywapi

weather_com_result = pywapi.get_weather_from_weather_com('78728')
yahoo_result = pywapi.get_weather_from_yahoo('78728')
noaa_result = pywapi.get_weather_from_noaa('KATT')

print "Weather.com says: It is " + weather_com_result['current_conditions'][
    'text'].lower() + " and " + str(
        float(weather_com_result['current_conditions']['temperature']) * 1.8 +
        32.0) + "F now in Austin"

print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() +
      " and " + str(float(yahoo_result['condition']['temp']) * 1.8 + 32.0) +
      "F now in Austin.")

print("NOAA says: It is " + noaa_result['weather'].lower() + " and " +
      noaa_result['temp_c'] + "C now in Austin.")