weather/weather.go
2019-08-14 21:09:40 +02:00

113 lines
2.8 KiB
Go

package main
import (
"fmt"
"net/http"
"encoding/json"
"io/ioutil"
"time"
influx "github.com/influxdata/influxdb1-client/v2"
)
type Weather struct {
Config Config
WeatherDatas []WeatherData
}
type WeatherData struct {
City string `json:"name"`
Main struct {
Humidity int `json:"humidity"`
Pressure int `json:"pressure"`
Temperature float32 `json:"temp"`
} `json:"main"`
Clouds struct {
All int `json:"all"`
} `json:"clouds"`
Rain struct {
OneHour float32 `json:"1h"`
TreeHours float32 `json:"3h"`
} `json:"rain"`
Snow struct {
OneHour float32 `json:"1h"`
TreeHours float32 `json:"3h"`
} `json:"snow"`
Wind struct {
Speed float32 `json:"speed"`
Direction int `json:"deg"`
} `json:"Wind"`
Sys struct {
Country string `json:"country"`
} `json:"sys"`
}
func (w *Weather) FetchData() {
for _, city := range w.Config.Cities {
resp, err := http.Get(
fmt.Sprintf(
"%s/weather?q=%s&appid=%s&units=%s",
URI,
city,
w.Config.OpenWeatherMap.ApiKey,
w.Config.OpenWeatherMap.Units,
),
)
if err != nil {
fmt.Printf("%s", err)
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%s", err)
}
weatherData := WeatherData{}
json.Unmarshal(data, &weatherData)
w.WeatherDatas = append(w.WeatherDatas, weatherData)
time.Sleep(500 * time.Millisecond)
}
}
func (w *Weather) SendToInfluxDB() error {
conn, err := influx.NewHTTPClient(influx.HTTPConfig{
Addr: w.Config.InfluxDB.URL,
Username: w.Config.InfluxDB.Username,
Password: w.Config.InfluxDB.Password,
})
if err != nil {
return err
}
bps, _ := influx.NewBatchPoints(
influx.BatchPointsConfig{
Database: w.Config.InfluxDB.Database,
})
for _, weather := range w.WeatherDatas {
tags := map[string]string{ "city": weather.City, "country": weather.Sys.Country }
fields := map[string]interface{}{
"temperature": weather.Main.Temperature,
"humidity": weather.Main.Humidity,
"pressure": weather.Main.Pressure,
"clouds": weather.Clouds.All,
"wind_speed": weather.Wind.Speed,
"wind_direction": weather.Wind.Direction,
"rain_1h": weather.Rain.OneHour,
"rain_3h": weather.Rain.TreeHours,
"snow_1h": weather.Snow.OneHour,
"snow_3h": weather.Snow.TreeHours,
}
point, _ := influx.NewPoint(w.Config.InfluxDB.Measurement, tags, fields, time.Now())
bps.AddPoint(point)
}
err = conn.Write(bps)
if err != nil {
return err
}
return nil
}