From f49a7f8a0a9f00d129ac0dad18b3bdfe088a5ae3 Mon Sep 17 00:00:00 2001 From: Adema Date: Thu, 3 Apr 2025 13:12:38 +0200 Subject: [PATCH] Upload files to "BLE_client_values_record" --- .../BLE_client_values_record.ino | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 BLE_client_values_record/BLE_client_values_record.ino diff --git a/BLE_client_values_record/BLE_client_values_record.ino b/BLE_client_values_record/BLE_client_values_record.ino new file mode 100644 index 0000000..e810522 --- /dev/null +++ b/BLE_client_values_record/BLE_client_values_record.ino @@ -0,0 +1,83 @@ +#include + +#define SERVICE_UUID "12345678-1234-5678-1234-56789abcdef0" +#define CHARACTERISTIC_UUID "87654321-4321-6789-4321-fedcba987654" + +NimBLEClient* pClient = nullptr; +BLERemoteCharacteristic* pRemoteCharacteristic = nullptr; + +// Callback function for receiving notifications +static void notifyCallback(BLERemoteCharacteristic* pBLERemoteCharacteristic, + uint8_t* pData, size_t length, bool isNotify) { + if (length == 8) { // Expecting 4x uint16_t (8 bytes total) + uint16_t values[4]; + memcpy(values, pData, sizeof(values)); // Copy received bytes into uint16_t array + + // Send data to PC as CSV format + Serial.printf("%d,%d,%d,%d\n", values[0], values[1], values[2], values[3]); + } else { + Serial.println("Invalid data length!"); + } +} + +class MyClientCallbacks : public NimBLEClientCallbacks { + void onConnect(NimBLEClient* pClient) { + Serial.println("Connected to Server!"); + Serial.printf("Negotiated MTU: %d\n", pClient->getMTU()); + } + + void onDisconnect(NimBLEClient* pClient) { + Serial.println("Disconnected from Server!"); + } +}; + +void connectToServer() { + Serial.println("Initializing BLE..."); + NimBLEDevice::init(""); + + pClient = NimBLEDevice::createClient(); + if (!pClient) { + Serial.println("Failed to create client!"); + return; + } + pClient->setClientCallbacks(new MyClientCallbacks()); + + Serial.println("Connecting to server..."); + + // Replace with actual server MAC address + NimBLEAddress address(std::string("64:e8:33:85:36:ee"), BLE_ADDR_PUBLIC); + + if (!pClient->connect(address)) { + Serial.println("❌ Connection failed!"); + return; + } + + Serial.println("✅ Connected!"); + + BLERemoteService* pRemoteService = pClient->getService(SERVICE_UUID); + if (!pRemoteService) { + Serial.println("❌ Failed to find service!"); + pClient->disconnect(); + return; + } + + pRemoteCharacteristic = pRemoteService->getCharacteristic(CHARACTERISTIC_UUID); + if (!pRemoteCharacteristic) { + Serial.println("❌ Failed to find characteristic!"); + pClient->disconnect(); + return; + } + + Serial.println("✅ Subscribing to notifications..."); + pRemoteCharacteristic->subscribe(true, notifyCallback); +} + +void setup() { + Serial.begin(115200); + delay(1000); + connectToServer(); +} + +void loop() { + delay(1000); +}