Ble Demo with Raspberry PI updated

Dependencies:   BLE_API mbed nRF51822

Fork of BLE_DEMO_SPI by HM_IOT_Demo

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /************************************************************************
00002 *                                                                       *
00003 *                                                                       *
00004 ************************************************************************/
00005 #include "mbed.h"
00006 #include "hm_config.h"
00007 
00008 DiscoveredCharacteristic lightCharacteristic;
00009 //Gap::Handle_t connectionHandle = 0xFFFF;
00010 //static s_serviceInfo lightChar = {NULL,NULL};
00011 Serial pc(USBTX, USBRX);
00012 void bleint();
00013 void waitBleEvent();
00014 void ble_actions(int spi_data);
00015 
00016 uint8_t statusWR;
00017 uint8_t read_buffer[128];
00018 uint8_t nDiscoveredDevice = 0;
00019 static int receiveBufSize = 0;
00020 bool scanFlag = false;
00021 bool response_flag = false;
00022 bool first_connection = true;
00023 
00024 SPISlave spiSlave(P0_9, P0_11, P0_8, P0_10);
00025 lightCharacteristic_t ptr_temp_char;
00026 
00027 
00028 void read_Characteristics();
00029 void AddMacAddress(const uint8_t *u8MacAddress);
00030 void scanThread();
00031 void connectDevices(int device_type);
00032 //DiscoveredCharacteristic ptr_temp_char;
00033 
00034 bool connection_handle = 0;
00035 
00036 void AddMacAddress(const uint8_t *u8MacAddress)
00037 {
00038     printf("Add MAC Address::\r\n");
00039     int i;
00040     for(i=0; i< MAX_DEVICES; i++)
00041     {
00042         if(Ble_address[i][0] == '\0')
00043         {
00044             for(unsigned j=0; j< MAX_DEVICES; j++)
00045             {
00046                 if(Ble_address[j][0] == u8MacAddress[0])
00047                 {
00048                     printf("Already Added MAC Address \r\n");
00049                     return;
00050                 }
00051             }
00052             memset(Ble_address[i],0,MAC_ADDR_LEN);
00053             memcpy(Ble_address[i],u8MacAddress,MAC_ADDR_LEN);
00054             nDiscoveredDevice++;
00055             if(first_connection && Ble_address[i][0] == DEVICE_MAC_ADDR_1)
00056             {   
00057                 first_connection = false;
00058                 connectDevices(DEVICE_MAC_ADDR_1);
00059             }
00060             printf("MAC Address \r\n");
00061             for (unsigned index = 0; index < MAC_ADDR_LEN; index++) 
00062             {
00063                 printf("%02x ", Ble_address[i][index]);
00064             }
00065             break;
00066         }
00067         else
00068         {
00069             printf("MAC Address index[%d] is not NULL \r\n", i);            
00070         }
00071     }
00072     
00073 }
00074 
00075 void scanThread()
00076 {
00077     printf("Scan Thread\r\n");
00078     
00079     while(scanFlag)
00080     {
00081         wait(10.0);
00082         scanFlag = false;
00083         BLE::Instance().gap().stopScan();
00084     }
00085     
00086 }
00087 
00088 void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params) {
00089 
00090         if (params->peerAddr[0] == DEVICE_MAC_ADDR_1 || params->peerAddr[0] == DEVICE_MAC_ADDR_2 || 
00091             params->peerAddr[0] == DEVICE_MAC_ADDR_3 || params->peerAddr[0] == DEVICE_MAC_ADDR_4 ||
00092             params->peerAddr[0] == DEVICE_MAC_ADDR_5)
00093         { // 0x2F for red bear1.5 /* !ALERT! Alter this filter to suit your device. */
00094        
00095            pc.printf("adv peerAddr[%02x %02x %02x %02x %02x %02x] rssi %d, isScanResponse %u, AdvertisementType %u\r\n",
00096            params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],
00097            params->rssi, params->isScanResponse, params->type);
00098            pc.printf("Data Length : %d\r\n",params->advertisingDataLen);
00099            AddMacAddress(params->peerAddr);
00100          
00101         }
00102         else
00103         {
00104             printf("Not Matched your device\r\n");
00105             return;
00106         }
00107  }
00108 
00109 void connectDevices(int device_type)
00110 {
00111          pc.printf("Connection : %d\r\n", disconnect_status);
00112             pc.printf("Connection device Type: %d\r\n", device_type);
00113             uint8_t con_status =0;
00114             for(unsigned index = 0; index < nDiscoveredDevice; index++ )
00115             {
00116                 if(Ble_address[index][0] == device_type)
00117                 {
00118                     disconnect_status = false;
00119                     con_status = BLE::Instance().gap().connect(Ble_address[index], Gap::ADDR_TYPE_PUBLIC, NULL, NULL);
00120                     pc.printf("Connection Status : %d\r\n",con_status);
00121                     connect_status = 1;
00122                     return;
00123                 }
00124             }
00125 
00126 }
00127 void serviceDiscoveryCallback(const DiscoveredService *service) {
00128     pc.printf("Service Discovery Callback\r\n");
00129     if (service->getUUID().shortOrLong() == UUID::UUID_TYPE_SHORT) {
00130         pc.printf("S UUID-%x attrs[%u %u]\r\n", service->getUUID().getShortUUID(), service->getStartHandle(), service->getEndHandle());
00131     } else {
00132         //pc.printf("S UUID-");
00133         const uint8_t *longUUIDBytes = service->getUUID().getBaseUUID();
00134         for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
00135             printf("%02x", longUUIDBytes[i]);
00136         }
00137         pc.printf(" attrs[%u %u]\r\n", service->getStartHandle(), service->getEndHandle());
00138     }
00139 }
00140 
00141 void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP) {
00142     pc.printf("  C UUID-%x valueAttr[%u] props[%x]\r\n", characteristicP->getUUID().getShortUUID(), characteristicP->getValueHandle(), (uint8_t)characteristicP->getProperties().broadcast());
00143     
00144     if (characteristicP->getUUID().getShortUUID() == 0xEC0E || characteristicP->getUUID().getShortUUID() == 0xFFE9) { /* !ALERT! Alter this filter to suit your device. */
00145        lightCharacteristic = *characteristicP;
00146        pc.printf("Matched char UUID\r\n");
00147        printf("Conn Handle = %dand %d \r\n",characteristicP->getConnectionHandle(), lightCharacteristic.getConnectionHandle());
00148        printf("Value Handle = %d and %d\r\n",characteristicP->getValueHandle(),lightCharacteristic.getValueHandle());
00149        //AddCharNodes(lightCharacteristic);
00150        charDiscover = 1;
00151        serviceDiscover = false;
00152      }else {
00153         printf("Not Matched char UUID\r\n");
00154     }
00155 }
00156 
00157 void AddCharNodes(DiscoveredCharacteristic light_Characteristic)
00158 {
00159     //printf("Add Char Nodes\r\n");
00160     //lightCharacteristic_t ptr_temp_char;
00161     /*
00162     ptr_temp_char = lightChar.services_Char[0];
00163 
00164     
00165     if(NULL == ptr_temp_char)
00166     {
00167         ptr_temp_char = new lightCharacteristic_t;
00168         lightChar.services_Char[0] = ptr_temp_char;         
00169     }
00170     else
00171     {    
00172         while(NULL != ptr_temp_char->nextChar)
00173                 {
00174                     ptr_temp_char = ptr_temp_char->nextChar;
00175                 }  
00176             
00177         // add a new node 
00178         ptr_temp_char->nextChar = new lightCharacteristic_t;
00179         ptr_temp_char = ptr_temp_char->nextChar;
00180     }*/
00181             
00182     /* assign data to the node */
00183    /* ptr_temp_char.u_characteristicID = 1;
00184     pc.printf("Conn Handle = %d\r\n",light_Characteristic.getConnectionHandle());
00185     pc.printf("Value Handle = %d\r\n",light_Characteristic.getValueHandle());
00186     ptr_temp_char.connHandle = light_Characteristic.getConnectionHandle();
00187     ptr_temp_char.valueHandle = light_Characteristic.getValueHandle();
00188     */
00189     //ptr_temp_char.nextChar = NULL;
00190 }
00191 
00192 void discoveryTerminationCallback(Gap::Handle_t connectionHandle) {
00193     pc.printf("terminated SD for handle %u\r\n", connectionHandle);
00194     serviceDiscover = false;
00195     pc.printf("Service Discover handle %d\r\n", serviceDiscover);
00196 }
00197 
00198 void connectionCallback(const Gap::ConnectionCallbackParams_t *params) {
00199     pc.printf("Connection Callback\n\r");
00200     if (params->role == Gap::CENTRAL) 
00201     {
00202         pc.printf("Handle %u and peer addr [%02x]\r\n", params->handle,params->peerAddr[0]);
00203         pc.printf("Service and characterstics discovery callback\r\n");
00204         BLE::Instance().gattClient().onServiceDiscoveryTermination(discoveryTerminationCallback);
00205         switch(params->peerAddr[0])
00206         {
00207             case DEVICE_MAC_ADDR_1: // 0xec00 --> Services UUID and 0xec0e --> Characteristics UUID
00208                 error_status = BLE::Instance().gattClient().launchServiceDiscovery(params->handle, serviceDiscoveryCallback, characteristicDiscoveryCallback, 0xEC00, 0xEC0E);
00209                 break;
00210                     
00211             case DEVICE_MAC_ADDR_2: // 0xffe5 --> Services UUID and 0xffe9 --> Characteristics UUID
00212                 error_status = BLE::Instance().gattClient().launchServiceDiscovery(params->handle, serviceDiscoveryCallback, characteristicDiscoveryCallback, 0xffe5, 0xffe9);
00213                 break;
00214             default:
00215                 printf("************Unhandled Device Address *************\r\n");
00216                 break;
00217         }
00218         
00219         printf("Service Discovery Error Status =%d\n\r",error_status);
00220 
00221     }
00222 }
00223 
00224 void writeCallback(const GattWriteCallbackParams *eventDataP) 
00225 {
00226     pc.printf("written callback\r\n");    
00227 }
00228 
00229 void pairDevice()
00230 {
00231     if(read_flag)
00232     {
00233         printf("Read Pairdevice\r\n");
00234         connectDevices(DEVICE_MAC_ADDR_1);
00235     }
00236     else if(write_flag)
00237     {
00238         printf("Write Pairdevice\r\n");
00239         connectDevices(DEVICE_MAC_ADDR_2);
00240     }else
00241     {
00242         printf("invalid Pairdevice status\r\n");
00243     }
00244 }
00245 void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params) {
00246     pc.printf("disconnected\r\n");
00247     disconnect_status = true;
00248     //ble.gap().startScan(advertisementCallback);
00249     connect_status = 0;
00250     charDiscover = 0;
00251     serviceDiscover = true;
00252     pairDevice();
00253     //bleint();
00254 }
00255 
00256 void triggerRead(const GattReadCallbackParams *response)
00257 {
00258     printf("reading data : \r\n");
00259     if (response->handle == lightCharacteristic.getValueHandle())
00260     {   
00261         response_flag = true;
00262         printf("triggerToggledWrite: handle %u, offset %u, len %u\r\n", response->handle, response->offset, response->len);
00263         memcpy(read_buffer,response->data,response->len);
00264         receiveBufSize = response->len;
00265         for (unsigned index = 0; index < response->len; index++) 
00266         {
00267             printf("%c", read_buffer[index]);
00268         }
00269         printf("\r\n");
00270     }
00271 }
00272 
00273 /**
00274  * Callback triggered when the ble initialization process has finished
00275  */
00276 void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
00277 {
00278     BLE&        ble = params->ble;
00279     
00280     pc.printf("Ble Init\n\r");
00281     /* Ensure that it is the default instance of BLE */
00282     if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
00283         return;
00284     }
00285  
00286     ble.gap().onConnection(connectionCallback);
00287     ble.gap().onDisconnection(disconnectionCallback);
00288     ble.gattClient().onDataRead(triggerRead);
00289     
00290     ble.gap().setScanParams(1000, 800);
00291     ble.gap().startScan(advertisementCallback);
00292     
00293     scanFlag = true;
00294     
00295 }
00296 
00297 void read_Characteristics()
00298 {   uint16_t write_data;
00299     
00300     error_status = BLE::Instance().gattClient().read(lightCharacteristic.getConnectionHandle(),lightCharacteristic.getValueHandle(), write_data);
00301     
00302     printf("Error Status =%d\n\r",error_status);
00303 
00304     printf("READ VALUE : ");
00305     printf("%x \r\n", write_data);
00306     BLE::Instance().processEvents();
00307 }
00308 void light_actions(int * service_char)
00309 {
00310     uint8_t write_data[16];
00311 
00312     uint8_t numCount;
00313     if(connect_status)
00314     {
00315 
00316         switch(service_char[2])
00317         {
00318             case TURN_OFF: // off 
00319                 write_data[0]=0x56;
00320                 write_data[1]=0x00;
00321                 write_data[2]=0x00;
00322                 write_data[3]=0x00;
00323                 write_data[4]=0x00;
00324                 write_data[5]=0xf0;
00325                 write_data[6]=0xaa;
00326                 
00327                 error_status = BLE::Instance().gattClient().write(GattClient::GATT_OP_WRITE_CMD,lightCharacteristic.getConnectionHandle(),lightCharacteristic.getValueHandle(),7,write_data);
00328                 BLE::Instance().processEvents();
00329                 break;
00330                        
00331             case TURN_ON: //on
00332                 if(first_on)
00333                 {
00334                     pre_write_data[0]=0x56;
00335                     pre_write_data[1]=0xDE;
00336                     pre_write_data[2]=0x8E;
00337                     pre_write_data[3]=0xEE;
00338                     pre_write_data[4]=0x00;
00339                     pre_write_data[5]=0xf0;
00340                     pre_write_data[6]=0xaa;
00341                 }
00342                 error_status = BLE::Instance().gattClient().write(GattClient::GATT_OP_WRITE_CMD,lightCharacteristic.getConnectionHandle(),lightCharacteristic.getValueHandle(),7,pre_write_data);
00343                 BLE::Instance().processEvents();
00344                 break;
00345                        
00346             case COLOR: // Color
00347                 write_data[0]=0x56;
00348                 write_data[1]=lightColor[service_char[3]][0];//0xff
00349                 write_data[2]=lightColor[service_char[3]][1];//0x00;
00350                 write_data[3]=lightColor[service_char[3]][2];//0x00;
00351                 write_data[4]=0x00;
00352                 write_data[5]=0xf0;
00353                 write_data[6]=0xaa;
00354                 for(numCount=0; numCount < 7; numCount++){
00355                   pre_write_data[numCount] = write_data[numCount];
00356                 }
00357                 first_on=false;
00358                 error_status = BLE::Instance().gattClient().write(GattClient::GATT_OP_WRITE_CMD,lightCharacteristic.getConnectionHandle(),lightCharacteristic.getValueHandle(),7,write_data);
00359                 BLE::Instance().processEvents();
00360                 break;
00361                        
00362             default:
00363                 printf("Invalid Options\r\n");
00364         } 
00365             printf(" light Error Status =%d\n\r",error_status);
00366     }
00367 
00368 }
00369 
00370 void datancpy(char pre_write[], char writeData[], int data_size){
00371     int numCount;
00372     for(numCount=0; numCount <= data_size; numCount++){
00373         pre_write[numCount] = writeData[numCount];
00374     }
00375     
00376 }
00377 
00378 void bleint()
00379 {
00380     printf("Init\r\n");
00381     BLE &ble = BLE::Instance();
00382     BLE::Instance().init(bleInitComplete);
00383     
00384 }
00385 
00386 bool checkBytes(int byteValue)
00387 {    
00388     
00389     bool status = false;
00390     switch(byteValue)
00391     {
00392         case 0xAD:
00393             read_flag = false;
00394             write_flag = true;
00395             BLE::Instance().gap().disconnect(lightCharacteristic.getConnectionHandle(),Gap::REMOTE_USER_TERMINATED_CONNECTION);
00396             status = true;
00397             break;
00398         
00399         case 0xAF:
00400             read_flag = true;
00401             write_flag = false;
00402             BLE::Instance().gap().disconnect(lightCharacteristic.getConnectionHandle(),Gap::REMOTE_USER_TERMINATED_CONNECTION);
00403             status = true;
00404             break;
00405             
00406         default:
00407             status = false;
00408             break;
00409     }
00410     
00411     return status;
00412 }
00413 
00414 int main()
00415 {
00416     // Serial port configuration
00417     pc.baud(9600);
00418     wait(8.0);
00419     pc.printf("Start\n\r");
00420     statusWR=1;
00421 
00422     int read_temp_data;
00423     int write_temp_data;
00424     uint8_t read_bufferSize;
00425     
00426     bleint();
00427     
00428     spiSlave.reply(12);
00429 
00430     read_bufferSize = 0;
00431     while(1)
00432     {
00433         pc.printf("loop\r\n");
00434         printf( "Connect Status %d  and Char Discover %d \r\n", connect_status, charDiscover);
00435         
00436         scanThread();
00437         
00438         if(!(connect_status && charDiscover))
00439         {   
00440             printf( " Wait Event Connect Status %d  and Char Discover %d \r\n", connect_status, charDiscover);
00441             waitBleEvent();
00442             
00443         }
00444         printf("Readchar\r\n");
00445       
00446         if(connect_status && charDiscover)
00447         {
00448             //read_bufferSize = 0;
00449             if(read_flag)
00450             {
00451                 pc.printf("Read\r\n");
00452                 read_Characteristics();
00453                 printf("receiveBufSize : %d",receiveBufSize);
00454                 if(spiSlave.receive()  && response_flag)//
00455                 {   
00456                     
00457                     read_temp_data = spiSlave.read();
00458                           
00459                     while(spiSlave.receive()) 
00460                     {   
00461                         if(read_bufferSize == 0)  
00462                             spiSlave.reply(receiveBufSize);
00463                             
00464                         //if(read_bufferSize < receiveBufSize)
00465                          //   break;
00466                         
00467                         //vif(checkBytes(read_temp_data))
00468                          //v   break;
00469                             
00470                         read_temp_data = spiSlave.read();
00471                         if(read_temp_data == 0xAA)
00472                         {
00473                             spiSlave.reply(read_buffer[read_bufferSize]);
00474                             read_bufferSize++;   
00475                         }
00476                         
00477                         
00478                         
00479                     }
00480                 
00481                     if(read_bufferSize >= receiveBufSize)
00482                     {
00483                         read_bufferSize =0;
00484                         spiSlave.reply(0xFE);// Send 0xFE to Master to indicate stop polling the data.
00485                     }        
00486                 }
00487             }
00488             if(write_flag && connect_status && charDiscover)
00489             {
00490                 if(spiSlave.receive())
00491                 {
00492                     spiRX[write_bufferSize] = spiSlave.read();
00493                     write_temp_data = spiRX[write_bufferSize];
00494                     write_bufferSize = 0;
00495                     while(write_flag)
00496                     {
00497                         if(checkBytes(write_temp_data))
00498                             break;
00499                             
00500                         spiSlave.reply(spiRX[write_bufferSize]);
00501                         write_bufferSize++;
00502                         spiRX[write_bufferSize] = spiSlave.read();
00503                         write_temp_data = spiRX[write_bufferSize];
00504                         
00505                         if(write_bufferSize >= 5 )
00506                         {
00507                             light_actions(spiRX);
00508                             spiSlave.reply(0xFE); // Send 0xFE to Master to indicate stop polling the data.
00509                               
00510                         }
00511                     }
00512                 }
00513             }
00514         }  
00515     }
00516 
00517 }
00518 
00519 void waitBleEvent()
00520 {
00521     while(serviceDiscover )
00522     {
00523         printf("Service Discover =%d\r\n",serviceDiscover);
00524         printf(" Service Status = %d \r\n",BLE::Instance().gattClient().isServiceDiscoveryActive());
00525         BLE::Instance().waitForEvent();
00526         printf( "waitBleEvent loop\r\n");
00527     }
00528     printf( "waitBleEvent End\r\n"); 
00529 }
00530