<?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 Ryan Stout on Medium]]></title>
        <description><![CDATA[Stories by Ryan Stout on Medium]]></description>
        <link>https://medium.com/@ryanstout?source=rss-a16daa0cf631------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8ySe9H9bB5qa_JDoBdYaFA.jpeg</url>
            <title>Stories by Ryan Stout on Medium</title>
            <link>https://medium.com/@ryanstout?source=rss-a16daa0cf631------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:52:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryanstout/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[Training A Self Driving (Toy) Car]]></title>
            <link>https://medium.com/@ryanstout/training-a-self-driving-toy-car-05f42016817f?source=rss-a16daa0cf631------2</link>
            <guid isPermaLink="false">https://medium.com/p/05f42016817f</guid>
            <category><![CDATA[self-driving]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[stem]]></category>
            <category><![CDATA[mls]]></category>
            <dc:creator><![CDATA[Ryan Stout]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 01:08:18 GMT</pubDate>
            <atom:updated>2024-11-22T01:08:18.812Z</atom:updated>
            <content:encoded><![CDATA[<p>Last year, I was asked to help with the STEM club at <a href="https://www.jpthegreatdenver.org/">St John Paul the Great Catholic High School</a>. After discussion some options, the students decided they wanted to build a self driving car. It was a fun challenge for me to turn that into a project we could actually accomplish in a semester.</p><p>We ended up with a small car (with parts off of amazon) that used a webcam to navigate. You put down masking tape road lines and it stays between them.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2U398bKXbsI&amp;type=text%2Fhtml&amp;schema=youtube&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2U398bKXbsI%3Ffeature%3Doembed" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/560552333e5158a89e166c5a668b972a/href">https://medium.com/media/560552333e5158a89e166c5a668b972a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7RbWy35Cs1U&amp;type=text%2Fhtml&amp;schema=youtube&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7RbWy35Cs1U%3Ffeature%3Doembed" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/97246570af2ea0ade434a4f26b4bd392/href">https://medium.com/media/97246570af2ea0ade434a4f26b4bd392/href</a></iframe><p>The car does a great job of stays in the lanes. This was a fun project that the students seemed really excited about.</p><p>Due to limited time, we had to gloss over quite a few details, but I think this did a good job of getting them excited about computer science, engineering, and AI. There were lots of “where do I learn more” questions.</p><h3>How It Works</h3><p>MicroPilot takes in frames from an off the shelf webcam and predicts the steering angle.</p><p>We created a course by putting down masking tape for lanes. The goal was to get the car to follow the track and stay in the lanes using only the webcam footage as input.</p><p>It’s probably possible to run these models on the Pi itself (especially the Pi5), but since there’s no cooling in our setup, the Pi gets thermal throttled quite a bit. I found it easier to just connect the Pi to the Wifi, then record to and run inference on my machine. (Sending frames over a TCP connection)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qo24D2zV0oyzfX2N_fo--g.png" /></figure><p>To train the car, you attach a USB Joystick and drive the course. When the left upper button is held down, it records frames from the webcam and the steering angle of the joystick. The goal is to get a few types of training data:</p><p>- Footage driving the center of the track<br>- Footage of the car correcting when its pointing the wrong way. (So make the car face more towards the tape, then point the wheels hard in the correcting direction and start recording you correcting it back to the center) Also have the car slightly go over the lane and record data of it correcting back into the lane.</p><p>All recorded data should be with the wheels pointing in the direction you would use to correct the car back to the center. So let off the record button when you position the car closer to the edges.</p><p>The trick is also to make sure the wheel direction changes smoothly. It can be tempting to drive by toggling between strong adjustments and straight. For good training data, you’ll need to make your steering adjustments smooth. As you get closer to the edge, make your adjustments strong back towards the center of the lane. The training data should convey that when you’re in the middle you need little adjustments and as you get closer to the tape you need stronger adjustments.</p><p>Once we collected training data, we built a model that uses the features from a pretrained Vision Transformer (Vit). The features from the Vit are fed into a small model that uses a series of Linear layers to predict the steering angle. Finally a Tanh layer constraints the output to between -1 and 1.</p><h3>The Hardware</h3><p>Originally I had hoped we could build a car from scratch and 3d print a chassis, but as the semester went by, I realized time constraints meant we needed something that would work so we could focus more on the software/AI side. This project should work on any hardware, but v1 was built with a RaspberryPi 5, an off the shelf webcam and a kit I found on amazon for the car, motors, etc..</p><p>- <a href="https://www.amazon.com/Raspberry-Model-2019-Quad-Bluetooth">Raspberry Pi</a> — We used a Pi5, originally thinking we would run the model on the car. Any Pi should work with the way we ended up doing it. Also, I went with the Pi because I figured the drivers and packages would be easy to install, but I actually feel like RaspberryPiOS makes things harder not easier. I ended up turning off their managed pip package thing. (This might be a debian thing now?)</p><p>- <a href="https://www.amazon.com/gp/product/B0CGLPF29H/">SunFounder Smart Kit</a> — A car kit with most everything you need. While this makes it easy to get started with, the car itself is very slow and the steering has a lot of play in it and top speed is ridiculously slow. Were I to start over I would explore other options or building something DIY.</p><p>- <a href="https://www.amazon.com/gp/product/B0092QJRPC/">Any Random Webcam</a> — Any webcam that linux supports should be fine.</p><p><a href="https://www.amazon.com/gp/product/B003VAHYQY/">Game Controller</a> — For driving the car while training it.</p><h3>Conclusion</h3><p>If you’re interested in repeating our project, everything is up on <a href="https://github.com/ryanstout/micropilot/">github</a>. Sony of the students had some familiarity with python, which helped, but it’s a still a lot to cover in a short period of time. With that said, the students walked away with an interest in AI and software development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtqP93T6msrsNY2iRA-13Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05f42016817f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Camper Van Air Quality and What to Do About It]]></title>
            <link>https://medium.com/@ryanstout/camper-van-air-quality-and-what-to-do-about-it-2cf6ab8ff4f9?source=rss-a16daa0cf631------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf6ab8ff4f9</guid>
            <category><![CDATA[air-quality]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[campervan]]></category>
            <dc:creator><![CDATA[Ryan Stout]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 00:24:38 GMT</pubDate>
            <atom:updated>2024-02-28T00:24:38.825Z</atom:updated>
            <content:encoded><![CDATA[<p>A few years ago I read about how indoor air quality affects productivity. (Specifically CO2 levels). I’ve heard a lot of claims about what affects productivity, but after digging in, most of the studies seemed to be have good sample sizes and testing methodologies. So I bought an <a href="https://www.getawair.com/">air quality monitor</a> and was off to the races.</p><p>Never one to rule out the placebo effect, I did notice that my productivity seemed to slow when the CO2 level got above 1,000. My home office at the time was very sealed and would get to 1500ppm, especially when working out in the same room. Opening a window corrects the problem.</p><h3>The Van</h3><p>My camper van gets quite a bit of use. Being the founder/CEO of a <a href="https://witharsenal.com/">camera accessory company</a>, myself, our videographer, and our still photographer would often do road trips to field test and film marketing material. Consistently I would wake up with headaches. In hindsight the reason was fairly obvious, but for some reason I thought it was dehydration. Once I realized it was CO2, we started leaving the ceiling fan open and partially on at night, which solved the problem.</p><p>This however created another problem. When it’s cold, we run the van’s diesel furnace for heat. The furnace is more than capable of keeping the van warm, even with the fan constantly bringing in cold air. The problem is when there is a lack of wind outside, the fumes from the diesel furnace get pulled back into the van. (Raising the VOC and particulate counts on my air meter, and generally not being great for health)</p><p>I installed a 2nd MaxxAir fan so I could pull air in through the roof and also vent it through the roof. This helped, but still let the fumes in when the outside conditions were right.</p><h3>Solving the Problem</h3><p>Last month I set out to solve the problem once and for all. The fan doesn’t need to be open all of the time. A good air flush once an hour is usually fine. Though it depends on how many people are in the van and the outside wind. Vehicles aren’t designed to be air tight (you don’t want them to be.)</p><p>Using some Arduino compatible micro controller, I designed a mix of a thermostat and a CO2 monitor. Both MaxxAir fans in my van have an IR receiver (and an IR remote) that can be used to open/close the fan, or set auto open/close temperature settings, fan speed, etc.. I wired up an IR receiver to the board and tried to record the remote to learn how to control the fan over IR.</p><p>It took a few IR libraries and some reverse engineering before I was able to decode the signals. The <a href="https://github.com/Arduino-IRremote/Arduino-IRremote">Arduino IRRemote library</a> and some raw decoding of long signals was able to do the trick. I wired up an LED and now could open and close the fan. The fan’s remote sends all state from the remote in a sequence each time you press a button. So pushing temperature up or down will also pass the fan speed, etc..</p><p>I used the SparkFun SCD40 as a CO2 sensor. It worked great and was fairly easy to get up and running. Finally I hooked up a Adafruit MCP9808 for temperature sensing and was off to the races.</p><h3>Building a Thermostat</h3><p>One unique challenge of a van is that if it’s windy, the heater will constantly cycle on and off. Most off the shelf thermostats have a total of 2 degree (or less) of hysteresis. This is fine for a house, but in a van the heat can kick back on 10 minutes after it kicks off. Also, I’ve managed to make my diesel furnace fairly quite with some mufflers, but it’s still disturbs me while sleeping a bit.</p><p>So since I was building a thermostat also, I decided to up the hysteresis so the furnace kicked on less. This would mean the temperature would swing a bit more, but that’s better than it cycling too often.</p><p>The algorithm was pretty simple, if the temperature dropped more than 2 degrees below the set point, it called for heat until it reached 2 degrees above the set point. If the fan was open when the thermostat called for heat, it would close the fan, then turn on the heat. If the CO2 passed a set point, it would open the fan, and close it once CO2 dropped enough.</p><p>Pretty simple. And it worked well.</p><p>I added a 7 segment display to show the temperature, set point, and CO2 level and was off to the races.</p><h3>Making it Pretty</h3><p>Version 1 was built on a breadboard. I stuck the breadboard to the wall and wired it up. In my head I was done, it worked. My wife quickly pointed out however that it looked like someone had wired the van to blow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PzUxqsRopGfTi6SC8UTIeg.jpeg" /><figcaption>Yea, it looks sketchy when you see it through the window.</figcaption></figure><p>I also was confident the breadboard wouldn’t hold the connections when I was bouncing down the road. So I moved everything to perfboard and QUIK connectors. Then I designed a simple enclosure in Fusion 360 (great program imho) and 3d printed it. The result was a little bit easier to look at and less concerning to an outsider.</p><p>It had been a few years since I used Arduino, and I had spent part of 2022 writing low level C code for an automotive microcontroller. (With terrible documentation), so I was amazed at how fast everything came together. ChatGPT was able to write a lot of the code to read out the temperature and CO2 with almost no changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*w9eMkF7ipEww4TEO1RWe9A.jpeg" /></figure><p>I’ve released the source, part list, and STL files for a very basic enclosure <a href="https://github.com/ryanstout/co2thermostat">here</a>. Hit me up if you need any help wiring it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf6ab8ff4f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firmware Updates that Don’t Suck]]></title>
            <link>https://medium.com/better-programming/firmware-updates-that-dont-suck-6edd84b10597?source=rss-a16daa0cf631------2</link>
            <guid isPermaLink="false">https://medium.com/p/6edd84b10597</guid>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[customer-experience]]></category>
            <category><![CDATA[developer-tools]]></category>
            <dc:creator><![CDATA[Ryan Stout]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 19:34:24 GMT</pubDate>
            <atom:updated>2023-08-31T16:36:53.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Firmware Updates That Don’t Suck</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*007E0CG7ZzpjgRrO7jtVUw.gif" /><figcaption>Our Arsenal 2 Firmware Update. Less than 1 minute, 30 seconds “door to door”</figcaption></figure><p>Since 2017, we’ve shipped over 250,000 Arsenals (an AI photography assistant for DSLR/mirrorless cameras).</p><p>Being a small company, we didn’t have the customer support resources to walk users through the update process. Updates need to work, be fast, and be 100% resilient. Here’s everything we did to get there and some tips for anyone trying to do the same.</p><h3>Arsenal 1</h3><p>When building Arsenal 1, we time-boxed the firmware update “feature.”</p><p>We had so many things to do, we had to be OK with good enough. Spoiler: It wasn’t until Arsenal 2 that we had the time to get everything right.</p><h4>What we needed</h4><p>I did a lot of research in 2017, and there weren’t any good off-the-shelf solutions that met our requirements. Our perfect update system needed the following:</p><ol><li>designed for Linux, not microcontrollers (Arsenal runs Linux on an arm processor)</li><li>fault-tolerant. No way to brick a unit (surprisingly, not something most off-the-shelf solutions provided)</li><li>updated over Wi-Fi (from our mobile app)</li><li>minimal disk overhead (no duplicates of the whole firmware image)</li><li>fast updates</li></ol><h4>A lesson in what not to do</h4><p>The camera industry is a classic example of terrible update experiences. Most cameras require you to navigate a website, find your camera model, download a firmware binary, put it in a specific path on the SD card, insert the SD card in the camera, and then update through the camera menu. It’s a struggle for the user, but to be fair, it is simple to engineer and seems resilient.</p><p>Sony is probably the worst example of bad updates. Instead of the SD card workflow, most cameras require you to install a custom driver and kernel extension (yes, you read that right) on your Mac/PC to talk to the camera over USB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*eWrs_Gka0Igh_u1JrAlepA.png" /><figcaption>Call me crazy, but I don’t think firmware updates should need a ten-minute tutorial</figcaption></figure><p>With Arsenal, we wanted to raise the bar.</p><h4>Arsenal 1 firmware build</h4><p>We were <a href="https://www.kickstarter.com/projects/2092430307/arsenal-the-intelligent-camera-assistant-0">racing against a deadline</a> to ship Arsenal 1, so moving fast was the top priority. Our embedded/Linux engineer and I brainstormed a few options to implement a more production firmware build process.</p><p>For Arsenal 1, we created a simple build process based on Arch Linux and bash scripts.</p><figure><img alt="hideous star wars character smiling. caption: now witness the power of this fully operational bash script" src="https://cdn-images-1.medium.com/max/600/0*aB0EowWV10e2puhg.png" /></figure><p>Our build process involved the following:</p><ul><li>configure and build our Linux kernel and drivers</li><li>install a stock Arch image on the board — along with our custom kernel and drivers</li><li>install our dependencies with pacman and gcc</li><li>remove the build-related dependencies</li><li>copy our software to the disk</li><li>image and compress the disk image (The firmware image was just a tar of our disk image)</li></ul><p>The whole thing was glued together with bash scripts. Not the most elegant, but it worked. And more importantly, we got it built quickly.</p><h4>Disk overhead and operation never brick</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*d9eoI_7vCO2JunyQ0Yskjw.jpeg" /></figure><p>Embedded firmware images are usually really small, so a common technique is to have two partitions on the disk. You write the new image to one partition, then flip to it after a successful update. If something goes wrong, you don’t flip.</p><p>Our firmware images were huge, so we had no disk space for two copies of everything. Instead, we created a minimal image (using openembedded) that only had the firmware updater, USB/wifi drivers, and an HTTP server to upload to. We called this the “recovery image.”</p><p>“Recovery” sat on a small partition at the start of the disk. After that, there was the root partition for the main firmware image and then a user partition for all user data.</p><p>We made the recovery image and root partitions read-only so things like overflowing log files wouldn’t cause boot issues. Storing all user data (in our case, image caches) on the user partition meant a full user disk wouldn’t affect the actual boot, and our device code could clear the cache on boot even if we coded something wrong. (Which I assure you never happened, not even once.)</p><p>This kind of defensive design saved us a few times. Just assume you will screw something up at some point and try to design a firmware update process that can handle some screw-ups.</p><p><strong>Handling screw-ups</strong></p><p>Even with the precautions on the main firmware/root partition, I knew mistakes would be made. So, we needed to be able to handle a failed start on the root partition. Either from a <a href="https://tekhead.it/blog/2016/06/data-corruption-the-silent-killer/">bad disk write, corrupted bits</a>, or the software getting into a bad state (from a bug), we needed failed boots of the root partition to be recoverable.</p><h4>Automatic failover</h4><p>The recovery image was very small and targeted, so we decided if something went wrong with the root firmware boot, we would fail over to the recovery partition. From there, you could reupload the firmware image and be on your way again. To be safe, recovery updates clear the user partition, but Arsenal has very little on-device state, so for users, it’s not an issue.</p><p>You might wonder how you can be sure the device will flip over to recovery if something like a bad disk write happens. This is where hardware watchdogs come in. The hardware watchdogs are set up by <a href="https://en.wikipedia.org/wiki/Das_U-Boot">uboot</a>.</p><p>After the root partition boots (takes about six seconds to boot), our software has 30 seconds to disable the watchdog. If the watchdog isn’t disabled in 30 seconds, the unit will reboot. After three failed boots, it kicks over to recovery. (Check your processor’s data sheet for details on how to set up these watchdogs.)</p><p>Simple but effective. From the mobile app, we can treat recovery updates like normal updates.</p><p>The important thing with hardware watchdogs is that they are implemented in hardware (funny how that works). No amount of software mistakes (except accidentally disabling the watchdog) will prevent the reboot. Only the happy path, in our case, prevents Arsenal from entering recovery.</p><h4>Recovering recovery</h4><p>OK, so what happens if the recovery image gets corrupted? Our recovery image is about 10 MB, so we just did the obvious thing and added a second copy of the recovery image, again with a watchdog to failover and boot the second image. These images are actually files on the recovery partition, which uboot mounts as a read-only file system.</p><p>I don’t have any metrics on how many times having the second copy of recovery has saved us. Data on the <a href="https://dl.acm.org/doi/10.1145/1555349.1555372">frequency of cosmic ray-induced bit-flips</a> and some napkin math says it has happened. We have yet to get back a unit that wouldn’t boot into recovery.</p><h4>Version locking</h4><p>As a user, you mostly access Arsenal via a mobile app. To simplify things, I decided early that the mobile app should only connect if the device firmware version matched the mobile app version. (Otherwise, you go from a single app/device version that needs to be tested to a matrix of version combinations to test.)</p><p>On Arsenal 1, when the mobile app updated (which happens automatically on phones), the mobile app would see the versions didn’t match and require you to download and install the firmware update to continue. The process was fairly smooth, though automatically disconnecting and reconnecting wifi required a ton of debugging work and Wi-Fi driver fixes (especially to deal with Android)</p><p><em>ASIDE — HERE BE DRAGONS: Even today, Android’s Wi-Fi stacks are up to the phone manufacturer, and the quality of drivers and even implementation of the core Android Wi-Fi APIs are very poor. If you need automatic Wi-Fi connections to an Android device, be prepared for a lot of pain as you purchase and debug issues with how your Wi-Fi chips’ drivers communicate to any of the 30,000+ unique Android phones.</em></p><h4>The missing requirements</h4><p>Arsenal 1’s firmware update process had a huge flaw you may have already seen. If your mobile app updated (as happens in the background), and you weren’t on the internet when you opened the new version, you couldn’t download the firmware and connect.</p><p>Our firmware images were 500 MB, so you needed a good internet connection and a free data plan. Even if you were on Wi-Fi or had cell service, waiting for the update to download while the good light was fading made for unhappy users. (DJI and GoPro had the same issue in their apps then.)</p><p>This was a much harder problem to fix than you might think. In a perfect world, we would have blocked automatic app updates for our app, but that’s not an option.</p><p>For Arsenal 2, we added two more requirements for our firmware updater.</p><ol><li>either have offline update support or allow non-matched version connections</li><li>updates in less than two minutes, start to finish (“door to door,” as we call it, which is the time from pressing update until you’re connected to the updated Arsenal)</li></ol><h3>Arsenal 2</h3><h4>Offline updates</h4><p>The &lt; two-minute update requirement seemed like an impossible hurdle. Arsenal 1 updates took about eight minutes. (ugh) To get to &lt;2, we would need to rebuild every part of the system, but we’ll come back to that.</p><p>First, we debated if we could somehow handle the testing of unmatched mobile and device code versions. We thought about only supporting connections from five versions back, then requiring an update if it was older. This would still mean 5² = 25 combinations to test on each release. (And multiply that by the 100+ cameras we support.) QA already took weeks, so I nixed that idea pretty quickly.</p><p>Our only option was embedding the firmware in the app itself. When we built Arsenal 1, the amount of available storage on phones (especially iPhones) was really limited. Users told us a 550 MB app was a non-starter. So, we opted to download the firmware image when you needed it.</p><p>A lot had changed by Arsenal 2 (2020). I checked my phone; I had four apps, all taking up more than 500 MB. I had honestly never noticed. Users were still telling me that 500 MB was too big, but I decided to try embedding the firmware and see how many complaints we got.</p><p>Our #1 complaint on Arsenal 1 was blocked connections when a firmware update was needed, and you were offline, so we didn’t have a ton to lose.</p><h4>Shrinking the firmware</h4><p>I never liked the firmware build process for Arsenal 1. I had managed to integrate it into our CI pipeline, but it ran on a physical unit that booted into a DFU-type mode. We needed to send a special sequence to a pin on the board to get it into the DFU mode, so we wired an FTDI controller to the pin and flipped its GPIO pin to send the sequence. (#hacky)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6S0Pjuqx6N20QIa8K2B_Gg.jpeg" /><figcaption>Very professional, but hey, it worked</figcaption></figure><p>For Arsenal 2, firmware/software builds needed to be:</p><ol><li>faster (Arsenal 1 builds took hours)</li><li>repeatable (Arsenal 1 builds were downloading things from pacman and GitHub during the build. Not good)</li><li>more compact. The Arsenal 1 image was 500 MB. About 250 MB of that was machine learning models. The rest mainly was Arch Linux and the rest of the binary dependencies.</li></ol><p>Our Linux/embedded engineer had worked with <a href="https://www.yoctoproject.org/">yocto</a> and <a href="https://www.openembedded.org/wiki/Main_Page">openembedded</a> before. These projects let you build a custom Linux distribution with exactly what you need (and nothing you don’t.) They can even strip out unused symbols from binaries and do some other space optimization tricks.</p><p>They are really powerful, but not for the faint of heart. If it had just been me, I would opt for something like <a href="https://buildroot.org/">buildroot</a>. The great thing about these projects is that they cross-compile every package, so you can run the build (in parallel) on a large machine. My physically massive — 64-core, 256 GB machine learning machine would do fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*xDAJzurlvdZAk1US4ne62A.jpeg" /><figcaption>At one point, we had five RTX 3090s in this thing</figcaption></figure><blockquote>Also, my favorite thing about openembedded is that there’s some container/chroot jail type stuff that happens during the build, and inside of that is a fake sudo type command that’s named pseudo Best name ever.</blockquote><p>It took our embedded engineer a few months to get everything moved over, but once we did, we ended up with a firmware image that was &lt;50 MB with all of our dependencies. A 5x space savings. Not bad. There was still an additional 250 MB for the machine learning models. The smaller image made for a 2x faster boot. And lastly, openembedded brought our build time down to about ten minutes.</p><h4>Compressing the hell out of it</h4><p>The challenge with Arsenal 2 was that we had both a Standard and a Pro version. The Pro version ran a different Arm architecture than Standard, so we must embed both firmware images into the mobile app.</p><p>We were looking at about 300 MB per firmware image with gzip compression.</p><p><strong>Faster install times</strong></p><p>The 300 MB of firmware image would upload in about 45 seconds, giving us one minute 30 seconds to install the firmware and reboot. With gzip compression, the install time was … five minutes. I benchmarked the disk and figured out the bottleneck was decompression performance. Moving to parallel gzip decoding improved things, but not enough.</p><p>I spent a day building a script to test every compression format I thought might work well on our hardware. (I tried gzip, bzip, deflate, snappy, zstd, and blosc.)</p><p>The TL;DR is <a href="https://github.com/facebook/zstd">zstd</a> won. The compression times were much longer, but all that mattered for us was the decompression times and compression ratio. Zstd’s decompression uses SIMD instructions on ARM, and decompression time doesn’t increase as the compression level goes up.</p><p>Zstd took our 300 MB image with light gzip compression to a 220 MB image with very high zstd compression.</p><p>The smaller image and parallel decoding reduced our install time to one minute, and the smaller image shaved the upload time down to about 30 seconds. Disabling TCP-slow start for the firmware upload connection got it the rest of the way.</p><p>After months of work, we had a firmware update that took 1 minute 30 seconds from when you push the update button to when you’re reconnected on the new version.</p><h4>The moment of truth</h4><p>We had sent out a few hundred Arsenal 2s to some early testers. The first version had the old Arsenal 1 installer. We pushed the new app version with the new installer when it was ready. Then we waited…</p><p>I knew that embedding the firmware was our best option, so I was ready to defend why we had to make the app 500 MB.</p><p>The messages started coming in, but not the messages I thought. It was all positive feedback about how fast the update process was. To this day, the number of complaints about app size is less than 10. (I’m not sure this would have been the case in 2017, but since the app downloads in the background, most people never even look at the size.)</p><h3>Summary</h3><p>Firmware updates are a seldom discussed area of building hardware products. The quality of your update process can have a huge impact on how your product is received. Here’s what worked for us:</p><ol><li>openembedded for building firmware/disk images</li><li>zstd for fast decoding and high compression on ARM hardware</li><li>embed the images into the mobile app</li><li>recovery images and hardware watchdogs for safety</li></ol><p>If you’re about to build or integrate an existing firmware update solution, I advise you to allocate enough dev time. Firmware updates can seem like something easy from the outside, but once you dive in, there’s complexity hiding under every corner.</p><p>Be sure to program defensively and make sure your system can handle shipping a main image that will fail to boot under some conditions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6edd84b10597" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/firmware-updates-that-dont-suck-6edd84b10597">Firmware Updates that Don’t Suck</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>