Skip to content

Commit

Permalink
Examples
Browse files Browse the repository at this point in the history
  • Loading branch information
ivmarkov committed Jun 2, 2024
1 parent 93b4467 commit 1193487
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 65 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ edge-nal-std = { version = "0.2", optional = true }
[dev-dependencies]
static_cell = "2.1"
futures-lite = "1"
async-compat = "0.2"
env_logger = "0.11"

[[example]]
name = "light_eth"
Expand Down
84 changes: 19 additions & 65 deletions examples/light.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,78 +11,39 @@ use core::pin::pin;
use embassy_futures::select::select;
use embassy_time::{Duration, Timer};

use esp_idf_matter::{init_async_io, EspKvBlobStore, EspModem, EspPersist, EspWifiBleMatterStack};

use esp_idf_svc::eventloop::EspSystemEventLoop;
use esp_idf_svc::hal::peripherals::Peripherals;
use esp_idf_svc::hal::task::block_on;
use esp_idf_svc::log::EspLogger;
use esp_idf_svc::nvs::EspDefaultNvsPartition;
use esp_idf_svc::timer::EspTaskTimerService;

use log::{error, info};
use log::info;

use rs_matter::data_model::cluster_basic_information::BasicInfoConfig;
use rs_matter::data_model::cluster_on_off;
use rs_matter::data_model::device_types::DEV_TYPE_ON_OFF_LIGHT;
use rs_matter::data_model::objects::{Endpoint, HandlerCompat, Node};
use rs_matter::data_model::system_model::descriptor;
use rs_matter::error::Error;
use rs_matter::secure_channel::spake2p::VerifierData;
use rs_matter::utils::select::Coalesce;
use rs_matter::utils::std_mutex::StdRawMutex;
use rs_matter::CommissioningData;

use rs_matter_stack::modem::DummyLinuxModem;
use rs_matter_stack::persist::DummyPersist;

use rs_matter_stack::WifiBleMatterStack;
use static_cell::ConstStaticCell;

#[path = "dev_att/dev_att.rs"]
mod dev_att;

fn main() -> Result<(), anyhow::Error> {
EspLogger::initialize_default();
fn main() -> Result<(), Error> {
env_logger::init_from_env(
env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"),
);

info!("Starting...");

// Run in a higher-prio thread to avoid issues with `async-io` getting
// confused by the low priority of the ESP IDF main task
// Also allocate a very large stack (for now) as `rs-matter` futures do occupy quite some space
let thread = std::thread::Builder::new()
.stack_size(70 * 1024)
.spawn(|| {
// Eagerly initialize `async-io` to minimize the risk of stack blowups later on
init_async_io()?;

run()
})
.unwrap();

thread.join().unwrap()
}

#[inline(never)]
#[cold]
fn run() -> Result<(), anyhow::Error> {
let result = block_on(matter());

if let Err(e) = &result {
error!("Matter aborted execution with error: {:?}", e);
}
{
info!("Matter finished execution successfully");
}

result
}

async fn matter() -> Result<(), anyhow::Error> {
// Take the Matter stack (can be done only once),
// as we'll run it in this thread
let stack = MATTER_STACK.take();

// Take some generic ESP-IDF stuff we'll need later
let sysloop = EspSystemEventLoop::take()?;
let timers = EspTaskTimerService::new()?;
let nvs = EspDefaultNvsPartition::take()?;
let peripherals = Peripherals::take()?;

// Our "light" on-off cluster.
// Can be anything implementing `rs_matter::data_model::AsyncHandler`
let on_off = cluster_on_off::OnOffCluster::new(*stack.matter().borrow());
Expand All @@ -109,15 +70,8 @@ async fn matter() -> Result<(), anyhow::Error> {
// Using `pin!` is completely optional, but saves some memory due to `rustc`
// not being very intelligent w.r.t. stack usage in async functions
let mut matter = pin!(stack.run(
// The Matter stack needs a persister to store its state
// `EspPersist`+`EspKvBlobStore` saves to a user-supplied NVS partition
// under namespace `esp-idf-matter`
EspPersist::new_wifi_ble(EspKvBlobStore::new_default(nvs.clone())?, stack),
// The Matter stack needs the BT/Wifi modem peripheral - and in general -
// the Bluetooth / Wifi connections will be managed by the Matter stack itself
// For finer-grained control, call `MatterStack::is_commissioned`,
// `MatterStack::commission` and `MatterStack::operate`
EspModem::new(peripherals.modem, sysloop, timers, nvs, stack),
DummyPersist,
DummyLinuxModem::default(),
// Hard-coded for demo purposes
CommissioningData {
verifier: VerifierData::new_with_pw(123456, *stack.matter().borrow()),
Expand Down Expand Up @@ -149,16 +103,16 @@ async fn matter() -> Result<(), anyhow::Error> {
});

// Schedule the Matter run & the device loop together
select(&mut matter, &mut device).coalesce().await?;

Ok(())
futures_lite::future::block_on(async_compat::Compat::new(
select(&mut matter, &mut device).coalesce(),
))
}

/// The Matter stack is allocated statically to avoid
/// program stack blowups.
/// It is also a mandatory requirement when the `WifiBle` stack variation is used.
static MATTER_STACK: ConstStaticCell<EspWifiBleMatterStack<()>> =
ConstStaticCell::new(EspWifiBleMatterStack::new_default(
static MATTER_STACK: ConstStaticCell<WifiBleMatterStack<StdRawMutex, ()>> =
ConstStaticCell::new(WifiBleMatterStack::new_default(
&BasicInfoConfig {
vid: 0xFFF1,
pid: 0x8000,
Expand All @@ -181,7 +135,7 @@ const LIGHT_ENDPOINT_ID: u16 = 1;
const NODE: Node = Node {
id: 0,
endpoints: &[
EspWifiBleMatterStack::<()>::root_metadata(),
WifiBleMatterStack::<StdRawMutex, ()>::root_metadata(),
Endpoint {
id: LIGHT_ENDPOINT_ID,
device_type: DEV_TYPE_ON_OFF_LIGHT,
Expand Down
4 changes: 4 additions & 0 deletions examples/light_eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ use static_cell::ConstStaticCell;
mod dev_att;

fn main() -> Result<(), Error> {
env_logger::init_from_env(
env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"),
);

info!("Starting...");

// Take the Matter stack (can be done only once),
Expand Down

0 comments on commit 1193487

Please sign in to comment.