Connect to a BLE device with BLE GATT Service of Environmental Sensing and BLE GATT Characteristic of UV Index and read the values from the Chrome browser console when the readings are updated.
Ensure the browser side of the code is also implemented with web-ble-gatt.html.
<buttonid="read">Connect with BLE device</button><buttonid="start"disabled>Start</button><buttonid="stop"disabled>Stop</button><script>vardeviceName='Palm'varbleService='environmental_sensing'varbleCharacteristic='uv_index'varbluetoothDeviceDetectedvargattCharacteristicdocument.querySelector('#read').addEventListener('click',function(){if(isWebBluetoothEnabled()){read()}})document.querySelector('#start').addEventListener('click',function(event){if(isWebBluetoothEnabled()){start()}})document.querySelector('#stop').addEventListener('click',function(event){if(isWebBluetoothEnabled()){stop()}})functionisWebBluetoothEnabled(){if(!navigator.bluetooth){console.log('Web Bluetooth API is not available in this browser!')returnfalse}returntrue}functiongetDeviceInfo(){letoptions={optionalServices:[bleService],filters:[{"name":deviceName}]}console.log('Requesting any Bluetooth Device...')returnnavigator.bluetooth.requestDevice(options).then(device=>{bluetoothDeviceDetected=device}).catch(error=>{console.log('Argh! '+error)})}functionread(){return(bluetoothDeviceDetected?Promise.resolve():getDeviceInfo()).then(connectGATT).then(_=>{console.log('Reading UV Index...')returngattCharacteristic.readValue()}).catch(error=>{console.log('Waiting to start reading: '+error)})}functionconnectGATT(){if(bluetoothDeviceDetected.gatt.connected&&gattCharacteristic){returnPromise.resolve()}returnbluetoothDeviceDetected.gatt.connect().then(server=>{console.log('Getting GATT Service...')returnserver.getPrimaryService(bleService)}).then(service=>{console.log('Getting GATT Characteristic...')returnservice.getCharacteristic(bleCharacteristic)}).then(characteristic=>{gattCharacteristic=characteristicgattCharacteristic.addEventListener('characteristicvaluechanged',handleChangedValue)document.querySelector('#start').disabled=falsedocument.querySelector('#stop').disabled=true})}functionhandleChangedValue(event){letvalue=event.target.value.getUint8(0)varnow=newDate()console.log('> '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds()+' UV Index is '+value)}functionstart(){gattCharacteristic.startNotifications().then(_=>{console.log('Start reading...')document.querySelector('#start').disabled=truedocument.querySelector('#stop').disabled=false}).catch(error=>{console.log('[ERROR] Start: '+error)})}functionstop(){gattCharacteristic.stopNotifications().then(_=>{console.log('Stop reading...')document.querySelector('#start').disabled=falsedocument.querySelector('#stop').disabled=true}).catch(error=>{console.log('[ERROR] Stop: '+error)})}</script>