Small dump of a tiny presentation I made for a rather small audience on
ElixirNerves and
Phoenix liveview.
Can be followed as a mini tutorial step by step to get an IoT system running a
livebook with a small application backed by Phoenix.
check the same commands through an ssh session: ssh nerves.local pw: nerves
h Toolshed
log_attach to attach to the Elixir Logger (useful to debug running apps)
weather :)
test communication with a simple snippet
Testing MQTT communication, setup:
Run an MQTT broker on the host machine, let’s use mosquitto (if an Address
not available error happens, use the following conf)
Finally run a mosquitto container mounting the local config
Create a new livebook and on the setup paste this dependency
Publish random temperature values in a subsequent code block
Oh no, must rebuild the livebook :( one current limitation of livebook in
nerves is that Mix.install is not supported yet. Livebook can be customized
easily on the host machine.
Flash nerves_livebook into device (rpi4)
Add dependency to the mix.exs
mix.exs
Build the firmware and push it to the device
Now the previous snippet should work correctly and we should see the message
published onto our MQTT broker.
Daring something more
Let’s expand the previous snippet: a GenServer perpetually generating
temperature values and also accepting command from the broker
On a subsequent block, we can run the GenServer
On the host we should see data coming every ~2s, we can confirm it by peeking into the
mosquitto logs or by subscribing to the topic on localhost
Phoenix liveview
Let’s build a simple Phoenix app to subscribe to the topic and see real-time
data coming through LiveView. Let’s not forget --no-ecto we don’t need DBs
here, --no-mailer, --no-gettext, --no-dashboard, and --live. This
should cut out a fair amount of boilerplate.
First thing, let’s add the required dependencies to the mix.exs
temp_dashboard/mix.exs
Update the dependencies with the newly added bit
Let’s add few lines to the main configuration and the development one:
temp_dashboard/config/config.exs
Same on temp_dashboard/config/dev.exs.
Let’s now generate a LiveView controller
We can remove some of them for our single-page app
Finally, we want to add some business logic to our app, fire up the editor on
temp_dashboard/lib/temp_dashboard_web/live/temperature_live/index.ex and
replace the content with the following snippet.
Last step, adding a handler to route our requests to index, removing the
existing /scope
lib/temp_dasboard_web/router.ex
Get the dependencies and run the application, we should see it connecting to
the broker
Let’s open the brower to localhost:4000.
Phoenix LiveView on RPI4
A “poncho project” is similar to an umbrella project except that it’s actually
multiple separate-but-related Elixir apps that use path dependencies instead of
in_umbrella dependencies