You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

73 regels
2.1 KiB

  1. package bridge
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "log/slog"
  7. "strings"
  8. "time"
  9. "github.com/AFASystems/presence/internal/pkg/common/appcontext"
  10. "github.com/AFASystems/presence/internal/pkg/kafkaclient"
  11. "github.com/AFASystems/presence/internal/pkg/model"
  12. "github.com/segmentio/kafka-go"
  13. )
  14. // HandleMQTTMessage processes an MQTT message: parses JSON array of RawReading or CSV.
  15. // For JSON, converts each reading to BeaconAdvertisement and writes to the writer if MAC is in lookup.
  16. // Hostname is derived from topic (e.g. "publish_out/gateway1" -> "gateway1"). Safe if topic has no "/".
  17. func HandleMQTTMessage(topic string, payload []byte, appState *appcontext.AppState, writer *kafka.Writer) {
  18. parts := strings.SplitN(topic, "/", 2)
  19. hostname := ""
  20. if len(parts) >= 2 {
  21. hostname = parts[1]
  22. }
  23. msgStr := string(payload)
  24. if strings.HasPrefix(msgStr, "[") {
  25. var readings []model.RawReading
  26. if err := json.Unmarshal(payload, &readings); err != nil {
  27. slog.Error("parsing MQTT JSON", "err", err, "topic", topic)
  28. return
  29. }
  30. for _, reading := range readings {
  31. if reading.Type == "Gateway" {
  32. continue
  33. }
  34. id, ok := appState.BeaconExists(reading.MAC)
  35. if !ok {
  36. continue
  37. }
  38. adv := appcontext.BeaconAdvertisement{
  39. ID: id,
  40. Hostname: hostname,
  41. MAC: reading.MAC,
  42. RSSI: int64(reading.RSSI),
  43. Data: reading.RawData,
  44. }
  45. encoded, err := json.Marshal(adv)
  46. if err != nil {
  47. slog.Error("marshaling beacon advertisement", "err", err)
  48. break
  49. }
  50. if err := kafkaclient.Write(context.Background(), writer, kafka.Message{Value: encoded}); err != nil {
  51. slog.Error("writing to Kafka", "err", err)
  52. time.Sleep(1 * time.Second)
  53. break
  54. }
  55. }
  56. return
  57. } else {
  58. fmt.Println("CSV message: ", msgStr)
  59. }
  60. // CSV format: validate minimum fields (e.g. 6 columns); full parsing can be added later
  61. s := strings.Split(msgStr, ",")
  62. if len(s) < 6 {
  63. slog.Error("invalid CSV MQTT message", "topic", topic, "message", msgStr)
  64. return
  65. }
  66. slog.Debug("CSV MQTT message received", "topic", topic, "fields", len(s))
  67. }