Skip to content

An Illustrative IoT Event Pipeline with Nerves, Phoenix and LiveView

A bird-feeder sensor is a useful setting for studying an event pipeline. “Avian Visitors” is only the source article’s inspiration label here: no primary evidence establishes its Hacker News ranking, authorship or implementation stack.

The design question is how a motion indication could travel from an embedded process through a server to a browser. A PIR event is not bird identification. Camera capture and ML classification are optional future components, not implemented below; collect no images of people or private locations for this demonstration.

The snippets illustrate Elixir, Nerves and Phoenix LiveView concepts. They are not an end-to-end production application: socket client, deployment, persistence and credential provisioning are omitted, and no code, GPIO or network service was run.

The Architecture: From Edge to Browser

Separate the conceptual design into three layers; reliability still requires explicit integration and testing:

  • Edge device: A supported Nerves target with a compatible GPIO input. The exact board image, pin identifier, voltage levels and sensor wiring must be checked against its documentation before any separate hardware work. No camera or board is configured here.
  • The Cloud Ingestion Hub (The Canopy): A Phoenix server acting as a highly concurrent WebSocket listener that ingests telemetry, manages state, and dispatches events.
  • Dashboard: Phoenix LiveView receives updates through its client connection and patches the page. This is not the separate Server-Sent Events protocol, and update latency is not guaranteed.

The diagram is conceptual. Its transport and optional image/ML branch are not implemented by the snippets:

[ PIR Sensor Trip ] 
       │
       ▼
[ Raspberry Pi (Nerves) ] ──(WSS / TLS transport)──► [ Phoenix Cloud App ]
                                                           │
                                            ┌──────────────┴──────────────┐
                                            ▼                             ▼
                                    [ Phoenix.PubSub ]             [ Optional image / ML ]
                                            │
                                            ▼
                                   [ LiveView Client ] 
                                 (Real-time DOM Update)

Part 1: The Edge Device with Elixir Nerves

Nerves combines Linux, Buildroot and Elixir/BEAM releases for embedded targets. Elixir is not compiled into a Linux microkernel. The project describes firmware sizes starting around 20–30 MB; that is not a maximum size or a measured boot time for this application.

Handling GPIO Interrupts on the Edge

This unexecuted circuits_gpio 2.x example receives edge notifications and sends a local message to a supplied process. The GPIO identifier must be passed explicitly after board-specific review. No socket client is implemented. A five-second cooldown limits accepted notifications here, not network traffic or guaranteed delivery.

defmodule AvianVisitor.Edge.MotionSensor do
  use GenServer
  alias Circuits.GPIO
  @cooldown_ms 5000

  def start_link(opts), do: GenServer.start_link(__MODULE__, opts)

  @impl true
  def init(opts) do
    gpio = Keyword.fetch!(opts, :gpio)
    sink = Keyword.fetch!(opts, :sink)
    if is_pid(sink) do
      case GPIO.open(gpio, :input) do
        {:ok, pin} ->
          case GPIO.set_interrupts(pin, :rising) do
            :ok -> {:ok, %{pin: pin, gpio: gpio, sink: sink, last_trigger: nil}}
            {:error, reason} ->
              GPIO.close(pin)
              {:stop, reason}
          end
        {:error, reason} -> {:stop, reason}
      end
    else
      {:stop, :sink_must_be_pid}
    end
  end

  @impl true
  def handle_info({:circuits_gpio, gpio, _timestamp, 1}, %{gpio: gpio} = state) do
    now = System.monotonic_time(:millisecond)
    if is_nil(state.last_trigger) or now - state.last_trigger >= @cooldown_ms do
      send(state.sink, {:motion_indication, now})
      {:noreply, %{state | last_trigger: now}}
    else
      {:noreply, state}
    end
  end
  def handle_info(_message, state), do: {:noreply, state}

  @impl true
  def terminate(_reason, state), do: GPIO.close(state.pin)
end

Notifications avoid a user-written busy-polling loop, but backend behavior and whole-device power consumption still matter. The GPIO timestamp may use a different clock from Erlang; this example uses its own monotonic clock only for local intervals. No battery or latency measurement was made.

Part 2: Channel ingestion concepts

Phoenix Channels provide topic-based messaging using processes and a transport such as WebSocket. Memory, throughput and connection capacity depend on payloads and application state; “a few kilobytes per device” and thousands of connections are not measured here.

Defining the Custom Socket Channel

The channel sketch below intentionally denies all joins until application-specific device verification and topic authorization are supplied. The stub is not an authentication system. A real integration also needs socket connect authentication, credential lifecycle, server-side rate limits, payload bounds and dashboard authorization. Accepted events use server receipt time, not an untrusted sensor timestamp.

defmodule AvianVisitor.DeviceAuth do
  def verify_and_authorize(_payload, _device_id), do: {:error, :not_configured}
end

defmodule AvianVisitorWeb.DeviceChannel do
  use AvianVisitorWeb, :channel

  def join("devices:" <> device_id, payload, socket)
      when byte_size(device_id) in 1..64 do
    case AvianVisitor.DeviceAuth.verify_and_authorize(payload, device_id) do
      :ok -> {:ok, assign(socket, :device_id, device_id)}
      _ -> {:error, %{reason: "unauthorized"}}
    end
  end
  def join(_topic, _payload, _socket), do: {:error, %{reason: "unauthorized"}}

  def handle_in("motion_detected", %{"motion" => true} = payload, socket)
      when map_size(payload) == 1 do
    event = %{device_id: socket.assigns.device_id,
              timestamp: System.system_time(:second)}
    case Phoenix.PubSub.broadcast(AvianVisitor.PubSub, "dashboard:activity",
           {:motion_indication, event}) do
      :ok -> {:reply, :ok, socket}
      {:error, _} -> {:reply, {:error, %{reason: "unavailable"}}, socket}
    end
  end
  def handle_in(_event, _payload, socket),
    do: {:reply, {:error, %{reason: "invalid_event"}}, socket}
end

Phoenix.PubSub supports adapters, including a distributed default adapter and an optional Redis adapter. Cross-node delivery requires a correctly configured connected cluster; starting extra nodes alone is not discovery or security configuration. PubSub is not a durable event log and does not establish exactly-once delivery.

Part 3: The Real-Time Frontend with Phoenix LiveView

LiveView is one way to keep a server-rendered dashboard updated. React, Vue and Redux were never required for every live interface; compare approaches according to application requirements.

LiveView maintains server-side state and sends diffs to its browser client, which uses JavaScript to update the DOM. It can reduce custom client code, but is not a JavaScript-free system, and this article does not establish a particular binary wire representation or payload size.

Writing the LiveView Component

defmodule AvianVisitor.DashboardAccess do
  def allowed?(_session), do: false
end

defmodule AvianVisitorWeb.DashboardLive do
  use AvianVisitorWeb, :live_view
  alias Phoenix.PubSub

  @impl true
  def mount(_params, session, socket) do
    if AvianVisitor.DashboardAccess.allowed?(session) do
      if connected?(socket), do: PubSub.subscribe(AvianVisitor.PubSub, "dashboard:activity")
      {:ok, assign(socket, events: [])}
    else
      {:ok, socket |> assign(events: []) |> redirect(to: "/")}
    end
  end

  @impl true
  def render(assigns) do
    ~H"""
    <section>
      <h2>Motion event demonstration</h2>
      <p :if={@events == []}>No received events.</p>
      <ul>
        <li :for={event <- @events}>
          {event.device_id}: {event.timestamp}
        </li>
      </ul>
    </section>
    """
  end

  @impl true
  def handle_info({:motion_indication, %{device_id: id, timestamp: ts} = event}, socket)
      when is_binary(id) and byte_size(id) in 1..64 and is_integer(ts) do
    {:noreply, assign(socket, events: Enum.take([event | socket.assigns.events], 5))}
  end
  def handle_info(_message, socket), do: {:noreply, socket}
end

If the omitted integration and access controls were implemented, a validated motion event could reach PubSub and an authorized LiveView subscriber. The retained list is bounded to five entries, but mailbox traffic and transport queues still need limits. Nothing was observed end to end, and no animation or sub-50 ms result is claimed. The dashboard stub denies access; use a different landing route at “/” rather than a redirect loop.

Security & Reliability Considerations at the Edge

Building real-time IoT networks isn't just about the happy path. If you are deploying edge devices out in the wild (literally!), you have to account for dirty power, spotty Wi-Fi, and security threats.

1. Resilience via Erlang Supervision Trees

Supervisors restart children according to a strategy and restart limits; they do not automatically implement exponential reconnect backoff for an arbitrary socket process. A device client must implement or configure reconnect, bounded buffering, retries and deduplication deliberately. Rapid repeated failures can exceed restart intensity and stop a supervisor.

2. TLS transport protection, not end-to-end encryption

Use wss:// with certificate-chain and hostname verification at each TLS connection, including an appropriate maintained trust store. TLS ends at its configured endpoint or proxy, so it does not imply application-level end-to-end encryption through the server. Device and viewer authorization remain separate requirements; certificate files alone do not configure verification.

Conclusion: The Power of Unified Stacks

Elixir, Nerves and Phoenix can express parts of a sensor-to-browser design in a related ecosystem. This article is an independent conceptual example, not the verified implementation of “Avian Visitors” or a demonstrated performant, resilient deployment.

Evaluate this stack alongside alternatives based on target hardware, team experience, access control, delivery guarantees and measured load. The snippets are a reading exercise, not a direction to deploy new infrastructure or connect hardware now.

Over to you: Have you experimented with edge computing, or run Elixir on embedded devices? What hardware setup are you using for your own home-automation or tracking projects? Let me know in the comments below!

Primary documentation

Post a Comment

Previous Post Next Post