Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

206 рядки
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. switch settings.CurrentAlgorithm {
  57. case "filter":
  58. getLikelyLocations(appState, writer)
  59. case "ai":
  60. fmt.Println("AI algorithm selected")
  61. }
  62. case msg := <-chRaw:
  63. assignBeaconToList(msg, appState)
  64. case msg := <-chSettings:
  65. appState.UpdateSettings(msg)
  66. }
  67. }
  68. slog.Info("broken out of the main event loop")
  69. wg.Wait()
  70. slog.Info("All go routines have stopped, Beggining to close Kafka connections")
  71. appState.CleanKafkaReaders()
  72. appState.CleanKafkaWriters()
  73. }
  74. func getLikelyLocations(appState *appcontext.AppState, writer *kafka.Writer) {
  75. beacons := appState.GetAllBeacons()
  76. settings := appState.GetSettingsValue()
  77. for _, beacon := range beacons {
  78. fmt.Println("id: ", beacon.ID)
  79. // Shrinking the model because other properties have nothing to do with the location
  80. r := model.HTTPLocation{
  81. Method: "Standard",
  82. Distance: 999,
  83. ID: beacon.ID,
  84. Location: "",
  85. LastSeen: 999,
  86. }
  87. mSize := len(beacon.BeaconMetrics)
  88. if (int64(time.Now().Unix()) - (beacon.BeaconMetrics[mSize-1].Timestamp)) > settings.LastSeenThreshold {
  89. slog.Warn("beacon is too old")
  90. continue
  91. }
  92. locList := make(map[string]float64)
  93. seenW := 1.5
  94. rssiW := 0.75
  95. for _, metric := range beacon.BeaconMetrics {
  96. res := seenW + (rssiW * (1.0 - (float64(metric.RSSI) / -100.0)))
  97. locList[metric.Location] += res
  98. }
  99. bestLocName := ""
  100. maxScore := 0.0
  101. for locName, score := range locList {
  102. if score > maxScore {
  103. maxScore = score
  104. bestLocName = locName
  105. }
  106. }
  107. if bestLocName == beacon.PreviousLocation {
  108. beacon.LocationConfidence++
  109. } else {
  110. beacon.LocationConfidence = 0
  111. }
  112. r.Distance = beacon.BeaconMetrics[mSize-1].Distance
  113. r.Location = bestLocName
  114. r.LastSeen = beacon.BeaconMetrics[mSize-1].Timestamp
  115. if beacon.LocationConfidence == settings.LocationConfidence && beacon.PreviousConfidentLocation != bestLocName {
  116. beacon.LocationConfidence = 0
  117. }
  118. beacon.PreviousLocation = bestLocName
  119. appState.UpdateBeacon(beacon.ID, beacon)
  120. js, err := json.Marshal(r)
  121. if err != nil {
  122. eMsg := fmt.Sprintf("Error in marshaling location: %v", err)
  123. slog.Error(eMsg)
  124. continue
  125. }
  126. msg := kafka.Message{
  127. Value: js,
  128. }
  129. err = writer.WriteMessages(context.Background(), msg)
  130. if err != nil {
  131. eMsg := fmt.Sprintf("Error in sending Kafka message: %v", err)
  132. slog.Error(eMsg)
  133. }
  134. }
  135. }
  136. func assignBeaconToList(adv model.BeaconAdvertisement, appState *appcontext.AppState) {
  137. id := adv.ID
  138. now := time.Now().Unix()
  139. settings := appState.GetSettingsValue()
  140. if settings.RSSIEnforceThreshold && (int64(adv.RSSI) < settings.RSSIMinThreshold) {
  141. slog.Info("Settings returns")
  142. return
  143. }
  144. beacon, ok := appState.GetBeacon(id)
  145. if !ok {
  146. beacon = model.Beacon{
  147. ID: id,
  148. }
  149. }
  150. beacon.IncomingJSON = adv
  151. beacon.LastSeen = now
  152. if beacon.BeaconMetrics == nil {
  153. beacon.BeaconMetrics = make([]model.BeaconMetric, 0, settings.BeaconMetricSize)
  154. }
  155. metric := model.BeaconMetric{
  156. Distance: utils.CalculateDistance(adv),
  157. Timestamp: now,
  158. RSSI: int64(adv.RSSI),
  159. Location: adv.Hostname,
  160. }
  161. if len(beacon.BeaconMetrics) >= settings.BeaconMetricSize {
  162. copy(beacon.BeaconMetrics, beacon.BeaconMetrics[1:])
  163. beacon.BeaconMetrics[settings.BeaconMetricSize-1] = metric
  164. } else {
  165. beacon.BeaconMetrics = append(beacon.BeaconMetrics, metric)
  166. }
  167. appState.UpdateBeacon(id, beacon)
  168. }