Advertisement
Guest User

Untitled

a guest
Dec 12th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "github.com/eclipse/paho.mqtt.golang"
  6. "sync"
  7. "github.com/sirupsen/logrus"
  8. )
  9.  
  10. // MQ is MQTT client struct
  11. type MQ struct {
  12. Addr string
  13. PubClientID string
  14. SubClientID string
  15. Login string
  16. Password string
  17. TopicIn string
  18. TopicOut string
  19. QoS byte
  20.  
  21. onceIn sync.Once
  22. onceOut sync.Once
  23.  
  24. pubClient mqtt.Client
  25. subClient mqtt.Client
  26. }
  27.  
  28.  
  29. func main() {
  30. mqClient := MQ{
  31. Addr: fmt.Sprintf("%s:%d", "datarouter.maximus.lan", 1883),
  32. PubClientID: "5f81487b-c75e-412c-9184-a028f8da7419",
  33. SubClientID: "6be68ef4-1c46-4b4f-9146-5e132761a995",
  34. Login: "test",
  35. Password: "SkXTKTBN6C",
  36. TopicIn: "services/integration/IN",
  37. TopicOut: "services/integration/OUT",
  38. QoS: 0,
  39. }
  40.  
  41. message := "test message"
  42. test := mqClient.GetPubClient()
  43. fmt.Printf("%+v", test)
  44.  
  45. t := mqClient.GetPubClient().Publish(mqClient.TopicOut, mqClient.QoS, false, message)
  46. t.Wait()
  47.  
  48. z := t.Error()
  49. if z != nil {
  50.  
  51. fmt.Printf("%+v", z)
  52. logrus.WithFields(logrus.Fields{
  53. "error": t.Error(),
  54. "message": string(message),
  55. }).Error("Can't send message to queue")
  56. }
  57.  
  58.  
  59. fmt.Printf("%+v", t)
  60.  
  61. }
  62.  
  63. // GetPubClient returns PUB MQTT connection
  64. func (m *MQ) GetPubClient() mqtt.Client {
  65. m.onceOut.Do(func() {
  66. mqtt.ERROR = logrus.New()
  67. opts := mqtt.NewClientOptions()
  68. opts = opts.AddBroker("tcp://" + m.Addr)
  69. opts.ClientID = m.PubClientID
  70. opts.Username = m.Login
  71. opts.Password = m.Password
  72.  
  73. m.pubClient = mqtt.NewClient(opts)
  74. token := m.pubClient.Connect()
  75. token.Wait()
  76.  
  77. if token.Error() != nil {
  78.  
  79.  
  80. }
  81.  
  82. })
  83. return m.pubClient
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement