Exploring the Internet of WebAssembly Things
local graph
Chapter 7 — Exploring the Internet of WebAssembly Things
Section titled “Chapter 7 — Exploring the Internet of WebAssembly Things”CHAPTER 7
Exploring the Internet of WebAssembly Things
The Internet of Things (IoT) is now as ubiquitous as the Internet itself. Some people see this as a tremendous opportunity for growth and innovation while others are terrified of an impending future dominated by millions of woefully underprotected, overconnected devices.
Today we have smart watches, refrigerators, toasters, doorbells, clothing, and thousands of other things that attach the real world to the digital world of the Internet. Infrastructure companies want to sell us platforms to support our IoT applications, security companies want to help us secure our smart devices, and the maker community is constantly expanding and building open source, connected hardware. IoT represents a nearly infinite number of ways to spend and earn money, so it’s no wonder it has inspired so much innovation.
As you’ve come to learn on your journey through this book, WebAssembly is about far more than just speeding up web applications. Its portable, compact format makes it ideal for systems under heavy disk, memory, and processing constraints. It’s ideal for isolating business logic from presentation and, as you’ll see in this chapter, from external, physical devices.
In this chapter, you’ll take advantage of WebAssembly’s portability and the Raspberry Pi’s easy access to hardware systems to build a pluggable host that separates the logic of determining what to display on a hardware indicator from the how of displaying it. The LED and computer parts for this chapter’s hardware are inexpensive, but even if you don’t have a Raspberry Pi, you’ll see how you can write and test code for hardware in isolation all from the comfort of your own workstation.
This chapter will operate on, and prove, the following two assumptions:
-
If a WebAssembly module can be hosted in a web browser or a console application, you can host it on a Raspberry Pi
-
If two WebAssembly modules adhere to the same contract, they can be interchanged like modular plugins
Before we start coding, let’s take a tour of a use case illustrating the problem we want to solve.
Overview of the Generic Indicator Module
Let’s assume that we’ve been tasked with designing and building part of an IoT project. This project is to build an autonomous wheeled robot that maneuvers its way through an obstacle course as they do in many robotics competitions.
Since we’re working as part of a team and there are hundreds of individual pieces on this robot, we’ve been tasked with handling the Generic Indicator Module System. Since all hardware projects need acronyms, we’ll call this one GIMS. Bonus points for a four-letter acronym, as that puts us just that tiny bit closer to feeling like NASA.
The robot will process multiple streams of sensor inputs from many different devices. GIMS’s job is to allow the sensory input to be fed into a WebAssembly module that can then determine how the current state of some aspect of the robot should be visualized. We might have access to gauges, multi-colored LEDs, headlights that could turn on when it’s dark—any number of amazing devices.
In some cases, the sensory input might already have been massaged a little bit by the more accurate timing of microcontrollers, while our GIMS will be running on a Raspberry Pi at the very heart of a robot. In this chapter, to keep from writing an entire new book on robotics and WebAssembly, we’ll focus solely on the generic indicator system.
The robotics team leadership has built these types of competition robots before, and they know the pain and true price of the integration cost when they have to go back into their code and fuss with tiny details every time they change a piece of hardware. If you haven’t played with microcontrollers, “maker kits,” or Raspberry Pis, you might assume that LEDs are just LEDs—you control one the same way you control another. The truth is far more annoying.
The reality is that you can go from the simplest LED (apply current, it lights up, magic!) to chains of multicolor LEDs that operate with simple timing sequences to systems that use very specific communications protocols like I2C.¹ Changing your peripherals mid-build can be a “stop the world” event, but we can engineer our way around that with a little help from WebAssembly.
With the GIMS design, we’ll be putting the indicator logic—which translates a series of sensor inputs into a series of hardware manipulation commands—into WebAssembly. This way, the indicator logic remains isolated and loosely coupled from the physical indicator(s). If someone changes an LED from a simple light-and-resistor to a brick of 200 “LED pixels,” they should be able to make a small change to an interface layer and leave our indicator relatively unbothered.
In short, we’re taking the software engineering principles of loose coupling and separation of concerns and, with the power of WebAssembly, bringing them to the world of consumer-grade electronics. The first thing we’re going to need to do in order to make that happen is design the contract between the host and the WebAssembly modules.
Designing the Module Contract
As you saw in the chapter on basic JavaScript integration, the contract between a WebAssembly module and its host is a very basic, low-level contract built from numeric primitives. That contract defines how linear memory is accessed, how parameter values can be passed to functions, how we can invoke functions exported from a module, and within the module, invoke functions imported from the host.
Above these low-level bindings, what we need is an API. We need an API that lets the host invoke functions whenever there are new sensor readings available. This API also needs to let the WebAssembly module control the indicator lights. We could even let WebAssembly modules control more hardware like motors and actuators, but that’s outside the scope of our GIMS project (though it certainly could be a lot of fun to explore).
First let’s think about sensor inputs. I’m sure in real-world circumstances, our sensors would have all different kinds of outputs, and some might have more than one value. But knowing that we’re doing this for the Raspberry Pi, and that other microcontrollers closer to the data might be able to massage it for us, it’s safe to assume that we’ll be able to get a decimal value from each
[1] i2c.info learn.sparkfun.com/tutorials/i2c sensor whenever a value changes. So our host is going to want to call a function like the one below to inform our wasm module of a new data point:
fn sensor_update(sensor_id: i32, sensor_value: f64) -> f64;Let’s say the motor speed is sensor 1, the ambient light detector is sensor 2, the collision detector is sensor 3, the battery of our main laser cannon is 20, etc. We’ll have to maintain the Rust-equivalent of a header file so that we can ensure all our modules are operating on the same list of sensors. If the team disagrees on sensor IDs, we’re basically back at square 1 and haven’t fixed any problems.
Another function we want the host to be able to call is apply(). If we need to animate or update our display over time, we could probably attempt some kind of intricate threading scheme to run each module, but it’s far easier to use the “game loop” model and just invoke something like apply() n times per second. We might be able to do fancier things when threading becomes a part of a future version of the WebAssembly specification, but this is good enough for our needs today.
To let the modules know about the passage of time, we can, however, invoke the same function at fixed intervals and pass a frame value that increases for each call. We can either agree on a frame rate for updates or write our code so it doesn’t really matter:
fn apply(frame: i64);For example, an animated indicator might have apply called 20 times per second.
That’s it for the input to our modules. Now we need to give the WebAssembly modules a way to control hardware without tightly coupling them to it. For this, we’ll abstract over the notion of setting the color of an individual LED with a function that takes an LED index and 3 RGB values between 0 and 255, like so:
fn set_led(led_index: i32, r: i32, g: i32, b: i32);If you think back to the fundamentals chapter, recall that while we’re allowed to use plenty of data types privately within the module code, we can’t import and export higher-level data types like structs. Let’s recap and take a look at the three functions in the GIMS API contract (import and export are from the point of view of the WebAssembly module) as shown in the table on page 135.
Now that we’ve got a preliminary contract defined between our hardware host and the wasm modules, we can create a couple of different indicators.
| Name | Direction | Params | Returns |
|---|---|---|---|
| apply() | export | • frame | None |
| sensor_update() | export | • sensor_id | Value |
| • sensor_value | |||
| set_led() | import | • led_index | None |
| • red | |||
| • green | |||
| • blue |
Creating Indicator Modules
Creating an indicator module is really just a matter of creating a regular Rust-based WebAssembly module that adheres to the contract we’ve defined. You’ve seen how to create wasm modules using Rust a number of times throughout this book, so it should be easy to get started.
To start, create a root directory that will hold a battery indicator, an animated indicator, and the host application. I chose to call my directory gims, but you can choose whatever you like. As a convenience, to allow you to run builds and tests on all subdirectories at once, you can create a new Cargo.toml in the gims directory with the following contents:
iot_gims/Cargo.toml
[workspace]members = [ "animatedindicator", "batteryindicator", "pihost"]Use cargo new —lib to create the batteryindicator and animatedindicator projects, and cargo new —bin to create the pihost project.
Creating the Battery Indicator
The first indicator module we’re going to build is a battery indicator. Its operation is fairly simple: one of the sensor inputs represents the amount of battery remaining as a percentage. In response to that percentage, we’re going to control the color of a group of eight LEDs.
These LED indicators are each capable of lighting up with colors comprised of RGB components ranging from 0 through 255. The actual hardware used will be a Blinkt! module from Pimoroni, and I’ll include all the details later in case you want to go shopping for your own kits.
Its core logic will be to convert a number from 0-100 into an eight-element array with each element containing an RGB color value—think of it like an LED-based progress bar. For this indicator, we’ll divide the percentages among the LEDs and only light them up if the value is >= the base value for that LED. Figuring out the base value for each LED is simple—divide the eight LEDs by 100 and we get 12.5% per LED.
Update your lib.rs with the following code:
iot_gims/batteryindicator/src/lib.rs#[derive(PartialEq, Debug, Clone)]struct LedColor(i32, i32, i32);
const SENSOR_BATTERY: i32 = 20;
const OFF: LedColor = LedColor(0, 0, 0);const YELLOW: LedColor = LedColor(255, 255, 0);const GREEN: LedColor = LedColor(0, 255, 0);const RED: LedColor = LedColor(255, 0, 0);const PCT_PER_PIXEL: f64 = 12.5_f64;
extern "C" { fn set_led(led_index: i32, r: i32, g: i32, b: i32);}
#[no_mangle]pub extern "C" fn sensor_update(sensor_id: i32, sensor_value: f64) -> f64 { if sensor_id == SENSOR_BATTERY { set_leds(get_led_values(sensor_value)); } sensor_value}
#[no_mangle]pub extern "C" fn apply(_frame: u32) { // NO OP, not an animated indicator}
fn get_led_values(battery_remaining: f64) -> [LedColor; 8] { let mut arr: [LedColor; 8] = [OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF,]; let lit = (battery_remaining / PCT_PER_PIXEL).ceil();
// 0 - 20 : Red // 21 - <50 : Yellow // 51 - 100 : Green
let color = if 0.0 <= battery_remaining && battery_remaining <= 20.0 { RED }} else if battery_remaining > 20.0 && battery_remaining < 50.0 { YELLOW} else { GREEN};for idx in 0..lit as usize { arr[idx] = color.clone();}arr}fn set_leds(values: [LedColor; 8]) { for x in 0..8 { let LedColor(r, g, b) = values[x]; unsafe { set_led(x as i32, r,g,b); } }}- Create a tuple-struct to hold the three-color codes
- Import the set_led() function from our host
- Expose the sensor_update() and apply() functions to the host
- Core logic to convert a percentage into a set of eight color codes
- Invoke the unsafe import in a loop to set all the LED colors on the host
With this code in place, we’re going to want to test our module before we plug it into real hardware.
Testing the Battery Indicator
Testing hardware and embedded systems is typically one of the hardest aspects of that kind of development. Pure hardware developers might want to just pull out an oscilloscope and take a look at how the current flows through your system, but this doesn’t help us test our business logic (though it could help integration test the host).
Fortunately for us, we don’t need to physically test the LEDs right now. We can assume that the host works and write unit tests for our business logic that determines which LEDs to light up and what colors to display.
This is where the pluggable modularity of WebAssembly modules starts to truly shine in the embedded and IoT space—finally giving us software developers a way to write unit tests for hardware-bound code without having to rig up elaborate Rube Goldberg machinery to our developer workstations.
This test code (at the bottom of lib.rs) just invokes the get_led_values() function for some known percentages and ensures that we get the right color array in response:
iot_gims/batteryindicator/src/lib.rs
#[cfg(test)]mod tests { use {OFF, YELLOW, RED, GREEN, get_led_values}; #[test] fn test_0_pct() { assert_eq!(get_led_values(0.0), [OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, ]); }
#[test] fn test_15_pct() { assert_eq!(get_led_values(15.0), [RED, RED, OFF, OFF, OFF, OFF, OFF, OFF]); }
#[test] fn test_49_pct() { assert_eq!(get_led_values(49.0), [YELLOW, YELLOW, YELLOW, YELLOW, OFF, OFF, OFF, OFF]); }
#[test] fn test_75_pct() { assert_eq!(get_led_values(75.0), [GREEN, GREEN, GREEN, GREEN, GREEN, OFF, OFF, ]); }
#[test] fn test_100_pct() { assert_eq!(get_led_values(100.0), [GREEN, GREEN, GREEN, GREEN, GREEN, GREEN, GREEN, ]); }}You should be able to run cargo test from the root gims directory, and your tests should be invoked, showing output that looks like the following:
running 5 tests test tests::test_0_pct … ok test tests::test_100_pct … ok test tests::test_49_pct … ok test tests::test_15_pct … ok test tests::test_75_pct … ok
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
That’s it for the battery indicator, now let’s move on to an animated indicator.
Creating the Pulsing Indicator
We have plenty of options available for building an animated indicator. Given that our API is going to be calling apply at a fixed frame rate, it makes sense for us to use a key frame² animation. Key frame animations are where you define (or interpolate) the values for an animation at given key points or frames.
Depending on your age, you might remember the pulsing light built into the front of the K.I.T.T. Pontiac from the old TV series Knight Rider. If not, then perhaps the pulsing animated visor in the heads of Cylons from Battlestar Galactica is more familiar. Using key frames, this is an incredibly easy animation to create.
Such a “pulser” could represent waiting for a command, an analysis in progress, a pending request to a remote system, or perhaps just to intimidate other robot operators in the competition.
The first thing we want to do is define the key frames. If we think of our eight-light LED strip as an array, then the key frames are actually just the index of the currently lit LED. With each successive frame, the “lit index” will move from left to right, take an additional pause on the far right, and then move back to the left again—reproducing the iconic “pulse” animation from Knight Rider and/or Battlestar Galactica.
You might be shocked by just how little code there is to write:
iot_gims/animatedindicator/src/lib.rs
const KEYFRAMES: [i32; 16] = [0,1,2,3,4,5,6,7, 7,6,5,4,3,2,1,0];
extern "C" { fn set_led(led_index: i32, r: i32, g: i32, b: i32);}
#[no_mangle]pub extern "C" fn sensor_update(_sensor_id: i32, _sensor_value: f64) -> f64 { // NO-OP, don't really care about sensor values 0.0}
#[no_mangle]pub extern "C" fn apply(frame: i32) { let idx = frame % 16;
for x in 0..8 { unsafe { set_led(x, 0, 0, 0); } }}[2] en.wikipedia.org/wiki/Key_frame
unsafe { set_led(KEYFRAMES[idx as usize], 255, 0, 0);}① Define the “lit index” for each of the 16 frames ② The exact same imports and exports as the previous module ③ Ensure that all eight LEDs are dark before we light up the key frame ④ Call set_led() to turn on the light for the key frame
Since we’re guaranteed by the host contract that the frame value will monotonically increase, we just need to grab the modulo 16 of the frame counter to figure out which frame index is lit. We’ll also have to assume that the host will reset the frame counter before doing an overflow. Further, the host can change the speed of the pulser by modifying the frequency of apply() calls without us having to modify the WebAssembly module at all.
With our two indicator modules in hand, let’s move on to building the Raspberry Pi host.
Building Rust Applications for ARM Devices
Section titled “Building Rust Applications for ARM Devices”Compiling for different target architectures, operating systems, and binary file formats is often an enormous pain in the neck depending on which language and tools you’re using. In the past, I’ve had to set up multiple virtual machines all running concurrently just so I could build the same application for multiple operating systems.
Cargo is an incredibly powerful tool and it comes equipped with the ability to compile for different targets. The rustup command lets you add and remove targets and list all of the available targets. Cross-compilation in Rust is usually quite simple.
Before you can compile for a target other than the default for your operating system, you’ll need to install the native compiler for that environment. There’s a GitHub repository that’s kept up to date with instructions on how to configure your workstation—Linux, Windows, or macOS—for cross-compilation.³
The first thing you’ll need to do after ensuring your workstation has the native compilation tool chain is to add the appropriate target via rustup. The target for Raspberry Pi 2+ devices is armv7-unknown-linux-gnueabihf. The Raspberry Pi 1 is an ARM v6 device, while all newer ones are ARM v7. The second element
[3] github.com/japaric/rust-cross In the target triple is the vendor (unknown in our case since it doesn’t matter). The third is the operating system and the fourth is the ABI (Application Binary Interface). Add the ARM v7 target with the following command:
$ rustup target add armv7-unknown-linux-gnueabihfinfo: downloading component 'rust-std' for 'armv7-unknown-linux-gnueabihf'50.5 MiB / 50.5 MiB (100 %) 6.5 MiB/s ETA: 0 sinfo: installing component 'rust-std' for 'armv7-unknown-linux-gnueabihf'Next, configure Cargo for cross-compilation using the instructions on the GitHub repository. For Ubuntu Linux, it will look like this:
$ mkdir -p ~/.cargo$ cat >>~/.cargo/config <<EOF[target.armv7-unknown-linux-gnueabihf]linker = "arm-linux-gnueabihf-gcc"EOFNext, create a new Rust binary application using the same commands you’ve been using throughout the book. To compile this application so it will run on a Raspberry Pi, use the following command (which looks very similar to how we specify the WebAssembly target for wasm compilation):
$ cargo build --target armv7-unknown-linux-gnueabihfCompiling crosscompiledemo v0.1.0(file:///home/kevin/Code/Rust/wasmbook/khrust/Book/code/crosscompiledemo)Finished dev [unoptimized + debuginfo] target(s) in 0.58sFinally, to verify that this new binary is actually an ARM v7 Linux binary and not a binary for the development workstation that ran the build, you can execute the following command:
$ file target/armv7-unknown-linux-gnueabihf/debug/crosscompiledemotarget/armv7-unknown-linux-gnueabihf/debug/crosscompiledemo:ELF 32-bit LSB shared object, ARM, EABI5 version 1 (SYSV),dynamically linked, interpreter /lib/ld-linux-armhf.so.3,for GNU/Linux 3.2.0, BuildID[sha1]=fb1690370f7516f436c440d5083447d8fe06077a,with debug_info, not strippedIf you’ve got a Raspberry Pi (2 or newer) handy, you can take the single cross-compiledemo binary and scp that to the device and execute it. You should see the standard “Hello, World” text. Now that your workstation is set up to do cross-compilation for ARM v7, it’s time to build the indicator module host.
Hosting Indicator Modules on a Raspberry Pi
Section titled “Hosting Indicator Modules on a Raspberry Pi”To build an application that resides on a Raspberry Pi (but that we can test on our workstations) that hosts our indicator modules, we’ll need to employ a few techniques that we haven’t covered in this book yet. The requirements for our Generic Indicator Module System are as follows:
-
Load a WebAssembly module at launch and immediately run, controlling LEDs
-
Enforce a fixed frame rate for animated modules
-
Trap the SIGINT and SIGTERM signals, gracefully turning off active LEDs before shutdown
-
Hot Reloading—if a new module is copied into a monitored location, pause, then load the new module and continue
The application is designed to start and continue running forever, constantly getting new sensor inputs (though we’re only faking one sensor) and feeding that data to the indicator module. To make all of this work, you’ll get into some new Rust patterns like using multi-threaded code, channels, and con- ditional compilation.
Creating a Raspberry Pi Application
In the previous section, you created an empty application called pihost. At the moment there’s nothing special that you need to do to make this application suitable for a Raspberry Pi. We do need to pick some dependencies—crates that will help us monitor the file system, read and execute WebAssembly modules, respond to OS signals, and operate the Blinkt hardware module. This is a Cargo.toml that pulls in those dependencies:
iot_gims/pihost/Cargo.toml
[package]name = "pihost"version = "0.1.0"
[dependencies]notify = "4.0.0"wasm = "0.4.1"ctrlc = { version = "3.0", features = ["termination"] }
[target.'cfg(any(target_arch = "arm", target_arch = "armv7"))'.dependencies]blinkt = "0.4.0"This is the first time you’ve seen conditional compilation in action. The high- lighted lines will only include the blinkt dependency when you’re compiling for the ARM architecture.
<h2>Watching for New Modules</h2><p>There are a number of mission-critical tasks in the application and, as you'll see, coordinating them can be really tricky. Thankfully Rust makes it pretty easy. The first task is monitoring the file system and then letting the main module runner know that it needs to reload a module. The following two functions make that possible:</p><pre><code>lot_gims/pihost/src/main.rs#[cfg(any(target_arch = "armv7", target_arch = "arm"))]extern crate blinkt;extern crate ctrlc;extern crate notify;extern crate wasmi;
use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher};use std::path::Path;use std::sync::mpsc::{channel, RecvTimeoutError, Sender};use std::thread;use std::time::Duration;use wasm::Runtime;use wasmi::RuntimeValue;
const MODULE_FILE: &'static str = "/home/kevin/indicators/indicator.wasm";const MODULE_DIR: &'static str = "/home/kevin/indicators";
enum RunnerCommand { Reload, Stop,}
fn watch(tx_wasm: Sender<RunnerCommand>) -> notify::Result<> { let (tx, rx) = channel();
let mut watcher: RecommendedWatcher = Watcher::new(tx, Duration::from_secs(1))?; watcher.watch(MODULE_DIR, RecursiveMode::NonRecursive)?;
loop { match rx.recv() { Ok(event) => handle_event(event, &tx_wasm), Err(e) => println!("watch error: {:?}" , e), } }}
fn handle_event(event: DebouncedEvent, tx_wasm: &Sender<RunnerCommand>) { match event { DebouncedEvent::NoticeWrite(path) => { let path = Path::new(&path); let filename = path.file_name().unwrap(); if filename == "indicator.wasm" { tx_wasm.send(RunnerCommand::Reload).unwrap(); } } }}</code></pre>} else { println!("write (unexpected file): {:?}, path);}}- => {}}① Creates a multi-producer, single-consumer communication channel ② Block the receive channel until a message arrives ③ Send a message on the channel, indicating that we should reload the WebAssembly module
In Rust, multi-producer-single-consumer (mpsc) channels are used as a safe way to communicate between threads. In the case of the watch() function, the main thread sits in a loop, awaiting file system notifications from the monitored directory. When we see the NoticeWrite event, it’s time to tell another thread to reload the module from disk.
Creating the Module Runner Thread
Section titled “Creating the Module Runner Thread”In the last section, you saw code that sends a message on a channel to tell another thread to reload a WebAssembly module. In this section, you’ll create that main thread. This thread has a number of jobs. It obviously needs to listen for the RunnerCommand::Reload message, but it also needs to handle the RunnerCommand::Stop message (which it will get from us monitoring OS signals). It also needs to invoke methods on the module itself, setting the fake sensor input value and calling apply() to take care of animations.
This is where it would be so much easier to throw up our hands and walk away. Juggling file system monitoring, two different threads, signal trapping, and ensuring a consistent frame rate in the WebAssembly module sounds as complicated as dealing with the three-body problem.1
Luckily, there’s a solution that doesn’t require creating yet another coordination thread. Instead, we can use the timeout feature of channel receives. If we wait for the inverse of the frame rate in milliseconds for a message to arrive, and no messages comes, then we can invoke the apply() function on the WebAssembly module. For example, if we want to enforce 20fps, then we would set our receive timeout delay to 50 milliseconds. For a frame rate of 10fps, we’d set the delay to 100 milliseconds, which actually produces a pretty good effect on the Blinkt hardware.
Let’s take a look at the code for the main() function (anything from the wasm module is code that we’ll write shortly):
lot_glims/pihost/src/main.rs
fn main() { let (tx_wasm, rx_wasm) = channel(); let _indicator_runner = thread::spawn(move || { let mut runtime = Runtime::new(); let mut module = wasm::get_module_instance(MODULE_FILE); println!("Starting wasm runner thread.."); loop { match rx_wasm.recv_timeout(Duration::from_millis(100)) { Ok(RunnerCommand::Reload) => { println!("Received a reload signal, sleeping for 2s"); thread::sleep(Duration::from_secs(2)); module = wasm::get_module_instance(MODULE_FILE); } Ok(RunnerCommand::Stop) => { runtime.shutdown(); break; } Err(RecvTimeoutError::Timeout) => { runtime.reduce_battery(); runtime.advance_frame(); module .invoke_export( "sensor_update", &[ RuntimeValue::from(wasm::SENSOR_BATTERY), RuntimeValue::F64( runtime.remaining_battery.into(), )[..], &mut runtime, ] .unwrap(); module .invoke_export( "apply", &[ RuntimeValue::from(runtime.frame)][..], &mut runtime, ] .unwrap(); } Err(_) => break, } } }); let tx_wasm_sig = tx_wasm.clone(); ctrlc::set_handler(move || { tx_wasm_sig.send(RunnerCommand::Stop).unwrap(); }).expect("Error setting Ctrl-C handler");if let Err(e) = watch(tx_wasm) { println!("error: {:?}, e)}mod wasm;① Enforce the frame rate with a 100ms timeout value on receive
② Send channels can be cloned, hence their presence in the multi-producer module
③ Use the ctrlc crate to trap SIGTERM and SIGINT, sending a Stop command in response
④ The watch() function blocks the main thread with an infinite loop
Creating the WebAssembly Module Runtime
Let’s create the wasm.rs module that was referenced by the previous set of code:
iot_gims/pihost/src/wasm.rs
use std::fmt;use std::fs::File;use wasmi::{ Error as InterpreterError, Externals, FuncInstance, FuncRef, HostError, ImportsBuilder, Module, ModuleImportResolver, ModuleInstance, ModuleRef, RuntimeArgs, RuntimeValue, Signature, Trap, ValueType,};① #[cfg(any(target_arch = “armv7”, target_arch = “arm”))]
use blinkt::Blinkt;fn load_module(path: &str) -> Module { use std::io::prelude::*; let mut file = File::open(path).unwrap(); let mut wasm_buf = Vec::new(); file.read_to_end(&mut wasm_buf).unwrap(); Module::from_buffer(&wasm_buf).unwrap()}
pub fn get_module_instance(path: &str) -> ModuleRef { let module = load_module(path); let mut imports = ImportsBuilder::new(); imports.push_resolver("env", &RuntimeModuleImportResolver);
ModuleInstance::new(&module, &imports) .expect("Failed to instantiate module") .assert_no_start()}
pub const SENSOR_BATTERY: i32 = 20;#[derive(Debug)]pub enum Error { Interpreter(InterpreterError),}
impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) }}
impl From<InterpreterError> for Error { fn from(e: InterpreterError) -> Self { Error::Interpreter(e) }}
impl HostError for Error {}
pub struct Runtime { #[cfg(any(target_arch = "armv7", target_arch = "arm"))] blinkt: Blinkt, pub frame: i32, pub remaining_battery: f64,}
impl Runtime { #[cfg(any(target_arch = "armv7", target_arch = "arm"))] pub fn new() -> Runtime { println!("Instantiating WASM runtime (ARM)"); Runtime { blinkt: Blinkt::new().unwrap(), frame: 0, remaining_battery: 100.0, } }
#[cfg(not(any(target_arch = "armv7", target_arch = "arm")))] pub fn new() -> Runtime { println!("Instantiating WASM runtime (non-ARM)"); Runtime { frame: 0, remaining_battery: 100.0, } }}
impl Externals for Runtime { fn invoke_index( &mut self, index: usize, args: RuntimeArgs, ) -> Result<Option<RuntimeValue>, Trap> {match index { 0 => { let idx: i32 = args.nth(0); let red: i32 = args.nth(1); let green: i32 = args.nth(2); let blue: i32 = args.nth(3); self.set_led(idx, red, green, blue); Ok(None) } _ => panic!("Unknown function index!"),}impl Runtime { #[cfg(not(any(target_arch = "armv7", target_arch = "arm")))] fn set_led(&self, idx: i32, red: i32, green: i32, blue: i32) { println!("[LED {}]: {}, {}, {}", idx, red, green, blue); }
#[cfg(any(target_arch = "armv7", target_arch = "arm"))] fn set_led(&mut self, idx: i32, red: i32, green: i32, blue: i32) { self.blinkt .set_pixel(idx as usize, red as u8, green as u8, blue as u8); self.blinkt.show().unwrap(); }
#[cfg(not(any(target_arch = "armv7", target_arch = "arm")))] pub fn shutdown(&mut self) { println!("WASM runtime shut down."); self.halt(); }
#[cfg(any(target_arch = "armv7", target_arch = "arm"))] pub fn shutdown(&mut self) { println!("WASM runtime shut down."); self.blinkt.clear(); self.blinkt.cleanup().unwrap(); self.halt(); }
fn halt(&self) { ::std::process::exit(0); }
pub fn reduce_battery(&mut self) { self.remaining_battery -= 1.0; if self.remaining_battery < 0.0 { self.remaining_battery = 100.0; } }
pub fn advance_frame(&mut self) { self.frame += 1; }}if self.frame > 1_000_000_000 { self.frame = 0;}}
struct RuntimeModuleImportResolver;
impl<'a> ModuleImportResolver for RuntimeModuleImportResolver { fn resolve_func( &self, field_name: &str, _signature: &Signature, ) -> Result<FuncRef, InterpreterError> { println!("Resolving {}", field_name); let func_ref = match field_name { "set_led" => FuncInstance::alloc_host( Signature::new( &[ ValueType::I32, ValueType::I32, ValueType::I32, ValueType::I32, ][..], None, 0, ), _ => { return Err(InterpreterError::Function(format!( "host module doesn't export function with name {}", field_name ))); } }; Ok(func_ref) }}① Conditionally add Blinkt to the module’s scope ② Conditionally add a blinkt field to the Runtime struct ③ The apply() function will have an index of 0. ④ The set_led() function is the only one exported by the host/imported by the module
Most of this should look pretty familiar to you as a lot of it is just the boiler-plate required to load the WebAssembly module, resolve its imports, and allow function calls.
You may have noticed one interesting thing: because of the conditional compilation, there are actually multiple functions with the same name. If we are building for ARM, then the Runtime struct gets an extra field called blink and the set_led() function uses that field to control real hardware, whereas the “regular” version of that struct and function just emit debug text to the console.
Running the Application
To run the application on your workstation, just build the binary and execute it or type cargo run. This will launch the application and it will load the module at /home/kevin/indicators/indicator.wasm (feel free to change that location to suit your needs).
Running on a Mac, Windows, or Linux, you’ll see some console output spam as the module tells the host what LEDs to light up 10 times per second (the following is output from the animated pulse indicator):
Instantiating Wasm runtime (non-ARM) Resolving set_led Starting wasm runner thread… [LED 0]: 0, 0, 0 [LED 1]: 0, 0, 0 [LED 2]: 0, 0, 0 [LED 3]: 0, 0, 0 [LED 4]: 0, 0, 0 [LED 5]: 0, 0, 0 [LED 6]: 0, 0, 0 [LED 7]: 0, 0, 0 [LED 1]: 255, 0, 0 [LED 0]: 0, 0, 0 [LED 1]: 0, 0, 0 [LED 2]: 0, 0, 0 [LED 3]: 0, 0, 0 [LED 4]: 0, 0, 0 [LED 5]: 0, 0, 0 [LED 6]: 0, 0, 0 ^CWasm runtime shut down.
Here I’ve tested the signal handling capabilities and the application shut down nicely in response to a Control-C. Next, we can try this out on real hardware.
Hardware Shopping List
Before you can run this code on a Raspberry Pi host, you’re obviously going to need a Raspberry Pi. For my own testing I used a Raspberry Pi 3 and I communicated with it via ssh over WiFi. You should be able to use a Raspberry Pi 2 as well. These devices are pretty inexpensive to obtain in the US, though price and availability does tend to fluctuate globally. If you can’t buy one, see if you can find a local makers group. They tend to have plenty of spares for testing and experimentation.
Next, you’ll need a Pimoroni Blinkt.⁵ These are amazing little devices and, at the time I write this, only cost $6. They come with pins and fit snugly right onto the GPIO ports of your Raspberry Pi.
For my own version, I bought a Mini Black Hat Hack3r,⁶ which allows you to attach a ribbon cable to your Pi’s GPIO ports and extend them outside its case. It’s like a GPIO “extension cord.” You’ll see the one I used in the demonstration video. I like the flexibility of this as it lets me keep some of my custom Raspberry Pi cases, but you certainly don’t need one to run the application.
That’s it—that’s all you need to run this demo, assuming your Pi has network access and a power supply. Don’t power it from a computer’s USB, power it from the wall. I’ve seen the drain from similar LEDs cause the power to “flicker” on the Pi causing it to reboot.
Running the Application on a Raspberry Pi
Now that you’ve got your hardware all set and your Blinkt is plugged into your Raspberry Pi, it’s time to play with some lights. First, scp the pihost binary to somewhere on the Pi. I just used the pi user’s home directory. Your Raspberry Pi OS and configuration may vary depending on whether you installed Raspbian⁷ or another distribution. Check your distribution’s documentation if you have trouble logging into the default user and creating directories.
Next, scp the batteryindicator.wasm and animatedindicator.wasm files onto the Pi. I also put these in the pi user’s home directory, but you can put them anywhere.
You’ll need to create and set the permissions on the indicator modules directory. The chapter code has this set for /home/kevin/indicators, but you can change that to whatever you like and recompile. You might need to sudo the commands to create those directories.
Finally, make sure the application can read from the indicator directory and that you won’t have any problems writing to it:
$ chmod -R a+rw /home/kevin/indicators
- shop.pimoroni.com/products/blinkt
- www.adafruit.com/product/3182
- www.raspberrypi.org/downloads/raspbian/
This grants global read/write access to that directory. In a production system, you’d probably want to be more careful about your permissions, but it’s fine for testing.
Copy one of the indicator wasm files to the indicator directory and make sure to call it indicator.wasm. While ssh’d into the Raspberry Pi, start the pihost exe- cutable. You should see the Blinkt immediately light up (it’s super bright) and start going through the pattern of whatever indicator you chose. The battery indicator will slowly make its way to “off” and then start over, while the ani- mated indicator will show a single red LED pulsing back and forth.
Now for the really fun part—with the application still running, copy a different indicator onto the indicator.wasm file. You’ll see the lights pause for a few seconds, then it’ll switch to the new indicator pattern and continue on its merry way, as you’ll see in this YouTube video.2
Endless Possibilities
I’ve asked you a couple times in this book to pause and reflect on your accomplishments and what you’ve been able to do with WebAssembly. Now let’s reflect on those reflections, but with the added perspective of knowing that we can build portable, immutable binaries that can snap into applications running attached to hardware, running on our laptops, running on servers, or running in browsers.
Thinking about this fires just about every neuron in my brain. Just think, you could create autopilot software for drones in WebAssembly and swap out different “brains” without ever needing to do anything to the drone itself. You could test this software in 3D rendered desktop environments or in browsers, all without ever having to modify the WebAssembly module. These drone hosts could go from a search-and-rescue mission to playing Quidditch3 with nothing more than an an over-the-air software update.
Factories, manufacturing facilities, power plants, and building management systems, all of which are normally tightly coupled to their hardware, could all benefit from this. Many of these places operate with hundreds of PLCs (Programmable Logic Controller) that interface with, monitor, and control all kinds of machines as shown in the figure on page 153.
What if instead of using languages like ladder diagrams or function blocks to program PLCs, we could just drop WebAssembly modules into them that
WebAssembly files are just binary files. That means that we can encrypt them and we can digitally sign them. There are a ton of things that you could do to add a layer of security to using WebAssembly modules that might one day be able to prevent things like PLC viruses.¹⁰
With all of this talk of hardware, I have not forgotten the idea of using WebAssembly to build in-browser applications—far from it. You could spend all of your WebAssembly time doing nothing but building browser applications and never run out of things to do or build. But there’s a bigger picture here. WebAssembly is bigger than the web, it’s bigger than just IoT, and it’s bigger than most people give it credit for. Hopefully this little section of the book has inspired you, and you’re cooking up the next amazing thing right now—all based on WebAssembly.
[10] en.wikipedia.org/wiki/Stuxnet
Wrapping Up
Section titled “Wrapping Up”In this chapter, we illustrated a number of really powerful techniques and we got into some more detail with the Rust programming language. You saw how to set up your workstation to cross-compile Rust applications for multiple platforms, including the Raspberry Pi. You read about how to conditionally compile different pieces of your codebase depending on your target architecture, and you saw how to coordinate multiple parallel activities in Rust with threads and channels.
You also got to see Rust playing host to WebAssembly modules and providing a bridge to controllable hardware like LED blocks to give WebAssembly incredible abilities. We built an application that can hot-swap LED controller modules without even needing a restart.
As you’ll see in the next chapter, we can take our knowledge of hosting WebAssembly outside the browser straight to the cloud, and leverage new technologies like FaaS (Functions as a Service) and serverless to deploy WebAssembly modules in our back end as well as in the browser.