работает в паре с micro:bit мигалкой

Dependencies:   mbed BLE_API nRF51822

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2006-2015 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 #include "mbed.h"
00018 #include "ble/BLE.h"
00019 #include "ble/DiscoveredCharacteristic.h"
00020 #include "ble/DiscoveredService.h"
00021 
00022 DigitalOut alivenessLED(LED1, 1);
00023 DigitalOut connectLED(P0_22, 0);
00024 
00025 Serial pc(USBTX, USBRX);
00026 
00027 bool                     triggerLedCharacteristic = false;
00028 DiscoveredCharacteristic ledCharacteristic;
00029 uint8_t bVal = 0;
00030 
00031 //Функции обработки событий кнопок
00032 void triggerfall_1();   //Button1 falling interrupt function
00033 void triggerrise_1();   //Button1 rising interrupt function
00034 void triggerfall_2();   //Button2 falling interrupt function
00035 void triggerrise_2();   //Button2 rising interrupt function
00036 
00037 DigitalIn  sw1(BUTTON1);
00038 DigitalIn  sw2(BUTTON2);
00039 
00040 //Initiate input interrupts
00041 InterruptIn sw1Press(BUTTON1);
00042 InterruptIn sw2Press(BUTTON2);
00043 
00044 BLE        ble;
00045 Ticker ticker;
00046 
00047 //событие по таймеру
00048 void periodicCallback(void) {
00049 //Мигаем светодиодом
00050     alivenessLED = !alivenessLED; /* Do blinky on LED1 while we're waiting for BLE events */
00051 }
00052 //результат сканирования
00053 void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params) {
00054 /*    if (params->peerAddr[0] != 0x37) { // !ALERT! Alter this filter to suit your device.
00055         return;
00056     }*/
00057     printf("adv peerAddr[%02x %02x %02x %02x %02x %02x] rssi %d, isScanResponse %u, AdvertisementType %u\r\n",
00058            params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],
00059            params->rssi, params->isScanResponse, params->type);
00060 
00061     BLE::Instance().gap().connect(params->peerAddr, Gap::ADDR_TYPE_RANDOM_STATIC, NULL, NULL);
00062 }
00063 //поиск сервисов
00064 void serviceDiscoveryCallback(const DiscoveredService *service) {
00065     printf("TEST!!!!!!!!\r\n");
00066     printf("S UUID-%x\r\n", service->getUUID().getShortUUID());
00067     if (service->getUUID().shortOrLong() == UUID::UUID_TYPE_SHORT) {
00068         printf("S UUID-%x attrs[%u %u]\r\n", service->getUUID().getShortUUID(), service->getStartHandle(), service->getEndHandle());
00069     } else {
00070         printf("S UUID-");
00071         const uint8_t *longUUIDBytes = service->getUUID().getBaseUUID();
00072         for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
00073             printf("%02x", longUUIDBytes[i]);
00074         }
00075         printf(" attrs[%u %u]\r\n", service->getStartHandle(), service->getEndHandle());
00076     }
00077 }
00078 //поиск характеристик и вывод инфы
00079 void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP) {
00080     printf("C UUID-%x valueAttr[%u] props[%x]\r\n", characteristicP->getUUID().getShortUUID(), characteristicP->getValueHandle(), (uint8_t)characteristicP->getProperties().broadcast());
00081     if (characteristicP->getUUID().getShortUUID() == 0xa001) { /* !ALERT! Alter this filter to suit your device. */
00082         ledCharacteristic        = *characteristicP;
00083         triggerLedCharacteristic = true;
00084     }
00085 }
00086 
00087 void discoveryTerminationCallback(Gap::Handle_t connectionHandle) {
00088     printf("terminated SD for handle %u\r\n", connectionHandle);
00089 }
00090 //Действие при событии "onConnection"
00091 void connectionCallback(const Gap::ConnectionCallbackParams_t *params) {
00092     if (params->role == Gap::CENTRAL) {
00093         BLE::Instance().gattClient().onServiceDiscoveryTermination(discoveryTerminationCallback);
00094         BLE::Instance().gattClient().launchServiceDiscovery(params->handle, serviceDiscoveryCallback, characteristicDiscoveryCallback, 0xa000, 0xa001);
00095     }
00096     printf("connected\r\n");
00097     connectLED = 1;
00098 }
00099 
00100 //Вызывается событием "onDataRead"
00101 void triggerToggledWrite(const GattReadCallbackParams *response) {
00102     if (response->handle == ledCharacteristic.getValueHandle()) {
00103 //#if DUMP_READ_DATA
00104         printf("triggerToggledWrite: handle %u, offset %u, len %u\r\n", response->handle, response->offset, response->len);
00105         for (unsigned index = 0; index < response->len; index++) {
00106             printf("%c[%02x]", response->data[index], response->data[index]);
00107         }
00108         printf("\r\n");
00109 //#endif
00110 //пишем в характеристику 0х00 или 0х01, т.е. моргаем диодом дистанционно
00111 //        uint8_t toggledValue = response->data[0] ^ 0x1;
00112         uint8_t toggledValue = bVal;
00113         ledCharacteristic.write(1, &toggledValue);
00114         printf("onDataRead\r\ntoggledValue: %02x\r\n", toggledValue);
00115     }
00116 }
00117 
00118 //Вызывается событием "onDataWrite"
00119 void triggerRead(const GattWriteCallbackParams *response) {
00120     if (response->handle == ledCharacteristic.getValueHandle()) {
00121         ledCharacteristic.read();
00122         printf("onDataWrite\r\n");
00123     }
00124 }
00125 
00126 //Действие при событии "Disconnect"
00127 void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params) {
00128     printf("disconnected\r\n");
00129     pc.printf("Rescan\r\n");
00130     ble.gap().startScan(advertisementCallback);
00131     connectLED = 0;
00132 }
00133 
00134 /**
00135  * This function is called when the ble initialization process has failed
00136  */
00137 void onBleInitError(BLE &ble, ble_error_t error)
00138 {
00139     /* Initialization error handling should go here */
00140 }
00141 
00142 /**
00143  * Callback triggered when the ble initialization process has finished
00144  */
00145 void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
00146 {
00147     BLE&        ble   = params->ble;
00148     ble_error_t error = params->error;
00149 
00150     if (error != BLE_ERROR_NONE) {
00151         /* In case of error, forward the error handling to onBleInitError */
00152         onBleInitError(ble, error);
00153         return;
00154     }
00155 
00156     /* Ensure that it is the default instance of BLE */
00157     if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
00158         return;
00159     }
00160  
00161     ble.gap().onConnection(connectionCallback);
00162     ble.gap().onDisconnection(disconnectionCallback);
00163 
00164     ble.gattClient().onDataRead(triggerToggledWrite);
00165     ble.gattClient().onDataWrite(triggerRead);
00166 
00167     ble.gap().setScanParams(500, 400);
00168     ble.gap().startScan(advertisementCallback);
00169 }
00170 
00171 int main(void) {
00172     pc.baud(9600);
00173     printf("--- Start!!! ---\r\n");
00174 
00175 //Set falling and rising edge to apppropriate interrup function
00176     sw1Press.fall(&triggerfall_1);
00177     sw1Press.rise(&triggerrise_1);
00178     sw2Press.fall(&triggerfall_2);
00179     sw2Press.rise(&triggerrise_2);
00180     
00181     ticker.attach(periodicCallback, 1);
00182 
00183     BLE &ble = BLE::Instance();
00184     ble.init(bleInitComplete);
00185 
00186     /* SpinWait for initialization to complete. This is necessary because the
00187      * BLE object is used in the main loop below. */
00188     while (ble.hasInitialized()  == false) { /* spin loop */ }
00189 
00190     while (true) {
00191         if (triggerLedCharacteristic && !ble.gattClient().isServiceDiscoveryActive()) {
00192             triggerLedCharacteristic = false;
00193             ledCharacteristic.read(); /* We could have issued this read just as easily from
00194                                        * characteristicDiscoveryCallback(); but
00195                                        * invoking it here demonstrates the use
00196                                        * of isServiceDiscoveryActive() and also
00197                                        * the fact that it is permitted to
00198                                        * operate on application-local copies of
00199                                        * DiscoveredCharacteristic. */
00200         }
00201         ble.waitForEvent();
00202     }
00203 }
00204 
00205 //Button1 falling interrupt function
00206 void triggerfall_1()
00207 {
00208     bVal =! bVal;
00209 }
00210 //Button1 rising interrupt function
00211 void triggerrise_1()
00212 {
00213 }
00214 
00215 //Button1 falling interrupt function
00216 void triggerfall_2()
00217 {
00218 }
00219 //Button1 rising interrupt function
00220 void triggerrise_2()
00221 {
00222 }