選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

231 行
6.0 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. settingsReader := appState.AddKafkaReader(cfg.KafkaURL, "settings", "gid-settings-loc")
  28. writer := appState.AddKafkaWriter(cfg.KafkaURL, "locevents")
  29. fmt.Println("Locations algorithm initialized, subscribed to Kafka topics")
  30. locTicker := time.NewTicker(1 * time.Second)
  31. defer locTicker.Stop()
  32. chRaw := make(chan model.BeaconAdvertisement, 2000)
  33. chApi := make(chan model.ApiUpdate, 2000)
  34. chSettings := make(chan model.SettingsVal, 5)
  35. wg.Add(3)
  36. go kafkaclient.Consume(rawReader, chRaw, ctx, &wg)
  37. go kafkaclient.Consume(apiReader, chApi, ctx, &wg)
  38. go kafkaclient.Consume(settingsReader, chSettings, ctx, &wg)
  39. eventLoop:
  40. for {
  41. select {
  42. case <-ctx.Done():
  43. break eventLoop
  44. case <-locTicker.C:
  45. getLikelyLocations(appState, writer)
  46. case msg := <-chRaw:
  47. assignBeaconToList(msg, appState)
  48. case msg := <-chApi:
  49. switch msg.Method {
  50. case "POST":
  51. id := msg.Beacon.ID
  52. fmt.Println("Beacon added to lookup: ", id)
  53. appState.AddBeaconToLookup(id)
  54. case "DELETE":
  55. id := msg.Beacon.ID
  56. appState.RemoveBeaconFromLookup(id)
  57. fmt.Println("Beacon removed from lookup: ", id)
  58. }
  59. case msg := <-chSettings:
  60. appState.UpdateSettings(msg)
  61. }
  62. }
  63. fmt.Println("broken out of the main event loop")
  64. wg.Wait()
  65. fmt.Println("All go routines have stopped, Beggining to close Kafka connections")
  66. appState.CleanKafkaReaders()
  67. appState.CleanKafkaWriters()
  68. }
  69. func getLikelyLocations(appState *appcontext.AppState, writer *kafka.Writer) {
  70. beacons := appState.GetAllBeacons()
  71. settings := appState.GetSettingsValue()
  72. for _, beacon := range beacons {
  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. fmt.Println("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. fmt.Println("this is called")
  113. js, err := json.Marshal(model.LocationChange{
  114. Method: "LocationChange",
  115. BeaconRef: beacon,
  116. Name: beacon.Name,
  117. PreviousLocation: beacon.PreviousConfidentLocation,
  118. NewLocation: bestLocName,
  119. Timestamp: time.Now().Unix(),
  120. })
  121. if err != nil {
  122. fmt.Println("This error happens: ", err)
  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. fmt.Println("Error in marshaling location: ", err)
  141. continue
  142. }
  143. msg := kafka.Message{
  144. Value: js,
  145. }
  146. err = writer.WriteMessages(context.Background(), msg)
  147. if err != nil {
  148. fmt.Println("Error in sending Kafka message: ", err)
  149. }
  150. }
  151. }
  152. func assignBeaconToList(adv model.BeaconAdvertisement, appState *appcontext.AppState) {
  153. id := adv.MAC
  154. ok := appState.BeaconExists(id)
  155. now := time.Now().Unix()
  156. if !ok {
  157. appState.UpdateLatestBeacon(id, model.Beacon{ID: id, BeaconType: adv.BeaconType, LastSeen: now, IncomingJSON: adv, BeaconLocation: adv.Hostname, Distance: utils.CalculateDistance(adv)})
  158. return
  159. }
  160. settings := appState.GetSettingsValue()
  161. if settings.RSSIEnforceThreshold && (int64(adv.RSSI) < settings.RSSIMinThreshold) {
  162. fmt.Println("Settings returns")
  163. return
  164. }
  165. beacon, ok := appState.GetBeacon(id)
  166. if !ok {
  167. beacon = model.Beacon{
  168. ID: id,
  169. }
  170. }
  171. beacon.IncomingJSON = adv
  172. beacon.LastSeen = now
  173. if beacon.BeaconMetrics == nil {
  174. beacon.BeaconMetrics = make([]model.BeaconMetric, 0, settings.BeaconMetricSize)
  175. }
  176. metric := model.BeaconMetric{
  177. Distance: utils.CalculateDistance(adv),
  178. Timestamp: now,
  179. RSSI: int64(adv.RSSI),
  180. Location: adv.Hostname,
  181. }
  182. if len(beacon.BeaconMetrics) >= settings.BeaconMetricSize {
  183. copy(beacon.BeaconMetrics, beacon.BeaconMetrics[1:])
  184. beacon.BeaconMetrics[settings.BeaconMetricSize-1] = metric
  185. } else {
  186. beacon.BeaconMetrics = append(beacon.BeaconMetrics, metric)
  187. }
  188. appState.UpdateBeacon(id, beacon)
  189. }