@@ -71,12 +71,13 @@ func (c *client) IsConnected() bool {
7171 return c .client .IsConnectionOpen ()
7272}
7373
74- func (c * client ) HandleMessage (_ paho. Client , msg paho. Message ) {
74+ func (c * client ) HandleMessage (topic string , payload [] byte ) {
7575 message := Message {
7676 Timestamp : time .Now (),
77- Value : msg . Payload () ,
77+ Value : payload ,
7878 }
79- c .topics .AddMessage (msg .Topic (), message )
79+
80+ c .topics .AddMessage (topic , message )
8081}
8182
8283func (c * client ) GetTopic (reqPath string ) (* Topic , bool ) {
@@ -104,9 +105,16 @@ func (c *client) Subscribe(reqPath string) *Topic {
104105 return t
105106 }
106107
107- log .DefaultLogger .Debug ("Subscribing to MQTT topic" , "topic" , t .Path )
108- if token := c .client .Subscribe (t .Path , 0 , c .HandleMessage ); token .Wait () && token .Error () != nil {
109- log .DefaultLogger .Error ("Error subscribing to MQTT topic" , "topic" , t .Path , "error" , token .Error ())
108+ log .DefaultLogger .Debug ("Subscribing to MQTT topic" , "topic" , topicPath )
109+
110+ topic := resolveTopic (t .Path )
111+
112+ if token := c .client .Subscribe (topic , 0 , func (_ paho.Client , m paho.Message ) {
113+ // by wrapping HandleMessage we can directly get the correct topicPath for the incoming topic
114+ // and don't need to regex it against + and #.
115+ c .HandleMessage (topicPath , []byte (m .Payload ()))
116+ }); token .Wait () && token .Error () != nil {
117+ log .DefaultLogger .Error ("Error subscribing to MQTT topic" , "topic" , topicPath , "error" , token .Error ())
110118 }
111119 c .topics .Store (t )
112120 return t
@@ -126,7 +134,9 @@ func (c *client) Unsubscribe(reqPath string) {
126134 }
127135
128136 log .DefaultLogger .Debug ("Unsubscribing from MQTT topic" , "topic" , t .Path )
129- if token := c .client .Unsubscribe (t .Path ); token .Wait () && token .Error () != nil {
137+
138+ topic := resolveTopic (t .Path )
139+ if token := c .client .Unsubscribe (topic ); token .Wait () && token .Error () != nil {
130140 log .DefaultLogger .Error ("Error unsubscribing from MQTT topic" , "topic" , t .Path , "error" , token .Error ())
131141 }
132142}
0 commit comments