BLE_SecureUART

Dependencies:   nRF51BLE_API mbed nRF51822

Fork of BLE_UARTConsole by Bluetooth Low Energy

Revision:
10:965f3a55bc89
Parent:
9:5f0732aa3008
--- a/main.cpp	Tue Sep 29 12:12:10 2015 +0000
+++ b/main.cpp	Tue May 31 09:19:36 2016 +0000
@@ -17,10 +17,12 @@
 #include <string.h>
 #include "mbed.h"
 #include "BLE.h"
+#include <string>
+using namespace std;
 
 #include "UARTService.h"
 
-#define NEED_CONSOLE_OUTPUT 1 /* Set this if you need debug messages on the console;
+#define NEED_CONSOLE_OUTPUT 0 /* Set this if you need debug messages on the console;
                                * it will have an impact on code-size and power consumption. */
 
 #if NEED_CONSOLE_OUTPUT
@@ -29,47 +31,189 @@
 #define DEBUG(...) /* nothing */
 #endif /* #if NEED_CONSOLE_OUTPUT */
 
+/*============ settting ================*/
+#define start  "1.Auto 2.Manual ?\r\n"
+bool mode = false;
+bool Auto = false;
+
 BLEDevice  ble;
 DigitalOut led1(LED1);
-UARTService *uart;
+UARTService *uartServicePtr;
+Serial dev(TX_PIN_NUMBER, RX_PIN_NUMBER);
+DigitalIn sensor(P0_12);
+char rxbuff;
+int i = 0;
+
+
+void connectionCallback(const Gap::ConnectionCallbackParams_t *params)
+{
+    printf("Connected!\r\n");
+}
 
 void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
 {
-    DEBUG("Disconnected!\n\r");
-    DEBUG("Restarting the advertising process\n\r");
+    printf("Disconnected!\r\n");
+    printf("Restarting the advertising process\r\n");
     ble.startAdvertising();
 }
 
+void passkeyDisplayCallback(Gap::Handle_t handle, const SecurityManager::Passkey_t passkey)
+{
+    printf("Input passKey: ");
+    for (unsigned i = 0; i < Gap::ADDR_LEN; i++) {
+        printf("%c ", passkey[i]);
+    }
+    printf("\r\n");
+}
+
+void securitySetupCompletedCallback(Gap::Handle_t handle, SecurityManager::SecurityCompletionStatus_t status)
+{
+    if (status == SecurityManager::SEC_STATUS_SUCCESS) {
+        printf("Security success\r\n");
+    } else {
+        printf("Security failed\r\n");
+    }
+}
+
+void linkSecureCallback(Gap::Handle_t handle, SecurityManager::SecurityMode_t securityMode)
+{
+    printf("LinkStatus: ");
+    switch(securityMode){
+        case SecurityManager::SECURITY_MODE_NO_ACCESS:
+            printf("NO_ACCESS\r\n");
+            break;
+        case SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK:
+            printf("OPEN_LINK\r\n");
+            break;
+        case SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM:
+            printf("ENCRYPTION_NO_MITM\r\n");
+            break;
+        case SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM:
+            printf("ENCRYPTION_WITH_MITM\r\n");
+            break;
+        case SecurityManager::SECURITY_MODE_SIGNED_NO_MITM:
+            printf("SIGNED_NO_MITM\r\n");
+            break;
+        case SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM:
+            printf("SIGNED_WITH_MITM\r\n");
+            break;
+        default :
+            printf("OPEN_LINK\r\n");
+            break;
+    }
+}
+
+void onDataWritten(const GattWriteCallbackParams *params)
+{
+    if ((uartServicePtr != NULL) && (params->handle == uartServicePtr->getTXCharacteristicHandle())) {
+        uint16_t bytesRead = params->len;
+        DEBUG("received %u bytes\n\r", bytesRead);
+        
+        printf("nrfRecv : ");
+        for (unsigned index = 0; index < bytesRead; index++) {
+            printf("%c", params->data[index]);
+        }
+        printf("\r\n");
+        
+        switch(*params->data) {
+            case '1':
+                Auto = false;
+                mode = true;
+                printf("-----Manual-----\r\n");
+                //ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), params->data, bytesRead);
+                ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), (uint8_t*)&rxbuff, 1);
+                printf("nrfSend : %c\r\n", rxbuff);
+                i++;
+                break;
+            case '2':
+                Auto = true;
+                mode = true;
+                printf("----- Auto -----\r\n");
+                break;
+            default:    
+                Auto = false;
+                mode = false;
+                break;
+        }    
+        /*
+        printf("received %u bytes \r\n", bytesRead);
+        for (unsigned index = 0; index < bytesRead; index++) {
+            printf("%c[%02x]", a[index], a[index]);
+        }
+        printf("\r\n");
+        */
+    }
+}
+
 void periodicCallback(void)
 {
-    led1 = !led1;
+    //led1 = !led1;
     DEBUG("ping\r\n");
+    int x = sensor.read();
+    
+    led1 = (Auto)? 0 : 1;    
+    
+    if(Auto && mode){
+        ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), (uint8_t*)&rxbuff, 1);
+        printf("nrfSend : %c\r\n", rxbuff);
+    }
+}
+
+void onCreate(void)
+{
+    while(uartServicePtr == NULL){}
+    ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), (uint8_t*)start, strlen((char *) start));
+   
+}
+
+void serial_rx ()
+{
+    rxbuff = dev.getc();
+    printf("Recv : %c\r\n", rxbuff);
+    
 }
 
 int main(void)
 {
-    led1 = 1;
+    led1 = 1;       // 共陽極
     Ticker ticker;
     ticker.attach(periodicCallback, 1);
+    dev.baud(9600);
+    dev.attach(&serial_rx,Serial::RxIrq);
 
-    DEBUG("Initialising the nRF51822\n\r");
+    printf("Initialising\r\n");
     ble.init();
-    ble.onDisconnection(disconnectionCallback);
+    
+    /* Initialize BLE security */
+    bool enableBonding = true;
+    bool requireMITM   = true;
+    ble.securityManager().init(enableBonding, requireMITM, SecurityManager::IO_CAPS_DISPLAY_ONLY);
+    ble.securityManager().purgeAllBondingState();
     
-    uart = new UARTService(ble);
+    /* Set callback functions */
+    ble.gap().onConnection(connectionCallback);
+    ble.gap().onDisconnection(disconnectionCallback);
+    ble.securityManager().onPasskeyDisplay(passkeyDisplayCallback);
+    ble.securityManager().onSecuritySetupCompleted(securitySetupCompletedCallback);
+    ble.securityManager().onLinkSecured(linkSecureCallback);
+    ble.onDataWritten(onDataWritten);
 
     /* setup advertising */
     ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
     ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
     ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
-                                     (const uint8_t *)"BLE UART", sizeof("BLE UART") - 1);
+                                     (const uint8_t *)"M10307431", sizeof("M10307431") - 1);
     ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
                                      (const uint8_t *)UARTServiceUUID_reversed, sizeof(UARTServiceUUID_reversed));
-
     ble.setAdvertisingInterval(160); /* 100ms; in multiples of 0.625ms. */
     ble.startAdvertising();
+    
+    UARTService uart(ble);
+    uartServicePtr = &uart;
+    onCreate();
+    
+    while (true) {
 
-    while (true) {
         ble.waitForEvent();
     }
 }