nfc/
api.rs

1// SPDX-FileCopyrightText: 2024 Foundation Devices, Inc. <hello@foundation.xyz>
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4use std::time::Duration;
5
6use server::{CheckedConn, CheckedPermissions, MessageAllowed};
7
8use crate::{error::NfcError, messages::*};
9
10#[macro_export]
11macro_rules! use_api {
12    () => {
13        mod nfc_permissions {
14            use nfc::messages::*;
15            #[derive(Clone, Default, server::Permissions)]
16            #[server_name = "os/nfc"]
17            pub struct NfcPermissions;
18        }
19        type NfcApi = nfc::api::NfcApi<nfc_permissions::NfcPermissions>;
20    };
21}
22
23pub struct NfcApi<P: CheckedPermissions> {
24    conn: CheckedConn<P>,
25}
26
27impl<P: CheckedPermissions> Default for NfcApi<P> {
28    fn default() -> Self { Self { conn: Default::default() } }
29}
30
31impl<P: CheckedPermissions> NfcApi<P> {
32    pub fn read_ndef_raw_msg(&self, timeout: Duration) -> Result<(Vec<u8>, Vec<u8>), NfcError>
33    where
34        P: MessageAllowed<ReadNdefRawMsg>,
35    {
36        self.conn.send_blocking_archive(ReadNdefRawMsg(timeout))
37    }
38
39    pub fn write_ndef_raw_msg(&self, uid: Vec<u8>, msg: Vec<u8>, timeout: Duration) -> Result<(), NfcError>
40    where
41        P: MessageAllowed<WriteNdefRawMsg>,
42    {
43        self.conn.send_blocking_archive(WriteNdefRawMsg((uid, msg, timeout)))
44    }
45
46    pub fn set_enabled(&mut self, enabled: bool) -> Result<(), NfcError>
47    where
48        P: MessageAllowed<SetEnabled>,
49    {
50        Ok(self.conn.try_send_blocking_scalar(SetEnabled(enabled))?)
51    }
52
53    pub fn is_enabled(&self) -> Result<bool, NfcError>
54    where
55        P: MessageAllowed<IsEnabled>,
56    {
57        Ok(self.conn.try_send_blocking_scalar(IsEnabled)?)
58    }
59
60    pub fn is_active(&self) -> Result<bool, NfcError>
61    where
62        P: MessageAllowed<IsActive>,
63    {
64        Ok(self.conn.try_send_blocking_scalar(IsActive)?)
65    }
66}