1+ /// UI elements
12const connectButton = document . getElementById ( 'connect' ) ;
23const batteryLevelElement = document . getElementById ( 'battery-level' ) ;
34const batteryLabel = document . getElementById ( 'battery-label' ) ;
@@ -8,6 +9,7 @@ const serviceUuid = '19b10000-0000-537e-4f6c-d104768a1214';
89let pollIntervalID ;
910let peripheralDevice ;
1011
12+ /// Data structure to hold the characteristics and their values plus data conversion functions.
1113let data = {
1214 "batteryPercentage" : {
1315 "name" : "Battery Percentage" ,
@@ -79,6 +81,12 @@ function onDisconnected(event) {
7981 batteryLabel . textContent = "" ;
8082}
8183
84+ /**
85+ * Connects to the Arduino board and starts reading the characteristics.
86+ * @param {Boolean } usePolling The default is to use notifications, but polling can be used instead.
87+ * In that case a poll interval can be defined.
88+ * @param {Number } pollInterval The interval in milliseconds to poll the characteristics from the device.
89+ */
8290async function connectToPeripheralDevice ( usePolling = false , pollInterval = 5000 ) {
8391 if ( peripheralDevice && peripheralDevice . gatt . connected ) {
8492 console . log ( "Already connected" ) ;
@@ -129,6 +137,12 @@ connectButton.addEventListener('click', async () => {
129137 }
130138} ) ;
131139
140+ /**
141+ * Renders the data from the device in the UI.
142+ * It displays the battery level as a visual bar color coded from red to green.
143+ * It also displays the battery voltage and the percentage of the regulated voltage.
144+ * It also displays the charging and external power status.
145+ */
132146function displayBatteryData ( ) {
133147 const batteryPercentage = data . batteryPercentage . value ;
134148 const batteryVoltage = data . batteryVoltage . value ;
@@ -144,6 +158,10 @@ function displayBatteryData() {
144158 externalPowerIconElement . style . display = data . runsOnBattery . value ? "none" : "block" ;
145159}
146160
161+ /**
162+ * Used together with polling to read the characteristics from the device.
163+ * After reading the data it is displayed in the UI by calling displayBatteryData().
164+ */
147165async function readCharacteristicsData ( ) {
148166 await Promise . all (
149167 Object . keys ( data ) . map ( async ( key ) => {
@@ -156,6 +174,11 @@ async function readCharacteristicsData() {
156174 displayBatteryData ( ) ;
157175}
158176
177+ /**
178+ * Callback function that is called when a characteristic value changes.
179+ * Updates the data object with the new value and displays it in the UI by calling displayBatteryData().
180+ * @param {* } event The event that contains the characteristic that changed.
181+ */
159182function handleCharacteristicChange ( event ) {
160183 // Find the characteristic that changed in the data object by matching the UUID
161184 let dataItem = Object . values ( data ) . find ( item => item . characteristicUUID === event . target . uuid ) ;
0 commit comments