Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 16 — Edge, IoT & Mobile

OTP is not limited to servers. Three stacks push BEAM toward hardware — each keeps the same process/supervision model at different scales.

16.1 Mental Model First

  • Nerves = BEAM on Linux (full OS)
  • AtomVM = BEAM on microcontrollers (no OS)
  • LiveView Native = server-driven LiveView rendered as real native views
  • Mob / Dala = BEAM running on the phone, offline-first

That third line is the one most readers have not heard of, and it is the one you probably want: LiveView Native (LVN) renders your existing LiveViews through SwiftUI and Jetpack Compose components. Same .heex, same handle_event, real native widgets — but it needs a server, because the LiveView runs there. Mob runs the BEAM on the device, so it works offline.

Pick by that single question:

RequirementChoiceWhy
Must work offline / no serverMob (experimental — evaluate per app)BEAM on the phone, ~4MB runtime
Native UI, server always reachableLiveView Nativeshare LiveViews with your web app
Own the whole deviceNervesfull Linux + supervision tree
flowchart TD
    SRC["Elixir / Erlang source"]
    SRC --> NERVES["Nerves<br/>(Buildroot Linux)"]
    SRC --> ATOM["AtomVM<br/>(compact BEAM)"]
    SRC --> MOB["Mob<br/>(BEAM on device)"]
    SRC --> LVN["LiveView Native<br/>(server LiveViews)"]
    NERVES --> LINUX["Linux device<br/>RPi · BeagleBone · custom boards"]
    ATOM --> MCU["MCU<br/>ESP32 · STM32 · RP2040"]
    MOB --> MOBILE["iOS / Android<br/>native UI, offline"]
    LVN --> MOBILE2["iOS / Android<br/>native UI, online"]

16.2 Nerves — Embedded Linux Firmware

Nerves cross-compiles your Elixir app + BEAM + a minimal Linux (Buildroot) into a firmware image. Boots straight into your supervision tree in ~3 seconds.

flowchart TD
    EX["Elixir"] --> NR["Nerves<br/>Buildroot + tooling"]
    NR --> DEV["Linux device"]
    DEV --> HW["GPIO · Sensors ·<br/>Network · Storage"]

Key libraries:

PackageRole
nerves_runtimefirmware info, hardware access
vintage_netnetwork configuration
circuits_gpio / circuits_i2c / circuits_spihardware buses
nerves_pack / ring_loggernetworking defaults, ring logging

Step-by-step first firmware:

mix archive.install hex nerves_bootstrap
mix nerves.new my_device
cd my_device
export MIX_TARGET=rpi4          # Raspberry Pi 4 target
mix deps.get
mix firmware                     # produces .fw image
mix burn <sd-card-device>        # write to SD card, boot the device

Great fits: industrial gateways, robotics, edge nodes, kiosks, device telemetry.

Targets, Toolchains, and What’s in a .fw

Each MIX_TARGET pulls a prebuilt system — Buildroot Linux + BEAM for that board — plus a cross-toolchain, cached under ~/.nerves and versioned in mix.exs. Your app cross-compiles against them and fwup assembles the .fw image:

TargetBoard classNotes
rpi0_2, rpi3, rpi4, rpi5Raspberry Pi familythe usual starters
mangopi_mq_proOrange Picheap SBCs
bbbBeagleBone Blackindustrial I/O heritage
grisp2GRiSP2purpose-built Erlang hardware, niche
x86_64generic PC/VMkiosks, laptop dev

Check the Nerves supported-targets page for the exact list for your nerves version; target names have changed across releases (rpi0 became rpi0_2).

Inside the image: a minimal read-only rootfs, your release, and fwup slots — A/B partitions enabling atomic upgrades and rollback, which is what the update story below leans on.

Network Config and Reaching the Device

vintage_net models interfaces as supervised processes — each NIC is a child whose configuration is a plain map:

# config/target.exs (evaluated on-device)
config :vintage_net,
  regulatory_domain: "US",
  config: [
    {"eth0", %{type: VintageNetEthernet, ipv4: %{method: :dhcp}}},
    {"wlan0",
     %{
       type: VintageNetWiFi,
       vintage_net_wifi: %{
         networks: [%{key_mgmt: :wpa_psk, ssid: "shop-floor", psk: "..."}]
       },
       ipv4: %{method: :dhcp}
     }}
  ]

Inspect at runtime like any process state: VintageNet.get_by_prefix(["interface"]). Once booted, the device is just a BEAM node on your LAN:

ssh nerves.local                    # drops straight into IEx on the device
iex> Nerves.Runtime.KV.get_all_active()   # firmware provenance

(mix upload over SSH needs nerves_ssh in the firmware and your public key in the device’s authorized_keys; without it you are back to nerves.local login or a serial console.) No adb, no serial-console ritual (though UART remains the rescue hatch) — it’s remsh with a power plug.

Fleet Management: NervesHub

The line above is the single-device story. A fleet needs more, and the standard answer is NervesHub — open source, and what most teams use instead of hand-rolling OTA:

# config/target.exs — connect the device to NervesHub
# deps: {:nerves_hub_link, "~> 2.2"}
config :nerves_hub_link,
  host: "your.nerveshub.host",
  shared_secret: [
    product_key: System.get_env("NERVESHUB_PRODUCT_KEY"),
    product_secret: System.get_env("NERVESHUB_PRODUCT_SECRET")
  ]

nerves_hub_link supervises itself and handles the whole update loop — announcement, download, signature verification, staged rollout, progress reporting — so you do not write it. The parts you do own:

  • Channel structure — prod vs staging, and per-device or per-group targeting, so you can stage a rollout before it reaches the fleet.
  • Signing — sign firmware so devices refuse unsigned images.
  • A/B firmware slots — fwup writes the new image to the inactive slot and flips a bootloader flag, so a failed flash rolls back on next boot rather than bricking the device. This is a hardware/fwup property, not something you code.

If you skip NervesHub you are writing all three yourself. Do not skip it.

16.3 AtomVM — Microcontrollers, No OS

AtomVM is a compact BEAM implementation (~200KB flash, ~100KB RAM) running directly on ESP32, STM32, RP2040:

  • Preemptive scheduler, GenServers, supervisors — yes, really
  • Native modules written in C for hardware access (Rust is possible via NIF experiments, not the documented path — plan on C)
  • No operating system; boots to OTP semantics on bare metal
flowchart TD
    SRC["Elixir / Erlang"] --> AVM["AtomVM<br/>compact BEAM"]
    AVM --> MCU["Microcontroller<br/>ESP32 / STM32 / RP2040"]
    MCU --> IO["Sensors · Actuators ·<br/>BLE · WiFi"]

Use when Linux is too heavy: battery sensors, small actuators, BLE devices.

Constraints vs the Full BEAM

AtomVM is a reimplementation, not a port — plan around the deltas:

CapabilityFull BEAM (Nerves)AtomVM
Processes, supervisors, GenServeryesyes
Binary/term semanticscompletecore subset
Distribution (net_kernel)yesno — raw sockets instead
OTP breadth (crypto, ssl, …)extensiveselective per platform
RAM floortens of MB (Linux)~100 KB class

Hardware access follows the Erlang tradition of thin native edges: C/Rust native modules compiled into the VM image, reached from ordinary Elixir calls. The architectural pattern from servers holds here too — keep native code dumb and narrow, model the device as a supervised process (§16.5), and let restarts absorb flaky buses. When a sensor fleet outgrows MCU limits the escape hatch is architectural, not linguistic: AtomVM nodes report to a Nerves gateway, which reports to your cluster.

16.4 Mobile — Three Options, One Question

LiveView Native is the production answer and gets a full section below. Mob and Dala are the experimental branch: both embed BEAM inside native iOS/Android apps with real native UI (not web views), which means genuine offline capability — at the cost of stability.

MobDala
ApproachBEAM/OTP inside the appRust-powered native layer + BEAM + Edge AI
UISwiftUI / Jetpack ComposeSwiftUI / Jetpack Compose
StatusActive experiment, descended from Elixir DesktopEmerging, Rust-based
IntegrationNIFs for platform APIsRust NIFs, unified layer

Read both as research directions, not as dependencies you can rely on. Both have moved through 0.x with breaking changes and neither offers the ecosystem depth of Phoenix; evaluate per app against the Elixir Forum threads before committing. Dala in particular markets “Edge AI” without a documented API surface — if that capability is the reason you are considering it, verify it exists before designing around it.

Pipelines:

flowchart LR
    subgraph MOBPIPE["Mob"]
        E1["Elixir → OTP/BEAM"] --> M1["Mob"] --> U1["Native UI<br/>iOS / Android"]
    end
    subgraph DALAPIPE["Dala"]
        E2["Elixir/OTP → BEAM"] --> R2["Rust native layer"] --> U2["Native UI<br/>iOS / Android"]
    end

Your OTP skills apply directly: offline state machines, background sync, and fault-tolerant local services inside the app.

16.4.1 LiveView Native — Your Existing LiveViews, Natively Rendered

The mainstream option, and the one to reach for first. LiveView Native takes a .heex template plus SwiftUI/Jetpack Compose component implementations and renders it with real native widgets. The LiveView still runs on your server; the phone is a thin native client speaking the LiveView wire protocol.

# mix.exs — server side
def deps do
  [{:live_view_native, "~> 0.3"}]
end
# lib/my_app_web/live/hello_live.ex — one template, two renderers
defmodule MyAppWeb.HelloLive do
  use MyAppWeb, :live_view

  @impl true
  def render(assigns) do
    ~LVN"""
    <VStack spacing={10}>
      <Text>{@title}</Text>
      <Button phx-click="inc">Count: {@count}</Button>
    </VStack>
    """
  end

  # handle_event/3 is unchanged from the web LiveView
  @impl true
  def handle_event("inc", _params, socket) do
    {:noreply, update(socket, :count, &(&1 + 1))}
  end
end

The ~LVN sigil marks the template for the LVN compiler; <VStack>, <Text>, <Button> are SwiftUI/Compose components you implement on the client side. Everything Ch 10 taught — assign/3, handle_event/3, streams, the diffing protocol — is unchanged.

What you get: real native accessibility, native lists and pickers (via components), and one server codebase serving web and both platforms. What you give up: it is not offline. If the server is unreachable, the LiveView has nothing to render — that requirement points at Mob instead.

16.5 The Same OTP Model Represents a Device

The pattern that transfers: a peripheral is a process.

defmodule TemperatureSensor do
  use GenServer

  def start_link(opts \\ []),
    do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)

  def read, do: GenServer.call(__MODULE__, :read)

  @impl true
  def init(_opts) do
    # On real hardware: {:ok, ref} = Circuits.GPIO.open(pin, :input)
    Process.send_after(self(), :tick, 1000)   # self-scheduling: no external kick
    {:ok, %{value: 23.5, unit: :celsius}}
  end

  @impl true
  def handle_call(:read, _from, state), do: {:reply, state.value, state}

  @impl true
  def handle_info(:tick, state) do
    new_value = state.value + Enum.random(-5..5) / 10   # drift ±0.5°
    Process.send_after(self(), :tick, 1000)
    {:noreply, %{state | value: new_value}}
  end
end

{:ok, _pid} = TemperatureSensor.start_link()
TemperatureSensor.read()      #=> 23.5 (then watch it drift via :sys.get_state/1)
Fully runnable in IEx or a Livebook cell — and note the process schedules its own first tick from init/1, so nothing external has to kick it. That matters on firmware: the external `Process.send_after(TemperatureSensor,
tick, 1000)` from the previous version only worked because IEx happened to send it. A device that boots and then waits forever is a bug that no test catches.

Enum.random/1 picks from the range — :rand.uniform/1 only accepts a positive integer bound, so :rand.uniform(-5..5) would crash. On real hardware the state represents a sensor, actuator, connection, or device controller — all supervised, fault-tolerant, distributable.

16.6 Supervision Tree for a Device

flowchart TD
    APP["Device Application"] --> SUP["Device.Supervisor"]
    SUP --> TS["TemperatureSensor<br/>GenServer"]
    SUP --> HS["HumiditySensor<br/>GenServer"]
    SUP --> MOTOR["MotorController<br/>GenServer"]
    SUP --> MQTT["MQTTClient → Cloud"]
    SUP --> OTA["OTAUpdater → firmware"]
    SUP --> WD["Watchdog<br/>hardware watchdog"]
    APP --> RUNTIME["Nerves.Runtime<br/>firmware · network · hw"]

Two different things wear the name “watchdog” — keep them apart:

  • The supervision strategy decides what BEAM does when a process dies. :one_for_one restarts only the crashed sensor, which is what you want.
  • The hardware watchdog is a separate SoC-level timer. If it is not fed within its window, the board resets regardless of what the BEAM believes. That is what recovers from a wedged VM — a supervisor cannot restart a runtime that is no longer scheduling.

No special embedded framework is required for either. The tree you’ve drawn a hundred times for servers is the firmware architecture.

Firmware Updates: burn, Upload, OTA

Three escalation levels, all fwup underneath:

mix burn <sd-card-device>    # factory install — SD card in hand
mix upload nerves.local      # push over SSH: build, stream, swap slot;
                             # device reboots into the new slot atomically

True OTA swaps only the transport, not the mechanism — and you should not be writing that transport. NervesHub (§16.2) gives you update announcement, download, signature verification, staged rollout, and progress reporting as a supervised process you drop into your tree. The device polls a firmware server (or receives an MQTT announcement), downloads the .fw, and fwup validates signatures before touching slots. A failed upgrade falls back to the previous slot — the supervisor’s crash-recovery instinct, applied to images. Because slots make upgrades atomic you ship often; because the BEAM is there, you can also hot-patch inside a running slot when a restart would drop live connections.

Three Tools Every Nerves Session Needs

Small libraries, all in the firmware’s deps, none optional once you start debugging on real hardware:

# 1. Log to a ring buffer instead of the console — survives a crash,
#    readable later with RingLogger.next()/tail()/get()
{:ring_logger, "~> 0.11"}   # + config :logger, backends: [RingLogger]

# 2. Keep the VM alive when an OTP application crashes, and control start order
{:shoehorn, "~> 0.9"}       # + steps: [&Shoehorn.Release.init/1, :assemble]

# 3. IEx helpers for the device — top, cmd, ping, tree, and more
{:toolshed, "~> 0.4"}       # then `use Toolshed` at the IEx prompt

Without RingLogger a panic takes the only diagnostic with it, because stdout went to a console you cannot scroll back. Add it before you need it.

Checkpoint

  1. Which stack would you pick for a $2 microcontroller? A gateway box?
  2. What replaces “driver code” in the AtomVM world?
  3. How does a crashed sensor process recover?
Answers
  1. AtomVM for bare-metal MCUs; Nerves for Linux-class devices/gateways.
  2. Native modules written in C, loaded by the AtomVM packer and called from Elixir as ordinary functions.
  3. Its supervisor restarts it per strategy; siblings continue untouched.

Explore More

  • Nerves getting started — install the toolchain, blink an LED, burn real firmware
  • Nerves projects list — hardware targets, community firmware examples
  • AtomVM docs — ESP32 port guides and the Erlang/Elixir API subset supported
  • vintage_net docs — network configuration you’ll configure on every real device
  • Exercise idea: take Ch 09’s release workflow knowledge to hardware — mix firmware is mix release with a Buildroot rootfs; diff the two trees

Next: Chapter 17 — Nx Fundamentals