Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
95 lines (76 loc) · 2.72 KB
/
Copy pathindex.js
File metadata and controls
95 lines (76 loc) · 2.72 KB
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
const EventEmitter = require('events');
var noble = require('noble');
class MiScale extends EventEmitter {
constructor(macAddr) {
super();
let self = this;
this._macAddr = macAddr;
this._scales = new Array();
noble.on('discover', function (foo) {
self._nobleDiscoverListener(foo);
});
};
_scaleListener(peripheral) {
let scale = new Object();
scale.address = peripheral.address;
if (peripheral.advertisement.serviceData.length === 0) {
return;
}
// Assume only single service is available on scale.
scale.svcUUID = peripheral.advertisement.serviceData[0].uuid;
scale.svcData = peripheral.advertisement.serviceData[0].data;
scale.manufacturerData = peripheral.advertisement.manufacturerData;
//Is it duplicated packet?
if(this._scales[scale.address] &&
this._scales[scale.address].svcData.compare(scale.svcData) == 0) {
return;
}
//Save scale object in duplication lookup table.
this._scales[scale.address] = scale;
//Parse service data.
let svcData = scale.svcData;
scale.isStabilized = ((svcData[0] & (1<<5)) !== 0) ? true : false;
scale.loadRemoved = ((svcData[0] & (1<<7)) !== 0) ? true : false;
if((svcData[0] & (1<<4)) !== 0) { // Chinese Catty
scale.unit = "jin";
} else if ((svcData[0] & 0x0F) === 0x03) { // Imperial pound
scale.unit = "lbs";
} else if ((svcData[0] & 0x0F) === 0x02) { // MKS kg
scale.unit = "kg";
} else {
throw new Error("Invalid data!");
}
scale.weight = svcData.readUInt16LE(1) / 100;
scale.sequence = svcData.readUInt16BE(8);
if(scale.unit === "kg") { //Convert chinese Catty to kg.
scale.weight /= 2;
}
this.emit('data', scale);
};
_nobleDiscoverListener(peripheral) {
if(this._macAddr != undefined) {
if(peripheral.address == this._macAddr &&
peripheral.advertisement.localName === "MI_SCALE") {
// Matched!
this._scaleListener(peripheral);
}
} else {
// Match any Xiaomi scale and send event.
if(peripheral.advertisement.localName === "MI_SCALE") {
//Matched!
this._scaleListener(peripheral);
}
}
};
startScanning() {
noble.on('stateChange', function(state) {
if (state === 'poweredOn') {
noble.startScanning([], true);
}
});
};
stopScanning() {
noble.stopScanning();
};
};
module.exports = MiScale;