No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

217 líneas
5.3 KiB

  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  8. "log/slog"
  9. "os"
  10. "os/signal"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. "time"
  15. "github.com/AFASystems/presence/internal/pkg/common/appcontext"
  16. "github.com/AFASystems/presence/internal/pkg/config"
  17. "github.com/AFASystems/presence/internal/pkg/kafkaclient"
  18. "github.com/AFASystems/presence/internal/pkg/model"
  19. mqtt "github.com/eclipse/paho.mqtt.golang"
  20. "github.com/segmentio/kafka-go"
  21. )
  22. var wg sync.WaitGroup
  23. func mqtthandler(writer *kafka.Writer, topic string, message []byte, appState *appcontext.AppState) {
  24. hostname := strings.Split(topic, "/")[1]
  25. msgStr := string(message)
  26. if strings.HasPrefix(msgStr, "[") {
  27. var readings []model.RawReading
  28. err := json.Unmarshal(message, &readings)
  29. if err != nil {
  30. log.Printf("Error parsing JSON: %v", err)
  31. return
  32. }
  33. for _, reading := range readings {
  34. if reading.Type == "Gateway" {
  35. continue
  36. }
  37. val, ok := appState.BeaconExists(reading.MAC)
  38. // fmt.Printf("reading: %+v\n", reading)
  39. if !ok {
  40. continue
  41. }
  42. adv := model.BeaconAdvertisement{
  43. ID: val,
  44. Hostname: hostname,
  45. MAC: reading.MAC,
  46. RSSI: int64(reading.RSSI),
  47. Data: reading.RawData,
  48. }
  49. encodedMsg, err := json.Marshal(adv)
  50. if err != nil {
  51. fmt.Println("Error in marshaling: ", err)
  52. break
  53. }
  54. msg := kafka.Message{
  55. Value: encodedMsg,
  56. }
  57. err = writer.WriteMessages(context.Background(), msg)
  58. if err != nil {
  59. fmt.Println("Error in writing to Kafka: ", err)
  60. time.Sleep(1 * time.Second)
  61. break
  62. }
  63. }
  64. }
  65. // } else {
  66. // s := strings.Split(string(message), ",")
  67. // if len(s) < 6 {
  68. // log.Printf("Messaggio CSV non valido: %s", msgStr)
  69. // return
  70. // }
  71. // rawdata := s[4]
  72. // buttonCounter := parseButtonState(rawdata)
  73. // if buttonCounter > 0 {
  74. // adv := model.BeaconAdvertisement{}
  75. // i, _ := strconv.ParseInt(s[3], 10, 64)
  76. // adv.Hostname = hostname
  77. // adv.BeaconType = "hb_button"
  78. // adv.MAC = s[1]
  79. // adv.RSSI = i
  80. // adv.Data = rawdata
  81. // adv.HSButtonCounter = buttonCounter
  82. // read_line := strings.TrimRight(string(s[5]), "\r\n")
  83. // it, err33 := strconv.Atoi(read_line)
  84. // if err33 != nil {
  85. // fmt.Println(it)
  86. // fmt.Println(err33)
  87. // os.Exit(2)
  88. // }
  89. // }
  90. // }
  91. }
  92. var messagePubHandler = func(msg mqtt.Message, writer *kafka.Writer, appState *appcontext.AppState) {
  93. mqtthandler(writer, msg.Topic(), msg.Payload(), appState)
  94. }
  95. var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
  96. fmt.Println("Connected")
  97. }
  98. var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
  99. fmt.Printf("Connect lost: %v", err)
  100. }
  101. func main() {
  102. // Load global context to init beacons and latest list
  103. appState := appcontext.NewAppState()
  104. cfg := config.Load()
  105. // Create log file -> this section and below can be moved in a package, as it is always the same
  106. logFile, err := os.OpenFile("server.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  107. if err != nil {
  108. log.Fatalf("Failed to open log file: %v\n", err)
  109. }
  110. // shell and log file multiwriter
  111. w := io.MultiWriter(os.Stderr, logFile)
  112. logger := slog.New(slog.NewJSONHandler(w, nil))
  113. slog.SetDefault(logger)
  114. // define context
  115. ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
  116. defer stop()
  117. // define kafka reader
  118. apiReader := appState.AddKafkaReader(cfg.KafkaURL, "apibeacons", "bridge-api")
  119. // define kafka writer
  120. writer := appState.AddKafkaWriter(cfg.KafkaURL, "rawbeacons")
  121. slog.Info("Bridge initialized, subscribed to kafka topics")
  122. chApi := make(chan model.ApiUpdate, 200)
  123. wg.Add(1)
  124. go kafkaclient.Consume(apiReader, chApi, ctx, &wg)
  125. opts := mqtt.NewClientOptions()
  126. opts.AddBroker(fmt.Sprintf("tcp://%s:%d", cfg.MQTTHost, 1883))
  127. opts.SetClientID("go_mqtt_client")
  128. opts.SetUsername("emqx")
  129. opts.SetPassword("public")
  130. opts.SetDefaultPublishHandler(func(c mqtt.Client, m mqtt.Message) { messagePubHandler(m, writer, appState) })
  131. opts.OnConnect = connectHandler
  132. opts.OnConnectionLost = connectLostHandler
  133. client := mqtt.NewClient(opts)
  134. if token := client.Connect(); token.Wait() && token.Error() != nil {
  135. panic(token.Error())
  136. }
  137. sub(client)
  138. eventloop:
  139. for {
  140. select {
  141. case <-ctx.Done():
  142. break eventloop
  143. case msg := <-chApi:
  144. switch msg.Method {
  145. case "POST":
  146. id := msg.ID
  147. appState.AddBeaconToLookup(msg.MAC, id)
  148. lMsg := fmt.Sprintf("Beacon added to lookup: %s", id)
  149. slog.Info(lMsg)
  150. case "DELETE":
  151. id := msg.MAC
  152. if id == "all" {
  153. appState.CleanLookup()
  154. fmt.Println("cleaned up lookup map")
  155. continue
  156. }
  157. appState.RemoveBeaconFromLookup(id)
  158. lMsg := fmt.Sprintf("Beacon removed from lookup: %s", id)
  159. slog.Info(lMsg)
  160. }
  161. }
  162. }
  163. slog.Info("broken out of the main event loop")
  164. wg.Wait()
  165. slog.Info("All go routines have stopped, Beggining to close Kafka connections")
  166. appState.CleanKafkaReaders()
  167. appState.CleanKafkaWriters()
  168. client.Disconnect(250)
  169. slog.Info("Closing connection to MQTT broker")
  170. }
  171. func publish(client mqtt.Client) {
  172. num := 10
  173. for i := 0; i < num; i++ {
  174. text := fmt.Sprintf("Message %d", i)
  175. token := client.Publish("topic/test", 0, false, text)
  176. token.Wait()
  177. time.Sleep(time.Second)
  178. }
  179. }
  180. func sub(client mqtt.Client) {
  181. topic := "publish_out/#"
  182. token := client.Subscribe(topic, 1, nil)
  183. token.Wait()
  184. fmt.Printf("Subscribed to topic: %s\n", topic)
  185. }