Skip to content
Snippets Groups Projects
Commit db450764 authored by Neil Gershenfeld's avatar Neil Gershenfeld
Browse files

wip

parent 60497220
No related branches found
No related tags found
No related merge requests found
<!DOCTYPE html>
<html lang="en">
<head>
<script>
//
// based on https://github.com/makerdiary/web-device-cli
//
const ServiceUUID = '6e400001-b5a3-f393-e0a9-e50e24dcca9e'
const RxUUID = '6e400002-b5a3-f393-e0a9-e50e24dcca9e'
const TxUUID = '6e400003-b5a3-f393-e0a9-e50e24dcca9e'
const MTU = 20
//
var bleDevice
var nusService
var rxCharacteristic
//
function connect() {
if (!navigator.bluetooth) {
console.log('Bluetooth not available, enable browser flag')
return
}
navigator.bluetooth.requestDevice({
optionalServices:[ServiceUUID],acceptAllDevices:true})
.then(device => {
bleDevice = device
console.log('connect to '+device.name)
bleDevice.addEventListener('gattserverdisconnected', ondisconnect)
return device.gatt.connect()
})
.then(server => {
return server.getPrimaryService(ServiceUUID)})
.then(service => {
nusService = service;
return nusService.getCharacteristic(RxUUID)})
.then(characteristic => {
rxCharacteristic = characteristic
return nusService.getCharacteristic(TxUUID)})
.then(characteristic => {
let txCharacteristic = characteristic
txCharacteristic.startNotifications()
txCharacteristic.addEventListener('characteristicvaluechanged',receive)
console.log(bleDevice.name+' connected')})
.catch(error => {
console.log(''+error);
if(bleDevice && bleDevice.gatt.connected) {
bleDevice.gatt.disconnect()
}
})
}
function disconnect() {
if (!bleDevice) {
console.log('nothing connected')
return
}
if (bleDevice.gatt.connected)
bleDevice.gatt.disconnect()
else
console.log('already disconnected')
}
function ondisconnect() {
console.log(bleDevice.name+' disconnected')
}
function receive(event) {
let value = event.target.value
let str = '';
for (let i = 0; i < value.byteLength; i++)
str += String.fromCharCode(value.getUint8(i))
console.log('receive: '+str)
}
function transmit(s) {
if(bleDevice && bleDevice.gatt.connected) {
console.log("send: "+s)
let arr = new Uint8Array(s.length)
for (let i = 0; i < s.length; i++) {
let val = s[i].charCodeAt(0)
arr[i] = val
}
send(arr)
}
else
console.log('not connected')
}
function send(a) {
let chunk = a.slice(0,MTU)
rxCharacteristic.writeValue(chunk)
.then(function() {
if (a.length > MTU) {
send(a.slice(MTU))
}
})
}
function LEDon() {
transmit('1')
}
function LEDoff() {
transmit('0')
}
</script>
</head>
<body>
<button onclick='connect()'>Connect</button>&nbsp;
<button onclick='disconnect()'>Disconnect</button>&nbsp;
<button onclick='LEDon()'>turn LED on</button>&nbsp;
<button onclick='LEDoff()'>turn LED off</button>&nbsp;
<div id='message'></div>
</body>
</html>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment