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. Accepts `t:module/0`.
- `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. Accepts `t:keyword/0`.
## Examples
iex> result = FluxMQTT.connection(Tortoise.Handler.Logger)
...> with {Tortoise.Connection, _specification} <- result, do: :passed
:passed
"""
@doc since: "0.0.1"
@spec connection(module, keyword) :: {Tortoise.Connection, keyword}
def connection(handler, opts \\ []) do
Connector.connection(handler, opts)
end
@doc """
Send a message to the broker using the active MQTT service on the service
supersivion tree.
## Parameters
- `payload` - The message. Accepts `t:String.t/0`.
- `topic` - The MQTT topic which the message will be sent. Accepts
`t:String.t/0`.
- `client_id` - The sender client id. Accepts `t:String.t/0`.
- `opts` - The `Tortoise.publish/4` options. Accepts `t:keyword/0`.
## 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(String.t(), String.t(), String.t(), keyword) ::
:ok | {:ok, reference} | {:error, :unknown_connection}
def send(payload, topic, client_id, opts \\ []) do
Logger.debug("Sending MQTT message",
flux_mqtt_detail: inspect(topic: topic, client_id: client_id, opts: opts),
flux_mqtt_message: inspect(payload)
)
case Sender.send(payload, topic, client_id, opts) do
{:error, reason} = error ->
Logger.error("MQTT message sending failed",
flux_mqtt_error: inspect(reason),
flux_mqtt_error_detail: inspect(topic: topic, client_id: client_id, opts: opts),
flux_mqtt_error_message: inspect(payload)
)
error
result ->
Logger.debug("MQTT message successfully sent",
flux_mqtt_detail: inspect(topic: topic, client_id: client_id, opts: opts),
flux_mqtt_success_message: inspect(payload)
)
result
end
end
end