-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
218 lines (168 loc) · 8.53 KB
/
script.js
File metadata and controls
218 lines (168 loc) · 8.53 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
const stepCountElement = document.getElementById('stepsCount');
// CONFIGURACIÓN
const SENSOR_FREQUENCY = 30;
const WINDOW_SIZE = SENSOR_FREQUENCY * 2; // 2 segundos de ventana
// UMBRALES DE DETECCIÓN
const MIN_STEP_INTERVAL = 250; // mínimo 250ms entre pasos
const MAX_STEP_INTERVAL = 2000; // máximo 2s entre pasos
const MIN_PEAK_MAGNITUDE = 4.0; // magnitud mínima de pico para contar paso
const DESK_MOVEMENT_THRESHOLD = 0.4; // regularidad máxima para movimiento de escritorio
const MIN_STEPS_TO_CONFIRM = 2; // pasos mínimos para empezar a contar
// VARIABLES DE ESTADO
let stepCount = 0;
let tempStepCount = 0; // pasos temporales antes de confirmar
let isStepInProgress = false;
let lastStepTime = 0;
let isWalkingConfirmed = false;
// HISTORIAL
let magnitudeHistory = [];
let peakHistory = []; // historial de picos detectados
if ("LinearAccelerationSensor" in window) {
try {
const sensor = new LinearAccelerationSensor({ frequency: SENSOR_FREQUENCY });
sensor.addEventListener("reading", () => {
const now = Date.now();
// CALCULAR MAGNITUD TOTAL
const magnitude = Math.sqrt(
sensor.x ** 2 +
sensor.y ** 2 +
sensor.z ** 2
);
// GUARDAR HISTORIAL
magnitudeHistory.push(magnitude);
if (magnitudeHistory.length > WINDOW_SIZE) magnitudeHistory.shift();
// ESPERAR SUFICIENTES DATOS
if (magnitudeHistory.length < SENSOR_FREQUENCY / 2) return;
// ANÁLISIS ESTADÍSTICO
const avg = magnitudeHistory.reduce((a, b) => a + b, 0) / magnitudeHistory.length;
const variance = magnitudeHistory.reduce((a, b) => a + (b - avg) ** 2, 0) / magnitudeHistory.length;
const stdDev = Math.sqrt(variance);
// Regularidad del movimiento
const regularity = stdDev / (avg + 0.1);
// UMBRALES DINÁMICOS
const STEP_THRESHOLD = avg + stdDev * 1.8;
const RESET_THRESHOLD = avg + stdDev * 0.7;
// DETECCIÓN DE PICO
const isPeak = magnitude > STEP_THRESHOLD && magnitude > MIN_PEAK_MAGNITUDE;
if (isPeak && !isStepInProgress) {
const timeSinceLastStep = now - lastStepTime;
// FILTRO 1: MOVIMIENTO DE ESCRITORIO
// Movimientos de escritorio son muy regulares y de baja variabilidad
// La caminata tiene más variabilidad natural
if (regularity < DESK_MOVEMENT_THRESHOLD) {
console.log(`🖥️ Movimiento de escritorio detectado (reg: ${regularity.toFixed(2)})`);
isStepInProgress = true;
return;
}
// FILTRO 2: INTERVALO DE TIEMPO
if (lastStepTime > 0) {
if (timeSinceLastStep < MIN_STEP_INTERVAL) {
console.log(`⚡ Demasiado rápido: ${timeSinceLastStep}ms`);
isStepInProgress = true;
return;
}
if (timeSinceLastStep > MAX_STEP_INTERVAL) {
console.log(`⏸️ Pausa detectada: ${timeSinceLastStep}ms - Reseteando`);
// Resetear la confirmación de caminata
peakHistory = [];
tempStepCount = 0;
isWalkingConfirmed = false;
}
}
// FILTRO 3: MAGNITUD MÍNIMA
if (magnitude < MIN_PEAK_MAGNITUDE) {
console.log(`📉 Magnitud insuficiente: ${magnitude.toFixed(2)}`);
isStepInProgress = true;
return;
}
// FILTRO 4: DEBE TENER VARIABILIDAD SUFICIENTE
// La caminata genera variabilidad, levantar el teléfono es suave
if (stdDev < 1.5) {
console.log(`📱 Movimiento muy suave (stdDev: ${stdDev.toFixed(2)})`);
isStepInProgress = true;
return;
}
// GUARDAR PICO Y ANALIZAR PATRÓN
peakHistory.push({
time: now,
magnitude: magnitude,
interval: timeSinceLastStep
});
// Mantener solo los últimos 10 picos
if (peakHistory.length > 10) peakHistory.shift();
// VALIDACIÓN INTELIGENTE
let isValidStep = true;
// Si tenemos suficiente historial, verificamos el patrón
if (peakHistory.length >= 4) {
const recentIntervals = peakHistory.slice(-4).map(p => p.interval).filter(i => i > 0);
if (recentIntervals.length >= 3) {
// Calcular mediana en lugar de promedio (más robusto a outliers)
const sortedIntervals = [...recentIntervals].sort((a, b) => a - b);
const median = sortedIntervals[Math.floor(sortedIntervals.length / 2)];
// Verificar que el intervalo actual no sea extremadamente diferente
const deviation = Math.abs(timeSinceLastStep - median) / median;
// Permitimos hasta 150% de desviación
if (deviation > 1.5) {
console.log(`📊 Desviación alta: ${(deviation * 100).toFixed(0)}% de la mediana`);
isValidStep = false;
}
}
}
// FILTRO ANTI-SACUDIDAS
// Si hay muchos picos en muy poco tiempo, es una sacudida
const recentPeaks = peakHistory.filter(p => now - p.time < 1000);
if (recentPeaks.length > 5) {
console.log(`🤯 Demasiados picos en 1 segundo: ${recentPeaks.length}`);
isValidStep = false;
}
// CONTAR PASO
if (isValidStep) {
lastStepTime = now;
isStepInProgress = true;
// Sistema de confirmación: necesitamos pasos consecutivos
if (!isWalkingConfirmed) {
tempStepCount++;
console.log(`🔄 Paso temporal ${tempStepCount}/${MIN_STEPS_TO_CONFIRM}`);
if (tempStepCount >= MIN_STEPS_TO_CONFIRM) {
isWalkingConfirmed = true;
stepCount += tempStepCount;
console.log(`✅ Caminata confirmada! ${tempStepCount} pasos contados`);
tempStepCount = 0;
}
} else {
stepCount++;
console.log(`👣 Paso ${stepCount} | ${timeSinceLastStep}ms | mag: ${magnitude.toFixed(2)} | std: ${stdDev.toFixed(2)}`);
}
// ACTUALIZAR UI
stepCountElement.innerText = stepCount;
// ENVIAR EVENTO A OBJETIVES.JS
document.dispatchEvent(
new CustomEvent("stepUpdated", { detail: { stepCount } })
);
} else {
// Paso inválido - resetear confirmación
tempStepCount = 0;
isWalkingConfirmed = false;
peakHistory = [];
isStepInProgress = true;
}
}
// RESETEAR DETECTOR DE PICO
if (magnitude < RESET_THRESHOLD) {
isStepInProgress = false;
}
});
sensor.addEventListener("error", (event) => {
if (event.error.name === "NotAllowedError") {
sensorStatusElement.innerText = "Sensor permission denied.";
} else {
sensorStatusElement.innerText = `Sensor error: ${event.error.name}`;
}
});
sensor.start();
} catch (error) {
sensorStatusElement.innerText = `The sensor could not be started: ${error}`;
}
} else {
sensorStatusElement.innerText = "This device does NOT support LinearAccelerationSensor.";
}