Packages

An interface to connect to MQTT broker, sending and handling messages.

Current section

Files

Jump to
flux_mqtt lib flux_mqtt.ex
Raw

lib/flux_mqtt.ex

defmodule FluxMQTT do
@moduledoc """
An interface to connect to MQTT broker, sending and handling messages.
"""
@moduledoc since: "0.0.1"
alias FluxMQTT.{Connector, Sender}
require Logger
@doc """
Define a tuple with `{Tortoise.Connection, specification}` to be used as a
child definition to the service supervision tree.
## Parameters
- `handler` - A module which uses `FluxMQTT.Handler` (or `Tortoise.Handler`)
responsible to handle messages received.
- `opts` - A keyword list with connection settings. Definition is the same
as [application configuration](readme#application-configuration) and the
opts defined here are merged with the application configuration. Can be
blank.
## Examples
iex> result = FluxMQTT.connection(Tortoise.Handler.Logger)
...> with {Tortoise.Connection, _specification} <- result, do: :passed
:passed
"""
@doc since: "0.0.1"
@spec connection(atom(), keyword()) :: {Tortoise.Connection, keyword()}
def connection(handler, opts \\ []) do
Connector.connection(handler, opts)
|> log_connection_and_continue(handler, opts)
end
@doc """
Send a message to the broker using the active MQTT service on the service
supersivion tree.
## Parameters
- `payload` - The message string.
- `topic` - The MQTT topic which the message will be sent.
- `client_id` - The sender client id.
- `opts` - The `Tortoise.publish/4` options.
## Examples
iex> opts = [
...> client: [
...> auth: [authenticate?: false],
...> correlation: [create_correlation_id?: false]
...> ]
...> ]
...> {connection, specification} = FluxMQTT.connection(Tortoise.Handler.Logger, opts)
...> connection.start_link(specification)
...> FluxMQTT.send("Hello, World!", "a/topic", "client")
:ok
"""
@doc since: "0.0.1"
@spec send(binary(), binary(), binary(), keyword()) ::
:ok | {:ok, reference} | {:error, :unknown_connection}
def send(payload, topic, client_id, opts \\ []) do
Sender.send(payload, topic, client_id, opts)
|> log_send_and_continue(payload, topic, client_id, opts)
end
defp log_connection_and_continue(result, handler, opts) do
Logger.debug("MQTT connection specification created",
flux_mqtt_result: inspect(result),
flux_mqtt_params:
inspect(
handler: handler,
opts: opts
)
)
result
end
defp log_send_and_continue(result, payload, topic, client_id, opts) do
case result do
{:error, _reason} ->
Logger.error("MQTT message sending failed",
error: inspect(result),
flux_mqtt_params:
inspect(
client_id: client_id,
topic: topic,
payload: payload,
opts: opts
)
)
_success ->
Logger.info("MQTT message successfully sent",
flux_mqtt_result: inspect(result),
flux_mqtt_params:
inspect(
client_id: client_id,
topic: topic,
payload: payload,
opts: opts
)
)
end
result
end
end