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.
 
 
 
 

224 rivejä
5.7 KiB

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