-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
251 lines (223 loc) · 10.4 KB
/
Copy pathApp.tsx
File metadata and controls
251 lines (223 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { ConnectionStatus, Prediction, BluetoothDevice, BluetoothRemoteGATTCharacteristic, HydrationEntry } from './types';
import { CLASSIFICATION_LABELS, MAX_PREDICTIONS } from './constants';
import { connectToDevice, disconnectFromDevice } from './services/bleService';
import StatusIndicator from './components/StatusIndicator';
import CurrentPrediction from './components/CurrentPrediction';
import HistoryChart from './components/HistoryChart';
import { BluetoothIcon } from './components/icons/BluetoothIcon';
// --- CONSTANTS ---
const DRINKING_CONFIDENCE_THRESHOLD = 0.8;
// --- ICONS & UI COMPONENTS ---
const WaterDropIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
<path d="M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C5 11.1 4 13 4 15a7 7 0 0 0 7 7z" />
</svg>
);
const Reminder: React.FC<{ show: boolean }> = ({ show }) => {
if (!show) return null;
return (
<div className="bg-sky-800/50 border border-sky-600 text-sky-300 p-4 rounded-2xl flex items-center gap-4 animate-pulse">
<WaterDropIcon className="w-8 h-8 flex-shrink-0 text-sky-400" />
<div>
<h3 className="font-bold">Time for a drink!</h3>
<p className="text-sm">Stay hydrated to keep your energy up.</p>
</div>
</div>
);
};
const HydrationLog: React.FC<{ log: HydrationEntry[] }> = ({ log }) => (
<div className="flex flex-col h-full">
<h3 className="text-lg font-semibold text-white mb-3">Hydration Log</h3>
<div className="bg-slate-900/50 rounded-lg p-4 flex-grow overflow-y-auto border border-slate-700/50">
{log.length === 0 ? (
<p className="text-slate-500 text-center py-4">Your drinking events will appear here.</p>
) : (
<ul className="space-y-3">
{log.map((entry, index) => (
<li key={index} className="flex items-center gap-4 text-slate-300 animate-fade-in">
<WaterDropIcon className="w-5 h-5 text-sky-500"/>
<span>Drinking event detected</span>
<span className="ml-auto text-slate-400 text-sm">{entry.time.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
</li>
))}
</ul>
)}
</div>
</div>
);
// --- MAIN APP COMPONENT ---
export default function App(): React.ReactNode {
const [status, setStatus] = useState<ConnectionStatus>('disconnected');
const [error, setError] = useState<string | null>(null);
const [predictions, setPredictions] = useState<Prediction[]>([]);
const [bleDevice, setBleDevice] = useState<BluetoothDevice | null>(null);
const [bleCharacteristic, setBleCharacteristic] = useState<BluetoothRemoteGATTCharacteristic | null>(null);
// Hydration state
const [isDrinking, setIsDrinking] = useState<boolean>(false);
const [hydrationLog, setHydrationLog] = useState<HydrationEntry[]>([]);
const [lastDrinkTime, setLastDrinkTime] = useState<Date | null>(null);
const [showReminder, setShowReminder] = useState<boolean>(false);
const [reminderInterval, setReminderInterval] = useState<number>(30);
const handleDataReceived = useCallback((event: Event) => {
const target = event.target as BluetoothRemoteGATTCharacteristic;
const value = target.value;
if (!value) return;
const newScores: Record<string, number> = {};
let topLabel = '';
let topScore = -1;
CLASSIFICATION_LABELS.forEach((label, index) => {
const score = value.getFloat32(index * 4, true);
newScores[label] = score;
if (score > topScore) {
topScore = score;
topLabel = label;
}
});
setPredictions(prev => [...prev, { timestamp: Date.now(), scores: newScores }].slice(-MAX_PREDICTIONS));
// Hydration logic
if (topLabel === 'drinking' && topScore > DRINKING_CONFIDENCE_THRESHOLD) {
if (!isDrinking) setIsDrinking(true);
} else {
if (isDrinking) {
setIsDrinking(false);
const now = new Date();
const newEntry = { time: now };
setHydrationLog(prev => [newEntry, ...prev]);
setLastDrinkTime(now);
setShowReminder(false);
}
}
}, [isDrinking]);
const resetHydrationState = () => {
setHydrationLog([]);
setLastDrinkTime(null);
setShowReminder(false);
setIsDrinking(false);
setPredictions([]);
};
const handleDeviceDisconnected = useCallback(() => {
setStatus('disconnected');
setBleDevice(null);
setBleCharacteristic(null);
setShowReminder(false);
if (!error) {
setError("Device disconnected.");
}
}, [error]);
const handleConnect = async () => {
setError(null);
setStatus('connecting');
try {
const { device, characteristic } = await connectToDevice();
setBleDevice(device);
setBleCharacteristic(characteristic);
setStatus('connected');
resetHydrationState();
device.addEventListener('gattserverdisconnected', handleDeviceDisconnected);
} catch (e: unknown) {
if (e instanceof DOMException && e.name === 'NotFoundError') {
setStatus('disconnected');
setError(null);
return;
}
const errorMessage = e instanceof Error ? e.message : String(e);
setError(`Connection failed: ${errorMessage}`);
setStatus('error');
}
};
const handleDisconnect = async () => {
if (bleDevice) {
bleDevice.removeEventListener('gattserverdisconnected', handleDeviceDisconnected);
disconnectFromDevice(bleDevice);
handleDeviceDisconnected();
setError(null);
}
};
useEffect(() => {
if (bleCharacteristic) {
bleCharacteristic.startNotifications();
bleCharacteristic.addEventListener('characteristicvaluechanged', handleDataReceived);
return () => {
bleCharacteristic.removeEventListener('characteristicvaluechanged', handleDataReceived);
};
}
}, [bleCharacteristic, handleDataReceived]);
useEffect(() => {
const intervalId = setInterval(() => {
if (status !== 'connected' || !reminderInterval || reminderInterval <= 0) {
setShowReminder(false);
return;
}
// Use connection time if no drink has been logged yet
const checkTime = lastDrinkTime || (bleDevice ? new Date() : null);
if (!checkTime) return;
const minutesSinceLastDrink = (Date.now() - checkTime.getTime()) / (1000 * 60);
if (minutesSinceLastDrink > reminderInterval) {
setShowReminder(true);
}
}, 60 * 1000); // Check every minute
return () => clearInterval(intervalId);
}, [lastDrinkTime, status, bleDevice, reminderInterval]);
const latestPrediction = useMemo(() => predictions.length > 0 ? predictions[predictions.length - 1] : null, [predictions]);
return (
<div className="min-h-screen bg-slate-900 text-slate-200 font-sans flex flex-col p-4 sm:p-6 lg:p-8">
<header className="w-full max-w-7xl mx-auto mb-6">
<h1 className="text-3xl sm:text-4xl font-bold text-sky-400">Hydration Monitoring</h1>
<p className="text-slate-400 mt-1">Real-time activity classification and hydration event logging.</p>
</header>
<main className="w-full max-w-7xl mx-auto flex-grow flex flex-col lg:flex-row gap-6">
<aside className="lg:w-1/3 xl:w-1/4 flex flex-col gap-6">
<div className="bg-slate-800/50 p-6 rounded-2xl border border-slate-700">
<h2 className="text-xl font-semibold text-white mb-4">Controls</h2>
<div className="flex items-center gap-4 mb-5"><StatusIndicator status={status} /></div>
{status !== 'connected' ? (
<button onClick={handleConnect} disabled={status === 'connecting'} className="w-full flex items-center justify-center gap-2 bg-sky-500 hover:bg-sky-600 disabled:bg-slate-600 text-white font-bold py-3 px-4 rounded-lg transition-all duration-200 transform hover:scale-105 disabled:scale-100">
<BluetoothIcon className="w-5 h-5" />
<span>{status === 'connecting' ? 'Connecting...' : 'Connect to Bottle'}</span>
</button>
) : (
<button onClick={handleDisconnect} className="w-full flex items-center justify-center gap-2 bg-red-500 hover:bg-red-600 text-white font-bold py-3 px-4 rounded-lg transition-all duration-200 transform hover:scale-105">
<BluetoothIcon className="w-5 h-5" />
<span>Disconnect</span>
</button>
)}
{error && <p className="text-red-400 text-sm mt-4 break-words">{error}</p>}
<div className="mt-6 border-t border-slate-700 pt-5">
<label htmlFor="reminder-interval" className="block text-sm font-medium text-slate-300 mb-2">
Reminder Interval (minutes)
</label>
<input
id="reminder-interval"
type="number"
value={reminderInterval}
onChange={(e) => {
const value = parseInt(e.target.value, 10);
setReminderInterval(value > 0 ? value : 1);
}}
disabled={status !== 'connected'}
min="1"
className="w-full bg-slate-700 border border-slate-600 rounded-lg py-2 px-3 text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-sky-500 disabled:opacity-50 disabled:cursor-not-allowed"
/>
</div>
</div>
<Reminder show={showReminder && status === 'connected'} />
<CurrentPrediction prediction={latestPrediction} />
</aside>
<section className="flex-grow lg:w-2/3 xl:w-3/4">
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6 h-full">
<div className="xl:col-span-2 bg-slate-800/50 p-4 sm:p-6 rounded-2xl border border-slate-700 flex flex-col">
<h2 className="text-xl font-semibold text-white mb-4">Live Activity Feed</h2>
<div className="flex-grow">
<HistoryChart data={predictions} />
</div>
</div>
<div className="xl:col-span-1 bg-slate-800/50 p-4 sm:p-6 rounded-2xl border border-slate-700 flex flex-col">
<HydrationLog log={hydrationLog} />
</div>
</div>
</section>
</main>
</div>
);
}