feat: implement SQLite storage for state messages and add message retrieval endpoint
This commit is contained in:
+27
-2
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
"git.piskot.si/SeminarM2/lambdaiot-core/internal/handler"
|
||||
"git.piskot.si/SeminarM2/lambdaiot-core/internal/middleware"
|
||||
mqttclient "git.piskot.si/SeminarM2/lambdaiot-core/internal/mqtt"
|
||||
"git.piskot.si/SeminarM2/lambdaiot-core/internal/storage"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -52,6 +54,21 @@ func main() {
|
||||
|
||||
// connect to MQTT broker (best-effort)
|
||||
var mq *mqttclient.Client
|
||||
// initialize sqlite for state messages
|
||||
var db *storage.DB
|
||||
{
|
||||
dbPath := os.Getenv("SQLITE_PATH")
|
||||
if dbPath == "" {
|
||||
dbPath = "state_messages.db"
|
||||
}
|
||||
dbInit, err := storage.Init(dbPath)
|
||||
if err != nil {
|
||||
log.Printf("warning: sqlite init failed: %v", err)
|
||||
} else {
|
||||
db = dbInit
|
||||
storage.SetDefault(db)
|
||||
}
|
||||
}
|
||||
if cfg.MQTT.Broker != "" {
|
||||
mqc, err := mqttclient.Connect(cfg.MQTT)
|
||||
if err != nil {
|
||||
@@ -64,6 +81,12 @@ func main() {
|
||||
if cfg.MQTT.Topic != "" {
|
||||
if err := mq.Subscribe(cfg.MQTT.Topic, func(t string, p []byte) {
|
||||
log.Printf("mqtt recv on %s: %s", t, string(p))
|
||||
// if topic starts with state: -> store in sqlite
|
||||
if strings.HasPrefix(t, "state:") {
|
||||
if storage.Default != nil {
|
||||
_ = storage.Default.InsertMessage(string(p), time.Now())
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
log.Printf("warning: mqtt subscribe failed: %v", err)
|
||||
}
|
||||
@@ -93,8 +116,7 @@ func main() {
|
||||
r.POST("/login", h.Login)
|
||||
r.GET("/devices", h.GetDevices)
|
||||
|
||||
// mqttping endpoint handled by internal/handler
|
||||
r.POST("/mqttping", h.MQTTPing)
|
||||
// mqttping endpoint handled by internal/handler (protected)
|
||||
|
||||
// Protected routes
|
||||
auth := r.Group("/")
|
||||
@@ -130,6 +152,9 @@ func main() {
|
||||
if mq != nil {
|
||||
mq.Close()
|
||||
}
|
||||
if db != nil {
|
||||
db.Close()
|
||||
}
|
||||
log.Println("server exiting")
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user