View Source NervesHubLink.Connection (nerves_hub_link v1.2.0)

Agent used to keep the simple state of the devices connection to nerves-hub.org.

The state is a tuple where the first element is an atom of :connected or :disconnected and the second element is the value of System.monotonic_time/1 at the time of setting the new state.

In practice, this state is set anytime the device connection to nerves-hub.org channel changes. Likewise, it is set after a HTTP request fails or succeeds. This makes it useful when you want to consider the connection to nerves-hub.org as part of the overall health of the device and perform explicit actions based on the result, such as using the Erlang :heart module to force a reboot if the callback check fails.

# Set a callback for heart to check every 5 seconds. If the function returns anything other than
# `:ok`, it will cause reboot.
:heart.set_callback(NervesHubLink.Connection, :check!)

Or, you can use the check as part of a separate function with other health checks as well

defmodule MyApp.Checker do
  def health_check do
    with :ok <- NervesHubLink.Connection.check,
         :ok <- MyApp.another_check,
         :ok <- MyApp.yet_another_check,
    do
      :ok
    else
      err -> err
    end
  end
end

# Somewhere else in MyApp
:heart.set_callback(MyApp.Checker, :health_check)

Link to this section Summary

Functions

Same as check/0, but raises RuntimeError if the check fails

A simple check to see if the device is considered ok.

Returns a specification to start this module under a supervisor.

Sets the state to {:connected, System.monotonic_time(:seconds)}

Sets the state to {:disconnected, System.monotonic_time(:seconds)}

Reads the state directly without modification.

Link to this section Functions

@spec check!() :: :ok

Same as check/0, but raises RuntimeError if the check fails

@spec check() :: :ok | {:error, {:disconnected_too_long, integer()}}

A simple check to see if the device is considered ok.

This will still return :ok if the device is in a disconnected state, but within the :connection_timeout timeframe to allow for intermittent connection failures that are recoverable. Once the disconnection has exceeded the timeout, this check will be consided unhealthy.

The default connection timeout is 15 minutes (900 seconds), but is configurable:

# 60 second timeout
config :nerves_hub, connection_timeout: 60

Returns a specification to start this module under a supervisor.

See Supervisor.

@spec connected() :: :ok

Sets the state to {:connected, System.monotonic_time(:seconds)}

@spec disconnected() :: :ok

Sets the state to {:disconnected, System.monotonic_time(:seconds)}

@spec read() :: {:connected, integer()} | {:disconnected, integer()}

Reads the state directly without modification.

@spec start_link(any()) :: {:error, any()} | {:ok, pid()}