spoke

Types

Authentication details passed to the server when connecting. Remember that these are not encrypted, unless working with an encrypted transport channel.

pub type AuthDetails {
  AuthDetails(username: String, password: Option(BitArray))
}

Constructors

  • AuthDetails(username: String, password: Option(BitArray))

An opaque handle for the MQTT client. Can live across multiple sessions and connections, or resume sessions that were previously disconnected. Under the hood, the client is an OTP actor.

pub opaque type Client

Error code from the server - we got a response, but there was an error.

pub type ConnectError {
  UnacceptableProtocolVersion
  IdentifierRefused
  ServerUnavailable
  BadUsernameOrPassword
  NotAuthorized
}

Constructors

  • UnacceptableProtocolVersion

    The MQTT server doesn’t support MQTT 3.1.1

  • IdentifierRefused

    The Client identifier is correct UTF-8 but not allowed by the Server

  • ServerUnavailable

    The Network Connection has been made but the MQTT service is unavailable

  • BadUsernameOrPassword

    The data in the user name or password is malformed

  • NotAuthorized

    The Client is not authorized to connect

The set of options used to establish a connection to the server. Includes the set of data that should generally not change across multiple connect calls (if they are needed).

pub type ConnectOptions {
  ConnectOptions(
    connector: TransportChannelConnector,
    client_id: String,
    authentication: Option(AuthDetails),
    keep_alive_seconds: Int,
    server_timeout_ms: Int,
  )
}

Constructors

  • ConnectOptions(
      connector: TransportChannelConnector,
      client_id: String,
      authentication: Option(AuthDetails),
      keep_alive_seconds: Int,
      server_timeout_ms: Int,
    )

    Arguments

    • connector

      Function to establish a transport channel.

    • client_id

      The MQTT client ID used when connecting to the server.

    • authentication

      Optional username and (additionally optional) password

    • keep_alive_seconds

      Keep-alive interval in seconds (MQTT spec doesn’t allow more granular control)

    • server_timeout_ms

      “Reasonable amount of time” for the server to respond (including network latency), as used in the MQTT specification.

Represents the state of the connection to the server.

pub type ConnectionState {
  ConnectFailed(String)
  ConnectRejected(ConnectError)
  ConnectAccepted(session_present: Bool)
  Disconnected
  DisconnectedUnexpectedly(reason: String)
}

Constructors

  • ConnectFailed(String)

    Connecting to the server failed before we got a response to the connect packet.

  • ConnectRejected(ConnectError)

    The server was reachable, but rejected our connect packet

  • ConnectAccepted(session_present: Bool)

    The server has accepted our connect packet

  • Disconnected

    Disconnected as a result of calling disconnect

  • DisconnectedUnexpectedly(reason: String)

    The connection was dropped for an unexpected reason, e.g. a transport channel error or protocol violation.

Unified error type for operations that are completed in a blocking way.

pub type OperationError {
  NotConnected
  OperationTimedOut
  ProtocolViolation
  KilledDuringOperation
}

Constructors

  • NotConnected

    The client was not connected when it was required.

  • OperationTimedOut

    The operation did not complete in time.

  • ProtocolViolation

    We received unexpected data from the server, and will disconnect.

  • KilledDuringOperation

    The client actor was killed while the operation was in progress.

A convenience record to hold all the data used when publishing messages.

pub type PublishData {
  PublishData(
    topic: String,
    payload: BitArray,
    qos: QoS,
    retain: Bool,
  )
}

Constructors

  • PublishData(
      topic: String,
      payload: BitArray,
      qos: QoS,
      retain: Bool,
    )

Quality of Service levels, as specified in the MQTT specification

pub type QoS {
  AtMostOnce
  AtLeastOnce
  ExactlyOnce
}

Constructors

  • AtMostOnce

    The message is delivered according to the capabilities of the underlying network. No response is sent by the receiver and no retry is performed by the sender. The message arrives at the receiver either once or not at all.

  • AtLeastOnce

    This quality of service ensures that the message arrives at the receiver at least once.

  • ExactlyOnce

    This is the highest quality of service, for use when neither loss nor duplication of messages are acceptable. There is an increased overhead associated with this quality of service.

Utility record for the data required to request a subscription.

pub type SubscribeRequest {
  SubscribeRequest(filter: String, qos: QoS)
}

Constructors

  • SubscribeRequest(filter: String, qos: QoS)

The result of a subscribe operation

pub type Subscription {
  SuccessfulSubscription(topic_filter: String, qos: QoS)
  FailedSubscription(topic_filter: String)
}

Constructors

  • SuccessfulSubscription(topic_filter: String, qos: QoS)

    The subscribe succeeded with the specified QoS level.

  • FailedSubscription(topic_filter: String)

    The server returned a failure for requested subscription.

A function that connects a transport channel and returns the send, receive, and shutdown functions or an error. NOTE: This only uses standard library and Erlang types, so that implementors do not need to depend on the Spoke package.

pub type TransportChannelConnector =
  fn() ->
    Result(
      #(
        fn(BytesTree) -> Result(Nil, String),
        fn() -> Selector(Result(BitArray, String)),
        fn() -> Nil,
      ),
      String,
    )

Represents a received message or change in the client.

pub type Update {
  ReceivedMessage(
    topic: String,
    payload: BitArray,
    retained: Bool,
  )
  ConnectionStateChanged(ConnectionState)
}

Constructors

  • ReceivedMessage(topic: String, payload: BitArray, retained: Bool)

    A published message to a topic this client was subscribed to was received.

  • ConnectionStateChanged(ConnectionState)

    The connection state of this client changed.

Functions

pub fn connect(client: Client, clean_session: Bool) -> Nil

Starts connecting to the MQTT server. The connection state will be published as an update. If a connection is already established or being established, this will be a no-op. Note that switching between clean_session values while already connecting is currently not well handled.

pub fn connect_with_id(
  connector: fn() ->
    Result(
      #(
        fn(BytesTree) -> Result(Nil, String),
        fn() -> Selector(Result(BitArray, String)),
        fn() -> Nil,
      ),
      String,
    ),
  client_id: String,
) -> ConnectOptions

Constructs connect options from transport options, the given client id, and default settings for the rest of the options.

pub fn connect_with_will(
  client: Client,
  clean_session: Bool,
  will: PublishData,
) -> Nil

Same as connect, but specifies a will message for this connection.

pub fn disconnect(client: Client) -> String

Disconnects from the MQTT server. The connection state change will also be published as an update. If a connection is not established or being established, this will be a no-op. Returns the serialized session state to be potentially restored later.

pub fn keep_alive_seconds(
  options: ConnectOptions,
  keep_alive_seconds: Int,
) -> ConnectOptions

Builder function for specifying the keep-alive time in the connect options.

pub fn pending_publishes(client: Client) -> Int

Returns the number of QoS > 0 publishes that haven’t yet been completely published. Also see wait_for_publishes_to_finish.

pub fn publish(client: Client, data: PublishData) -> Nil

Connects to the MQTT server. Will disconnect if the connect times out, and send the Disconnect update. Note that in case of a timeout, the message might still have been already published.

pub fn restore_session(
  connect_options: ConnectOptions,
  state: String,
) -> Result(Client, String)

Restores an MQTT session from a previously stored state, as returned by disconnect. Will return an error if the session state can not be restored from the provided string. Does not connect to the server, until connect is called.

pub fn server_timeout_ms(
  options: ConnectOptions,
  server_timeout_ms: Int,
) -> ConnectOptions

Builder function for specifying the server operation timeout in the connect options.

pub fn start_session(connect_options: ConnectOptions) -> Client

Starts a new MQTT session with the given options. Does not connect to the server, until connect is called.

pub fn subscribe(
  client: Client,
  topics: List(SubscribeRequest),
) -> Result(List(Subscription), OperationError)

Subscribes to the given topics. Will block until we get a response from the server, returning the result of the operation.

pub fn unsubscribe(
  client: Client,
  topics: List(String),
) -> Result(Nil, OperationError)

Unsubscribes from the given topics. Will block until we get a response from the server, returning the result of the operation.

pub fn updates(client: Client) -> Subject(Update)

Returns a Subject for receiving client updates (received messages and connection state changes). NOTE: This function is provided for convenience as receiving updates only works from the process that created the client! Future versions of spoke might support receiving updates in multiple processes.

pub fn using_auth(
  options: ConnectOptions,
  username: String,
  password: Option(BitArray),
) -> ConnectOptions

Builder function for specifying the authentication details to be used when connecting.

pub fn wait_for_publishes_to_finish(
  client: Client,
  timeout: Int,
) -> Result(Nil, Nil)

Wait for all pending QoS > 0 publishes to complete. Returns an error if the operation times out, or client is killed while waiting.

Search Document