Created
February 9, 2020 15:11
-
-
Save dnicolson/8fbc56cc6fdb3c88bf3f71cc160738c1 to your computer and use it in GitHub Desktop.
Script to a control a SwitchBot device without depending on gatttool
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
const noble = require('@abandonware/noble'); | |
const address = ''; | |
const uuidPrimary = 'cba20d00224d11e69fb80002a5d5c51b'; | |
const uuidWrite = 'cba20002224d11e69fb80002a5d5c51b'; | |
noble.on('stateChange', state => { | |
if (state === 'poweredOn') { | |
noble.startScanning([uuidPrimary], false); | |
} else { | |
noble.stopScanning(); | |
} | |
}); | |
noble.on('discover', peripheral => { | |
if (peripheral.address === idOrAddress) { | |
noble.stopScanning(); | |
const advertisement = peripheral.advertisement; | |
const serviceData = advertisement.serviceData; | |
const buf = serviceData[0].data; | |
const byte1 = buf.readUInt8(1); | |
const state = byte1 & 0b01000000 ? true : false; | |
console.log('SwitchBot state:', state); | |
writeCharacterstic(peripheral, state); | |
} | |
}); | |
function writeCharacterstic(peripheral, state) { | |
peripheral.on('disconnect', () => { | |
process.exit(0); | |
}); | |
peripheral.connect(error => { | |
peripheral.discoverAllServicesAndCharacteristics((error, services, chars) => { | |
chars.forEach(char => { | |
if (char.uuid === uuidWrite) { | |
const off = new Buffer.from('570101', 'hex'); | |
const on = new Buffer.from('570102', 'hex'); | |
const cmd = state ? off : on; | |
console.log('Turning light', state ? 'off' : 'on'); | |
char.write(cmd, false, error => { | |
peripheral.disconnect(); | |
}); | |
} | |
}); | |
} | |
); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment