The availability request supplies hardware, enabled and permission state. Keep each result unknown until the host reports it. A manifest declaration does not mean permission has been granted, and an enabled adapter does not mean it supports BLE.
The request, pending state and callback handling belong to the shared state module. The shell only selects a target and installs the checked-in translations.
{"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::*;
const ENVIRONMENTAL_SENSING_SERVICE: &str = "0000181a-0000-1000-8000-00805f9b34fb";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pending { Check, Permission, Scan }
#[derive(Debug, Default)]
pub struct ProbeState {
pub permission: BluetoothPermission,
pub enabled: Option<bool>,
pub low_energy: Option<bool>,
pub pending: Option<Pending>,
pub scan_complete: bool,
pub devices: Vec<BluetoothDevice>,
pub issue_key: Option<&'static str>,
}
impl GlobalState for ProbeState {}
impl ProbeState {
pub fn can_scan(&self) -> bool {
self.pending.is_none()
&& self.permission == BluetoothPermission::Granted
&& self.enabled == Some(true)
&& self.low_energy == Some(true)
}
}
pub fn check(state: &mut ProbeState, ctx: &mut ReducerContext<ProbeState>) {
if state.pending.is_some() { return; }
state.pending = Some(Pending::Check);
state.issue_key = None;
let ok = ctx.effects.bind(ProbeChecked, reduce_with!(probe_checked));
let err = ctx.effects.bind(ProbeFailed, reduce_with!(probe_failed));
ctx.effects.bluetooth().availability().on_ok(ok).on_err(err);
}
#[fission_reducer(RequestProbePermission)]
pub fn request_permission(
state: &mut ProbeState,
reason: String,
ctx: &mut ReducerContext<ProbeState>,
) {
if state.pending.is_some() { return; }
state.pending = Some(Pending::Permission);
state.issue_key = None;
let ok = ctx.effects.bind(ProbePermissionReported, reduce_with!(probe_permission_reported));
let err = ctx.effects.bind(ProbeFailed, reduce_with!(probe_failed));
ctx.effects.bluetooth()
.request_permission(BluetoothPermissionRequest { reason: Some(reason) })
.on_ok(ok).on_err(err);
}
pub fn scan(state: &mut ProbeState, ctx: &mut ReducerContext<ProbeState>) {
if !state.can_scan() { return; }
state.pending = Some(Pending::Scan);
state.scan_complete = false;
state.devices.clear();
state.issue_key = None;
let ok = ctx.effects.bind(ProbesReported, reduce_with!(probes_reported));
let err = ctx.effects.bind(ProbeFailed, reduce_with!(probe_failed));
ctx.effects.bluetooth().scan_devices(BluetoothScanRequest {
service_uuids: vec![ENVIRONMENTAL_SENSING_SERVICE.into()],
timeout_ms: Some(5_000),
include_paired: false,
allow_duplicates: false,
}).on_ok(ok).on_err(err);
}
#[fission_reducer(ProbeChecked)]
fn probe_checked(state: &mut ProbeState, ctx: &mut ReducerContext<ProbeState>) {
if state.pending != Some(Pending::Check) { return; }
state.pending = None;
match ctx.input.capability_ok(GET_BLUETOOTH_AVAILABILITY) {
Some(value) => {
state.permission = value.permission;
state.enabled = Some(value.enabled);
state.low_energy = Some(value.supports_low_energy);
}
None => state.issue_key = Some("probe.failed"),
}
}
#[fission_reducer(ProbePermissionReported)]
fn probe_permission_reported(state: &mut ProbeState, ctx: &mut ReducerContext<ProbeState>) {
if state.pending != Some(Pending::Permission) { return; }
state.pending = None;
match ctx.input.capability_ok(REQUEST_BLUETOOTH_PERMISSION) {
Some(permission) => state.permission = permission,
None => state.issue_key = Some("probe.failed"),
}
}
#[fission_reducer(ProbesReported)]
fn probes_reported(state: &mut ProbeState, ctx: &mut ReducerContext<ProbeState>) {
if state.pending != Some(Pending::Scan) { return; }
state.pending = None;
match ctx.input.capability_ok(SCAN_BLUETOOTH_DEVICES) {
Some(result) => {
state.devices = result.devices;
state.scan_complete = true;
}
None => state.issue_key = Some("probe.failed"),
}
}
#[fission_reducer(ProbeFailed)]
fn probe_failed(state: &mut ProbeState, ctx: &mut ReducerContext<ProbeState>) {
let code = match state.pending.take() {
Some(Pending::Check) => ctx.input.capability_error(GET_BLUETOOTH_AVAILABILITY).map(|error| error.code),
Some(Pending::Permission) => ctx.input.capability_error(REQUEST_BLUETOOTH_PERMISSION).map(|error| error.code),
Some(Pending::Scan) => ctx.input.capability_error(SCAN_BLUETOOTH_DEVICES).map(|error| error.code),
None => return,
};
state.issue_key = Some(match code.as_deref() {
Some("unsupported") => "probe.unsupported",
Some("permission_denied") => "probe.denied",
_ => "probe.failed",
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scan_requires_current_known_prerequisites() {
let mut state = ProbeState::default();
assert!(!state.can_scan());
state.permission = BluetoothPermission::Granted;
state.enabled = Some(true);
assert!(!state.can_scan());
state.low_energy = Some(true);
assert!(state.can_scan());
state.pending = Some(Pending::Scan);
assert!(!state.can_scan());
}
}
{"id":"fission-tabs-1","index":1,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::state::{self, ProbeState, RequestProbePermission, request_permission};
fission_component! {
pub ProbeFinder<ProbeState> {}
view(_finder, state, cx) {
let tokens = &cx.view.env().theme.tokens;
} =>
SafeArea(
child: Scroll(
child: Container(
child: Column(gap: tokens.spacing.m, children: [
Text(cx.tr("probe.title")).size(tokens.typography.heading2_size),
Text(cx.tr("probe.context")),
Text(cx.tr("probe.service")),
Button(
child: Text(cx.tr("probe.check")),
key: "check-bluetooth",
disabled: state.pending.is_some(),
on_press: reduce { state::check(state, cx); },
).semantics_identifier("probe.check"),
Text(cx.tr(match state.permission {
BluetoothPermission::Granted => "probe.granted",
BluetoothPermission::Denied => "probe.not_granted",
BluetoothPermission::Restricted => "probe.restricted",
BluetoothPermission::Unknown => "probe.unknown",
})),
if let Some(enabled) = state.enabled {
Text(cx.tr(if enabled { "probe.enabled" } else { "probe.disabled" }))
},
if let Some(supported) = state.low_energy {
Text(cx.tr(if supported { "probe.le" } else { "probe.no_le" }))
},
if state.pending.is_some() {
Spinner(
motion: Some(SpinnerMotion::Default),
label: cx.tr("probe.pending"),
)
},
if let Some(key) = state.issue_key { Text(cx.tr(key)) },
Text(cx.tr("probe.connection_gap")),
]),
).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"}
probe.title: "Find a nearby environmental sensor"
probe.context: "Discover devices advertising the Environmental Sensing service. A name or signal strength does not authenticate a sensor or provide a temperature."
probe.service: "Bluetooth LE Environmental Sensing service · 0x181A"
probe.check: "Check Bluetooth and permission"
probe.granted: "Permission was granted at the last check."
probe.not_granted: "Permission was not granted at the last check."
probe.restricted: "The last check reported restricted access."
probe.unknown: "Permission has not been confirmed."
probe.enabled: "Bluetooth was enabled at the last check."
probe.disabled: "Bluetooth was disabled at the last check. Enable it in device settings, then check again."
probe.le: "The device reports Bluetooth LE support."
probe.no_le: "The device does not report Bluetooth LE support."
probe.request_permission: "Request Bluetooth access"
probe.permission_reason: "Find the environmental sensor for this inspection"
probe.permission_help: "Finish any Android permission prompt, then choose Check Bluetooth and permission again. This provider may report the old permission before the prompt is answered."
probe.scan: "Find nearby sensors"
probe.no_results: "No matching devices were reported"
probe.empty_help: "Check the sensor's advertising mode, permissions and Bluetooth settings. An empty response does not prove the sensor is absent."
probe.unnamed: "Unnamed Bluetooth device"
probe.signal: "Reported signal: {rssi} dBm"
probe.no_signal: "No signal strength was reported."
probe.pending: "Waiting for the Bluetooth operation…"
probe.unsupported: "This host does not support the requested Bluetooth operation."
probe.denied: "Bluetooth access is not granted. Review the device permission settings before trying again."
probe.failed: "No valid Bluetooth result was received. Check device settings before starting another request."
probe.connection_gap: "This Android provider can discover devices but cannot connect, pair or read sensor characteristics. No sensor is connected by this app."
{"id":"fission-tabs-1","index":4,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
probe.title: "Buscar un sensor ambiental cercano"
probe.context: "Descubre dispositivos que anuncian el servicio de detección ambiental. Un nombre o una señal no autentica un sensor ni proporciona una temperatura."
probe.service: "Servicio Bluetooth LE de detección ambiental · 0x181A"
probe.check: "Comprobar Bluetooth y el permiso"
probe.granted: "El permiso estaba concedido en la última comprobación."
probe.not_granted: "El permiso no estaba concedido en la última comprobación."
probe.restricted: "La última comprobación indicó acceso restringido."
probe.unknown: "Todavía no se ha confirmado el permiso."
probe.enabled: "Bluetooth estaba activado en la última comprobación."
probe.disabled: "Bluetooth estaba desactivado. Actívalo en los ajustes y vuelve a comprobarlo."
probe.le: "El dispositivo indica compatibilidad con Bluetooth LE."
probe.no_le: "El dispositivo no indica compatibilidad con Bluetooth LE."
probe.request_permission: "Solicitar acceso Bluetooth"
probe.permission_reason: "Buscar el sensor ambiental para esta inspección"
probe.permission_help: "Responde al diálogo de Android y después vuelve a comprobar Bluetooth y el permiso. El proveedor puede devolver el permiso anterior antes de que respondas."
probe.scan: "Buscar sensores cercanos"
probe.no_results: "No se informó de dispositivos coincidentes"
probe.empty_help: "Revisa el anuncio del sensor, los permisos y Bluetooth. Una respuesta vacía no demuestra que el sensor esté ausente."
probe.unnamed: "Dispositivo Bluetooth sin nombre"
probe.signal: "Señal indicada: {rssi} dBm"
probe.no_signal: "No se indicó la intensidad de señal."
probe.pending: "Esperando la operación Bluetooth…"
probe.unsupported: "Este host no admite la operación Bluetooth solicitada."
probe.denied: "No se ha concedido el acceso Bluetooth. Revisa los permisos antes de volver a intentarlo."
probe.failed: "No se recibió ningún resultado Bluetooth válido. Revisa los ajustes antes de iniciar otra solicitud."
probe.connection_gap: "Este proveedor Android descubre dispositivos, pero no conecta, empareja ni lee características. Esta aplicación no conecta ningún sensor."
{"id":"fission-tabs-1","index":5,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod state;
mod translations;
use app::ProbeFinder;
use state::ProbeState;
use fission::prelude::*;
#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<ProbeState, _>::new(ProbeFinder)
.with_env(translations::create_env())
.run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<ProbeState, ProbeFinder> {
let app = MobileApp::<ProbeState, _>::new(ProbeFinder)
.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::<ProbeState, _>::new(ProbeFinder)
.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::ProbeState, _>::new(app::ProbeFinder)
.with_env(translations::create_env())
.mount("#fission-web-mount")
.run()
.map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}