MQTT and Zotonic

Receiving messages from an MQTT broker, directly to your Zotonic powered web-site.

To install the third party module which implements both an MQTT broker and an MQTT client, you need to run the following command:

zotonic installmodule mod_mqtt

You now need to go to the modules menu in the Zotonic admin, and enable mod_mqtt.

By default, mod_mqtt will assume you want to use a external broker, but if you want to use the built in broker, you can go to the Config menu in Zotonic, and add the following config variable:

mod_mqtt -> start_broker -> true

Other config variable for the broker are port, allow_anonymous, username and password.

To subscribe to topics, you can add the following code to your Zotonic module's init function:

 mqtt_store:start(),
 {ok, ClientPid} = z_mqtt:connect("127.0.0.1", [], 1883, Context),
 z_mqtt:subscribe(ClientPid, "#", Context),

# is a wild card, so this client is subscribed to all topics from the broker.

Now that you client is connected and subscribed, all yu need to do now is handle the messages as they come in.

To do that, add a handle_info like this to your gen_server module:

 

handle_info({mqtt,_,_ProtocolVersion,_,_,_,{Topic,Message}}, #state{context=Context}=State) ->
 io:format("Topic: ~p~n", [Topic]),
 io:format("Message: ~p~n", [Message]),
 {noreply, State};
handle_info(_Info, State) ->
 {noreply, State}.

Now you should be able to use mosquitto_pub from the command line, to send a message with any topic to your broker, and it will be pushed to your website.

Comments