SunLo is a prototype that turns a stock Android phone into a bench tool for spotting unusual sounds in fans and pumps. An operator selects a machine profile, holds the phone near the running unit, and taps Start check. Three seconds later the app shows Normal, Recheck, or Retake, with a plain-language next step in English or Hindi.
Every live inference runs on the device. There is no cloud API, no account, no network call, and no stored audio. The laptop appears only in the demo as a blind playback source.
This post walks through the architecture, the DSP, the Android audio capture, the model, the tricky parts we hit, and what we would do for a production pilot.
1. Why a phone?
The original concept used an external microcontroller board with a separate microphone. On the bench, that microphone path returned flat PCM through both OTG and TTL; the speaker worked, but the capture path did not. That pushed us to a simpler idea: use the sensor already in every budget Android phone.
A phone gives us:
- a built-in microphone,
- enough CPU for a small classifier,
- a screen for immediate feedback,
- and a form factor an operator can actually carry to the bench.
The tradeoff is acoustic variability. A phone’s mic, AGC, and placement change the signal. We handle that with a capture pipeline that prefers unprocessed audio, a model trained with simulated playback coloration, and a Retake verdict for captures that are too quiet, clipped, or ambiguous.
2. Architecture
┌──────────────────────────────────────────────────────────────────────┐
│ LAPTOP (demo only) │
│ │
│ python server.py │
│ ├─ /player blind sample picker (Fan / Pump) │
│ ├─ /api/library clip IDs for the selected profile │
│ ├─ /api/reveal/id ground-truth label (shown after the check) │
│ └─ /clips/NN.wav real MIMII recordings, level-matched │
│ │
│ Role: play a sound through the laptop speaker. No inference here. │
└───────────────────────────────┬──────────────────────────────────────┘
│ sound through air
▼
┌──────────────────────────────────────────────────────────────────────┐
│ ANDROID PHONE (all inference) │
│ │
│ Expo SDK 54 · React Native 0.81 · TypeScript · Expo Router │
│ │
│ ┌────────────────────────────────────────────────────────────────┐ │
│ │ UI (src/app/index.tsx) │ │
│ │ Fan / Pump selector · Start check · verdict · next step │ │
│ │ English / Hindi switch · sound details · recent checks │ │
│ └───────────────────────┬────────────────────────────────────────┘ │
│ │ capture() │
│ ┌───────────────────────▼────────────────────────────────────────┐ │
│ │ Native module (Kotlin): SunLoMicModule │ │
│ │ AudioRecord → mono PCM16 │ │
│ │ source: UNPROCESSED → VOICE_RECOGNITION → MIC │ │
│ │ rate: 16 kHz → 48 kHz → 44.1 kHz (resampled to 16 kHz) │ │
│ │ prefers TYPE_BUILTIN_MIC, rejects external mic routes │ │
│ └───────────────────────┬────────────────────────────────────────┘ │
│ │ base64 PCM16 (3 s @ 16 kHz) │
│ ┌───────────────────────▼────────────────────────────────────────┐ │
│ │ Classifier (src/classifier.ts) │ │
│ │ centre crop → Hann FFT → 18 log bands → medians + deviations │ │
│ │ Fan: two calibrated logistic models + agreement gate │ │
│ │ Pump: logistic model bundled from Python training │ │
│ │ → verdict + reason + level + spectrum │ │
│ └────────────────────────────────────────────────────────────────┘ │
│ │
│ Bundled models: mobile/assets/fan-mic-model.json, │
│ mobile/assets/pump-model.json │
│ Captured PCM stays in memory for the check and is never saved. │
└──────────────────────────────────────────────────────────────────────┘
The separation matters for honesty:
- Direct-file benchmark — original WAVs fed to the reference Python model.
- Over-the-air handset test — laptop speaker → phone mic → on-device model.
- We never present one as the other.
3. The signal path
3.1 Capture
The native module is a local Expo module (mobile/modules/sunlo-mic). It uses AudioRecord in a foreground capture. The capture loop:
- Checks
RECORD_AUDIOpermission. - Finds a
TYPE_BUILTIN_MICinput device. - Tries audio sources in order:
UNPROCESSED(if the device advertises support),VOICE_RECOGNITION, thenMIC. - Tries sample rates 16 kHz, 48 kHz, and 44.1 kHz.
- Reads 3 seconds of mono PCM16 with non-blocking reads.
- Rejects a routed device that is not the built-in mic (for example, a headset).
- Resamples to 16 kHz if needed and returns base64 PCM to JavaScript.
Why prefer UNPROCESSED? Many phones apply beamforming, noise suppression, and automatic gain control on MIC and VOICE_RECOGNITION. Those transforms can remove exactly the spectral detail a defect check depends on. When a device exposes UNPROCESSED, we use it; otherwise we accept the fallback and keep the Retake gate.
The relevant Kotlin shape:
val sources = mutableListOf(MediaRecorder.AudioSource.VOICE_RECOGNITION)
if (audio.getProperty(AudioManager.PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED) == "true") {
sources.add(0, MediaRecorder.AudioSource.UNPROCESSED)
}
sources.add(MediaRecorder.AudioSource.MIC)
for (source in sources) {
for (rate in intArrayOf(MODEL_RATE, 48000, 44100)) {
val buffer = AudioRecord.getMinBufferSize(
rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT
)
if (buffer <= 0) continue
val recorder = AudioRecord.Builder()
.setAudioSource(source)
.setAudioFormat(AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setChannelMask(AudioFormat.CHANNEL_IN_MONO)
.setSampleRate(rate)
.build())
.setBufferSizeInBytes(maxOf(buffer * 2, rate / 2))
.build()
if (recorder.state != AudioRecord.STATE_INITIALIZED) continue
recorder.setPreferredDevice(builtin)
// read 3 s, then resample to 16 kHz and return PCM16
}
}
Linear resampling to 16 kHz is deliberately simple and portable:
private fun resample(input: ShortArray, rate: Int): ShortArray {
val ratio = rate.toDouble() / MODEL_RATE
return ShortArray(MODEL_RATE * SECONDS) { index ->
val start = index * ratio
val end = min((index + 1) * ratio, input.size.toDouble())
var sample = floor(start).toInt()
var position = start
var sum = 0.0
while (position < end) {
val stop = min((sample + 1).toDouble(), end)
sum += input[sample] * (stop - position)
position = stop
sample++
}
(sum / ratio).roundToInt().coerceIn(-32768, 32767).toShort()
}
}
3.2 Feature extraction
The classifier takes the centre 2.5 seconds of the 3-second capture (dropping 0.25 s at each end) to avoid button taps and capture boundaries. It computes a Hann-windowed 2048-point FFT every 1024 samples, then accumulates power into 18 log-spaced bands from 230 Hz to 6.5 kHz.
const RATE = 16000;
const FFT_SIZE = 2048;
const HOP = 1024;
const BAND_COUNT = 18;
const startSample = 4000;
const sampleCount = RATE * 3;
const bandEdges = Array.from({ length: BAND_COUNT + 1 }, (_, i) =>
230 * (6500 / 230) ** (i / BAND_COUNT),
);
Per frame, each band is log10(power + 1e-9), then the frame mean is subtracted so absolute volume does not dominate. Across frames we take, per band:
- the median log level, and
- the standard deviation of the log level.
That gives a 36-value vector: 18 medians + 18 deviations. The medians describe the spectral shape; the deviations describe how unstable each band is over time. A healthy fan has a stable hum; an abnormal unit often has modulation, rub, or bearing noise that changes the variability.
3.3 Quality gates
Before scoring, the app rejects unusable captures:
if (level < minimumLevel) return finish('retake', 'quiet');
if (clipped / samples.length > 0.015) return finish('retake', 'clipped');
Fan also uses a higher floor (minimumLevel = -44 dBFS) because our phone tests showed that weak playback collapses the spectrum toward silence and produces false positives. A subtle but important lesson: the model’s input distribution matters more than its headline accuracy.
4. The models
4.1 Reference models (Python)
scripts/train.py trains one logistic model per profile from 72 source recordings, augmented with random 3-second crops and simulated speaker/mic equalization. Training uses a held-out split of 24 original recordings per profile.
for variant in range(8):
start = rng.integers(0, len(samples) - SAMPLES + 1)
eq = None
if variant:
# approximate speaker/mic coloration; not measured phone audio
gains = rng.normal(0, 6, len(knots))
gains[:2] -= rng.uniform(1, 18, 2)
eq = 10 ** (np.interp(FREQ, knots, gains) / 10)
features.append(feature_vector(prepare(crop(samples, start)), eq))
labels.append(label)
The logistic classifier is fit with L2 regularization:
x = (x - mean) / scale
for _ in range(1800):
error = logistic(x @ weight + bias) - y
weight -= 0.075 * (x.T @ error / len(x) + 0.018 * weight)
bias -= 0.075 * error.mean()
On the original-file holdout, counting Retakes against the score:
| Profile | Spectral model | Loudness baseline | Missed abnormal | False rechecks | Retakes |
|---|---|---|---|---|---|
| Fan | 18/24 | 16/24 | 1 | 0 | 5 |
| Pump | 20/24 | 20/24 | 2 | 0 | 2 |
4.2 Android Fan model
The original fan model assumed near-line-level audio. Through a phone speaker and mic, the spectrum changes enough that the same weights produced false alarms and, in an early build, missed abnormal clips entirely. We therefore built a separate Android fan model.
scripts/train_android_fan.py pairs 24 labelled handset captures with the corresponding source recordings. It learns a channel shift between source features and phone features, then trains two small models:
- a mixed model on simulated playback features plus handset captures,
- a handset model on the 24 measured captures only.
Both use only the 18 median bands after removing the first few broad DCT components, which suppresses coloration and keeps local spectral detail:
cosine_basis = dct(np.eye(18), axis=0, norm="ortho")[remove_components:]
projection = cosine_basis.T @ cosine_basis
detail = bands @ projection
At inference, the app computes both scores and requires them to agree:
const mixed = fanScore(medians, fanModel.mixed);
const handset = fanScore(medians, fanModel.handset);
const margin = Math.log(0.64 / 0.36);
if (Math.min(mixed, handset) >= margin) return finish('recheck', 'different', medians);
if (Math.max(mixed, handset) <= -margin) return finish('normal', 'match', medians);
return finish('retake', 'unclear', medians);
This is intentionally conservative. When the two views disagree, the operator gets Retake, not a confident wrong answer.
The bundled training data stores 18 spectral-band summaries per capture, no PCM, so we can iterate on the model without shipping raw field audio.
4.3 Pump model
Pump uses the Python-trained model bundled as JSON. The classifier reads it into the same 36-value feature vector and applies the logistic score directly. Pump results are reported separately from Fan results.
4.4 Portability check
We compiled the TypeScript classifier with tsc and ran it against the Python reference on 72 cases: all 48 held-out original WAVs, attenuated Fan captures, silence, and clipping. Every verdict matched, and Pump verdicts remained unchanged after the Fan refit.
This test is part of why we keep the DSP in plain TypeScript instead of adding a native inference runtime: it is small, deterministic, and easy to compare against the Python reference.
5. UI and interaction
The UI was rebuilt for a shop-floor context rather than a generic dashboard. It uses a warm ivory background, rust accents, custom machine illustrations, and a fixed bottom action.
Key decisions:
- Two large machine tiles, not a dropdown. Fan and Pump are always visible and tappable with a glove.
- One persistent action: Start check / Check again lives in a bottom dock.
- Result first, chart second: the verdict and next step appear immediately; sound details are behind a disclosure.
-
Bilingual: English and Hindi copy is in
mobile/src/copy.ts, saved with AsyncStorage, with the device locale as the default. - TalkBack-friendly: roles, labels, live regions, and large tap targets are explicit. We verified the layout at 360 dp and 150% text size.
<Pressable
accessibilityRole="button"
accessibilityState={{ disabled: blocking || !machine, busy: blocking }}
disabled={blocking || !machine}
onPress={startInspection}
style={styles.action}
>
<ListenMark colour={colours.white} size={24} />
<Text style={styles.actionText}>
{blocking ? heading : result || error ? text.again : text.start}
</Text>
</Pressable>
The copy is plain language:
- Normal — “The sound is close to this machine’s normal reference.”
- Recheck — “Set this unit aside for a manual check.”
- Retake — “The sound was too faint. Move the phone’s mic closer and try again.”
A screening result is not a defect diagnosis, and the copy says so.
6. The laptop blind player
server.py is intentionally small. It serves one page and four endpoints:
-
GET /player— sample picker -
GET /api/library?profile=fan|pump— clip IDs -
GET /api/reveal/NN?profile=fan|pump— ground-truth label -
GET /clips/NN.wav?profile=fan|pump— audio with byte-range support
There is no capture endpoint and no model on the laptop. The label is only revealed when the operator clicks Reveal label, after the phone result is recorded.
def do_GET(self):
url = urlsplit(self.path)
if url.path in STATIC:
name, mime = STATIC[url.path]
self.send_payload((ROOT / "web" / name).read_bytes(), f"{mime}; charset=utf-8")
return
profile = parse_qs(url.query).get("profile", ["fan"])
...
The player switched profiles with a native radio group, using the HTML guide’s rule to expose two to five mutually exclusive choices as visible radios. Switching profiles clears playback, selection, and revealed labels to avoid mixing evidence across machines.
7. Build and verification
Build requirements: Node.js 20.19+, Expo SDK 54, Android SDK Platform 36, Build Tools 36, NDK 27, JDK 17.
cd mobile
npm ci
npm run typecheck
npm run lint
npx expo prebuild --platform android --no-install
cd android
NODE_ENV=production ./gradlew :app:assembleRelease \
-PreactNativeArchitectures=arm64-v8a,armeabi-v7a
Release checks we ran:
-
npx expo lintandtsc --noEmitclean. -
npx expo install --checkreports dependencies up to date. -
apksigner verifyon the release APK. - APK installs on a Galaxy S24 Ultra and a compact emulator.
- Both profiles, language switching, permission flow, and verdict states verified on screen.
- 360 dp + 150% text size: both machine tiles and the action button remain on-screen.
- Offline: the app runs with airplane mode enabled.
8. What went wrong, and what we learned
- The external mic path was a dead end. A board with a working speaker still returned flat PCM. Moving to the phone mic removed the entire class of hardware problems.
- A quiet clip is not a normal clip. Weak speaker-to-phone playback pushed the spectrum toward silence and produced false flags. The level floor now rejects weak captures instead of scoring them.
- Original-file accuracy does not transfer automatically. The same classifier that scored 18/24 on WAVs missed an abnormal clip over the air. We built a separate handset-calibrated fan model and kept the file benchmark separate.
- Conservative disagreement beats confident error. Requiring two fan models to agree produces more Retakes, but avoids telling an operator a wrong answer.
- Architecture matters in a shop tool. A fixed action button and large machine tiles worked better than a dense dashboard, especially in Hindi and at larger text sizes.
9. Limitations
- The demo uses one fan ID and one pump ID from MIMII. It does not prove generalization to new machine models.
- Over-the-air results depend on laptop volume, phone model, mic placement, and room noise.
- Room audio can produce a verdict if a machine is not running; the operator still has to hold the phone near the target machine.
- The prototype APK is debug-signed and intended for a controlled demo, not Play Store distribution.
- Normal and Recheck are screening outcomes, not factory release decisions or defect diagnoses.
10. Next steps for a real pilot
- Fix the phone position with a simple cradle and mark the mic location on the fixture.
- Record known-good units of the actual SKU, then fit a profile per SKU.
- Hold out entire physical units, not just random crops from the same recordings.
- Log profile, unit ID, verdict, retakes, and time added per check.
- Add a batch view so repeated rechecks on one station or batch become visible.
- Only then test a second SKU.
The long-term idea is not “an app that knows every machine.” It is a repeatable way for a manufacturer to teach SunLo what their known-good machines sound like, then screen against that reference with a phone they already own.
11. Repository and artifacts
- Repository: https://github.com/harishkotra/sunlo
- Release APK and source bundle: https://github.com/harishkotra/sunlo/releases/tag/v1.1.1
- Data: MIMII, Hitachi, Ltd., CC BY-SA 4.0, https://doi.org/10.5281/zenodo.3384388
- Platforms: Expo SDK 54, React Native 0.81, TypeScript
Code & more: https://www.dailybuild.xyz/project/331-sunlo
Top comments (0)