Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
119 lines (119 loc) · 7.18 KB
/
Copy pathindex.html
File metadata and controls
119 lines (119 loc) · 7.18 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
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Diagnóstico BLE MIDI — Casio</title>
<style>
body{font:17px/1.5 system-ui,sans-serif;background:#131927;color:#f4f7fc;max-width:700px;margin:0 auto;padding:22px}
button{background:#e5eefc;color:#0c1930;border:0;border-radius:9px;padding:12px 15px;font-size:17px;margin:3px;cursor:pointer}
button:disabled{opacity:.5}
#state{background:#293448;border-radius:9px;padding:15px;font-weight:700}
#note{font-size:48px;min-height:72px}
pre{background:#080d16;color:#cfdfed;padding:16px;min-height:180px;white-space:pre-wrap;overflow-wrap:anywhere;border-radius:9px;font-size:13px}
small{color:#c7d2e2}
</style>
</head>
<body>
<h1>Diagnóstico BLE MIDI</h1>
<p>Prueba directa desde Chrome a midimittr en el iPhone.</p>
<button id="go">Conectar Casio</button>
<button id="inspect">Inspeccionar servicios</button><button id="cccd">Inspeccionar descriptor 0x2902</button>
<button id="off">Desconectar</button><button id="reset">Olvidar Casio en Chrome</button>
<p id="state">Sin conectar</p>
<div id="note">—</div>
<small>Registro de conexión y mensajes MIDI:</small>
<pre id="log"></pre>
<script>
'use strict';
const MIDI_SERVICE='03b80e5a-ede8-4b33-a751-6ce34ec4c700';
const MIDI_CHARACTERISTIC='7772e5db-3868-4112-a1a9-f2669d106bf3';
let device=null, server=null, characteristic=null, subscriptionPending=false;
const out=document.querySelector('#log');
const status=document.querySelector('#state');
const notes=document.querySelector('#note');
function log(message){const time=new Date().toLocaleTimeString();out.textContent+='['+time+'] '+message+'\n';out.scrollTop=out.scrollHeight;}
function step(message){status.textContent=message;log(message);}
async function timeout(promise,label,ms=15000){
let id;
try{return await Promise.race([promise,new Promise((_,reject)=>{id=setTimeout(()=>reject(new Error(label+' no respondió en '+(ms/1000)+' segundos')),ms);})]);}
finally{clearTimeout(id);}
}
function incoming(event){
const view=event.target.value;
const bytes=new Uint8Array(view.buffer,view.byteOffset,view.byteLength);
log('MIDI HEX: '+[...bytes].map(b=>b.toString(16).padStart(2,'0')).join(' '));
// Interpretación básica de mensajes Note On dentro de un paquete BLE MIDI.
for(let i=2;i<bytes.length-2;i++){
const b=bytes[i];
if((b&0xf0)===0x90 && (bytes[i+1]&0x80)===0){
const note=bytes[i+1],velocity=bytes[i+2];
const names=['Do','Do♯','Re','Re♯','Mi','Fa','Fa♯','Sol','Sol♯','La','La♯','Si'];
notes.textContent=velocity?names[note%12]+(Math.floor(note/12)-1):'—';
}
}
}
document.querySelector('#go').onclick=async()=>{
try{
if(!navigator.bluetooth)throw new Error('Web Bluetooth no está disponible. Usa Chrome sobre HTTPS.');
step('Buscando servicio BLE MIDI...');
device=await navigator.bluetooth.requestDevice({filters:[{services:[MIDI_SERVICE]}]});
log('Encontrado: '+(device.name||'(sin nombre)')+' / id: '+device.id);
device.addEventListener('gattserverdisconnected',()=>step('Bluetooth desconectado'));
step('Conectando GATT...');
const connectionAttempt=device.gatt.connect();
connectionAttempt.then(()=>log('Conexión GATT completada (incluso si hubo espera previa).'),e=>log('Conexión GATT rechazó: '+e.message));
try{server=await timeout(connectionAttempt,'Conexión GATT',20000)}catch(e){if(device?.gatt?.connected)device.gatt.disconnect();throw e;}
step('GATT conectado');
step('Consultando servicio BLE MIDI...');
const service=await timeout(server.getPrimaryService(MIDI_SERVICE),'Consulta del servicio BLE MIDI',20000);
step('Servicio MIDI encontrado: '+service.uuid);
step('Buscando característica MIDI...');
characteristic=await timeout(service.getCharacteristic(MIDI_CHARACTERISTIC),'Consulta de característica MIDI',20000);
log('Propiedades: '+JSON.stringify({notify:characteristic.properties.notify,indicate:characteristic.properties.indicate,read:characteristic.properties.read,write:characteristic.properties.write,writeWithoutResponse:characteristic.properties.writeWithoutResponse}));
characteristic.addEventListener('characteristicvaluechanged',incoming);
log('Característica encontrada: '+characteristic.uuid);
step('Activando notificaciones MIDI...');
subscriptionPending=true;
try { await timeout(characteristic.startNotifications(),'Activación de notificaciones MIDI',20000); subscriptionPending=false;step('Notificaciones ACTIVADAS: toca el Casio.'); }
catch(error){subscriptionPending=false;step('Suscripción pendiente/fallida: '+error.message);log('Toca teclas igualmente para comprobar si llegan eventos.');}
}catch(error){step('ERROR: '+(error.name||'Error')+' — '+error.message);log('Conectado actualmente: '+Boolean(device&&device.gatt&&device.gatt.connected));}
};
document.querySelector('#inspect').onclick=async()=>{
try{
if(!device?.gatt?.connected)throw new Error('Conéctate primero a Casio.');
step('Enumerando servicios GATT autorizados...');
const services=await timeout(device.gatt.getPrimaryServices(),'Enumeración de servicios GATT',20000);
log('Servicios accesibles: '+(services.map(s=>s.uuid).join(', ')||'(ninguno)'));
step('Enumeración terminada ('+services.length+' servicios accesibles).');
}catch(error){step('ERROR al inspeccionar: '+error.message);}
};
document.querySelector('#cccd').onclick=async()=>{try{if(!characteristic)throw Error('Primero pulsa Conectar Casio.'); log('Comprobando descriptor CCCD 0x2902...');const descriptors=await timeout(characteristic.getDescriptors(),'Enumeración de descriptores',12000);log('Descriptores visibles: '+descriptors.map(d=>d.uuid).join(', '));const d=descriptors.find(d=>d.uuid==='00002902-0000-1000-8000-00805f9b34fb');if(d){try{const value=await timeout(d.readValue(),'Lectura CCCD',12000);log('CCCD: '+[...new Uint8Array(value.buffer)].map(v=>v.toString(16).padStart(2,'0')).join(' '));}catch(e){log('No se pudo leer CCCD: '+e.message);}}step('Revisión de descriptor terminada.')}catch(e){step('ERROR descriptor: '+e.message)}};
document.querySelector('#reset').onclick=async()=>{try{
if(!navigator.bluetooth)throw Error('Web Bluetooth no disponible.');
if(device?.gatt?.connected)device.gatt.disconnect();
let target=device;
if(!target && typeof navigator.bluetooth.getDevices==='function'){
const items=await navigator.bluetooth.getDevices();
target=items.find(d=>d.name==='Casio')||null;
}
if(!target){
step('Chrome no permite listar dispositivos autorizados. Pulsa Conectar Casio y después Olvidar Casio, o borra los permisos Bluetooth del sitio en Ajustes de Chrome.');
return;
}
if(typeof target.forget!=='function'){
step('Este Chrome no admite device.forget(). Borra el permiso Bluetooth para fer-gil.github.io desde Ajustes del sitio en Chrome.');
return;
}
await target.forget();
device=null;server=null;characteristic=null;
step('Permiso de Casio olvidado. Vuelve a pulsar Conectar Casio.');
}catch(e){step('No se pudo olvidar Casio: '+e.message)}
};
document.querySelector('#off').onclick=()=>{
if(device?.gatt?.connected)device.gatt.disconnect();
else step('No hay una conexión activa.');
};
log('Página de diagnóstico v5 cargada. Web Bluetooth: '+Boolean(navigator.bluetooth));
</script>
</body></html>