-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
146 lines (124 loc) · 4.79 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package main
import (
"bresser-weather-exporter/exporter/influxDb"
"bresser-weather-exporter/exporter/mqtt"
"bresser-weather-exporter/exporter/prometheus"
"bresser-weather-exporter/model"
"bresser-weather-exporter/model/configuration"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
const (
// Endpoint which is called by the weather station for transmitting the data (This endpoint appears to
// be hardcoded in the weather station software and is appended to the server address configured in
// the weather station settings.)
weatherStationApiUrl = "/weatherstation/updateweatherstation.php"
)
var (
BuildVersion = "dev"
BuildTime = "-"
)
var (
weatherData = new(model.WeatherData)
configPath string
config configuration.Configuration
)
func init() {
flag.StringVar(&configPath, "config_path", ".", "path to search for a config.yaml")
}
func loadConfig() {
viper.SetConfigName("config")
viper.AddConfigPath(configPath)
viper.AutomaticEnv()
viper.SetEnvPrefix("weather_exporter")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetDefault("webserverPort", 8080)
viper.SetDefault("loglevel", "info")
viper.SetDefault("jsonExporter", map[string]interface{}{"enabled": true})
viper.SetDefault("prometheusExporter", map[string]interface{}{"enabled": true})
viper.SetDefault("influxDbExporter", map[string]interface{}{"enabled": false})
if err := viper.ReadInConfig(); err != nil {
log.Infof("Unable to read config file, using default values or environment. %s", err)
}
err := viper.Unmarshal(&config)
if err != nil {
log.Fatalf("unable to decode into struct, %v", err)
}
logLevel, err := log.ParseLevel(config.LogLevel)
if err == nil {
log.SetLevel(logLevel)
}
log.Info("Config loaded.")
}
func runWebserver() {
http.HandleFunc(weatherStationApiUrl, weatherStationEventHandler)
if config.JsonExporter.Enabled {
http.HandleFunc("/json", jsonExporterHandler)
}
if config.PrometheusExporter.Enabled {
http.Handle("/metrics", promhttp.Handler())
}
log.Info(fmt.Sprintf("Starting Webserver on port %d", config.WebserverPort))
if err := http.ListenAndServe(fmt.Sprintf(":%d", config.WebserverPort), nil); err != nil {
log.Fatal(err)
}
}
func weatherStationEventHandler(w http.ResponseWriter, req *http.Request) {
keys := req.URL.Query()
log.Debug("Received new data record from weather station: ", keys)
parseDataRecord(keys)
prometheus.UpdatePromGauges(weatherData)
influxDb.WriteDataToDb(weatherData)
mqtt.PublishData(weatherData)
_, err := io.WriteString(w, "success")
if err != nil {
log.Error("Unable to write response string.")
}
}
func parseDataRecord(keys url.Values) {
weatherData.TemperatureOutdoorFahrenheit, weatherData.TemperatureOutdoorCelsius = parseTemperature(keys.Get("tempf"))
weatherData.TemperatureIndoorFahrenheit, weatherData.TemperatureIndoorCelsius = parseTemperature(keys.Get("indoortempf"))
weatherData.HumidityOutdoor = parseInteger(keys.Get("humidity"))
weatherData.HumidityOutdoorAbsolute = float32(calculateAbsoluteHumidity(weatherData.HumidityOutdoor, float64(weatherData.TemperatureOutdoorCelsius)))
weatherData.HumidityIndoor = parseInteger(keys.Get("indoorhumidity"))
weatherData.HumidityIndoorAbsolute = float32(calculateAbsoluteHumidity(weatherData.HumidityIndoor, float64(weatherData.TemperatureIndoorCelsius)))
weatherData.Uv = parseFloat(keys.Get("uv"))
weatherData.BarometerMercury, weatherData.BarometerHektopascal = parsePressure(keys.Get("baromin"))
weatherData.RainDailyInch, weatherData.RainDailyMillimeter = parseRain(keys.Get("dailyrainin"))
weatherData.RainCurrentInch, weatherData.RainCurrentMillimeter = parseRain(keys.Get("rainin"))
weatherData.DewpointFahrenheit, weatherData.DewpointCelsius = parseTemperature(keys.Get("dewptf"))
weatherData.SolarRadiation = parseFloat(keys.Get("solarradiation"))
weatherData.WindDirection = parseInteger(keys.Get("winddir"))
weatherData.WindGustMilesPerHour, weatherData.WindGustKilometerPerHour = parseSpeed(keys.Get("windgustmph"))
weatherData.WindSpeedMilesPerHours, weatherData.WindSpeedKilometerPerHour = parseSpeed(keys.Get("windspeedmph"))
weatherData.LastRefresh = time.Now()
}
func jsonExporterHandler(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err := json.NewEncoder(w).Encode(weatherData)
if err != nil {
log.Error("Unable to generate json string.")
}
}
func main() {
flag.Parse()
log.SetFormatter(&log.TextFormatter{
ForceColors: true,
FullTimestamp: true,
})
log.Infof("Hello Weather Exporter %s! ☀ (Build: %s)", BuildVersion, BuildTime)
loadConfig()
influxDb.SetupInfluxDb(&config)
mqtt.SetupMqttConnection(&config)
runWebserver()
}