コード例 #1
0
ファイル: metoffice.py プロジェクト: ksenia1997/program-y
    def check_for_license_keys(self, license_keys):

        if license_keys.has_key('METOFFICE_API_KEY'):
            api_key = license_keys.get_key('METOFFICE_API_KEY')
        else:
            raise Exception("No valid license key METOFFICE_API_KEY found")

        self._met_office_api = metoffer.MetOffer(api_key)
コード例 #2
0
ファイル: 322.py プロジェクト: mscroggs/KLBFAX
    def background(self):
        import metoffer

        api_key = "f2ef8ecf-175f-491d-aea1-93a38209bd55"
        M = metoffer.MetOffer(api_key)
        #x = M.nearest_loc_forecast(51.4033, -0.3375, metoffer.THREE_HOURLY)
        x = M.nearest_loc_forecast(51.5252257441084, -0.134831964969635,
                                   metoffer.DAILY)
        self.y = metoffer.parse_val(x)

        self.tagline = "Live from the Met Office"
コード例 #3
0
    def __init__(self, cache_hours=6):
        if "met_office_api" in _config:
            self._M = metoffer.MetOffer(_config["met_office_api"])
        else:
            self._M = None

        self.cache_hours = cache_hours
        self.cache = dict()
        cachedir = _config["cachedir"]
        try:
            with open(f"{cachedir}/weather.cache", "rb") as f:
                self.cache = pickle.load(f)
        except:
            pass
コード例 #4
0
ファイル: scrapers.py プロジェクト: fneiva2006/rpi-facerec
def met():  #retrieve 5-day information
    key = '568fbf63-75c5-451e-a282-1388c877e60b'
    try:
        M = metoffer.MetOffer(key)
        x = M.nearest_loc_forecast(53.4840, -2.2440, metoffer.THREE_HOURLY)
        y = metoffer.parse_val(x)
        weatherData = [y.name]  #weather forecast data
        for i in y.data:
            a = ("{}-{}".format(i["timestamp"][0].strftime("%D %b, %H:%M"),
                                metoffer.WEATHER_CODES[i["Weather Type"][0]]) +
                 " " + str(i["Temperature"][0]))
            weatherData.append(a)
        return weatherData
    except Exception, e:
        return 0
コード例 #5
0
ファイル: metoffice.py プロジェクト: uganyasavur/program-y
    def __init__(self, license_keys):

        self.current_observation_response_file = None
        self.three_hourly_forecast_response_file = None
        self.daily_forecast_response_file = None

        if license_keys.has_key('METOFFICE_API_KEY'):
            api_key = license_keys.get_key('METOFFICE_API_KEY')
        else:
            raise Exception("No valid license key METOFFICE_API_KEY found")

        if license_keys.has_key('CURRENT_OBSERVATION_RESPONSE_FILE'):
            self.current_observation_response_file = license_keys.get_key('CURRENT_OBSERVATION_RESPONSE_FILE')
        if license_keys.has_key('THREE_HOURLY_FORECAST_RESPONSE_FILE'):
            self.three_hourly_forecast_response_file = license_keys.get_key('THREE_HOURLY_FORECAST_RESPONSE_FILE')
        if license_keys.has_key('DAILY_FORECAST_RESPONSE_FILE'):
            self.daily_forecast_response_file = license_keys.get_key('DAILY_FORECAST_RESPONSE_FILE')

        self._met_office_api = metoffer.MetOffer(api_key)
コード例 #6
0
    def __init__(
            self, sLocation, dLatitude, dLongitude, sMetApiKey,
            sMeasurementType):  # This is run when an onject is first created
        self.sLocation = sLocation
        self.dLatitude = dLatitude
        self.dLongitude = dLongitude
        self.sMetApiKey = sMetApiKey
        self.sMeasurementType = sMeasurementType

        oMet = metoffer.MetOffer(sMetApiKey)

        if self.sMeasurementType == 'nearest_loc_obs':
            self.dicWeatherData = oMet.nearest_loc_obs(
                self.dLatitude, self.dLongitude
            )  # This finds the nearest observation station of which there are not that many so your data may be inaccruate.
        if self.sMeasurementType == 'nearest_loc_forecast':
            self.dicWeatherData = oMet.nearest_loc_forecast(
                dLatitude, dLongitude, metoffer.THREE_HOURLY
            )  # This gives forecast data for the given area.

        self.oWeatherReport = metoffer.parse_val(self.dicWeatherData)
コード例 #7
0
    '20': 'Hail shower (day)',
    '21': 'Hail',
    '22': 'Light snow shower (night)',
    '23': 'Light snow shower (day)',
    '24': 'Light snow',
    '25': 'Heavy snow shower (night)',
    '26': 'Heavy snow shower (day)',
    '27': 'Heavy snow',
    '28': 'Thunder shower (night)',
    '29': 'Thunder shower (day)',
    '30': 'Thunder'
}

#Met Office API Key details
api_key = ''  #insert your API Key inside the ' '
M = metoffer.MetOffer(api_key)


#Data Producer function
def Producer():

    moList = []  #build the list to be serialized

    for i in location:  #iterate through all the locations
        city, postcode, lat, lon = club_location(
            i)  # import location details from 'reference.py'
        x = M.nearest_loc_forecast(
            float(lat), float(lon),
            metoffer.THREE_HOURLY)  #location specific, 3 hourly forecast
        y = metoffer.parse_val(x)
        myDict = y.data  #data retrieved from MetOffice
コード例 #8
0
ファイル: wx_gen_ids.py プロジェクト: nowster/ceefax
import metoffer
import pprint

key = ""  # Met Office API key
M = metoffer.MetOffer(key)


def ids_of(sitelist):
    try:
        sites = [(s["name"], s["id"])
                 for s in sitelist["Locations"]["Location"]]
    except KeyError:
        sites = [(s["@name"], s["@id"])
                 for s in sitelist["Locations"]["Location"]]
    return dict(sites)


def print_cities(forecast_sites):

    cities = [
        "Inverness",
        "Pitlochry",
        "Edinburgh",
        "Newcastle Upon Tyne",
        "Manchester",
        "Belfast",
        "Birmingham",
        "Cardiff",
        "Plymouth",
        "Cambridge",
        "London",
コード例 #9
0
 def __init__(self):
     self.time = None
     self.humidity = None
     self.temperature = None
     self.met = metoffer.MetOffer(API_KEY)
コード例 #10
0
def main():
    cmdparser = optparse.OptionParser()
    cmdparser.add_option("--noclear",
                         action="store_true",
                         default=False,
                         help="Do not clear the eink before drawing.")
    cmdparser.add_option("--noweather",
                         action="store_true",
                         default=False,
                         help="Do not draw the weather forecast.")
    cmdparser.add_option(
        "-o",
        "--output",
        type="string",
        default="",
        help=
        "Save the output to two files called output-b.png and output-r.png. Will not attempt to draw on eink."
    )
    cmdparser.add_option(
        "-i",
        "--input",
        type="string",
        default="",
        help=
        "Do not render a frame, draw the provided images to the eink. This option is the 'black' image. Use in conjunction with --redinput."
    )
    cmdparser.add_option("-r",
                         "--redinput",
                         type="string",
                         default="",
                         help="The 'red' image file for use with --input.")
    cmdparser.add_option("-c",
                         "--calendars",
                         type="string",
                         default="primary",
                         help="Calendar IDs to use, delimited by comma.")
    cmdparser.add_option("-v",
                         "--verbose",
                         action="store_true",
                         default=False,
                         help="Verbose mode.")
    cmdparser.add_option("--width",
                         type="int",
                         default=880,
                         help="If not drawing to eink, output width of image.")
    cmdparser.add_option(
        "--height",
        type="int",
        default=528,
        help="If not drawing to eink, output height of image.")
    cmdparser.add_option("-d",
                         "--days",
                         type="int",
                         default=7,
                         help="Number of days to look ahead for events.")
    cmdparser.add_option(
        "--cache",
        type="string",
        help=
        "Filename of cache file to save fetched events to. Will only redraw if the events have changed."
    )
    cmdparser.add_option(
        "--cachehours",
        type="int",
        default=2,
        help="Number of hours that the cache remains valid for.")

    (options, _) = cmdparser.parse_args()

    if (options.redinput != ""
            and options.input == "") or (options.redinput == ""
                                         and options.input != ""):
        print("Options --input and --redinput must be used together.")
        sys.exit(1)

    if options.output == "":
        if platform.system() != "Linux":
            print(
                "Cannot use the Waveshare libraries on a non-Linux platform. Use the --output option to output to an image file."
            )
            sys.exit(1)
        try:
            from waveshare_epd import epd7in5b_HD
        except ImportError:
            print(
                "Could not find the waveshare_epd libraries. Download the Waveshare Python code from https://www.waveshare.com/wiki/7.5inch_HD_e-Paper_HAT_%28B%29 and ensure it is visible to Python."
            )
            sys.exit(1)
        epd = epd7in5b_HD.EPD()
        epd.init()
        options.width = epd.width
        options.height = epd.height

    redraw = True

    if options.input == "":
        calservice = registerCalendarService()
        ids = getIDsFromNames(calservice, options.calendars)
        events = getEvents(calservice, ids)
        days = eventsToDays(events, options.days)

        if not options.noweather:
            if os.path.exists(os.path.join(curdir, 'weather.json')):
                with open(os.path.join(curdir, 'weather.json')) as f:
                    data = json.load(f)
                if not "lat" in data and not "lon" in data and not "apikey" in data:
                    print("weather.json is in an incorrect format.")
                    sys.exit()
            else:
                weatherjson = '{\n\t"lat": "54.9755153",\n\t"lon": "-1.6222127",\n\t"apikey": "00000000-0000-0000-0000-000000000000"\n}'
                with open(os.path.join(curdir, 'weather.json'), 'a') as f:
                    f.write(weatherjson)
                print("weather.json created. Fill it in and retry.")
                sys.exit()

            mo = metoffer.MetOffer(data['apikey'])
            forecast = mo.nearest_loc_forecast(float(data['lat']),
                                               float(data['lon']),
                                               metoffer.THREE_HOURLY)
            dailyforecast = mo.nearest_loc_forecast(float(data['lat']),
                                                    float(data['lon']),
                                                    metoffer.DAILY)
            weather = (metoffer.Weather(forecast),
                       metoffer.Weather(dailyforecast))

            if options.verbose:
                print(f"Weather forecast for {weather[0].name} fetched.")
        else:
            weather = None

        if options.cache != None:
            cachefile = os.path.join(curdir, options.cache)
            if os.path.exists(cachefile):
                try:
                    (cacheddays,
                     cachedtime) = pickle.load(open(cachefile, "rb"))
                    if cacheddays == days and datetime.now(
                    ) < cachedtime + timedelta(hours=options.cachehours):
                        #Nothing has changed
                        if options.verbose:
                            print(f"Fetched data is the same as cached data.")
                        redraw = False
                except:
                    #Any errors handling the cache, just invalitate it
                    print("Error whilst reading cache: ", sys.exc_info()[0])
            #Else we will update the cache
            #We store the days dictionary and the current time in the cache, because the MetOffice objects are incomparable and this
            #is the easiest way to ensure that we update at least frequently enough to show the new forecast.
            pickle.dump((days, datetime.now()), open(cachefile, "wb"))

        if options.verbose:
            pprint.pprint(days)

        if redraw:
            if options.verbose: print("Drawing frame.")
            (bimage, rimage) = renderFrame(options.width, options.height, days,
                                           weather)
    else:
        bimage = Image.open(os.path.join(curdir, options.input))
        rimage = Image.open(os.path.join(curdir, options.redinput))

    if options.output == "":
        if redraw:
            if options.noclear == False:
                if options.verbose: print("Clearing eink.")
                epd.Clear()
                if options.verbose: print("eink cleared.")

            if options.verbose: print("Sending frame to eink.")

            epd.display(epd.getbuffer(bimage), epd.getbuffer(rimage))
            if options.verbose: print("eink done.")
            epd.sleep()
        else:
            if options.verbose:
                print("eink not updated because fetched data matches cache.")
    else:
        if redraw:
            bimage.save(options.output + "-b.png", format="png")
            rimage.save(options.output + "-r.png", format="png")
            if options.verbose:
                print(
                    f"Rendered frame saved to {options.output}-b.png and {options.output}-r.png."
                )
        else:
            if options.verbose:
                print(
                    "Output files not updated because fetched data matches cache."
                )
コード例 #11
0
ファイル: metoffice.py プロジェクト: lilnana00/3ddd
 def __init__(self, api_key):
     self._met_office_api = metoffer.MetOffer(api_key)