cptec

package module
v0.0.0-...-f0b81a8 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2018 License: BSD-3-Clause Imports: 18 Imported by: 0

README

gocptec

Weather data for geekers

GoDoc Go Report Card Coverage Status Build Status License

Go Cptec is an INPE/CPTEC weather data parser. The data range from weather stations, given (temperature, rain, etc.), alerts, forecast.

The project has no link with INPE/CPTEC.

Table of Contents

Features

  • Station list
  • Weather data
  • Forecast

Installing

From source (always latest)

Make sure to have go (1.9+) installed, then do:

go get -u github.com/murilobsd/cptec

Usage

Get stations:

cptec := cptec.New(nil)
stations, err := cptec.Station.GetAll()
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}

for _, station := range stations {
    fmt.Println(station)
}

# Output
# ID: 32549 - UF: TO - Locality: UHE Isamu Ikeda Montante
# ID: 32619 - UF: TO - Locality: Xambioa

License

Released under the BSD license.

Documentation

Overview

Package cptec fornece métodos para obter históricos de medições meteorologia e dados das estações do CPTEC/INPE (Centro de Previsão de Tempo e Estudos Climáticos).

Além da coleta desses dados o pacote fornece a exportação dos mesmos nos formatos csv e json.:

Exemplo de saída csv:

id,uf,locality
32619,to,xambioa

Exemplo de saída json:

{"id": "32619", "uf": "to", "locality": "xambioa"}

O autor desenvolveu o pacote como forma de estudo e não se responsabiliza pelo uso dos dados.

Aviso CPTEC/INPE:

Os produtos apresentados nesta página não podem ser usados para propósitos comerciais, copiados integral ou parcialmente para a reprodução em meios de divulgação, sem a expressa autorização do CPTEC/INPE. Os usuários deverão sempre mencionar a fonte das informações e dados como "CPTEC/INPE" A geração e a divulgação de produtos operacionais obedecem critérios sistêmicos de controle de qualidade, padronização e periodicidade de disponibilização. Em nenhum caso o CPTEC/INPE pode ser responsabilizado por danos especiais, indiretos ou decorrentes, ou nenhum dano vinculado ao que provenha do uso destes produtos.

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrParseDate error parse date
	ErrParseDate = errors.New("Invalid parse date")
)
View Source
var (
	ErrStatusCode = errors.New("Http invalid status code")
)

These are the errors that can be returned

View Source
var Marshal = func(v interface{}) (io.Reader, error) {
	b, err := json.MarshalIndent(v, "", "\t")
	if err != nil {
		return nil, err
	}
	return bytes.NewReader(b), nil
}

Marshal is a function that marshals the object into an io.Reader. By default, it uses the JSON marshaller.

View Source
var Unmarshal = func(r io.Reader, v interface{}) error {
	return json.NewDecoder(r).Decode(v)
}

Unmarshal is a function that unmarshals the data from the reader into the specified value. By default, it uses the JSON unmarshaller.

Functions

func CleanString

func CleanString(value string) string

CleanString Remove no caracteres

func FindLat

func FindLat(value string)

FindLat pesquisa a latitude

func FindLon

func FindLon(value string)

FindLon pesquisa a longitude

func FixCityState

func FixCityState(cityValue string) (string, string)

FixCityState ajusta o nome da cidade e do estado

func Load

func Load(path string, v interface{}) error

Load loads the file at path into v. Use os.IsNotExist() to see if the returned error is due to the file being missing.

func ParserDate

func ParserDate(date string) (*time.Time, error)

ParserDate parsea o dado de data

func ParserTime

func ParserTime(timestr string) (*time.Time, error)

ParserTime parsea o dade de útil para o horário do nascer do sol e o por do sol

func PeriodToTime

func PeriodToTime(period string) time.Time

PeriodToTime convert period to time

func Save

func Save(path string, v interface{}) error

Save saves a representation of v to the file at path.

func ToFloat

func ToFloat(number string) float64

ToFloat converte string para float64, caso retorne erro o valor -999.0 é retornado.

func ToInt

func ToInt(number string) int64

ToInt converte string para int64, caso retorne erro o valor -999 é retornado.

func Trim

func Trim(value string) string

Trim space

Types

type CPTEC

type CPTEC struct {
	Client *http.Client // HTTP client used to communicate with the API.

	// Base URL for CPTEC requests. BaseURL should always be specified with a
	// trailing slash.
	BaseURL *url.URL

	// User agent used when communicating with the CPTEC.
	UserAgent string

	// Services used for talking to different parts of the CPTEC.
	Station  *StationService
	Forecast *ForecastService
}

CPTEC manages communication with the CPTEC.

func New

func New(httpClient *http.Client) *CPTEC

New returns a new CPTEC client. If a nil httpClient is provided, http.DefaultClient will be used.

func (*CPTEC) NewRequest

func (c *CPTEC) NewRequest(method, path string, data interface{}, header interface{}) (req *http.Request, err error)

NewRequest ...

type Forecast

type Forecast struct {
	Date            *time.Time `json:"date"`
	Description     string     `json:"description"`
	PictureURL      string     `json:"picture"`
	TempMin         float64    `json:"temp_min"`
	TempMax         float64    `json:"temp_max"`
	Sunrise         *time.Time `json:"sunrise"`
	Sunset          *time.Time `json:"sunset"`
	UvIndex         int64      `json:"uv_index"`
	RainProbability float64    `json:"rain_probability"`
}

Forecast estrutura do dado retornado da previsão

func (*Forecast) String

func (fo *Forecast) String() string

type ForecastCity

type ForecastCity struct {
	City      string      `json:"city"`
	UF        string      `json:"uf"`
	Forecasts []*Forecast `json:"forecasts"`
}

ForecastCity representa a previsão da cidade

type ForecastService

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

ForecastService serviço que fornece o cliente para informações

func (*ForecastService) Get

func (f *ForecastService) Get(cityName string)

Get get weather forecast of city.

type Station

type Station struct {
	ID        string `json:"id"`
	UF        string `json:"uf"`
	Locality  string `json:"locality"`
	Latitude  string `json:"latitude"`
	Longitude string `json:"longitude"`
}

Station structure representing the CPTEC/INPE weather station.

Information such as location and identification is part of this structure.

func (*Station) Hash

func (s *Station) Hash() string

Hash return md5 of station

func (*Station) String

func (s *Station) String() string

func (*Station) ToBytes

func (s *Station) ToBytes() []byte

ToBytes convert station to byte

type StationService

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

StationService ...

func (*StationService) Get

func (s *StationService) Get(station *Station) error

Get coleta todos

func (*StationService) GetAll

func (s *StationService) GetAll() ([]*Station, error)

GetAll ...

func (*StationService) GetFull

func (s *StationService) GetFull() ([]*Station, error)

GetFull ...

type Stations

type Stations []*Station

Stations array ...

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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