Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

73 строки
2.1 KiB

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