datapoint

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 10, 2024 License: Apache-2.0 Imports: 10 Imported by: 0

README

datapoint

A simple Go library for the Met Office DataPoint API

Interactions have been developed against the endpoints described in this document: https://www.metoffice.gov.uk/binaries/content/assets/metofficegovuk/pdf/data/datapoint_api_reference.pdf along with experimental testing

This module aims to provide some wrapper types around the raw responses to make them easier to work with in code, and therefore the objects will not map to exactly what is returned from the server.

Quick Start

This will give you a quick setup with the DataPoint library and show you how to print the temperature in Exeter

client, err := dp.NewClient(dp.WithApiKey("00000000-0000-0000-0000-000000000000"))
if err != nil {
    panic(err)
}

list, err := client.ForecastSiteList()
if err != nil {
    panic(err)
}

exeterId := -1
for _, site := range list {
    if site.Name == "Exeter" {
        exeterId = site.Id
    }
}

if exeterId == -1 {
    panic("Could not find exeter")
}

forecast, err := client.FiveDayForecast(dp.ResolutionDaily, exeterId, nil)
if err != nil {
    panic(err)
}

fmt.Printf("Forecast was generated at: %v\n", forecast.DataDate)
for _, period := range forecast.Location.Period {
    fmt.Printf("  %v (%v)\n", period.Time, period.Type)
    for _, fore := range period.Forecasts {
        temp := 0
        unit := ""
        t, ok := fore.IntParams[string(dp.KnownParameterTemperature)]
        if ok {
            temp = t.Value
            unit = t.Units
        } else {
            t, ok = fore.IntParams[string(dp.KnownParameterDayMaximumTemperature)]
            if ok {
                temp = t.Value
                unit = t.Units
            } else {
                t, ok = fore.IntParams[string(dp.KnownParameterNightMinimumTemperature)]
                if ok {
                    temp = t.Value
                    unit = t.Units
                } else {
                    panic("Could not find temperature in forecast!")
                }
            }
        }
        fmt.Printf("    %v: %v%v\n", fore.Time, temp, unit)
    }
}

[!NOTE] This is quite a bad way to do this, but it gives you an idea

Documentation

Overview

Package datapoint provides a way to interact with the Met Office DataPoint API. Interactions have been developed against the endpoints described in this document: https://www.metoffice.gov.uk/binaries/content/assets/metofficegovuk/pdf/data/datapoint_api_reference.pdf along with experimental testing

This module aims to provide some wrapper types around the raw responses to make them easier to work with in code, and therefore the objects will not map to exactly what is returned from the server.

Quick Start

This will give you a quick setup with the DataPoint library and show you how to print the temperature in Exeter

client, err := dp.NewClient(dp.WithApiKey("00000000-0000-0000-0000-000000000000"))
if err != nil {
	panic(err)
}

list, err := client.ForecastSiteList()
if err != nil {
	panic(err)
}

exeterId := -1
for _, site := range list {
	if site.Name == "Exeter" {
		exeterId = site.Id
	}
}

if exeterId == -1 {
	panic("Could not find exeter")
}

forecast, err := client.FiveDayForecast(dp.ResolutionDaily, exeterId, nil)
if err != nil {
	panic(err)
}

fmt.Printf("Forecast was generated at: %v\n", forecast.DataDate)
for _, period := range forecast.Location.Period {
	fmt.Printf("  %v (%v)\n", period.Time, period.Type)
	for _, fore := range period.Forecasts {
		temp := 0
		unit := ""
		t, ok := fore.IntParams[string(dp.KnownParameterTemperature)]
		if ok {
			temp = t.Value
			unit = t.Units
		} else {
			t, ok = fore.IntParams[string(dp.KnownParameterDayMaximumTemperature)]
			if ok {
				temp = t.Value
				unit = t.Units
			} else {
				t, ok = fore.IntParams[string(dp.KnownParameterNightMinimumTemperature)]
				if ok {
					temp = t.Value
					unit = t.Units
				} else {
					panic("Could not find temperature in forecast!")
				}
			}
		}
		fmt.Printf("    %v: %v%v\n", fore.Time, temp, unit)
	}
}

Note: this is quite a bad way to do this, but it gives you an idea

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DataPointClient

type DataPointClient struct {
	// contains filtered or unexported fields
}

DataPointClient represents a client used for interacting with the MetOffice DataPoint service

func NewClient

func NewClient(opt ...Opt) (*DataPointClient, error)

NewClient returns a new DataPointClient, applying all the options set. If an API key is not provided, this will fail and return an error. Look for With functions for the options which can be provided

func (*DataPointClient) FiveDayForecast

func (d *DataPointClient) FiveDayForecast(resolution Resolution, locationID int, at *time.Time) (*SiteRep, error)

FiveDayForecast provides access to daily and three hourly forecast data from the Met Office for each of the roughly 5,000 sites for which the Met Office provides data. The forecast data is provided for time steps that are three hours apart, or daily (day and night), starting with the time at which the forecast was last run, and ending approximately five days later (meaning that approximately 10 or 40 forecast timesteps are available for each site). The data provided by the web service is updated on an hourly basis, and at any given point in time the exact set of timesteps that are available can be obtained using the capabilities web service. For a full list of the 5,000 sites, call the 5,000 UK locations site list data feed.

func (*DataPointClient) FiveDayForecastForAllLocations

func (d *DataPointClient) FiveDayForecastForAllLocations(resolution Resolution, at *time.Time) ([]SiteRep, error)

FiveDayForecastForAllLocations implements the same functionality as FiveDayForecast but returns the results for all locations supported by the DataPoint service. The result for this will be quite large

func (*DataPointClient) ForecastSiteList

func (d *DataPointClient) ForecastSiteList() ([]Site, error)

ForecastSiteList returns the 5,000 UK locations forecast site list data feed provides a list of the locations (also known as sites) for which results are available for the 5,000 UK locations three hourly forecast and 5,000 UK locations daily forecast data feeds. You can use this data feed to find details such as the ID of the site that you are interested in finding data for.

func (*DataPointClient) ForecastTimeStepCapabilities

func (d *DataPointClient) ForecastTimeStepCapabilities(resolution Resolution) (*TimeSteps, error)

ForecastTimeStepCapabilities exposes the capabilities data feed which provides a summary of the timesteps for which results are available for the 5,000 UK locations daily and three hourly forecast data feed. You can use this data feed to check that the timestep you are interested in is available before querying the relevant web service to get the data. In this way you can minimise the number of redundant calls that have to be made.

func (*DataPointClient) ObservationSiteList

func (d *DataPointClient) ObservationSiteList() ([]Site, error)

ObservationSiteList returns a list of locations (also known as sites) for which results are available for the hourly observations data feed. You can use this to find the ID of the site that you are interested in

func (*DataPointClient) RegionalForecastCapabilities

func (d *DataPointClient) RegionalForecastCapabilities() (*RegionalForecastCapabilities, error)

RegionalForecastCapabilities provides a summary of the results that are available from the regional forecast data feed, specifying when the forecast was last updated

func (*DataPointClient) RegionalForecastSiteList

func (d *DataPointClient) RegionalForecastSiteList() ([]RegionalForecastSite, error)

RegionalForecastSiteList provides a list of the locations (also known as sites) for which results are available for the regional forecast data feed. You can use this data feed to find details such as the ID of the region that you are interested in finding data for

func (*DataPointClient) UkExtremesCapabilities

func (d *DataPointClient) UkExtremesCapabilities() (*ExtremeCapabilities, error)

UkExtremesCapabilities indicates when the regional extremes observations data feed was last updated, and the period it covers

func (*DataPointClient) UkExtremesLatest

func (d *DataPointClient) UkExtremesLatest() (*LatestExtremes, error)

UkExtremesLatest provides access to the observed extremes of weather across the UK for the day of issue. The data provided by the web service is updated on a daily basis.

type Extreme

type Extreme struct {
	// LocationId [official] is location ID of the location where the extreme was observed. The location ID may not
	// be listed in the 5,000 locations resource.
	LocationId int
	// LocationName [official] is the full name of the location where the extreme was observed.
	LocationName string
	// Type [official] is the type of the extreme. For example 'HMAXT' would represent the highest maximum
	//temperature, and 'LMINT' would represent the lowest minimum temperature.
	Type string
	// UnitOfMeasurement [official - uom] is the unit of measurement for the extreme
	UnitOfMeasurement string
	// Value [official - $] is the value fo the observed extreme, in units specified in UnitOfMeasurement
	Value float64
}

Extreme represents a single extreme reading

type ExtremeCapabilities

type ExtremeCapabilities struct {
	// ExtremeDate [official] is the date of the observation
	ExtremeDate time.Time
	// IssuedAt [official] is the date at which the observation was issued
	IssuedAt time.Time
}

ExtremeCapabilities describes the last update to a UK extreme measurement

type Forecast

type Forecast struct {
	// Time [unofficial] is the time at which this forecast represents, this is derived from the time offset returned in the response
	Time time.Time
	// IntParams contains all known parameters which will always be numeric, anything else will appear in StringParams
	IntParams map[string]IntParameterValue
	// StringParams contains all parameters which are not known to be integers
	StringParams map[string]StringParameterValue
}

Forecast represents a single forecast issues for a specific time, which contains a set of parameters describing the weather at that time

type IntParameterValue

type IntParameterValue struct {
	ParameterDescriptor
	// Value [official] the value of the measure
	Value int
}

IntParameterValue is a combination of an int value and a parameter definition

type KnownParameter

type KnownParameter string
const (
	KnownParameterFeelsLikeTemp                  KnownParameter = "F"
	KnownParameterWindGust                       KnownParameter = "G"
	KnownParameterWindGustNoon                   KnownParameter = "Gn"
	KnownParameterScreenRelativeHumidity         KnownParameter = "H"
	KnownParameterScreenRelativeHumidityNoon     KnownParameter = "Hn"
	KnownParameterTemperature                    KnownParameter = "T"
	KnownParameterDayMaximumTemperature          KnownParameter = "Dm"
	KnownParameterNightMinimumTemperature        KnownParameter = "Nm"
	KnownParameterFeelsLikeDayMaximumTemperature KnownParameter = "FDm"
	KnownParameterVisibility                     KnownParameter = "V"
	KnownParameterWindDirection                  KnownParameter = "D"
	KnownParameterWindSpeed                      KnownParameter = "S"
	KnownParameterMaxUvIndex                     KnownParameter = "U"
	KnownParameterWeatherType                    KnownParameter = "W"
	KnownParameterPrecipitationProbability       KnownParameter = "Pp"
	KnownParameterPrecipitationProbabilityDay    KnownParameter = "PPd"
	KnownParameterPrecipitationProbabilityNight  KnownParameter = "PPn"
)

type LatestExtremes

type LatestExtremes struct {
	// ExtremeDate [official] is the date of the observation
	ExtremeDate time.Time
	// IssuedAt [official] is the date at which the observation was issued
	IssuedAt time.Time
	// Regions [official] are the regions in which observations are found
	Regions []Region
}

LatestExtremes represents the response from the latest UK extremes endpoints

type LocationRep

type LocationRep struct {
	// Id [official - i] is the ID number of the location
	Id int
	// Latitude [official - lan] is the latitude of the location in decimal degrees
	Latitude float64
	// Longitude [official - lon] is the longitude of the location in decimal degrees
	Longitude float64
	// Name [official] is the name of the location
	Name string
	// Country [official] is the country of the location
	Country string
	// Continent [official] is the continent of the location
	Continent string
	// Elevation [unofficial] is the elevation of the location, not always returned
	Elevation float64
	// Period is the set of periods for which forecasts are available
	Period []Period
}

LocationRep contains a set of periods and forecasts for a single location area

type Opt

type Opt interface {
	// contains filtered or unexported methods
}

Opt is an option that can apply to a DataPointClient

func WithApiKey

func WithApiKey(key string) Opt

WithApiKey sets the API key of the client to the string provided, this cannot be updated during use

func WithApiSupplier

func WithApiSupplier(supplier Supplier[string]) Opt

WithApiSupplier sets the API key to this supplier, this will be called on each invocation to the DataPoint API

func WithBaseURI

func WithBaseURI(uri string) Opt

WithBaseURI will update the data point client to use a different base URI from the standard. This can be used to to a simple proxy if required

func WithHttpClient

func WithHttpClient(client *http.Client) Opt

WithHttpClient replaces the HTTP client which will be used for making requests to the service. This can be used to configure a real proxy, or set specific timeouts, etc

type ParameterDescriptor

type ParameterDescriptor struct {
	// Name [official] is the name of the attribute
	Name string
	// Units [official] is the unit in which the attribute is represented
	Units string
	// Description [official - $] is the textual description of what the attribute represents
	Description string
}

ParameterDescriptor contains the definition of one of the attributes in a single forecast

type Period

type Period struct {
	// Type [official] is the type of period this represents, usually Day
	Type string
	// Time [official] is the start date of this period
	Time time.Time
	// Forecasts [official] is the set of forecasts for this period
	Forecasts []Forecast
}

Period represents a single time period which can contain any number of forecasts based on the resolution.

type Region

type Region struct {
	// Id [official] is the short name of the region
	Id string
	// Name [official] is the full name of the region
	Name string
	// Extremes [official] holds the set of extreme measurements found in this region
	Extremes []Extreme
}

Region represents a region in which extreme values have been observed

type RegionalForecastCapabilities

type RegionalForecastCapabilities struct {
	IssuedAt time.Time
}

RegionalForecastCapabilities indicates when the last set of regional forecasts were issues by the Met Office

type RegionalForecastSite

type RegionalForecastSite struct {
	// Id [official] The ID of region
	Id int
	// Name [official] The short name of the region
	Name string
}

RegionalForecastSite is an individual location for which a regional forecast is available

type Resolution

type Resolution string
const (
	ResolutionThreeHourly Resolution = "3hourly"
	ResolutionDaily       Resolution = "daily"
)

type Site

type Site struct {
	// Id [official]: The ID number of the location e.g. '310069'
	Id int `json:"id"`
	// Latitude [official]: The latitude of the location in decimal degrees e.g. '50.7179'
	Latitude float64 `json:"latitude"`
	// Longitude [official]: The longitude of the location in decimal degrees e.g. '-3.5327'
	Longitude float64 `json:"longitude"`
	// Name [official]: The name of the location e.g. 'Exeter'
	Name string `json:"name"`
	// Elevation [undocumented]: The elevation of the location
	Elevation float64 `json:"elevation"`
	// Region [undocumented]: The region of the location
	Region string `json:"region"`
	// UnitaryAuthArea [undocumented]: The unitary auth area of the location
	UnitaryAuthArea string `json:"unitaryAuthArea"`
}

A Site represents a single location for which 3 hourly forecasts are available

type SiteRep

type SiteRep struct {
	// DataDate [official] is the date and time at which the forecast was run
	DataDate time.Time
	// Type [official] is the type of data that is returned (Forecast or Obs)
	Type string
	// Location [official] is the combination of location information and forecast data
	Location LocationRep
}

SiteRep is a forecast entry for a single location

type StringParameterValue

type StringParameterValue struct {
	ParameterDescriptor
	// Value [official] the value of the measure
	Value string
}

StringParameterValue is a combination of a string value and a parameter definition

type Supplier

type Supplier[T any] interface {
	Get() T
}

Supplier is a simple interface for something that returns a type. This can be used to abstract over backing storage in an independent way

type TimeSteps

type TimeSteps struct {
	// DataDate [official]: The date and time at which the data was last updated, expressed according to the ISO
	// 8601 combined date and time convention. e.g. '2012-11-21T15:00:00Z'
	DataDate time.Time
	// Resolution [official]: The temporal resolution of the web service for which the capabilities have been returned.
	// This is set to the temporal resolution specified in the query. e.g. 'daily', '3hourly' or
	// 'hourly'
	Resolution Resolution
	// Type [official]: The resource type of the web service for which the capabilities have been returned. e.g.
	// 'wxfcs' or 'wxobs'
	Type string
	// TimeSteps [official]: The value of each TS object (or each element in the TS array in the JSON representation)
	// provides a description of a single available timestep, expressed according to the ISO 8601
	// combined date and time convention. e.g. '2012-11-21T06:00:00Z
	TimeSteps []time.Time
}

TimeSteps represents the set of available time step that can be queried for the given start and resolution values

type UvIndex

type UvIndex int

func (UvIndex) IsExtremeExposure

func (i UvIndex) IsExtremeExposure() bool

func (UvIndex) IsHighExposure

func (i UvIndex) IsHighExposure() bool

func (UvIndex) IsLowExposure

func (i UvIndex) IsLowExposure() bool

func (UvIndex) IsModerateExposure

func (i UvIndex) IsModerateExposure() bool

func (UvIndex) IsVeryHighExposure

func (i UvIndex) IsVeryHighExposure() bool

type Visibility

type Visibility string
const (
	VisibilityUnknown   Visibility = "UN"
	VisibilityVeryPoor  Visibility = "VP"
	VisibilityPoor      Visibility = "PO"
	VisibilityModerate  Visibility = "MO"
	VisibilityGood      Visibility = "GO"
	VisibilityVeryGood  Visibility = "VG"
	VisibilityExcellent Visibility = "EX"
)

type WeatherType

type WeatherType int
const (
	WeatherTypeClearNight           WeatherType = 0
	WeatherTypeSunnyDay             WeatherType = 1
	WeatherTypePartlyCloudyNight    WeatherType = 2
	WeatherTypePartlyCloudyDay      WeatherType = 3
	WeatherTypeMist                 WeatherType = 5
	WeatherTypeFog                  WeatherType = 6
	WeatherTypeCloudy               WeatherType = 7
	WeatherTypeOvercast             WeatherType = 8
	WeatherTypeLightRainShowerNight WeatherType = 9
	WeatherTypeLightRainShowerDay   WeatherType = 10
	WeatherTypeDrizzle              WeatherType = 11
	WeatherTypeLightRain            WeatherType = 12
	WeatherTypeHeavyRainShowerNight WeatherType = 13
	WeatherTypeHeavyRainShowerDay   WeatherType = 14
	WeatherTypeHeavyRain            WeatherType = 15
	WeatherTypeSleetShowerNight     WeatherType = 16
	WeatherTypeSleetShowerDay       WeatherType = 17
	WeatherTypeSleet                WeatherType = 18
	WeatherTypeHailShowerNight      WeatherType = 19
	WeatherTypeHailShowerDay        WeatherType = 20
	WeatherTypeHail                 WeatherType = 21
	WeatherTypeLightSnowShowerNight WeatherType = 22
	WeatherTypeLightSnowShowerDay   WeatherType = 23
	WeatherTypeLightSnow            WeatherType = 24
	WeatherTypeHeavySnowShowerNight WeatherType = 25
	WeatherTypeHeavySnowShowerDay   WeatherType = 26
	WeatherTypeHeavySnow            WeatherType = 27
	WeatherTypeThunderShowerNight   WeatherType = 28
	WeatherTypeThunderShowerDay     WeatherType = 29
	WeatherTypeThunder              WeatherType = 30
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL