package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "net/http" "os" "time" client "github.com/influxdata/influxdb1-client/v2" "gopkg.in/ini.v1" ) // GetConfig fetch config from ini file func GetConfig(weatherconfig *WeatherConfig, configfile string) error { flag.Usage = Usage config, err := ini.Load(configfile) if err != nil { return err } var wc WeatherConfig weatherSection := config.Section("weather") wc.WeatherAppID = weatherSection.Key("appid").MustString("appid") wc.WeatherCities = weatherSection.Key("cities").Strings(",") if len(wc.WeatherCities) < 1 { return fmt.Errorf("No cities provided in config") } wc.WeatherMeasurements = weatherSection.Key("measurements").Strings(",") if len(wc.WeatherMeasurements) < 1 { return fmt.Errorf("No measurements provided in config") } influxdbSection := config.Section("influxdb") wc.InfluxHost = influxdbSection.Key("hostname").MustString("localhost") wc.InfluxPort = influxdbSection.Key("port").MustInt(8086) wc.InfluxUser = influxdbSection.Key("username").MustString("username") wc.InfluxPass = influxdbSection.Key("password").MustString("password") wc.InfluxDB = influxdbSection.Key("database").MustString("me") *weatherconfig = wc return err } // FetchData fetch data from api func FetchData(wc *WeatherConfig, city string) (Data, error) { var d Data pollTo := 30 * time.Millisecond c := &http.Client{Timeout: pollTo * time.Second, Transport: &http.Transport{ IdleConnTimeout: pollTo, DisableCompression: false, }} q := fmt.Sprintf("https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric", city, wc.WeatherAppID) r, err := c.Get(q) if err != nil { return Data{}, err } b, err := ioutil.ReadAll(r.Body) if err != nil { return Data{}, err } err = json.Unmarshal(b, &d) if err != nil { return Data{}, err } d.Points = map[string]interface{}{"temperature": d.Main.Temperature, "humidity": d.Main.Humidity, "pressure": d.Main.Pressure} return d, nil } // SendToInflux sends time series data to influxdb func SendToInflux(wc *WeatherConfig, d Data) error { wc.InfluxAddr = fmt.Sprintf("http://%s:%d", wc.InfluxHost, wc.InfluxPort) httpClient, err := client.NewHTTPClient(client.HTTPConfig{ Addr: wc.InfluxAddr, Username: wc.InfluxUser, Password: wc.InfluxPass, }) if err != nil { return err } bp, err := client.NewBatchPoints(client.BatchPointsConfig{ Database: wc.InfluxDB, }) if err != nil { return err } for key, value := range d.Points { tags := map[string]string{"city": d.City} fields := map[string]interface{}{"value": value} point, err := client.NewPoint( key, tags, fields, time.Now(), ) if err != nil { return err } bp.AddPoint(point) err = httpClient.Write(bp) if err != nil { return err } } return nil } // Usage displays possible arguments func Usage() { flag.PrintDefaults() os.Exit(1) }