Skip to content

Commit

Permalink
added battery telemetry
Browse files Browse the repository at this point in the history
  • Loading branch information
SaintSampo committed Jul 24, 2024
1 parent d367fec commit 6ac00cd
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 39 deletions.
5 changes: 4 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@
</div>

<div class="container" id="interface">
<button id="ButtonBLE">CONNECT</button>
<button id="ble-button">🔗</button>
<button id="battery-level">🔋:?V</button>
<button id="ble-status">not connected</button>

<div id="settings-grid">
<div class="settings-label">Mobile Layout</div>

Expand Down
91 changes: 56 additions & 35 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
let isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)

let bleAgent = createBleAgent();
let keyboardAgent = createKeyboardAgent();
let axisAgent = createMobileAxisAgent();
Expand All @@ -19,7 +21,6 @@ let toggleInfo = document.getElementById('toggle-info');
// --------------------------- state management ------------------------------------ //

if (localStorage.getItem(toggleMobile.id) == null) {
let isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
if (isMobile) {
localStorage.setItem(toggleMobile.id, 'true');
} else {
Expand Down Expand Up @@ -148,42 +149,35 @@ function renderLoop() {
// -------------------------------------------- bluetooth --------------------------------------- //

function createBleAgent() {
let parent = document.getElementById('ButtonBLE')
let buttonBLE = document.getElementById('ble-button')
let statusBLE = document.getElementById('ble-status')
let batteryDisplay = document.getElementById('battery-level')

const SERVICE_UUID_PESTOBLE = '27df26c5-83f4-4964-bae0-d7b7cb0a1f54';
const CHARACTERISTIC_UUID_GAMEPAD = '452af57e-ad27-422c-88ae-76805ea641a9';
const CHARACTERISTIC_UUID_TELEMETRY = '266d9d74-3e10-4fcd-88d2-cb63b5324d0c';

parent.onclick = changeBleState;
parent.ontouchend = changeBleState;

function displayBleStatus(status) {
parent.innerHTML = status;
switch (status) {
case 'Connecting':
parent.style.backgroundColor = 'grey';
break;
case 'Connected':
parent.style.backgroundColor = '#4dae50';
break;
case 'Disconnecting':
parent.style.backgroundColor = 'grey';
break;
case 'Not Connected':
parent.style.backgroundColor = 'grey';
break;
default:
parent.style.backgroundColor = '#eb5b5b';
}
if (isMobile){
buttonBLE.ontouchend = updateBLE;
} else {
buttonBLE.onclick = updateBLE;
}

function displayBleStatus(status, color) {
statusBLE.innerHTML = status;
console.log(status)
statusBLE.style.backgroundColor = color;
}

let device;
let device = null;
let server;
let service;
let characteristic_gamepad;
let bleUpdateInProgress = false;
let characteristic_battery;
let isConnectedBLE = false;
let bleUpdateInProgress = false;

async function changeBleState() {
async function updateBLE() {
if (bleUpdateInProgress) return
bleUpdateInProgress = true;
if (!isConnectedBLE) connectBLE();
Expand All @@ -192,46 +186,73 @@ function createBleAgent() {
}

async function connectBLE() {
displayBleStatus('Connecting');

try {
device = await navigator.bluetooth.requestDevice({ filters: [{ services: [SERVICE_UUID_PESTOBLE] }] });
if (device == null){
displayBleStatus('Connecting', 'black');
device = await navigator.bluetooth.requestDevice({ filters: [{ services: [SERVICE_UUID_PESTOBLE] }] });
} else {
displayBleStatus('Attempting Reconnect...', 'black');
}

server = await device.gatt.connect();
service = await server.getPrimaryService(SERVICE_UUID_PESTOBLE);

characteristic_gamepad = await service.getCharacteristic(CHARACTERISTIC_UUID_GAMEPAD);
characteristic_battery = await service.getCharacteristic(CHARACTERISTIC_UUID_TELEMETRY);
await characteristic_battery.startNotifications()
await characteristic_battery.addEventListener('characteristicvaluechanged', handleBatteryCharacteristic);

await device.addEventListener('gattserverdisconnected', robotDisconnect);

displayBleStatus('Connected');
displayBleStatus('Connected', '#4dae50'); //green
isConnectedBLE = true;
buttonBLE.innerHTML = '❌';

} catch (error) {
displayBleStatus("Error");
console.error('Error:', error);
if (error.name === 'NotFoundError') {
displayBleStatus('No Device Selected', '#eb5b5b');
} else if (error.name === 'SecurityError') {
displayBleStatus('Security error', '#eb5b5b');
} else {
console.log( error);
displayBleStatus('Connection failed', '#eb5b5b');
connectBLE();
}
}
}

function handleBatteryCharacteristic(event){
let value = event.target.value.getUint8(0);
let voltage = (value/255.0) * 12
batteryDisplay.innerHTML = "🔋:" + voltage.toFixed(2) + "V";
}

async function disconnectBLE() {
displayBleStatus('Disconnecting');
try {
await device.removeEventListener('gattserverdisconnected', robotDisconnect);
await device.gatt.disconnect();

displayBleStatus('Not Connected');
displayBleStatus('Not Connected', 'grey');
isConnectedBLE = false;
buttonBLE.innerHTML = '🔗';


} catch (error) {
displayBleStatus("Error");
displayBleStatus("Error", '#eb5b5b');
console.error('Error:', error);
}
}

function robotDisconnect(event) {
displayBleStatus('Not Connected');
displayBleStatus('Not Connected', 'grey');
isConnectedBLE = false;
connectBLE();
}

async function sendPacketBLE(byteArray) {
if (!isConnectedBLE) return;
if (bleUpdateInProgress) return;

try {
await characteristic_gamepad.writeValueWithoutResponse(new Uint8Array(byteArray));
Expand Down
39 changes: 36 additions & 3 deletions styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -121,21 +121,53 @@ body {
width: 20vw;
height: 30vw;
display: grid;
grid-template-rows: 1fr 3fr;
grid-template-columns: 1fr;
grid-template-rows: 1fr 1fr 2fr;
grid-template-columns: 1fr 1fr;
grid-gap: 1vw;
padding: 1vw;
}

#ButtonBLE {
#ble-button {
background-color: rgb(189, 188, 188);
border-radius: 1vw;
font-size: 4vw;
grid-row: 1;
grid-column: 1;
cursor: pointer;
border: none;
color: #fff;
text-align: center;
transition: background-color 0.3s, transform 0.1s, box-shadow 0.3s;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#ble-button:hover {
background-color: rgb(169, 169, 169);
}
#ble-button:active {
background-color: rgb(159, 159, 159);
transform: translateY(2px);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

#battery-level {
background-color: grey;
border-radius: 1vw;
font-size: 2vw;
grid-row: 1;
grid-column: 2;
cursor: pointer;
}

#ble-status {
background-color: black;
font-size: 2vw;
grid-row: 2;
grid-column: 1;
grid-column: span 2;
cursor: pointer;
}


#mobile-button button {
font-size: 5vw;
background-color: grey;
Expand Down Expand Up @@ -195,6 +227,7 @@ body {
padding: 0.5vw;
grid-column-gap: 0.5vw;
grid-template-columns: 2fr 1fr;
grid-column: span 2;
background-color: grey;
border-radius: 1vw;
justify-content: center;
Expand Down

0 comments on commit 6ac00cd

Please sign in to comment.