summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2024-11-04 10:45:28 -0500
committerSam Anthony <sam@samanthony.xyz>2024-11-04 10:45:28 -0500
commitba7d760a2f832465fdeddc64241a7bb378d68b5e (patch)
treedb1cc711750c27a190bc7c63ca4f008b952c69ee
parentd97eb666b84fd2368aeade810abcdf535c542a89 (diff)
downloadsoen422-ba7d760a2f832465fdeddc64241a7bb378d68b5e.zip
server: calculate average humidity of building
-rw-r--r--server/server.go30
1 files changed, 24 insertions, 6 deletions
diff --git a/server/server.go b/server/server.go
index 2795890..53e5db2 100644
--- a/server/server.go
+++ b/server/server.go
@@ -48,15 +48,12 @@ func (h HumidityHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
func (h HumidityHandler) get(w http.ResponseWriter, r *http.Request) {
- c := make(chan float32)
- h.humidity.getRecent <- c
- humidity, ok := <-c
- if !ok {
+ if humidity, ok := h.average(); ok {
+ fmt.Fprintf(w, "%.2f", humidity)
+ } else {
w.WriteHeader(http.StatusGone)
fmt.Fprintf(w, "no humidity data stored on server")
- return
}
- fmt.Fprintf(w, "%.2f", humidity)
}
func (h HumidityHandler) post(w http.ResponseWriter, r *http.Request) {
@@ -70,6 +67,27 @@ func (h HumidityHandler) post(w http.ResponseWriter, r *http.Request) {
h.humidity.put <- float32(humidity)
}
+// Calculate the average humidity in the building. Returns false if there is not enough data available.
+func (h HumidityHandler) average() (Humidity, bool) {
+ sum := 0
+ nRooms := 0
+ for room, record := range h.rooms {
+ c := make(chan Humidity)
+ record.getRecent() <- c
+ if humidity, ok := <-c; ok {
+ sum += humidity
+ nRooms++
+ } else {
+ log.Printf("Warning: no humidity for room '%s'\n", room)
+ }
+ }
+ if nRooms == 0 {
+ log.Println("Warning: not enough data to calculate average humidity")
+ return -1.0, false
+ }
+ return sum/nRooms, true
+}
+
func main() {
humidityHandler := newHumidityHandler()
defer humidityHandler.Close()