Closed ArTyGill closed 5 years ago
The problem is not in the semaphore, but in the callback functions of the bluetooth. HELP ME PLS.
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.
This stale issue has been automatically closed. Thank you for your contributions.
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"); };
};
//BLE pCharacteristic(LED Characteristic) callbaks class MyCallbacks : public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) {
};
//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; }
};
//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){
}
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) {
} //aes cbc-128 std::string aes_encrypt(uint8_t data_in, /uint8_t data_out,/ uint8_t key, unsigned char iv, size_t bytes) {
} //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);
}
//random string std::string get_random_string(unsigned int len){
}
//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) {
}
void FirstStart(void) { PrFlash.begin("FLASH", false);
};
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(){
}
void setup() {
}
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());
}
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