|
- package main
-
- import (
- "context"
- "encoding/json"
- "fmt"
- "time"
-
- "github.com/AFASystems/presence/internal/pkg/common/appcontext"
- "github.com/AFASystems/presence/internal/pkg/common/utils"
- "github.com/AFASystems/presence/internal/pkg/config"
- "github.com/AFASystems/presence/internal/pkg/kafkaclient"
- "github.com/AFASystems/presence/internal/pkg/model"
- "github.com/segmentio/kafka-go"
- )
-
- func main() {
- // Load global context to init beacons and latest list
- appState := appcontext.NewAppState()
- cfg := config.Load()
-
- // Kafka reader for Raw MQTT beacons
- rawReader := kafkaclient.KafkaReader(cfg.KafkaURL, "rawbeacons", "gid-raw-loc")
- defer rawReader.Close()
-
- // Kafka reader for API server updates
- apiReader := kafkaclient.KafkaReader(cfg.KafkaURL, "apibeacons", "gid-api-loc")
- defer apiReader.Close()
-
- writer := kafkaclient.KafkaWriter(cfg.KafkaURL, "locevents")
- defer writer.Close()
-
- fmt.Println("Locations algorithm initialized, subscribed to Kafka topics")
-
- locTicker := time.NewTicker(1 * time.Second)
- defer locTicker.Stop()
-
- chRaw := make(chan model.BeaconAdvertisement, 2000)
- chApi := make(chan model.ApiUpdate, 2000)
-
- go kafkaclient.Consume(rawReader, chRaw)
- go kafkaclient.Consume(apiReader, chApi)
-
- for {
- select {
- case <-locTicker.C:
- getLikelyLocations(appState, writer)
- case msg := <-chRaw:
- assignBeaconToList(msg, appState)
- case msg := <-chApi:
- switch msg.Method {
- case "POST":
- id := msg.Beacon.ID
- fmt.Println("Beacon added to lookup: ", id)
- appState.AddBeaconToLookup(id)
- case "DELETE":
- fmt.Println("Incoming delete message")
- }
- }
- }
- }
-
- func getLikelyLocations(appState *appcontext.AppState, writer *kafka.Writer) {
- beacons := appState.GetAllBeacons()
- settings := appState.GetSettingsValue()
-
- for _, beacon := range beacons {
- // Shrinking the model because other properties have nothing to do with the location
- r := model.HTTPLocation{
- Method: "Standard",
- Distance: 999,
- ID: beacon.ID,
- Location: "",
- LastSeen: 999,
- }
-
- mSize := len(beacon.BeaconMetrics)
-
- if (int64(time.Now().Unix()) - (beacon.BeaconMetrics[mSize-1].Timestamp)) > settings.LastSeenThreshold {
- fmt.Println("Beacon is too old")
- continue
- }
-
- locList := make(map[string]float64)
- seenW := 1.5
- rssiW := 0.75
- for _, metric := range beacon.BeaconMetrics {
- res := seenW + (rssiW * (1.0 - (float64(metric.RSSI) / -100.0)))
- locList[metric.Location] += res
- }
-
- bestLocName := ""
- maxScore := 0.0
- for locName, score := range locList {
- if score > maxScore {
- maxScore = score
- bestLocName = locName
- }
- }
-
- if bestLocName == beacon.PreviousLocation {
- beacon.LocationConfidence++
- } else {
- beacon.LocationConfidence = 0
- }
-
- r.Distance = beacon.BeaconMetrics[mSize-1].Distance
- r.Location = bestLocName
- r.LastSeen = beacon.BeaconMetrics[mSize-1].Timestamp
-
- if beacon.LocationConfidence == settings.LocationConfidence && beacon.PreviousConfidentLocation != bestLocName {
- beacon.LocationConfidence = 0
-
- // Why do I need this if I am sending entire structure anyways? who knows
- fmt.Println("this is called")
- js, err := json.Marshal(model.LocationChange{
- Method: "LocationChange",
- BeaconRef: beacon,
- Name: beacon.Name,
- PreviousLocation: beacon.PreviousConfidentLocation,
- NewLocation: bestLocName,
- Timestamp: time.Now().Unix(),
- })
-
- if err != nil {
- fmt.Println("This error happens: ", err)
- beacon.PreviousConfidentLocation = bestLocName
- beacon.PreviousLocation = bestLocName
- appState.UpdateBeacon(beacon.ID, beacon)
- continue
- }
-
- msg := kafka.Message{
- Value: js,
- }
-
- err = writer.WriteMessages(context.Background(), msg)
- if err != nil {
- fmt.Println("Error in sending Kafka message")
- }
- }
-
- beacon.PreviousLocation = bestLocName
- appState.UpdateBeacon(beacon.ID, beacon)
-
- js, err := json.Marshal(r)
- if err != nil {
- fmt.Println("Error in marshaling location: ", err)
- continue
- }
-
- msg := kafka.Message{
- Value: js,
- }
-
- err = writer.WriteMessages(context.Background(), msg)
- if err != nil {
- fmt.Println("Error in sending Kafka message: ", err)
- }
- }
- }
-
- func assignBeaconToList(adv model.BeaconAdvertisement, appState *appcontext.AppState) {
- id := adv.MAC
- ok := appState.BeaconExists(id)
- now := time.Now().Unix()
-
- if !ok {
- appState.UpdateLatestBeacon(id, model.Beacon{ID: id, BeaconType: adv.BeaconType, LastSeen: now, IncomingJSON: adv, BeaconLocation: adv.Hostname, Distance: utils.CalculateDistance(adv)})
- return
- }
-
- settings := appState.GetSettingsValue()
-
- if settings.RSSIEnforceThreshold && (int64(adv.RSSI) < settings.RSSIMinThreshold) {
- fmt.Println("Settings returns")
- return
- }
-
- beacon, ok := appState.GetBeacon(id)
- if !ok {
- beacon = model.Beacon{
- ID: id,
- }
- }
-
- beacon.IncomingJSON = adv
- beacon.LastSeen = now
-
- if beacon.BeaconMetrics == nil {
- beacon.BeaconMetrics = make([]model.BeaconMetric, 0, settings.BeaconMetricSize)
- }
-
- metric := model.BeaconMetric{
- Distance: utils.CalculateDistance(adv),
- Timestamp: now,
- RSSI: int64(adv.RSSI),
- Location: adv.Hostname,
- }
-
- if len(beacon.BeaconMetrics) >= settings.BeaconMetricSize {
- copy(beacon.BeaconMetrics, beacon.BeaconMetrics[1:])
- beacon.BeaconMetrics[settings.BeaconMetricSize-1] = metric
- } else {
- beacon.BeaconMetrics = append(beacon.BeaconMetrics, metric)
- }
-
- appState.UpdateBeacon(id, beacon)
- }
|