Rust for embedded
The advantages of the Rust programming language are generally well-known; memory safety is a feature that has attracted a lot of developer attention over the last few years. At the inaugural Embedded Open Source Summit (EOSS), which is an umbrella event for numerous embedded-related conferences, Martin Mosler presented on using Rust for an embedded project. In the talk, he showed how easy it is to get up and running with a Rust-based application on a RISC-V-based development board.
Mosler works for Zühlke Engineering in Switzerland; both he and his company see the potential of Rust for new development, particularly for embedded projects. That is why the company supports his community work on Rust, including holding Rust meet-ups and traveling to Prague to attend EOSS and give the talk. He is building up Rust knowledge within the company so that it is available for new projects as they arise.
Over the last few months, he has been working on his own project: an Internet of Things (IoT) temperature-measurement device. He based the device on the ESP32-C3-DevKitM-1, which is a development board with a RISC-V processor and onboard WiFi. He chose that board because it is well-supported by the community, with various articles, libraries, and the like, and that it has the WiFi needed to send out the recorded measurements.
There are some additional benefits to the hardware he chose, including no need for a proprietary toolchain to build for RISC-V; he can simply install Clang and LLVM for what he needs. The board is also fairly inexpensive, around €10, and, importantly, is widely available, unlike Raspberry Pi devices over the last few years. Beyond that, it has 4MB of flash; he is currently only using around 1MB, but the extra space will allow him to do over-the-air updates and to store measurement data while the device is offline.
Hello Rustaceans
The traditional "hello world" program is used to introduce a new a programming language and Mosler followed that lead. Using his laptop and the development board, he did a live demo of creating, building, deploying, and running the program. He noted that Rust comes with a lot of different tools, including "one quite important tool called 'cargo'"; it is a build tool and dependency manager, but it can do even more than that. He had installed the cargo-generate extension that can be used to create a new project from a template; in his case, he used it to create a project using a template for the ESP IoT development framework (ESP-IDF).
He used cargo generate with a local path for the template file (though one could instead retrieve it from GitHub using different command-line parameters); it asked a couple of questions, then created a pre-populated directory for the project. The application code lives in src/main.rs, while the Cargo.toml file describes the application and its dependencies; the rest of the files configure the cross-compilation toolchain to build for his board.
The template project comes with code that initializes the device and will jump to the main() function in the binary that gets built. He looked inside his version of main.rs, where he had added calls to initialize the Rust logger and then to log messages at different severity levels (using info!(), warn!(), and error!()). In keeping with the theme, "Hello, Rustaceans!" was the info!() message.
To compile, deploy, and run that code, all that he needed to do was issue the "cargo run" command. He used the --release option to cargo, which builds a somewhat smaller binary image that will take less time to send to the board. The code in his local directory had already been built, so it simply asked him to confirm which serial device to use and sent the binary to the development board. If the code had not yet been built, cargo would have downloaded and built all of the dependencies, which takes a fair amount of time, he said.
But just flashing the code to the device took a bit of time, so he went back to his slides to show how he had installed the toolchain. He noted that the rustup project provides an easy-to-use mechanism to get what is needed for Rust development. Beyond that, he needed to install a handful of packages for his Fedora virtual machine, add a udev rule to recognize the USB serial device, and then install a few crates via cargo install, including the espflash crate that provides a tool to flash the development board.
He switched back to the output of the download, which had completed; once that happened, the serial device switched to a console displaying the system log for the device. It showed that it took around 300ms to initialize and jump to his code, then it printed his messages, in three different colors based on the severity, to the serial console.
Temperature monitor
With those preliminaries out of the way, he moved on to the IoT temperature monitor that was his real project. He chose to use the DS18B20 temperature sensor in the monitor because it uses a one-wire communication protocol, thus it only uses one pin (plus power and ground). The board can be connected to an external power supply, but he uses three AA batteries since the monitor is installed in his garden. He can run for about three weeks before he has to replace the batteries, which is good, but "there's still room for improvement".
The device needs to measure the temperature using the sensor and send it to his web site where it can be displayed. An important optimization is to put the device into a deep sleep between operations; otherwise, the device consumes the batteries in less than a day. In addition, the device needs to periodically connect to a WiFi network in order to send the measurements out to the cloud.
The code for all of what he demonstrated lives in his GitHub repository; looking at the history shows the evolution from the simple logging example he showed earlier to the more complex—though not horrifically so—temperature monitor. After checking out the version he wanted to demonstrate, which is simpler than the full-featured monitor described above, and starting to build and download it in the background, he began describing the new code, starting with:
// Initialize one-wire-bus on GPIO3
let peripherals = Peripherals::take().unwrap();
let driver = PinDriver::input_output_od(peripherals.pins.gpio3).unwrap();
let mut one_wire_bus = OneWire::new(driver).unwrap();
The Peripherals singleton comes from the IoT framework and the take() method takes ownership of that singleton for his application; no other part of the application can access it once that happens. That is the first real Rust-specific concept that he presented; the ownership is something that the compiler will enforce for a Rust program. While Mosler did not mention it here, the unwrap() call extracts the payload from the returned value, and will panic the program if the result (of the take() in this case) is an error.
He then uses the peripherals object to get to the specific GPIO pin (3) that he chose to use for the sensor; that gets turned into a driver object for a pin that is used as both an input and an output via the PinDriver::input_output_od() call. Once again, his code takes ownership of the GPIO 3, so no other part of the application can use or redefine it. That driver is used to create a OneWire object that can be used to communicate with the sensor chip.
He then described the main (infinite) loop of the program, which consists of a match statement (followed by a ten-second sleep):
// Temperature measurement on one-wire-bus
match measure_temperature(&mut one_wire_bus) {
Ok(measurement) => send(&measurement).unwrap(),
Err(MeasurementError::NoDeviceFound) => warn!("No device found on one-wire-bus"),
Err(err) => error!("{:?}", err),
}
The measure_temperature() function follows the Rust idiom of returning a Result (an enum containing either the value of interest or an error indication); the match statement does pattern matching as in functional languages (and similar to the match recently added to Python). In this case, if the function did not return an error (i.e. Ok), then measurement is assigned to the return value and is sent out using send(). If the result is the specific MeasurementError::NoDeviceFound error, the warning is issued, otherwise, all other error results get logged using error!().
The final, catch-all line for all errors in the match assigns the result to the err variable so that it can be emitted as part of the error message, but it has an additional role. In Rust, the match must have all of the possible outcomes covered by a pattern, he said, so removing that error catch-all line would cause a compilation error. But removing the NoDeviceFound line is just fine, since the error catch-all will cover that case.
Mosler then looked at his send() function and the data type that it uses:
#[derive(Serialize)]
struct Measurement {
device_id: String,
temperature: f32,
}
fn send(measurement: &Measurement) -> std::io::Result<()> {
let message = serde_json::to_string_pretty(&measurement)?;
info!("{}", message);
Ok(())
}
The Measurement type consists of a string and a floating-point value, but it has been declared to be serializable, which means that the serde library ("serde" for serialize-deserialize) can be used to serialize the type into a variety of formats. In send(), he uses serde_json to do JSON serialization (in a "pretty" string form with indentation using to_string_pretty()) before logging the value.
He returned to the measure_temperature() call in the match:
match measure_temperature(&mut one_wire_bus) {
The one_wire_bus variable cannot be passed to the function, in an ownership sense, since the call is in a loop; subsequent calls would cause an error because the main function would no longer own one_wire_bus, he said. So the & operator is used to indicate that a reference to the variable is being passed (and the function is "borrowing" the value); Mosler did not note it, but send() is also borrowing its value in the match. Beyond that, though, one_wire_bus can be both read and written in the function, thus it is a mutable value, so the mut keyword is used in its declaration and in the call to and the definition of measure_temperature().
The measure_temperature() function is somewhat complicated, in part because multiple sensor chips can be installed in parallel and the ds18b20 library he is using will try to retrieve data from all of them. One Rust lesson from his description is the use of the ? as at the end of the line that starts the temperature measurement process:
ds18b20::start_simultaneous_temp_measurement(one_wire_bus, &mut Ets)?;
The ? says that if the called function returns an error (start_simultaneous_temp_measurement() in this case), the current function should simply immediately return that error to the caller. It is a shortcut mechanism for an early error return from a function and it is used in several places in measure_temperature(). "All the error-handling code is hidden behind the '?'; that's pretty nice." He also showed how a function returns a non-error result, by using an Ok() expression:
return Ok(Measurement {
device_id: format!("{:?}", device_address),
temperature: sensor_data.temperature,
});
He switched over to the serial console; his program had downloaded and started running on the board. Every ten seconds, it was printing the measurement (as pretty-printed JSON). The room was warm and the temperature was measured at around 28°C; he touched the sensor chip for ten seconds to see it rise ("hopefully not above 40°C"). The next reading was over 32°C.
More features
The infinite loop for measuring the temperature means that the board is always running; it draws around 20-30mA so his batteries would last around ten hours before he would need to recharge them. He made some small changes to his main program, removing the loop and calling a new function, deep_sleep(), for nine seconds after a measurement is done (and logged). That function simply calls into the framework:
fn deep_sleep(seconds: u64) -> ! {
info!("Powering down for {} seconds", seconds);
unsafe {
esp_deep_sleep(seconds * 1_000_000);
}
}
The return type of "!" tells the compiler that the function never returns. It simply logs a message, then calls esp_deep_sleep() in an unsafe block, which means that the compiler will not check the code in the block for undefined behavior; unsafe suspends other rules that apply to Rust code as well. That function is written in C, so the compiler cannot check it; if he removes the unsafe, he gets a compilation error. esp_deep_sleep() powers down the system, except for the realtime clock and a timer, for the specified time; when it wakes back up, it goes through the reset vector and reruns the program.
He flashed the program to the board and demonstrated it running. As before, every ten seconds it put out a log message with the JSON-formatted measurement. This version was somewhat noisier, with the log message from deep_sleep() and all of the startup messages each time the board came out of its sleep and reset. That change was enough to get the temperature monitor to run for three weeks before needing a battery change.
He then moved on to show the changes he made to support WiFi. Most of the changes are in a new wifi.rs file, but the main program needs to initialize the Wifi object before taking the measurement and then shut it down afterward. Each of those steps is accompanied by a hard-coded two-second delay, in order to ensure that a DHCP lease has been granted during initialization and to wait for the network queue to drain before shutting it down. Changing those to actually test for the conditions would be better, of course.
The send() function also needed to change; in addition to logging the measurement, it also sends it out over a socket. The new code is as follows:
let socket = UdpSocket::bind("0.0.0.0:1337")?;
...
socket.connect(format!("{}:1337", env!("SERVER_IP")))?;
socket.send(message.as_bytes())?;
Mosler noted that this code knows nothing about WiFi, it simply opens a UDP socket, connects to the server, and then sends the JSON-formatted message. The env!() call resolves the SERVER_IP environment variable at compile time, so there is no need to commit that address to GitHub. He does a similar thing with the WiFi SSID and password in wifi.rs.
He then showed this final version of his code running on the board; it had log messages that indicated it had connected successfully to the conference WiFi network. The server address he was using was a cloud server that he then logged into. A simple netcat command was used to listen for the message; after a few seconds, it showed the temperature of the room on the server in the cloud. Mission accomplished in around 100 lines of code. He noted that the Rust compiler was quite helpful in the process of building the application; it takes some time to understand the error messages, but it is well worth doing.
He then demonstrated another cargo feature: searching. You can do a cargo search for a specific crate, then add it to your project with a cargo add. After that, cargo will download the library, build it, and link it into the project the next time it is built. It is a nice way to do rapid prototyping, he said; for production code, though, the library should be scrutinized for its stability, maintenance status, and so on.
With that, Mosler took questions from the audience. The first was about the delay function that he used, which was FreeRtos::delay_ms(); "is there a FreeRTOS running?" Mosler said that the ESP-IDF that he used has FreeRTOS as part of it; it is a high-level framework, that comes with WiFi support, which is one of the reasons he chose it. Those who want to work at a lower level can install the ESP framework instead, but then they will need to install WiFi and other libraries, do additional initialization, directly handle dynamic memory allocation, and so on.
Another question was about whether an asynchronous runtime, such as Tokio, could be used instead of FreeRTOS. Mosler said that one of the things he wanted to look into was alternative runtimes; he mentioned Embassy, which is another Rust-based, asynchronous framework. He would like to evaluate some of those in the future.
[I would like to thank LWN's travel sponsor, the Linux Foundation, for assisting with my travel to Prague.]
| Index entries for this article | |
|---|---|
| Conference | Embedded Open Source Summit/2023 |
