SmartySmile commited on
Commit
26c01af
·
verified ·
1 Parent(s): 983e818

Update src/App.js

Browse files
Files changed (1) hide show
  1. src/App.js +170 -56
src/App.js CHANGED
@@ -1,4 +1,4 @@
1
- import React, { useState } from 'react';
2
  import './App.css';
3
 
4
  const App = () => {
@@ -7,6 +7,11 @@ const App = () => {
7
  const [error, setError] = useState(null);
8
  const [selectedSense, setSelectedSense] = useState('');
9
  const [connectedDevice, setConnectedDevice] = useState(null);
 
 
 
 
 
10
 
11
  const senses = {
12
  aural: {
@@ -32,24 +37,103 @@ const App = () => {
32
  }
33
  };
34
 
35
- const checkBluetoothSupport = async () => {
 
 
 
 
 
 
36
  if (!navigator.bluetooth) {
37
- setError('Web Bluetooth API not supported. Use Chrome/Edge for headset scanning.');
38
- return false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  try {
41
- const available = await navigator.bluetooth.getAvailability();
42
- if (!available) {
43
- setError('Bluetooth is disabled. Enable it in your device settings to scan headsets.');
44
- return false;
 
 
 
 
 
 
 
 
 
 
45
  }
46
  } catch (err) {
47
- console.warn('Bluetooth availability check failed:', err);
 
 
 
 
48
  }
49
- return true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  };
51
 
52
  const scanBluetoothHeadset = async (senseKey) => {
 
 
 
 
 
53
  if (!await checkBluetoothSupport()) return;
54
 
55
  setIsScanning(true);
@@ -61,14 +145,13 @@ const App = () => {
61
  try {
62
  console.log(`Scanning for ${senses[senseKey].name} headsets...`);
63
 
64
- // Filter for headset-like devices
65
  const device = await navigator.bluetooth.requestDevice({
66
  filters: [
67
- { namePrefix: ['Headset', 'Earbuds', 'Audio', 'Muse', 'Emotiv'] }, // Name filters for headsets
68
- { services: senses[senseKey].services } // Sense-specific services
69
  ],
70
  optionalServices: ['battery_service', 'device_information', ...senses[senseKey].services],
71
- acceptAllDevices: false // Strict filtering for headsets
72
  });
73
 
74
  if (!device) {
@@ -78,29 +161,23 @@ const App = () => {
78
  console.log(`Connecting to headset: ${device.name || device.id}`);
79
  setConnectedDevice(device.name || `Headset ${device.id.slice(-4)}`);
80
 
81
- // Connect to GATT server
82
  const server = await device.gatt.connect();
83
  console.log('Connected to headset GATT server');
84
 
85
  let headsetData = {};
86
 
87
  try {
88
- // Read battery as base for sensor readiness
89
  const batteryService = await server.getPrimaryService('battery_service');
90
  const batteryChar = await batteryService.getCharacteristic('battery_level');
91
  const batteryValue = await batteryChar.readValue();
92
  const batteryLevel = batteryValue.getUint8(0);
93
 
94
- // Read sense-specific data (mocked; replace with real characteristics)
95
  headsetData = generateHeadsetSensorData(senseKey, batteryLevel);
96
-
97
- // For real headsets: Add reads like await char.readValue() for custom UUIDs
98
  } catch (serviceError) {
99
  console.log('Headset services not fully available, using mock data');
100
  headsetData = generateHeadsetSensorData(senseKey, Math.floor(Math.random() * 100));
101
  }
102
 
103
- // Simulate data processing (e.g., headset sensor delay)
104
  await new Promise(resolve => setTimeout(resolve, 2000));
105
 
106
  const scanResult = {
@@ -137,9 +214,26 @@ const App = () => {
137
  }
138
  };
139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  const generateHeadsetSensorData = (senseKey, baseValue) => {
141
  const timestamp = Date.now();
142
- const variance = Math.floor(Math.random() * 20 - 10); // Small variation
143
 
144
  switch (senseKey) {
145
  case 'aural':
@@ -180,7 +274,7 @@ const App = () => {
180
  <button
181
  key={key}
182
  onClick={() => scanBluetoothHeadset(key)}
183
- disabled={isScanning}
184
  className="sense-button"
185
  style={{ backgroundColor: isScanning && selectedSense === key ? '#6c757d' : senses[key].color }}
186
  >
@@ -195,6 +289,16 @@ const App = () => {
195
  setSelectedSense('');
196
  };
197
 
 
 
 
 
 
 
 
 
 
 
198
  return (
199
  <div className="App">
200
  <header className="App-header">
@@ -204,6 +308,50 @@ const App = () => {
204
  </header>
205
 
206
  <main className="App-main">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  <div className="scan-info">
208
  <p>Put your Bluetooth headset in pairing mode and select a sense type to scan:</p>
209
  </div>
@@ -277,37 +425,3 @@ const App = () => {
277
  if (['deviceName', 'deviceId', 'senseType', 'status', 'timestamp', 'connection', 'pairingTip'].includes(key)) {
278
  return null;
279
  }
280
- return (
281
- <div key={key} className="sensor-reading">
282
- <span className="sensor-label">{key.replace(/([A-Z])/g, ' $1').trim()}:</span>
283
- <span className="sensor-value">{value}</span>
284
- </div>
285
- );
286
- })}
287
- </div>
288
-
289
- <div className="result-actions">
290
- <button onClick={clearResults} className="clear-button">
291
- Clear Results
292
- </button>
293
- <button onClick={() => scanBluetoothHeadset(selectedSense)} className="rescan-button">
294
- Rescan Headset
295
- </button>
296
- </div>
297
- </div>
298
- </div>
299
- )}
300
- </main>
301
-
302
- <footer className="App-footer">
303
- <div className="footer-content">
304
- <p><strong>Copyright © nanoSOFT TECH</strong></p>
305
- <p>Operating System: <strong>nCONNECT OS</strong> | BLE Headset Compatible</p>
306
- <p className="version">Version 2.0 | For Audio & Bio-Sensor Headsets</p>
307
- </div>
308
- </footer>
309
- </div>
310
- );
311
- };
312
-
313
- export default App;
 
1
+ import React, { useState, useEffect } from 'react';
2
  import './App.css';
3
 
4
  const App = () => {
 
7
  const [error, setError] = useState(null);
8
  const [selectedSense, setSelectedSense] = useState('');
9
  const [connectedDevice, setConnectedDevice] = useState(null);
10
+
11
+ // New states for permissions
12
+ const [bluetoothStatus, setBluetoothStatus] = useState('checking'); // 'checking', 'ready', 'needed', 'unsupported'
13
+ const [locationStatus, setLocationStatus] = useState('checking'); // 'checking', 'ready', 'needed', 'unsupported'
14
+ const [showPermissions, setShowPermissions] = useState(true);
15
 
16
  const senses = {
17
  aural: {
 
37
  }
38
  };
39
 
40
+ // Check permissions on mount
41
+ useEffect(() => {
42
+ checkPermissions();
43
+ }, []);
44
+
45
+ const checkPermissions = async () => {
46
+ // Check Bluetooth
47
  if (!navigator.bluetooth) {
48
+ setBluetoothStatus('unsupported');
49
+ } else {
50
+ try {
51
+ const available = await navigator.bluetooth.getAvailability();
52
+ setBluetoothStatus(available ? 'ready' : 'needed');
53
+ } catch (err) {
54
+ setBluetoothStatus('needed');
55
+ }
56
+ }
57
+
58
+ // Check Location (for Android BLE)
59
+ if (!navigator.geolocation) {
60
+ setLocationStatus('unsupported');
61
+ } else {
62
+ try {
63
+ const permission = await navigator.permissions.query({ name: 'geolocation' });
64
+ setLocationStatus(permission.state === 'granted' ? 'ready' : 'needed');
65
+ } catch (err) {
66
+ setLocationStatus('needed'); // Assume needed if query fails
67
+ }
68
  }
69
+
70
+ // Hide permissions panel if both ready
71
+ if (bluetoothStatus === 'ready' && locationStatus === 'ready') {
72
+ setShowPermissions(false);
73
+ }
74
+ };
75
+
76
+ const requestBluetoothPermission = async () => {
77
+ if (!navigator.bluetooth) {
78
+ setError('Web Bluetooth not supported. Use Chrome/Edge.');
79
+ return;
80
+ }
81
+
82
  try {
83
+ setBluetoothStatus('checking');
84
+ // Lightweight request to trigger prompt (without full scan)
85
+ const device = await navigator.bluetooth.requestDevice({
86
+ filters: [{ services: ['battery_service'] }],
87
+ optionalServices: ['battery_service'],
88
+ acceptAllDevices: false
89
+ });
90
+ if (device) {
91
+ setBluetoothStatus('ready');
92
+ // Disconnect immediately
93
+ if (device.gatt) device.gatt.disconnect();
94
+ checkPermissions(); // Re-check
95
+ } else {
96
+ setBluetoothStatus('needed');
97
  }
98
  } catch (err) {
99
+ console.error('Bluetooth request failed:', err);
100
+ setBluetoothStatus('needed');
101
+ if (err.name === 'SecurityError') {
102
+ setError('Bluetooth access denied. Allow in browser settings.');
103
+ }
104
  }
105
+ };
106
+
107
+ const requestLocationPermission = () => {
108
+ if (!navigator.geolocation) {
109
+ setError('Geolocation not supported. Enable Location in device settings.');
110
+ return;
111
+ }
112
+
113
+ setLocationStatus('checking');
114
+ navigator.geolocation.getCurrentPosition(
115
+ (position) => {
116
+ setLocationStatus('ready');
117
+ checkPermissions();
118
+ console.log('Location permission granted');
119
+ },
120
+ (error) => {
121
+ setLocationStatus('needed');
122
+ console.error('Location permission denied:', error);
123
+ if (error.code === error.PERMISSION_DENIED) {
124
+ setError('Location access denied. Enable in Chrome settings and device Location services.');
125
+ }
126
+ },
127
+ { enableHighAccuracy: false, timeout: 5000, maximumAge: 0 }
128
+ );
129
  };
130
 
131
  const scanBluetoothHeadset = async (senseKey) => {
132
+ if (bluetoothStatus !== 'ready' || locationStatus !== 'ready') {
133
+ setError('Please enable Bluetooth and Location permissions first.');
134
+ return;
135
+ }
136
+
137
  if (!await checkBluetoothSupport()) return;
138
 
139
  setIsScanning(true);
 
145
  try {
146
  console.log(`Scanning for ${senses[senseKey].name} headsets...`);
147
 
 
148
  const device = await navigator.bluetooth.requestDevice({
149
  filters: [
150
+ { namePrefix: ['Headset', 'Earbuds', 'Audio', 'Muse', 'Emotiv'] },
151
+ { services: senses[senseKey].services }
152
  ],
153
  optionalServices: ['battery_service', 'device_information', ...senses[senseKey].services],
154
+ acceptAllDevices: false
155
  });
156
 
157
  if (!device) {
 
161
  console.log(`Connecting to headset: ${device.name || device.id}`);
162
  setConnectedDevice(device.name || `Headset ${device.id.slice(-4)}`);
163
 
 
164
  const server = await device.gatt.connect();
165
  console.log('Connected to headset GATT server');
166
 
167
  let headsetData = {};
168
 
169
  try {
 
170
  const batteryService = await server.getPrimaryService('battery_service');
171
  const batteryChar = await batteryService.getCharacteristic('battery_level');
172
  const batteryValue = await batteryChar.readValue();
173
  const batteryLevel = batteryValue.getUint8(0);
174
 
 
175
  headsetData = generateHeadsetSensorData(senseKey, batteryLevel);
 
 
176
  } catch (serviceError) {
177
  console.log('Headset services not fully available, using mock data');
178
  headsetData = generateHeadsetSensorData(senseKey, Math.floor(Math.random() * 100));
179
  }
180
 
 
181
  await new Promise(resolve => setTimeout(resolve, 2000));
182
 
183
  const scanResult = {
 
214
  }
215
  };
216
 
217
+ const checkBluetoothSupport = async () => {
218
+ if (!navigator.bluetooth) {
219
+ setError('Web Bluetooth API not supported. Use Chrome/Edge for headset scanning.');
220
+ return false;
221
+ }
222
+ try {
223
+ const available = await navigator.bluetooth.getAvailability();
224
+ if (!available) {
225
+ setError('Bluetooth is disabled. Use the Enable Bluetooth button above.');
226
+ return false;
227
+ }
228
+ } catch (err) {
229
+ console.warn('Bluetooth availability check failed:', err);
230
+ }
231
+ return true;
232
+ };
233
+
234
  const generateHeadsetSensorData = (senseKey, baseValue) => {
235
  const timestamp = Date.now();
236
+ const variance = Math.floor(Math.random() * 20 - 10);
237
 
238
  switch (senseKey) {
239
  case 'aural':
 
274
  <button
275
  key={key}
276
  onClick={() => scanBluetoothHeadset(key)}
277
+ disabled={isScanning || bluetoothStatus !== 'ready' || locationStatus !== 'ready'}
278
  className="sense-button"
279
  style={{ backgroundColor: isScanning && selectedSense === key ? '#6c757d' : senses[key].color }}
280
  >
 
289
  setSelectedSense('');
290
  };
291
 
292
+ const getStatusIcon = (status) => {
293
+ switch (status) {
294
+ case 'ready': return '✅';
295
+ case 'needed': return '⚠️';
296
+ case 'checking': return '⏳';
297
+ case 'unsupported': return '❌';
298
+ default: return '❓';
299
+ }
300
+ };
301
+
302
  return (
303
  <div className="App">
304
  <header className="App-header">
 
308
  </header>
309
 
310
  <main className="App-main">
311
+ {showPermissions && (
312
+ <div className="permissions-setup">
313
+ <h3>🔧 Setup Permissions (Required for Scanning)</h3>
314
+ <p>Enable Bluetooth and Location for headset discovery (especially on Android).</p>
315
+
316
+ <div className="permission-row">
317
+ <div className="permission-item">
318
+ <span className="status-icon">{getStatusIcon(bluetoothStatus)}</span>
319
+ <span className="status-label">Bluetooth: {bluetoothStatus}</span>
320
+ {bluetoothStatus === 'needed' && (
321
+ <button onClick={requestBluetoothPermission} className="permission-button bluetooth-btn">
322
+ Enable Bluetooth
323
+ </button>
324
+ )}
325
+ {bluetoothStatus === 'unsupported' && <span className="unsupported-text">Not supported in this browser</span>}
326
+ </div>
327
+ </div>
328
+
329
+ <div className="permission-row">
330
+ <div className="permission-item">
331
+ <span className="status-icon">{getStatusIcon(locationStatus)}</span>
332
+ <span className="status-label">Location: {locationStatus}</span>
333
+ {locationStatus === 'needed' && (
334
+ <button onClick={requestLocationPermission} className="permission-button location-btn">
335
+ Grant Location Access
336
+ </button>
337
+ )}
338
+ {locationStatus === 'unsupported' && <span className="unsupported-text">Not supported in this browser</span>}
339
+ </div>
340
+ </div>
341
+
342
+ <p className="permission-tip">
343
+ After granting, refresh the page or click "Check Again" below. On Android: Go to Settings > Apps > Chrome > Permissions.
344
+ </p>
345
+ <button onClick={checkPermissions} className="check-again-btn">Check Again</button>
346
+ </div>
347
+ )}
348
+
349
+ {!showPermissions && (
350
+ <div className="permissions-ready">
351
+ <p>✅ Permissions ready! You can now scan headsets.</p>
352
+ </div>
353
+ )}
354
+
355
  <div className="scan-info">
356
  <p>Put your Bluetooth headset in pairing mode and select a sense type to scan:</p>
357
  </div>
 
425
  if (['deviceName', 'deviceId', 'senseType', 'status', 'timestamp', 'connection', 'pairingTip'].includes(key)) {
426
  return null;
427
  }