-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
96 lines (75 loc) · 1.91 KB
/
main.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
package main
import (
"encoding/json"
"time"
"fmt"
"log"
"net/http"
"github.com/d2r2/go-dht"
"github.com/gorilla/mux"
"github.com/rs/cors"
)
var state = map[string]float32{
"temperature": 0,
"humidity": 0,
}
var lastUpdate = time.Now()
// Root does Root
func Root(w http.ResponseWriter, r *http.Request) {
temperature, humidity, retried, err := dht.ReadDHTxxWithRetry(dht.DHT22, 4, false, 10)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, `temp: %v\nhumidity: %v\nreried: %v`, temperature, humidity, retried)
}
// SensorState set and get state
func SensorState() map[string]float32 {
newTime := time.Now()
if newTime.Sub(lastUpdate).Seconds() > 10 {
temperature, humidity, _, err := dht.ReadDHTxxWithRetry(dht.DHT22, 4, false, 10)
if err != nil {
log.Fatal(err)
}
lastUpdate = newTime
state["temperature"] = temperature
state["humidity"] = humidity
}
return (state)
}
// Humidity blah
func Humidity(w http.ResponseWriter, r *http.Request) {
SensorState()
humidity := map[string]float32{
"humidity": state["humidity"],
}
payload, err := json.Marshal(humidity)
if err != nil {
log.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(payload)
}
// Temperature temp
func Temperature(w http.ResponseWriter, r *http.Request) {
SensorState()
temperature := map[string]float32{
"temperature": state["temperature"],
}
payload, err := json.Marshal(temperature)
if err != nil {
log.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(payload)
}
func main() {
router := mux.NewRouter()
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000"},
})
router.HandleFunc("/", Root).Methods("GET")
router.HandleFunc("/api/humidity", Humidity).Methods("GET")
router.HandleFunc("/api/temperature", Temperature).Methods("GET")
handler := c.Handler(router)
log.Fatal(http.ListenAndServe("0.0.0.0:3000", handler))
}