<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adrián on Medium]]></title>
        <description><![CDATA[Stories by Adrián on Medium]]></description>
        <link>https://medium.com/@adrian_ribao?source=rss-dd30921ad06b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Klm6sgeWvvQCZt1xe3unMw.jpeg</url>
            <title>Stories by Adrián on Medium</title>
            <link>https://medium.com/@adrian_ribao?source=rss-dd30921ad06b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:29:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adrian_ribao/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Setting up network, DNS, OTA upgrades, SSH access and Debugging— Part 2]]></title>
            <link>https://medium.com/@adrian_ribao/setting-up-network-dns-ota-upgrades-ssh-access-and-debugging-part-2-17afca274027?source=rss-dd30921ad06b------2</link>
            <guid isPermaLink="false">https://medium.com/p/17afca274027</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[nerve]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <dc:creator><![CDATA[Adrián]]></dc:creator>
            <pubDate>Tue, 02 Oct 2018 15:52:30 GMT</pubDate>
            <atom:updated>2018-10-02T15:52:30.464Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elixir Nerves: Setting up network, DNS, OTA upgrades, SSH access and Debugging— Part 2</h3><p>This follows the previous part <a href="https://medium.com/@adrian_ribao/building-a-product-based-on-an-embedded-device-with-elixir-nerves-phoenix-part-1-f7b52b1aee11">Building a product based on an embedded device with Elixir, Nerves &amp; Phoenix</a>.</p><p>The first post was mainly an introduction to the problem we had to solve and how we did it. Now it’s time to go deeper in details!</p><p>The first thing we did on the device was to try some <a href="https://hexdocs.pm/nerves/getting-started.html#nerves-examples">examples</a>. That was nice but we had to move fast to meet our first deadline, and that’s when we had to face the fact that the device wasn’t connected to the network, we couldn’t connect to the device and we had no idea what was going on once it was powered on.</p><p>On the <a href="https://nerves-project.org/libraries/">libraries</a> page, we found <a href="https://github.com/nerves-project/nerves_init_gadget">nerves init gadget</a> which as it is said in the github page:</p><blockquote>* Basic network initialization for USB gadget devices (Raspberry Pi Zero and B+ eaglebone) and wired and wireless Ethernet</blockquote><blockquote>* mDNS support to advertise a name like nerves.local or nerves-1234.local if devices have serial numbers</blockquote><blockquote>* Device detection, filesystem mounting, and basic device control from nerves_runtime</blockquote><blockquote>* Over-the-air firmware updates using nerves_firmware_ssh</blockquote><blockquote>* Easy setup of Erlang distribution to support remsh, Observer and other debug and tracing tools</blockquote><blockquote>* Access to the IEx console via ssh and transfer files with sftp</blockquote><blockquote>* IEx helpers for a happier commandline experience</blockquote><blockquote>* Logging via <a href="https://github.com/nerves-project/ring_logger">ring_logger</a></blockquote><blockquote><a href="https://github.com/nerves-project/shoehorn">* shoehorn</a>-aware instructions to reduce the number of SDCard reprogrammings that you need to do in regular development.</blockquote><p>Ok great, now we could have some very nice features, so let’s go!</p><p>This is the config for nerves init gadget:</p><pre>config :nerves_init_gadget,<br>  ifname: &quot;eth0&quot;,<br>  address_method: :dhcp,<br>  node_name: &quot;my_domain&quot;,<br>  node_host: :mdns_domain,<br>  ssh_console_port: 22</pre><p>Nerves init gadget uses <a href="https://github.com/nerves-project/nerves_network">nerves network</a> so it can be configured easily following the docs:</p><pre>config :nerves_network, :default,<br>  eth0: [<br>    ipv4_address_method: :dhcp<br>  ]</pre><p>Great! and it’s also possible to connect using a WiFi AP:</p><pre>config :nerves_network, :default,<br>  wlan0: [<br>    ssid: System.get_env(&quot;NERVES_NETWORK_SSID&quot;),<br>    psk: System.get_env(&quot;NERVES_NETWORK_PSK&quot;),<br>    key_mgmt: String.to_atom(key_mgmt)<br>  ]</pre><p>Don’t forget to change ifname: &quot;eth0&quot; to ifname: &quot;wlan0&quot;<em> -or the appropiate interface name for the wlan connection-</em> on config :nerves_init_wadget if you want to use a wireless connection. Also keep in mind that environment variables NERVES_NETWORK_SSID and NERVES_NETWORK_PSK should be set when building the firmware.</p><p>…and voila! after burning the new firmware into the device, it’s possible to connect via SSH or even upload a firmware! But wait! what is the IP of the device?</p><p>We started looking in the router, get the IP and use it:</p><pre>ssh &lt;ip_of_the_device&gt;</pre><p>or for OTA upgrades:</p><pre>clear &amp;&amp; mix firmware &amp;&amp; mix firmware.push &lt;ip_of_the_device&gt;</pre><p>We are going to use <a href="https://en.wikipedia.org/wiki/Multicast_DNS">mDNS</a> to expose the ip through a local domain adding mdns_domain: &quot;&lt;my_domain&gt;.local&quot; to the configuration. If you use an Apple device, the address &lt;my_domain&gt;.local is available without further configuration. In my case, since I use a Linux box, I had to install <a href="http://avahi.org/">avahi</a>.</p><p>Here we go! The device is running and accessible using:</p><pre>ssh &lt;my_domain&gt;.local</pre><p>and we are into an IEx console!</p><p><strong><em>Note:</em></strong><em> for exiting the console, you need to use the sequence </em><em>~. that is a ssh escape sequence.</em></p><p>nerves-init-gadget provides <a href="https://github.com/nerves-project/ring_logger">Ring Logger</a> which is an in-memory ring buffer backend for the <a href="https://hexdocs.pm/logger/Logger.html">Elixir Logger</a></p><p>For enabling ring logger, we need to add or edit config.exs and makse sure our logger is configured like this:</p><pre>config :logger, backends: [RingLogger]</pre><p>this time let’s use the OTA upgrade for pushing the new firmware with Ring Logger enabled:</p><pre>clear &amp;&amp; mix firmware &amp;&amp; mix firmware.push &lt;my_domain&gt;.local</pre><p>once it has been uploaded, we can ssh into the IEx shell and attach to the logger:</p><pre>ssh &lt;my_domain&gt;.local<br>iex(derberos@derberos.local)1&gt; RingLogger.attach</pre><p>As you can see in the previous code, my app name and domain name is derberos , you should see your own name here.</p><p>If you want to see the previous logged messages since the app started:</p><pre>iex(derberos@derberos.local)1&gt; RingLogger.tail</pre><p>Nice, we have now a pretty decent device to start working on. We could connect a screen using the HDMI port, but maybe you don’t have one available or you prefer to view the full output of the device in the console.</p><p>For this you need a USB to TTL serial cable like this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*_WzP7n7nWcbUpVY4ADCV6g.jpeg" /><figcaption>USB to TTL cable for Raspberry PI</figcaption></figure><p>One of the ends has 4 cables:</p><ul><li>Red: power</li><li>Black: ground</li><li>White: RX (receiving)</li><li>Green: TX (transmission)</li></ul><p>Red and black are easy (5V PWR &amp; ground), and what you have to take into consideration is that white cable receives data, so it must be connected to the transmission pin of the device. And the green cable sends data, so it must be connected to the receiving pin on the raspberry.</p><p>For a Raspberri PI 3, this is the diagram of the GPIO ports:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*mT0D31yPekh08s1_xpF8-w.png" /><figcaption>Raspberry PI 3 GPIO ports</figcaption></figure><p>The green cable goes to pin 10, and white cable goes to pin 8. Here is a picture of my prototype device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7KUshXbUELNdNpJV_UkocA.jpeg" /><figcaption>Photo of the connections of a Raspberry PI3 to a UART cable</figcaption></figure><p>Once you had connected the device to the computer, you need a program for serial communication, I usually use <a href="https://github.com/npat-efault/picocom">picocom</a> or <a href="https://linux.die.net/man/1/minicom">minicom</a>, but there are many available for every platform.</p><p>Before connecting to the device, we need to find the USB id. Connect the cable to the device and the computer, and then, you should see the id under/dev/serial/by-id</p><pre>ls /dev/serial/by-id/</pre><p>It’s important to set the the baud rate for the communication to 115200.</p><p>Now you are ready to see your device output with one of these two commands:</p><pre>picocom -b 115200 /dev/serial/by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller-if00-port0</pre><p>or</p><pre>minicom -b 115200 -o -D /dev/serial/by-path/pci-0000:00:1d.0-usb-0:1.6:1.0-port0</pre><p>If the Raspberry Pi was already connected and powered on, maybe you can’t see anything because nothing is happening, but you can restart it and check the boot-up sequence:</p><pre>iex(derberos@derberos.local)1&gt; Nerves.Runtime.reboot</pre><p>Here an example of the first second of the bootup:</p><pre>[ 0.000000] Booting Linux on physical CPU 0x0<br>[ 0.000000] Linux version 4.9.80 (antares@escorpion) (gcc version 7.3.0 (crosstool-NG 1.23.0.418-d590) ) #2 SMP PREEMPT Mon Aug 6 21:04:15 CEST 2018<br>[ 0.000000] CPU: ARMv7 Processor [410fd034] revision 4 (ARMv7), cr=10c5383d<br>[ 0.000000] CPU: div instructions available: patching division code<br>[ 0.000000] CPU: PIPT / VIPT nonaliasing data cache, VIPT aliasing instruction cache<br>[ 0.000000] OF: fdt:Machine model: Raspberry Pi 3 Model B Plus Rev 1.3<br>[ 0.000000] cma: Reserved 8 MiB at 0x33800000<br>[ 0.000000] Memory policy: Data cache writealloc<br>[ 0.000000] percpu: Embedded 14 pages/cpu <a href="http://twitter.com/b3060000">@b3060000</a> s25804 r8192 d23348 u57344<br>[ 0.000000] Built 1 zonelists in Zone order, mobility grouping on. Total pages: 211120<br>[ 0.000000] Kernel command line: 8250.nr_uarts=1 bcm2708_fb.fbwidth=656 bcm2708_fb.fbheight=416 bcm2708_fb.fbswap=1 vc_mem.mem_base=0x3ec00000 vc_mem.mem_size=0x40000000<br>[ 0.000000] PID hash table entries: 4096 (order: 2, 16384 bytes)<br>[ 0.000000] Dentry cache hash table entries: 131072 (order: 7, 524288 bytes)<br>[ 0.000000] Inode-cache hash table entries: 65536 (order: 6, 262144 bytes)<br>[ 0.000000] Memory: 822992K/851968K available (7168K kernel code, 414K rwdata, 1588K rodata, 1024K init, 473K bss, 20784K reserved, 8192K cma-reserved)<br>[ 0.000000] Virtual kernel memory layout:<br>[ 0.000000] vector : 0xffff0000–0xffff1000 ( 4 kB)<br>[ 0.000000] fixmap : 0xffc00000–0xfff00000 (3072 kB)<br>[ 0.000000] vmalloc : 0xb4800000–0xff800000 (1200 MB)<br>[ 0.000000] lowmem : 0x80000000–0xb4000000 ( 832 MB)<br>[ 0.000000] modules : 0x7f000000–0x80000000 ( 16 MB)<br>[ 0.000000] .text : 0x80008000–0x80800000 (8160 kB)<br>[ 0.000000] .init : 0x80b00000–0x80c00000 (1024 kB)<br>[ 0.000000] .data : 0x80c00000–0x80c678b8 ( 415 kB)<br>[ 0.000000] .bss : 0x80c69000–0x80cdf628 ( 474 kB)<br>[ 0.000000] SLUB: HWalign=64, Order=0–3, MinObjects=0, CPUs=4, Nodes=1<br>[ 0.000000] Preemptible hierarchical RCU implementation.<br>[ 0.000000] Build-time adjustment of leaf fanout to 32.<br>[ 0.000000] NR_IRQS:16 nr_irqs:16 16<br>[ 0.000000] arm_arch_timer: Architected cp15 timer(s) running at 19.20MHz (phys).<br>[ 0.000000] clocksource: arch_sys_counter: mask: 0xffffffffffffff max_cycles: 0x46d987e47, max_idle_ns: 440795202767 ns<br>[ 0.000007] sched_clock: 56 bits at 19MHz, resolution 52ns, wraps every 4398046511078ns<br>[ 0.000023] Switching to timer-based delay loop, resolution 52ns<br>[ 0.000303] Console: colour dummy device 80x30<br>[ 0.001634] console [tty1] enabled<br>[ 0.001690] Calibrating delay loop (skipped), value calculated using timer frequency.. 38.40 BogoMIPS (lpj=192000)<br>[ 0.001780] pid_max: default: 32768 minimum: 301<br>[ 0.001985] Mount-cache hash table entries: 2048 (order: 1, 8192 bytes)<br>[ 0.002042] Mountpoint-cache hash table entries: 2048 (order: 1, 8192 bytes)<br>[ 0.003115] Disabling memory control group subsystem<br>[ 0.003229] CPU: Testing write buffer coherency: ok<br>[ 0.003306] ftrace: allocating 20926 entries in 62 pages<br>[ 0.048159] CPU0: update cpu_capacity 1024<br>[ 0.048217] CPU0: thread -1, cpu 0, socket 0, mpidr 80000000<br>[ 0.048285] Setting up static identity map for 0x100000–0x100034<br>[ 0.218224] CPU1: update cpu_capacity 1024<br>[ 0.218232] CPU1: thread -1, cpu 1, socket 0, mpidr 80000001<br>[ 0.288328] CPU2: update cpu_capacity 1024<br>[ 0.288335] CPU2: thread -1, cpu 2, socket 0, mpidr 80000002<br>[ 0.358450] CPU3: update cpu_capacity 1024<br>[ 0.358457] CPU3: thread -1, cpu 3, socket 0, mpidr 80000003<br>[ 0.358561] Brought up 4 CPUs<br>[ 0.358777] SMP: Total of 4 processors activated (153.60 BogoMIPS).<br>[ 0.358816] CPU: All CPU(s) started in HYP mode.<br>[ 0.358849] CPU: Virtualization extensions available.<br>[ 0.359712] devtmpfs: initialized<br>[ 0.371864] VFP support v0.3: implementor 41 architecture 3 part 40 variant 3 rev 4<br>[ 0.372217] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 19112604462750000 ns<br>[ 0.372293] futex hash table entries: 1024 (order: 4, 65536 bytes)<br>[ 0.372885] pinctrl core: initialized pinctrl subsystem<br>[ 0.373901] NET: Registered protocol family 16<br>[ 0.376168] DMA: preallocated 1024 KiB pool for atomic coherent allocations<br>[ 0.385460] hw-breakpoint: found 5 (+1 reserved) breakpoint and 4 watchpoint registers.<br>[ 0.385520] hw-breakpoint: maximum watchpoint size is 8 bytes.<br>[ 0.385699] Serial: AMBA PL011 UART driver<br>[ 0.387865] bcm2835-mbox 3f00b880.mailbox: mailbox enabled<br>[ 0.388547] uart-pl011 3f201000.serial: could not find pctldev for node /soc/gpio@7e200000/uart0_pins, deferring probe<br>[ 0.389211] irq: no irq domain found for /soc/aux@0x7e215000 !<br>[ 0.436506] bcm2835-dma 3f007000.dma: DMA legacy API manager at b480d000, dmachans=0x1<br>[ 0.438466] SCSI subsystem initialized<br>[ 0.438666] usbcore: registered new interface driver usbfs<br>[ 0.438781] usbcore: registered new interface driver hub<br>[ 0.438920] usbcore: registered new device driver usb<br>[ 0.448520] raspberrypi-firmware soc:firmware: Attached to firmware from 2018–03–21 14:52<br>[ 0.450711] clocksource: Switched to clocksource arch_sys_counter<br>[ 0.492303] FS-Cache: Loaded<br>[ 0.492596] CacheFiles: Loaded<br>[ 0.506100] NET: Registered protocol family 2<br>[ 0.506938] TCP established hash table entries: 8192 (order: 3, 32768 bytes)<br>[ 0.507086] TCP bind hash table entries: 8192 (order: 4, 65536 bytes)<br>[ 0.507306] TCP: Hash tables configured (established 8192 bind 8192)<br>[ 0.507432] UDP hash table entries: 512 (order: 2, 16384 bytes)<br>[ 0.507508] UDP-Lite hash table entries: 512 (order: 2, 16384 bytes)<br>[ 0.507768] NET: Registered protocol family 1<br>[ 0.508466] hw perfevents: enabled with armv7_cortex_a7 PMU driver, 7 counters available<br>[ 0.511070] workingset: timestamp_bits=14 max_order=18 bucket_order=4<br>[ 0.527511] squashfs: version 4.0 (2009/01/31) Phillip Lougher<br>[ 0.532799] Block layer SCSI generic (bsg) driver version 0.4 loaded (major 251)<br>[ 0.532988] io scheduler noop registered<br>[ 0.533025] io scheduler deadline registered<br>[ 0.533362] io scheduler cfq registered (default)<br>[ 0.539128] BCM2708FB: allocated DMA memory f3900000<br>[ 0.539188] BCM2708FB: allocated DMA channel 0 @ b480d000<br>[ 0.547185] Console: switching to colour frame buffer device 82x26<br>[ 0.554021] Serial: 8250/16550 driver, 1 ports, IRQ sharing enabled<br>[ 0.558670] bcm2835-rng 3f104000.rng: hwrng registered<br>[ 0.560998] vc-mem: phys_addr:0x00000000 mem_base=0x3ec00000 mem_size:0x40000000(1024 MiB)<br>[ 0.565902] vc-sm: Videocore shared memory driver<br>[ 0.583794] brd: module loaded<br>[ 0.595498] loop: module loaded<br>[ 0.597615] Loading iSCSI transport class v2.0–870.<br>[ 0.600438] spi-bcm2835 3f204000.spi: could not get clk: -517<br>[ 0.602858] dwc_otg: version 3.00a 10-AUG-2012 (platform bus)<br>[ 0.832900] Core Release: 2.80a<br>[ 0.834869] Setting default values for core params<br>[ 0.836853] Finished setting default values for core params<br>[ 1.039191] Using Buffer DMA mode</pre><p>This helps a lot when something breaks the Erlang VM and you can’t ssh into the IEx console and take a look at Ring Logger. Usually this happens with issues starting processes.</p><p>And that’s it. We have accomplished quite a few things in this post, in the next posts I’ll keep talking about how to configure the raspberry pi to be an useful device with a purpose.</p><p>Don’t miss part 3, coming soon: Using OTP Genservers on nerves to publish the device IP to a custom domain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17afca274027" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a product based on an embedded device with Elixir, Nerves & Phoenix — Part 1]]></title>
            <link>https://medium.com/@adrian_ribao/building-a-product-based-on-an-embedded-device-with-elixir-nerves-phoenix-part-1-f7b52b1aee11?source=rss-dd30921ad06b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7b52b1aee11</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[nerve]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <dc:creator><![CDATA[Adrián]]></dc:creator>
            <pubDate>Tue, 25 Sep 2018 10:06:40 GMT</pubDate>
            <atom:updated>2018-10-02T15:53:27.535Z</atom:updated>
            <content:encoded><![CDATA[<p>We are facing some changes in Europe regarding data protection. The <a href="https://eugdpr.org/">EU General Data Protection Regulation (GDPR)</a> has changed some rules, and has made some advancements protecting the citizens data. This is very good from an user perspective, but it requires work for the companies. Data must be treated very carefully, with contracts with every customer &amp; provider, security is considered very important and consents to use people’s data need to be explicit.</p><p>Slowly, companies are more and more concerned about the data they manage, and they want to protect it and be GDPR compliant. This led to one of those companies to ask us for a product to sign digital contracts, consents with the users/patients, and other features they needed. One constraint was that they want to hold the data in their offices. No cloud, external servers or SAAS. Basically they wanted a box with the software running, and that’s what we did.</p><p>We could have used the traditional pre-cloud era approach. Buy them a server and put it in their installations. But even a normal server is over-dimensioned for their needs, it’s big -physically-, consumes electricity, it’s noisy sometimes… so we thought about it and concluded that we could try to embed it in a small box with a Raspberry Pi 3, that they could just plug and use. For them is pretty cool because they are using an iPad, so they just plug the box, and they have the app in their iPad through the browser, which can move with them through the installations.</p><p>We were going to do it using <a href="https://elixir-lang.org/">Elixir</a> &amp; <a href="http://elm-lang.org/">Elm</a> and it happens that Elixir has an awesome project, the <a href="https://nerves-project.org/">Nerves Project</a>, that would be perfect for our needs. We were excited by the fact of device ruled by the Erlang VM, with a very small footprint and the concurrency and reliability that makes the Erlang VM glorious.</p><p>The truth is that coming from years of pure web developments, starting to develop taking the OS and the hardware into consideration wasn’t a piece of cake. But I can tell you it was pretty fun. We had an amazing support from the community, we couldn’t have done it otherwise. We asked a lot in the <a href="https://elixirforum.com/">Elixir Forum</a>, and two core developers were specially helpful, so I want to thank to <a href="https://github.com/ConnorRigby">Connor Rigby</a><a href="http://www.gregmefford.com/">, Greg Mefford</a><a href="https://github.com/tmecklem">, Tim Mecklem,</a> <a href="https://github.com/fhunleth">Frank Hunleth</a>…and some others… for their help. They are doing an awesome job.</p><p>After this introduction, let’s go with the technical details of the project.</p><p>We started setting up nerves in a Raspberry Pi 3, and no problem here. It worked! But we were just beginning :-)</p><p>The buildroot image is not what we were used to. The device had no network, no ssh access, no shell, we couldn’t debug easily, not easy to upgrade the firmware, we had to take the SDCard out of the device, burn the new image, insert it again and reboot… Not what we expected.</p><p>We found the <a href="https://github.com/nerves-project/nerves_init_gadget">nerves init gadget</a> listed in the <a href="https://nerves-project.org/libraries/">libraries page</a> of the nerves web, it provides several useful tools for making the device more useful, so after we set it up we had a device connected to a network, with over-the-air (OTA) upgrades via ssh, an IEx shell accessible through ssh, and a mDNS domain published in our network.</p><p>Next we installed the UI using <a href="https://phoenixframework.org/">Phoenix</a> and it was very satisfying to find out that introducing the local domain name in the browser showed our UI! Very exciting!</p><p>At this point we focused efforts on the UI. We build what we were asked for. Nothing new from what we were used to do, just developing a web app. But there was a point where I felt a bit different, from previous cloud developments. I wanted to show in the UI the usage of the storage. Showing hardware information wasn’t something usual for us. At that point, I felt comfortable with the sense of control that we got managing the whole stack: Hardware, OS and software. I finally understood Apple :-)</p><p>I can tell you something, OTP in an embedded device gives me a great peace of mind!</p><p>From here we had to face som other problems:</p><ul><li>We needed a better way to debug the console without connecting the device to a monitor. We connected the Raspberry Pi to a console using a TTL USB Serial Cable.</li><li>We planned to sell the device in all the country, and who knows if in other countries too in the future. What if once the device is in the customer installations we needed to debug or fix something? Should we go to their installations? We can’t afford that. We need to connect remotely to the device. We have access to an elixir shell, but we need the public IP for the device, and a properly configured network that allow us to access the device. How do we get that IP?</li><li>What if we ever need a very basic ssh access to the device? Could we get access the <a href="https://busybox.net/">busybox</a> utils?</li><li>The project was based on a SQLite3 database. It was a very good idea for our initial requirements. All the data in a single file, easy to backup, portable, and it fit perfectly for the expected load. But as the project grows, potential customers asked us to make other developments, and I decided to use PostgreSQL in the device. What a fascinating journey is installing PostgreSQL in busybox…</li></ul><p>Every point deserves their own post, and this one got already bigger than I expected, so let’s split them up. In the upcoming posts I’ll talk how we resolved those problems:</p><ul><li><a href="https://medium.com/@adrian_ribao/setting-up-network-dns-ota-upgrades-ssh-access-and-debugging-part-2-17afca274027">Setting up network, DNS, OTA upgrades, SSH access and Debugging with Ring Logger and a TTL USB Serial Cable.</a></li><li>Using OTP Genservers on nerves to publish the device IP to a custom domain.</li><li>Creating the UI using <a href="https://phoenixframework.org/">Phoenix</a></li><li>Connect remotely to a shell on the device and use basic linux commands using <a href="https://matt.ucc.asn.au/dropbear/dropbear.html">dropbear</a>, a tiny ssh server.</li><li>Customizing Buildroot packages: How to setup PostgreSQL, with Elixir Nerves &amp; Phoenix</li></ul><p>In the following days I’ll be publishing my notes on those topics, I hope you find them useful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7b52b1aee11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Elm — How to show content in tabs]]></title>
            <link>https://medium.com/@adrian_ribao/learning-elm-how-to-show-content-in-tabs-6150262dff4d?source=rss-dd30921ad06b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6150262dff4d</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[tabs]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Adrián]]></dc:creator>
            <pubDate>Fri, 08 Jun 2018 12:32:05 GMT</pubDate>
            <atom:updated>2018-06-08T12:32:05.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpsSSJJ-P4LJwzND-QKrww.png" /></figure><p>In <a href="https://adrima.es/">Adrima</a> we are currently growing and new people is coming to work with us. We are very excited about that, but here in Spain not too many people knows <a href="http://elm-lang.org/">Elm</a>. I find myself tutoring the new developers, so I thought, “why not write it down and make it publicly available?”. At least this way I can reuse the time spent on teaching. I don’t have too much time myself, I work way too many hours a day, and we are lucky to be part of very interesting and awesome projects, so don’t expect this series to be an exhaustive tutorial. The reader will have to spend time investigating and thinking too :-)</p><p>I’d like to start with something very simple. Let’s emulate a tab component built 100% with Elm. I will use <a href="https://getbootstrap.com/">Bootstrap4</a> just to make it look nice, but in the future everything will be done using the wonderful library <a href="http://package.elm-lang.org/packages/mdgriffith/style-elements/4.3.0">Elm style elements</a>.</p><p>Let’s start with a basic program. We will be using <a href="https://ellie-app.com/new">ellie</a> to show the progress.</p><p><a href="https://ellie-app.com/s8z8mFmfsfa1">https://ellie-app.com/s8z8mFmfsfa1</a></p><p>These are the <strong>requirements</strong>:</p><ul><li>We need three tabs for our application: <strong>Step1</strong>, <strong>Step2</strong> and <strong>Step3</strong></li><li>Only one tab can be selected</li><li>The app must show if the tab is active somehow</li></ul><p>Union Types are great for this particular purpose. Read about them here:</p><ul><li><a href="https://guide.elm-lang.org/types/union_types.html">Union Types · An Introduction to Elm</a></li><li><a href="https://www.elm-tutorial.org/en/01-foundations/05-union-types.html">Union types · Elm Tutorial</a></li></ul><p>So we can define our tabs like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/809d29f99b26c20de5d43cb082981daa/href">https://medium.com/media/809d29f99b26c20de5d43cb082981daa/href</a></iframe><p>and in our model, we only need to keep track of the current active tab, so the model it’s quite simple in this case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b16b6f5105fc1a93c8ad816fd66a0b98/href">https://medium.com/media/b16b6f5105fc1a93c8ad816fd66a0b98/href</a></iframe><p>Our app now would look like this:</p><p><a href="https://ellie-app.com/s9bcbhmTmBa1">https://ellie-app.com/s9bcbhmTmBa1</a></p><p>still the same results, but we have our model ready to be used in the view.</p><p>The views are easily rendered now based on our model. We know which tab is currently active and we can render the content for that tab.</p><p>We can think of the view as two separated parts, the tabs headers and the tab content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff329fb788c624067b6aefab856ee573/href">https://medium.com/media/ff329fb788c624067b6aefab856ee573/href</a></iframe><p>We are using Bootstrap to make it look nice at the moment. The markup it’s a bit more verbose but it’s not that bad. This could be the renderHeaders function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6330b9c0539c04e9538f347538c3fb4d/href">https://medium.com/media/6330b9c0539c04e9538f347538c3fb4d/href</a></iframe><p>And therenderTabContent function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/667018ae49ea3d601f7fcdf40690a070/href">https://medium.com/media/667018ae49ea3d601f7fcdf40690a070/href</a></iframe><p>Our app now looks a bit better, but still we can’t change tabs:</p><p><a href="https://ellie-app.com/s9tKJNCkg7a1">https://ellie-app.com/s9tKJNCkg7a1</a></p><p>One of the things I like more about Elm, is that the compiler checks for you that the code should take into consideration all the possibilities in conditionals, and we should never find an undefined/unconsidered situation. If in the previous function, if we remove from line 10 to the end, the compiler shows a nice message:</p><pre>This `case` does not have branches for all possibilities.</pre><pre>You need to account for the following values: </pre><pre> Main.Step3 </pre><pre>Add a branch to cover this pattern!</pre><pre>If you are seeing this error for the first time, check out these hints: &lt;https://github.com/elm-lang/elm-compiler/blob/0.18.0/hints/missing-patterns.md&gt; The recommendations about wildcard patterns and `Debug.crash` are important!</pre><p>The compiler tell us to take into consideration the Step3 of the tabs that we didn’t include in our conditional case. This is awesome.</p><p>What we need now is the ability to change the active tab. For modifying a model we always need to trigger a message. That message will change the model and render the view with the new model. We need only one message here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/659aa14f0157e072f8dd53d90eef4ecd/href">https://medium.com/media/659aa14f0157e072f8dd53d90eef4ecd/href</a></iframe><p>and take car of it in the update function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/365c9e3661e58e55916225441b1aedbc/href">https://medium.com/media/365c9e3661e58e55916225441b1aedbc/href</a></iframe><p>and finally, we need to send that message when we click on the headers. The <a href="http://package.elm-lang.org/packages/elm-lang/html/2.0.0/Html-Events#onClick">onClick event does just that</a>. So we need to update our tab headers and process the onClick event:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7e37edb8c665e9321c89c0fac5e5f07/href">https://medium.com/media/f7e37edb8c665e9321c89c0fac5e5f07/href</a></iframe><p>Note that the onClick event takes only one argument so we need to either use parenthesis or the &lt;|pipeline operator.</p><p>These is equivalent:</p><pre>onClick (ChangeTab Step1)</pre><pre>and</pre><pre>onClick &lt;| ChangeTab Step1</pre><p>And finally we’d like to highlight the current tab. We are using the <a href="http://package.elm-lang.org/packages/elm-lang/html/2.0.0/Html-Attributes#classList">classList</a> Attribute for that.</p><p><em>classList</em> takes a list of tuples, where the first element in the tuple is the class name and the second is a Boolean indicating whether this class is going to be applied or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea4a40a21880387bdc7d49bf91c0ef21/href">https://medium.com/media/ea4a40a21880387bdc7d49bf91c0ef21/href</a></iframe><p>This is our final app:</p><p><a href="https://ellie-app.com/s9ZmrdLTMZa1">https://ellie-app.com/s9ZmrdLTMZa1</a></p><p>Basic tab functionality on Elm!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6150262dff4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursive decoders on Elm to manage server side validation errors]]></title>
            <link>https://medium.com/@adrian_ribao/recursive-decoders-on-elm-to-manage-server-side-validation-errors-82bee47cc38c?source=rss-dd30921ad06b------2</link>
            <guid isPermaLink="false">https://medium.com/p/82bee47cc38c</guid>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Adrián]]></dc:creator>
            <pubDate>Tue, 28 Mar 2017 14:22:24 GMT</pubDate>
            <atom:updated>2017-03-28T14:22:24.305Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m refactoring a big project using <a href="http://www.phoenixframework.org/">Phoenix Framework </a>and <a href="http://elm-lang.org/">Elm</a>, the previous technology included a <a href="https://www.djangoproject.com/">Django</a> backend with some sort of frontend technologies using mostly jQuery and a bit of backbone.</p><p>After some serious research, I decided to use <a href="http://elixir-lang.org/">Elixir</a> for the backend and Elm for the frontend, and so far, I couldn’t be happier. As the project grows, Elm provides a robust compiler that helps a lot when adding features and making sure the old code still works. The compiler is like a very smart assistant that prevents me from doing mistakes.</p><p>It wasn’t an easy path, switching from an OO paradigm to a functional one that is so different from all the other technologies I knew, took me some time. I had to start thinking in different ways, but this is like using vim, once you learn it, you can’t live without it. Totally worth it.</p><p>In functional programming, recursion is an important topic. It helps to write clean programs that can do tricky things, but sometimes is not very straightforward to reason about recursion. I’m explaining here one problem I had these days trying to get validation errors from the backend for nested forms, and how I solved it with some help from the community.</p><p>When submitting data with invalid fields, this is how the server responds:</p><pre>{ &quot;errors&quot; : {<br>    &quot;field_name&quot;: [&quot;Invalid length&quot;]<br>}}</pre><p>Each field name has a list of strings explaining the validation errors. A decoder for this data is very straightforward:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.ellie-app.com%2FLFx55gFDT4a1%2F2&amp;url=https%3A%2F%2Fellie-app.com%2FLFx55gFDT4a1%2F2&amp;image=https%3A%2F%2Fdbamidicc4dm6.cloudfront.net%2Fimages%2Fellie-announcement%2Fellie_profile_pic_2.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=ellie-app" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3932384d8a4c51cbd1769aeead78fdce/href">https://medium.com/media/3932384d8a4c51cbd1769aeead78fdce/href</a></iframe><p>Now, let’s introduce oneOf, a decoder that can try different decoders from a list and use the first one that succeeded decoding the values.</p><p>If we had a json where the values of the field could either be a string or an integer like this:</p><pre>{ &quot;errors&quot; : {<br>    &quot;field_name&quot;: [&quot;Invalid length&quot;],<br>    &quot;second_field&quot;: [1, 2, 3]<br>}}</pre><p>we could define the decodeFieldErro function as:</p><pre>decodeFieldError : Decoder FieldError<br>decodeFieldError =<br>    dict &lt;| list &lt;| oneOf [ string, int ]</pre><p>but that will give us an error:</p><pre>The 1st entry has this type:<br><br>Decoder String<br><br>But the 2nd is:<br><br>Decoder Int</pre><p>This is great, we have been informed that the decoder has to return the same type of value for each scenario. This is why elm is so good, won’t allow us to do this kind of things that cause so much pain in other languages. Here we can use <a href="https://guide.elm-lang.org/types/union_types.html">Union Types</a> (also known by the fancier name of <a href="https://en.wikipedia.org/wiki/Algebraic_data_type">Algebraic data types</a>) to combine the different values that might be in the json:</p><pre>type FieldValueError<br>    = StringError String<br>    | IntError Int</pre><p>That would work. We define a FieldValueError type that can either be a StringError or an IntError, both of them are of the type FieldValueError. StringError contains strings and IntErrorcontains ints.</p><p>Let’s make oneOf return a FieldValueError:</p><pre>-- Field Error now doesn&#39;t return a string, but a FieldValueError<br>type alias FieldError =<br>    Dict String (List FieldValueError)</pre><pre>-- and this is how the decoder would look:<br>decodeFieldError : Decoder FieldError<br>decodeFieldError =<br>    dict &lt;|<br>        list &lt;|<br>            oneOf<br>                [ map StringError string<br>                , map IntError int<br>                ]</pre><p>We map the values of the decoder to the type constructors. This is the result we get after decoding:</p><pre>(Dict.fromList [<br>    (&quot;name&quot;, [StringError &quot;Invalid length&quot;]),<br>    (&quot;other_field&quot;,[IntError 1,IntError 2,IntError 3])<br>])</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.ellie-app.com%2FLFx55gFDT4a1%2F3&amp;url=https%3A%2F%2Fellie-app.com%2FLFx55gFDT4a1%2F3&amp;image=https%3A%2F%2Fdbamidicc4dm6.cloudfront.net%2Fimages%2Fellie-announcement%2Fellie_profile_pic_2.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=ellie-app" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/94c036d34ec367145e0d3ed59addb107/href">https://medium.com/media/94c036d34ec367145e0d3ed59addb107/href</a></iframe><p>We are already familiar oneOf and how it helps to decode different shapes for json values. The integer decoder was just an example, but to decode our nested errors fields we don’t need it. So now we have a json like this:</p><pre>{ &quot;errors&quot; : {<br>    &quot;name&quot;: [&quot;Invalid length&quot;],<br>    &quot;nested_field&quot;: [<br>        {&quot;age&quot;: [&quot;Invalid age&quot;], &quot;name&quot;: [&quot;Name too long&quot;]},<br>        {&quot;name&quot;: [&quot;Name too short&quot;]}<br>    ]<br>}}</pre><p>The field nested_fieldhas a list but that list instead of being from strings are from a different type. Its a list of dicts that have a string as a key and a list of strings as values. We need to shape this data in our FieldValueError.</p><pre>type FieldValueError<br>    = StringError String<br>    | NestedError (Dict String (List FieldValueError))</pre><p><em>Note that we have removed IntError for clarity</em></p><p>We have introduced the recursion here. The nested field is a list of dicts, and what can those dicts have as a values? In this case a list of strings, but it could also contain another list of dicts for a depth 2 nested forms.</p><p>It’s time to make the decodeFieldError return also nested errors, but first, since the function is getting too big, let’s split it:</p><pre>decodeFieldError : Decoder FieldError<br>decodeFieldError =<br>    dict &lt;| list &lt;| decodeValue</pre><pre>decodeValue : Decoder FieldValueError<br>decodeValue =<br>    oneOf<br>        [ map StringError string<br>        , map NestedError &lt;| (dict (list (lazy (\_ -&gt; decodeValue))))<br>        ]</pre><p>the important thing here is the line:</p><pre>map NestedError &lt;| dict (list (lazy (\_ -&gt; decodeValue)))</pre><p>We know that the values of the field may be a dict of strings or a dict of dicts. Either of them are decoded with the function decodeValue. So the first thing that came to my mind was to use</p><pre>map NestedError &lt;| dict (list decodeValue)</pre><p>But this causes an infinite loop, and here is when we use the <a href="http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode#lazy">lazy</a> function of Json.Decode</p><blockquote>Sometimes you have JSON with recursive structure, like nested comments. You can use lazy to make sure your decoder unrolls lazily.</blockquote><p>So let’s replace decodeValuewith lazy(\_ -&gt; decodeValue).</p><p>And this is the final result that we get from this decoder:</p><pre>Dict.fromList [<br>    (&quot;name&quot;,[StringError &quot;Invalid length&quot;]),<br>    (&quot;nested_field&quot;, [<br>        NestedError (Dict.fromList [<br>          (&quot;age&quot;,[StringError &quot;Invalid age&quot;]),<br>          (&quot;name&quot;,[StringError &quot;Name too long&quot;])]),<br>        NestedError (Dict.fromList [(<br>          &quot;name&quot;,[StringError &quot;Name too short&quot;])])<br>     ])<br>]</pre><p>The code:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.ellie-app.com%2FLFx55gFDT4a1%2F6&amp;url=https%3A%2F%2Fellie-app.com%2FLFx55gFDT4a1%2F6&amp;image=https%3A%2F%2Fdbamidicc4dm6.cloudfront.net%2Fimages%2Fellie-announcement%2Fellie_profile_pic_2.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=ellie-app" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9b37f7e30e14a318f8cff1a59915fd0/href">https://medium.com/media/a9b37f7e30e14a318f8cff1a59915fd0/href</a></iframe><p>Isn’t this beautiful?! The code looks pretty good, nice and clean, and is doing a great job for us. Phoenix is managing very well the nested forms in the backend, we have solid tools that, in my case, are helping me to build a great interface to manage complex data, like data related to job offers and Curriculum Vitae (resumé).</p><p>As a side note, I’m also working on other big projects using React and redux, and I don’t even want to think on how I would do this using only js.</p><p>Do you want to experiment with deeper nested fields like:</p><pre>{ &quot;errors&quot; : {<br>    &quot;name&quot;: [&quot;Invalid length&quot;],<br>    &quot;nested_field&quot;: [<br>        {&quot;age&quot;: [&quot;Invalid age&quot;], &quot;name&quot;: [&quot;Name too long&quot;]},<br>        {&quot;name&quot;: [&quot;Name too short&quot;]},<br>        {&quot;depth2&quot; : [<br>            {&quot;nickname&quot;: [&quot;This nickname is too ugly&quot;]}<br>        ]}<br>    ]<br>}}</pre><p>Try it on Ellie and get excited with the results! :-)</p><p>If you don’t know elm, I strongly encourage you to learn it, whether you end up using it or not, your brain will be able face problems in new original ways.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82bee47cc38c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a SPA application in Elm 0.18 (from scratch)]]></title>
            <link>https://medium.com/@adrian_ribao/how-to-create-a-spa-application-in-elm-0-18-from-scratch-68d25e0631f6?source=rss-dd30921ad06b------2</link>
            <guid isPermaLink="false">https://medium.com/p/68d25e0631f6</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Adrián]]></dc:creator>
            <pubDate>Tue, 15 Nov 2016 20:13:50 GMT</pubDate>
            <atom:updated>2016-11-16T11:13:31.837Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basic routing</h3><p>The new Elm version introduces some breaking changes in the syntax and the navigation libraries that simplifies a bit the creation of SPA apps using Elm.</p><p>I’ve been working with Python and Django since 2007, and lately, functional languages caught my eye. I’m very interested in real time applications under high loads. Even though Django is great, it wasn’t designed under this paradigm. That’s why I’m investing time on learning Elixir and Elm. Both projects are really exciting, I didn’t have this feeling since I discovered Django. I never liked nodejs to be honest, and perhaps the main reason is that I don’t like javascript.</p><p>This is where Elm comes into action. I’m new in Elm, and the change of paradigm from OO to functional is not easy. Also, Elm lacks the maturity of other languages and frameworks where you can find tons of examples. The good point is that once you grasp some basic concepts you don’t want to go back again.</p><p>In order to learn more about Elixir, Phoenix and Elm, I decided to rewrite a medium-sized product that was written in Django. I’m happy with the decision, but some things like SPAs took me some time to learn.</p><p>Here I will explain a method to create SPAs, using ELM. Something very basic that could be easily extended.</p><p>All the code lives here: <a href="https://github.com/AdrianRibao/elm-spa-example">https://github.com/AdrianRibao/elm-spa-example</a> and I will tag commits with each step of the process.</p><p>So starting from a basic elm structure like this, we are creating a basic SPA with some concepts I learned in the way.</p><pre>module SPA exposing (..)<br><br>import Html exposing (..)<br><br><br>main =<br>    Html.program<br>        { init = init<br>        , view = view<br>        , update = update<br>        , subscriptions = subscriptions<br>        }<br><br><br>type alias Model =<br>    {}<br><br><br>init : ( Model, Cmd Msg )<br>init =<br>    ( Model, Cmd.none )<br><br><br><br>-- UPDATE<br><br><br>type Msg<br>    = Noop<br><br><br>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        Noop -&gt;<br>            ( model, Cmd.none )<br><br><br><br>-- VIEW<br><br><br>view : Model -&gt; Html Msg<br>view model =<br>    div []<br>        [ text &quot;Hello world!&quot;<br>        ]<br><br><br><br>-- SUBSCRIPTIONS<br><br><br>subscriptions : Model -&gt; Sub Msg<br>subscriptions model =<br>    Sub.none</pre><p>SPAs means that we have several pages, so the view function can render the appropriate page each time. First thing is to know which page is currently active, so we need to track it in the model.</p><p>We will define also a Page union type with the pages that will conform our application, for example:</p><pre>type Page<br>    = Home<br>    | Login<br>    | About</pre><p>and update our model to track the current Page:</p><pre>type alias Model =<br>    { currentPage : Page<br>    }</pre><p>We need to change also the init function to return the initial current page (Home in this case):</p><pre>init : ( Model, Cmd Msg )<br>init =<br>    ( Model Home, Cmd.none )</pre><p>So now let’s change our view function so it shows the content for each selected page:</p><pre>view : Model -&gt; Html Msg<br>view model =<br>    div []<br>        [ h1 [] [ text &quot;SPA application&quot; ]<br>        , render_page model<br>        ]</pre><p>where the function <em>render_page</em> is:</p><pre>render_page : Model -&gt; Html Msg<br>render_page model =<br>    let<br>        page_content =<br>            case model.currentPage of<br>                Home -&gt;<br>                    text &quot;Home&quot;</pre><pre>                Login -&gt;<br>                    text &quot;Login&quot;</pre><pre>                About -&gt;<br>                    text &quot;About&quot;<br>    in<br>        div [] [ page_content ]</pre><p>We have to take care of all the pages defined in the Page union type, otherwise, the compiler will complain with a nice error message: “This `case` does not have branches for all possibilities.” This is one of the reasons that make Elm so great. The compiler will remind us if we forget something.</p><p>So now the only thing to do is to change from page to page. This is done sending messages to the update function</p><p>Let’s add a menu in the view</p><pre>view : Model -&gt; Html Msg<br>view model =<br>    div []<br>        [ h1 [] [ text &quot;SPA application&quot; ]<br>        , render_menu model<br>        , render_page model<br>        ]</pre><pre>render_menu : Model -&gt; Html Msg<br>render_menu model =<br>    div []<br>        [ button [ onClick GoHome ] [ text &quot;Home&quot; ]<br>        , button [ onClick GoLogin ] [ text &quot;Login&quot; ]<br>        , button [ onClick GoAbout ] [ text &quot;About&quot; ]<br>        ]</pre><p>Here we have added three messages:</p><ul><li>GoHome</li><li>GoLogin</li><li>GoAbout</li></ul><p>so let’s add them to the Msg union type:</p><pre>type Msg<br>    = GoHome<br>    | GoLogin<br>    | GoAbout</pre><p>Each time the buttons are pressed, the update function will receive the messages and will update the model:</p><pre>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        GoHome -&gt;<br>            ( { model | currentPage = Home }, Cmd.none )</pre><pre>        GoLogin -&gt;<br>            ( { model | currentPage = Login }, Cmd.none )</pre><pre>        GoAbout -&gt;<br>            ( { model | currentPage = About }, Cmd.none )</pre><p>At this point, we already have a view that is rendering different content based on the current page defined in the model, but the code could be improved in several ways yet.</p><p>Besides, we need to take care also of the url changes. It’s expected that if we enter the path <em>/app#login</em> in the browser, the app must render the login page. And every time we click the button, the URL should change in the browser accordingly. This will be our next step.</p><p>You can find the code done so far here: <a href="https://github.com/AdrianRibao/elm-spa-example/tree/step1">https://github.com/AdrianRibao/elm-spa-example/tree/step1</a></p><h3>Managing URL changes</h3><p>Now it’s time to manage changes in URL four our SPA. We will be using the Navigation package: <a href="http://package.elm-lang.org/packages/elm-lang/navigation/latest/Navigation">http://package.elm-lang.org/packages/elm-lang/navigation/latest/Navigation</a></p><p>This package allow us to work with URL Locations. Every time the location changes, it will send it to a function, where we have to manage it and return a Msg that will be intercepted in the update function.</p><p>We need to update our main function to use Navigation.program, which takes an extra argument that is the function to be called every time the url changes. Also, the init function now takes the location value so we can set the currentPage based on the location value.</p><pre>main =<br>    Navigation.program locFor<br>        { init = init<br>        , update = update<br>        , view = view<br>        , subscriptions = subscriptions<br>        }</pre><p>Here the locFor function is taking the location and returning a message every time the location changes.</p><pre>locFor : Location -&gt; Msg<br>locFor location =<br>    case location.hash of<br>        &quot;#home&quot; -&gt;<br>            GoHome</pre><pre>        &quot;#login&quot; -&gt;<br>            GoLogin</pre><pre>        &quot;#about&quot; -&gt;<br>            GoAbout</pre><pre>        _ -&gt;<br>            GoHome</pre><p>And let’s update the init function so it sets the currentPage every time we enter the app:</p><pre>init : Location -&gt; ( Model, Cmd Msg )<br>init location =<br>   let<br>        page =<br>            case location.hash of<br>                &quot;#home&quot; -&gt;<br>                    Home</pre><pre>                &quot;#login&quot; -&gt;<br>                    Login</pre><pre>                &quot;#about&quot; -&gt;<br>                    About</pre><pre>                _ -&gt;<br>                    Home<br>   in<br>        ( Model page, Cmd.none )</pre><p>We are repeating a lot of code but we will take care of this later.</p><p>At this point if you are using elm reactor, you can go to any of this URLs the correct page will be rendered:</p><ul><li>http://localhost:8000/main.elm?#home</li><li>http://localhost:8000/main.elm?#login</li><li>http://localhost:8000/main.elm?#about</li></ul><p>So the next step is to update the url when clicking on the buttons.</p><p>First, let’s add a new Msg named <em>LinkTo</em></p><pre>type Msg<br>    = GoHome<br>    | GoLogin<br>    | GoAbout<br>    | LinkTo String</pre><p>and the update function that will take care of this new Msg.</p><pre>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        GoHome -&gt;<br>            ( { model | currentPage = Home }, Cmd.none )</pre><pre>        GoLogin -&gt;<br>            ( { model | currentPage = Login }, Cmd.none )</pre><pre>        GoAbout -&gt;<br>            ( { model | currentPage = About }, Cmd.none )</pre><pre>        LinkTo path -&gt;<br>            ( model, newUrl path )</pre><blockquote>Note: The newUrl function comes from the Navigation Package</blockquote><p>and the view function that will use LinkTo</p><pre>render_menu : Model -&gt; Html Msg<br>render_menu model =<br>    div []<br>        [ button [ onClick (LinkTo &quot;#home&quot;) ] [ text &quot;Home&quot; ]<br>        , button [ onClick (LinkTo &quot;#login&quot;) ] [ text &quot;Login&quot; ]<br>        , button [ onClick (LinkTo &quot;#about&quot;) ] [ text &quot;About&quot; ]<br>        ]</pre><p>That’s it, now the URL is changing on every button click. Great! We can copy the url from the browser, paste it in other browser and the page will be rendered correctly. Thanks to elm, we are sure that all possibilities are managed, and a route that is not managed explicitly in the code will render the Home page.</p><p>You can find the code written so far here: <a href="https://github.com/AdrianRibao/elm-spa-example/tree/step1">https://github.com/AdrianRibao/elm-spa-example/tree/step</a>2</p><p>This works, but we can do it better. We can try to simplify the code and manage parameters in the urls, for example for a path like: <em>/posts/&lt;post_id&gt;/</em></p><h3>Simplify messages</h3><p>The next step is to remove all the GoHome, GoLogin… messages and replace with a single GoTo Message. This way it will be easier to add pages to our application.</p><pre>type Msg<br>    = GoTo Page<br>    | LinkTo String</pre><p>And the update function can be reduced to:</p><pre>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        GoTo page -&gt;<br>            ( { model | currentPage = page }, Cmd.none )</pre><pre>        LinkTo path -&gt;<br>           ( model, newUrl path )</pre><p>and the locFor function is now:</p><pre>locFor : Location -&gt; Msg<br>locFor location =<br>    case location.hash of<br>        &quot;#home&quot; -&gt;<br>            GoTo Home</pre><pre>        &quot;#login&quot; -&gt;<br>            GoTo Login</pre><pre>        &quot;#about&quot; -&gt;<br>            GoTo About</pre><pre>        _ -&gt;<br>            GoTo Home</pre><p>It looks better now.</p><h3>url-parser</h3><p>Now we will be adding the package url-parser to manage routes and it’s parameters. The documentation for url-parser lives in <a href="http://package.elm-lang.org/packages/evancz/url-parser/latest">http://package.elm-lang.org/packages/evancz/url-parser/latest</a></p><p>Let’s define our routes using UrlParser:</p><pre>route : Parser (Page -&gt; a) a<br>route =<br>    oneOf<br>        [ UrlParser.map Home (UrlParser.s &quot;home&quot;)<br>        , UrlParser.map Login (UrlParser.s &quot;login&quot;)<br>        , UrlParser.map About (UrlParser.s &quot;about&quot;)<br>        ]</pre><p>and the locFor function now will be using this route function:</p><pre>locFor : Location -&gt; Msg<br>locFor location =<br>    parseHash route location<br>        |&gt; GoTo</pre><p>There is one more thing we need to do now. The Navigation.parseHash function returns a <em>Maybe Page</em> and we are expecting a <em>Page</em> so let’s manage this new data:</p><pre>type Msg<br>    = GoTo (Maybe Page)<br>    | LinkTo String</pre><p>and of course we need to modify the update function:</p><pre>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        GoTo maybepage -&gt;<br>            case maybepage of<br>                Nothing -&gt;<br>                    ( { model | currentPage = Home }, Cmd.none )</pre><pre>                Just page -&gt;<br>                    ( { model | currentPage = page }, Cmd.none )</pre><pre>        LinkTo path -&gt;<br>            ( model, newUrl path )</pre><p>This is saying that if no route is found it returns Nothing and we will render Home view.</p><p>And the last thing is to update the init function to use the parseHash function:</p><pre>init : Location -&gt; ( Model, Cmd Msg )<br>init location =<br>    let<br>        page =<br>            case parseHash route location of<br>                Nothing -&gt;<br>                    Home</pre><pre>                Just page -&gt;<br>                    page<br>    in<br>        ( Model page, Cmd.none )</pre><p>With this changes, we have removed some duplicated code, and adding pages it’s now easier.</p><p>Here is the code: <a href="https://github.com/AdrianRibao/elm-spa-example/tree/step3">https://github.com/AdrianRibao/elm-spa-example/tree/step3</a></p><p>This has been a long post, but before ending it, I’d like to add another route to the SPA, one that shows posts based on the ids.</p><p>We want to show a Post page and we receive the id of the post we want to render. The Page would be like:</p><pre>type Page<br>    = Home<br>    | Login<br>    | About<br>    | PostShow Int</pre><p>add to the routes:</p><pre>route : Parser (Page -&gt; a) a<br>route =<br>    oneOf<br>        [ UrlParser.map Home (UrlParser.s &quot;home&quot;)<br>        , UrlParser.map Login (UrlParser.s &quot;login&quot;)<br>        , UrlParser.map About (UrlParser.s &quot;about&quot;)<br>        , UrlParser.map PostShow (UrlParser.s &quot;post&quot; &lt;/&gt; int)<br>        ]</pre><p>and if you compile you’ll se Elm asking us to manage this new Page in the view, so let’s do it:</p><pre>render_page : Model -&gt; Html Msg<br>render_page model =<br>    let<br>        page_content =<br>            case model.currentPage of<br>                Home -&gt;<br>                    text &quot;Home&quot;</pre><pre>                Login -&gt;<br>                    text &quot;Login&quot;</pre><pre>                About -&gt;<br>                    text &quot;About&quot;</pre><pre>                PostShow postid -&gt;<br>                    text (&quot;Render the post with id: &quot; ++ toString postid)<br>    in<br>        div [] [ page_content ]</pre><p>Let’s test if it works adding a new button that will take us to post with id 17:</p><pre>render_menu : Model -&gt; Html Msg<br>render_menu model =<br>    div []<br>        [ button [ onClick (LinkTo &quot;#home&quot;) ] [ text &quot;Home&quot; ]<br>        , button [ onClick (LinkTo &quot;#login&quot;) ] [ text &quot;Login&quot; ]<br>        , button [ onClick (LinkTo &quot;#about&quot;) ] [ text &quot;About&quot; ]<br>        , button [ onClick (LinkTo &quot;#post/17&quot;) ] [ text &quot;Go to post 17&quot; ]<br>        ]</pre><p>We can also try to navigate to an url with other ids: <em>/main.elm?#post/9</em> and you’ll see the post_id being shown correctly.</p><p>What happens if we try to access <em>/main.elm?#post/whatever</em> ?</p><p>As expected, elm covers all the options. No runtime errors. This route won’t match any route defined in the <em>route</em> function and will return <em>Nothing </em>which in our case just renders the Home page.</p><p>The final code: <a href="https://github.com/AdrianRibao/elm-spa-example/tree/step4">https://github.com/AdrianRibao/elm-spa-example/tree/step4</a></p><p>Next steps could involve creating a reverse function that returns a location given a certain page, like:</p><pre>urlFor (Post 12)</pre><pre>returns: #posts/12</pre><p>is a simple task but I will leave it as an exercise.</p><p>In this post I described the process that led me to implement SPA app, but as I said, I’m just learning Elm, so comments are welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68d25e0631f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>