Basic BLE Device using ESP32 NodeMCU.
Code can be found here: https://github.com/sukapx/Esp32_BLE
Documentation of Web Bluetooth that will be used
Good to know: Blazor Remote Debugging – Android
Calling Javascript from Razor and Razor from Javascript: Microsoft Docs
Preparation
Create a new selfhosted Blazor Web Assembly project
dotnet new blazorwasm --hosted -o Solution
Add new files
@page "/blue"
@inject IJSRuntime JS
<h3>Bluetooth</h3>
<button @onclick="GetDevices">GetDevices</button>
@code{
public async Task GetDevices()
{
await JS.InvokeVoidAsync("ConnectBluetooth");
}
}
async function ConnectBluetooth() {
console.log("Hello from Javascript");
}
For convenience add a link to the new page.
+++ b/Solution/Client/Shared/NavMenu.razor
@@ -24,6 +24,11 @@
<span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
</NavLink>
</div>
+ <div class="nav-item px-3">
+ <NavLink class="nav-link" href="blue">
+ <span class="oi oi-list-rich" aria-hidden="true"></span> Bluetooth
+ </NavLink>
+ </div>
</nav>
</div>
And make Page load our new Javascript
+++ b/Solution/Client/wwwroot/index.html
@@ -20,6 +20,7 @@
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
+ <script src="bluetooth.js"></script>
</body>
</html>
If now reloading the page on our phone, selecting the Bluetooth page and pushing the button, Javascript greets us.
Search and connect BLE Device
To search and connect BLE devices we write actual code into to javascript.
async function ConnectBluetooth() {
if(!navigator.bluetooth) {
console.error("No access to bluetooth");
return;
}
let device = await navigator.bluetooth.requestDevice({
filters: [{
services: ['00000001-5239-4069-806d-7e5c97393755'],
}]
});
console.log({device});
let server = await device.gatt.connect();
console.log({server});
let service = await server.getPrimaryService('00000001-5239-4069-806d-7e5c97393755');
console.log({service});
let charac_deviceTime = await service.getCharacteristic('00000002-5239-4069-806d-7e5c97393755');
console.log({charac_deviceTime});
charac_deviceTime.addEventListener('characteristicvaluechanged', (event) => {
console.log(event.target);
let value = event.target.value.getFloat32(0, true);
console.log('> Characteristic is ' + value);
});
await charac_deviceTime.startNotifications();
}
Where the UUID’s are taken from https://github.com/sukapx/Esp32_BLE and we already add a filter to the devices service.
If button is pressed now, we get an Android system message, to select the BLE device
Followed by log of connecting, selecting the characteristic and handling change notifications.
Final code can be found here:
https://github.com/sukapx/tryout_blazor_webbluetooth/tree/b958f4e460c969c20fa595645a5f477dd9ddde86