@livelywire/homebridge-ledstrip
Version:
A Homebridge plugin for controlling LED strips via BLE.
90 lines (79 loc) • 2.45 kB
JavaScript
const noble = require('noble');
const DEVICE_ADDRESS = 'FF:FF:4A:03:B5:62'; // Replace with your device's MAC address
const CHARACTERISTIC_UUID = '0003'; // Replace with your characteristic UUID
// Start scanning for devices
noble.on('stateChange', (state) => {
if (state === 'poweredOn') {
noble.startScanning([], true); // Start scanning for all peripherals
} else {
noble.stopScanning();
}
});
noble.on('discover', (peripheral) => {
if (peripheral.address === DEVICE_ADDRESS) {
noble.stopScanning();
connectToPeripheral(peripheral);
}
});
function connectToPeripheral(peripheral) {
peripheral.connect((err) => {
if (err) {
console.error('Failed to connect:', err);
return;
}
peripheral.discoverServices([], (err, services) => {
if (err) {
console.error('Failed to discover services:', err);
return;
}
// Assuming the first service is the one we need
const service = services[0];
service.discoverCharacteristics([], (err, characteristics) => {
if (err) {
console.error('Failed to discover characteristics:', err);
return;
}
// Find the characteristic you need
const characteristic = characteristics.find(c => c.uuid === CHARACTERISTIC_UUID);
if (characteristic) {
// Write to the characteristic
characteristic.write(Buffer.from([0x04, 0x00]), true, (err) => {
if (err) {
console.error('Failed to write characteristic:', err);
}
});
}
});
});
});
}
module.exports = (homebridge) => {
homebridge.registerAccessory('homebridge-ledstrip', 'LEDStrip', LEDStripAccessory);
};
class LEDStripAccessory {
constructor(log, config) {
this.log = log;
this.name = config.name;
this.service = new homebridge.hap.Service.Switch(this.name);
// Initialize noble and start scanning
noble.on('stateChange', (state) => {
if (state === 'poweredOn') {
noble.startScanning([], true);
} else {
noble.stopScanning();
}
});
noble.on('discover', (peripheral) => {
if (peripheral.address === DEVICE_ADDRESS) {
noble.stopScanning();
this.connectToPeripheral(peripheral);
}
});
}
connectToPeripheral(peripheral) {
// Same connectToPeripheral function as above
}
getServices() {
return [this.service];
}
}