MQTTListener/main.go
Siegfried Siegert daa79b27ca Extend this program:
- add a database for devices
- read devices from database and present this data on a simple web/REST
interface

The code or model is from a blog entry from Alex Edward:
https://www.alexedwards.net/blog/organising-database-access
2020-08-30 07:16:50 +02:00

67 lines
1.1 KiB
Go

package main
import (
"mqttListener/Config"
"mqttListener/models"
"mqttListener/mqtt"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"net/http"
)
type Env struct {
db models.Datastore
}
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}
mqtt.Setup()
mqtt.Connect()
go mqtt.Listen()
http.HandleFunc("/devices", env.devicesIndex)
go http.ListenAndServe(":3000", nil)
fmt.Println("awaiting signal")
<-c // wait for SIGTERM
fmt.Println("exiting")
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)
}
}