spacepanel_aggregator/httppoll.go

59 lines
1.0 KiB
Go
Raw Normal View History

2020-01-30 23:24:19 +00:00
package spacepanel_aggregator
import (
2020-01-31 00:59:39 +00:00
"encoding/json"
2020-01-30 23:24:19 +00:00
"fmt"
2020-01-31 00:59:39 +00:00
"io/ioutil"
"net/http"
2020-01-30 23:24:19 +00:00
"time"
)
2020-01-31 14:42:04 +00:00
func Poll(url string, led int) {
2020-01-30 23:24:19 +00:00
for true {
2020-01-31 00:59:39 +00:00
resp, err := http.Get(url)
if err != nil {
2020-01-31 14:42:04 +00:00
ErrorPoll(url, err, led)
2020-01-31 00:59:39 +00:00
} else {
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
2020-01-31 14:42:04 +00:00
ErrorPoll(url, err, led)
2020-01-31 14:20:40 +00:00
_ = resp.Body.Close()
2020-01-31 00:59:39 +00:00
} else {
2020-01-31 14:20:40 +00:00
_ = resp.Body.Close()
2020-01-31 00:59:39 +00:00
var parsed V13
err = json.Unmarshal(data, &parsed)
if err != nil {
2020-01-31 14:42:04 +00:00
ErrorPoll(url, err, led)
2020-01-31 00:59:39 +00:00
} else {
if parsed.State.Open != nil {
open := parsed.State.Open.(bool)
if open {
2020-01-31 14:20:40 +00:00
SetSpaceState(url, Open)
2020-01-31 00:59:39 +00:00
} else {
2020-01-31 14:20:40 +00:00
SetSpaceState(url, Close)
2020-01-31 00:59:39 +00:00
}
} else {
2020-01-31 14:20:40 +00:00
SetSpaceState(url, Unknown)
2020-01-31 00:59:39 +00:00
}
}
}
}
2020-01-30 23:24:19 +00:00
time.Sleep(sleeptime)
}
}
2020-01-31 00:59:39 +00:00
2020-01-31 14:42:04 +00:00
func ErrorPoll(url string, err error, led int) {
2020-01-31 00:59:39 +00:00
if spacestates[url] != Unknown {
2020-01-31 14:20:40 +00:00
SetSpaceState(url, Outdated)
2020-01-31 00:59:39 +00:00
}
2020-01-31 14:42:04 +00:00
fmt.Println("LED", led, err.Error())
2020-01-31 00:59:39 +00:00
}
2020-01-31 14:20:40 +00:00
func SetSpaceState(url string, s State) {
lock.Lock()
spacestates[url] = s
lock.Unlock()
}