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.
 
 
 
 

207 lines
5.1 KiB

  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  8. "log/slog"
  9. "os"
  10. "os/signal"
  11. "sync"
  12. "syscall"
  13. "time"
  14. "github.com/AFASystems/presence/internal/pkg/common/appcontext"
  15. "github.com/AFASystems/presence/internal/pkg/common/utils"
  16. "github.com/AFASystems/presence/internal/pkg/config"
  17. "github.com/AFASystems/presence/internal/pkg/kafkaclient"
  18. "github.com/AFASystems/presence/internal/pkg/model"
  19. "github.com/segmentio/kafka-go"
  20. )
  21. var wg sync.WaitGroup
  22. func main() {
  23. // Load global context to init beacons and latest list
  24. appState := appcontext.NewAppState()
  25. cfg := config.Load()
  26. // Create log file
  27. logFile, err := os.OpenFile("server.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  28. if err != nil {
  29. log.Fatalf("Failed to open log file: %v\n", err)
  30. }
  31. // shell and log file multiwriter
  32. w := io.MultiWriter(os.Stderr, logFile)
  33. logger := slog.New(slog.NewJSONHandler(w, nil))
  34. slog.SetDefault(logger)
  35. // Define context
  36. ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
  37. defer stop()
  38. rawReader := appState.AddKafkaReader(cfg.KafkaURL, "rawbeacons", "gid-raw-loc")
  39. settingsReader := appState.AddKafkaReader(cfg.KafkaURL, "settings", "gid-settings-loc")
  40. writer := appState.AddKafkaWriter(cfg.KafkaURL, "locevents")
  41. slog.Info("Locations algorithm initialized, subscribed to Kafka topics")
  42. locTicker := time.NewTicker(1 * time.Second)
  43. defer locTicker.Stop()
  44. chRaw := make(chan model.BeaconAdvertisement, 2000)
  45. chSettings := make(chan map[string]any, 5)
  46. wg.Add(3)
  47. go kafkaclient.Consume(rawReader, chRaw, ctx, &wg)
  48. go kafkaclient.Consume(settingsReader, chSettings, ctx, &wg)
  49. eventLoop:
  50. for {
  51. select {
  52. case <-ctx.Done():
  53. break eventLoop
  54. case <-locTicker.C:
  55. settings := appState.GetSettings()
  56. fmt.Printf("Settings: %+v\n", settings)
  57. switch settings.CurrentAlgorithm {
  58. case "filter":
  59. getLikelyLocations(appState, writer)
  60. case "ai":
  61. fmt.Println("AI algorithm selected")
  62. }
  63. case msg := <-chRaw:
  64. assignBeaconToList(msg, appState)
  65. case msg := <-chSettings:
  66. fmt.Printf("settings msg: %+v\n", msg)
  67. appState.UpdateSettings(msg)
  68. }
  69. }
  70. slog.Info("broken out of the main event loop")
  71. wg.Wait()
  72. slog.Info("All go routines have stopped, Beggining to close Kafka connections")
  73. appState.CleanKafkaReaders()
  74. appState.CleanKafkaWriters()
  75. }
  76. func getLikelyLocations(appState *appcontext.AppState, writer *kafka.Writer) {
  77. beacons := appState.GetAllBeacons()
  78. settings := appState.GetSettingsValue()
  79. for _, beacon := range beacons {
  80. // Shrinking the model because other properties have nothing to do with the location
  81. r := model.HTTPLocation{
  82. Method: "Standard",
  83. Distance: 999,
  84. ID: beacon.ID,
  85. Location: "",
  86. LastSeen: 999,
  87. }
  88. mSize := len(beacon.BeaconMetrics)
  89. if (int64(time.Now().Unix()) - (beacon.BeaconMetrics[mSize-1].Timestamp)) > settings.LastSeenThreshold {
  90. slog.Warn("beacon is too old")
  91. continue
  92. }
  93. locList := make(map[string]float64)
  94. seenW := 1.5
  95. rssiW := 0.75
  96. for _, metric := range beacon.BeaconMetrics {
  97. res := seenW + (rssiW * (1.0 - (float64(metric.RSSI) / -100.0)))
  98. locList[metric.Location] += res
  99. }
  100. bestLocName := ""
  101. maxScore := 0.0
  102. for locName, score := range locList {
  103. if score > maxScore {
  104. maxScore = score
  105. bestLocName = locName
  106. }
  107. }
  108. if bestLocName == beacon.PreviousLocation {
  109. beacon.LocationConfidence++
  110. } else {
  111. beacon.LocationConfidence = 0
  112. }
  113. r.Distance = beacon.BeaconMetrics[mSize-1].Distance
  114. r.Location = bestLocName
  115. r.LastSeen = beacon.BeaconMetrics[mSize-1].Timestamp
  116. if beacon.LocationConfidence == settings.LocationConfidence && beacon.PreviousConfidentLocation != bestLocName {
  117. beacon.LocationConfidence = 0
  118. }
  119. beacon.PreviousLocation = bestLocName
  120. appState.UpdateBeacon(beacon.ID, beacon)
  121. js, err := json.Marshal(r)
  122. if err != nil {
  123. eMsg := fmt.Sprintf("Error in marshaling location: %v", err)
  124. slog.Error(eMsg)
  125. continue
  126. }
  127. msg := kafka.Message{
  128. Value: js,
  129. }
  130. err = writer.WriteMessages(context.Background(), msg)
  131. if err != nil {
  132. eMsg := fmt.Sprintf("Error in sending Kafka message: %v", err)
  133. slog.Error(eMsg)
  134. }
  135. }
  136. }
  137. func assignBeaconToList(adv model.BeaconAdvertisement, appState *appcontext.AppState) {
  138. id := adv.ID
  139. now := time.Now().Unix()
  140. settings := appState.GetSettingsValue()
  141. if settings.RSSIEnforceThreshold && (int64(adv.RSSI) < settings.RSSIMinThreshold) {
  142. slog.Info("Settings returns")
  143. return
  144. }
  145. beacon, ok := appState.GetBeacon(id)
  146. if !ok {
  147. beacon = model.Beacon{
  148. ID: id,
  149. }
  150. }
  151. beacon.IncomingJSON = adv
  152. beacon.LastSeen = now
  153. if beacon.BeaconMetrics == nil {
  154. beacon.BeaconMetrics = make([]model.BeaconMetric, 0, settings.BeaconMetricSize)
  155. }
  156. metric := model.BeaconMetric{
  157. Distance: utils.CalculateDistance(adv),
  158. Timestamp: now,
  159. RSSI: int64(adv.RSSI),
  160. Location: adv.Hostname,
  161. }
  162. if len(beacon.BeaconMetrics) >= settings.BeaconMetricSize {
  163. copy(beacon.BeaconMetrics, beacon.BeaconMetrics[1:])
  164. beacon.BeaconMetrics[settings.BeaconMetricSize-1] = metric
  165. } else {
  166. beacon.BeaconMetrics = append(beacon.BeaconMetrics, metric)
  167. }
  168. appState.UpdateBeacon(id, beacon)
  169. }