Test
source/main.cpp
- Committer:
- HelGast95
- Date:
- 2019-01-31
- Revision:
- 79:9f3aca04de4e
- Parent:
- 78:bb7e309408a2
- Child:
- 80:5e52c5847273
File content as of revision 79:9f3aca04de4e:
#define END_OF_JSON 0xFE
#define MAC_FILTER 0x8E
#define VERBOSE_MODE 1 // Habilita la generacion de logs por el puerto USB
#include "mbed.h"
#include "picojson.h"
#include "stats_report.h"
/* Librerías para BLE - Servicio GATT */
#include "ble/BLE.h"
#include "ble/Gap.h"
#include "TOFService.h"
#include "ble/DiscoveredCharacteristic.h"
#include "ble/DiscoveredService.h"
const static char DEVICE_NAME[] = "BLE_CONTROLLER";
static const uint16_t uuid16_list[] = {TOFService::CUSTOM_TOF_SERVICE_UUID};
bool serviceDiscovered = false;
char finalCharacterJSON = END_OF_JSON;
typedef struct {
string MAC; /* Dirección MAC */
float ToF; /* Tiempo de vuelo */
} BLEdata_t;
DigitalOut led3Test(LED3);
DigitalOut led4BLE(LED4);
Serial pcSerial(USBTX, USBRX); // Abrimos conexión serial con el puerto USB
TOFService* tofService;
EventQueue eventQueue;
Queue<BLEdata_t, 32> BLEqueue;
MemoryPool<BLEdata_t, 32> BLEmpool;
Thread threadLED(osPriorityAboveNormal1, 1000);
Thread threadSerial(osPriorityAboveNormal2, 2500);
Thread threadBLE(osPriorityRealtime3, 1000);
template<typename arg>
void printLog(const char * log, arg data) {
if(VERBOSE_MODE) printf(log, data);
}
void printLog(const char * log) {
if(VERBOSE_MODE) printf(log);
}
/**
* Thread encargado de parpadear un LED continuamente
*/
void blinkLED3() {
while(true) {
led3Test = !led3Test;
wait(0.8);
}
}
/**
* Método encargado de enviar un string por el puerto serie char a char
*/
void sendCharArrayToSerial(char const *array, Serial *serial) {
uint32_t i = 0;
while(array[i] != '\0') {
serial->putc(array[i]);
i++;
}
serial->putc('\0');
}
/**
* Thread encargado de enviar JSONs por el puerto serie
*/
void sendJsonOverSerial() {
char tmp[512]; // Vble auxiliar para el tratamiento de cadenas de char.
string str;
while(true) {
// Esperamos a un mensaje en la cola
picojson::object json;
picojson::object event;
picojson::object extraInfo;
osEvent evt = BLEqueue.get();
if (evt.status == osEventMessage) {
BLEdata_t *BLEdata = (BLEdata_t*)evt.value.p;
BLEmpool.free(BLEdata);
int type = rand() % 4;
event["idEvent"] = picojson::value(BLEdata->MAC);
event["type"] = picojson::value((double) type);
str = "E9:ED:F4:AC:BF:8E";
extraInfo["hazardousDevice"] = picojson::value(str);
str = "D5:62:12:BF:B8:45";
if(type != 0) extraInfo["affectedDevice"] = picojson::value(str);
event["extraInfo"] = picojson::value(extraInfo);
json["Event"] = picojson::value(event);
str = picojson::value(json).serialize();
// Convertimos el string a char *
strncpy(tmp, str.c_str(), sizeof(tmp));
strncat(tmp, &finalCharacterJSON, sizeof(finalCharacterJSON)); // Añadimos el caracter al final
tmp[sizeof(tmp) - 1] = 0;
sendCharArrayToSerial(tmp, &pcSerial);
}
}
}
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params) {
printLog("Desconectado. Se comienza la fase de Advertising de nuevo\r\n");
BLE::Instance(BLE::DEFAULT_INSTANCE).gap().startAdvertising();
}
void connectionCallback(const Gap::ConnectionCallbackParams_t *params) {
printLog("Conectado al servidor\r\n");
}
void writeCharCallback(const GattWriteCallbackParams *params) {
if(params->handle == tofService->getValueHandle()) {
char toChar [TOFService::TOF_CHAR_ARRAY_SIZE + 1];
printLog("Data received: length = %d, data = 0x", params->len);
for(int x=0; x < params->len; x++) {
toChar[x] = (char) params->data[x];
printLog("%x", params->data[x]);
}
toChar[params->len] = '\0';
string str(toChar);
printLog("\n\r");
printLog("Dato parseado a string: %s\n\r", str);
}
}
/**
* Esta función se llama si ha habido algún error en el proceso de inicialización del BLE
*/
void onBleInitError(BLE &ble, ble_error_t error) {
printLog("Ha ocurrido un error al inicializar la configuracion del BLE\n");
}
void printMacAddress() {
/* Print out device MAC address to the console*/
Gap::AddressType_t addr_type;
Gap::Address_t address;
BLE::Instance().gap().getAddress(&addr_type, address);
printLog("DEVICE MAC ADDRESS: ");
for (int i = 5; i >= 1; i--){
printLog("%02x:", address[i]);
}
printLog("%02x\r\n", address[0]);
}
/**
* Callback triggered when the ble initialization process has finished
*/
void bleInitComplete(BLE::InitializationCompleteCallbackContext *params) {
BLE &ble = params->ble;
ble_error_t error = params->error;
if (error != BLE_ERROR_NONE) {
return;
}
ble.gap().onDisconnection(disconnectionCallback);
ble.gap().onConnection(connectionCallback);
ble.gattServer().onDataWritten(writeCharCallback);
tofService = new TOFService(ble);
/* 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.
/* Start advertising */
ble.gap().startAdvertising();
}
void scheduleBleEventsProcessing(BLE::OnEventsToProcessCallbackContext* context) {
BLE &ble = BLE::Instance();
eventQueue.call(Callback<void()>(&ble, &BLE::processEvents));
}
void BLEServiceManagment() {
BLE &ble = BLE::Instance();
ble.onEventsToProcess(scheduleBleEventsProcessing);
ble.init(bleInitComplete);
eventQueue.dispatch_forever();
}
int main() {
srand(time(NULL));
threadLED.start(callback(blinkLED3));
threadBLE.start(callback(BLEServiceManagment));
//threadSerial.start(callback(sendJsonOverSerial));
threadLED.join();
threadBLE.join();
//threadSerial.join();
}