Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/ci/esp-lte-mtls.toml
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ port = 23
# Use mqtt:// for basic auth (plain TCP). Use mqtts:// for mTLS.
broker_url = "mqtts://broker.example.com"
# Names this device's MQTT topics, and the app learns it over BLE: give each device its own.
client_id = "dev-car"

# Specify the type of authentication to the broker.
# - `basic` is for username/password combo (no certs needed)
Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ ssid = "YourSSID"
password = "YourPassword"

[network.mqtt]
broker_url = "mqtts://broker.example.com" # mqtt:// is plain TCP: only on a network you trust
auth_mode = "mtls" # or "basic" (username/password)
broker_url = "mqtt://192.168.0.100:1883" # or mqtts:// for TLS
auth_mode = "basic" # "none", "basic" (username/password) or "mtls"
```

A broker on the internet (any LTE setup) should use `mqtts://` with `auth_mode = "mtls"`: see [MQTT over TLS](docs/mqtt-tls.md) for the certificates and the broker's settings.
Any MQTT broker works as a relay for remote access: the app and the device talk through it with the end-to-end encrypted secure channel, so the broker never sees the state or the commands, and TLS and broker credentials are optional hardening. See [MQTT relay](docs/mqtt-relay.md).

To reach the broker over a cellular modem instead of WiFi, disable `[network.wifi]` and set the SIM's APN in `[network.lte]` (see [LTE](docs/lte.md)). Per-board settings live under `[hardware.esp]` / `[hardware.pc]`, including CAN buses (`[[hardware.<board>.can_buses]]`, where order determines `bus_id`) and BLE options. The `board` and `platform` values can be overridden with `--board` and `--platform`. To reverse engineer a car, `[network.can_logger] enabled = true` streams the CAN buses to SavvyCAN over WiFi (see [CAN bus](docs/can.md#savvycan-logging)). Hardware profiles in `hardware-profiles/` are ready-made pin/CAN setups for specific devices; anything set in `config.toml`, including `board`, wins over the profile.

Expand Down Expand Up @@ -96,7 +96,7 @@ The firmware is a Cargo workspace of independently compiled crates that cooperat
┌───────▼──────────────────▼──────────────┐
│ core-interface │
│ static Channels · Embassy tasks │
│ platform_id gating · BLE/MQTT routing │
│ platform_id gating · routing · Noise │
└─────────────────────────────────────────┘
```

Expand All @@ -107,7 +107,7 @@ The firmware is a Cargo workspace of independently compiled crates that cooperat
| `cars/*` | Vehicle logic: CAN decoding, command handling, state encoding |
| `xtask` | Build orchestrator: reads `config.toml`, generates `.app_build/`, invokes cargo |

Details: [Architecture](docs/architecture.md) · [BLE](docs/ble.md) · [CAN bus](docs/can.md) · [LAN direct](docs/lan.md) · [LTE](docs/lte.md) · [MQTT over TLS](docs/mqtt-tls.md) · [Vehicle commands](docs/commands.md)
Details: [Architecture](docs/architecture.md) · [BLE](docs/ble.md) · [CAN bus](docs/can.md) · [LAN direct](docs/lan.md) · [LTE](docs/lte.md) · [MQTT relay](docs/mqtt-relay.md) · [Vehicle commands](docs/commands.md)

## 📂 Project Structure

Expand Down
1 change: 0 additions & 1 deletion boards/esp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ mod hardware {
pub fn start(spawner: &embassy_executor::Spawner) {
status_leds::set_flag(status_leds::FLAG_POWER, true);
spawner.spawn(core_interface::process_ble_commands_task().unwrap());
spawner.spawn(core_interface::process_mqtt_commands_task().unwrap());
spawner.spawn(core_interface::route_responses_task().unwrap());
spawner.spawn(core_interface::publish_state_task().unwrap());
spawner.spawn(core_interface::publish_can_access_task().unwrap());
Expand Down
212 changes: 118 additions & 94 deletions boards/esp/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,21 @@
//! direct (`lan.rs`) runs on the WiFi stack.
//!
//! `mqtt_driver_task` connects to the MQTT broker over TCP on whichever stack it is
//! given (with TLS through MbedTLS for `mqtts://`, see `docs/mqtt-tls.md`), subscribes
//! to the command topic, and bridges the `MQTT_RX_CHANNEL` / `MQTT_TX_CHANNEL` channel
//! pair. It reconnects from scratch on any session failure.
//! given (with TLS through MbedTLS for `mqtts://`, see `docs/mqtt-relay.md`), subscribes
//! to the device's relay topics, and moves secure channel frames between the broker and
//! `core_interface`'s relay. It reconnects from scratch on any session failure.

#[cfg(feature = "hardware")]
mod hardware {
use alloc::string::String;
use alloc::vec::Vec;

use core_interface::{
MQTT_RX_CHANNEL, MQTT_STATE_TX, MQTT_TX_CHANNEL, MqttTls, Transport, proto,
};
use core_interface::MqttTls;
use embassy_net::{Runner, Stack, StackResources, dns::DnsQueryType, tcp::TcpSocket};
use esp_radio::wifi::sta::StationConfig;
use esp_radio::wifi::{
Config as WifiModeConfig, ControllerConfig as WifiControllerConfig,
Interface as WifiInterface, WifiController,
};
use prost::Message as _;
use rust_mqtt::{
Bytes,
buffer::AllocBuffer,
Expand Down Expand Up @@ -217,21 +213,27 @@ mod hardware {
}
}

/// Inner MQTT session logic. Authenticates, subscribes, then loops until an
/// error occurs. Returns `Err(())` on any protocol or IO fault so the caller
/// can reconnect.
/// One session with the broker for the relay (docs/mqtt-relay.md in the contracts):
/// connects with the device's client ID, subscribes to its device topics, then moves
/// secure channel frames both ways until an error, at which point it returns
/// `Err(())` so the caller reconnects. Nothing but frames is sent or accepted.
async fn run_mqtt_session<N: embedded_io_async::Read + embedded_io_async::Write>(
network: N,
client_id: &'static str,
cmd_topic: &'static str,
data_topic: &'static str,
username: &'static str,
password: &'static str,
) -> Result<(), ()> {
use embassy_time::{Duration, Instant};

let (Some(client_id), Some(filter)) = (
core_interface::relay_client_id(),
core_interface::relay_subscribe_filter(),
) else {
log::warn!("MQTT: no device identity yet");
return Err(());
};

let mut buffer = AllocBuffer;
let mut client = Client::<_, _, 1, 1, 1, 0>::new(&mut buffer);
let mut client = Client::<_, _, 1, 4, 4, 0>::new(&mut buffer);

let mut connect_opts = ConnectOptions::new().clean_start();
if !username.is_empty() {
Expand All @@ -244,94 +246,129 @@ mod hardware {
.connect(
network,
&connect_opts,
Some(MqttString::from_str_unchecked(client_id)),
Some(MqttString::from_str_unchecked(&client_id)),
)
.await
.map_err(|e| {
log::warn!("MQTT: connect failed: {:?}", e);
})?;

log::info!("MQTT: connected, subscribing to '{}'", cmd_topic);
log::info!(
"MQTT: connected as '{}', subscribing to '{}'",
client_id,
filter
);

let filter = TopicFilter::new_unchecked(MqttString::from_str_unchecked(cmd_topic));
let topic_filter = TopicFilter::new_unchecked(MqttString::from_str_unchecked(&filter));
client
.subscribe(filter, SubscriptionOptions::new())
.subscribe(topic_filter, SubscriptionOptions::new().at_least_once())
.await
.map_err(|e| {
log::warn!("MQTT: subscribe failed: {:?}", e);
})?;

log::info!("MQTT: ready");
core_interface::set_link_up(Transport::Mqtt, true);

let keepalive = Duration::from_secs(55);
let mut last_ping = Instant::now();
let data_topic_name = TopicName::new_unchecked(MqttString::from_str_unchecked(data_topic));

loop {
// Responses and system state first, then the newest vehicle state.
while let Some(msg) = MQTT_TX_CHANNEL
.try_receive()
.ok()
.or_else(|| MQTT_STATE_TX.try_take())
{
let mut buf = Vec::<u8>::new();
if msg.encode(&mut buf).is_ok() {
let t = data_topic_name.as_borrowed();
let pub_opts = PublicationOptions::new(TopicReference::Name(t));
client
.publish(&pub_opts, Bytes::Borrowed(buf.as_slice()))
let Some(relay) = core_interface::relay_connect() else {
return Err(());
};
log::info!("MQTT: relay ready");

let result = async {
let keepalive = Duration::from_secs(55);
let mut last_ping = Instant::now();
// A frame the client couldn't take yet (too many publications waiting for
// their PUBACK): sent once the broker acknowledges one.
let mut pending: Option<core_interface::RelayFrame> = None;
loop {
// Publish what is ready before polling inbound: responses and system
// state first, then the vehicle state, as the relay decides.
loop {
let Some(frame) = pending.take().or_else(|| {
core_interface::relay_try_next_frame(relay, Instant::now().as_millis())
}) else {
break;
};
let topic =
TopicName::new_unchecked(MqttString::from_str_unchecked(&frame.topic));
let pub_opts =
PublicationOptions::new(TopicReference::Name(topic)).at_least_once();
match client
.publish(&pub_opts, Bytes::Borrowed(frame.frame.as_slice()))
.await
.map_err(|e| {
{
Ok(_) => {}
Err(MqttError::SendQuotaExceeded | MqttError::SessionBuffer) => {
pending = Some(frame);
break;
}
Err(e) => {
log::warn!("MQTT: publish failed: {:?}", e);
})?;
return Err(());
}
}
}
}

if last_ping.elapsed() >= keepalive {
client.ping().await.map_err(|e| {
log::warn!("MQTT: ping failed: {:?}", e);
})?;
last_ping = Instant::now();
}
if last_ping.elapsed() >= keepalive {
client.ping().await.map_err(|e| {
log::warn!("MQTT: ping failed: {:?}", e);
})?;
last_ping = Instant::now();
}

let poll_result =
embassy_time::with_timeout(Duration::from_millis(100), client.poll()).await;

match poll_result {
Err(_timeout) => continue,
Ok(Err(e)) => {
log::warn!("MQTT: poll error: {:?}", e);
// abort() panics if the broker sent a clean DISCONNECT
// (e.g. SessionTakenOver) because the network is still in
// Ok state. Only call it for IO/protocol errors.
if !matches!(e, MqttError::Disconnect { .. }) {
client.abort().await;
let poll_result =
embassy_time::with_timeout(Duration::from_millis(100), client.poll()).await;

match poll_result {
Err(_timeout) => continue,
Ok(Err(e)) => {
log::warn!("MQTT: poll error: {:?}", e);
// abort() panics if the broker sent a clean DISCONNECT
// (e.g. SessionTakenOver) because the network is still in
// Ok state. Only call it for IO/protocol errors.
if !matches!(e, MqttError::Disconnect { .. }) {
client.abort().await;
}
return Err(());
}
return Err(());
}
Ok(Ok(Event::Publish(p))) => {
if p.topic.as_ref().as_str() == cmd_topic {
let payload = p.message.as_bytes();
if let Ok(msg) = proto::AppToDevice::decode(payload) {
// Use try_send to avoid blocking here. If we blocked on
// MQTT_RX_CHANNEL.send().await while downstream tasks are
// simultaneously blocked on BASIC_CMD_CHANNEL and
// CMD_RESP_CHANNEL, route_responses_task would be stuck
// trying to send to MQTT_TX_CHANNEL — which we can't drain
// because we're blocked. That forms a deadlock cycle.
// Dropping one inbound command under back-pressure is safe;
// the app can retry. What we must never do is stall the
// outbound drain loop.
if MQTT_RX_CHANNEL.try_send(msg).is_err() {
log::warn!("MQTT: RX channel full, dropping inbound command");
Ok(Ok(Event::Publish(p))) => {
// Never blocks on a downstream queue: the dispatcher answers
// through the session's queue with try_send (see
// docs/architecture.md).
let topic = String::from(p.topic.as_ref().as_str());
let payload = p.message.as_bytes().to_vec();
drop(p);
let reply =
core_interface::relay_receive_frame(relay, &topic, &payload).await;
if let Some(reply) = reply {
let name = TopicName::new_unchecked(MqttString::from_str_unchecked(
&reply.topic,
));
let pub_opts =
PublicationOptions::new(TopicReference::Name(name)).at_least_once();
match client
.publish(&pub_opts, Bytes::Borrowed(reply.frame.as_slice()))
.await
{
Ok(_) => {}
// The client handshakes again after its timeout.
Err(MqttError::SendQuotaExceeded | MqttError::SessionBuffer) => {
log::warn!(
"MQTT: too many publications in flight, reply dropped"
);
}
Err(e) => {
log::warn!("MQTT: publish failed: {:?}", e);
return Err(());
}
}
}
}
Ok(Ok(_)) => {}
}
Ok(Ok(_)) => {}
}
}
.await;
core_interface::relay_disconnect(relay);
result
}

/// Public MQTT driver task. Waits for the network, resolves the broker, opens a TCP connection to the
Expand All @@ -341,9 +378,6 @@ mod hardware {
stack: &'static NetStack,
broker_host: &'static str,
broker_port: u16,
client_id: &'static str,
cmd_topic: &'static str,
data_topic: &'static str,
username: &'static str,
password: &'static str,
tls: Option<MqttTls>,
Expand Down Expand Up @@ -400,15 +434,10 @@ mod hardware {
}

#[cfg(not(feature = "mqtt-tls"))]
let result =
run_mqtt_session(socket, client_id, cmd_topic, data_topic, username, password)
.await;
let result = run_mqtt_session(socket, username, password).await;
#[cfg(feature = "mqtt-tls")]
let result = match &tls {
None => {
run_mqtt_session(socket, client_id, cmd_topic, data_topic, username, password)
.await
}
None => run_mqtt_session(socket, username, password).await,
Some(setup) => {
match mbedtls_rs::Session::new(
setup.tls.reference(),
Expand All @@ -433,10 +462,7 @@ mod hardware {
"MQTT: TLS established, {} B heap free",
esp_alloc::HEAP.free()
);
run_mqtt_session(
session, client_id, cmd_topic, data_topic, username, password,
)
.await
run_mqtt_session(session, username, password).await
}
},
}
Expand All @@ -445,8 +471,6 @@ mod hardware {
if result.is_err() {
log::info!("MQTT: session ended, reconnecting in 5s");
}
// Drops what was queued for this session instead of sending it on the next.
core_interface::set_link_up(Transport::Mqtt, false);
Timer::after(Duration::from_secs(5)).await;
}
}
Expand Down
Loading