|
- package service
-
- import (
- "context"
- "encoding/json"
- "fmt"
- "slices"
- "strings"
-
- "github.com/AFASystems/presence/internal/pkg/common/appcontext"
- "github.com/AFASystems/presence/internal/pkg/model"
- "github.com/segmentio/kafka-go"
- "gorm.io/gorm"
- )
-
- func LocationToBeaconService(msg model.HTTPLocation, db *gorm.DB, writer *kafka.Writer, ctx context.Context) {
- if msg.ID == "" {
- return
- }
-
- var zones []model.TrackerZones
- if err := db.Select("zoneList").Where("tracker = ?", msg.ID).Find(&zones).Error; err != nil {
- return
- }
-
- fmt.Printf("zones: %v\n", zones)
-
- var allowedZones []string
- for _, z := range zones {
- allowedZones = append(allowedZones, z.ZoneList...)
- }
-
- var gw model.Gateway
- mac := formatMac(msg.Location)
- if err := db.Select("id").Where("mac = ?", mac).First(&gw).Error; err != nil {
- fmt.Printf("Gateway not found for MAC: %s\n", mac)
- return
- }
-
- if len(allowedZones) != 0 && !slices.Contains(allowedZones, gw.ID) {
- alert := model.Alert{
- ID: msg.ID,
- Type: "Restricted zone",
- Value: gw.ID,
- }
-
- eMsg, err := json.Marshal(alert)
- if err != nil {
- fmt.Println("Error in marshaling")
- } else {
- msg := kafka.Message{
- Value: eMsg,
- }
- writer.WriteMessages(ctx, msg)
- }
- }
-
- if err := db.Updates(&model.Tracker{ID: msg.ID, Location: gw.ID, Distance: msg.Distance}).Error; err != nil {
- fmt.Println("Error in saving distance for beacon: ", err)
- return
- }
- }
-
- // func LocationToBeaconService(msg model.HTTPLocation, appState *appcontext.AppState, ctx context.Context) error {
- // id := msg.ID
- // beacon, ok := appState.GetHTTPResult(id)
- // if !ok {
- // appState.UpdateHTTPResult(id, model.HTTPResult{ID: id, Position: msg.Location, Distance: msg.Distance, LastSeen: msg.LastSeen, PreviousConfidentLocation: msg.PreviousConfidentLocation})
- // } else {
- // beacon.ID = id
- // beacon.Position = msg.Location
- // beacon.Distance = msg.Distance
- // beacon.LastSeen = msg.LastSeen
- // beacon.PreviousConfidentLocation = msg.PreviousConfidentLocation
- // appState.UpdateHTTPResult(id, beacon)
- // }
-
- // return nil
- // }
-
- func EventToBeaconService(msg model.BeaconEvent, appState *appcontext.AppState, ctx context.Context) error {
- id := msg.ID
- beacon, ok := appState.GetHTTPResult(id)
- if !ok {
- appState.UpdateHTTPResult(id, model.HTTPResult{ID: id, BeaconType: msg.Type, Battery: int64(msg.Battery), Event: msg.Event})
- } else {
- beacon.ID = id
- beacon.BeaconType = msg.Type
- beacon.Battery = int64(msg.Battery)
- beacon.Event = msg.Event
- appState.UpdateHTTPResult(id, beacon)
- }
-
- return nil
- }
-
- func formatMac(MAC string) string {
- var res strings.Builder
- for i := 0; i < len(MAC); i += 2 {
- if i > 0 {
- res.WriteByte(':')
- }
-
- end := min(i+2, len(MAC))
-
- res.WriteString(MAC[i:end])
- }
-
- return res.String()
- }
|