MQTTListener/main.go

67 lines
1.1 KiB
Go
Raw Normal View History

2020-08-26 09:54:26 +02:00
package main
import (
"mqttListener/Config"
"mqttListener/models"
2020-08-26 09:54:26 +02:00
"mqttListener/mqtt"
"fmt"
"log"
2020-08-26 09:54:26 +02:00
"os"
"os/signal"
"syscall"
"net/http"
2020-08-26 09:54:26 +02:00
)
type Env struct {
db models.Datastore
}
2020-08-26 09:54:26 +02:00
func main() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
Config.ReadConfig()
// DEBUG Config
// fmt.Println("BrokerAddress = ", Config.BrokerAddress)
db, err := models.NewDB("simple.sqlite")
if err != nil {
log.Panic(err)
}
env := &Env{db}
2020-08-26 09:54:26 +02:00
mqtt.Setup()
mqtt.Connect()
go mqtt.Listen()
http.HandleFunc("/devices", env.devicesIndex)
go http.ListenAndServe(":3000", nil)
2020-08-26 09:54:26 +02:00
fmt.Println("awaiting signal")
2020-08-26 09:54:26 +02:00
<-c // wait for SIGTERM
fmt.Println("exiting")
2020-08-26 09:54:26 +02:00
mqtt.Disconnect()
}
func (env *Env) devicesIndex(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), 405)
return
}
devices, err := env.db.AllDevices()
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
for _, device := range devices {
fmt.Fprintf(w, "%s, %s, %s, £%.2f\n", device.ID, device.MAC, device.SN, device.LastMsg)
}
}