Skip to content

Update index.js - Xiaomi battery voltage #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,37 @@ var shepherd = new ZShepherd('/dev/ttyACM0', {
}
});

function toUTF8Array(str) {
var utf8 = [];
for (var i=0; i < str.length; i++) {
var charcode = str.charCodeAt(i);
if (charcode < 0x80) utf8.push(charcode);
else if (charcode < 0x800) {
utf8.push(0xc0 | (charcode >> 6),
0x80 | (charcode & 0x3f));
}
else if (charcode < 0xd800 || charcode >= 0xe000) {
utf8.push(0xe0 | (charcode >> 12),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
// surrogate pair
else {
i++;
// UTF-16 encodes 0x10000-0x10FFFF by
// subtracting 0x10000 and splitting the
// 20 bits of 0x0-0xFFFFF into two halves
charcode = 0x10000 + (((charcode & 0x3ff)<<10)
| (str.charCodeAt(i) & 0x3ff));
utf8.push(0xf0 | (charcode >>18),
0x80 | ((charcode>>12) & 0x3f),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
}
return utf8;
}

shepherd.on('ready', function() {
console.log('Server is ready. Current devices:');
shepherd.list().forEach(function(dev){
Expand Down Expand Up @@ -46,6 +77,15 @@ shepherd.on('ind', function(msg) {
pl=1;

switch (msg.data.cid) {
case 'genBasic': //Basic device information
if(typeof msg.data.data[65281] !== 'undefined') { // decode Xiaomi device string for battery information
var battStr = toUTF8Array(msg.data.data[65281]);
var voltage = (battStr[5] << 8) + battStr[4];
topic += '/battery';
pl = voltage / 1000.0;
console.log ('Voltage '+ pl);
}
break;
case 'genOnOff': // various switches
topic += '/' + msg.endpoints[0].epId;
pl = msg.data.data['onOff'];
Expand Down Expand Up @@ -109,4 +149,4 @@ client.on('connect', function() {
shepherd.start(function(err) { // start the server
if (err)
console.log(err);
});
});