Shared subscription option tortoise MQTT library

This library is a client application for MQTT @gausby . It works fine for single subscription but not working fine for shared.

This is the code

  def start(_type, _args) do
     import Supervisor.Spec
     client_id: "my_client_id",
     handler: {MqttManager.Handler, []},
     server: {Tortoise.Transport.Tcp, host: 'localhost', port: 1883},
     subscriptions: [{"$share/d/+", 0}, {"d/+", 0}]


This is the handler code

 def init(args) do
   {:ok, args}

def connection(status, state) do
  {:ok, state}

def handle_message(topic, payload, state) do
  {:ok, state}

def subscription(status, topic_filter, state) do
  {:ok, state}

def terminate(reason, state) do  

When i test it with single subscription It works fine giving me payload and topic information

 Tortoise.publish("my_client_id", "d/dev","d/dev msg" , qos: 0)

When i try to test shared subscription it gives me no error or error message just this and no topic and payload information

 Tortoise.publish("my_client_id", "$share/d/dev","$share/d/dev msg" , qos: 0)

Any suggestions?


You don’t really do anything in the handle_message/3 in your handler.

What happen if you change the handle_message/3 to:

def handle_message(topic, payload, state) do
  IO.inspect {:message, topic, payload}
  {:ok, state}


Also…what if you publish on the topic dev ? The $share/group topic seems to be a convention for these shared subscriptions.

Let me know if this makes it work. I haven’t looked into shared subscriptions as they are part of the MQTT 5 version of the protocol, and for now I only implement MQTT 3.1.1.

I just tested it; it works just fine if the clients subscribe to the correct topic format, and post to the correct topic. Here’s an example:

Thanks for your reply. I forgot to put IO.inspect! inside handler here in the post. Its working fine for {"d/+", 0}. But it only returns :ok for the shared. I attached the screen shot console.

That is expected. The return of the Tortoise.publish/4 function is :ok when it dispatch the message. On line 4 you publish to the topic $share/d/dev. Please look at the example I just posted.

When you subscribe to $share/d/dev you say: "create a shared subscription on the topic-filter called dev for the group I call “d”. In this case the clients will take turn receiving messages posted to topic dev.

Thanks.Appreciate your help

1 Like