Ejemplo n.º 1
0
 def get_api_request(self, request=None, is_json=True, postdata=None, headers=None, dictify=True):
     """
     Make the request to the API by passing a url request string
     """
     if utils.get_timestamp(self.req_connect_err):
         return {} if dictify else None  # Connection error in last minute for this api so don't keep trying
     if self.req_wait_time:
         utils.rate_limiter(addon_name=self.cache_name, wait_time=self.req_wait_time, api_name=self.req_api_name)
     try:
         response = requests.post(request, data=postdata, headers=headers) if postdata else requests.get(request, headers=headers)  # Request our data
     except Exception as err:
         self.req_connect_err = utils.set_timestamp()
         xbmcgui.Window(10000).setProperty(self.req_connect_err_prop, str(self.req_connect_err))
         utils.kodi_log(u'ConnectionError: {}\nSuppressing retries for 1 minute'.format(err), 1)
         return {} if dictify else None
     if not response.status_code == requests.codes.ok and utils.try_parse_int(response.status_code) >= 400:  # Error Checking
         if response.status_code == 401:
             utils.kodi_log(u'HTTP Error Code: {0}\nRequest: {1}\nPostdata: {2}\nHeaders: {3}\nResponse: {4}'.format(response.status_code, request, postdata, headers, response), 1)
             self.invalid_apikey()
         elif response.status_code == 500:
             self.req_connect_err = utils.set_timestamp()
             xbmcgui.Window(10000).setProperty(self.req_connect_err_prop, str(self.req_connect_err))
             utils.kodi_log(u'HTTP Error Code: {0}\nRequest: {1}\nSuppressing retries for 1 minute'.format(response.status_code, request), 1)
         elif utils.try_parse_int(response.status_code) > 400:  # Don't write 400 error to log
             utils.kodi_log(u'HTTP Error Code: {0}\nRequest: {1}'.format(response.status_code, request), 1)
         return {} if dictify else None
     if dictify and is_json:
         response = response.json()  # Make the response nice
     elif dictify:
         response = self.translate_xml(response)
     return response
Ejemplo n.º 2
0
def fetchAltDaily(num):

    latlong = ADDON.getSetting('Location' + str(num) + "LatLong")
    latitude = latlong.rsplit(',', 1)[0]
    longitude = latlong.rsplit(',', 1)[1]

    url = "https://forecast.weather.gov/MapClick.php?lon=" + longitude + "&lat=" + latitude + "&FcstType=json"
    log('forecast url: %s' % url)

    daily_weather = get_url_JSON(url)

    ####	[{"Title": t, "Score": s} for t, s in zip(titles, scores)]if daily_weather and daily_weather != '' and 'data' in daily_weather:
    if daily_weather and daily_weather != '' and 'data' in daily_weather:

        dailydata = [{
            "startPeriodName": a,
            "startValidTime": b,
            "tempLabel": c,
            "temperature": d,
            "pop": e,
            "weather": f,
            "iconLink": g,
            "hazard": h,
            "hazardUrl": i,
            "text": j
        } for a, b, c, d, e, f, g, h, i, j in zip_x(
            None, daily_weather['time']['startPeriodName'],
            daily_weather['time']['startValidTime'], daily_weather['time']
            ['tempLabel'], daily_weather['data']['temperature'],
            daily_weather['data']['pop'], daily_weather['data']['weather'],
            daily_weather['data']['iconLink'], daily_weather['data']['hazard'],
            daily_weather['data']['hazardUrl'], daily_weather['data']['text'])]

    else:
        xbmc.log('failed to retrieve weather data from : %s' % url,
                 level=xbmc.LOGERROR)
        xbmc.log('%s' % daily_weather, level=xbmc.LOGERROR)
        return None

    for count, item in enumerate(dailydata):
        #code = str(item['weather'][0].get('id',''))

        icon = item['iconLink']

        #https://api.weather.gov/icons/land/night/ovc?size=small
        #icon=icon.rsplit('?', 1)[0]
        code, rain = code_from_icon(icon)
        #xbmc.log('icon %s' % icon,level=xbmc.LOGINFO)
        #xbmc.log('code %s' % code,level=xbmc.LOGINFO)
        weathercode = WEATHER_CODES.get(code)

        starttime = item['startValidTime']
        startstamp = get_timestamp(starttime)
        set_property('Day%i.Title' % (count), item['startPeriodName'])

        #		if item['tempLabel'] == 'High':
        #			set_property('Day%i.HighTemp'	% (count), str(FtoC(item['temperature'])))
        #		if item['tempLabel'] == 'Low':
        #			set_property('Day%i.LowTemp'	% (count), str(FtoC(item['temperature'])))
        set_property('Day%i.Outlook' % (count), item['weather'])
        set_property('Day%i.Details' % (count), item['text'])
        set_property('Day%i.OutlookIcon' % (count), weathercode)
        set_property('Day%i.RemoteIcon' % (count), icon)

        # NOTE: Day props are 0 based, but Daily/Hourly are 1 based
        ####set_property('Daily.%i.isDaytime'	% (count+1),str(item['isDaytime']))
        set_property('Daily.%i.Outlook' % (count + 1), item['text'])
        set_property('Daily.%i.ShortOutlook' % (count + 1), item['weather'])

        set_property('Daily.%i.RemoteIcon' % (count + 1), icon)
        set_property('Daily.%i.OutlookIcon' % (count + 1),
                     WEATHER_ICON % weathercode)
        set_property('Daily.%i.FanartCode' % (count + 1), weathercode)
        ##set_property('Daily.%i.WindDirection'	% (count+1), item['windDirection'])
        ##set_property('Daily.%i.WindSpeed'	% (count+1), item['windSpeed'])

        if item['tempLabel'] == 'High':
            set_property('Daily.%i.LongDay' % (count + 1),
                         item['startPeriodName'])
            set_property('Daily.%i.ShortDay' % (count + 1),
                         get_weekday(startstamp, 's') + " (d)")
            set_property('Daily.%i.TempDay' % (count + 1),
                         u'%s\N{DEGREE SIGN}%s' % (item['temperature'], "F"))
            set_property('Daily.%i.HighTemperature' % (count + 1),
                         u'%s\N{DEGREE SIGN}%s' % (item['temperature'], "F"))
            set_property('Daily.%i.TempNight' % (count + 1), '')
            set_property('Daily.%i.LowTemperature' % (count + 1), '')
        if item['tempLabel'] == 'Low':
            set_property('Daily.%i.LongDay' % (count + 1),
                         item['startPeriodName'])
            set_property('Daily.%i.ShortDay' % (count + 1),
                         get_weekday(startstamp, 's') + " (n)")
            set_property('Daily.%i.TempDay' % (count + 1), '')
            set_property('Daily.%i.HighTemperature' % (count + 1), '')
            set_property('Daily.%i.TempNight' % (count + 1),
                         u'%s\N{DEGREE SIGN}%s' % (item['temperature'], "F"))
            set_property('Daily.%i.LowTemperature' % (count + 1),
                         u'%s\N{DEGREE SIGN}%s' % (item['temperature'], "F"))
        #set_property('Daily.%i.LongDay'		% (count+1), get_weekday(startstamp, 'l'))
        #set_property('Daily.%i.ShortDay'		% (count+1), get_weekday(startstamp,'s'))
        if DATEFORMAT[1] == 'd' or DATEFORMAT[0] == 'D':
            set_property('Daily.%i.LongDate' % (count + 1),
                         get_month(startstamp, 'dl'))
            set_property('Daily.%i.ShortDate' % (count + 1),
                         get_month(startstamp, 'ds'))
        else:
            set_property('Daily.%i.LongDate' % (count + 1),
                         get_month(startstamp, 'ml'))
            set_property('Daily.%i.ShortDate' % (count + 1),
                         get_month(startstamp, 'ms'))

        rain = str(item['pop'])
        if (rain != ''):
            set_property('Daily.%i.Precipitation' % (count + 1), rain + '%')
        else:
            set_property('Daily.%i.Precipitation' % (count + 1), '')

#		set_property('Daily.%i.WindDegree'	% (count+1), str(item.get('deg','')) + u'\N{DEGREE SIGN}')
#		set_property('Daily.%i.Humidity'	% (count+1), str(item.get('humidity','')) + '%')
#		set_property('Daily.%i.TempMorn'	% (count+1), TEMP(item['temp']['morn']) + TEMPUNIT)
#		set_property('Daily.%i.TempDay'		% (count+1), TEMP(item['temp']['day']) + TEMPUNIT)
#		set_property('Daily.%i.TempEve'		% (count+1), TEMP(item['temp']['eve']) + TEMPUNIT)
#		set_property('Daily.%i.TempNight'	% (count+1), TEMP(item['temp']['night']) + TEMPUNIT)
#		set_property('Daily.%i.HighTemperature' % (count+1), TEMP(item['temp']['max']) + TEMPUNIT)
#		set_property('Daily.%i.LowTemperature'	% (count+1), TEMP(item['temp']['min']) + TEMPUNIT)
#		set_property('Daily.%i.FeelsLike'	% (count+1), FEELS_LIKE(item['temp']['day'], item['speed'] * 3.6, item['humidity']) + TEMPUNIT)
#		set_property('Daily.%i.DewPoint'	% (count+1), DEW_POINT(item['temp']['day'], item['humidity']) + TEMPUNIT)

    if daily_weather and daily_weather != '' and 'currentobservation' in daily_weather:
        data = daily_weather['currentobservation']
        #xbmc.log('data %s' % data,level=xbmc.LOGINFO)
        icon = "http://forecast.weather.gov/newimages/large/%s" % data.get(
            'Weatherimage')
        code, rain = code_from_icon(icon)
        weathercode = WEATHER_CODES.get(code)
        set_property('Current.Location', data.get('name'))
        set_property('Current.RemoteIcon', icon)
        set_property(
            'Current.OutlookIcon', '%s.png' %
            weathercode)  # xbmc translates it to Current.ConditionIcon
        set_property('Current.FanartCode', weathercode)
        set_property('Current.Condition',
                     FORECAST.get(data.get('Weather'), data.get('Weather')))
        set_property('Current.Humidity', data.get('Relh'))
        set_property('Current.DewPoint', FtoC(data.get('Dewp')))

        try:
            temp = data.get('Temp')
            set_property('Current.Temperature',
                         FtoC(temp))  # api values are in C
        except:
            set_property('Current.Temperature', '')

        try:
            set_property('Current.Wind',
                         str(round(float(data.get('Winds')) * 1.609298167)))
        except:
            set_property('Current.Wind', '')

        try:
            set_property(
                'Current.WindDirection',
                xbmc.getLocalizedString(WIND_DIR(int(data.get('Windd')))))
        except:
            set_property('Current.WindDirection', '')

        try:
            set_property('Current.WindGust',
                         SPEED(float(data.get('Gust')) / 2.237) + SPEEDUNIT)
        except:
            set_property('Current.WindGust', '')

        #set_property('Current.Precipitation',	str(round(data.get('precipitationLast3Hours').get('value') *	0.04 ,2)) + ' in')
        if (rain != ''):
            set_property('Current.ChancePrecipitaion',
                         str(rain) + '%')
        else:
            set_property('Current.ChancePrecipitaion', '')

        try:
            set_property(
                'Current.FeelsLike',
                FEELS_LIKE(FtoC(data.get('Temp')),
                           float(data.get('Winds')) / 2.237,
                           int(data.get('Relh')), False))
        except:
            set_property('Current.FeelsLike', '')
Ejemplo n.º 3
0
def fetchHourly(num):

    url = ADDON.getSetting('Location' + str(num) + 'forecastHourly_url')

    hourly_weather = get_url_JSON(url)
    if hourly_weather and hourly_weather != '' and 'properties' in hourly_weather:
        data = hourly_weather['properties']
    else:
        xbmc.log('failed to find proper hourly weather from %s' % url,
                 level=xbmc.LOGERROR)
        return

# extended properties
    for count, item in enumerate(data['periods']):

        icon = item['icon']
        #https://api.weather.gov/icons/land/night/ovc?size=small
        icon = icon.rsplit('?', 1)[0]
        code, rain = code_from_icon(icon)
        set_property('Hourly.%i.RemoteIcon' % (count + 1), icon)

        weathercode = WEATHER_CODES.get(code)
        starttime = item['startTime']
        startstamp = get_timestamp(starttime)
        if DATEFORMAT[1] == 'd' or DATEFORMAT[0] == 'D':
            set_property('Hourly.%i.LongDate' % (count + 1),
                         get_month(startstamp, 'dl'))
            set_property('Hourly.%i.ShortDate' % (count + 1),
                         get_month(startstamp, 'ds'))
        else:
            set_property('Hourly.%i.LongDate' % (count + 1),
                         get_month(startstamp, 'ml'))
            set_property('Hourly.%i.ShortDate' % (count + 1),
                         get_month(startstamp, 'ms'))

        set_property('Hourly.%i.Time' % (count + 1), get_time(startstamp))
        if DATEFORMAT[1] == 'd' or DATEFORMAT[0] == 'D':
            set_property('Hourly.%i.LongDate' % (count + 1),
                         get_month(startstamp, 'dl'))
            set_property('Hourly.%i.ShortDate' % (count + 1),
                         get_month(startstamp, 'ds'))
        else:
            set_property('Hourly.%i.LongDate' % (count + 1),
                         get_month(startstamp, 'ml'))
            set_property('Hourly.%i.ShortDate' % (count + 1),
                         get_month(startstamp, 'ms'))
        outlook = FORECAST.get(item['detailedForecast'],
                               item['detailedForecast'])
        if len(outlook) < 3:
            outlook = FORECAST.get(item['shortForecast'],
                                   item['shortForecast'])
        set_property('Hourly.%i.Outlook' % (count + 1), outlook)
        set_property(
            'Hourly.%i.ShortOutlook' % (count + 1),
            FORECAST.get(item['shortForecast'], item['shortForecast']))
        set_property('Hourly.%i.OutlookIcon' % (count + 1),
                     WEATHER_ICON % weathercode)
        set_property('Hourly.%i.FanartCode' % (count + 1), weathercode)
        #set_property('Hourly.%i.Humidity'		% (count+1), str(item['main'].get('humidity','')) + '%')
        set_property('Hourly.%i.WindDirection' % (count + 1),
                     item['windDirection'])
        set_property('Hourly.%i.WindSpeed' % (count + 1), item['windSpeed'])

        set_property(
            'Hourly.%i.Temperature' % (count + 1),
            str(item['temperature']) + u'\N{DEGREE SIGN}' +
            item['temperatureUnit'])

        if rain != '':
            set_property('Hourly.%i.Precipitation' % (count + 1), rain + '%')
            set_property('Hourly.%i.ChancePrecipitation' % (count + 1),
                         rain + '%')
        else:
            set_property('Hourly.%i.Precipitation' % (count + 1), '')
            set_property('Hourly.%i.ChancePrecipitation' % (count + 1), '')

    count = 1
Ejemplo n.º 4
0
def fetchDaily(num):

    url = ADDON.getSetting('Location' + str(num) + 'forecast_url')
    log('forecast url: %s' % url)

    ##current_props(current_weather,loc)

    daily_weather = get_url_JSON(url)

    if daily_weather and daily_weather != '' and 'properties' in daily_weather:
        data = daily_weather['properties']
    else:
        xbmc.log('failed to find weather data from : %s' % url,
                 level=xbmc.LOGERROR)
        xbmc.log('%s' % daily_weather, level=xbmc.LOGERROR)
        ###return None
        return fetchAltDaily(num)

    for count, item in enumerate(data['periods']):
        #code = str(item['weather'][0].get('id',''))
        icon = item['icon']
        #https://api.weather.gov/icons/land/night/ovc?size=small
        icon = icon.rsplit('?', 1)[0]
        code, rain = code_from_icon(icon)
        #xbmc.log('icon %s' % icon,level=xbmc.LOGINFO)
        #xbmc.log('code %s' % code,level=xbmc.LOGINFO)

        weathercode = WEATHER_CODES.get(code)
        starttime = item['startTime']
        startstamp = get_timestamp(starttime)
        set_property('Day%i.isDaytime' % (count), str(item['isDaytime']))
        set_property('Day%i.Title' % (count), item['name'])
        #xbmc.log('temperature %s' % item['temperature'],level=xbmc.LOGINFO)

        if item['isDaytime'] == True:
            set_property('Day%i.HighTemp' % (count),
                         str(FtoC(item['temperature'])))
            set_property('Day%i.LowTemp' % (count),
                         str(FtoC(item['temperature'])))
        if item['isDaytime'] == False:
            set_property('Day%i.HighTemp' % (count),
                         str(FtoC(item['temperature'])))
            set_property('Day%i.LowTemp' % (count),
                         str(FtoC(item['temperature'])))
        set_property('Day%i.Outlook' % (count), item['shortForecast'])
        #set_property('Day%i.Details'		% (count+1), item['detailedForecast'])
        set_property('Day%i.OutlookIcon' % (count), weathercode)
        set_property('Day%i.RemoteIcon' % (count), icon)

        # NOTE: Day props are 0 based, but Daily/Hourly are 1 based
        set_property('Daily.%i.isDaytime' % (count + 1),
                     str(item['isDaytime']))
        set_property('Daily.%i.Outlook' % (count + 1),
                     item['detailedForecast'])
        set_property('Daily.%i.ShortOutlook' % (count + 1),
                     item['shortForecast'])

        set_property('Daily.%i.RemoteIcon' % (count + 1), icon)
        set_property('Daily.%i.OutlookIcon' % (count + 1),
                     WEATHER_ICON % weathercode)
        set_property('Daily.%i.FanartCode' % (count + 1), weathercode)
        set_property('Daily.%i.WindDirection' % (count + 1),
                     item['windDirection'])
        set_property('Daily.%i.WindSpeed' % (count + 1), item['windSpeed'])

        if item['isDaytime'] == True:
            set_property('Daily.%i.LongDay' % (count + 1), item['name'])
            set_property('Daily.%i.ShortDay' % (count + 1),
                         get_weekday(startstamp, 's') + " (d)")
            set_property(
                'Daily.%i.TempDay' % (count + 1), u'%i\N{DEGREE SIGN}%s' %
                (item['temperature'], item['temperatureUnit']))
            set_property(
                'Daily.%i.HighTemperature' % (count + 1),
                u'%i\N{DEGREE SIGN}%s' %
                (item['temperature'], item['temperatureUnit']))
            set_property('Daily.%i.TempNight' % (count + 1), '')
            set_property('Daily.%i.LowTemperature' % (count + 1), '')
        if item['isDaytime'] == False:
            set_property('Daily.%i.LongDay' % (count + 1), item['name'])
            set_property('Daily.%i.ShortDay' % (count + 1),
                         get_weekday(startstamp, 's') + " (n)")
            set_property('Daily.%i.TempDay' % (count + 1), '')
            set_property('Daily.%i.HighTemperature' % (count + 1), '')
            set_property(
                'Daily.%i.TempNight' % (count + 1), u'%i\N{DEGREE SIGN}%s' %
                (item['temperature'], item['temperatureUnit']))
            set_property(
                'Daily.%i.LowTemperature' % (count + 1),
                u'%i\N{DEGREE SIGN}%s' %
                (item['temperature'], item['temperatureUnit']))
        #set_property('Daily.%i.LongDay'		% (count+1), get_weekday(startstamp, 'l'))
        #set_property('Daily.%i.ShortDay'		% (count+1), get_weekday(startstamp,'s'))
        if DATEFORMAT[1] == 'd' or DATEFORMAT[0] == 'D':
            set_property('Daily.%i.LongDate' % (count + 1),
                         get_month(startstamp, 'dl'))
            set_property('Daily.%i.ShortDate' % (count + 1),
                         get_month(startstamp, 'ds'))
        else:
            set_property('Daily.%i.LongDate' % (count + 1),
                         get_month(startstamp, 'ml'))
            set_property('Daily.%i.ShortDate' % (count + 1),
                         get_month(startstamp, 'ms'))

        if (rain != ''):
            set_property('Daily.%i.Precipitation' % (count + 1), rain + '%')
        else:
            set_property('Daily.%i.Precipitation' % (count + 1), '')