Flux MQTT v0.0.4 FluxMQTT.Handler behaviour View Source

Module responsible for MQTT messages handling.

The main approach to handle is done by defining a module which extends FluxMQTT.Handler and implements handle/3 function:

defmodule MyApp.MQTT.Handler do
  use FluxMQTT.Handler

  @impl FluxMQTT.Handler
  def handle(topic, payload, state) do
    # Handle message
  end
end

Then, set the connection on the supervision tree:

defmodule MyApp.MQTT.Supervisor do
  use Supervisor

  alias MyApp.MQTT.Handler

  def start_link(arg), do: Supervisor.start_link(__MODULE__, arg, name: __MODULE__)

  @impl Supervisor
  def init(_arg) do
    children = [
      FluxMQTT.connection(Handler)
    ]

    opts = [strategy: :one_for_one]

    Supervisor.init(children, opts)
  end
end

Application:

defmodule MyApp.Application do
  use Application

  @impl Application
  def start(_type, _args) do
    children = [
      MyApp.MQTT.Supervisor
    ]

    opts = [strategy: :one_for_one]

    Supervisor.start_link(children, opts)
  end
end

Matching Dynamic Topics

Sometimes the definition of topics cannot be determined programatically, such as when using environment variables to set the service topics.

When a module uses FluxMQTT.Handler, the function match_topic/3 is imported to the module. This function expects as parameters:

  • received - The topic received on handle/3 function. Accepts a list/0 of String.t/0.

  • expected - The topic defined dynamically. Accepts String.t/0.

  • matcher - Used to define the key names for the resultant map. Accepts String.t/0.

Example:

defmodule MyApp.MQTT.Handler do
  use FluxMQTT.Handler

  @impl FluxMQTT.Handler
  def handle(topic, payload, state) do
    expected = "user/+/friend/+"
    matcher = "user/id/friend/friend_id"

    case match_topic(topic, expected, matcher) do
      {:ok, %{id: id, friend_id: friend_id}} -> # Use ids
      {:error, :unmatch} -> # Not the expected topic
    end
  end
end

Link to this section Summary

Link to this section Callbacks

Link to this callback

handle(topic, payload, state)

View Source
handle(topic :: [String.t()], payload :: String.t(), state :: keyword()) ::
  any()