Created
December 22, 2019 21:52
-
-
Save astagi/5f2cd8195af8840acd5d2dd5ca825656 to your computer and use it in GitHub Desktop.
R2D2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let writePacket = (characteristic, buff, waitForNotification=false, timeout=0) => { | |
return new Promise(function(resolve, reject) { | |
let dataRead = []; | |
let checkIsAValidRequest = (dataRead) => { | |
if (dataRead[5] != 0x00) { | |
characteristic.removeListener('data', listenerForRead); | |
reject(dataRead[5]); | |
} | |
} | |
let finish = () => { | |
setTimeout(() => { | |
characteristic.removeListener('data', listenerForRead); | |
resolve(true); | |
}, timeout); | |
} | |
let listenerForRead = (data, isNotification) => { | |
dataRead.push(...data) | |
if (data[data.length - 1] === EOP) { | |
if (waitForNotification) { | |
if (dataRead[1] % 2 == 0) { | |
finish(); | |
} else { | |
checkIsAValidRequest(dataRead); | |
} | |
} else { | |
checkIsAValidRequest(dataRead); | |
finish(); | |
} | |
dataRead = []; | |
} | |
}; | |
characteristic.on('data', listenerForRead); | |
characteristic.write(Buffer.from(buff)); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment