Reputation: 59
I have a method to monitor a characteristic on my BLE device.
import {
BleError,
BleManager,
Device,
Subscription,
} from "react-native-ble-plx";
const bleManager = new BleManager();
const BUTTON_RESULT = {
down: "AQ==",
up: "AA==",
};
Here are methods used to connect to the device:
const connectToDevice = async (device: Device) => {
try {
console.log("🔄 Attempting to connect to:", device.id, device.name);
const connected = await bleManager.connectToDevice(device.id);
console.log("✅ Device connected:", connected.id, connected.name);
await connected.discoverAllServicesAndCharacteristics();
setConnectedDevice(connected);
setAttemptDisconnect(false);
console.log("🔄 Attempting to monitor button clicks");
monitorButtonClicks(device);
bleManager.onDeviceDisconnected(device.id, () => {
console.log("❌ Device disconnected");
setConnectedDevice(null);
});
} catch (e) {
console.log("❌ FAILED TO CONNECT:", e);
}
};
const monitorButtonClicks = async (device: Device) => {
try {
if (buttonClickSubscriptionRef.current) {
console.log("Already monitoring button clicks, skipping...");
return;
}
console.log("Monitoring button clicks...");
const characteristic = await device.monitorCharacteristicForService(
SERVICE_UUID,
CHARACTERISTIC_UUID.button,
(error, characteristic) => {
if (error) {
console.error("Notification Error:", error);
return;
}
console.log("Button characteristic value:", characteristic?.value);
if (characteristic?.value) {
if (characteristic.value === BUTTON_RESULT.up) {
console.log("Button pressed up");
handleButtonCount();
} else if (characteristic.value === BUTTON_RESULT.down) {
console.log("Button pressed down");
}
}
}
);
buttonClickSubscriptionRef.current = characteristic;
} catch (error) {
console.error("Subscription Error:", error);
}
};
The monitoring is working so far. I log "button pressed up/down" when those events occur. The issue I'm having is related to handleButtonCount()
const handleButtonCount = () => {
const currentTime = Date.now();
console.log("Current time:", currentTime);
console.log("Last press time:", lastPressTimeRef.current);
if (currentTime - lastPressTimeRef.current > debounceInterval) {
console.log("Handling button count increment...");
lastPressTimeRef.current = currentTime;
setButtonCount((prevCount) => {
const newCount = prevCount + 1;
console.log("Button count updated:", newCount); // Log the updated value
return newCount; // Ensure this is returned for the state to update
});
} else {
console.log("Debounce interval not passed, skipping increment.");
}
};
The thing is, the buttonCount state does not ever get updated even though the presses are being logged. This UseEffect never runs:
useEffect(() => {
if (buttonCount > 0) {
console.log("Button count updated:", buttonCount);
// You can perform actions based on updated buttonCount here
}
}, [buttonCount]); // Ensure this effect runs when buttonCount changes
Upvotes: -2
Views: 62