From 60c2f3c930af28afdb42cc85ba58662ceda39fdb Mon Sep 17 00:00:00 2001 From: Mike Shoup Date: Sun, 30 Sep 2018 15:45:22 -0600 Subject: [PATCH] Add status handler --- thermostat.go | 13 +++++++------ web.go | 20 ++++++++++++++++++-- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/thermostat.go b/thermostat.go index e17cc7e..bff97ed 100644 --- a/thermostat.go +++ b/thermostat.go @@ -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() diff --git a/web.go b/web.go index f3c4a2a..a021bd8 100644 --- a/web.go +++ b/web.go @@ -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 } }()