// NewRouter sets the routes to the web service func NewRouter(b *wsblaster.Blaster) *mux.Router { // And route for '/ws' explicitly since we need access to 'b' routes = append(routes, Route{ "Websocket", "GET", "/ws", b.GetWSHandler(), }, ) router := mux.NewRouter().StrictSlash(true) for _, route := range routes { var handler http.Handler handler = route.HandlerFunc handler = Logger(handler, route.Name) router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(handler) } return router }
func averageReadings(m *Message, b *wsblaster.Blaster) bool { messages := b.GetReadBuffer() messages.Lock() defer messages.Unlock() numMessages := len(messages.Messages) log.Printf("received %d messages\n", numMessages) var avgTemp float64 var avgRad int32 count := 0 for _, msg := range messages.Messages { reading := &SensorMessage{} err := json.Unmarshal(*msg, reading) if err != nil { log.Println("Unable to unmarshal sensor data") log.Printf("%s\n", err) continue } avgTemp += reading.Temperature avgRad += int32(reading.Radiation) count++ } messages.Messages = nil if count == 0 { return false } m.Lock() defer m.Unlock() m.Radiation = avgRad / int32(count) m.Temperature = avgTemp / float64(count) log.Printf("Averages now: %d, %f", m.Radiation, m.Temperature) return true }