-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
65 lines (51 loc) · 1.8 KB
/
app.js
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
const connectButton = document.getElementById('scan')
const primaryServiceUuid = '6e400001-b5a3-f393-e0a9-e50e24dcca9e'
const receiveCharUuid = '6e400001-b5a3-f393-e0a9-e50e24dcca9e'
const sendCharUuid = '6e400002-b5a3-f393-e0a9-e50e24dcca9e'
let device = null
function hexToRgb(hex) {
const r = parseInt(hex.substring(1, 3), 16)
const g = parseInt(hex.substring(3, 5), 16)
const b = parseInt(hex.substring(5, 7), 16)
return [r, g, b]
};
let options = {
filters: [
{ name: 'UART Service' }, // name should match the esp32 device BLE name
],
optionalServices: ['6e400001-b5a3-f393-e0a9-e50e24dcca9e']
}
connectButton.onclick = async () => {
device = await navigator.bluetooth.requestDevice(options)
const element = document.getElementById('output')
element.innerHTML = '---> connected to: ' + device.name
}
async function sendDataToBle(data) {
const server = await device.gatt.connect();
const service = await server.getPrimaryService(primaryServiceUuid);
const buffer = Uint8Array.from(data)
const sendCharacteristic = await service.getCharacteristic(sendCharUuid);
sendCharacteristic.writeValue(buffer);
}
async function sendString() {
const inputElement = document.getElementById('input')
const inputData = inputElement.value
const element = document.getElementById('output')
if (!device) {
element.innerText = 'Connect to the BLE device before sending any data'
return
}
element.innerText += `${new Date().toLocaleString(undefined, {
hour: '2-digit',
hour12: false,
minute: '2-digit',
second: '2-digit'
})}---> ${inputData} \n`
sendDataToBle(inputData)
inputElement.value = ''
}
async function sendColorData() {
const colorPicker = document.getElementById('colorPicker')
const colorData = hexToRgb(colorPicker.value)
sendDataToBle(colorData)
}