Build two advanced mobile sensing applications: a Progressive Web App (PWA) with Service Workers for offline multi-sensor data collection, and a participatory noise monitoring system using the Web Audio API that measures decibel levels and tags readings with GPS coordinates for crowdsourced noise mapping.
Key Concepts
Progressive Web App (PWA): A web application that uses modern APIs to deliver app-like experiences; key features: service worker for offline caching, Web App Manifest for home screen installation, and HTTPS for secure sensor API access
Service Worker: A JavaScript file running in a background thread separate from the web page; intercepts network requests for offline caching, enables background sync for sensor data collected without connectivity, and can receive push notifications
Web Audio API: A JavaScript API providing low-level audio processing: capturing microphone input (getUserMedia), analyzing frequency content (AnalyserNode), computing sound level (dB SPL approximation from FFT magnitude), and visualizing waveforms
AudioContext / AnalyserNode: AudioContext manages the Web Audio processing graph; AnalyserNode computes real-time FFT spectrums and time-domain waveforms from microphone input; provides getByteFrequencyData() and getByteTimeDomainData() for visualization
Sound Level Meter Implementation: Approximating dB SPL from AnalyserNode data: sum the RMS of time-domain samples, convert to dB: level_dB = 20 * log10(rms); note this gives relative dB, not calibrated SPL without a reference calibration point
Offline-First Architecture: Designing the application to function without network connectivity by pre-caching sensor UI assets and buffering collected data in IndexedDB or localStorage for later sync; essential for mobile sensing in areas with unreliable connectivity
Web App Manifest: A JSON file (manifest.json) linked from the HTML that describes the app name, icon, theme color, and display mode; enables ‘Add to Home Screen’ on Android and iOS, giving the PWA a native-like launch experience
getUserMedia API: Browser API requesting access to microphone (and camera) streams; requires user permission; returns a MediaStream object that can be connected to Web Audio API nodes or recorded as audio blobs via MediaRecorder
18.1 Learning Objectives
By completing these labs, you will be able to:
Create Progressive Web Apps (PWAs) with offline capability
Implement Service Workers for resource caching
Build installable mobile applications without app stores
Capture smartphone microphone input using the Web Audio API
Process audio data in real-time for noise level measurement
Implement participatory sensing with location-tagged data
18.2 Lab 3: Progressive Web App for Multi-Sensor Data Collection
Objective: Create an installable PWA that collects data from multiple smartphone sensors and works offline.
Materials:
Smartphone
Web server (can use Python’s http.server)
Text editor
For Beginners: What is a Progressive Web App?
A Progressive Web App (PWA) is like a website that pretends to be a real app! You can add it to your home screen, use it offline, and it looks just like any other app on your phone - but you don’t need to download it from an app store.
Think of it like a magic website that can: - Work without internet (it saves stuff on your phone) - Send you notifications - Look and feel like a “real” app
The Sensor Squad says: “PWAs are super cool because they’re easier to make than regular apps, but they can do almost everything a regular app can do!”
18.2.1 Step 1: Create the Main Application (index.html)
18.2.2 Step 2: Create the Web App Manifest (manifest.json)
{"name":"IoT Multi-Sensor App","short_name":"IoT Sensors","description":"Collect data from smartphone sensors for IoT applications","start_url":"/","display":"standalone","background_color":"#ffffff","theme_color":"#007bff","icons":[{"src":"/icon-192.png","sizes":"192x192","type":"image/png"},{"src":"/icon-512.png","sizes":"512x512","type":"image/png"}]}
18.2.3 Step 3: Create the Service Worker (sw.js)
const CACHE_NAME ='iot-sensors-v1';const urlsToCache = ['/','/index.html','/manifest.json'];// Install service worker and cache resourcesself.addEventListener('install',event=> {event.waitUntil( caches.open(CACHE_NAME).then(cache => cache.addAll(urlsToCache)) );});// Serve cached content when offlineself.addEventListener('fetch',event=> {event.respondWith( caches.match(event.request).then(response => response ||fetch(event.request)) );});// Clean up old caches on activationself.addEventListener('activate',event=> {event.waitUntil( caches.keys().then(cacheNames => {returnPromise.all( cacheNames.filter(name => name !== CACHE_NAME).map(name => caches.delete(name)) ); }) );});
18.2.4 Step 4: Serve and Install the PWA
# Start a local web serverpython3-m http.server 8000# Access on smartphone: http://[your-computer-ip]:8000# Use browser's "Add to Home Screen" option to install
18.2.5 PWA Architecture
18.2.6 Expected Learning Outcomes
After completing this lab, you will understand:
Create Progressive Web Apps with offline support
Use Service Workers for caching
Implement installable mobile applications
Access multiple sensors simultaneously
18.2.7 Exercises
Add background sync for uploading data when online using navigator.serviceWorker.sync
Objective: Build a crowdsourced noise level monitoring system using smartphone microphones.
Materials:
Smartphone with microphone
Web browser
Optional: Location services enabled
For Beginners: What is Noise Monitoring?
Sound is vibrations in the air, and we measure how loud sounds are using decibels (dB). Your phone’s microphone can “hear” these vibrations and tell you how loud things are around you!
Here’s what different noise levels feel like: - 0-30 dB: Very quiet, like a library - 30-60 dB: Normal talking volume - 60-80 dB: Busy traffic - 80-100 dB: Lawnmower - getting uncomfortably loud! - 100+ dB: Concert or fireworks - can hurt your ears!
The Sensor Squad explains: “When lots of people use an app like this and share their noise readings, we can make a map of where it’s noisy and where it’s quiet in a whole city! That’s called participatory sensing - everyone participates to help!”
Implement frequency analysis to identify noise sources (traffic vs. construction vs. voices)
Create noise pollution heatmap from crowdsourced data using mapping libraries
Add time-based analysis showing noise patterns throughout the day
Implement privacy-preserving location obfuscation using grid-based reporting (snap to 100m grid)
Label the Diagram
💻 Code Challenge
Order the Steps
Match the Concepts
18.4 Summary
In these two labs, you built advanced mobile sensing applications:
Key Accomplishments
Lab 3 - Progressive Web App:
Created an installable PWA with manifest.json
Implemented Service Worker for offline caching
Built multi-sensor data collection (accelerometer, gyroscope, GPS, light)
Added automatic sync when connectivity restored
Lab 4 - Noise Monitoring:
Accessed microphone using Web Audio API
Processed audio with FFT analysis
Calculated dB levels from RMS values
Implemented participatory sensing with location tagging
Worked Example: Calculating Sound Pressure Level from Web Audio API
Objective: Convert raw audio samples from the microphone into meaningful decibel (dB) measurements for noise monitoring.
The challenge: The Web Audio API provides raw audio samples (0-255 byte values), but we need dB SPL (Sound Pressure Level) for noise pollution monitoring. How do we convert?
// RMS = sqrt(sum of squares / count)functioncalculateRMS(dataArray) {let sum =0;for (let i =0; i < dataArray.length; i++) { sum += dataArray[i] * dataArray[i]; }returnMath.sqrt(sum / dataArray.length);}const rms =calculateRMS(dataArray);// Result: 0-255
Step 3: Convert RMS to dB (simplified)
// Decibel formula: dB = 20 × log10(RMS / reference)// For Web Audio API, we use a heuristic conversionfunctionrmsToDecibels(rms) {// Add 1 to avoid log10(0) = -Infinity// Scale factor chosen empiricallyreturnMath.round(20*Math.log10(rms +1));}const db =rmsToDecibels(rms);console.log(`Noise level: ${db} dB`);
Why this is an approximation:
Professional sound level meters:
Calibrated microphone: Known sensitivity (e.g., 50 mV/Pa)
Reference SPL: 20 µPa (threshold of human hearing)
Frequency weighting: A-weighting filter mimics human ear sensitivity
Time weighting: Fast (125ms) or Slow (1s) averaging
This works because relative comparisons are valid even without calibration. A reading of 40 dB on one phone and 42 dB on another phone at the same location still indicates “both phones measured loud noise.”
For research/regulatory use: Use professional calibrated sound level meters (Class 1: ±1 dB, Class 2: ±2 dB) that cost $200-2000. Smartphone apps are useful for crowdsourcing relative noise patterns but not for legal compliance measurements.
Key insight: Web Audio API provides uncalibrated relative measurements. Useful for identifying noisy vs. quiet areas (heatmaps), detecting anomalies (sudden loud event), and comparing trends over time - but not for regulatory compliance or medical diagnosis without proper calibration.
18.5 Knowledge Checks
Question 1: PWA Architecture
What is the primary role of a Service Worker in a Progressive Web App?
To increase the phone’s sensor sampling rate
To intercept network requests and serve cached resources when offline
To connect directly to Bluetooth sensors
To replace the phone’s operating system
Answer
B) To intercept network requests and serve cached resources when offline. Service Workers act as a programmable proxy between the web app and the network. During installation, they cache essential resources (HTML, CSS, JavaScript). When the device goes offline, the Service Worker intercepts fetch requests and serves the cached versions, allowing the app to function without connectivity – critical for field data collection in areas with poor coverage.
Question 2: Audio Sensing
In the noise monitoring lab, why is the dB calculation described as a “rough approximation” rather than a precise measurement?
The Web Audio API does not support microphones
Smartphone microphones are not calibrated against a reference sound pressure level
The FFT algorithm is too slow for real-time processing
Answer
B) Smartphone microphones are not calibrated against a reference sound pressure level. Professional sound level meters are calibrated against a known 94 dB or 114 dB reference tone, with frequency weighting (A-weighting) applied. Smartphone microphones vary in sensitivity between models and have automatic gain control that adjusts input levels. The dB values from the Web Audio API are relative, not absolute, so they are useful for comparing levels but not for regulatory compliance measurements.
Key Takeaway
PWAs with Service Workers solve the fundamental offline challenge of mobile IoT sensing – data collection must not stop when connectivity does. Combined with the Web Audio API for sound sensing and Geolocation for spatial tagging, you can build a complete participatory sensing platform using only web technologies, deployable to any device with a modern browser.
For Kids: Meet the Sensor Squad!
Sammy the Sensor was proud of what the team built today. “We made a magic website that works even without internet!”
“How is that possible?” Lila the LED asked, puzzled. “Websites need the internet!”
Max the Microcontroller explained: “It is called a Progressive Web App. When you first visit the website, a helper called a Service Worker saves a copy of everything onto your phone. So the next time you open it – even in an airplane or a cave – it works perfectly!”
“That is amazing!” Lila blinked. “What about the noise measuring app?”
Bella the Battery jumped in. “That one uses the phone’s microphone to listen to how loud things are. It measures sound in decibels – that is like a ruler for noise. A library is about 30 decibels. A rock concert is over 100 decibels – ouch!”
Sammy added, “And the coolest part is that the app also records WHERE you measured the noise using GPS. So if thousands of kids all around a city use the app, we can make a giant map showing quiet neighborhoods and noisy ones!”
“Like a treasure map, but for sound!” Lila exclaimed.
“Exactly! And since the data saves on your phone when there is no internet, you never lose a single measurement,” Max added. “The Service Worker stores it safely until you are back online.”
The Sensor Squad Lesson: PWAs are websites with superpowers – they work offline and can be installed like real apps. Combined with the microphone and GPS, you can build apps that measure sound levels anywhere and help create noise maps of entire cities!
18.6 Knowledge Check
Quiz: PWA and Audio Sensing
Interactive Quiz: Match PWA and Audio Sensing Concepts Concepts
Interactive Quiz: Sequence the Steps
Common Pitfalls
1. Service Worker Caching Breaking Development Updates
Once a service worker is installed, it serves cached assets even when you update the files. During development, hard-refresh (Ctrl+Shift+R) or unregister the service worker in DevTools to force a fresh load. In production, version your cache keys so updated deployments invalidate old cached files.
2. Web Audio API Context Suspended Until User Gesture
Modern browsers prevent AudioContext from starting until a user interaction (click, tap). If you create AudioContext on page load, it starts in ‘suspended’ state and microphone capture fails silently. Always call audioContext.resume() inside a user gesture event handler before starting audio capture.
3. Sound Level Measurements Not Calibrated in Absolute dB SPL
Web Audio API provides relative amplitude values, not calibrated sound pressure level. The dB values computed from AnalyserNode are device and microphone dependent — a 70 dB reading on one smartphone may correspond to 65 dB on another. To get calibrated SPL, measure against a reference sound level meter and apply a device-specific offset correction.
4. PWA Install Prompt Not Shown Due to Missing Requirements
The browser will only display the ‘Add to Home Screen’ prompt if specific criteria are met: served over HTTPS, has a valid manifest with icons, and a registered service worker. Missing any one of these silently prevents the install prompt. Verify all three in Chrome DevTools > Application > Manifest before expecting the install prompt to appear.
18.7 What’s Next
If you want to…
Read this
Explore mobile sensor Web APIs for motion and location