Watch
0
0
Fork
You've already forked esp32-c_its-companion
0

Compare commits

..
Author SHA1 Message Date
Jannik Beyerstedt
0b055900cf WIP Add battery level readout and publish on BLE
TODO: show on display when low battery
TODO: ADC readout is not plausible
2026-09-30 09:36:57 +02:00
11 changed files with 982 additions and 245260 deletions

View file

@ -1,2 +1,2 @@
stack-size-threshold = 1024
doc-valid-idents = ["WiFi", "GeoNetworking", "QoS", ".."]
doc-valid-idents = ["WiFi", "GeoNetworking", "QoS", "LiPo", ".."]

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{
"board": {
"active_layer": 0,
"active_layer": 25,
"active_layer_preset": "",
"auto_track_width": true,
"hidden_netclasses": [],

View file

@ -236,7 +236,6 @@
{
"td_allow_use_two_tracks": true,
"td_curve_segcount": 0,
"td_enabled": false,
"td_height_ratio": 1.0,
"td_length_ratio": 0.5,
"td_maxheight": 2.0,
@ -248,7 +247,6 @@
{
"td_allow_use_two_tracks": true,
"td_curve_segcount": 0,
"td_enabled": false,
"td_height_ratio": 1.0,
"td_length_ratio": 0.5,
"td_maxheight": 2.0,
@ -260,7 +258,6 @@
{
"td_allow_use_two_tracks": true,
"td_curve_segcount": 0,
"td_enabled": false,
"td_height_ratio": 1.0,
"td_length_ratio": 0.5,
"td_maxheight": 2.0,
@ -314,7 +311,7 @@
"internal_id": "",
"mfg": "",
"mpn": "",
"sch_revision": "v1.1"
"sch_revision": "v1.0"
},
"layer_pairs": [],
"layer_presets": [],
@ -543,7 +540,6 @@
"pin_to_pin": "warning",
"power_pin_not_driven": "error",
"same_local_global_label": "warning",
"same_local_global_power": "warning",
"similar_label_and_power": "warning",
"similar_labels": "warning",
"similar_power": "warning",
@ -599,8 +595,8 @@
"meta": {
"version": 5
},
"net_colors": {},
"netclass_assignments": {},
"net_colors": null,
"netclass_assignments": null,
"netclass_patterns": [
{
"netclass": "Power",
@ -626,7 +622,7 @@
"netlist": "",
"plot": "",
"specctra_dsn": "",
"step": "../housing/c_its-companion-v1.1.step",
"step": "../housing/c_its-companion-v1.0.step",
"vrml": ""
},
"page_layout_descr_file": ""
@ -761,7 +757,7 @@
"uuid": "9ad468b0-d7e4-4d4a-b652-c4a81a952e30"
}
],
"used_designators": "#FLG1-3,#PWR1-11,C1,H1-4,J1-2,SW1,TP1-5,U1-2",
"used_designators": "H1-4,C1,#PWR1-11,J1-2,SW1,TP1-5,U1-2,#FLG1-3",
"variants": []
},
"sheets": [

View file

@ -6,8 +6,8 @@
(paper "A4" portrait)
(title_block
(title "C-ITS Companion")
(date "2026-11-02")
(rev "v1.1")
(date "2026-09-06")
(rev "v1.0")
(company "jtbx")
)
(lib_symbols
@ -4682,8 +4682,7 @@
)
(symbol
(lib_id "Connector:Conn_01x02_Socket")
(at 38.1 165.1 0)
(mirror y)
(at 38.1 167.64 180)
(unit 1)
(body_style 1)
(exclude_from_sim no)
@ -4691,9 +4690,10 @@
(on_board yes)
(in_pos_files yes)
(dnp no)
(fields_autoplaced yes)
(uuid "892402cc-04d7-4ef7-82b9-1d18ac58ae6e")
(property "Reference" "J2"
(at 38.735 172.72 0)
(at 38.735 160.02 0)
(show_name no)
(do_not_autoplace no)
(effects
@ -4703,7 +4703,7 @@
)
)
(property "Value" "Battery"
(at 38.735 170.18 0)
(at 38.735 162.56 0)
(show_name no)
(do_not_autoplace no)
(effects
@ -4712,8 +4712,8 @@
)
)
)
(property "Footprint" "Connector_JST:JST_PH_S2B-PH-K_1x02_P2.00mm_Horizontal"
(at 38.1 165.1 0)
(property "Footprint" "Connector_PinHeader_2.54mm:PinHeader_1x02_P2.54mm_Horizontal"
(at 38.1 167.64 0)
(hide yes)
(show_name no)
(do_not_autoplace no)
@ -4724,7 +4724,7 @@
)
)
(property "Datasheet" ""
(at 38.1 165.1 0)
(at 38.1 167.64 0)
(hide yes)
(show_name no)
(do_not_autoplace no)
@ -4735,7 +4735,7 @@
)
)
(property "Description" "Generic connector, single row, 01x02, script generated"
(at 38.1 165.1 0)
(at 38.1 167.64 0)
(hide yes)
(show_name no)
(do_not_autoplace no)

File diff suppressed because it is too large Load diff

View file

@ -23,6 +23,8 @@ pub static TX_DATA: Mutex<RefCell<Option<ArrayQueue<BleSendable>>>> =
pub static RX_DATA: Mutex<RefCell<Option<io::msg::PositionState>>> = Mutex::new(RefCell::new(None));
pub enum BleSendable {
BatteryLevel(u8),
#[cfg(feature = "cam")]
CamRaw(io::msg::RawMsgRx),
#[cfg(feature = "cam")]
@ -87,6 +89,7 @@ pub fn string_as_padded_buf(value: &str, length: usize) -> alloc::vec::Vec<u8> {
struct Server {
c_its_events: CITSEvents,
device_info_service: DeviceInfoService,
battery_service: BatteryService,
}
#[gatt_service(uuid = service::DEVICE_INFORMATION)]
@ -108,6 +111,15 @@ struct DeviceInfoService {
sw_revision: [u8; DIS_SW_REVISION_MAX_LEN],
}
#[gatt_service(uuid = service::BATTERY)]
struct BatteryService {
/// Battery Level
#[descriptor(uuid = descriptors::VALID_RANGE, read, value = [0, 100])]
#[descriptor(uuid = descriptors::MEASUREMENT_DESCRIPTION, name = "main", read, value = "Battery Level", type = &'static str)]
#[characteristic(uuid = characteristic::BATTERY_LEVEL, read, notify, value = 0)]
level: u8,
}
#[gatt_service(uuid = "c0b70000-d4f4-4000-ada8-f99a02ee315c")]
struct CITSEvents {
#[descriptor(uuid = descriptors::MEASUREMENT_DESCRIPTION, name = "Position", read, value = "PositionState proto msg", type = &'static str)]
@ -214,8 +226,11 @@ pub async fn run(
// advertise and run update logic
let _ = embassy_futures::join::join(ble_task(runner), async {
loop {
match advertise(&mut peripheral, &server, &short_name).await {
Ok(conn) => {
// run advertisement and set data until a client connects
let a = advertise(&mut peripheral, &server, &short_name);
let b = data_update_task(&server);
match embassy_futures::select::select(a, b).await {
embassy_futures::select::Either::First(Ok(conn)) => {
info!("BLE: New client connected");
// set up tasks when the connection is established to a central, so they don't run when no one is connected.
@ -230,15 +245,17 @@ pub async fn run(
let _ = value_ref.replace(false);
});
}
Err(e) => {
embassy_futures::select::Either::First(Err(e)) => {
panic!("BLE ADV: fatal error: {e:?}");
}
_ => {}
}
}
})
.await;
}
/// Queues data for BLE notification (only when client is connected)
pub fn update(payload: BleSendable) {
critical_section::with(|cs| {
// only add to queue when someone is connected
@ -254,6 +271,24 @@ pub fn update(payload: BleSendable) {
});
}
/// Queues data for characteristic update (may notify a connected client)
///
/// This can be used instead of `update()`, but will always write the data to the characteristic even when no client is connected.
/// So a newly connected client will be able to read an up to date value at connection and not just when new data was received.
///
/// This is useful for (device) information which is not time-critical (like received V2X data).
pub fn set(payload: BleSendable) {
critical_section::with(|cs| {
let queue_rc = TX_DATA.borrow(cs).borrow();
// unwrap is fine b/c we stored something in it before
let queue = queue_rc.as_ref().unwrap();
if queue.push(payload).is_err() {
log::error!("BLE TX queue is full");
}
});
}
/// Create an advertiser to use to connect to a BLE Central, and wait for it to connect.
async fn advertise<'values, 'server, C: Controller>(
peripheral: &mut Peripheral<'values, C, DefaultPacketPool>,
@ -375,6 +410,12 @@ async fn publishing_task<P: PacketPool>(server: &Server<'_>, conn: &GattConnecti
});
match new_data {
Some(BleSendable::BatteryLevel(value)) => {
if let Err(err) = server.battery_service.level.notify(conn, &value).await {
warn!("BLE: failed notifying connection of new battery level: {err:?}");
}
}
#[cfg(feature = "cam")]
Some(BleSendable::Cam(cam_event)) => match cam_event.serialize_ble_proto() {
Ok(value) => {
@ -476,6 +517,33 @@ async fn publishing_task<P: PacketPool>(server: &Server<'_>, conn: &GattConnecti
}
}
async fn data_update_task(server: &Server<'_>) {
loop {
embassy_time::Timer::after(embassy_time::Duration::from_millis(10)).await;
let mut new_data = None;
critical_section::with(|cs| {
let queue_rc = TX_DATA.borrow(cs).borrow();
// unwrap is fine b/c we stored something in it before
let queue = queue_rc.as_ref().unwrap();
if let Some(data) = queue.pop() {
new_data = Some(data);
}
});
#[allow(clippy::single_match)]
match new_data {
Some(BleSendable::BatteryLevel(value)) => {
if let Err(err) = server.battery_service.level.set(server, &value) {
warn!("BLE: failed setting new battery level: {err:?}");
}
}
_ => {}
}
}
}
async fn send_raw_notify<P: PacketPool>(
server: &Server<'_>,
conn: &GattConnection<'_, '_, P>,

View file

@ -59,7 +59,9 @@ mod screen;
#[cfg(feature = "gnss_ubx")]
mod ubx;
mod util;
mod xiao;
const BAT_UPDATE_INTERVAL: esp_hal::time::Duration = esp_hal::time::Duration::from_secs(30);
const WIFI_CHANNEL: radio::Channel = 180;
const WIFI_TXPOWER: i8 = 10; // dBm, 2..20
#[cfg(feature = "spat")]
@ -144,6 +146,9 @@ async fn main(spawner: Spawner) -> ! {
info!("Embassy initialized!");
// Setup battery voltage readout (GPIO6 as input and GPIO26 as enable)
let mut battery = xiao::Battery::new(peripherals.ADC1, peripherals.GPIO6, peripherals.GPIO26);
// Setup ST7789 screen
// SCL: D8/ GPIO8 (SPI_SCK)
// SDA: D10/ GPIO10 (SPI_MOSI)
@ -284,6 +289,13 @@ async fn main(spawner: Spawner) -> ! {
#[cfg(feature = "_gnss")]
info!("GNSS task started, waiting for GNSS fix...");
// Setup main loop
let (bat_percent, bat_millivolt) = battery.read();
log::info!("Battery: {bat_millivolt} mV, {bat_percent} %");
#[cfg(feature = "ble")]
ble::set(ble::BleSendable::BatteryLevel(bat_percent));
let mut last_bat_update = esp_hal::time::Instant::now();
#[cfg(any(feature = "cam_tx", feature = "uart"))]
let (mut seq_no, mac_bytes) = {
// unwrap is fine since [`esp_hal::efuse::MacAddress`] is just an `[u8; 6]`
@ -626,6 +638,17 @@ async fn main(spawner: Spawner) -> ! {
// maintenance
state.prune();
let cpu_now = esp_hal::time::Instant::now();
if last_bat_update + BAT_UPDATE_INTERVAL < cpu_now {
let (bat_percent, bat_millivolt) = battery.read();
log::info!("Battery: {bat_millivolt} mV, {bat_percent} %");
#[cfg(feature = "ble")]
ble::set(ble::BleSendable::BatteryLevel(bat_percent));
last_bat_update = cpu_now;
}
}
}

94
src/xiao.rs Normal file
View file

@ -0,0 +1,94 @@
//! XIAO ESP32-C5 Helpers
use esp_hal::analog::adc;
use esp_hal::gpio;
use log::debug;
type AdcPeripheral<'a> = esp_hal::peripherals::ADC1<'a>;
pub struct Battery<'a, IoAdc>
where
IoAdc: adc::AdcChannel + gpio::AnalogPin,
{
// using `AdcCalCurve` here gives readings in millivolts
adc_pin: adc::AdcPin<IoAdc, AdcPeripheral<'a>, adc::AdcCalCurve<AdcPeripheral<'a>>>,
adc: adc::Adc<'a, AdcPeripheral<'a>, esp_hal::Blocking>,
}
impl<'a, IoAdc> Battery<'a, IoAdc>
where
IoAdc: adc::AdcChannel + gpio::AnalogPin,
{
pub fn new<IoEnable: gpio::OutputPin>(
adc_periph: AdcPeripheral<'a>,
adc_pin: IoAdc,
enable_pin: IoEnable,
) -> Self {
// enable battery voltage readout
let _ = gpio::Output::new(enable_pin, gpio::Level::High, gpio::OutputConfig::default());
// configure ADC
let mut adc_config = adc::AdcConfig::new();
let adc_pin = adc_config.enable_pin_with_cal(adc_pin, adc::Attenuation::_11dB);
let adc = adc::Adc::new(adc_periph, adc_config);
Self { adc_pin, adc }
}
/// Reads from ADC and returns battery voltage in millivolts
pub fn read_millivolts(&mut self) -> u16 {
// average over 16 samples
let mut accu = 0u16;
for _ in 0..16 {
let val = loop {
match self.adc.read_oneshot(&mut self.adc_pin) {
Ok(value) => break value,
Err(err) => {
debug!("Failed to read from ADC: {err:?}");
}
}
};
accu += val;
}
let adc_val = accu / 16;
// convert to battery voltage: 1:2 voltage divider
adc_val * 2
}
/// Returns estimated battery charge state in percent
#[allow(unused)]
pub fn read_percent(&mut self) -> u8 {
Self::millivolts_to_percent(self.read_millivolts())
}
/// Returns estimated battery charge state in percent and millivolts
pub fn read(&mut self) -> (u8, u16) {
let millivolt = self.read_millivolts();
let percent = Self::millivolts_to_percent(millivolt);
(percent, millivolt)
}
/// Converts single cell LiPo battery voltage to charge state in percent
///
/// Note: The implementation is a drastically simplified linear estimation.
/// This is known to be insufficient for an actual state of charge, but should be fine for now.
pub fn millivolts_to_percent(millivolt: u16) -> u8 {
let (full_mv, empty_mv) = (4200, 3270); // 100% to 0% SoC
if millivolt < empty_mv {
0
} else if millivolt >= full_mv {
100
} else {
let percent = i32::from(millivolt - empty_mv) * 100 / i32::from(full_mv - empty_mv);
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let result = percent as u8;
result
}
}
}