Availability is a request, not a value inferred from the presence of a manifest declaration. The reducer queues it, and the completion reducer decodes GET_NFC_AVAILABILITY from ctx.input.
A missing response is a failure. A disabled adapter is different from missing hardware, and neither should be presented as a successful tag read. These are the useful working diagnostics available from the default Android host today.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/state.rs","value":"src-state-rs"},{"index":1,"label":"src/app.rs","value":"src-app-rs"},{"index":2,"label":"src/translations.rs","value":"src-translations-rs"},{"index":3,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":4,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"},{"index":5,"label":"src/lib.rs","value":"src-lib-rs"},{"index":6,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/state.rs","value":"src-state-rs"}
use fission::prelude::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pending { Check, Read, Write }
#[derive(Debug, Default)]
pub struct NfcState {
pub availability: Option<NfcAvailability>,
pub pending: Option<Pending>,
pub records_read: Option<usize>,
pub status_key: Option<&'static str>,
}
impl GlobalState for NfcState {}
pub fn check(state: &mut NfcState, ctx: &mut ReducerContext<NfcState>) {
if state.pending.is_some() { return; }
state.pending = Some(Pending::Check);
state.status_key = None;
let ok = ctx.effects.bind(NfcChecked, reduce_with!(nfc_checked));
let err = ctx.effects.bind(NfcFailed, reduce_with!(nfc_failed));
ctx.effects.nfc().availability().on_ok(ok).on_err(err);
}
pub fn read(state: &mut NfcState, ctx: &mut ReducerContext<NfcState>) {
if state.pending.is_some() { return; }
state.pending = Some(Pending::Read);
state.status_key = None;
let ok = ctx.effects.bind(NfcRead, reduce_with!(nfc_read));
let err = ctx.effects.bind(NfcFailed, reduce_with!(nfc_failed));
ctx.effects.nfc().scan_tag(NfcScanRequest {
technologies: vec![NfcTechnology::Ndef],
read_multiple_records: true,
..Default::default()
}).on_ok(ok).on_err(err);
}
pub fn write(
state: &mut NfcState,
ctx: &mut ReducerContext<NfcState>,
text: String,
) {
if state.pending.is_some() { return; }
if text.trim().is_empty() || text.len() > 256 {
state.status_key = Some("nfc.invalid_text");
return;
}
state.pending = Some(Pending::Write);
state.status_key = None;
let ok = ctx.effects.bind(NfcWritten, reduce_with!(nfc_written));
let err = ctx.effects.bind(NfcFailed, reduce_with!(nfc_failed));
ctx.effects.nfc().write_tag(NfcWriteRequest {
// The author explicitly enters English text in this integration example.
records: vec![NfcRecord::text("en", text)],
make_read_only: false,
..Default::default()
}).on_ok(ok).on_err(err);
}
#[fission_reducer(NfcChecked)]
fn nfc_checked(state: &mut NfcState, ctx: &mut ReducerContext<NfcState>) {
if state.pending != Some(Pending::Check) { return; }
state.pending = None;
match ctx.input.capability_ok(GET_NFC_AVAILABILITY) {
Some(value) => { state.availability = Some(value); state.status_key = None; }
None => state.status_key = Some("nfc.failed"),
}
}
#[fission_reducer(NfcRead)]
fn nfc_read(state: &mut NfcState, ctx: &mut ReducerContext<NfcState>) {
if state.pending != Some(Pending::Read) { return; }
state.pending = None;
match ctx.input.capability_ok(SCAN_NFC_TAG) {
Some(tag) => {
state.records_read = Some(tag.records.len());
state.status_key = Some("nfc.read_result");
}
None => state.status_key = Some("nfc.failed"),
}
}
#[fission_reducer(NfcWritten)]
fn nfc_written(state: &mut NfcState, ctx: &mut ReducerContext<NfcState>) {
if state.pending != Some(Pending::Write) { return; }
state.pending = None;
state.status_key = Some(match ctx.input.capability_ok(WRITE_NFC_TAG) {
Some(receipt) if receipt.completed => "nfc.write_result",
_ => "nfc.failed",
});
}
#[fission_reducer(NfcFailed)]
fn nfc_failed(state: &mut NfcState, ctx: &mut ReducerContext<NfcState>) {
let code = match state.pending.take() {
Some(Pending::Check) => ctx.input.capability_error(GET_NFC_AVAILABILITY).map(|error| error.code),
Some(Pending::Read) => ctx.input.capability_error(SCAN_NFC_TAG).map(|error| error.code),
Some(Pending::Write) => ctx.input.capability_error(WRITE_NFC_TAG).map(|error| error.code),
None => return,
};
state.status_key = Some(match code.as_deref() {
Some("unsupported") => "nfc.unsupported",
Some("cancelled") => "nfc.cancelled",
Some("permission_denied") => "nfc.denied",
_ => "nfc.failed",
});
}
{"id":"fission-tabs-1","index":1,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::state::{self, NfcState};
fission_component! {
pub NfcDiagnostics<NfcState> {
state {
write_text: String = String::new(),
own_tag_confirmed: bool = false,
}
}
view(screen, state, cx) {
let tokens = &cx.view.env().theme.tokens;
} =>
SafeArea(
child: Scroll(
child: Container(
child: Column(gap: tokens.spacing.m, children: [
Text(cx.tr("nfc.title")).size(tokens.typography.heading2_size),
Text(cx.tr("nfc.boundary")),
Button(
child: Text(cx.tr("nfc.check")),
key: "check-nfc",
disabled: state.pending.is_some(),
on_press: reduce { state::check(state, cx); },
).semantics_identifier("nfc.check"),
if let Some(availability) = &state.availability {
Column(gap: tokens.spacing.s, children: [
Text(cx.tr(if availability.supported {
"nfc.hardware_present"
} else { "nfc.no_hardware" })),
Text(cx.tr(if availability.enabled {
"nfc.enabled"
} else { "nfc.disabled" })),
Text(cx.tr("nfc.flags_warning")),
])
},
if state.pending.is_some() {
Spinner(
motion: Some(SpinnerMotion::Default),
label: cx.tr("nfc.pending"),
)
},
if let Some(key) = state.status_key { Text(cx.tr(key)) },
if let Some(count) = state.records_read {
Text(cx.tr("nfc.record_count").replace("{count}", &count.to_string()))
},
]),
).padding_all(tokens.spacing.l),
),
)
}
{"id":"fission-tabs-1","index":2,"label":"src/translations.rs","value":"src-translations-rs"}
use std::collections::HashMap;
use fission::prelude::*;
pub fn create_env() -> Env {
let mut env = Env::default();
env.locale = Locale::from("en-US");
for (locale, source) in [
("en-US", include_str!("../i18n/en-US.yaml")),
("es-ES", include_str!("../i18n/es-ES.yaml")),
] {
let messages: HashMap<String, String> =
serde_yaml::from_str(source).expect("valid checked-in translations");
env.i18n.add_bundle(TranslationBundle { locale: Locale::from(locale), messages });
}
env
}
{"id":"fission-tabs-1","index":3,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
nfc.title: "NFC integration diagnostics"
nfc.boundary: "The current Android provider detects the NFC adapter but does not implement tag read or write. This is an integration outline, not a working tag-writing app."
nfc.check: "Check NFC adapter"
nfc.hardware_present: "The last response reported NFC hardware present."
nfc.no_hardware: "The last response did not report NFC hardware."
nfc.enabled: "The last response reported NFC enabled."
nfc.disabled: "The last response reported NFC disabled."
nfc.flags_warning: "An availability flag is not proof that this provider can read or write a tag. Check the actual operation result."
nfc.read: "Request an NDEF read"
nfc.write_text: "English test text for an owned tag"
nfc.write_help: "Use non-sensitive English text, up to 256 UTF-8 bytes. A write may replace the tag's existing records."
nfc.confirm_owned: "This is my writable test tag and I accept replacing its contents."
nfc.write: "Request writing this text to the tag"
nfc.pending: "Waiting for the NFC operation…"
nfc.invalid_text: "Enter non-empty test text of at most 256 UTF-8 bytes."
nfc.read_result: "The host returned a tag. This does not authenticate the tag or its contents."
nfc.record_count: "Last returned NDEF record count: {count}"
nfc.write_result: "The host acknowledged write completion. This example has not read the tag back."
nfc.unsupported: "This provider does not implement the requested NFC operation. Your input has been preserved."
nfc.cancelled: "The NFC operation was cancelled. No successful result was reported."
nfc.denied: "The host denied the NFC request. Check the device policy and NFC settings."
nfc.failed: "No valid completed NFC result was received. Preserve the input and check the host before retrying a write."
{"id":"fission-tabs-1","index":4,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
nfc.title: "Diagnóstico de integración NFC"
nfc.boundary: "El proveedor Android actual detecta el adaptador NFC, pero no implementa la lectura ni la escritura de etiquetas. Esto es un esquema de integración, no una aplicación de escritura completa."
nfc.check: "Comprobar el adaptador NFC"
nfc.hardware_present: "La última respuesta indicó que existe hardware NFC."
nfc.no_hardware: "La última respuesta no indicó hardware NFC."
nfc.enabled: "La última respuesta indicó que NFC estaba activado."
nfc.disabled: "La última respuesta indicó que NFC estaba desactivado."
nfc.flags_warning: "Un indicador de disponibilidad no demuestra que el proveedor pueda leer o escribir. Comprueba el resultado de la operación."
nfc.read: "Solicitar una lectura NDEF"
nfc.write_text: "Texto de prueba en inglés para una etiqueta propia"
nfc.write_help: "Usa texto en inglés no sensible de hasta 256 bytes UTF-8. Escribir puede sustituir los registros de la etiqueta."
nfc.confirm_owned: "La etiqueta de prueba es mía, es escribible y acepto sustituir su contenido."
nfc.write: "Solicitar escribir este texto en la etiqueta"
nfc.pending: "Esperando la operación NFC…"
nfc.invalid_text: "Escribe texto de prueba no vacío de hasta 256 bytes UTF-8."
nfc.read_result: "El host devolvió una etiqueta. Esto no autentica la etiqueta ni su contenido."
nfc.record_count: "Último número de registros NDEF recibidos: {count}"
nfc.write_result: "El host confirmó la escritura. Este ejemplo no ha vuelto a leer la etiqueta."
nfc.unsupported: "Este proveedor no implementa la operación NFC solicitada. Se conservaron los datos introducidos."
nfc.cancelled: "La operación NFC se canceló. No se informó de ningún resultado correcto."
nfc.denied: "El host denegó la solicitud NFC. Revisa la política del dispositivo y los ajustes NFC."
nfc.failed: "No se recibió ningún resultado NFC completado y válido. Conserva los datos y comprueba el host antes de repetir una escritura."
{"id":"fission-tabs-1","index":5,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod state;
mod translations;
use app::NfcDiagnostics;
use state::NfcState;
use fission::prelude::*;
#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<NfcState, _>::new(NfcDiagnostics::new())
.with_env(translations::create_env())
.run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<NfcState, NfcDiagnostics> {
let app = MobileApp::<NfcState, _>::new(NfcDiagnostics::new())
.with_env(translations::create_env());
#[cfg(all(target_os = "android", debug_assertions))]
let app = app.with_test_control_port(48761);
app
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> { mobile_app().run() }
#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
let _ = mobile_app().run_with_android_app(app_handle);
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
console_error_panic_hook::set_once();
WebApp::<NfcState, _>::new(NfcDiagnostics::new())
.with_env(translations::create_env())
.run()
.map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":6,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod state;
mod translations;
use fission::prelude::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
console_error_panic_hook::set_once();
WebApp::<state::NfcState, _>::new(app::NfcDiagnostics::new())
.with_env(translations::create_env())
.mount("#fission-web-mount")
.run()
.map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}