Tema SCPI Negru Rares-Razvan
Dependencies: BLE_API mbed nRF51822
Fork of nRF51822_TemperatureEx by
Diff: main.cpp
- Revision:
- 9:303d3628986a
- Parent:
- 8:f28ad4600b0f
- Child:
- 10:c7d53e4e0602
--- a/main.cpp Mon Apr 11 17:21:14 2016 +0000 +++ b/main.cpp Mon Apr 25 19:34:39 2016 +0000 @@ -2,17 +2,17 @@ Copyright (c) 2012-2014 RedBearLab -Permission is hereby granted, free of charge, to any person obtaining a copy of this software -and associated documentation files (the "Software"), to deal in the Software without restriction, -including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @@ -22,18 +22,23 @@ * Type something from the Terminal to send * to the BLEController App or vice verse. * Characteristics received from App will print on Terminal. + * Read read_me.md file for more informations about the extended feature */ - -#include "mbed.h" + + #include "ble/BLE.h" #include <myData.h> -//#include "LocalFileSystem.h" +#include <Gap.h> +#include "ble_flash.h" +#include "ble_flash.c" #define BLE_UUID_TXRX_SERVICE 0x0000 /**< The UUID of the Nordic UART Service. */ #define BLE_UUID_TX_CHARACTERISTIC 0x0002 /**< The UUID of the TX Characteristic. */ #define BLE_UUIDS_RX_CHARACTERISTIC 0x0003 /**< The UUID of the RX Characteristic. */ -#define TXRX_BUF_LEN 20 +#define TXRX_BUF_LEN 20 /** For radio message transmission*/ + +#define MyASSERT(cond , serialpc, errVal) assert_error_app((bool)cond, serialpc, (uint16_t)errVal, __LINE__, __FILE__) BLE ble; @@ -53,411 +58,521 @@ static uint8_t rx_buf[TXRX_BUF_LEN]; static uint8_t rx_len=0; -static uint32_t gTimeInstant = 5; // 1 second - -//LocalFileSystem local("local"); +static uint32_t gTimeInstant = 1; // TimerTick Resolution, in seconds -static myData_t g_MyData[MAXBUFFER]; +bool g_bIsConnected = false; +bool g_bIsAdvertising = false; +bool g_LogActive = false; +static myDataLog_t g_MyData; +uint8_t g_MyDataIdx=0; -uint16_t g_MyDataIdx=0; - -//uint8_t infoCollector[TXRX_BUF_LEN][10]; - +// pins connected for measuring DigitalOut led(LED1); PwmOut buzzer(p15); - +InterruptIn event(p29); // button AnalogIn VP3(A3); AnalogIn VP4(A4); AnalogIn VP5(A5); +AnalogIn* VP[3]= {&VP3,&VP4,&VP5}; +#define NUM_OF_READINGS (4u) +myPayload_t g_currMeasures; // last measurements Timeout timeout_err; // timeout for buzz on error -Ticker periodicActions, eachInstant; +Ticker periodicActions; mtime_manager_t g_myTimeVar; mdate_manager_t g_myDateVar; -InterruptIn event(p7); +GattCharacteristic txCharacteristic (uart_tx_uuid, txPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE); -GattCharacteristic txCharacteristic (uart_tx_uuid, txPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE); - GattCharacteristic rxCharacteristic (uart_rx_uuid, rxPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY); - + GattCharacteristic *uartChars[] = {&txCharacteristic, &rxCharacteristic}; GattService uartService(uart_base_uuid, uartChars, sizeof(uartChars) / sizeof(GattCharacteristic *)); - -//extern bool isInputValid(uint8_t * buffer); - -bool isInputValid(uint8_t * buffer){ - bool retValue= false; - - switch (buffer[0]){ - case 'i': - switch (buffer[1]){ - case '3': - case '4': - case '5': - retValue = true; - break; - default: - retValue = false; - } - break; - case 'l': - retValue = true; - break; - case 's': - if (((buffer[1]>'9')||(buffer[1]<'0'))||((buffer[2]>'9')||(buffer[2]<'0'))) - retValue = false; - else - retValue = true; - break; - case 't': //timestamp - retValue = true; - break; - case 'd': //date - retValue= true; - break; - default: - // error - retValue = false; - } - return retValue; +void sendRadioMsg(const uint8_t* buf, uint16_t length) +{ + uint8_t retVal; + retVal = ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, length); + //pc.printf("Err=%d\r\n",retVal); + MyASSERT((retVal!=0),&pc, retVal); } - void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason) { pc.printf("Disconnected \r\n"); - pc.printf("Restart advertising \r\n"); - ble.startAdvertising(); + g_bIsConnected = false; + g_bIsAdvertising = false; } -void buzz_int(uint8_t period, uint8_t duty_cycle){ - if (period!=0) { - buzzer = (9.0 - (float)duty_cycle)/9.0; - buzzer.period((float)period); - } else { - buzzer = 0; - } +void connectionCallback(const Gap::ConnectionCallbackParams_t *params) +{ + pc.printf("Connected \r\n"); + g_bIsConnected = true; + g_bIsAdvertising = false; } -float readInput_f(uint8_t channelID){ - float retVal=0.0; - switch (channelID){ - case 3: - retVal = VP3.read(); +void at_timeout_err() +{ + // stop buzz + buzz_int(&buzzer, 0,0); +} +void connectionUpdate(connection_update_t option){ + switch (option){ + case eStartAdvertising:{ + if ((g_bIsConnected == false)&&(g_bIsAdvertising == false)) { + pc.printf("Start Advertising\r"); + ble.startAdvertising(); + g_bIsAdvertising = true; + } + break; + } + case eStopAdvertising:{ + if (g_bIsAdvertising == true){ + pc.printf("Stop Advertising\r"); + ble.stopAdvertising(); + g_bIsAdvertising = false; + } + break; + } + case eDisconnect:{ + if (g_bIsConnected == true) { + pc.printf("Close connection\r"); + ble.disconnect((Gap::DisconnectionReason_t)0x12); + } else if (g_bIsAdvertising == true){ + pc.printf("Stop Advertising\r"); + ble.stopAdvertising(); + g_bIsAdvertising = false; + } break; - case 4: - retVal = VP4.read(); - break; - case 5: - retVal = VP5.read(); - break; + } } - return ((retVal*3.3)); +} +void write_data_to_flash(uint32_t *tick) +{ + uint32_t retVal=0; + uint8_t page_num=0; + + if (g_MyDataIdx==0) { + //initiate connection + connectionUpdate(eStartAdvertising); + // time and date used to initialize the g_MyData variable + memcpy(&g_MyData.startData.date,&g_myDateVar.currentDate, sizeof(date_t)); + memcpy(&g_MyData.startData.time,&g_myTimeVar.currentTime, sizeof(mtime_t)); + memcpy(&g_MyData.startData.data,&g_currMeasures, sizeof(myPayload_t)); + } else { + // it should be logged here the time difference from last record... + g_MyData.myData[g_MyDataIdx].min = (uint16_t)(*tick*gTimeInstant / 60); + g_MyData.myData[g_MyDataIdx].sec = (*tick*gTimeInstant% 60); + memcpy(&g_MyData.myData[g_MyDataIdx].data,&g_currMeasures, sizeof(myPayload_t)); + } + *tick = 0; + + if (g_MyDataIdx==(MAXBUFFER-5)) { + //initiate disconnection + connectionUpdate(eDisconnect); + } + + if (g_MyDataIdx==(MAXBUFFER-1)) { + // write2Flash the current page num + page_num=flash_currPage(); + // write2Flash the current page data + retVal=ble_flash_page_write(page_num, (uint32_t*)&(g_MyData), 251u); + pc.printf("retValWr: %d, Pg:%d, Min: %d \r\n",retVal, page_num,g_myTimeVar.currentTime.min); + flash_go_nextPage(); + //save_flash_curr_pageNr(g_myDateVar.currentDate); + } + g_MyDataIdx = (g_MyDataIdx+1)%(MAXBUFFER); } -void at_timeout_err(){ - // stop buzz - buzz_int(0,0); + +void on_error_radioMsg() +{ + char myBuf[TXRX_BUF_LEN]; + + sprintf(myBuf,"%s","WrongSyntax"); + buzz_int(&buzzer,5,3); + timeout_err.attach(&at_timeout_err, 2); + sendRadioMsg((uint8_t*)&myBuf[0], 12); } -void at_eachInstant(){ - //static uint32_t counter = 0; +void flash_page_serial_dump(uint32_t* p_curr_addr) +{ +myDataLogShort_t initialData; +myDataL_t dataOut[2]; +uint8_t i; + + p_curr_addr += 2; // skip the magic number and the word count + memcpy((uint32_t*)&initialData, p_curr_addr, 6*sizeof(uint32_t)); + pc.printf("20%2d_%2d_%2d H:%2d P:%4x\r",initialData.startData.date.year, initialData.startData.date.month, initialData.startData.date.day, initialData.startData.time.hour, p_curr_addr); + pc.printf("%2d:%2d;%3d;%3d;%3d \r",initialData.startData.time.min, initialData.startData.time.sec, initialData.startData.data.light, initialData.startData.data.gndV, initialData.startData.data.temp); + pc.printf("%2d:%2d;%3d;%3d;%3d;%2d\r",initialData.myData.min, initialData.myData.sec, initialData.myData.data.light, initialData.myData.data.gndV, initialData.myData.data.temp); + p_curr_addr += 6; + + for (i=0; i<49; i++) { + memcpy((uint32_t*)&dataOut, p_curr_addr, 5*sizeof(uint32_t)); + pc.printf("%2d:%2d;%3d;%3d;%3d;%2d\r",dataOut[0].min, dataOut[0].sec, dataOut[0].data.light, dataOut[0].data.gndV, dataOut[0].data.temp, i); + pc.printf("%2d:%2d;%3d;%3d;%3d\r",dataOut[1].min, dataOut[1].sec, dataOut[1].data.light, dataOut[1].data.gndV, dataOut[1].data.temp); + p_curr_addr += 5; + } +} + +int update_measurements() +{ +int retVal; +static myPayload_t prevMeasures=(myPayload_t) {0, 0, 0, 0, 0 }; + + g_currMeasures = (myPayload_t) { + VP[0]->read_u16(), VP[2]->read_u16(), VP[1]->read_u16(), led, 0 + }; + retVal = memcmp(&g_currMeasures,&prevMeasures,sizeof(myPayload_t)); + memcpy(&prevMeasures,&g_currMeasures,sizeof(myPayload_t)); + return retVal; +} + +void at_eachInstant() +{ + static uint32_t tick=0; + int retVal; + // update time - if (g_myTimeVar.updateTime ==false){ - g_myTimeVar.newTime.sec = (g_myTimeVar.currentTime.sec + gTimeInstant)% 60; - g_myTimeVar.newTime.min = (g_myTimeVar.currentTime.min + ((gTimeInstant + g_myTimeVar.currentTime.sec) / 60))%60; - if (g_myTimeVar.newTime.min< g_myTimeVar.currentTime.min ) { - g_myTimeVar.currentTime.hour++; - } - g_myTimeVar.newTime.hour = (g_myTimeVar.currentTime.hour + (gTimeInstant / 3600+g_myTimeVar.newTime.min/60))%24; - if (g_myTimeVar.newTime.hour < g_myTimeVar.currentTime.hour){ - g_myDateVar.newDate.day = (g_myDateVar.currentDate.day + 1)%(eNrDaysPerMonth[g_myDateVar.currentDate.month]+1); - if (g_myDateVar.newDate.day < g_myDateVar.currentDate.day ){ - g_myDateVar.newDate.month = (g_myDateVar.currentDate.month+ 1)%13+1; - if (g_myDateVar.newDate.month< g_myDateVar.currentDate.month){ - g_myDateVar.newDate.year = (g_myDateVar.currentDate.year+ 1); + update_time(&g_myTimeVar, &g_myDateVar, gTimeInstant); + + //update measurements + retVal = update_measurements(); + + // if there are changes in data save + if ((retVal!=0)&&(g_LogActive==true)) { + write_data_to_flash(&tick); + } + tick++; +} + +// Radio commands decode +void decode(uint8_t * buffer, uint16_t length) +{ + uint16_t len; + char myBuf[TXRX_BUF_LEN]; + + switch (buffer[0]) { + case 'i': {// Analog Input Read Request + switch (buffer[1]) { + case '0': { + // display all inputs + sprintf(myBuf,"All:%3d,%3d,%3d,%2d", g_currMeasures.light,g_currMeasures.gndV,g_currMeasures.temp,g_currMeasures.led_on); + len = 18; + break; + } + case '1': { + sprintf(myBuf,"Input 1 = %3d", g_currMeasures.light); + len = 13; + break; + } + case '2': { + sprintf(myBuf,"Input 2 = %3d", g_currMeasures.gndV); + len = 13; + break; + } + case '3': { + sprintf(myBuf,"Input 3 = %3d", g_currMeasures.temp); + len = 13; + break; + } + case '4': { + sprintf(myBuf,"Input 4 = %2d", g_currMeasures.led_on); + len = 12; + break; + } + default: { + sprintf(myBuf,"All:%3d,%3d,%3d,%2d", g_currMeasures.light,g_currMeasures.gndV,g_currMeasures.temp,g_currMeasures.led_on); + len = 18; + break; } } - memcpy(&g_myDateVar.currentDate,&g_myDateVar.newDate, sizeof(date_t)); + sendRadioMsg((uint8_t *)myBuf, len); + break; + } + case 'l': {// toogle led + led = ! led; + if (led==0) { + sprintf(myBuf,"%s","ON"); + len = 2; + } else { + sprintf(myBuf,"%s","OFF"); + len = 3; + } + sendRadioMsg((uint8_t *)myBuf, len); + break; + } + case 's': {// buzzer + if (((buffer[1]>'9')||(buffer[1]<'0'))||((buffer[2]>'9')||(buffer[2]<'0'))){ + MyASSERT(true,&pc, buffer[1]); // notify on serial interface + on_error_radioMsg(); // notify on radio + break; + } else { + buzz_int(&buzzer, (buffer[1]-'0'),(buffer[2]-'0')); + sprintf(myBuf,"%s:%f","S",buzzer.read()); + len= 7; + } + sendRadioMsg((uint8_t *)myBuf, len); + break; + } + case 't': {// time operations + switch (buffer[1]) { + case 'i': {// time insert + memcpy(myBuf,&buffer[2],2); + g_myTimeVar.newTime.hour=atoi(myBuf); // TODO check if it is a number + memcpy(myBuf,&buffer[4],2); + g_myTimeVar.newTime.min=atoi(myBuf); // TODO check if it is a number + memcpy(myBuf,&buffer[6],2); + g_myTimeVar.newTime.sec=atoi(myBuf); // TODO check if it is a number + g_myTimeVar.updateTime = true; + sprintf(myBuf,"TimeInserted"); + len= 12; + sendRadioMsg((uint8_t *)myBuf, len); + break; + } + case 'g': {// time get + sprintf(myBuf,"H:%2d:%2d:%2d",g_myTimeVar.currentTime.hour,g_myTimeVar.currentTime.min,g_myTimeVar.currentTime.sec); + len = 11; + sendRadioMsg((uint8_t *)myBuf, len); + break; + } + default: + MyASSERT(true,&pc, buffer[1]); // notify on serial interface + on_error_radioMsg(); // notify on radio + } + break; } - memcpy(&g_myTimeVar.currentTime,&g_myTimeVar.newTime, sizeof(mtime_t)); - } else { - memcpy(&g_myTimeVar.currentTime,&g_myTimeVar.newTime, sizeof(mtime_t)); - g_myTimeVar.updateTime =false; + case 'd': {// date operations + switch (buffer[1]) { + case 'i': { // date insert + memcpy(myBuf,&buffer[2],2); + g_myDateVar.newDate.year=atoi(myBuf); // TODO check if it is a number + memcpy(myBuf,&buffer[4],2); + g_myDateVar.newDate.month=atoi(myBuf); // TODO check if it is a number + memcpy(myBuf,&buffer[6],2); + g_myDateVar.newDate.day=atoi(myBuf); // TODO check if it is a number + g_myDateVar.updateDate = true; + sprintf(myBuf,"DateInserted"); + len= 12; + sendRadioMsg((uint8_t *)myBuf, len); + break; + } + case 'g': { // time get + sprintf(myBuf,"D:20%2d:%2d:%2d",g_myDateVar.currentDate.year,g_myDateVar.currentDate.month,g_myDateVar.currentDate.day); + len = 13; + sendRadioMsg((uint8_t *)myBuf, len); + break; + } + default: + MyASSERT(true,&pc, buffer[1]); // notify on serial interface + on_error_radioMsg(); // notify on radio + } + break; + } + + case 'f': {// file operations + switch (buffer[1]) { + case '1': { + //pc.printf("S Payload_t: %d \r\n",sizeof(myPayload_t)); + //pc.printf("S myDataL_t: %d \r\n",sizeof(myDataL_t)); + + sprintf(myBuf,"g_idx=%2d Page=%3d",g_MyDataIdx, flash_currPage()); + len = 18; + sendRadioMsg((uint8_t *)myBuf, len); + break; + } + case '2':{// start measuring + sprintf(myBuf,"Start Meas"); + len = 12; + sendRadioMsg((uint8_t *)myBuf, len); + g_LogActive = true; + break; + } + case '3':{// stop measuring + sprintf(myBuf,"Stop Meas"); + len = 11; + sendRadioMsg((uint8_t *)myBuf, len); + g_LogActive = false; + break; + } + + default: { + // error + } + } + break; + } + default: { + MyASSERT(true,&pc, buffer[1]); // notify on serial interface + on_error_radioMsg(); // notify on radio; + } } - if (g_myDateVar.updateDate ==true){ // there is a new Date ? - memcpy(&g_myDateVar.currentDate,&g_myDateVar.newDate, sizeof(date_t)); - g_myDateVar.updateDate =true; - } - - // save some data - memcpy(&g_MyData[g_MyDataIdx].date,&g_myDateVar.currentDate, sizeof(date_t)); - memcpy(&g_MyData[g_MyDataIdx].time,&g_myTimeVar.currentTime, sizeof(mtime_t)); - g_MyData[g_MyDataIdx].light = readInput_f(3); - g_MyData[g_MyDataIdx].gndV = readInput_f(5); - g_MyData[g_MyDataIdx].temp = readInput_f(4); - g_MyData[g_MyDataIdx].led_on = led; - - /* - int i=0; - char buf[45]; - if (g_MyDataIdx==MAXBUFFER-1){ - // write2File - FILE *fp = fopen("out.txt","a+"); - for (i=0;i<MAXBUFFER;i++){ - sprintf(buf,"20%2d-%2d-%2d %2d:%2d:%2d %4.3f %4.3f %4.3f %2d \r\n",g_MyData[i].date.year, - g_MyData[i].date.month,g_MyData[i].date.day, g_MyData[i].time.hour, g_MyData[i].time.min, - g_MyData[i].time.sec, g_MyData[i].light, g_MyData[i].gndV, g_MyData[i].temp, g_MyData[i].led_on); - fwrite(buf,sizeof(uint8_t),strlen(buf),fp); - } - fclose(fp); - - }*/ - g_MyDataIdx = (g_MyDataIdx+1)%MAXBUFFER; } -/* -void at_periodicActions(){ - char myBuf[TXRX_BUF_LEN]; - int index=0, length; - float value[3]; - - value[0] = readInput_f(3); - value[1] = readInput_f(4); - sprintf(myBuf,">I3:%4.3f;I4:%4.3f",value[0],value[1]); - length =18; - memcpy(&infoCollector[0][index],&myBuf,length); - ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), &infoCollector[0][index], length); - wait(0.3); - - index ++; - value[2] = readInput_f(5); - sprintf(myBuf,">I5:%4.3f;",value[2]); - length= 10; - memcpy(&infoCollector[0][index],&myBuf,length); - ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), &infoCollector[0][index], length); - wait(0.3); - index ++; - length = 9; - if (led==0){ - sprintf(myBuf,"%s",">LED: ON"); - memcpy(&infoCollector[0][index],&myBuf,length); - } - else { - sprintf(myBuf,"%s",">LED:OFF"); - memcpy(&infoCollector[0][index],&myBuf,length); - } - ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), &infoCollector[0][index], length); - wait(0.3); -} -*/ -int decode(uint8_t * buffer, uint16_t* length){ - int retVal = 0; - char myBuf[TXRX_BUF_LEN+1]; - float value; +// decode serial command that starts with x +static void decode_s(uint8_t * buffer, uint16_t length) +{ + uint8_t page_nr; + char myBuf[5]; + uint32_t * p_curr_addr; - buffer[0]=buffer[3]; - buffer[1]=' '; - buffer[2]=':'; - switch (buffer[3]){ - case 'i': // Analog Input Read Request - buffer[1]=buffer[4]; - if (isInputValid(&buffer[3])){ - value = readInput_f((buffer[4]-'0')); - sprintf(myBuf,"%f",value); - memcpy(&buffer[3],&myBuf,7); // e.g. 3.12345 - *length= 7+3; - } - else { - retVal= -1; - } - break; - case 'l': // toogle led - led = ! led; - if (led==0){ - sprintf(myBuf,"%s","ON"); - memcpy(&buffer[3],&myBuf,2); - } - else { - sprintf(myBuf,"%s","OFF"); - memcpy(&buffer[3],&myBuf,3); - } - *length = 3 + 3; - break; - case 's': // buzzer - buffer[1]=buffer[4]; - if (isInputValid(&buffer[3])){ - buzz_int((buffer[4]-'0'),(buffer[5]-'0')); - buffer[2]=buffer[5]; - sprintf(myBuf,"%s:%f","S",buzzer.read()); - memcpy(&buffer[3],&myBuf,7); - *length= 7+3; - retVal= 1; - } - else { - retVal= -1; + switch (buffer[0]) { + case 'f': { // info about selected flash page + if ((buffer[1]<='9')&&(buffer[1]>='0')) { + memcpy(myBuf,&buffer[1],3); + page_nr= atoi(myBuf); + uint8_t p_word_count; + + pc.printf("buffer[1]: %c \r\n",buffer[1]); + + p_curr_addr= (uint32_t *)((uint16_t)BLE_FLASH_PAGE_SIZE * (flash_currPage() - page_nr)); + pc.printf("page_addr: %x, pgNr = %d \r\n",p_curr_addr,(flash_currPage() - page_nr)); + p_curr_addr += 1; + pc.printf("page_addr: %x \r\n",p_curr_addr); + p_word_count = (uint8_t)(*(p_curr_addr)); + pc.printf("nr_of_words: %d \r\n",p_word_count); + flash_page_serial_dump((p_curr_addr-1)); + } + break; + } + case 'd': { // full dump + uint16_t page0; + pc.printf("Full dump \r\n"); + + page0 = flash_currPage(); + for (page_nr=1; page_nr<=(MAX_PAGE_NUM-MIN_PAGE_NUM+1); page_nr++) { + if ((page0-page_nr)< MIN_PAGE_NUM){ + page0 = MAX_PAGE_NUM + page_nr; } - break; - case 't': // time operations - buffer[1]=buffer[4]; - retVal=1; - switch (buffer[1]){ - case 'i': // time insert - memcpy(myBuf,&buffer[5],2); - g_myTimeVar.newTime.hour=atoi(myBuf); // TODO check if it is a number - memcpy(myBuf,&buffer[7],2); - g_myTimeVar.newTime.min=atoi(myBuf); // TODO check if it is a number - memcpy(myBuf,&buffer[9],2); - g_myTimeVar.newTime.sec=atoi(myBuf); // TODO check if it is a number - g_myTimeVar.updateTime = true; - *length = 3+2; - break; - case 'g': // time get - sprintf(myBuf,"H:%2d:%2d:%2d",g_myTimeVar.currentTime.hour,g_myTimeVar.currentTime.min,g_myTimeVar.currentTime.sec); - memcpy(&buffer[3],myBuf,11); - *length = 3+11; - break; - default: - retVal = -1; //error + p_curr_addr= (uint32_t *)((uint16_t)BLE_FLASH_PAGE_SIZE * (page0-page_nr)); + flash_page_serial_dump(p_curr_addr); + } + break; + } + case 'g':{ + pc.printf("g_MyDataIdx= %d\r", g_MyDataIdx); + break; + } + case 'c': { + switch (buffer[1]){ + case 'a': { + connectionUpdate(eStartAdvertising); + break; + } + case 'c' : { + connectionUpdate(eDisconnect); + break; } - break; - case 'd': // date operations - buffer[1]=buffer[4]; - retVal=1; - switch (buffer[1]){ - case 'i': // date insert - memcpy(myBuf,&buffer[5],2); - g_myDateVar.newDate.year=atoi(myBuf); // TODO check if it is a number - memcpy(myBuf,&buffer[7],2); - g_myDateVar.newDate.month=atoi(myBuf); // TODO check if it is a number - memcpy(myBuf,&buffer[9],2); - g_myDateVar.newDate.day=atoi(myBuf); // TODO check if it is a number - g_myDateVar.updateDate = true; - *length = 3+2; - break; - case 'g': // time get - sprintf(myBuf,"D:20%2d:%2d:%2d",g_myDateVar.currentDate.year,g_myDateVar.currentDate.month,g_myDateVar.currentDate.day); - memcpy(&buffer[3],myBuf,13); - *length = 3+13; - break; - default: - retVal = -1; //error + case 's' : { + connectionUpdate(eStopAdvertising); + break; } - break; - default: - retVal = -1; + default: pc.printf("Not recognized cmd !\r"); + } + break; + } + default: { + // nothing } - if (retVal == -1){ - sprintf(myBuf,"%s","Incorect"); - memcpy(&buffer[3],&myBuf,8); - *length= 8+3; - buzz_int(5,3); - timeout_err.attach(&at_timeout_err, 2); - } - return retVal; + } } + void WrittenHandler(const GattWriteCallbackParams *Handler) -{ - uint8_t buf[TXRX_BUF_LEN+1]; - uint16_t bytesRead, index; - - if (Handler->handle == txCharacteristic.getValueAttribute().getHandle()) - { +{ + uint8_t buf[TXRX_BUF_LEN+1]= {'R',':',0}; + uint16_t bytesRead; + + if (Handler->handle == txCharacteristic.getValueAttribute().getHandle()) { ble.readCharacteristicValue(txCharacteristic.getValueAttribute().getHandle(), &buf[2], &bytesRead); memset(txPayload, 0, TXRX_BUF_LEN); - memcpy(txPayload, &buf[2], TXRX_BUF_LEN); - if (buf[2] == 'x'){ - decode(buf,&bytesRead); - } else { - //echo back - buf[0]='R'; - buf[1]=':'; - bytesRead+=2; - } - ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, bytesRead); + memcpy(txPayload, &buf[2], bytesRead); + if (txPayload[0] == 'x') { + decode(&txPayload[1],bytesRead); + } + //echo back + bytesRead+=2; + sendRadioMsg(buf, bytesRead); + // print on PC monitor - //pc.printf("WriteHandler \r\n"); - //pc.printf("Length: %d \r\n", bytesRead); - pc.printf("R: "); - for(index=0; index<bytesRead; index++) - { - pc.putc(txPayload[index]); - } - pc.printf("\r\n"); - + buf[bytesRead]='\r'; + //buf[bytesRead+1]='\n'; + pc.printf("%s",buf); } } void uartCB(void) -{ - while(pc.readable()) - { - rx_buf[rx_len++] = pc.getc(); - if(rx_len>=20 || rx_buf[rx_len-1]=='\0' || rx_buf[rx_len-1]=='\n') - { - ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), rx_buf, rx_len); - //pc.printf("Rec: Length: %d \r\n",rx_len); - rx_len = 2; - rx_buf[0]='S'; - rx_buf[1]=':'; +{ + while(pc.readable()) { + rx_buf[rx_len++] = pc.getc(); + if(rx_len>=20 || rx_buf[rx_len-1]=='\0' || rx_buf[rx_len-1]=='\n') { + ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), rx_buf, rx_len); + if ((rx_buf[0]=='x')) { + decode_s(&rx_buf[1],(rx_len-1)); // serial decode + } + rx_len= 0; break; } } } -void button(){ +void button() +{ uint8_t buf[TXRX_BUF_LEN+1]; buf[0]='B'; buf[1]=':'; buf[2]='O'; buf[3]='N'; - ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, 4); + ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, 4); } -void g_varInit(){ - g_myTimeVar.currentTime = (mtime_t){0,0,0}; +void g_varInit() +{ + g_myDateVar.updateDate = false; g_myTimeVar.updateTime = false; - g_myDateVar.currentDate =(date_t){3,10,16}; - g_myDateVar.updateDate = false; + /* retreive latest date, time and page flash available */ + search_latest_in_flash(&g_myDateVar.currentDate, &g_myTimeVar.currentTime ); } - int main(void) { ble.init(); + g_varInit(); ble.onDisconnection(disconnectionCallback); - ble.onDataWritten(WrittenHandler); + ble.onConnection(connectionCallback); + ble.onDataWritten(WrittenHandler); event.rise(&button); - periodicActions.attach(&at_eachInstant,gTimeInstant); // each second + pc.baud(19200); pc.printf("SimpleChat Init \r\n"); - g_varInit(); - + pc.attach( uartCB , pc.RxIrq); - // setup advertising + // setup advertising ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED); ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, - (const uint8_t *)"MyBleVT", sizeof("MyBleVT") - 1); + (const uint8_t *)"MyBleVT", sizeof("MyBleVT") - 1); ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, - (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid)); - //ble.accumulateAdvertisingPayload(GapAdvertisingData::TX_POWER_LEVEL,(const uint8_t *)txPower, sizeof(txPower)); - ble.setTxPower(txPower); - // 100ms; in multiples of 0.625ms. + (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid)); + //ble.accumulateAdvertisingPayload(GapAdvertisingData::TX_POWER_LEVEL,(const uint8_t *)txPower, sizeof(txPower)); + ble.setTxPower(txPower); + // 100ms; in multiples of 0.625ms. ble.setAdvertisingInterval(160); - + /* + // activate radio notifications - usefull for flashwrite + void (*ptrFunc)(bool); + ptrFunc = ble_flash_on_radio_active_evt; + //needed for flash write + //ble.onRadioNotification(ptrFunc); + */ ble.addService(uartService); - - ble.startAdvertising(); + ble.startAdvertising(); pc.printf("Advertising Start \r\n"); - - while(1) - { - ble.waitForEvent(); + periodicActions.attach(&at_eachInstant,gTimeInstant); + while(1) { + ble.waitForEvent(); } }