您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

210 行
5.3 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. fmt.Println("Beacon added to lookup: ", id)
  44. appState.AddBeaconToLookup(id)
  45. case "DELETE":
  46. fmt.Println("Incoming delete message")
  47. }
  48. }
  49. }
  50. }
  51. func getLikelyLocations(appState *appcontext.AppState, writer *kafka.Writer) {
  52. beacons := appState.GetAllBeacons()
  53. settings := appState.GetSettingsValue()
  54. for _, beacon := range beacons {
  55. // Shrinking the model because other properties have nothing to do with the location
  56. r := model.HTTPLocation{
  57. Method: "Standard",
  58. Distance: 999,
  59. ID: beacon.ID,
  60. Location: "",
  61. LastSeen: 999,
  62. }
  63. mSize := len(beacon.BeaconMetrics)
  64. if (int64(time.Now().Unix()) - (beacon.BeaconMetrics[mSize-1].Timestamp)) > settings.LastSeenThreshold {
  65. fmt.Println("Beacon is too old")
  66. continue
  67. }
  68. locList := make(map[string]float64)
  69. seenW := 1.5
  70. rssiW := 0.75
  71. for _, metric := range beacon.BeaconMetrics {
  72. res := seenW + (rssiW * (1.0 - (float64(metric.RSSI) / -100.0)))
  73. locList[metric.Location] += res
  74. }
  75. bestLocName := ""
  76. maxScore := 0.0
  77. for locName, score := range locList {
  78. if score > maxScore {
  79. maxScore = score
  80. bestLocName = locName
  81. }
  82. }
  83. if bestLocName == beacon.PreviousLocation {
  84. beacon.LocationConfidence++
  85. } else {
  86. beacon.LocationConfidence = 0
  87. }
  88. r.Distance = beacon.BeaconMetrics[mSize-1].Distance
  89. r.Location = bestLocName
  90. r.LastSeen = beacon.BeaconMetrics[mSize-1].Timestamp
  91. if beacon.LocationConfidence == settings.LocationConfidence && beacon.PreviousConfidentLocation != bestLocName {
  92. beacon.LocationConfidence = 0
  93. // Why do I need this if I am sending entire structure anyways? who knows
  94. fmt.Println("this is called")
  95. js, err := json.Marshal(model.LocationChange{
  96. Method: "LocationChange",
  97. BeaconRef: beacon,
  98. Name: beacon.Name,
  99. PreviousLocation: beacon.PreviousConfidentLocation,
  100. NewLocation: bestLocName,
  101. Timestamp: time.Now().Unix(),
  102. })
  103. if err != nil {
  104. fmt.Println("This error happens: ", err)
  105. beacon.PreviousConfidentLocation = bestLocName
  106. beacon.PreviousLocation = bestLocName
  107. appState.UpdateBeacon(beacon.ID, beacon)
  108. continue
  109. }
  110. msg := kafka.Message{
  111. Value: js,
  112. }
  113. err = writer.WriteMessages(context.Background(), msg)
  114. if err != nil {
  115. fmt.Println("Error in sending Kafka message")
  116. }
  117. }
  118. beacon.PreviousLocation = bestLocName
  119. appState.UpdateBeacon(beacon.ID, beacon)
  120. js, err := json.Marshal(r)
  121. if err != nil {
  122. fmt.Println("Error in marshaling location: ", err)
  123. continue
  124. }
  125. msg := kafka.Message{
  126. Value: js,
  127. }
  128. err = writer.WriteMessages(context.Background(), msg)
  129. if err != nil {
  130. fmt.Println("Error in sending Kafka message: ", err)
  131. }
  132. }
  133. }
  134. func assignBeaconToList(adv model.BeaconAdvertisement, appState *appcontext.AppState) {
  135. id := adv.MAC
  136. ok := appState.BeaconExists(id)
  137. now := time.Now().Unix()
  138. if !ok {
  139. appState.UpdateLatestBeacon(id, model.Beacon{ID: id, BeaconType: adv.BeaconType, LastSeen: now, IncomingJSON: adv, BeaconLocation: adv.Hostname, Distance: utils.CalculateDistance(adv)})
  140. return
  141. }
  142. settings := appState.GetSettingsValue()
  143. if settings.RSSIEnforceThreshold && (int64(adv.RSSI) < settings.RSSIMinThreshold) {
  144. fmt.Println("Settings returns")
  145. return
  146. }
  147. beacon, ok := appState.GetBeacon(id)
  148. if !ok {
  149. beacon = model.Beacon{
  150. ID: id,
  151. }
  152. }
  153. beacon.IncomingJSON = adv
  154. beacon.LastSeen = now
  155. if beacon.BeaconMetrics == nil {
  156. beacon.BeaconMetrics = make([]model.BeaconMetric, 0, settings.BeaconMetricSize)
  157. }
  158. metric := model.BeaconMetric{
  159. Distance: utils.CalculateDistance(adv),
  160. Timestamp: now,
  161. RSSI: int64(adv.RSSI),
  162. Location: adv.Hostname,
  163. }
  164. if len(beacon.BeaconMetrics) >= settings.BeaconMetricSize {
  165. copy(beacon.BeaconMetrics, beacon.BeaconMetrics[1:])
  166. beacon.BeaconMetrics[settings.BeaconMetricSize-1] = metric
  167. } else {
  168. beacon.BeaconMetrics = append(beacon.BeaconMetrics, metric)
  169. }
  170. appState.UpdateBeacon(id, beacon)
  171. }