espressif / arduino-esp32

Arduino core for the ESP32
GNU Lesser General Public License v2.1
13.46k stars 7.38k forks source link

BLE ERROR CALLBACK MESSAGE. #2796

Closed ArTyGill closed 5 years ago

ArTyGill commented 5 years ago

Hardware:

Board: ESP32 Wrover Core Installation version: v1.0.3 - rc1 IDE name: Arduino IDE + VS code Flash Frequency: 40Mhz PSRAM enabled: yes Upload Speed: 115200? Computer OS: Windows 10

Description:

I wrote a program for working with BLE, the only problem that arose in the process is that I created 2 separate semaphores for each characteristic in the service. But if you send a long message about 100 characters via nrf connect, both tasks from either of the two semaphores are started. Possibly not semaphore, and in the stack BLE.

Sketch: (leave the backquotes for [code formatting]

//Change the code below by your sketch

include "Arduino.h"

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include "mbedtls/aes.h"

include "mbedtls/base64.h"

include

extern "C" {

include "libb64/cdecode.h"

include "libb64/cencode.h"

}

include "soc/soc.h"

include "soc/rtc_cntl_reg.h"

include <rom/rtc.h>

include "headers/soft_wdt.h"

//#include "headers/oppen_crypto.h"

include "esp_bt_device.h"

if defined(CONFIG_BT_ENABLED)

//------------------------ Generic Acces Profile(GAP) -------------------------------------------

define GAP_SERVICE BLEUUID((uint16_t)UUID_SERVCLASS_GAP_SERVER)

define DEV_NAME_CHARACTERISTIC BLEUUID((uint16_t)ESP_GATT_UUID_GAP_DEVICE_NAME)

define APPEARANCE_CHARACTERISTIC BLEUUID((uint16_t)GATT_UUID_GAP_ICON)

define PREF_CONN_PARAM_CHARACTERISTIC BLEUUID((uint16_t)ESP_GATT_UUID_GAP_PREF_CONN_PARAM)

define DEFAULT_NAME "RamiskaBlinky"

//------------------------ Generic Attribute Profile(GATT) --------------------------------------

define GATT_SERVICE BLEUUID((uint16_t)UUID_SERVCLASS_GATT_SERVER )

//------------------------ NORDIC SERV and CHARACH ----------------------------------------------

define NORDIC_SERVICE_UUID "00001523-1212-EFDE-1523-785FEABCD123"

define LED_CHARACTERISTIC_UUID "00001525-1212-EFDE-1523-785FEABCD123"

define BUTTON_CHARACTERISTIC_UUID "00001524-1212-EFDE-1523-785FEABCD123"

define FIRM_VERSION_CHARACTERISTIC_UUID "00001526-1212-efde-1523-785feabcd123"

//------------------------ OTHER SERV and CHARACH ----------------------------------------------

define BATTERY_SERVISE BLEUUID((uint16_t)ESP_GATT_UUID_BATTERY_SERVICE_SVC)

define BATTERY_LEVEL_CHARACTERISTIC_UUID BLEUUID((uint16_t)ESP_GATT_UUID_BATTERY_LEVEL)

define DEV_INFO_SERVISE BLEUUID((uint16_t)ESP_GATT_UUID_DEVICE_INFO_SVC)

define MANUFCTURE_CHARACTERISTIC_UUID BLEUUID((uint16_t)ESP_GATT_UUID_MANU_NAME)

//------------------------ iBeacon UUID --------------------------------------------------------

define DEFAULT_BEACON_UUID BLEUUID((std::string)UUID_ibeacon_1)

define UUID_ibeacon_1 "55555555-5555-5555-5555-555555555555"

endif // CONFIG_BT_ENABLED

define DEFINED 1

if defined(DEFINED)

define PORT_AUDIO 25

define PORT_BUTTON 36

define PORT_FIRE 39

define PORT_DATA0 35

define PORT_DATA1 34

define PORT_OUT_1 22

define PORT_OUT_2 21

define PORT_OUT_3 32

define PORT_WDT 27

define PORT_1_LEVEL HIGH

define PORT_2_LEVEL HIGH

define TIME_OPEN 4000

define LED_AUTO_OFF_DELAY (TIME_OPEN*1000) //in uSec

define SWITCH_DELAY (180000) //in mSec

define WGND_TIMEOUT (20000) //in uSec

define CARD_DETECTED 0x02

define READER_IS_READY 0x01

define READER_OFF 0x00

define ACTIVE 0x01

endif

define FIRMWAREVERSION 19

define FIRST_INIT (uint8_t)0x00

define RE_INIT (uint8_t)0xFF

define DEFAULT_URL ""

define DEFAULT_MODE 0x01

define DEFAULT_DISTANSE 100

define MODE_ENCODE 0x01

define MODE_DECODE 0x02

define DEFAULT_KEY (char*)("abcdefghabcdefgh")

define CBC_IV (char*)("RandomInitVector")

RTC_DATA_ATTR int bootCount = 0; RTC_DATA_ATTR uint32_t filePosition = 0;

uint8_t bleScanner = 0x01;

Preferences PrFlash;

uint8_t lockMode; uint8_t fbMode; uint8_t openDistanse = 100; uint32_t openTime = 12000;

//char Base64_symbols[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n";

std::string devname = "OPPEN"; std::string serviseUUID = "55555555-5555-5555-5555-555555555555";

String PermanentHexKey = "abcdefghabcdefgh"; std::string randKey; std::string lastKey;

struct auth { bool newSession; uint16_t connection; uint8_t validConnection; std::string recievedData; std::string authKey; };

auth authConnection;

String UpdateURL = String("");

BLEScan* pBLEScan;

BLEServer *pServer;

BLEBeacon iBeacon_slot1; BLEBeacon iBeacon_slot2;

BLEService pService; BLEService UUIDService;

BLEAdvertising ibeacon_adv; BLEAdvertising ibeacon2_adv; BLEAdvertising *pAdvertising;

BLECharacteristic pCharacteristic; BLECharacteristic pCharacteristicBut; BLECharacteristic *firmwareVersionCharacteristic;

BLECharacteristic *CharSetup;

BLEAdvertisementData LEDCOMPLETE; BLEAdvertisementData advertisementData; BLEAdvertisementData AdvBeaconData;

bool deviceConnected = false; bool newConnection = false; bool BLEinital = false;

struct SigPins { const uint8_t Pin; uint32_t numberKeyPresses; bool isPressed; };

bool ChangeKey = false; bool getUpdate = false; bool buzActive = false;

bool SwitchFlag = false;

bool logUpdate = false;

bool commandGet = false; bool commandUpload = false;

uint16_t connectionWrite;

std::string pack; static std::string ServiceRecieve; std::string strJson; //std::string decrypt;

size_t olen = 0;

time_t lastDay; static uint16_t count = 0; static uint16_t countSwitchTimer = 0;

SigPins BUTTON = { PORT_BUTTON, 0, false }; SigPins FIRE = { PORT_FIRE, 0, false };

portMUX_TYPE timerMux0 = portMUX_INITIALIZER_UNLOCKED;

SemaphoreHandle_t xBinarySemaphoreAuthentication; SemaphoreHandle_t xBinarySemaphoreParsingData;

hw_timer_t LedTimer1 = NULL; hw_timer_t SwitchTimer = NULL;

std::string scanedDevices; uint16_t bleDeviceID;

// the number of the LED pin const int ledPin = PORT_OUT_2; // 16 corresponds to GPIO16

// setting PWM properties const int freq = 4; const int ledChannel = 6; const int resolution = 8;

const int ledChannel2 = 8;

TimerHandle_t tmrwdt; uint32_t timeridWDT = 1; uint32_t intervalWDT = 15000;

char trigButton = 0;

//Function prototypes

void openDoor(char sound); void FirstStart(void); void TimerInit(hw_timer_t timer, uint8_t numTimer, void(fn)(), unsigned long long uSec, bool autoReload);

std::string get_random_string(unsigned int len);

//int setTime(time_t Time);

void timerwdtTask( TimerHandle_t xTimer ); void authenticTask (void *pvParameters);

//BLE scanner callbacks class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks { void onResult(BLEAdvertisedDevice advertisedDevice) {

}

};

//BLE server callbacks class MyServerCallbacks : public BLEServerCallbacks { void onConnect(BLEServer* pServer) { deviceConnected = true; newConnection= true; Serial.println("Connected"); };

void onDisconnect(BLEServer* pServer) {
    if (!pServer->getConnectedCount()) deviceConnected = false;
    uint16_t disconnectID = pServer->getConnId();
    Serial.printf("\r\nDisconnect connID: %d", disconnectID);
    uint8_t tempBitMask = (authConnection.validConnection<<(7-disconnectID));
    tempBitMask = (authConnection.validConnection>>(7-disconnectID));
    authConnection.validConnection = (authConnection.validConnection>>(7-(disconnectID-1))); 
    authConnection.validConnection = (authConnection.validConnection<<(7-(disconnectID-1)));
    authConnection.validConnection |= (tempBitMask << 1);
}

};

//BLE pCharacteristic(LED Characteristic) callbaks class MyCallbacks : public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) {

    connectionWrite = pCharacteristic->getWriteID();
    ServiceRecieve = pCharacteristic->getValue().c_str();   

    portMUX_TYPE myMutex1 = portMUX_INITIALIZER_UNLOCKED;
    portENTER_CRITICAL(&myMutex1);

    BaseType_t xHigherPriorityTaskWoken1;
    xHigherPriorityTaskWoken1 = pdFALSE;
    xSemaphoreGiveFromISR( xBinarySemaphoreParsingData, &xHigherPriorityTaskWoken1 );
    portEXIT_CRITICAL(&myMutex1);
}

};

//BLE pCharacteristicBut(BUTTON Characteristic) callbaks class MyCallbacks2 : public BLECharacteristicCallbacks { void onRead(BLECharacteristic *pCharacteristicBut) { lastKey = randKey; randKey.clear(); randKey = get_random_string(16); pCharacteristicBut->setValue(randKey); authConnection.authKey = lastKey; }

void onWrite(BLECharacteristic *pCharacteristicBut){
    authConnection.newSession = true;
    authConnection.connection = pCharacteristicBut->getWriteID();
    authConnection.recievedData = pCharacteristicBut->getValue().c_str();
    vTaskDelay(20/portTICK_PERIOD_MS);
    pCharacteristicBut->setValue(randKey);

    portMUX_TYPE myMutex2 = portMUX_INITIALIZER_UNLOCKED;
    portENTER_CRITICAL(&myMutex2);
    BaseType_t xHigherPriorityTaskWoken2;
    xHigherPriorityTaskWoken2 = pdFALSE;

    xSemaphoreGiveFromISR( xBinarySemaphoreAuthentication, &xHigherPriorityTaskWoken2 );
    portEXIT_CRITICAL(&myMutex2);
}

};

//BLE SetupHands callbacks class SetupCallBacks : public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *CharSetup) { CharSetup->setValue({ FIRMWAREVERSION }); } };

//AutoClose door timer void IRAM_ATTR onTimer() { buzActive = false; digitalWrite(PORT_OUT_1, !lockMode); digitalWrite(PORT_OUT_3, !fbMode); ledcWrite(ledChannel, 0); }

//Timer switch beacons void IRAM_ATTR TimOnSwitch() { if (countSwitchTimer++ > 1000) { SwitchFlag ^= true; countSwitchTimer = 0; } }

void IRAM_ATTR butFireIsr() { delayMicroseconds(15); uint8_t BUT_LEVEL = digitalRead(0); if (!BUT_LEVEL) { delayMicroseconds(20); if (!digitalRead(0)){ trigButton = 1^trigButton; pCharacteristicBut->setValue({trigButton});

    }
}

}

//Timer setup void TimerInit(hw_timer_t timer, uint8_t numTimer, void(fn)(), unsigned long long uSec, bool autoReload) { timer = timerBegin(numTimer, 80, true); timerAttachInterrupt(timer, *fn, true); timerAlarmWrite(timer, uSec, autoReload); timerStart(timer); timerAlarmEnable(timer); }

esp_err_t authClearConn (auth *connection){

connection->recievedData.clear();
connection->newSession = false;
connection->connection = 0;

}

char Base64_symbols[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n";

std::string Base64_convert(uint8_t mode, uint8_t data_in, size_t size, uint8_t data_out, size_t outlen) { if (mode == MODE_ENCODE) { size_t base64size = ((size 1.6f) + 1); char buffer = (char )malloc(base64size); if (buffer) { base64_encodestate _state; base64_init_encodestate(&_state); int len = base64_encode_block((const char )&data_in[0], size, &buffer[0], &_state); len = base64_encode_blockend((buffer + len), &_state); std::string base64encode; base64encode.append(buffer); free(buffer); outlen = len; return base64encode; } free(buffer); } else if (mode == MODE_DECODE) {

    size_t numBase64 = size;
    //Serial.println("Confirm base64: ");
    //Serial.println();
    if (!size) return "Error";
    while (numBase64--)
    {

        uint8_t success = 0;
        for (size_t i = 0; i < sizeof(Base64_symbols); i++)
        {
            if (Base64_symbols[i] == data_in[numBase64]) success = 1;
        }
        if (!success) return "\nError symbols base64";

    }

    base64_decodestate state_dec;
    base64_init_decodestate(&state_dec);
    *outlen = base64_decode_block((char*)data_in, size, (char*)data_out, &state_dec);
    //Serial.println("\rDecode from Base64 is OK!");

    return "\nDecoded from base64";
}
else
{
    //Serial.println("Error to convert from Base64");
    return "\nError decode from base64";
}
return"";

} //aes cbc-128 std::string aes_encrypt(uint8_t data_in, /uint8_t data_out,/ uint8_t key, unsigned char iv, size_t bytes) {

size_t outLen = 0;
uint8_t* tempBuf = (uint8_t*)malloc(bytes);
uint8_t* aesOut = (uint8_t *)malloc(bytes);
size_t dataLen = strlen((char*)data_in);
memcpy(tempBuf, data_in, dataLen);
memset(tempBuf + dataLen, 0x00, bytes - dataLen);

mbedtls_aes_context aes_cntx;
mbedtls_aes_init(&aes_cntx);
mbedtls_aes_setkey_enc(&aes_cntx, (unsigned char*)key, strlen((char*)key) * 8);
mbedtls_aes_crypt_cbc(&aes_cntx, MBEDTLS_AES_ENCRYPT, bytes, (uint8_t*)iv, (unsigned char*)tempBuf, (unsigned char*)aesOut); // @suppress("Function cannot be resolved")
mbedtls_aes_free(&aes_cntx);
free(tempBuf);
std::string Base64_Out = Base64_convert(MODE_ENCODE, aesOut, bytes, NULL, &outLen);
free(aesOut);

return Base64_Out;

} //aes cbc-128 std::string aes_decrypt(uint8_t data_in, /uint8_t data_out,/ uint8_t key, unsigned char iv, size_t bytes) { //Serial.println("Setup size"); size_t base64_size = base64_decode_expected_len(bytes); //Serial.printf("\r\nSize base64: %d", base64_size); //base64_size = base64_size 16; //Serial.println("Setup tempbuf malloc"); uint8_t tempBuf = (uint8_t)malloc(base64_size); size_t outLen = 0; //Serial.println("Base64 convert"); std::string message = Base64_convert(MODE_DECODE, data_in, bytes, tempBuf, &outLen); //Serial.printf("\r\nOutLen: %d", outLen); if (outLen % 16) return "Error decrypt AES 128 CBC;"; //Serial.println(message); if (!strstr(message.c_str(), "Error") && !(outLen % 16) && message.length()) { //Serial.println("Setup aesout malloc"); uint8_t aesOut = (uint8_t )malloc(outLen + 1); //size_t dataLen = strlen((char)data_in);

    mbedtls_aes_context aes_cntx;
    mbedtls_aes_init(&aes_cntx);
    mbedtls_aes_setkey_enc(&aes_cntx, (unsigned char*)key, strlen((char*)key) * 8);
    //Serial.println("Decrypt AES");
    mbedtls_aes_crypt_cbc(&aes_cntx, MBEDTLS_AES_DECRYPT, outLen, (uint8_t*)iv, (unsigned char*)tempBuf, (unsigned char*)aesOut); // @suppress("Function cannot be resolved")
    mbedtls_aes_free(&aes_cntx);
    //Serial.println("Free variables");
    aesOut[outLen] = '\0';
    //Serial.printf("\nDecode print %s", (char*)aesOut);
    free(tempBuf);
    //Serial.println("Bytes to string");
    message.clear();
    message.append((char*)aesOut);
    free(aesOut);
}
else {
    free(tempBuf);
    message = "Error decrypt AES 128 CBC;";
}
//Serial.printf("Result AES: %s\r\n", message.c_str());
return message;

}

//random string std::string get_random_string(unsigned int len){

unsigned int i;
std::string randomStr;
for (i = 0; i < len - 1; i++)
{
    randomStr.append(1, Base64_symbols[(random(0, 64))]);
}
randomStr.append(1, '\0');
return randomStr;

}

//activate doors void openDoor(char sound) { uint8_t num_timer = 1; TimerInit((hw_timer_t )LedTimer1, num_timer, &onTimer, openTime 1000, false); digitalWrite(PORT_OUT_1, lockMode); digitalWrite(PORT_OUT_3, fbMode); ledcWrite(ledChannel, 127); if (sound) buzActive = true; Serial.println("Oppen"); } //BLE init void ble_init(void) {

BLEinital = true;
Serial.println("StartBLE");
//randKey.clear();
randKey = get_random_string(17);
lastKey = randKey;
authConnection.authKey = lastKey;
Serial.printf("\r\nrandKey: %s", randKey.c_str());
Serial.println("Generate string");
BLEDevice::init(devname /*"New_Door"*/);  //INIT BLE and GAP
BLEDevice::setMTU(512);
BLEServer *pServer = BLEDevice::createServer();             //Create Server(or Client)
pServer->setCallbacks(new MyServerCallbacks());             //Use Callback function up
Serial.println("Create server");
pService = pServer->createService(NORDIC_SERVICE_UUID);   //Create new Service with UUID
Serial.println("Create Servise nordic");
pCharacteristicBut = pService->createCharacteristic(BUTTON_CHARACTERISTIC_UUID,
    BLECharacteristic::PROPERTY_READ  |
    BLECharacteristic::PROPERTY_WRITE |
    BLECharacteristic::PROPERTY_NOTIFY
);
Serial.println("Create charac button");
pCharacteristicBut->setCallbacks(new MyCallbacks2());
pCharacteristicBut->addDescriptor(new BLE2902());
pCharacteristicBut->setValue(randKey);
Serial.println("set Servise button");
pCharacteristic = pService->createCharacteristic(LED_CHARACTERISTIC_UUID,
    BLECharacteristic::PROPERTY_READ  |
    BLECharacteristic::PROPERTY_WRITE |
    BLECharacteristic::PROPERTY_NOTIFY
);
pCharacteristic->setValue({ 0x00 });

pCharacteristic->setCallbacks(new MyCallbacks());

pCharacteristic->addDescriptor(new BLE2902());

Serial.println("set Servise led");

pService->start();

iBeacon_slot1.setManufacturerId(uint16_t(0x4c00));
iBeacon_slot1.setMajor(uint16_t(1));
iBeacon_slot1.setMinor(uint16_t(1));
iBeacon_slot1.setProximityUUID(BLEUUID(serviseUUID));
iBeacon_slot1.setSignalPower(0xbd);

iBeacon_slot2.setManufacturerId(uint16_t(0x4c00));
iBeacon_slot2.setMajor(uint16_t(2));
iBeacon_slot2.setMinor(uint16_t(2));
iBeacon_slot2.setProximityUUID(BLEUUID(serviseUUID));
iBeacon_slot2.setSignalPower(0xbd);

advertisementData.setManufacturerData(iBeacon_slot1.getData());
advertisementData.setFlags(ESP_BLE_ADV_FLAG_LIMIT_DISC | ESP_BLE_ADV_FLAG_DMT_HOST_SPT | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT);
ibeacon_adv = pServer->getAdvertising();
ibeacon_adv->setAdvertisementData(advertisementData);
AdvBeaconData.setFlags(ESP_BLE_ADV_FLAG_LIMIT_DISC | ESP_BLE_ADV_FLAG_DMT_HOST_SPT | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT);
AdvBeaconData.setManufacturerData(iBeacon_slot2.getData());
ibeacon_adv = pServer->getAdvertising();
ibeacon_adv->setAdvertisementData(AdvBeaconData);

pAdvertising = pServer->getAdvertising();
LEDCOMPLETE.setFlags(ESP_BLE_ADV_FLAG_NON_LIMIT_DISC | ESP_BLE_ADV_FLAG_DMT_HOST_SPT | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT);
LEDCOMPLETE.setCompleteServices(BLEUUID(NORDIC_SERVICE_UUID));
pAdvertising->setAdvertisementData(LEDCOMPLETE);
BLESecurity *mySecure = new BLESecurity();
mySecure->setAuthenticationMode(ESP_LE_AUTH_BOND);
mySecure->setCapability(ESP_IO_CAP_NONE);
pAdvertising->setMinInterval(20);
pAdvertising->setMinInterval(40);
Serial.println("set Security");
pAdvertising->start();

}

void FirstStart(void) { PrFlash.begin("FLASH", false);

if (PrFlash.getUChar("init") == (uint8_t)FIRST_INIT) {
    PrFlash.clear();
    PrFlash.putUChar("init", RE_INIT);
    PrFlash.putUChar("openDistanse", DEFAULT_DISTANSE);
    PrFlash.putUChar("lockMode", DEFAULT_MODE);
    PrFlash.putUChar("feedBack", DEFAULT_MODE);
    PrFlash.putString("updateURL", DEFAULT_URL);
    PrFlash.putString("beaconUUID", String(UUID_ibeacon_1));
    PrFlash.putString("name", String(DEFAULT_NAME));
    PrFlash.putULong("openTime", TIME_OPEN);
    PrFlash.putString("defaultKey", PermanentHexKey);
    PrFlash.putUChar("bleScan", !ACTIVE);
    //PrFlash.putLong("Time", timeToSec());
    //setTime(PrFlash.getLong("Time"));
}
PrFlash.end();

};

void varSetup(void) { PrFlash.begin("FLASH", false); PrFlash.putUInt("softVersion", FIRMWAREVERSION); openDistanse = PrFlash.getUChar("openDistanse"); serviseUUID = PrFlash.getString("beaconUUID", String(UUID_ibeacon_1)).c_str(); devname = PrFlash.getString("name", String(DEFAULT_NAME)).c_str(); PermanentHexKey = PrFlash.getString("defaultKey"); lockMode = PrFlash.getUChar("lockMode"); fbMode = PrFlash.getUChar("feedBack"); bleScanner = PrFlash.getUChar("bleScan"); openTime = PrFlash.getULong("openTime", TIME_OPEN); UpdateURL = PrFlash.getString("updateURL"); PrFlash.end(); }

void initMyWDT(uint32_t interval){ esp_task_wdt_init((uint32_t)(interval/1000), true) ; tmrwdt = xTimerCreate("MyTimer", pdMS_TO_TICKS(interval), pdTRUE, (void*)timeridWDT, &timerwdtTask); }

void startMyWDT(){ esp_task_wdt_add(NULL) ; if( xTimerStart(tmrwdt, 10 ) != pdPASS ) { printf("Timer start error"); } }

void rstMyWDT(){ xTimerReset(tmrwdt, 10); esp_task_wdt_reset(); }

void stpMyWDT(){

esp_task_wdt_delete(NULL);
xTimerStop(tmrwdt, 10);

}

void setup() {

initMyWDT(intervalWDT);
startMyWDT();
pinMode(2, OUTPUT);
pinMode(22, OUTPUT);
pinMode(27, OUTPUT);
pinMode(0, INPUT_PULLUP);
attachInterrupt(0, butFireIsr, FALLING);
Serial.begin(115200);
FirstStart();
varSetup();
ble_init();
Serial.println("Create semaphore");
//pCharacteristic->setValue({0x00});
//pCharacteristicBut->setValue({0x01});

xBinarySemaphoreAuthentication = xSemaphoreCreateBinary();
if( xBinarySemaphoreAuthentication != NULL )
{
    xTaskCreate( authenticTask, "authenticTask", 3000, NULL, 3, NULL );
    Serial.println("Created semaphore Authentication");
}

xBinarySemaphoreParsingData = xSemaphoreCreateBinary();
if( xBinarySemaphoreParsingData != NULL )
{
    xTaskCreate( openParserTask, "openParserTask", 3000, NULL, 4, NULL );
    Serial.println("Created semaphore parse Data");
}

}

void loop() { rstMyWDT(); vTaskDelay(500 / portTICK_PERIOD_MS); // if (deviceConnected)pCharacteristicBut->notify(-1); // vTaskDelay(20 / portTICK_PERIOD_MS); if (newConnection){ pAdvertising->start(); newConnection = false; } }

void timerwdtTask( TimerHandle_t xTimer ) { ets_printf("reboot\n"); esp_restart(); }

void authenticTask (void pvParameters1){ for(;;) { xSemaphoreTake( xBinarySemaphoreAuthentication, portMAX_DELAY ); Serial.println("Auth read key"); if(authConnection.newSession){
std::string decryptedData; static uint8_t iv[16]; Serial.printf("\r\nrecieved Data: %s", authConnection.recievedData.c_str()); Serial.printf("\r\nKey Auth: %s", authConnection.authKey.c_str()); Serial.printf("\r\nKey Last: %s", lastKey.c_str()); memcpy(iv, CBC_IV, strlen(CBC_IV)); decryptedData = aes_decrypt((uint8_t
)authConnection.recievedData.c_str(), (uint8_t*)PermanentHexKey.c_str(), iv, authConnection.recievedData.length()); Serial.printf("Decrypted: %s", decryptedData.c_str());

        if (strstr(decryptedData.c_str(), authConnection.authKey.c_str()) != NULL){
            pCharacteristic->setValue("succes auth!");
            pCharacteristic->notify(authConnection.connection);
            vTaskDelay(30/portTICK_PERIOD_MS);
            authConnection.validConnection |= (1<<authConnection.connection);

        }

        authClearConn(&authConnection);
    }
}
vTaskDelete(NULL);
ESP.restart();

}

void openParserTask (void *pvParameters2){ for(;;) { xSemaphoreTake( xBinarySemaphoreParsingData, portMAX_DELAY ); if(!(ServiceRecieve.empty())){ Serial.println("DataRecieve"); if (authConnection.validConnection & (1<<connectionWrite)){ unsigned char led = ServiceRecieve.c_str()[0]; Serial.printf("Length %d", ServiceRecieve.length()); Serial.printf("Input value %d", led); if(ServiceRecieve.length()) led = true; else led = false; digitalWrite(2, led); digitalWrite(22, led); digitalWrite(27, led); pCharacteristic->setValue("succes open"); pCharacteristic->notify(connectionWrite); vTaskDelay(30/portTICK_PERIOD_MS); } else { Serial.printf("\r\nNotify error"); pCharacteristic->setValue("error acces"); pCharacteristic->notify(connectionWrite); vTaskDelay(30/portTICK_PERIOD_MS); } Serial.printf("\r\nSet zero"); pCharacteristic->setValue({0}); vTaskDelay(20/portTICK_PERIOD_MS); ServiceRecieve.clear(); } } vTaskDelete(NULL); ESP.restart(); }

External lib "soft_wdt"

FILE "soft_wdt.h"

include "Arduino.h"

ifdef __cplusplus

extern "C" {

include

include

}

endif

define WDT_DELAY (15000*1000) //in uSec

define WDT_TASK_DELAY (15) //in Sec

ArTyGill commented 5 years ago

The problem is not in the semaphore, but in the callback functions of the bluetooth. HELP ME PLS.

stale[bot] commented 5 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] commented 5 years ago

This stale issue has been automatically closed. Thank you for your contributions.