Runtime for use MqttX — a module-based MQTT client (GitHub issue #1).
defmodule MyClient do
use MqttX
@impl true
def init(opts) do
{:ok, %{count: 0}}
end
@impl true
def handle_message(topic, payload, _packet, state) do
# Publishing from inside a callback is safe: callbacks run in
# their own process, not inside the connection.
publish("replies/" <> Enum.join(topic, "/"), "got it", qos: 1)
{:ok, %{state | count: state.count + 1}}
end
end
# In a supervision tree:
children = [
{MyClient, host: "broker.example.com", client_id: "my-client"}
]use MqttX injects start_link/1, child_spec/1, and the convenience
functions publish/2,3, subscribe/1,2, unsubscribe/1, connected?/0,
and disconnect/0,1 (which address the process registered under the
module name). Connection options passed to start_link/1 are the same as
MqttX.Client.connect/1; :name overrides the registered name (when you
do that, use the MqttX.SimpleClient functions with your name instead of
the injected helpers).
Callbacks
Every callback has a default implementation, so implement only the ones you need.
init(opts)— build the initial state from thestart_link/1options. Default:{:ok, %{}}.handle_message(topic, payload, packet, state)— one incoming PUBLISH.topicis a list of segments.handle_connected(info, state)— after CONNACK success (also after automatic reconnects);infohas:session_presentand:properties.handle_disconnected(reason, state)— connection lost (an automatic reconnect follows unless the broker rejection was fatal).handle_publish_error(topic, packet_id, reason_code, state)— broker rejected a QoS 1/2 publish.handle_info(message, state)— any other message sent to the process.
Each returns {:ok, state} or {:stop, reason, state}.
Summary
Functions
Returns a specification to start this module under a supervisor.
Types
@type state() :: term()