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.
 
 
 
 

93 regels
2.1 KiB

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