weather/functions.go

129 lines
2.7 KiB
Go

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(configfile string, weatherconfig *WeatherConfig) error {
flag.Usage = Usage
config, err := ini.Load(configfile)
if err != nil {
return err
}
var wc WeatherConfig
weatherSection := config.Section("weather")
wc.WeatherVersion = weatherSection.Key("version").String()
wc.WeatherAppID = weatherSection.Key("appid").String()
wc.WeatherCities = weatherSection.Key("cities").Strings(",")
wc.WeatherMeasurements = weatherSection.Key("measurements").Strings(",")
wc.WeatherTable = weatherSection.Key("table").String()
influxdbSection := config.Section("influxdb")
wc.InfluxHost = influxdbSection.Key("hostname").String()
wc.InfluxPort, err = influxdbSection.Key("port").Int()
if err != nil {
return err
}
wc.InfluxUser = influxdbSection.Key("username").String()
wc.InfluxPass = influxdbSection.Key("password").String()
wc.InfluxDB = influxdbSection.Key("database").String()
*weatherconfig = wc
return err
}
func FetchData(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,
}}
resp, err := c.Get(fmt.Sprintf("https://api.openweathermap.org/data/%s/weather?q=%s&appid=%s", wc.WeatherVersion, city, wc.WeatherAppID))
b, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(b, &d)
d.Temperature = kelvin + d.Main["temp"]
d.Humidity = int64(d.Main["humidity"])
return d, err
}
// SendToInflux sends time series data to influxdb
func SendToInflux(wc *WeatherConfig, d Data) error {
httpClient, err := client.NewHTTPClient(client.HTTPConfig{
Addr: fmt.Sprintf("http://%s:%d", wc.InfluxHost, wc.InfluxPort),
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
}
tags := map[string]string{"city": d.City}
fields := map[string]interface{}{"value": d.Temperature}
point, _ := client.NewPoint(
"temperature",
tags,
fields,
time.Now(),
)
bp.AddPoint(point)
err = httpClient.Write(bp)
if err != nil {
return err
}
tags = map[string]string{"city": d.City}
fields = map[string]interface{}{"value": d.Humidity}
point, _ = client.NewPoint(
"humidity",
tags,
fields,
time.Now(),
)
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)
}