BLE Client UART function

Dependencies:   RingBuffer

This is a BLE Client (Central) program for nRF51.
You can communicate with mbed BLE using "BLE_Uart_Server" program as follows.
/users/kenjiArai/code/BLE_Uart_Server/
Please refer following my notebook.
/users/kenjiArai/notebook/ble-client-and-peripheral-using-switch-sience-ty51/#

Files at this revision

API Documentation at this revision

Comitter:
kenjiArai
Date:
Sun Oct 22 09:45:44 2017 +0000
Parent:
2:6fb0b87b041d
Child:
4:342b665fb826
Commit message:
Run on Mbed-os5. Extend pc serial buffer. Delete low power related lib.

Changed in this revision

BLE_API.lib Show diff for this revision Revisions of this file
RingBuffer.lib Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed-os.lib Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show diff for this revision Revisions of this file
nRF51822.lib Show diff for this revision Revisions of this file
nRF51_LowPwr.lib Show diff for this revision Revisions of this file
--- a/BLE_API.lib	Mon Jun 13 09:53:27 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-http://mbed.org/teams/Bluetooth-Low-Energy/code/BLE_API/#66159681aa21
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/RingBuffer.lib	Sun Oct 22 09:45:44 2017 +0000
@@ -0,0 +1,1 @@
+http://os.mbed.com/users/ykuroda/code/RingBuffer/#ea6d02ba96ae
--- a/main.cpp	Mon Jun 13 09:53:27 2016 +0000
+++ b/main.cpp	Sun Oct 22 09:45:44 2017 +0000
@@ -1,5 +1,6 @@
 /*
- *  ------- BLE Client UART function -------------------------------------
+ *  ------- BLE Central/Client UART function -----------------------------------
+ *          communicate with BLE_UART_Server program
  *      --- Tested on Switch Science mbed TY51822r3 ---
  *
  *  Modified by Kenji Arai
@@ -8,214 +9,123 @@
  *
  *      Started:  April     8th, 2016
  *      Revised:  June     13th, 2016
+ *      Revised:  October  22nd, 2017   Run on mbed-OS-5.6.2
  *
  *  Original program (see original.cpp file):
  *      S130 potential unstability case [closed] by Fabien Comte
- *      https://devzone.nordicsemi.com/question/49705/s130-potential-unstability-case/
+ *      https://devzone.nordicsemi.com/question/49705/
+ *                              s130-potential-unstability-case/
  *      GitHub Q&A by Fabien COMTE
  *      https://github.com/ARMmbed/ble/issues/69
  *  Tested Server Device:
  *      BLE_Uart_Server
  *      https://developer.mbed.org/users/kenjiArai/code/BLE_Uart_Server/
- *
  */
 
-//  Include ---------------------------------------------------------------------------------------
+//  Include --------------------------------------------------------------------
 #include "mbed.h"
 #include "BLE.h"
 #include "UARTService.h"
 #include "ble/DiscoveredCharacteristic.h"
 #include "ble/DiscoveredService.h"
-#include "nRF51_lowpwr.h"
+#include "RingBuffer.h"
 
-//  Definition ------------------------------------------------------------------------------------
-//  Before using this function, please specify your program are used following functions or not.
-#define    USE_DEVICE_STDIO_MESSAGES       0   // printf
-#define    USE_DEVICE_SERIAL               1   // Serial or DEBUG & etc.
-#define    USE_DEVICE_I2C                  0   // Sensors with I2C, LCD, EEPROM, Driver chips & etc.
-#define    USE_DEVICE_SPI                  0   // Sensors with SPI, LCD, EEPROM, Driver chips & etc.
-#define    USE_DEVICE_SPISLAVE             0   // Communication with master vis SPI
-#define    USE_DEVICE_PWMOUT               0   // PWM duty output, Serve & etc.
-#define    USE_DEVICE_ANALOGIN             0   // Analog adc
+//  Definition -----------------------------------------------------------------
+#define     NUM_ONCE                20
+#define     BFSIZE                  (NUM_ONCE+4)
 
-#if USE_DEVICE_STDIO_MESSAGES
-#define DEBUG(...)              { printf(__VA_ARGS__); }
+//#define    USE_DEBUG_MODE
+#ifdef USE_DEBUG_MODE
+#define DBG(...) { pc.printf(__VA_ARGS__); }
 #else
-#define DEBUG(...)
-#endif
-
-#if USE_DEVICE_SERIAL
-#define BAUD(x)                 pc.baud(x)
-#define GETC(x)                 pc.getc(x)
-#define PUTC(x)                 pc.putc(x)
-#define PRINTF(...)             { pc.printf(__VA_ARGS__); }
-#define READABLE(x)             pc.readable(x)
-#define ATTACH(x,y)             pc.attach(x, y);
-#else
-#define BAUD(x)
-#define GETC(x)                 'c'
-#define PUTC(x)
-#define PRINTF(...)
-#define READABLE(x)
-#define ATTACH(x,y)
+#define DBG(...)
 #endif
 
 #define SOFT_DEVICE_FATHER_HANDLE   3
-#define BOARDS_COUNT                3
 
-//  Object ----------------------------------------------------------------------------------------
-BLE          ble;
-DigitalOut   alivenessLED(LED1, 1);
-DigitalOut   connectedLED(D10, 0);
-DigitalIn    sw(D12, PullUp);
-InterruptIn  signal_sw(D12);         // duplicated!!
-Serial       pc(USBTX, USBRX);
-Ticker       ticker;
+//  Object ---------------------------------------------------------------------
+BLE         ble;
+DigitalOut  alivenessLED(LED1, 1);
+DigitalOut  connectedLED(D10, 0);
+Serial      pc(USBTX, USBRX, 115200);
+//Serial      pc(P0_3, P0_1, 115200);     // for another board
+Ticker      ticker;
+RingBuffer  ser_bf(1536);
+Thread      tsk;
 
-//  ROM / Constant data ---------------------------------------------------------------------------
+//  ROM / Constant data --------------------------------------------------------
 #warning "You need to modify below value based on your board."
-const Gap::Address_t    mac_board_0   = {0x59, 0x2c, 0xa8, 0x0e, 0xe2, 0xef};
-//const Gap::Address_t    mac_board_0   = {0x30, 0x74, 0x6d, 0xbd, 0x83, 0xf4};
-//const Gap::Address_t    mac_board_0   = {0xe4, 0x34, 0xbc, 0xb9, 0xc4, 0xf1};
-const Gap::Address_t    mac_board_1   = {0x50, 0x2b, 0xea, 0x14, 0x95, 0xd2};
+const Gap::Address_t    mac_board_0   = {0x50, 0x2b, 0xea, 0x14, 0x95, 0xd2};
+const Gap::Address_t    mac_board_1   = {0x59, 0x2c, 0xa8, 0x0e, 0xe2, 0xef};
 const Gap::Address_t    mac_board_2   = {0x0f, 0x72, 0xbf, 0x43, 0xbc, 0xd0};
-const Gap::Address_t    mac_board_3   = {0x83, 0xc9, 0x1a, 0x90, 0xdf, 0xd6}; // TY small with LiC
-const Gap::Address_t    mac_board_4   = {0x43, 0xa4, 0x36, 0x11, 0x5b, 0xeb}; // TY small
-//const Gap::Address_t    mac_board_4   = {0x98, 0x1a, 0x92, 0x10, 0x7f, 0xd5};
-#warning "You need to confirm your device name."
-const static char       DEVICE_NAME[] = "UART_C";
-static const uint16_t   uuid16_list[] = {UARTServiceShortUUID};
-const nRF51_LOWPWR_TypeDef  lowpwr_table = 
-                        {
-                        #if USE_DEVICE_STDIO_MESSAGES 
-                            true,
-                        #else
-                            false,
-                        #endif
-                        #if USE_DEVICE_SERIAL
-                            true,
-                        #else
-                            false,
-                        #endif
-                        #if USE_DEVICE_I2C
-                            true,
-                        #else
-                            false,
-                        #endif
-                        #if USE_DEVICE_SPI
-                            true,
-                        #else
-                            false,
-                        #endif
-                        #if USE_DEVICE_SPISLAVE
-                            true,
-                        #else
-                            false,
-                        #endif
-                        #if USE_DEVICE_PWMOUT
-                            true,
-                        #else
-                            false,
-                        #endif
-                        #if USE_DEVICE_ANALOGIN
-                            true
-                        #else
-                            false
-                        #endif
-                        };
+const Gap::Address_t    mac_board_3   = {0x83, 0xc9, 0x1a, 0x90, 0xdf, 0xd6};
+const Gap::Address_t    mac_board_4   = {0x43, 0xa4, 0x36, 0x11, 0x5b, 0xeb};
 
-//  RAM -------------------------------------------------------------------------------------------
-Gap::Handle_t   connectionHandle          = 0xFFFF;
+//  RAM ------------------------------------------------------------------------
+Gap::Handle_t   connectionHandle        = 0xFFFF;
 DiscoveredCharacteristic uartTXCharacteristic;
 DiscoveredCharacteristic uartRXCharacteristic;
 bool            foundUartRXCharacteristic = false;
-bool            connected2server          = false;
-bool            connection_1st            = false;
-bool            connection_tx             = false;
-bool            connection_rx             = false;
-UARTService *   uartServicePtr            = NULL;
+bool            connected2server        = false;
+bool            connection_tx           = false;
+bool            connection_rx           = false;
+UARTService *   uartServicePtr          = NULL;
 Gap::Address_t  my_mac;
-int             my_board_index            = -1;
-bool            recieved_uart_dat0        = false;
-int8_t          uart_buffer0[24];
-uint8_t         uart_bf0_len;
-bool            recieved_uart_dat1        = false;
-int8_t          uart_buffer1[24];
-uint8_t         uart_bf1_len;
-bool            line_input                = false;
-uint8_t         linebuf_irq[24];
-int             linebf_irq_len            = 0;
-uint8_t         linebuf[24];
-int             linebf_len                = 0;
+int             my_board_index          = -1;
+bool            received_uart_dat       = false;
+int8_t          uart_buffer[BFSIZE];
+uint8_t         uart_bf_len;
+volatile bool   rx_isr_busy             = false;
 
-//  Function prototypes ---------------------------------------------------------------------------
+//  Function prototypes --------------------------------------------------------
 //      BLE
-void onReceivedDataFromCentralCallback(const GattWriteCallbackParams *params);
-void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params);
-void serviceDiscoveryCallback(const DiscoveredService *service);
-void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP);
-void discoveryTerminationCallback(Gap::Handle_t connectionHandle);
-void onReceivedDataFromDeviceCallback(const GattHVXCallbackParams *params);
-void connectionCallback(const Gap::ConnectionCallbackParams_t *params);
-void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params);
+void advertisementCallback(const Gap::AdvertisementCallbackParams_t *);
+void serviceDiscoveryCallback(const DiscoveredService *);
+void characteristicDiscoveryCallback(const DiscoveredCharacteristic *);
+void discoveryTerminationCallback(Gap::Handle_t );
+void onReceivedDataFromDeviceCallback(const GattHVXCallbackParams *);
+void connectionCallback(const Gap::ConnectionCallbackParams_t *);
+void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *);
 //      Interrupt related
 void periodicCallback(void);
 void serialRxCallback(void);
+//      serial receiving
+void pc_ser_rx(void);
+void preparation_sending_data(void);
 //      Pre-check
-bool mac_equals(const Gap::Address_t mac_1, const Gap::Address_t mac_2);
-int  get_board_index(const Gap::Address_t mac);
-void adjust_line(uint8_t *bf);
+bool mac_equals(const Gap::Address_t, const Gap::Address_t);
+int  get_board_index(const Gap::Address_t);
+void adjust_line(uint8_t *);
 
-//-------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 //  Control Program
-//-------------------------------------------------------------------------------------------------
-int main(void){
-    LowPwr set_lowpwr(&lowpwr_table);
+//------------------------------------------------------------------------------
+int main(void)
+{
     alivenessLED = 0;
-    ATTACH(&serialRxCallback, Serial::RxIrq);
+    pc.attach(&serialRxCallback, Serial::RxIrq);
     ticker.attach(periodicCallback, 1);
-    for (int k = 0; k < 20; k++) { PRINTF("\r\n");}          // clear terminal output
-    PRINTF("UART Communication / Client side\r\n");          // opening message
-    PRINTF("  Client(Central) and Server(Peripheral)\r\n");  // opening message
-    // Mixed role *************************************************************
+    tsk.start(pc_ser_rx);
+    // clear terminal output
+    for (int k = 0; k < 5; k++) { pc.printf("\r\n");}
+    // opening message
+    pc.printf("UART Communication / Client(Central) side\r\n");
+    pc.printf("  need Sever module (run BLE_Uart_Sever program)\r\n"); 
+    // Mixed role **************************************************************
     ble.init();
-    Gap::AddressType_t my_mac_type;
-    ble.gap().getAddress(&my_mac_type, my_mac);
-    my_board_index = get_board_index(my_mac);
-    DEBUG(
-        "me %02x:%02x:%02x:%02x:%02x:%02x (%s)\r\n",
-        my_mac[5], my_mac[4], my_mac[3], my_mac[2], my_mac[1], my_mac[0],
-        (my_mac_type == Gap::ADDR_TYPE_PUBLIC) ? "public" : "random"
-    );
     ble.gap().onConnection(connectionCallback);
     ble.gap().onDisconnection(disconnectionCallback);
-    // Server(Peripheral) role ************************************************
-    ble.gattServer().onDataWritten(onReceivedDataFromCentralCallback);
-    UARTService uartService(ble);
-    uartServicePtr = &uartService;
-    // setup advertising
-    ble.accumulateAdvertisingPayload(
-        GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE
-    );
-    ble.accumulateAdvertisingPayload(
-        GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME)
-    );
-    ble.accumulateAdvertisingPayload(
-        GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS,
-        (uint8_t *)uuid16_list,
-        sizeof(uuid16_list)
-    ); // UUID's broadcast in advertising packet (set advertising type)
-    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
-    ble.setAdvertisingInterval(100);
-    // Client(Central) role ***************************************************
+    // Client(Central) role ****************************************************
     ble.gattClient().onHVX(onReceivedDataFromDeviceCallback);
     ble.gap().setScanParams(500, 450);
-    ble.startAdvertising();                     // start advertising and scan
     ble.gap().startScan(advertisementCallback);
     while(true) {
         // allow notifications from Server(Peripheral)
-        if (foundUartRXCharacteristic && !ble.gattClient().isServiceDiscoveryActive()){
-            foundUartRXCharacteristic = false; // need to do the following only once
+        if (foundUartRXCharacteristic &&
+            !ble.gattClient().isServiceDiscoveryActive())
+        {
+            // need to do the following only once
+            foundUartRXCharacteristic = false;
             uint16_t value = BLE_HVX_NOTIFICATION;
             ble.gattClient().write(
                 GattClient::GATT_OP_WRITE_REQ,
@@ -225,118 +135,109 @@
                 reinterpret_cast<const uint8_t *>(&value)
             );
         }
-        if (recieved_uart_dat0 == true){
-            recieved_uart_dat0 = false;
-            for(int i = 0; i < uart_bf0_len; i++){
-                PRINTF("%c", uart_buffer0[i]);
-            }
-            PRINTF("\r\n");
-        }
-        if (recieved_uart_dat1 == true){
-            recieved_uart_dat1 = false;
-            for(int i = 0; i < uart_bf1_len; i++){
-                PRINTF("%c", uart_buffer1[i]);
-            }
-            PRINTF("\r\n");
-        }
-        if (line_input == true){
-            line_input = false;
-            // Client to Server(central to peripheral)
-            adjust_line(linebuf);
-            int ret = uartTXCharacteristic.write(20, linebuf);
-            if (ret == BLE_ERROR_NONE){
-                DEBUG("\r\ndone (c2p)\r\n");
-            } else if (ret == BLE_STACK_BUSY){
-                DEBUG("\r\nbusy (c2p)\r\n");
-            } else if (ret == BLE_ERROR_OPERATION_NOT_PERMITTED) {
-                DEBUG("\r\nnot connected (c2d)\r\n");
-            } else  {
-                DEBUG("\r\ncode %d (c2d)\r\n", ret);
-            }
-            // Server to Client(peripheral to central)
-            if (ble.gap().getState().connected){
-                int ret = ble.gattServer().write(
-                    uartServicePtr->getRXCharacteristicHandle(),
-                    linebuf,
-                    linebf_len
-                );
-                if (ret == BLE_ERROR_NONE){
-                    DEBUG("\r\ndone (p2c)\r\n");
-                }  else if (ret == BLE_STACK_BUSY){
-                    DEBUG("\r\nbusy (p2c)\r\n");
-                }  else if (ret == BLE_ERROR_OPERATION_NOT_PERMITTED){
-                    DEBUG("\r\nnot connected (p2c)\r\n");
-                }  else {
-                    DEBUG("\r\ncode %d (p2c)\r\n", ret);
-                }
+        if (received_uart_dat == true){
+            received_uart_dat = false;
+            for(int i = 0; i < uart_bf_len; i++){
+                //pc.printf("%c", uart_buffer[i]);
+                pc.putc(uart_buffer[i]);
             }
         }
-        if ((connection_tx == true) && (connection_rx == true) && (connection_1st == false)){
-            PRINTF("Send *? Command\r\n");
-            connection_1st = true;
-            wait(3.0);
-            // Client to Server(central to peripheral)
-            //                 12345678901234567890
-            const uint8_t *msg = "*?                  ";
-            uartTXCharacteristic.write(20, msg);
-        }
-        ble.waitForEvent(); // save power
+        ble.waitForEvent();
+    }
+}
+
+void periodicCallback(void)
+{
+    // Do blinky on alivenessLED to indicate system aliveness
+    alivenessLED = !alivenessLED; 
+    if (connected2server){
+        connectedLED = 1;
+    } else {
+        connectedLED = 0;
+    }
+    if (rx_isr_busy == true){
+        rx_isr_busy = false;
+    } else {
+        tsk.signal_set(0x01);
     }
 }
 
-void serialRxCallback(){
-    char c = GETC();
-    if (c == '\r') {
-        linebuf_irq[linebf_irq_len++] = c;
-        PRINTF("\r\n");
-        linebf_len = linebf_irq_len;
-        strcpy((char *)linebuf, (char *)linebuf_irq);
-        linebf_irq_len = 0;
-        line_input = true;
-    } else if ((c == '\b') && linebf_irq_len) {
-        linebf_irq_len--;
-        PUTC(c);
-        PUTC(' ');
-        PUTC(c);
-    } else if (((uint8_t)c >= ' ') && (linebf_irq_len < 20)) {
-        linebuf_irq[linebf_irq_len++] = c;
-        PUTC(c);
-    } else if ( c == 0x1f ){    // Control+?
-        NVIC_SystemReset();     // Reset
-    }
-    linebuf_irq[linebf_irq_len] = 0; 
+void serialRxCallback()
+{
+    ser_bf.save(pc.getc());
+    rx_isr_busy = true;
+    tsk.signal_set(0x01);
 }
 
-void adjust_line(uint8_t *bf){
-uint8_t i, c;
+void pc_ser_rx()
+{
+    static uint8_t linebf_irq[BFSIZE];
+    static volatile uint8_t linebf_irq_len = 0;
 
-    for (i = 0; i <20; bf++, i++){
-        c = *bf;
-        if ( (c == '\r') || (c == '\n') || (c == 0)){
-            break;
+    while(true){
+        Thread::signal_wait(0x01);
+        if (ser_bf.check() == 0){
+            if (linebf_irq_len != 0){
+                linebf_irq[linebf_irq_len] = 0;
+                adjust_line(linebf_irq);
+                linebf_irq_len = 0;
+                uartTXCharacteristic.write(NUM_ONCE, linebf_irq);
+            }
         }
-    }
-    for (; i < 20; bf++, i++){
-        *bf = ' ';
-    }
-    *(bf + 1) = 0;
-}
-
-// Server(Peripheral) role ****************************************************
-void onReceivedDataFromCentralCallback(const GattWriteCallbackParams *params){
-    if (uartServicePtr != NULL){
-        if ((params->handle ==
-                uartServicePtr->getTXCharacteristicHandle()) && (params->len >= 1))
-        {
-            uart_bf0_len = params->len;
-            strcpy((char *)uart_buffer0, (char *)params->data);
-            recieved_uart_dat0 = true;
+        while(ser_bf.check() != 0){
+            char c = ser_bf.read();
+            if (c == '\b'){
+                linebf_irq_len--;
+                pc.putc(c);
+                pc.putc(' ');
+                pc.putc(c);
+            } else if ((c >= ' ') || (c == '\r') || (c == '\n')){
+                bool overflow = false;
+                if ((c == '\r') || (c == '\n')) {
+                    if (linebf_irq_len == NUM_ONCE - 1){// remain only 1 buffer
+                        overflow = true;
+                        linebf_irq[linebf_irq_len++] = '\r';
+                        pc.putc('\r');
+                    } else {
+                        overflow = false;
+                        linebf_irq[linebf_irq_len++] = '\r';
+                        linebf_irq[linebf_irq_len++] = '\n';
+                        pc.printf("\r\n");
+                    }
+                } else {
+                    linebf_irq[linebf_irq_len++] = c;
+                    pc.putc(c);
+                }
+                if (linebf_irq_len >= NUM_ONCE ){
+                    linebf_irq[linebf_irq_len] = 0;
+                    uartTXCharacteristic.write(linebf_irq_len, linebf_irq);
+                    linebf_irq_len = 0;
+                    if (overflow == true){
+                        overflow = false;
+                        linebf_irq[linebf_irq_len++] = '\n';
+                        pc.putc('\n');
+                    }
+                }
+            }
         }
     }
 }
 
-void onReceivedDataFromDeviceCallback(const GattHVXCallbackParams *params){
-    DEBUG(
+void adjust_line(uint8_t *bf)
+{
+    uint8_t i, c;
+
+    for (i = 0; i <NUM_ONCE; bf++, i++){
+        c = *bf;
+        if (c == 0){ break;}
+    }
+    for (; i < NUM_ONCE; bf++, i++){ *bf = 0x11;}
+    *(bf + 1) = 0;
+}
+
+void onReceivedDataFromDeviceCallback(const GattHVXCallbackParams *params)
+{
+    DBG(
         "received HVX callback for handle %u; type %s\r\r\n",
         params->handle,
         (params->type == BLE_HVX_NOTIFICATION) ? "notification" : "indication"
@@ -345,88 +246,87 @@
         if ((params->handle
                 == uartRXCharacteristic.getValueHandle()) && (params->len > 0))
         {
-            uart_bf1_len = params->len;
-            strcpy((char *)uart_buffer1, (char *)params->data);
-            recieved_uart_dat1 = true;
+            uart_bf_len = params->len;
+            strcpy((char *)uart_buffer, (char *)params->data);
+            received_uart_dat = true;
          }
     }
 }
 
-void periodicCallback(void){
-    alivenessLED = !alivenessLED; // Do blinky on alivenessLED to indicate system aliveness
-    if (connected2server){
-        connectedLED = 1;
-    } else {
-        connectedLED = 0;
+bool mac_equals(const Gap::Address_t mac_1, const Gap::Address_t mac_2)
+{
+    DBG("Address: ");
+    for (int i = 0; i < 6; i++){
+        DBG("0x%02x ", mac_1[i]);
     }
-}
-
-bool mac_equals(const Gap::Address_t mac_1, const Gap::Address_t mac_2){
-    DEBUG("Address: ");
-    for (int i = 0; i < 6; i++){
-        DEBUG("0x%02x ", mac_1[i]);
-    }
-    DEBUG("\r\n");
+    DBG("\r\n");
     for (int i = 0; i < 6; i++){
         if (mac_1[i] != mac_2[i]){
-            DEBUG("0x%02x != 0x%02x at %d\r\n", mac_1[i], mac_2[i], i);
+            DBG("0x%02x != 0x%02x at %d\r\n", mac_1[i], mac_2[i], i);
             return false;
         } else {
-            DEBUG("0x%02x == 0x%02x at %d\r\n", mac_1[i], mac_2[i], i);
+            DBG("0x%02x == 0x%02x at %d\r\n", mac_1[i], mac_2[i], i);
         }
     }
     return true;
 }
 
-int get_board_index(const Gap::Address_t mac){
-    if (mac_equals(mac, mac_board_0)) {     return 0;}
-    if (mac_equals(mac, mac_board_1)) {     return 1;}
-    if (mac_equals(mac, mac_board_2)) {     return 2;}
-    if (mac_equals(mac, mac_board_3)) {     return 3;}
-    if (mac_equals(mac, mac_board_4)) {     return 4;}
+int get_board_index(const Gap::Address_t mac)
+{
+    if (mac_equals(mac, mac_board_0)) { return 0;}
+    if (mac_equals(mac, mac_board_1)) { return 1;}
+    if (mac_equals(mac, mac_board_2)) { return 2;}
+    if (mac_equals(mac, mac_board_3)) { return 3;}
+    if (mac_equals(mac, mac_board_4)) { return 4;}
     return -1;
 }
 
-// Client(Central) role *******************************************************
-void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params){
+// Client(Central) role ********************************************************
+void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params)
+{
     // connections
     int peer_board_index = get_board_index(params->peerAddr);
     if (peer_board_index != -1){
-        PRINTF("adv peerAddr");
-        PRINTF(
-            "[%02x %02x %02x %02x %02x %02x] rssi %+4d, isScanResponse %u, AdvertisementType %u",
+        pc.printf("");
+        pc.printf(
+            "adv peerAddr [%02x %02x %02x %02x %02x %02x]\r\n",
             params->peerAddr[5], params->peerAddr[4], params->peerAddr[3],
-            params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],
-            params->rssi,
-            params->isScanResponse,
-            params->type
+            params->peerAddr[2], params->peerAddr[1], params->peerAddr[0] 
         );
-        PRINTF("\r\n");
-        ble.gap().connect(params->peerAddr, Gap::ADDR_TYPE_RANDOM_STATIC, NULL, NULL);
+        pc.printf(
+            "rssi=%+4d, isScanResponse %u, AdvertisementType %u\r\n",
+            params->rssi, params->isScanResponse, params->type
+        );
+        ble.gap().connect(
+            params->peerAddr, Gap::ADDR_TYPE_RANDOM_STATIC, NULL, NULL);
     }
 }
 
-void serviceDiscoveryCallback(const DiscoveredService *service) {
-    DEBUG("service found...\r\n");
-    if (service->getUUID().shortOrLong() == UUID::UUID_TYPE_SHORT) {
-        DEBUG(
+void serviceDiscoveryCallback(const DiscoveredService *service)
+{
+    DBG("service found...\r\n");
+    if (service->getUUID().shortOrLong() == UUID::UUID_TYPE_SHORT){
+        DBG(
             "Service UUID-%x attrs[%u %u]\r\n",
             service->getUUID().getShortUUID(),
             service->getStartHandle(),
             service->getEndHandle()
         );
     } else {
-        DEBUG("Service UUID-");
+        DBG("Service UUID-");
         const uint8_t *longUUIDBytes = service->getUUID().getBaseUUID();
         for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
-            DEBUG("%02x", longUUIDBytes[i]);
+            DBG("%02x", longUUIDBytes[i]);
         }
-        DEBUG(" attrs[%u %u]\r\n", service->getStartHandle(), service->getEndHandle());
+        DBG(" attrs[%u %u]\r\n",
+                service->getStartHandle(), service->getEndHandle());
     }
 }
 
-void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP){
-    DEBUG(
+void characteristicDiscoveryCallback(
+    const DiscoveredCharacteristic *characteristicP)
+{
+    DBG(
         " C UUID-%x valueAttr[%u] props[%x]\r\n",
         characteristicP->getUUID().getShortUUID(),
         characteristicP->getValueHandle(),
@@ -435,70 +335,58 @@
     if (characteristicP->getUUID().getShortUUID()
                 == UARTServiceTXCharacteristicShortUUID)
     {
-        PRINTF("Sevice TX 0x%04x\r\n", UARTServiceTXCharacteristicShortUUID);
+        DBG("Sevice TX 0x%04x\r\n", UARTServiceTXCharacteristicShortUUID);
         uartTXCharacteristic = *characteristicP;
         connection_tx = true;
     } else if (characteristicP->getUUID().getShortUUID()
                 == UARTServiceRXCharacteristicShortUUID)
     {
-        PRINTF("Sevice RX 0x%04x\r\n", UARTServiceRXCharacteristicShortUUID);
+        DBG("Sevice RX 0x%04x\r\n", UARTServiceRXCharacteristicShortUUID);
         uartRXCharacteristic = *characteristicP;
         foundUartRXCharacteristic = true;
         connection_rx = true;
     }
 }
 
-void discoveryTerminationCallback(Gap::Handle_t connectionHandle){
-    DEBUG("terminated SD for handle=%u\r\n", connectionHandle);
+void discoveryTerminationCallback(Gap::Handle_t connectionHandle)
+{
+    DBG("terminated SD for handle=%u\r\n", connectionHandle);
 }
 
-// Mixed role *****************************************************************
-void connectionCallback(const Gap::ConnectionCallbackParams_t *params){
+// Mixed role ******************************************************************
+void connectionCallback(const Gap::ConnectionCallbackParams_t *params)
+{
     if (params->role == Gap::CENTRAL) {
-        DEBUG("connected as Client(central) (handle = %d)\r\n\r", params->handle);
+        pc.printf("connected as Client(Central) (handle = %d)\r\n\r",
+                    params->handle);
         connected2server = true;
         connectionHandle = params->handle;
-        ble.gattClient().onServiceDiscoveryTermination(discoveryTerminationCallback);
+        ble.gattClient().onServiceDiscoveryTermination(
+                discoveryTerminationCallback);
         ble.gattClient().launchServiceDiscovery(
                 params->handle,
                 serviceDiscoveryCallback,
-                characteristicDiscoveryCallback/*,
-                0xa000, 0xa001*/
-        );
-    } else {
-        DEBUG("connected as Server (handle = %d)\r\n\r", params->handle);
-        DEBUG(
-            "Conn. params => min=%d, max=%d, slave=%d, supervision=%d\r\n",
-            params->connectionParams->minConnectionInterval,
-            params->connectionParams->maxConnectionInterval,
-            params->connectionParams->slaveLatency,
-            params->connectionParams->connectionSupervisionTimeout
+                characteristicDiscoveryCallback
         );
-        Gap::ConnectionParams_t connectionParams;
-        connectionParams.minConnectionInterval        = 6;
-        connectionParams.maxConnectionInterval        = 12;
-        connectionParams.slaveLatency                 = 0;
-        connectionParams.connectionSupervisionTimeout = 500;
-        if (ble.updateConnectionParams(params->handle, &connectionParams) != BLE_ERROR_NONE){
-            DEBUG("failed to update connection parameter\r\n");
-        }
     }
-    DEBUG(
-        "own %02x:%02x:%02x:%02x:%02x:%02x (%s), peer %02x:%02x:%02x:%02x:%02x:%02x (%s)\r\n",
+    pc.printf(
+        "Client(Central/Myself)      %02x:%02x:%02x:%02x:%02x:%02x\r\n",
         params->ownAddr[5], params->ownAddr[4], params->ownAddr[3],
-        params->ownAddr[2], params->ownAddr[1], params->ownAddr[0],
-        (params->ownAddrType == Gap::ADDR_TYPE_PUBLIC) ? "public" : "random",
+        params->ownAddr[2], params->ownAddr[1], params->ownAddr[0]
+    );
+    pc.printf(
+        "Connected Sever(peripheral) %02x:%02x:%02x:%02x:%02x:%02x\r\n",
         params->peerAddr[5], params->peerAddr[4], params->peerAddr[3],
-        params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],
-        (params->peerAddrType == Gap::ADDR_TYPE_PUBLIC) ? "public" : "random"
+        params->peerAddr[2], params->peerAddr[1], params->peerAddr[0]
     );
 }
 
-void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params){
-    DEBUG("handle = %d ", params->handle);
-    PRINTF(" -> disconnected\r\n", params->handle);
+void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
+{
+    DBG("handle = %d ", params->handle);
+    pc.printf(" -> disconnected\r\n", params->handle);
     connected2server = false;
-    connection_1st = false;
+//    connection_1st = false;
     connection_tx = false;
     connection_rx = false;
     if (params->handle == SOFT_DEVICE_FATHER_HANDLE) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-os.lib	Sun Oct 22 09:45:44 2017 +0000
@@ -0,0 +1,1 @@
+https://github.com/ARMmbed/mbed-os/#6e0d01cd13e8aca7bf4d697c3699ec9225386881
--- a/mbed.bld	Mon Jun 13 09:53:27 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-http://mbed.org/users/mbed_official/code/mbed/builds/6c34061e7c34
\ No newline at end of file
--- a/nRF51822.lib	Mon Jun 13 09:53:27 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-http://mbed.org/teams/Nordic-Semiconductor/code/nRF51822/#f7faad332abc
--- a/nRF51_LowPwr.lib	Mon Jun 13 09:53:27 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-http://mbed.org/users/kenjiArai/code/nRF51_LowPwr/#ffd5168de563