You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
2.6 KiB

package api
import (
"encoding/json"
"fmt"
"git.darknebu.la/akarl/tankerkoenig2influx/struct"
"github.com/spf13/viper"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
func GetDetailInfoByUuid(Uuid string) (Details structure.DetailInfos, err error) {
fmt.Printf("Fetching DetailInfo for: %s\n", Uuid)
url := fmt.Sprintf("https://creativecommons.tankerkoenig.de/json/detail.php?id=%s&apikey=%s", Uuid, viper.GetString("Endpoint.Api"))
tankApiClient := http.Client{
Timeout: time.Second * 2,
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
res, getErr := tankApiClient.Do(req)
if getErr != nil {
log.Fatal(getErr)
}
data, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
}
defer res.Body.Close()
log.Printf("%v", string(data))
var record structure.DetailInfos
if err := json.Unmarshal(data, &record); err != nil {
return structure.DetailInfos{}, err
} else {
return record, nil
}
}
func GetPrices() {
now := time.Now()
fmt.Printf("Run Cron: %v \n", now.Format("02.01.2006 15:04"))
t := viper.GetStringSlice("Stations")
stationsPart := strings.Join(t, ",")
log.Printf("Fetching Price for: %s", stationsPart)
url := fmt.Sprintf("https://creativecommons.tankerkoenig.de/json/prices.php?ids=%s&apikey=%s", stationsPart, viper.GetString("Endpoint.Api"))
tankApiClient := http.Client{
Timeout: time.Second * 2,
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
res, getErr := tankApiClient.Do(req)
if getErr != nil {
log.Fatal(getErr)
}
data, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
}
defer res.Body.Close()
var record structure.PricesRoot
if err := json.Unmarshal(data, &record); err != nil {
log.Print(record.Ok)
log.Printf("Error Unmarshal JSON in GetPrices %v", err)
} else {
for key, element := range record.Prices {
var stationName string
// Get Detailinfo for station - wanted cause you dont get the name of the station from the prices entpoint
data, err := GetDetailInfoByUuid(key)
// If the station is open you will add points to influx?
if element.Status == "open" {
// Check if you get a name from Details Endpoint
// if an error occurred
if err != nil {
log.Println(err.Error())
stationName = ""
} else {
// if no error occurred
stationName = data.Station.Name
}
// insert data in influxdb
InsertInflux(stationName, element.E5, element.E10, element.Diesel)
} else {
// Log that the station is closed
log.Printf("Station %s is closed.", key)
}
}
}
}