tauri_plugin_nfc/
lib.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5#![cfg(mobile)]
6
7use serde::{Deserialize, Serialize};
8use tauri::{
9    plugin::{Builder, PluginHandle, TauriPlugin},
10    Manager, Runtime,
11};
12
13pub use models::*;
14
15mod error;
16mod models;
17
18pub use error::{Error, Result};
19
20#[cfg(target_os = "android")]
21const PLUGIN_IDENTIFIER: &str = "app.tauri.nfc";
22
23#[cfg(target_os = "ios")]
24tauri::ios_plugin_binding!(init_plugin_nfc);
25
26/// Access to the nfc APIs.
27pub struct Nfc<R: Runtime>(PluginHandle<R>);
28
29#[derive(Deserialize)]
30struct IsAvailableResponse {
31    available: bool,
32}
33
34#[derive(Serialize)]
35struct WriteRequest {
36    records: Vec<NfcRecord>,
37}
38
39impl<R: Runtime> Nfc<R> {
40    pub fn is_available(&self) -> crate::Result<bool> {
41        self.0
42            .run_mobile_plugin::<IsAvailableResponse>("isAvailable", ())
43            .map(|r| r.available)
44            .map_err(Into::into)
45    }
46
47    pub fn scan(&self, payload: ScanRequest) -> crate::Result<ScanResponse> {
48        self.0
49            .run_mobile_plugin("scan", payload)
50            .map_err(Into::into)
51    }
52
53    pub fn write(&self, records: Vec<NfcRecord>) -> crate::Result<()> {
54        self.0
55            .run_mobile_plugin("write", WriteRequest { records })
56            .map_err(Into::into)
57    }
58}
59
60/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the NFC APIs.
61pub trait NfcExt<R: Runtime> {
62    fn nfc(&self) -> &Nfc<R>;
63}
64
65impl<R: Runtime, T: Manager<R>> crate::NfcExt<R> for T {
66    fn nfc(&self) -> &Nfc<R> {
67        self.state::<Nfc<R>>().inner()
68    }
69}
70
71/// Initializes the plugin.
72pub fn init<R: Runtime>() -> TauriPlugin<R> {
73    Builder::new("nfc")
74        .setup(|app, api| {
75            #[cfg(target_os = "android")]
76            let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "NfcPlugin")?;
77            #[cfg(target_os = "ios")]
78            let handle = api.register_ios_plugin(init_plugin_nfc)?;
79            app.manage(Nfc(handle));
80            Ok(())
81        })
82        .build()
83}