tauri-plugin-torchlight

A Tauri v2 plugin to control a smartphone's torch (flashlight): turn it on and off, set its brightness, query availability and current state, and react to torch changes coming from the system. Android and iOS.

View on GitHub Dual licensed MIT / Apache-2.0

Overview

This plugin exposes a small API for using the camera flash unit as a flashlight from a Tauri v2 mobile app. It ships as two packages: the Rust plugin with its commands, and typed JavaScript/TypeScript bindings.

  • On and off — setTorch(true) / setTorch(false).
  • Brightness — a 0.0–1.0 level, honoured on devices that support it (iOS, and Android 13+). Elsewhere the torch simply turns on at full power.
  • Availability — isAvailable() reports whether a camera with a real flash unit exists.
  • Current state — isEnabled().
  • Device capabilities — capabilities() reports whether the hardware exists, whether it is usable right now, and whether brightness control actually does anything.
  • Atomic flip — toggle(level?) does the read and the write inside the native plugin.
  • Change events — onTorchModeChanged() keeps your UI correct when the OS, another app, or thermal limits change the torch.
  • Structured errors — every rejection is a TorchlightError with a machine-readable kind, so you never have to match on message text.
  • Explicit desktop behaviour — a clear error instead of silently doing nothing.
Two packages
tauri-plugin-torchlight (crates.io) and tauri-plugin-torchlight-api (npm) are released together and always share the same version number.

Requirements

Item Requirement
Tauri v2
Rust 1.85.0 or later (edition 2024)
Android minSdk 23; brightness needs API 33 (Android 13) or later
iOS iOS 13 or later
@tauri-apps/api v2 (dependency of the JS bindings)

Installation

Rust

cargo add tauri-plugin-torchlight

Or add it to src-tauri/Cargo.toml directly:

[dependencies]
tauri-plugin-torchlight = "1"

JavaScript / TypeScript

Optional but recommended — it gives you typed helpers instead of raw invoke calls.

npm install tauri-plugin-torchlight-api

Setup

Register the plugin in src-tauri/src/lib.rs:

fn main() {
    tauri::Builder::default()
        .plugin(tauri_plugin_torchlight::init()) // Add this line
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

Then grant the permission in src-tauri/capabilities/default.json:

{
    "permissions": [
        "torchlight:default"
    ]
}
Android permissions
No CAMERA permission is required. The plugin uses CameraManager.setTorchMode, so there is no runtime permission prompt. The manifest only declares android.hardware.camera.flash with required="false", which keeps the app installable on devices without a flash unit (isAvailable() returns false there).

Quick start

import {
    setTorch,
    isAvailable,
    isEnabled,
    capabilities,
    toggle,
    onTorchModeChanged,
} from "tauri-plugin-torchlight-api"

// Check support before showing a torch button.
if (await isAvailable()) {
    await setTorch(true)            // full brightness
    await setTorch(true, 0.5)       // half brightness where supported
    const lit = await isEnabled()   // -> true
    await toggle(0.5)               // flips the current state, returns the new one
    await setTorch(false)           // off
}

// Decide whether a brightness slider is worth showing.
const caps = await capabilities()
if (caps.brightnessSupported) {
    // caps.levelSteps is the step count (null on iOS, which is continuous)
}

// Stay in sync when the system changes the torch.
const listener = await onTorchModeChanged(({ enabled, available }) => {
    console.log("torch:", enabled, "available:", available)
})

// Later, when you are done:
await listener.unregister()

setTorch

function setTorch(enabled: boolean, level?: number): Promise<void>

Turns the torch on or off.

Parameter Type Description
enabledrequired boolean true turns the torch on, false turns it off.
leveloptional number Brightness in the 0.0–1.0 range. Used only when turning on, and only on devices where brightnessSupported is true. Out-of-range values are clamped into 0.01–1.0, and non-finite values (NaN, Infinity) are treated as "no level requested". Omitting it uses full brightness.

Rejects on devices without a torch and on desktop. See error handling.

isAvailable

function isAvailable(): Promise<boolean>

Whether the device has torch hardware. This is a static property of the device and never changes while the app runs. On Android the plugin looks for a camera with a flash unit; on iOS it checks whether the default video device reports hasTorch. Always false on desktop.

Use it to decide whether to show a torch button at all. For "can I use it right now", read usable from capabilities() or follow available on the onTorchModeChanged event.

isEnabled

function isEnabled(): Promise<boolean>

Whether the torch is currently lit. Always false on desktop.

Where the Android value comes from
On Android the value is served from a cache kept up to date by CameraManager.TorchCallback, registered when the plugin loads. Changes made by other apps or by the OS are therefore reflected. The cache is also updated the moment a torch() or toggle() call succeeds, so the value is correct without waiting for the asynchronous callback.

capabilities

function capabilities(): Promise<TorchCapabilities>

Reports what this device's torch can actually do. Use it instead of isAvailable() whenever the UI offers a brightness control.

Field Type Description
available boolean Whether the device has torch hardware. Static; it never changes while the app runs.
usable boolean Whether the torch can be used right now. Goes false when another app takes the camera or the device is under thermal duress, and back to true afterwards.
brightnessSupported boolean Whether a level actually changes the brightness. Always true on iOS; on Android it is false below API 33 and on devices that report a single strength level.
levelSteps number | null Number of discrete brightness steps. A number on Android when brightness is supported; null on iOS (a continuous scale) or when there is no brightness control.
available and usable are different questions
available means "the hardware exists"; usable means "it works right now". Passing a level on a device where brightnessSupported is false still succeeds — the torch just turns on at full power.
const { available, brightnessSupported, levelSteps } = await capabilities()

// Never show a slider that silently does nothing
if (available && brightnessSupported) {
    showBrightnessSlider({ steps: levelSteps ?? undefined })
}

On desktop it resolves with all four fields reporting "no torch" (false and null) instead of rejecting.

toggle

function toggle(level?: number): Promise<boolean>

Flips the torch and returns the state it ended up in (true = on). An optional level sets the brightness when the toggle turns the torch on; it is interpreted exactly as in setTorch().

The read and the write are atomic
The flip happens inside the native plugin — on Android within a synchronized block, on iOS on a serial DispatchQueue. Two concurrent toggle() calls cannot both observe the same starting state.

onTorchModeChanged

function onTorchModeChanged(
    handler: (payload: TorchModeChangedPayload) => void,
): Promise<PluginListener>

Registers a listener for torch changes coming from the system: another app taking the camera, thermal limits, or the OS turning the torch off.

The returned PluginListener comes from @tauri-apps/api/core. Always call unregister() when you are done.

On desktop the registration succeeds and the listener simply never fires — the plugin supplies no-op register_listener / remove_listener commands — so callers do not have to special-case the platform.

const listener = await onTorchModeChanged(({ enabled, available }) => {
    setLit(enabled)
    setSupported(available)
})

// e.g. when the component unmounts
await listener.unregister()
Timing differs per platform
Android uses CameraManager.TorchCallback (onTorchModeChanged and onTorchModeUnavailable); iOS observes both isTorchActive and isTorchAvailable on the AVCaptureDevice via KVO. Both platforms therefore emit an event when only availability changes — thermal duress while the torch is off, for instance. The event reports changes only: the plugin loads before your listener can exist, so anything emitted then never reaches you. Read the initial state with isEnabled() / capabilities() rather than waiting for an event. Note that your own setTorch() and toggle() calls also fire the event.

Type reference

interface TorchModeChangedPayload {
    /** Whether the torch is currently lit. */
    enabled: boolean
    /** Whether the torch is usable *right now* (not whether hardware exists). */
    available: boolean
}

interface TorchCapabilities {
    /** Whether the device has torch hardware. Static. */
    available: boolean
    /** Whether the torch can be used right now. Can change at runtime. */
    usable: boolean
    /** Whether a level actually changes the brightness. */
    brightnessSupported: boolean
    /** Discrete step count, or null for a continuous scale (iOS) / no control. */
    levelSteps: number | null
}

type TorchErrorKind =
    | "unsupported"    // desktop: no torch hardware on this platform
    | "unavailable"    // this device has no usable torch
    | "cameraAccess"   // the camera could not be accessed (Android)
    | "torchFailed"    // the torch could not be driven, e.g. thermal duress
    | "internal"       // anything else: IPC, serialization, a plugin bug

class TorchlightError extends Error {
    readonly kind: TorchErrorKind
}

Command list

These are the Tauri commands exposed by the Rust side. The JS bindings are a thin wrapper over them.

Command Arguments Returns
plugin:torchlight|torch { enabled: boolean, level?: number } void
plugin:torchlight|toggle { level?: number } boolean
plugin:torchlight|is_available — boolean
plugin:torchlight|is_enabled — boolean
plugin:torchlight|capabilities — TorchCapabilities
plugin:torchlight|register_listener { event: string, handler: Channel } void
plugin:torchlight|remove_listener { event: string, channelId: number } void

Those seven are everything the plugin declares. The listener pair is handled by Tauri's mobile runtime on Android and iOS, and by no-op stand-ins this plugin registers on desktop. They need permissions, but you never call them directly — onTorchModeChanged uses them internally.

Events

Event Payload
torchModeChanged { enabled: boolean, available: boolean }

Using raw invoke

You can skip the npm package entirely.

import { invoke } from "@tauri-apps/api/core"

await invoke("plugin:torchlight|torch", { enabled: true, level: 0.5 })

const available = await invoke("plugin:torchlight|is_available")
const enabled = await invoke("plugin:torchlight|is_enabled")
const caps = await invoke("plugin:torchlight|capabilities")
const next = await invoke("plugin:torchlight|toggle", { level: 0.5 })

Going this way, a rejection arrives as a raw { kind, message } object — the npm package is what wraps it into a TorchlightError.

Subscribe to the event with addPluginListener:

import { addPluginListener } from "@tauri-apps/api/core"

const listener = await addPluginListener("torchlight", "torchModeChanged", (payload) => {
    console.log(payload.enabled, payload.available)
})

Permissions (capabilities)

torchlight:default includes these seven:

  • allow-torch
  • allow-toggle
  • allow-is-available
  • allow-is-enabled
  • allow-capabilities
  • allow-register-listener
  • allow-remove-listener

To be more restrictive, grant them individually as torchlight:allow-torch and so on. Each command also has a matching deny-* permission.

Events need two of them
onTorchModeChanged requires both allow-register-listener and allow-remove-listener.

A read-only configuration

To observe the torch without ever turning it on:

{
    "permissions": [
        "torchlight:allow-is-available",
        "torchlight:allow-is-enabled",
        "torchlight:allow-capabilities",
        "torchlight:allow-register-listener",
        "torchlight:allow-remove-listener"
    ]
}

init

pub fn init<R: Runtime>() -> TauriPlugin<R>

Builds the plugin; pass it to tauri::Builder::plugin(). On mobile it registers the native plugin (TorchlightPlugin on Android, init_plugin_torchlight on iOS); on desktop it registers the stub implementation.

Registration is no longer unwrap()ed. When the native class genuinely cannot be loaded — stripped by R8, a stale AAR, a package rename — the failure propagates to the caller instead of panicking the app during setup.

On desktop, init() also registers no-op register_listener / remove_listener commands, so addPluginListener does not reject with "command not found".

TorchlightExt

To drive the torch from Rust, use the extension trait available on any Manager (such as AppHandle). The trait itself has a single method, fn torchlight(&self) -> &Torchlight<R>; the handle it returns is what exposes the operations below.

use tauri_plugin_torchlight::TorchlightExt;

#[tauri::command]
async fn blink(app: tauri::AppHandle) -> tauri_plugin_torchlight::Result<()> {
    if app.torchlight().is_available()? {
        app.torchlight().torch(true, Some(0.7))?;
        std::thread::sleep(std::time::Duration::from_millis(200));
        app.torchlight().torch(false, None)?;
    }
    Ok(())
}
Method Signature
torch fn torch(&self, enabled: bool, level: Option<f64>) -> Result<()>
is_available fn is_available(&self) -> Result<bool>
is_enabled fn is_enabled(&self) -> Result<bool>
toggle fn toggle(&self, level: Option<f64>) -> Result<bool>
capabilities fn capabilities(&self) -> Result<TorchCapabilities>

The crate also re-exports Error, Result, TorchCapabilities, TorchRequest, ToggleRequest, AvailabilityResponse, EnabledResponse and the MIN_LEVEL constant (0.01).

Error

#[non_exhaustive]
pub enum Error {
    /// The native mobile plugin returned an error (mobile only)
    PluginInvoke(tauri::plugin::mobile::PluginInvokeError),
    /// No torch hardware exists on desktop (desktop only)
    Unsupported,
}

impl Error {
    /// A stable, machine-readable discriminator: "unsupported",
    /// "unavailable", "cameraAccess", "torchFailed" or "internal".
    pub fn kind(&self) -> String;
    /// The human-readable message.
    pub fn message(&self) -> String;
}

The variants are platform-partitioned, so Rust consumers that match on this enum must either handle the _ arm or gate their arms on cfg(mobile) / cfg(desktop). #[non_exhaustive] makes that requirement explicit and leaves room for future variants.

Error serializes as { "kind": "...", "message": "..." }, and the JS bindings turn that into a TorchlightError. The desktop Unsupported message is:

torchlight is only supported on Android and iOS; this is a desktop platform

Support matrix

Feature Android iOS Desktop
On / off Yes Yes Error
Brightness API 33+ Yes Error
isAvailable Yes Yes Always false
isEnabled Yes Yes Always false
toggle Yes Yes Error
capabilities Yes Yes All false
levelSteps API 33+ null (continuous) null
torchModeChanged Yes Yes Registers, never fires

Android

  • On/off goes through CameraManager.setTorchMode.
  • Brightness uses turnOnTorchWithStrengthLevel on API 33 (Android 13) and later. A device whose FLASH_INFO_STRENGTH_MAXIMUM_LEVEL is 1 or less is treated as having no brightness control and falls back to a plain toggle.
  • A 0.0–1.0 level is mapped onto the device's 1..maxLevel range. The result is always at least 1, so setTorch(true, 0.0) does not turn the torch off. That maxLevel is what levelSteps reports.
  • The camera used is a back-facing one (LENS_FACING_BACK) with a flash unit (FLASH_INFO_AVAILABLE), falling back to any camera that has one. Relying on cameraIdList ordering alone can pick a flash-capable front or auxiliary camera on multi-camera devices. If no camera has a flash, isAvailable() returns false and torch rejects.
  • toggle() reads and writes inside synchronized(torchLock).
  • The cached torch state is updated optimistically the moment a torch() or toggle() call succeeds, because TorchCallback is delivered asynchronously on the main looper. Waiting for it would make isEnabled() lie immediately after a successful call.
  • Registering the TorchCallback in load() also delivers the current mode once, which seeds that cache — so isEnabled() is right even on a cold start with the torch already lit. The event that seeding emits is discarded, because load() runs before the webview can register a listener.
  • The TorchCallback is unregistered in onDestroy. It registers into a process-scoped singleton that holds the plugin — and therefore the Activity — alive, so without this the Activity leaks and a re-created plugin emits duplicate events.
  • No CAMERA runtime permission is needed.
  • Requires minSdk 23.

iOS

  • Uses AVCaptureDevice.default(for: .video), but only when it reports hasTorch.
  • Brightness uses setTorchModeOn(level:). When the level is 1.0 or above, AVCaptureMaxAvailableTorchLevel is used instead, because passing exactly 1.0 can throw.
  • Omitting level, or passing a non-finite one, means full brightness. Out-of-range values are clamped into TorchMath.minLevel (0.01) to 1.0.
  • setTorchModeOn(level: 0.0) raises an Objective-C NSInvalidArgumentException, which Swift do/catch cannot catch and which terminates the process. Flooring at minLevel prevents that and gives both platforms the same contract: 0 means "as dim as possible", never "off".
  • toggle()'s read-modify-write, and the configuration lock, run on a serial DispatchQueue.
  • The event observes both isTorchActive and isTorchAvailable via KVO. Nothing is emitted at load() — no listener can exist yet — and iOS reads its state straight off the device, so there is no cache to seed.
  • Brightness is a continuous scale, so brightnessSupported is always true and levelSteps is always null.
  • Under thermal pressure the call can fail (for example AVErrorTorchLevelUnavailable) and the promise rejects.
  • Requires iOS 13 or later.
About Info.plist
Torch control does not need NSCameraUsageDescription. If your app also captures from the camera, follow that feature's own requirements.

Desktop

Desktop machines have no torch hardware, so the plugin is explicit rather than silently pretending to succeed.

  • setTorch() and toggle() reject with the Unsupported error (kind: "unsupported").
  • isAvailable() and isEnabled() return false.
  • capabilities() resolves with { available: false, usable: false, brightnessSupported: false, levelSteps: null }.
  • onTorchModeChanged() registers successfully and never fires.

As long as you branch on isAvailable(), running on desktop during development will not break your UI.

Keeping the UI in sync

The torch can change for reasons outside your app. Read the initial state, then follow the event.

import { useEffect, useState } from "react"
import { isAvailable, isEnabled, onTorchModeChanged, setTorch } from "tauri-plugin-torchlight-api"

export function TorchButton() {
    const [supported, setSupported] = useState(false)
    const [lit, setLit] = useState(false)

    useEffect(() => {
        let listener: { unregister: () => Promise<void> } | undefined
        let disposed = false

        ;(async () => {
            setSupported(await isAvailable())
            setLit(await isEnabled())

            const l = await onTorchModeChanged(({ enabled, available }) => {
                setLit(enabled)
                setSupported(available)
            })
            // Handle unmounting before registration finished
            if (disposed) await l.unregister()
            else listener = l
        })()

        return () => {
            disposed = true
            listener?.unregister()
        }
    }, [])

    if (!supported) return null

    return (
        <button onClick={() => setTorch(!lit)}>
            {lit ? "Turn torch off" : "Turn torch on"}
        </button>
    )
}

Working with brightness

Passing a level is always safe: devices without support simply turn on at full power rather than failing.

// 30% where supported, full brightness elsewhere
await setTorch(true, 0.3)

Before building the UI, though, ask capabilities(), so you never show a slider that silently does nothing.

const caps = await capabilities()
if (caps.brightnessSupported) {
    // A numeric levelSteps lets you snap the slider to the device's steps
    showBrightnessSlider({ steps: caps.levelSteps ?? undefined })
}
level: 0 does not turn the torch off
setTorch(true, 0) means "turn on, as dim as this device allows". That is the contract on both Android and iOS — 0 is never "off". To turn the torch off, always use setTorch(false). Out-of-range values are clamped into 0.01–1.0, and non-finite values (NaN, Infinity) count as "no level requested", i.e. full brightness.

To change brightness while the torch is already lit, call again with enabled: true and a different level.

await setTorch(true, 0.2)
await setTorch(true, 0.8) // changes brightness without turning off

Error handling

Every function in this API rejects with a TorchlightError. It extends Error, so e instanceof Error holds, and it carries a machine-readable kind to branch on.

import { setTorch, TorchlightError } from "tauri-plugin-torchlight-api"

try {
    await setTorch(true)
} catch (e) {
    if (e instanceof TorchlightError) {
        switch (e.kind) {
            case "unsupported":
                // Desktop — the right fix is not to show the button at all
                break
            case "unavailable":
                toast("This device has no torch")
                break
            case "cameraAccess":
                toast("Close the other app that is using the camera")
                break
            case "torchFailed":
                toast("The torch could not be used — the device may be hot")
                break
            case "internal":
                console.error(e.message)
                break
        }
    } else {
        throw e
    }
}

The main cases where setTorch() and toggle() reject, and the kind each one carries:

Situation kind Message
Running on desktop unsupported torchlight is only supported on Android and iOS; this is a desktop platform
Device has no flash unit unavailable Torch is not available on this device
Android cannot access the camera cameraAccess The CameraAccessException message, or Camera access error
The torch could not be driven (thermal limits, etc.) — Android or iOS torchFailed Torch could not be used: ... on iOS; the exception message or The torch could not be used on Android
A missing ACL permission, an IPC failure, or a plugin bug internal Whatever string Tauri rejected with

The message is for humans and is not a stable API — always branch on kind, and better still, check isAvailable() or capabilities() up front.

Limitations

Not supported today
  • No built-in strobe or blink patterns — drive setTorch() from your own timer if you need them.
  • On Android, brightness only works on API 33 and later.

Troubleshooting

The command fails with a permission error

Check that torchlight:default is listed in src-tauri/capabilities/*.json. If you use the event, you also need allow-register-listener and allow-remove-listener.

isAvailable() returns false

You are probably on a device without a flash unit, an emulator or simulator, or desktop. Verify on real hardware.

Brightness changes have no visible effect

Android 12 and earlier, and devices whose FLASH_INFO_STRENGTH_MAXIMUM_LEVEL is 1, do not support brightness control. Turning on at full power is the documented fallback. Check brightnessSupported from capabilities() to detect this up front.

The torch went off when I opened another app

Another app took the camera, or the OS turned it off. Subscribe to onTorchModeChanged to keep the UI correct.

Releases and versioning

tauri-plugin-torchlight on crates.io and tauri-plugin-torchlight-api on npm are published together under the same version number. A push to main triggers the GitHub Actions workflow that publishes both; versions that already exist are skipped.

A test gate runs first: cargo clippy --all-targets -- -D warnings, cargo test, npm run build, and a check that the Cargo.toml and package.json versions agree. Nothing is published if any of them fails.

Publishing then goes to npm first and crates.io second. npm allows an unpublish within 72 hours, while a crates.io yank does not un-publish, so this order means a failure cannot leave a half-release behind.

The project is dual licensed under MIT and Apache-2.0, at your option.

tauri-plugin-torchlight · MIT OR Apache-2.0 · crates.io · npm · GitHub