Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

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