Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

99 righe
2.3 KiB

  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "slices"
  7. "strings"
  8. "time"
  9. "github.com/AFASystems/presence/internal/pkg/common/appcontext"
  10. "github.com/AFASystems/presence/internal/pkg/model"
  11. "github.com/segmentio/kafka-go"
  12. "gorm.io/gorm"
  13. )
  14. func LocationToBeaconService(msg model.HTTPLocation, db *gorm.DB, writer *kafka.Writer, ctx context.Context) {
  15. if msg.ID == "" {
  16. fmt.Println("empty ID")
  17. return
  18. }
  19. var zones []model.TrackerZones
  20. if err := db.Select("zoneList").Where("tracker = ?", msg.ID).Find(&zones).Error; err != nil {
  21. return
  22. }
  23. var allowedZones []string
  24. for _, z := range zones {
  25. allowedZones = append(allowedZones, z.ZoneList...)
  26. }
  27. var gw model.Gateway
  28. mac := formatMac(msg.Location)
  29. if err := db.Select("id").Where("mac = ?", mac).First(&gw).Error; err != nil {
  30. fmt.Printf("Gateway not found for MAC: %s\n", mac)
  31. return
  32. }
  33. if len(allowedZones) != 0 && !slices.Contains(allowedZones, gw.ID) {
  34. alert := model.Alert{
  35. ID: msg.ID,
  36. Type: "Restricted zone",
  37. Value: gw.ID,
  38. }
  39. eMsg, err := json.Marshal(alert)
  40. if err != nil {
  41. fmt.Println("Error in marshaling")
  42. } else {
  43. msg := kafka.Message{
  44. Value: eMsg,
  45. }
  46. writer.WriteMessages(ctx, msg)
  47. }
  48. }
  49. if err := db.Create(&model.Tracks{UUID: msg.ID, Timestamp: time.Now(), Gateway: gw.ID, GatewayMac: gw.MAC, Tracker: msg.ID}).Error; err != nil {
  50. fmt.Println("Error in saving distance for beacon: ", err)
  51. return
  52. }
  53. if err := db.Updates(&model.Tracker{ID: msg.ID, Location: gw.ID, Distance: msg.Distance}).Error; err != nil {
  54. fmt.Println("Error in saving distance for beacon: ", err)
  55. return
  56. }
  57. }
  58. func EventToBeaconService(msg model.BeaconEvent, appState *appcontext.AppState, ctx context.Context) error {
  59. id := msg.ID
  60. beacon, ok := appState.GetHTTPResult(id)
  61. if !ok {
  62. appState.UpdateHTTPResult(id, model.HTTPResult{ID: id, BeaconType: msg.Type, Battery: int64(msg.Battery), Event: msg.Event})
  63. } else {
  64. beacon.ID = id
  65. beacon.BeaconType = msg.Type
  66. beacon.Battery = int64(msg.Battery)
  67. beacon.Event = msg.Event
  68. appState.UpdateHTTPResult(id, beacon)
  69. }
  70. return nil
  71. }
  72. func formatMac(MAC string) string {
  73. var res strings.Builder
  74. for i := 0; i < len(MAC); i += 2 {
  75. if i > 0 {
  76. res.WriteByte(':')
  77. }
  78. end := min(i+2, len(MAC))
  79. res.WriteString(MAC[i:end])
  80. }
  81. return res.String()
  82. }