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.
 
 
 
 

204 rivejä
5.1 KiB

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