<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>BLE UART read/write</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>BLE UART read/write</h1>
<p>Micro:bitに接続完了後、ボタンA・B、タッチセンサーを操作してください。<br> 
ボタン・タッチセンサーの情報を取得します。<br>
また、メッセージ送信でLEDに表示します。</p>
<hr>
<p><button type="button" id="connect">接続</button> <span id="msg"></span></p>
受信内容<br>
<textarea id="recieve_text" rows="10" cols="30"></textarea>
<p><button type="button" id="clear">クリア</button></p>
<p>送信内容 <input type="text" id="send_text" value="test"> 
<button type="button" id="send" disabled>送信</button></p>
<script>
const uuid1 = '6e400001-b5a3-f393-e0a9-e50e24dcca9e' //UUID_UART_SERVICE
const uuid2 = '6e400002-b5a3-f393-e0a9-e50e24dcca9e' //UUID_TX_CHAR_CHARACTERISTIC
const uuid3 = '6e400003-b5a3-f393-e0a9-e50e24dcca9e' //UUID_RX_CHAR_CHARACTERISTIC

let gatt = null
let tx = null
let rx = null
function update(connected) {
  connect.textContent = connected ? '切断' : '接続'
  msg.innerHTML = connected ? 'BLE connected' : 'BLE disconnected'
  send.disabled = !connected ;
}
function sendm(text) { rx.writeValue(new TextEncoder().encode(text + '\n')) }

document.getElementById('connect').addEventListener('click', function(e){
  if(!(navigator.bluetooth && navigator.bluetooth.requestDevice)) {
    alert('WebBluetooth に未対応のブラウザです。')
    return
  }
  if (document.getElementById('connect').textContent == '接続') {
    navigator.bluetooth.requestDevice({
      filters: [ { services: [uuid1] },{ namePrefix: 'BBC micro:bit' } ] })
      .then(device => { gatt = device.gatt ; return gatt.connect() })
      .then(server => server.getPrimaryService(uuid1))
      .then(service => Promise.all([ service.getCharacteristic(uuid2),service.getCharacteristic(uuid3)]))
      .then(characteristics => {
            tx = characteristics[0]
            rx = characteristics[1]
            tx.startNotifications()
            tx.addEventListener('characteristicvaluechanged', function(e){
                const text = new TextDecoder().decode(e.target.value)
                document.getElementById('recieve_text').value = text + "\n" + document.getElementById('recieve_text').value
            })
            update(true) ;
      })
      .catch(function(err) { alert(err) })
  } else { gatt.disconnect() ; update(false) ; }
})

document.getElementById('send').addEventListener('click', e => { sendm(send_text.value) })
clear.addEventListener('click', function(e) { recieve_text.value = "" ; })
</script>
</body>
</html>