-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
222 lines (201 loc) · 9.07 KB
/
index.html
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<!--
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-web-bluetooth/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-->
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Web BLE App</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="favicon.ico">
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="UTF-8">
</head>
<body>
<div class="topnav">
<h1>ESP32 Web BLE Application</h1>
</div>
<div class="content">
<div class="card-grid">
<div class="card">
<p>
<button id="connectBleButton" class="connectButton"> Connect to BLE Device</button>
<button id="disconnectBleButton" class="disconnectButton"> Disconnect BLE Device</button>
</p>
<p class="gray-label">BLE state: <strong><span id="bleState" style="color:#d13a30;">Disconnected</span></strong></p>
</div>
</div>
<div class="card-grid">
<div class="card">
<h2>Fetched Value</h2>
<p class="reading"><span id="valueContainer">NaN</span></p>
<p class="gray-label">Last reading: <span id="timestamp"></span></p>
</div>
<div class="card">
<h2>Control GPIO 2</h2>
<button id="onButton" class="onButton">ON</button>
<button id="offButton" class="offButton">OFF</button>
<p class="gray-label">Last value sent: <span id="valueSent"></span></p>
</div>
</div>
</div>
<div class="footer">
<p><a href="https://randomnerdtutorials.com/">Created by RandomNerdTutorials.com</a></p>
<p><a href="https://RandomNerdTutorials.com/esp32-web-bluetooth/">Read the full project here.</a></p>
</div>
</body>
<script>
// DOM Elements
const connectButton = document.getElementById('connectBleButton');
const disconnectButton = document.getElementById('disconnectBleButton');
const onButton = document.getElementById('onButton');
const offButton = document.getElementById('offButton');
const retrievedValue = document.getElementById('valueContainer');
const latestValueSent = document.getElementById('valueSent');
const bleStateContainer = document.getElementById('bleState');
const timestampContainer = document.getElementById('timestamp');
//Define BLE Device Specs
var deviceName ='ESP32';
var bleService = '19b10000-e8f2-537e-4f6c-d104768a1214';
var ledCharacteristic = '19b10002-e8f2-537e-4f6c-d104768a1214';
var sensorCharacteristic= '19b10001-e8f2-537e-4f6c-d104768a1214';
//Global Variables to Handle Bluetooth
var bleServer;
var bleServiceFound;
var sensorCharacteristicFound;
// Connect Button (search for BLE Devices only if BLE is available)
connectButton.addEventListener('click', (event) => {
if (isWebBluetoothEnabled()){
connectToDevice();
}
});
// Disconnect Button
disconnectButton.addEventListener('click', disconnectDevice);
// Write to the ESP32 LED Characteristic
onButton.addEventListener('click', () => writeOnCharacteristic(1));
offButton.addEventListener('click', () => writeOnCharacteristic(0));
// Check if BLE is available in your Browser
function isWebBluetoothEnabled() {
if (!navigator.bluetooth) {
console.log('Web Bluetooth API is not available in this browser!');
bleStateContainer.innerHTML = "Web Bluetooth API is not available in this browser/device!";
return false
}
console.log('Web Bluetooth API supported in this browser.');
return true
}
// Connect to BLE Device and Enable Notifications
function connectToDevice(){
console.log('Initializing Bluetooth...');
navigator.bluetooth.requestDevice({
filters: [{name: deviceName}],
optionalServices: [bleService]
})
.then(device => {
console.log('Device Selected:', device.name);
bleStateContainer.innerHTML = 'Connected to device ' + device.name;
bleStateContainer.style.color = "#24af37";
device.addEventListener('gattservicedisconnected', onDisconnected);
return device.gatt.connect();
})
.then(gattServer =>{
bleServer = gattServer;
console.log("Connected to GATT Server");
return bleServer.getPrimaryService(bleService);
})
.then(service => {
bleServiceFound = service;
console.log("Service discovered:", service.uuid);
return service.getCharacteristic(sensorCharacteristic);
})
.then(characteristic => {
console.log("Characteristic discovered:", characteristic.uuid);
sensorCharacteristicFound = characteristic;
characteristic.addEventListener('characteristicvaluechanged', handleCharacteristicChange);
characteristic.startNotifications();
console.log("Notifications Started.");
return characteristic.readValue();
})
.then(value => {
console.log("Read value: ", value);
const decodedValue = new TextDecoder().decode(value);
console.log("Decoded value: ", decodedValue);
retrievedValue.innerHTML = decodedValue;
})
.catch(error => {
console.log('Error: ', error);
})
}
function onDisconnected(event){
console.log('Device Disconnected:', event.target.device.name);
bleStateContainer.innerHTML = "Device disconnected";
bleStateContainer.style.color = "#d13a30";
connectToDevice();
}
function handleCharacteristicChange(event){
const newValueReceived = new TextDecoder().decode(event.target.value);
console.log("Characteristic value changed: ", newValueReceived);
retrievedValue.innerHTML = newValueReceived;
timestampContainer.innerHTML = getDateTime();
}
function writeOnCharacteristic(value){
if (bleServer && bleServer.connected) {
bleServiceFound.getCharacteristic(ledCharacteristic)
.then(characteristic => {
console.log("Found the LED characteristic: ", characteristic.uuid);
const data = new Uint8Array([value]);
return characteristic.writeValue(data);
})
.then(() => {
latestValueSent.innerHTML = value;
console.log("Value written to LEDcharacteristic:", value);
})
.catch(error => {
console.error("Error writing to the LED characteristic: ", error);
});
} else {
console.error ("Bluetooth is not connected. Cannot write to characteristic.")
window.alert("Bluetooth is not connected. Cannot write to characteristic. \n Connect to BLE first!")
}
}
function disconnectDevice() {
console.log("Disconnect Device.");
if (bleServer && bleServer.connected) {
if (sensorCharacteristicFound) {
sensorCharacteristicFound.stopNotifications()
.then(() => {
console.log("Notifications Stopped");
return bleServer.disconnect();
})
.then(() => {
console.log("Device Disconnected");
bleStateContainer.innerHTML = "Device Disconnected";
bleStateContainer.style.color = "#d13a30";
})
.catch(error => {
console.log("An error occurred:", error);
});
} else {
console.log("No characteristic found to disconnect.");
}
} else {
// Throw an error if Bluetooth is not connected
console.error("Bluetooth is not connected.");
window.alert("Bluetooth is not connected.")
}
}
function getDateTime() {
var currentdate = new Date();
var day = ("00" + currentdate.getDate()).slice(-2); // Convert day to string and slice
var month = ("00" + (currentdate.getMonth() + 1)).slice(-2);
var year = currentdate.getFullYear();
var hours = ("00" + currentdate.getHours()).slice(-2);
var minutes = ("00" + currentdate.getMinutes()).slice(-2);
var seconds = ("00" + currentdate.getSeconds()).slice(-2);
var datetime = day + "/" + month + "/" + year + " at " + hours + ":" + minutes + ":" + seconds;
return datetime;
}
</script>
</html>