1
0
Fork 0
mirror of https://github.com/shouptech/tempgopher.git synced 2026-02-03 16:49:42 +00:00

Add status handler

This commit is contained in:
Emma 2018-09-30 15:45:22 -06:00
parent b353b15004
commit 60c2f3c930
2 changed files with 25 additions and 8 deletions

View file

@ -12,11 +12,11 @@ import (
// State represents the current state of the thermostat
type State struct {
ID string
Temp float64
Cooling bool
Heating bool
Changed time.Time
Alias string `json:"alias"`
Temp float64 `json:"temp"`
Cooling bool `json:"cooling"`
Heating bool `json:"heating"`
Changed time.Time `json:"changed"`
}
// ReadTemperature will return the current temperature (in degrees celsius) of a specific sensor.
@ -54,7 +54,7 @@ func PinSwitch(pin rpio.Pin, on bool, invert bool) {
// RunThermostat monitors the temperature of the supplied sensor and does its best to keep it at the desired state.
func RunThermostat(sensor Sensor, sc chan<- State, run *bool, wg *sync.WaitGroup) {
var s State
s.ID = sensor.ID
s.Alias = sensor.Alias
s.Changed = time.Now()
cpin := rpio.Pin(sensor.CoolGPIO)
@ -114,6 +114,7 @@ func RunThermostat(sensor Sensor, sc chan<- State, run *bool, wg *sync.WaitGroup
}
}
log.Printf("%s Shutting down thermostat", sensor.Alias)
PinSwitch(cpin, false, sensor.CoolInvert)
PinSwitch(hpin, false, sensor.HeatInvert)
wg.Done()

20
web.go
View file

@ -10,11 +10,24 @@ import (
"github.com/gin-gonic/gin"
)
var states map[string]State
// PingHandler responds to get requests with the message "pong".
func PingHandler(c *gin.Context) {
c.String(http.StatusOK, "pong")
}
// StatusHandler responds to get requests with the current status of a sensor
func StatusHandler(c *gin.Context) {
if c.Param("alias") == "/" {
c.JSON(http.StatusOK, states)
} else if val, ok := states[c.Param("alias")[1:]]; ok {
c.JSON(http.StatusOK, val)
} else {
c.JSON(http.StatusNotFound, "Not found")
}
}
// SetupRouter initializes the gin router.
func SetupRouter() *gin.Engine {
r := gin.Default()
@ -24,17 +37,20 @@ func SetupRouter() *gin.Engine {
// Ping
r.GET("/ping", PingHandler)
// Status
r.GET("/api/status/*alias", StatusHandler)
return r
}
// RunWeb launches a web server. sc is used to update the states from the Thermostats.
func RunWeb(sc <-chan State, done <-chan bool, wg *sync.WaitGroup) {
// Update sensor states when a new state comes back from the thermostat.
states := make(map[string]State)
states = make(map[string]State)
go func() {
for {
s := <-sc
states[s.ID] = s
states[s.Alias] = s
}
}()