Posted on ::

Lately I've been really into Rust. Since I got the printed book (highly recommended for anyone who wants to learn and doesn't know English), I haven't stopped doing small exercises. Even finishing rustlings didn't feel like enough, because there's a whole world around this language, and I'll never finish specializing in every one of its uses.

That's why I made 3 decisions:

  1. Start this blog, an important step to remember the skills I learn over time.

  2. Learn English. I'm trying to watch the talks by Steve Klabnik, who is the author of the book, so I learn the language while watching things I'm interested in.

  3. Take a Rust course.

For that last point I looked on Udemy (highly recommended, by the way), and here we are.

Let me introduce my project: A telemetry gateway for remote sensors.

In short, it's a translator that listens in real time, over the TCP protocol, to sensors that communicate in binary.

The project handles memory through raw bytes. In plain words, this means that if you're off by a millimeter on a latitude, the coordinates are wrong and the altitude sends you to the middle of the sea instead of where the sensor really is. It also helped me finally understand the power of concurrency with tokio.

The assignment was that this system simulates the systems used for large-scale logistics of trucks carrying goods. At the product level, we assume each truck has a hidden sensor that sends its location and how much battery it has left. The sensor sends very little info, using binary numbers, so the battery lasts for months, and the gateway makes sure that same info reaches the control center perfectly.

Let's go to the code:

1. The imports

At the top of the file we bring in the tools we're going to use. tokio so everything is async, chrono to add date and time, and serde so Rust knows how to turn our structures into data that other systems understand.

use std::net::SocketAddr;
use chrono::{DateTime, Utc};
use serde::Serialize;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};

2. What shape the struct has

Here I define what shape the data has for us. The important part is that, even though the sensor sends numbers, we need to turn them into something readable. The #[derive(Debug, Serialize)] is key to be able to print the data in the console while we test.

#[derive(Debug, Serialize)]
struct TelemetryFrame {
    timestamp: DateTime<Utc>,
    latitude_deg: f32,
    longitude_deg: f32,
    battery_level: u8,
}

3. The translator

This is the most careful part of the system. The sensor sends 9 bytes, and this is where we split them precisely, without mistakes.

impl TelemetryFrame {
    fn from_bytes(raw: &[u8]) -> Result<Self, String> {
        if raw.len() != 9 {
            return Err(format!("invalid frame length: expected 9 bytes, got {}", raw.len()));
        }

        // Sacamos de los bytes
        let lat_bytes: [u8; 4] = raw[0..4].try_into().map_err(|_| "failed to extract latitude bytes".to_string())?;
        let lon_bytes: [u8; 4] = raw[4..8].try_into().map_err(|_| "failed to extract longitude bytes".to_string())?;

        // Convertimos de Big-Endian (el orden del sensor) a números que entienda nuestra PC
        let lat_microdeg = i32::from_be_bytes(lat_bytes);
        let lon_microdeg = i32::from_be_bytes(lon_bytes);
        let battery_level = raw[8];

        Ok(Self {
            timestamp: Utc::now(),
            latitude_deg: lat_microdeg as f32 / 1_000_000.0,
            longitude_deg: lon_microdeg as f32 / 1_000_000.0,
            battery_level,
        })
    }
}

4. The main server in main

main is what gets everything running. First we define which address we're going to listen on (port 9000). One of the most powerful parts here is the loop with tokio::spawn. Every time a truck connects (async task), we let it talk in peace without slowing down the others.

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let bind_addr = std::env::var("TELEMETRY_BIND_ADDR").unwrap_or_else(|_| "0.0.0.0:9000".into());
    let metrics_addr = std::env::var("METRICS_FORWARD_ADDR").unwrap_or_else(|_| "127.0.0.1:9100".into());

    let listener = TcpListener::bind(&bind_addr).await?;

    loop {
        let (socket, peer_addr) = listener.accept().await?;
        let metrics_addr = metrics_addr.clone();

        tokio::spawn(async move {
            if let Err(e) = handle_connection(socket, peer_addr, &metrics_addr).await {
                eprintln!("connection error from {}: {}", peer_addr, e);
            }
        });
    }
}

5. Taking care of the sensor (handle_connection)

This function handles the conversation with each sensor. It uses a BufReader to read, line by line, what the truck sends in hexadecimal.

async fn handle_connection(socket: TcpStream, peer_addr: SocketAddr, metrics_addr: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let (reader, _writer) = socket.into_split();
    let mut buf_reader = BufReader::new(reader);
    let mut line = String::new();

    loop {
        line.clear();
        let bytes_read = buf_reader.read_line(&mut line).await?;
        if bytes_read == 0 { break; } // Conexión cerrada

        let hex_str = line.trim();
        if hex_str.is_empty() { continue; }

        match decode_and_parse_frame(hex_str) {
            Ok(frame) => {
                forward_to_metrics(&frame, metrics_addr).await?;
            }
            Err(err) => eprintln!("Error parseando: {}", err),
        }
    }
    Ok(())
}

6. The final send (forward_to_metrics)

To finish, once we have the processed data, we open another connection and send it to the central metrics server.

async fn forward_to_metrics(frame: &TelemetryFrame, metrics_addr: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let mut stream = TcpStream::connect(metrics_addr).await?;
    let line = format!(
        "telemetry lat={:.6},lon={:.6},battery={} timestamp={}\n",
        frame.latitude_deg, frame.longitude_deg, frame.battery_level, frame.timestamp
    );
    stream.write_all(line.as_bytes()).await?;
    stream.flush().await?;
    Ok(())
}

That was the last step of our system.