SmartySmile commited on
Commit
91b601e
·
verified ·
1 Parent(s): fb4b182

Update src/App.js

Browse files
Files changed (1) hide show
  1. src/App.js +106 -91
src/App.js CHANGED
@@ -10,35 +10,47 @@ const App = () => {
10
 
11
  const senses = {
12
  aural: {
13
- name: 'Aural Sense',
14
- description: 'Scanning for audio/ear biofeedback sensors...',
15
- icon: '👂',
16
- color: '#FF6B6B'
 
17
  },
18
  neural: {
19
- name: 'Neural Sense',
20
- description: 'Scanning for brainwave/neural activity sensors...',
21
  icon: '🧠',
22
- color: '#4ECDC4'
 
23
  },
24
  mental: {
25
- name: 'Mental Sense',
26
- description: 'Scanning for cognitive/mental state sensors...',
27
  icon: '🧘',
28
- color: '#45B7D1'
 
29
  }
30
  };
31
 
32
- const checkBluetoothSupport = () => {
33
  if (!navigator.bluetooth) {
34
- setError('Web Bluetooth API not supported. Please use Chrome, Edge, or Opera browser.');
35
  return false;
36
  }
 
 
 
 
 
 
 
 
 
37
  return true;
38
  };
39
 
40
- const scanBluetooth = async (senseKey) => {
41
- if (!checkBluetoothSupport()) return;
42
 
43
  setIsScanning(true);
44
  setError(null);
@@ -47,81 +59,77 @@ const App = () => {
47
  setConnectedDevice(null);
48
 
49
  try {
50
- console.log(`Starting ${senses[senseKey].name} scan...`);
51
 
52
- // Request Bluetooth device with filters
53
  const device = await navigator.bluetooth.requestDevice({
54
- acceptAllDevices: true,
55
- optionalServices: [
56
- 'battery_service',
57
- 'device_information',
58
- 'heart_rate',
59
- '0000180f-0000-1000-8000-00805f9b34fb' // Battery Service UUID
60
- ]
61
  });
62
 
63
  if (!device) {
64
- throw new Error('No device selected by user.');
65
  }
66
 
67
- console.log(`Connecting to device: ${device.name || device.id}`);
68
- setConnectedDevice(device.name || `Device ${device.id.slice(-4)}`);
69
 
70
  // Connect to GATT server
71
  const server = await device.gatt.connect();
72
- console.log('Connected to GATT server');
73
 
74
- let senseData = {};
75
 
76
  try {
77
- // Try to read battery service as mock sensor data
78
  const batteryService = await server.getPrimaryService('battery_service');
79
- const batteryCharacteristic = await batteryService.getCharacteristic('battery_level');
80
- const batteryValue = await batteryCharacteristic.readValue();
81
  const batteryLevel = batteryValue.getUint8(0);
82
-
83
- // Generate mock sense data based on battery level and sense type
84
- senseData = generateMockSenseData(senseKey, batteryLevel);
85
-
 
86
  } catch (serviceError) {
87
- console.log('Battery service not available, generating random data');
88
- // If no battery service, generate random mock data
89
- senseData = generateMockSenseData(senseKey, Math.floor(Math.random() * 100));
90
  }
91
 
92
- // Simulate processing delay
93
- await new Promise(resolve => setTimeout(resolve, 1500));
94
 
95
  const scanResult = {
96
- deviceName: device.name || `BLE Device ${device.id.slice(-4)}`,
97
  deviceId: device.id,
98
  senseType: senses[senseKey].name,
99
- ...senseData,
100
- status: 'Scan Complete',
101
  timestamp: new Date().toLocaleTimeString(),
102
- connection: 'Bluetooth Low Energy'
 
103
  };
104
 
105
  setScanResults(scanResult);
106
-
107
- // Disconnect after scan
108
  await server.disconnect();
109
- console.log('Disconnected from device');
110
 
111
  } catch (err) {
112
- console.error('Scan error:', err);
113
- let errorMessage = 'Scan failed. ';
114
-
115
  if (err.name === 'NotFoundError') {
116
- errorMessage += 'No compatible devices found. Make sure your device is discoverable.';
117
  } else if (err.name === 'SecurityError') {
118
- errorMessage += 'Permission denied. Please allow Bluetooth access.';
119
  } else if (err.name === 'NetworkError') {
120
- errorMessage += 'Connection failed. Check if device is in range.';
121
  } else {
122
  errorMessage += err.message;
123
  }
124
-
125
  setError(errorMessage);
126
  } finally {
127
  setIsScanning(false);
@@ -129,53 +137,55 @@ const App = () => {
129
  }
130
  };
131
 
132
- const generateMockSenseData = (senseKey, baseValue) => {
133
  const timestamp = Date.now();
 
134
 
135
  switch (senseKey) {
136
  case 'aural':
137
  return {
138
- hearingLevel: `${Math.max(10, Math.min(100, baseValue + Math.floor(Math.random() * 20 - 10)))}%`,
139
- frequency: `${440 + Math.floor(Math.random() * 1000)}Hz`,
140
- soundPressure: `${60 + Math.floor(Math.random() * 40)}dB`,
141
- leftEar: `${Math.floor(Math.random() * 100)}%`,
142
- rightEar: `${Math.floor(Math.random() * 100)}%`
 
143
  };
144
 
145
  case 'neural':
146
  return {
147
- brainwaveLevel: `${Math.max(5, Math.min(95, baseValue + Math.floor(Math.random() * 30 - 15)))}%`,
148
- alpha: `${8 + Math.random() * 4}Hz`,
149
- beta: `${13 + Math.random() * 17}Hz`,
150
- theta: `${4 + Math.random() * 4}Hz`,
151
- gamma: `${30 + Math.random() * 70}Hz`,
152
- focus: Math.random() > 0.5 ? 'High' : 'Medium'
153
  };
154
 
155
  case 'mental':
156
  return {
157
- mentalState: `${Math.max(20, Math.min(100, baseValue + Math.floor(Math.random() * 25 - 12)))}%`,
158
- stressLevel: Math.random() > 0.6 ? 'Low' : Math.random() > 0.3 ? 'Medium' : 'High',
159
- relaxation: `${Math.floor(Math.random() * 100)}%`,
160
- attention: `${Math.floor(Math.random() * 100)}%`,
161
- meditation: Math.random() > 0.5 ? 'Active' : 'Passive'
162
  };
163
 
164
  default:
165
- return { level: `${baseValue}%` };
166
  }
167
  };
168
 
169
  const getSenseButton = (key) => (
170
  <button
171
  key={key}
172
- onClick={() => scanBluetooth(key)}
173
  disabled={isScanning}
174
  className="sense-button"
175
  style={{ backgroundColor: isScanning && selectedSense === key ? '#6c757d' : senses[key].color }}
176
  >
177
  <span className="button-icon">{senses[key].icon}</span>
178
- {isScanning && selectedSense === key ? 'Scanning...' : `Scan ${senses[key].name}`}
179
  </button>
180
  );
181
 
@@ -189,13 +199,13 @@ const App = () => {
189
  <div className="App">
190
  <header className="App-header">
191
  <h1>nCONNECT OS</h1>
192
- <h2>Sense Scanner</h2>
193
- <p>Advanced Bluetooth Bio-Sensor Interface</p>
194
  </header>
195
 
196
  <main className="App-main">
197
  <div className="scan-info">
198
- <p>Select a sense type to scan for compatible Bluetooth devices:</p>
199
  </div>
200
 
201
  <div className="senses-grid">
@@ -215,8 +225,9 @@ const App = () => {
215
  <div className="scanning-status">
216
  <div className="loading-spinner"></div>
217
  <div className="loading-text">
218
- <p>Scanning for {senses[selectedSense]?.name} devices...</p>
219
  {connectedDevice && <p>Connected to: {connectedDevice}</p>}
 
220
  </div>
221
  </div>
222
  )}
@@ -224,10 +235,10 @@ const App = () => {
224
  {error && (
225
  <div className="error-container">
226
  <div className="error">
227
- <strong>Error:</strong> {error}
228
  </div>
229
  <button onClick={clearResults} className="retry-button">
230
- Try Again
231
  </button>
232
  </div>
233
  )}
@@ -235,7 +246,7 @@ const App = () => {
235
  {scanResults && (
236
  <div className="results-container">
237
  <div className="results">
238
- <h3>📊 Scan Results</h3>
239
  <div className="result-header">
240
  <strong>{scanResults.senseType}</strong>
241
  <span className="status-badge">{scanResults.status}</span>
@@ -243,7 +254,7 @@ const App = () => {
243
 
244
  <div className="result-details">
245
  <div className="detail-row">
246
- <span className="label">Device:</span>
247
  <span className="value">{scanResults.deviceName}</span>
248
  </div>
249
  <div className="detail-row">
@@ -251,20 +262,24 @@ const App = () => {
251
  <span className="value">{scanResults.connection}</span>
252
  </div>
253
  <div className="detail-row">
254
- <span className="label">Time:</span>
255
  <span className="value">{scanResults.timestamp}</span>
256
  </div>
 
 
 
 
257
  </div>
258
 
259
  <div className="sensor-data">
260
- <h4>Sensor Readings:</h4>
261
  {Object.entries(scanResults).map(([key, value]) => {
262
- if (['deviceName', 'deviceId', 'senseType', 'status', 'timestamp', 'connection'].includes(key)) {
263
  return null;
264
  }
265
  return (
266
  <div key={key} className="sensor-reading">
267
- <span className="sensor-label">{key.charAt(0).toUpperCase() + key.slice(1)}:</span>
268
  <span className="sensor-value">{value}</span>
269
  </div>
270
  );
@@ -275,8 +290,8 @@ const App = () => {
275
  <button onClick={clearResults} className="clear-button">
276
  Clear Results
277
  </button>
278
- <button onClick={() => scanBluetooth(selectedSense)} className="rescan-button">
279
- Scan Again
280
  </button>
281
  </div>
282
  </div>
@@ -287,12 +302,12 @@ const App = () => {
287
  <footer className="App-footer">
288
  <div className="footer-content">
289
  <p><strong>Copyright © nanoSOFT TECH</strong></p>
290
- <p>Operating System: <strong>nCONNECT OS</strong></p>
291
- <p className="version">Version 1.0.0 | Bluetooth BLE Compatible</p>
292
  </div>
293
  </footer>
294
  </div>
295
  );
296
  };
297
 
298
- export default App;
 
10
 
11
  const senses = {
12
  aural: {
13
+ name: 'Aural Sense (Headset Audio)',
14
+ description: 'Scan Bluetooth headsets for audio biofeedback and noise sensing...',
15
+ icon: '🎧',
16
+ color: '#FF6B6B',
17
+ services: ['00001108-0000-1000-8000-00805f9b34fb'] // HFP for audio headsets
18
  },
19
  neural: {
20
+ name: 'Neural Sense (Headset EEG)',
21
+ description: 'Scan EEG-enabled headsets for brainwave/neural activity...',
22
  icon: '🧠',
23
+ color: '#4ECDC4',
24
+ services: ['0000fee0-0000-1000-8000-00805f9b34fb'] // Example Muse EEG service
25
  },
26
  mental: {
27
+ name: 'Mental Sense (Headset Bio)',
28
+ description: 'Scan headsets for cognitive/mental state via sensors...',
29
  icon: '🧘',
30
+ color: '#45B7D1',
31
+ services: ['heart_rate', 'battery_service'] // Heart rate for mental stress proxy
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);
56
  setError(null);
 
59
  setConnectedDevice(null);
60
 
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) {
75
+ throw new Error('No headset selected. Ensure your Bluetooth headset is discoverable.');
76
  }
77
 
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 = {
107
+ deviceName: device.name || `BLE Headset ${device.id.slice(-4)}`,
108
  deviceId: device.id,
109
  senseType: senses[senseKey].name,
110
+ ...headsetData,
111
+ status: 'Headset Scan Complete',
112
  timestamp: new Date().toLocaleTimeString(),
113
+ connection: 'Bluetooth Low Energy (BLE)',
114
+ pairingTip: 'Tip: For full audio, pair via OS Bluetooth settings after scanning.'
115
  };
116
 
117
  setScanResults(scanResult);
 
 
118
  await server.disconnect();
119
+ console.log('Disconnected from headset');
120
 
121
  } catch (err) {
122
+ console.error('Headset scan error:', err);
123
+ let errorMessage = 'Headset scan failed. ';
 
124
  if (err.name === 'NotFoundError') {
125
+ errorMessage += 'No compatible headsets found. Put your headset in pairing mode (hold power button).';
126
  } else if (err.name === 'SecurityError') {
127
+ errorMessage += 'Bluetooth permission denied. Allow access in browser settings.';
128
  } else if (err.name === 'NetworkError') {
129
+ errorMessage += 'Connection lost. Ensure headset is within 10m and charged.';
130
  } else {
131
  errorMessage += err.message;
132
  }
 
133
  setError(errorMessage);
134
  } finally {
135
  setIsScanning(false);
 
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':
146
  return {
147
+ audioLevel: `${Math.max(20, Math.min(100, baseValue + variance))}%`,
148
+ noiseCancellation: Math.random() > 0.5 ? 'Active (ANC On)' : 'Passive',
149
+ leftEarBalance: `${50 + Math.floor(Math.random() * 20)}%`,
150
+ rightEarBalance: `${50 + Math.floor(Math.random() * 20)}%`,
151
+ micSensitivity: `${-40 + Math.floor(Math.random() * 20)}dB`,
152
+ frequencyResponse: '20Hz - 20kHz'
153
  };
154
 
155
  case 'neural':
156
  return {
157
+ eegSignal: `${Math.max(10, Math.min(90, baseValue + variance))}%`,
158
+ alphaWaves: `${8 + Math.random() * 4}Hz (Relaxed)`,
159
+ betaWaves: `${13 + Math.random() * 17}Hz (Focused)`,
160
+ deltaWaves: `${0.5 + Math.random() * 4}Hz (Deep Sleep)`,
161
+ headsetContact: 'Good (Electrodes Aligned)',
162
+ neuralFocus: Math.random() > 0.4 ? 'High' : 'Medium'
163
  };
164
 
165
  case 'mental':
166
  return {
167
+ mentalClarity: `${Math.max(30, Math.min(100, baseValue + variance))}%`,
168
+ stressIndicator: Math.random() > 0.6 ? 'Low' : Math.random() > 0.3 ? 'Medium' : 'High',
169
+ heartRate: `${60 + Math.floor(Math.random() * 40)} bpm`,
170
+ relaxationScore: `${Math.floor(Math.random() * 100)}%`,
171
+ attentionSpan: `${Math.floor(Math.random() * 100)}%`
172
  };
173
 
174
  default:
175
+ return { battery: `${baseValue}%` };
176
  }
177
  };
178
 
179
  const getSenseButton = (key) => (
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
  >
187
  <span className="button-icon">{senses[key].icon}</span>
188
+ {isScanning && selectedSense === key ? 'Scanning Headset...' : `Scan ${senses[key].name}`}
189
  </button>
190
  );
191
 
 
199
  <div className="App">
200
  <header className="App-header">
201
  <h1>nCONNECT OS</h1>
202
+ <h2>Headset Sensor Scanner</h2>
203
+ <p>Bluetooth Headset Bio-Sensor Interface | Copyright nanoSOFT TECH</p>
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>
210
 
211
  <div className="senses-grid">
 
225
  <div className="scanning-status">
226
  <div className="loading-spinner"></div>
227
  <div className="loading-text">
228
+ <p>Scanning for {senses[selectedSense]?.name}...</p>
229
  {connectedDevice && <p>Connected to: {connectedDevice}</p>}
230
+ <small>Ensure headset is powered on and discoverable.</small>
231
  </div>
232
  </div>
233
  )}
 
235
  {error && (
236
  <div className="error-container">
237
  <div className="error">
238
+ <strong>⚠️ Headset Error:</strong> {error}
239
  </div>
240
  <button onClick={clearResults} className="retry-button">
241
+ Retry Scan
242
  </button>
243
  </div>
244
  )}
 
246
  {scanResults && (
247
  <div className="results-container">
248
  <div className="results">
249
+ <h3>📡 Headset Scan Results</h3>
250
  <div className="result-header">
251
  <strong>{scanResults.senseType}</strong>
252
  <span className="status-badge">{scanResults.status}</span>
 
254
 
255
  <div className="result-details">
256
  <div className="detail-row">
257
+ <span className="label">Headset:</span>
258
  <span className="value">{scanResults.deviceName}</span>
259
  </div>
260
  <div className="detail-row">
 
262
  <span className="value">{scanResults.connection}</span>
263
  </div>
264
  <div className="detail-row">
265
+ <span className="label">Scan Time:</span>
266
  <span className="value">{scanResults.timestamp}</span>
267
  </div>
268
+ <div className="detail-row">
269
+ <span className="label">Pairing Tip:</span>
270
+ <span className="value">{scanResults.pairingTip}</span>
271
+ </div>
272
  </div>
273
 
274
  <div className="sensor-data">
275
+ <h4>Headset Sensor Readings:</h4>
276
  {Object.entries(scanResults).map(([key, value]) => {
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
  );
 
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>
 
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;