BLE gattServer.write () - PullRequest
       47

BLE gattServer.write ()

0 голосов
/ 06 ноября 2018

У меня возникла проблема при попытке обновить значение характеристики в пользовательском сервисе BLE, работающем на MCU с mbedOS. Я пытаюсь обновить значение этой характеристики значением, переданным приложением «nRF Connect». значение получено правильно, но значение характеристики не обновляется. Пожалуйста, смотрите код ниже:

/* mbed Microcontroller Library


* Copyright (c) 2006-2015 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <events/mbed_events.h>
#include <mbed.h>
#include "ble/BLE.h"

uint16_t customServiceUUID  = 0xA000;
uint16_t readCharUUID       = 0xA001;
uint16_t writeCharUUID      = 0xA002;
char data_received[30];
char SSID[30];
char password[30];

char pin[] = "1234";
char code[5];

const static char     DEVICE_NAME[]        = "ChangeMe!!"; // change this
static const uint16_t uuid16_list[]        = {0xFFFF}; //Custom UUID, FFFF is reserved for development

/* Set Up custom Characteristics */
static uint8_t readValue[10] = {0};
ReadOnlyArrayGattCharacteristic<uint8_t, sizeof(readValue)> readChar(readCharUUID, readValue);

static uint8_t writeValue[10] = {0};
WriteOnlyArrayGattCharacteristic<uint8_t, sizeof(writeValue)> writeChar(writeCharUUID, writeValue);

/* Set up custom service */
GattCharacteristic *characteristics[] = {&readChar, &writeChar};
GattService        customService(customServiceUUID, characteristics, sizeof(characteristics) / sizeof(GattCharacteristic *));



/*
 *  Restart advertising when phone app disconnects
*/
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *)
{
    BLE::Instance(BLE::DEFAULT_INSTANCE).gap().startAdvertising();
}

/*
 *  Handle writes to writeCharacteristic
*/
void writeCharCallback(const GattWriteCallbackParams *params)
{
    /* Check to see what characteristic was written, by handle */
    if(params->handle == writeChar.getValueHandle()) {
        //printf("Data received: length = %d, data = 0x",params->len);
        for(int x=0; x < params->len; x++) {
            if(params->data[x] == 'a'){
                printf("il carattere e %c\n" , params->data[x]);
                for(int x ; x + 5 ; x++){
                    int i = 0;
                    code[i] = params->data[x];
                    i++;
                }

            }

            data_received[x] = params->data[x];
            printf("%c", params->data[x]);
        }
        printf("\n\r");
        printf("il codice e %s\n", code);


        /* Update the readChar with the value of writeChar */
        BLE::Instance(BLE::DEFAULT_INSTANCE).gattServer().write(readChar.getValueHandle(), params->data , params->len);


    }
}

/*
 * Initialization callback
 */
void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
    BLE &ble          = params->ble;
    ble_error_t error = params->error;

    if (error != BLE_ERROR_NONE) {
        return;
    }
    else{
        printf("%s",error);
    }


    ble.gap().onDisconnection(disconnectionCallback);
    ble.gattServer().onDataWritten(writeCharCallback);


    /* Setup advertising */
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); // BLE only, no classic BT
    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); // advertising type
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME)); // add name
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list)); // UUID's broadcast in advertising packet
    ble.gap().setAdvertisingInterval(100); // 100ms.

    /* Add our custom service */
    ble.addService(customService);

    /* Start advertising */
    ble.gap().startAdvertising();
}

/*
 *  Main loop
*/
int main(void)
{
    /* initialize stuff */
    printf("\n\r********* Starting Main Loop *********\n\r");

    BLE& ble = BLE::Instance(BLE::DEFAULT_INSTANCE);

    ble.init(bleInitComplete);


    /* SpinWait for initialization to complete. This is necessary because the
     * BLE object is used in the main loop below. */
    while (ble.hasInitialized()  == false) { /* spin loop */ }

    /* Infinite loop waiting for BLE interrupt events */
    while (true) {

        ble.waitForEvent(); /* Save power */
    }
}

В частности, функция, которая должна обновлять значение признака:

void writeCharCallback(const GattWriteCallbackParams *params)
{
    /* Check to see what characteristic was written, by handle */
    if(params->handle == writeChar.getValueHandle()) {
        //printf("Data received: length = %d, data = 0x",params->len);
        for(int x=0; x < params->len; x++) {
            if(params->data[x] == 'a'){
                printf("il carattere e %c\n" , params->data[x]);
                for(int x ; x + 5 ; x++){
                    int i = 0;
                    code[i] = params->data[x];
                    i++;
                }

            }

            data_received[x] = params->data[x];
            printf("%c", params->data[x]);
        }
        printf("\n\r");
        printf("il codice e %s\n", code);

        /* Update the readChar with the value of writeChar */
        BLE::Instance(BLE::DEFAULT_INSTANCE).gattServer().write(readChar.getValueHandle(), params->data , params->len);

    }
}

Для получения дополнительной информации см. Следующую ссылку https://os.mbed.com/teams/Bluetooth-Low-Energy/code/BLE_GATT_Example/

...