Skip to content

Commit

Permalink
In place initialization of the Matter object, the buffers and subsc…
Browse files Browse the repository at this point in the history
…riptions (#198)

* Give axes to transport mgr RX and TX buffers

* In-place initialization

Update the example; more ergonomic init of UnsafeCell and MaybeUninit

More constructors

In-place ctr for the built-in Mdns too

enable no_std for pinned-init

In-place init for BTP

Re-export pinned-init as its API is unstable; document

Initializer for GATT peripheral

PAtch pinned-init with a forked version that does not need nightly

zeroed in pinned-init master no longer has the E generic

Use upstream pinned-init

In-place initializer for State

Stop pretending that ContainerInit has any other use case besides UnsafeCell

Maybe and other extensions

(Code review feedbacmoveplit storage and sync types into their dedicated modules

Fix astro and zeroconf

Restore a larger stack for now, until in-place-init is fully utilized

Remove commented out code
  • Loading branch information
ivmarkov authored Sep 14, 2024
1 parent 7c1b2a1 commit 1e0117b
Show file tree
Hide file tree
Showing 58 changed files with 4,162 additions and 347 deletions.
62 changes: 37 additions & 25 deletions examples/onoff_light/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,36 @@ use rs_matter::persist::Psm;
use rs_matter::respond::DefaultResponder;
use rs_matter::secure_channel::spake2p::VerifierData;
use rs_matter::transport::core::MATTER_SOCKET_BIND_ADDR;
use rs_matter::utils::buf::PooledBuffers;
use rs_matter::utils::init::InitMaybeUninit;
use rs_matter::utils::select::Coalesce;
use rs_matter::utils::storage::pooled::PooledBuffers;
use rs_matter::MATTER_PORT;
use static_cell::StaticCell;

mod dev_att;

static DEV_DET: BasicInfoConfig = BasicInfoConfig {
vid: 0xFFF1,
pid: 0x8000,
hw_ver: 2,
sw_ver: 1,
sw_ver_str: "1",
serial_no: "aabbccdd",
device_name: "OnOff Light",
product_name: "Light123",
vendor_name: "Vendor PQR",
};

static DEV_ATT: dev_att::HardCodedDevAtt = dev_att::HardCodedDevAtt::new();

static MATTER: StaticCell<Matter> = StaticCell::new();

static BUFFERS: StaticCell<PooledBuffers<10, NoopRawMutex, IMBuffer>> = StaticCell::new();

static SUBSCRIPTIONS: StaticCell<Subscriptions<3>> = StaticCell::new();

static PSM: StaticCell<Psm<4096>> = StaticCell::new();

fn main() -> Result<(), Error> {
let thread = std::thread::Builder::new()
// Increase the stack size until the example can work without stack blowups.
Expand All @@ -54,7 +78,7 @@ fn main() -> Result<(), Error> {
// e.g., an opt-level of "0" will require a several times' larger stack.
//
// Optimizing/lowering `rs-matter` memory consumption is an ongoing topic.
.stack_size(95 * 1024)
.stack_size(65 * 1024)
.spawn(run)
.unwrap();

Expand All @@ -72,51 +96,37 @@ fn run() -> Result<(), Error> {
core::mem::size_of::<PooledBuffers<10, NoopRawMutex, IMBuffer>>()
);

let dev_det = BasicInfoConfig {
vid: 0xFFF1,
pid: 0x8000,
hw_ver: 2,
sw_ver: 1,
sw_ver_str: "1",
serial_no: "aabbccdd",
device_name: "OnOff Light",
product_name: "Light123",
vendor_name: "Vendor PQR",
};

let dev_att = dev_att::HardCodedDevAtt::new();

let matter = Matter::new(
&dev_det,
&dev_att,
let matter = MATTER.uninit().init_with(Matter::init(
&DEV_DET,
&DEV_ATT,
// NOTE:
// For `no_std` environments, provide your own epoch and rand functions here
MdnsService::Builtin,
rs_matter::utils::epoch::sys_epoch,
rs_matter::utils::rand::sys_rand,
MATTER_PORT,
);
));

matter.initialize_transport_buffers()?;

info!("Matter initialized");

let buffers = PooledBuffers::<10, NoopRawMutex, _>::new(0);
let buffers = BUFFERS.uninit().init_with(PooledBuffers::init(0));

info!("IM buffers initialized");

let mut mdns = pin!(run_mdns(&matter));

let on_off = cluster_on_off::OnOffCluster::new(Dataver::new_rand(matter.rand()));

let subscriptions = Subscriptions::<3>::new();
let subscriptions = SUBSCRIPTIONS.uninit().init_with(Subscriptions::init());

// Assemble our Data Model handler by composing the predefined Root Endpoint handler with our custom On/Off clusters
let dm_handler = HandlerCompat(dm_handler(&matter, &on_off));

// Create a default responder capable of handling up to 3 subscriptions
// All other subscription requests will be turned down with "resource exhausted"
let responder = DefaultResponder::new(&matter, &buffers, &subscriptions, dm_handler);
let responder = DefaultResponder::new(&matter, buffers, &subscriptions, dm_handler);
info!(
"Responder memory: Responder={}B, Runner={}B",
core::mem::size_of_val(&responder),
Expand Down Expand Up @@ -161,8 +171,10 @@ fn run() -> Result<(), Error> {

// NOTE:
// Replace with your own persister for e.g. `no_std` environments
let mut psm = Psm::new(&matter, std::env::temp_dir().join("rs-matter"))?;
let mut persist = pin!(psm.run());

let psm = PSM.uninit().init_with(Psm::init());

let mut persist = pin!(psm.run(std::env::temp_dir().join("rs-matter"), &matter));

// Combine all async tasks in a single one
let all = select4(
Expand Down
2 changes: 1 addition & 1 deletion examples/onoff_light_bt/src/comm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use rs_matter::interaction_model::core::IMStatusCode;
use rs_matter::interaction_model::messages::ib::Status;
use rs_matter::tlv::{FromTLV, OctetStr, TLVElement};
use rs_matter::transport::exchange::Exchange;
use rs_matter::utils::notification::Notification;
use rs_matter::utils::sync::Notification;

/// A _fake_ cluster implementing the Matter Network Commissioning Cluster
/// for managing WiFi networks.
Expand Down
9 changes: 4 additions & 5 deletions examples/onoff_light_bt/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,9 @@ use rs_matter::respond::DefaultResponder;
use rs_matter::secure_channel::spake2p::VerifierData;
use rs_matter::transport::core::MATTER_SOCKET_BIND_ADDR;
use rs_matter::transport::network::btp::{Btp, BtpContext};
use rs_matter::utils::buf::PooledBuffers;
use rs_matter::utils::notification::Notification;
use rs_matter::utils::select::Coalesce;
use rs_matter::utils::std_mutex::StdRawMutex;
use rs_matter::utils::storage::pooled::PooledBuffers;
use rs_matter::utils::sync::{blocking::raw::StdRawMutex, Notification};
use rs_matter::MATTER_PORT;

mod comm;
Expand Down Expand Up @@ -182,8 +181,8 @@ fn run() -> Result<(), Error> {

// NOTE:
// Replace with your own persister for e.g. `no_std` environments
let mut psm = Psm::new(&matter, std::env::temp_dir().join("rs-matter"))?;
let mut persist = pin!(psm.run());
let mut psm: Psm<4096> = Psm::new();
let mut persist = pin!(psm.run(std::env::temp_dir().join("rs-matter"), &matter));

if !matter.is_commissioned() {
// Not commissioned yet, start commissioning first
Expand Down
2 changes: 2 additions & 0 deletions rs-matter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ domain = { version = "0.10", default-features = false, features = ["heapless"] }
portable-atomic = "1"
qrcodegen-no-heap = "1.8"
scopeguard = { version = "1", default-features = false }
pinned-init = { version = "0.0.8", default-features = false }

# crypto
openssl = { version = "0.10", optional = true }
Expand Down Expand Up @@ -83,6 +84,7 @@ env_logger = "0.11"
nix = { version = "0.27", features = ["net"] }
futures-lite = "2"
async-channel = "2"
static_cell = "2"

[[example]]
name = "onoff_light"
Expand Down
41 changes: 27 additions & 14 deletions rs-matter/src/acl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,22 @@
* limitations under the License.
*/

use core::{cell::RefCell, fmt::Display, num::NonZeroU8};

use crate::{
data_model::objects::{Access, ClusterId, EndptId, Privilege},
error::{Error, ErrorCode},
fabric,
interaction_model::messages::GenericPath,
tlv::{self, FromTLV, Nullable, TLVElement, TLVList, TLVWriter, TagType, ToTLV},
transport::session::{Session, SessionMode, MAX_CAT_IDS_PER_NOC},
utils::writebuf::WriteBuf,
};
use core::{fmt::Display, num::NonZeroU8};

use log::error;

use num_derive::FromPrimitive;

use crate::data_model::objects::{Access, ClusterId, EndptId, Privilege};
use crate::error::{Error, ErrorCode};
use crate::fabric;
use crate::interaction_model::messages::GenericPath;
use crate::tlv::{self, FromTLV, Nullable, TLVElement, TLVList, TLVWriter, TagType, ToTLV};
use crate::transport::session::{Session, SessionMode, MAX_CAT_IDS_PER_NOC};
use crate::utils::cell::RefCell;
use crate::utils::init::{init, Init};
use crate::utils::storage::WriteBuf;

// Matter Minimum Requirements
pub const SUBJECTS_PER_ENTRY: usize = 4;
pub const TARGETS_PER_ENTRY: usize = 3;
Expand Down Expand Up @@ -417,7 +419,7 @@ impl AclEntry {

const MAX_ACL_ENTRIES: usize = ENTRIES_PER_FABRIC * fabric::MAX_SUPPORTED_FABRICS;

type AclEntries = heapless::Vec<Option<AclEntry>, MAX_ACL_ENTRIES>;
type AclEntries = crate::utils::storage::Vec<Option<AclEntry>, MAX_ACL_ENTRIES>;

pub struct AclMgr {
entries: AclEntries,
Expand All @@ -431,6 +433,7 @@ impl Default for AclMgr {
}

impl AclMgr {
/// Create a new ACL Manager
#[inline(always)]
pub const fn new() -> Self {
Self {
Expand All @@ -439,6 +442,14 @@ impl AclMgr {
}
}

/// Return an in-place initializer for ACL Manager
pub fn init() -> impl Init<Self> {
init!(Self {
entries <- AclEntries::init(),
changed: false,
})
}

pub fn erase_all(&mut self) -> Result<(), Error> {
self.entries.clear();
self.changed = true;
Expand Down Expand Up @@ -574,7 +585,7 @@ impl AclMgr {
pub fn load(&mut self, data: &[u8]) -> Result<(), Error> {
let root = TLVList::new(data).iter().next().ok_or(ErrorCode::Invalid)?;

tlv::from_tlv(&mut self.entries, &root)?;
tlv::vec_from_tlv(&mut self.entries, &root)?;
self.changed = false;

Ok(())
Expand Down Expand Up @@ -656,14 +667,16 @@ impl core::fmt::Display for AclMgr {
#[cfg(test)]
#[allow(clippy::bool_assert_comparison)]
pub(crate) mod tests {
use core::{cell::RefCell, num::NonZeroU8};
use core::num::NonZeroU8;

use crate::{
acl::{gen_noc_cat, AccessorSubjects},
data_model::objects::{Access, Privilege},
interaction_model::messages::GenericPath,
};

use crate::utils::cell::RefCell;

use super::{AccessReq, Accessor, AclEntry, AclMgr, AuthMode, Target};

pub(crate) const FAB_1: NonZeroU8 = match NonZeroU8::new(1) {
Expand Down
4 changes: 2 additions & 2 deletions rs-matter/src/cert/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::{
crypto::KeyPair,
error::{Error, ErrorCode},
tlv::{self, FromTLV, OctetStr, TLVArray, TLVElement, TLVWriter, TagType, ToTLV},
utils::{epoch::MATTER_CERT_DOESNT_EXPIRE, writebuf::WriteBuf},
utils::{epoch::MATTER_CERT_DOESNT_EXPIRE, storage::WriteBuf},
};
use log::error;
use num_derive::FromPrimitive;
Expand Down Expand Up @@ -857,7 +857,7 @@ mod tests {

use crate::cert::Cert;
use crate::tlv::{self, FromTLV, TLVWriter, TagType, ToTLV};
use crate::utils::writebuf::WriteBuf;
use crate::utils::storage::WriteBuf;

#[test]
fn test_asn1_encode_success() {
Expand Down
Loading

0 comments on commit 1e0117b

Please sign in to comment.