SmartySmile commited on
Commit
d567abc
·
verified ·
1 Parent(s): 162b511

Update src/App.js

Browse files
Files changed (1) hide show
  1. src/App.js +115 -151
src/App.js CHANGED
@@ -1,180 +1,144 @@
1
- import React, { useState, useRef, useEffect } from 'react';
2
- import * as tf from '@tensorflow/tfjs';
3
- import * as cocoSsd from '@tensorflow-models/coco-ssd';
4
- import './App.css';
5
 
6
- const App = () => {
7
- const [isScanning, setIsScanning] = useState(false);
8
- const [error, setError] = useState(null);
9
- const [predictions, setPredictions] = useState([]);
10
- const [model, setModel] = useState(null);
11
- const [detectionInterval, setDetectionInterval] = useState(null);
12
- const videoRef = useRef(null);
13
- const canvasRef = useRef(null);
14
- const streamRef = useRef(null);
15
-
16
- const videoConstraints = {
17
- width: 640,
18
- height: 480,
19
- facingMode: 'user'
20
- };
21
 
22
- useEffect(() => {
23
- const loadModel = async () => {
24
- try {
25
- await tf.setBackend('webgl');
26
- const loadedModel = await cocoSsd.load();
27
- setModel(loadedModel);
28
- console.log('Neural sensor model loaded – Ready for object detection.');
29
- } catch (err) {
30
- setError('Failed to load detection model.');
31
- console.error('Model load error:', err);
32
- }
33
- };
34
- loadModel();
35
 
36
- return () => {
37
- if (streamRef.current) {
38
- streamRef.current.getTracks().forEach(track => track.stop());
39
- }
40
- };
41
- }, []);
42
-
43
- const predictObjects = async () => {
44
- if (videoRef.current && videoRef.current.videoWidth > 0 && model && isScanning) {
45
- try {
46
- const predictionsArray = await model.detect(videoRef.current);
47
- setPredictions(predictionsArray);
48
- drawPredictions(predictionsArray);
49
- if (predictionsArray.length > 0) {
50
- console.log('Detected objects:', predictionsArray.map(p => p.class));
51
- if ('speechSynthesis' in window) {
52
- const utterance = new SpeechSynthesisUtterance(`Detected ${predictionsArray[0].class}`);
53
- speechSynthesis.speak(utterance);
54
- }
55
- }
56
- } catch (err) {
57
- console.error('Detection error:', err);
58
- }
59
  }
60
  };
61
 
62
- const drawPredictions = (preds) => {
63
- const canvas = canvasRef.current;
64
- if (!canvas || !videoRef.current) return;
65
- const ctx = canvas.getContext('2d');
66
- const video = videoRef.current;
67
- canvas.width = video.videoWidth;
68
- canvas.height = video.videoHeight;
69
- ctx.clearRect(0, 0, canvas.width, canvas.height);
70
-
71
- ctx.save();
72
- ctx.scale(-1, 1);
73
- ctx.translate(-canvas.width, 0);
74
-
75
- preds.forEach(pred => {
76
- const [x, y, width, height] = pred.bbox;
77
- ctx.strokeStyle = '#00ff00';
78
- ctx.lineWidth = 2;
79
- ctx.strokeRect(-x - width, y, width, height);
80
- ctx.fillStyle = '#00ff00';
81
- ctx.font = '16px Arial';
82
- ctx.fillText(`${pred.class} (${Math.round(pred.score * 100)}%)`, -x - width, y - 5);
83
- });
84
-
85
- ctx.restore();
86
- };
87
 
88
- const startScanning = async () => {
89
  try {
90
- const stream = await navigator.mediaDevices.getUser Media({
91
- video: videoConstraints,
92
- audio: false
 
 
93
  });
94
- streamRef.current = stream;
95
- if (videoRef.current) {
96
- videoRef.current.srcObject = stream;
97
- videoRef.current.play();
98
- }
99
- setIsScanning(true);
100
- setError(null);
101
- const interval = setInterval(predictObjects, 500);
102
- setDetectionInterval(interval);
103
- console.log('Front camera sensor activated – Neural detection started.');
104
  } catch (err) {
105
- setError('Failed to access front camera. Check permissions and HTTPS.');
106
- console.error('Scan error:', err);
107
  }
108
- };
109
 
110
- const stopScanning = () => {
111
- setIsScanning(false);
112
- if (detectionInterval) {
113
- clearInterval(detectionInterval);
114
- setDetectionInterval(null);
 
 
 
 
 
115
  }
116
- setPredictions([]);
117
- if (streamRef.current) {
118
- streamRef.current.getTracks().forEach(track => track.stop());
119
- streamRef.current = null;
 
 
 
 
 
 
 
120
  }
121
- if (videoRef.current) {
122
- videoRef.current.srcObject = null;
 
 
 
 
123
  }
124
- console.log('Sensor scan stopped – Neural processing halted.');
 
125
  };
126
 
 
 
 
 
 
 
 
 
 
127
  return (
128
  <div className="App">
129
  <header className="App-header">
130
- <h1>Aural Mental Neural Sense App</h1>
131
- <p>Front Camera Sensor with Object Detection (Native Fallback)</p>
132
- {error && <p style={{ color: 'red' }}>{error}</p>}
133
 
134
- {!isScanning ? (
135
- <button onClick={startScanning}>Activate Neural Sensor (Front Camera)</button>
 
 
136
  ) : (
137
  <div>
138
- <div style={{ position: 'relative', display: 'inline-block' }}>
139
- <video
140
- ref={videoRef}
141
- autoPlay
142
- muted
143
- playsInline
144
- style={{
145
- width: '100%',
146
- maxWidth: '640px',
147
- transform: 'scaleX(-1)',
148
- border: '2px solid #00ff00'
149
- }}
150
- />
151
- <canvas
152
- ref={canvasRef}
153
- style={{
154
- position: 'absolute',
155
- top: 0,
156
- left: 0,
157
- width: '640px',
158
- height: '480px',
159
- pointerEvents: 'none',
160
- transform: 'scaleX(-1)',
161
- border: '2px solid #00ff00'
162
- }}
163
- />
164
- </div>
165
- <br />
166
- <button onClick={stopScanning}>Deactivate Sensor</button>
167
- <p>Sensor active: Detecting objects in real-time. Predictions: {predictions.length}</p>
168
- <ul>
169
- {predictions.map((pred, index) => (
170
- <li key={index}>{pred.class} - Confidence: {Math.round(pred.score * 100)}%</li>
171
- ))}
172
- </ul>
173
  </div>
174
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  </header>
176
  </div>
177
  );
178
- };
179
 
180
- export default App;
 
1
+ import React, { useState, useEffect } from 'react';
2
+ import './App.css'; // Optional: Add styles below
 
 
3
 
4
+ const COPYRIGHT = 'Copyright © nanoSOFT TECH 2023. Powered by nCONNECT OS.';
5
+ const BLE_SERVICE_UUID = '12345678-1234-1234-1234-123456789abc'; // Mock service UUID
6
+ const AURAL_CHAR_UUID = '87654321-4321-4321-4321-cba987654321'; // Mock for aural sense
7
+ const NEURAL_CHAR_UUID = '87654321-4321-4321-4321-cba987654322'; // Mock for neural sense
8
+ const MENTAL_CHAR_UUID = '87654321-4321-4321-4321-cba987654323'; // Mock for mental sense
 
 
 
 
 
 
 
 
 
 
9
 
10
+ function App() {
11
+ const [device, setDevice] = useState(null);
12
+ const [scans, setScans] = useState({
13
+ aural: { connected: false, data: null },
14
+ neural: { connected: false, data: null },
15
+ mental: { connected: false, data: null }
16
+ });
17
+ const [error, setError] = useState('');
18
+ const [isScanning, setIsScanning] = useState(false);
 
 
 
 
19
 
20
+ // Connect to Bluetooth device
21
+ const connectDevice = async () => {
22
+ try {
23
+ setError('');
24
+ setIsScanning(true);
25
+ const bleDevice = await navigator.bluetooth.requestDevice({
26
+ filters: [{ services: [BLE_SERVICE_UUID] }],
27
+ optionalServices: [BLE_SERVICE_UUID]
28
+ });
29
+ setDevice(bleDevice);
30
+ await bleDevice.gatt.connect();
31
+ console.log('Connected to', bleDevice.name);
32
+ startScanning(bleDevice.gatt);
33
+ } catch (err) {
34
+ setError(`Bluetooth connection failed: ${err.message}`);
35
+ } finally {
36
+ setIsScanning(false);
 
 
 
 
 
 
37
  }
38
  };
39
 
40
+ // Start scanning mock data from GATT characteristics
41
+ const startScanning = async (gattServer) => {
42
+ const service = await gattServer.getPrimaryService(BLE_SERVICE_UUID);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ // Aural sense scan (mock audio frequency data)
45
  try {
46
+ const auralChar = await service.getCharacteristic(AURAL_CHAR_UUID);
47
+ await auralChar.startNotifications();
48
+ auralChar.addEventListener('characteristicvaluechanged', (event) => {
49
+ const value = event.target.value.getUint8(0); // Mock: 0-255 intensity
50
+ setScans(prev => ({ ...prev, aural: { connected: true, data: value } }));
51
  });
 
 
 
 
 
 
 
 
 
 
52
  } catch (err) {
53
+ console.warn('Aural scan unavailable:', err);
 
54
  }
 
55
 
56
+ // Neural sense scan (mock brainwave amplitude)
57
+ try {
58
+ const neuralChar = await service.getCharacteristic(NEURAL_CHAR_UUID);
59
+ await neuralChar.startNotifications();
60
+ neuralChar.addEventListener('characteristicvaluechanged', (event) => {
61
+ const value = event.target.value.getFloat32(0, true); // Mock: -100 to 100 Hz
62
+ setScans(prev => ({ ...prev, neural: { connected: true, data: value } }));
63
+ });
64
+ } catch (err) {
65
+ console.warn('Neural scan unavailable:', err);
66
  }
67
+
68
+ // Mental sense scan (mock focus level)
69
+ try {
70
+ const mentalChar = await service.getCharacteristic(MENTAL_CHAR_UUID);
71
+ await mentalChar.startNotifications();
72
+ mentalChar.addEventListener('characteristicvaluechanged', (event) => {
73
+ const value = event.target.value.getUint8(0); // Mock: 0-100% focus
74
+ setScans(prev => ({ ...prev, mental: { connected: true, data: value } }));
75
+ });
76
+ } catch (err) {
77
+ console.warn('Mental scan unavailable:', err);
78
  }
79
+ };
80
+
81
+ // Disconnect
82
+ const disconnect = () => {
83
+ if (device && device.gatt.connected) {
84
+ device.gatt.disconnect();
85
  }
86
+ setDevice(null);
87
+ setScans({ aural: { connected: false, data: null }, neural: { connected: false, data: null }, mental: { connected: false, data: null } });
88
  };
89
 
90
+ // Cleanup on unmount
91
+ useEffect(() => {
92
+ return () => {
93
+ if (device && device.gatt.connected) {
94
+ device.gatt.disconnect();
95
+ }
96
+ };
97
+ }, [device]);
98
+
99
  return (
100
  <div className="App">
101
  <header className="App-header">
102
+ <h1>nCONNECT OS Sensory Scanner</h1>
103
+ <p>Scan aural, neural, and mental senses via Bluetooth device.</p>
 
104
 
105
+ {!device ? (
106
+ <button onClick={connectDevice} disabled={isScanning || !navigator.bluetooth}>
107
+ {isScanning ? 'Scanning...' : 'Connect Bluetooth Device'}
108
+ </button>
109
  ) : (
110
  <div>
111
+ <p>Connected to: {device.name || 'Unknown Device'}</p>
112
+ <button onClick={disconnect}>Disconnect</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  </div>
114
  )}
115
+
116
+ {error && <p className="error">{error}</p>}
117
+
118
+ <div className="scans">
119
+ <div className="scan-card">
120
+ <h2>Aural Sense Scan</h2>
121
+ <p>Status: {scans.aural.connected ? 'Active' : 'Inactive'}</p>
122
+ <p>Data: {scans.aural.data !== null ? `${scans.aural.data} (Audio Intensity)` : 'No data'}</p>
123
+ </div>
124
+
125
+ <div className="scan-card">
126
+ <h2>Neural Sense Scan</h2>
127
+ <p>Status: {scans.neural.connected ? 'Active' : 'Inactive'}</p>
128
+ <p>Data: {scans.neural.data !== null ? `${scans.neural.data.toFixed(2)} Hz (Brainwave)` : 'No data'}</p>
129
+ </div>
130
+
131
+ <div className="scan-card">
132
+ <h2>Mental Sense Scan</h2>
133
+ <p>Status: {scans.mental.connected ? 'Active' : 'Inactive'}</p>
134
+ <p>Data: {scans.mental.data !== null ? `${scans.mental.data}% (Focus Level)` : 'No data'}</p>
135
+ </div>
136
+ </div>
137
+
138
+ <footer>{COPYRIGHT}</footer>
139
  </header>
140
  </div>
141
  );
142
+ }
143
 
144
+ export default App;