-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.html
382 lines (329 loc) · 17.2 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Renogy Battery Status</title>
<style>
body {
background-color: #484848;
}
h1 {
color: white;
text-align: center;
font-weight: bold;
}
.text-contrast {
color: white;
}
.form-control:disabled, .form-control[readonly] {
background-color: #fff;
opacity: 1;
}
.input-group-text {
width: 160px;
}
.timestamp {
font-size: 0.8em;
}
#myProgress {
background-color: white;
border-radius: 5px;
margin-bottom: 15px;
}
#myProgress > span {
padding: 5px;
}
#myBar {
width: 0%;
padding: 10px;
background-color: #04AA6D;
text-align: center; /* To center it horizontally (if you want) */
color: white;
border-radius: 0px 0px 0px 5px;
}
a {
color: #03a0fd
}
</style>
</head>
<body>
<div class="container">
<h1>Renogy Battery Status</h1>
<div id="battery-connect-container" class="container" style="padding-bottom: 20px">
<button id="battery-connect" class="btn btn-primary">Connect</button>
<div class="text-contrast">(Chrome only)</div>
</div>
<div class="container">
<div id="myProgress">
<span>Charge Level</span>
<div id="myBar">-</div>
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="watts">Watts</span>
<input type="text" class="form-control" id="watts-form" aria-describedby="watts" disabled="true">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="state">Charge State</span>
<input type="text" class="form-control" id="state-form" aria-describedby="state" disabled="true">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="temperatures">Temperatures</span>
<input type="text" class="form-control" id="temperatures-form" aria-describedby="temperatures" disabled="true">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="volt">Volt/Current</span>
<input type="text" class="form-control" id="volt-form" aria-describedby="volt" disabled="true">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="level">Charge Level</span>
<input type="text" class="form-control" id="level-form" aria-describedby="level" disabled="true">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="cellvolts">Cell Volts</span>
<input type="text" class="form-control" id="cellvolts-form" aria-describedby="cellvolts" disabled="true">
</div>
<div class="alert alert-primary" role="alert" id="msgalert" style="display: none"></div>
<div id="listContainer"></div>
</div>
<footer class="footer mt-3">
<div class="container">
<span class="small text-contrast">renogy-smart-battery is open source and hosted on <a href="https://github.com/chadj/renogy-smart-battery">Github</a>. Contributions are welcome. <a href="https://github.com/chadj/renogy-smart-battery">https://github.com/chadj/renogy-smart-battery</a> </span><br />
<span class="small text-contrast">Send questions or comments to <a href="mailto:[email protected]">[email protected]</a> | <a href="https://chadj.github.io/litime-bluetooth-battery/">Li Time version</a></span><br />
</div>
</footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script>
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const fmt = new Intl.NumberFormat('en-US', { maximumSignificantDigits: 4 });
let currentArray = [];
let statisticsArray = JSON.parse(localStorage.getItem('statisticsArray'));
if (!statisticsArray) {
statisticsArray = [];
}
let date = Date.now();
let $bcc = document.getElementById('battery-connect-container');
let $bc = document.getElementById('battery-connect');
let $tf = document.getElementById('temperatures-form');
// let $tfC = document.getElementById('temperaturesC-form');
let $vf = document.getElementById('volt-form');
let $cf = document.getElementById('current-form');
let $lf = document.getElementById('level-form');
let $cvf = document.getElementById('cellvolts-form');
let $sf = document.getElementById('state-form');
let $wf = document.getElementById('watts-form');
let $msg = document.getElementById('msgalert');
let elem = document.getElementById("myBar");
let width = 1;
function getTimestamp (time) {
const pad = (n,s=2) => (`${new Array(s).fill(0)}${n}`).slice(-s);
const d = new Date(time);
return `${pad(d.getFullYear(),4)}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
$bc.onclick = (e) => {
e.preventDefault();
(async function() {
let device;
if(navigator.userAgent.toLowerCase().includes('bluefy')) {
device = await navigator.bluetooth.requestDevice({
filters: [{services: [0xFFD0]}]
});
} else {
device = await navigator.bluetooth.requestDevice({
filters: [{services: [0xFFD0]}],
optionalServices: [0xFFF0]
});
}
let server = await device.gatt.connect();
let rxService = await server.getPrimaryService(0xFFD0);
let rxCharacteristic = await rxService.getCharacteristic(0xFFD1);
let txService = await server.getPrimaryService(0xFFF0);
let txCharacteristic = await txService.getCharacteristic(0xFFF1);
await txCharacteristic.startNotifications();
let requestType = '';
txCharacteristic.addEventListener('characteristicvaluechanged', (event) => {
try {
const packet = event.target.value;
const payload = new DataView(packet.buffer, 3);
// console.log('payload', payload);
if(requestType === 'getTemps') {
let numSensors = payload.getUint16(0);
let temps = [];
let tempsC = [];
for(let x=1; x <= numSensors; x++) {
// console.log('sensors', payload.getInt16(x*2));
let tempF = (payload.getInt16(x*2) / 10) * (9/5) + 32;
let tempC = (payload.getInt16(x*2) / 10);
temps.push(fmt.format(tempF));
tempsC.push(fmt.format(tempC));
}
$tf.value = tempsC.join(', ') + ' °C / ' + temps.join(', ') + ' °F';
} else if(requestType === 'getLevels') {
let current = payload.getInt16(0) / 100;
let volt = payload.getUint16(2) / 10;
let chargeLevel = payload.getUint32(4) / 1000;
let capacity = payload.getUint32(8) / 1000;
const maxCurrent = Math.max(...currentArray);
const minCurrent = Math.min(...currentArray);
// if there is an abruptly current change, we need to adapt average values faster
if (maxCurrent - minCurrent >= 3) {
currentArray.splice(0,7);
}
// create current Array for smooth out charge state estimation
currentArray.push(current);
if ( currentArray.length > 10 ) {
currentArray.shift();
}
const currentSum = currentArray.reduce((a, b) => a + b, 0);
const currentAvg = (currentSum / currentArray.length).toFixed(2) || 0;
let state = '-';
if(current > 0) {
let duration = Math.abs((capacity - chargeLevel) / currentAvg).toFixed(3);
let hours = Math.floor(duration);
let minutes = new String(Math.round((duration - hours) * 60)).padStart(2, '0');
state = fmt.format(hours) + "h " + minutes + "m till charged";
} else if(current < 0) {
let duration = Math.abs(chargeLevel / currentAvg).toFixed(3);
let hours = Math.floor(duration);
let minutes = new String(Math.round((duration - hours) * 60)).padStart(2, '0');
state = fmt.format(hours) + "h " + minutes + "m till depleted";
}
$vf.value = volt + ' / ' + currentAvg;
// $cf.value = currentAvg;
let chargePercent = (chargeLevel / capacity) * 100;
$lf.value = fmt.format(chargePercent) + "% (" + chargeLevel + "/" + capacity + ")";
$sf.value = state;
$wf.value = fmt.format((currentAvg * volt).toFixed(2));
elem.style.width = fmt.format(chargePercent) + "%";
elem.innerHTML = fmt.format(chargePercent) + "%";
// create a timestamp, update on every new poll to store the last infos
// let timestamp = Date.now();
let timestamp = new Date;
// create uID to store only the last value per day
uniqueTimeID = '' + timestamp.getFullYear() + (timestamp.getMonth()+1) + (timestamp.getDate()) + '';
manipulateEntry = statisticsArray.filter(element => element.uniqueTimeID === uniqueTimeID);
if ( manipulateEntry.length === 0 ) {
// create new item per day if nothing exist
statisticsArray.push({ uniqueTimeID: uniqueTimeID, time: timestamp,
chargeLevel: fmt.format(chargePercent),
volt: volt,
currentAvg: currentAvg,
});
} else {
// manipulate the existing entry per day
manipulateEntry[0].time = timestamp;
manipulateEntry[0].chargeLevel = fmt.format(chargePercent);
manipulateEntry[0].volt = volt;
manipulateEntry[0].currentAvg = currentAvg;
}
// cut array after 30 days
if ( statisticsArray.length > 30 ) {
statisticsArray.shift();
}
localStorage.setItem('statisticsArray', JSON.stringify(statisticsArray));
var strList = '<ul class="list-group">'
strList += '<li class="list-group-item active"> On phone stored statistics (max.30 days)</li>';
statisticsArray.forEach(function(element) {
strList += '<li class="list-group-item"><span class="timestamp">'+ getTimestamp (element.time) + '</span><br>' + element.chargeLevel + '% (' + element.volt + 'V / ' + element.currentAvg + 'A)</li>';
});
strList += '</ul>';
document.getElementById("listContainer").innerHTML = strList;
// console.log('chargeLevel', chargeLevel);
// console.log('capacity', capacity);
} else if(requestType === 'getCellVolts') {
let numCells = payload.getUint16(0);
let volts = [];
for(let x=1; x <= numCells; x++) {
let volt = payload.getUint16(x*2) / 10;
volts.push(volt);
}
$cvf.value = volts.join(', ');
}
} catch (error) {
console.error(error);
}
requestType = '';
});
let requestReady = async function() {
while(true) {
if(requestType === '') {
break;
}
await timeout(250);
}
};
let getTemps = async function () {
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
view.setUint16(0, 0x3003);
view.setUint16(2, 0x1399);
view.setUint16(4, 0x0005);
view.setUint16(6, 0x5543);
requestType = 'getTemps';
if(rxCharacteristic.writeValueWithResponse) {
await rxCharacteristic.writeValueWithResponse(buffer);
} else {
await rxCharacteristic.writeValue(buffer);
}
};
let getLevels = async function () {
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
view.setUint16(0, 0x3003);
view.setUint16(2, 0x13B2);
view.setUint16(4, 0x0006);
view.setUint16(6, 0x654A);
requestType = 'getLevels';
if(rxCharacteristic.writeValueWithResponse) {
await rxCharacteristic.writeValueWithResponse(buffer);
} else {
await rxCharacteristic.writeValue(buffer);
}
};
let getCellVolts = async function () {
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
view.setUint16(0, 0x3003);
view.setUint16(2, 0x1388);
view.setUint16(4, 0x0011);
view.setUint16(6, 0x0549);
requestType = 'getCellVolts';
if(rxCharacteristic.writeValueWithResponse) {
await rxCharacteristic.writeValueWithResponse(buffer);
} else {
await rxCharacteristic.writeValue(buffer);
}
};
$bcc.parentNode.removeChild($bcc);
$msg.style.display = 'none';
while(true) {
try {
// console.log('Starting battery read');
await requestReady();
await getTemps();
await requestReady();
await getLevels();
await requestReady();
await getCellVolts();
} catch(err) {
console.error(err);
$msg.style.display = 'block';
$msg.innerHTML = err;
}
await timeout(3000);
}
})().catch((err) => {
console.error(err);
$msg.style.display = 'block';
$msg.innerHTML = err;
});
};
</script>
</body>
</html>