/**
 * Constructor for the UARTService.
 * @param _ble an instance of BLEDevice
 * @param rxBufferSize the size of the rxBuffer
 * @param txBufferSize the size of the txBuffer
 *
 * @note defaults to 20
 */
MicroBitUARTService::MicroBitUARTService(BLEDevice &_ble, uint8_t rxBufferSize, uint8_t txBufferSize) : ble(_ble)
{
    rxBufferSize += 1;
    txBufferSize += 1;

    txBuffer = (uint8_t *)malloc(txBufferSize);
    rxBuffer = (uint8_t *)malloc(rxBufferSize);

    rxBufferHead = 0;
    rxBufferTail = 0;
    this->rxBufferSize = rxBufferSize;

    txBufferHead = 0;
    txBufferTail = 0;
    this->txBufferSize = txBufferSize;

    GattCharacteristic rxCharacteristic(UARTServiceRXCharacteristicUUID, rxBuffer, 1, rxBufferSize, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);

    txCharacteristic = new GattCharacteristic(UARTServiceTXCharacteristicUUID, txBuffer, 1, txBufferSize, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE);

    GattCharacteristic *charTable[] = {txCharacteristic, &rxCharacteristic};

    GattService uartService(UARTServiceUUID, charTable, sizeof(charTable) / sizeof(GattCharacteristic *));

    _ble.addService(uartService);

    this->rxCharacteristicHandle = rxCharacteristic.getValueAttribute().getHandle();

    _ble.gattServer().onDataWritten(this, &MicroBitUARTService::onDataWritten);
    _ble.gattServer().onConfirmationReceived(on_confirmation);
}
int main() {

    ble.init();
    ble.onDisconnection(disconnectionCallback);
    ble.onDataWritten(onDataWritten);

    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *)deviceName, strlen(deviceName));
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.setAdvertisingInterval(160); /* 100ms; in multiples of 0.625ms. */

    ble.startAdvertising();

    GattCharacteristic toggleCharacteristic(0x2222,
                                            &relayState,
                                            sizeof(relayState),
                                            sizeof(relayState),
                                            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE);

    GattCharacteristic *charTable[] = {&toggleCharacteristic};
    GattService toggleService(0x2220, charTable, sizeof(charTable) / sizeof(GattCharacteristic *));
    ble.addService(toggleService);

    while (true) {
        if (rxPayloadUpdated)
        {
            relayPIN = rxPayload[0];
            rxPayloadUpdated = false;
        }
            
        ble.waitForEvent();
    }
}
Exemple #3
0
void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason)
{
    isConnected = 0;
    (*led1) = 0;

    ticker->detach();
    ticker->attach(periodicCallback, 0.4f); // blink LED every second

    ble.startAdvertising();
}
void disconnectionCallback(Gap::Handle_t handle,
                     Gap::DisconnectionReason_t disconnectReason)
{
  pc.printf(">>Disconnected\n");
  /*led1.write(0);
  led2.write(0);
  led3.write(0);
  led4.write(0);
  */

  ble.startAdvertising();
}
Exemple #5
0
void timerCallback(void)
{
    DEBUG("start timer callback");
    sprintf(answer,"+.!");
    DEBUG("writing beatpulse \"%s\" with len %d to ble\n",answer,strlen(answer));
    int l = strlen(answer);
    for(int i = 0; i*20 < strlen(answer); i++) {
        int len = 20 < l ? 20 : l;
        ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), (uint8_t *)&answer[i*20], len);
        l -= 20;
    }
    ticker.detach();
}
/**
 * Write callback
 * Called when a Gatt characteristic is written to by a central device
 */
void writeCharCallback(const GattWriteCallbackParams *params)
{
    /* Prepare to add header to transmit message to the MicroView */
    char *total;
    total = (char*)malloc(sizeof(char)*(params->len+1));
    strcat(total+1, (char*)params->data);
    total[params->len+1]= '\0';
    
    // Check to see what characteristic was written, by handle    
    /* If it's a standard message (comming from a notification) */
    if(params->handle == writeChar.getValueHandle()) {
        /* If only one byte is sent, we change the LED's state with its value*/
        if(params->len == 1)
            led1 = params->data[0];
        else {
            //pc.printf("\n\r Data received: length = %d, data = 0x",params->len);
            /* If the data received is equal to "ON" or "OFF", we modify the LED's state accordingly */
            if(strncmp((char*)params->data, "ON",2) == 0) {
                //pc.printf("LED ON");
                led1=1;
            } else if(strncmp((char*)params->data, "OFF",3) == 0) {
                //pc.printf("LED OFF");
                led1=0;
            }
            else {
                /* For each message, we toggle the LED's state */
                led1=!led1;
            }
        }
                
         /* Add the header specific to standard messages (not time sync) */
        total[0] = headerSms;
        /* Update the readChar characteristic with the value of writeChar */
        //ble.updateCharacteristicValue(readChar.getValueHandle(), params->data, params->len);
        ble.updateCharacteristicValue(readChar.getValueHandle(), (const uint8_t *)total, strlen(total)+1);
        /* Send the whole string, including the header, to the Microview */
        i2c_port.write(addr, total, strlen(total)+1);
    }
    /* If the message has been sent to the timeSync Gatt characteristic */
    else if(params->handle == timeSyncChar.getValueHandle()) {
        /* Set the corresponding header byte */
        total[0] = headerTime;
        /* Send the whole string, including the header, to the MicroView */
        i2c_port.write(addr, total, strlen(total)+1);
        led1 = !led1;
    }
    free(total);
}
Exemple #7
0
int main() {
  ble.init();
  ble.onConnection(onConnection);
  ble.onDisconnection(onDisconnection);
  ble.onDataWritten(onDataWritten);
 
  ble.accumulateAdvertisingPayload(
      GapAdvertisingData::BREDR_NOT_SUPPORTED);
  ble.setAdvertisingType(
      GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
  ble.accumulateAdvertisingPayload(
      GapAdvertisingData::SHORTENED_LOCAL_NAME,
      (const uint8_t *)NAME,
      sizeof(NAME) - 1);
  ble.accumulateAdvertisingPayload(
      GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
      (const uint8_t *)UARTServiceUUID_reversed,
      sizeof(UARTServiceUUID_reversed));
  ble.accumulateScanResponse(
      GapAdvertisingData::SHORTENED_LOCAL_NAME,
      (const uint8_t *)NAME,
      sizeof(NAME) - 1);
  ble.accumulateScanResponse(
      GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
      (const uint8_t *)UARTServiceUUID_reversed,
      sizeof(UARTServiceUUID_reversed));

  ble.setDeviceName((const uint8_t *)NAME);
 
  ble.setAdvertisingInterval(Gap::MSEC_TO_GAP_DURATION_UNITS(1000));
  ble.startAdvertising();
 
  UARTService uartService(ble);
  uartServicePtr = &uartService;

  while (true) {
    ble.waitForEvent();
  }
}
Exemple #8
0
int main(void)
{
    int ret = 0;
    uint8_t *pTemp;
    int len;
    int ch;

//    led1 = new DigitalOut(P0_4);
    led1 = new DigitalOut(LED2);
     ticker = new Ticker();
    ticker->attach(periodicCallback, 0.4f); // blink LED
    serialPort = new Serial(USBTX, USBRX);
//    serialPort = new Serial(P0_0, P0_1);
    (*led1) = 1;
    serialPort->baud(115200);
    serialPort->attach(&rxInterrupt,SerialBase::RxIrq);

//    serialPort->printf("Yeth sport\r\n");
    wait_ms(100);
    ret = bicProcessInit();
    if (ret)
    {
        serialPort->printf("bic process init failed:%d\r\n", ret);
        while(1);
    }
//    serialPort->printf("%s\r\n", __TIME__);
    ble.init();
    ble.onDisconnection(disconnectionCallback);
    ble.onConnection(connectionEventCallback);

    uart = new UARTService(ble);

    recordInit();

    /* setup advertising */
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
                                     (const uint8_t *)"ysport", sizeof("ysport") - 1);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
                                     (const uint8_t *)UARTServiceUUID_reversed, sizeof(UARTServiceUUID_reversed));

    ble.setAdvertisingInterval(50); /* 100ms; in multiples of 0.625ms. */
    ble.startAdvertising();

    while (true) {
        ble.waitForEvent();
        ch = EOF;
        if (ledToggle) {
            (*led1) = !(*led1);
            ledToggle = 0;
        }
        while(1)
        {
            ch = uart->_getc();
            if (ch == EOF)
                break;
            serialPort->putc(ch);
            bicReceiveChar((uint8_t)ch);
        }

        while(0 == bicProcessDispatchEvents()){
            wait_ms(20);
        }
    }
}
Exemple #9
0
void onDataWritten(const GattWriteCallbackParams *params)
{
    if ((uartServicePtr != NULL) && (params->handle == uartServicePtr->getTXCharacteristicHandle())) {
        uint16_t bytesRead = params->len;
        bool handled = false;


        for(int i = 0; !handled && i < bytesRead; i++) {
            switch(params->data[i]) {
                case '?': {
                    DEBUG("Handle ?\n");
                    switch(getStateBM019()) {
                        case BM019_STATE_UNKNOWN:
                            DEBUG("BM019 Status: unknown\n");
                            sprintf(answer,"+?:0!");
                            break;
                        case BM019_STATE_ANSWERING:
                            DEBUG("BM019 Status: answering\n");
                            sprintf(answer,"+?:1!");
                            break;
                        case BM019_STATE_PROTOCOL:
                            DEBUG("BM019 Status: protocol set\n");
                            sprintf(answer,"+?:2!");
                            break;
                        default:
                            sprintf(answer,"-?%d!",getStateBM019());
                            DEBUG("BM019 Status: forgotten state\n");
                    }
                    handled = true;
                }
                break;

                case 'b':
                case 'B':
                    DEBUG("Handling b\n");
                    if(i + 5 <= bytesRead) {
                        sprintf(answer,"+b!");
                        int adr = 0;
                        char b[3];
                        b[0] = params->data[i+4];
                        b[1] = params->data[i+5];
                        b[2] = 0;
                        sscanf(b,"%x",&adr);
                        DEBUG("beat in %d sec\n",adr);
                        ticker.attach(timerCallback, adr);
                        i+=5;
                        handled=true;
                    } else {
                        sprintf(answer,"-b!");
                        handled=true;
                    }

                    break;
                case 'h':
                case 'H': {
                    DEBUG("Handling h\n");
                    if(hybernateBM019()) {
                        sprintf(answer,"+h!");
                    } else {
                        DEBUG("BM019 did hybernate wake\n")
                        sprintf(answer,"-h!");
                    }
                    handled=true;

                }
                break;

                case 'w':
                case 'W': {
                    DEBUG("handle w\n")

                    if(wakeBM019(100)) {
                        DEBUG("BM019 did wake\n")
                        sprintf(answer,"+w!");
                    } else {
                        DEBUG("BM019 did NOT wake\n")
                        sprintf(answer,"-w!");
                    }
                    handled = true;
                }
                break;

                case 'i':
                case 'I': {
                    DEBUG("handle i\n");
                    BM019_IDN idn;
                    if(idnBM019(&idn)) {
                        sprintf(answer,"+i:");
                        int i;
                        for(i = 0; i < 13; i++) {
                            sprintf(&answer[strlen(answer)],"%x",idn.deviceID[i]);
                        }
                        sprintf(&answer[strlen(answer)],":");
                        sprintf(&answer[strlen(answer)],"%x%x!",idn.romCRC[0],idn.romCRC[1]);
                        DEBUG("answered: %s",answer);
                    } else {
                        DEBUG("BM019 failed idn\n")
                        sprintf(answer,"-i!");
                    }

                    handled = true;
                }
                break;

                case 'p':
                case 'P': {
                    DEBUG("handle p\n");
                    if(setProtocolISO_EIC_15693BM019((BM019_PROTOCOL_ISO_IEC_15693_BYTE_0)(
                                                         BM019_PROTOCOL_ISO_IEC_15693_BYTE_0_0_CRC |
                                                         BM019_PROTOCOL_ISO_IEC_15693_BYTE_0_1_SINGLE_SUBCARRIER |
                                                         BM019_PROTOCOL_ISO_IEC_15693_BYTE_0_2_10_MODULATION |
                                                         BM019_PROTOCOL_ISO_IEC_15693_BYTE_0_3_WAIT_FOR_SOF |
                                                         BM019_PROTOCOL_ISO_IEC_15693_BYTE_0_45_26_KBPS)
                                                    )) {
                        DEBUG("BM019 proto\n")
                        sprintf(answer,"+p!");
                    } else {
                        DEBUG("BM019 failed proto\n")
                        sprintf(answer,"-p!");
                    }

                    handled = true;
                }
                break;

                case 'r':
                case 'R': {
                    DEBUG("handle r\n");
                    resetBM019();
                    sprintf(answer,"+r!");
                    handled = true;
                }
                break;

                case 'e':
                case 'E': {
                    DEBUG("handle e\n");
                    if(echoBM019()) {
                        DEBUG("BM019 sent echo\n");
                        sprintf(answer,"+e!");
                    } else {
                        DEBUG("BM019 NOT sent echo\n");
                        sprintf(answer,"-e!");
                    }
                    handled = true;
                }
                break;

                case 't':
                case 'T': {
                    DEBUG("handle t\n");
                    BM019_TAG tag;
                    if(inventoryISO_IES_15693BM019(&tag)) {
                        DEBUG("BM019 answered inventory\n");
                        sprintf(answer,"+t:");
                        for(int i = 0; i < 8; i++) {
                            sprintf(&answer[strlen(answer)],"%02x",tag.uid[i]);
                        }
                        sprintf(&answer[strlen(answer)],"!");
                    } else {
                        DEBUG("BM019 NOT answered inventory\n");
                        sprintf(answer,"-t!");
                    }
                    handled = true;
                }
                break;

                case 'd':
                case 'D': {
                    DEBUG("handle d\n");
                    if(i + 5 <= bytesRead) {
                        int adr = 0;
                        char b[3];
                        b[0] = params->data[i+4];
                        b[1] = params->data[i+5];
                        b[2] = 0;
                        sscanf(b,"%x",&adr);
                        DEBUG("read from %#04x\n",adr);
                        i+=5;
                        uint8_t rb[256];
                        int l = readBM019(adr,rb,256);
                        if(l>0) {
                            DEBUG("BM019 answered read\n");
                            sprintf(answer,"+d:");
                            for(int i = 0; i < l; i++) {
                                sprintf(&answer[strlen(answer)],"%02x",rb[i]);
                            }
                            sprintf(&answer[strlen(answer)],"!");
                        } else {
                            DEBUG("BM019 NOT answered read\n");
                            sprintf(answer,"-d!");
                        }
                    } else {
                        DEBUG("BM019 NOT answered read, no adr given\n");
                        sprintf(answer,"-d!");
                    }
                    handled = true;
                }
                break;

                case 'm':
                case 'M': {
                    DEBUG("handle multi d\n");
                    if(i + 10 <= bytesRead) {
                        int adr = 0;
                        char b[3];
                        b[0] = params->data[i+4];
                        b[1] = params->data[i+5];
                        b[2] = 0;
                        sscanf(b,"%x",&adr);

                        int count = 0;
                        b[0] = params->data[i+9];
                        b[1] = params->data[i+10];
                        b[2] = 0;
                        sscanf(b,"%x",&count);
                        DEBUG("read from %#04x for %d\n",adr,count);
                        i+=10;
                        uint8_t rb[256];
                        int l = readMultiBM019(adr,count,rb,256);
                        if(l>0) {
                            DEBUG("BM019 answered multi\n");
                            sprintf(answer,"+m:");
                            for(int i = 0; i < l; i++) {
                                sprintf(&answer[strlen(answer)],"%02x",rb[i]);
                            }
                            sprintf(&answer[strlen(answer)],"!");
                        } else {
                            DEBUG("BM019 NOT answered multi\n");
                            sprintf(answer,"-m!");
                        }
                    } else {
                        DEBUG("BM019 NOT answered read, no adr&count given\n");
                        sprintf(answer,"-m!");
                    }
                    handled = true;
                }
                break;
            }
        }

        if(handled) {
            DEBUG("writing \"%s\" with len %d to ble\n",answer,strlen(answer));
            int l = strlen(answer);
            for(int i = 0; i*20 < strlen(answer); i++) {
                int len = 20 < l ? 20 : l;
                ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), (uint8_t *)&answer[i*20], len);
                l -= 20;
            }

        } else {
            DEBUG("received %u bytes.. nothing handled.. echo\n", bytesRead);
            ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), params->data, bytesRead);
        }
    }
Exemple #10
0
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
{
    DEBUG("Disconnected!\n\r");
    DEBUG("Restarting the advertising process\n\r");
    ble.startAdvertising();
}
BLECharacteristicImp::BLECharacteristicImp(const bt_uuid_t* uuid, 
                                           unsigned char properties,
                                           uint16_t handle,
                                           const BLEDevice& bledevice):
    BLEAttribute(uuid, BLETypeCharacteristic),
    _value_length(0),
    _value_buffer(NULL),
    _value_updated(false),
    _value_handle(handle),
    _cccd_handle(0),
    _attr_chrc_value(NULL),
    _attr_cccd(NULL),
    _subscribed(false),
    _reading(false),
    _ble_device()
{
    _value_size = BLE_MAX_ATTR_DATA_LEN;// Set as MAX value. TODO: long read/write need to twist
    _value = (unsigned char*)malloc(_value_size);

    // TODO: Enable when max value is not set.
    //    if (_value_size > BLE_MAX_ATTR_DATA_LEN)
    //    {
    //        _value_buffer = (unsigned char*)malloc(_value_size);
    //    }

    if (_value)
    {
      memset(_value, 0, _value_size);
    }
    else
    {
        errno = ENOMEM;
    }
    
    memset(&_ccc_cfg, 0, sizeof(_ccc_cfg));
    memset(&_ccc_value, 0, sizeof(_ccc_value));
    memset(&_gatt_chrc, 0, sizeof(_gatt_chrc));
    memset(&_sub_params, 0, sizeof(_sub_params));
    memset(&_discover_params, 0, sizeof(_discover_params));
    
    _ccc_value.cfg = &_ccc_cfg;
    _ccc_value.cfg_len = 1;
    if (BLERead & properties)
    {
        _gatt_chrc.properties |= BT_GATT_CHRC_READ;
    }
    if (BLEWrite & properties)
    {
        _gatt_chrc.properties |= BT_GATT_CHRC_WRITE;
    }
    if (BLEWriteWithoutResponse & properties)
    {
        _gatt_chrc.properties |= BT_GATT_CHRC_WRITE_WITHOUT_RESP;
    }
    if (BLENotify & properties)
    {
        _gatt_chrc.properties |= BT_GATT_CHRC_NOTIFY;
        _sub_params.value |= BT_GATT_CCC_NOTIFY;
    }
    if (BLEIndicate & properties)
    {
        _gatt_chrc.properties |= BT_GATT_CHRC_INDICATE;
        _sub_params.value |= BT_GATT_CCC_INDICATE;
    }
    _gatt_chrc.uuid = (bt_uuid_t*)this->bt_uuid();//&_characteristic_uuid;//this->uuid();
    memset(_event_handlers, 0, sizeof(_event_handlers));
    memset(_oldevent_handlers, 0, sizeof(_oldevent_handlers));
    
    _sub_params.notify = profile_notify_process;
        
    // Update BLE device object
    _ble_device.setAddress(*bledevice.bt_le_address());
    
    memset(&_descriptors_header, 0, sizeof(_descriptors_header));
}
BLECharacteristicImp::BLECharacteristicImp(BLECharacteristic& characteristic, 
                                           const BLEDevice& bledevice):
    BLEAttribute(characteristic.uuid(), BLETypeCharacteristic),
    _value_length(0),
    _value_buffer(NULL),
    _value_updated(false),
    _value_handle(0),
    _cccd_handle(0),
    _attr_chrc_value(NULL),
    _attr_cccd(NULL),
    _subscribed(false),
    _reading(false),
    _ble_device()
{
    unsigned char properties = characteristic._properties;
    _value_size = characteristic._value_size;
    _value = (unsigned char*)malloc(_value_size);
    if (_value == NULL)
    {
        errno = ENOMEM;
    }
    if (_value_size > BLE_MAX_ATTR_DATA_LEN)
    {
        _value_buffer = (unsigned char*)malloc(_value_size);
    }
    
    memset(&_ccc_cfg, 0, sizeof(_ccc_cfg));
    memset(&_ccc_value, 0, sizeof(_ccc_value));
    memset(&_gatt_chrc, 0, sizeof(_gatt_chrc));
    memset(&_sub_params, 0, sizeof(_sub_params));
    memset(&_discover_params, 0, sizeof(_discover_params));
    
    _ccc_value.cfg = &_ccc_cfg;
    _ccc_value.cfg_len = 1;
    if (BLERead & properties)
    {
        _gatt_chrc.properties |= BT_GATT_CHRC_READ;
    }
    if (BLEWrite & properties)
    {
        _gatt_chrc.properties |= BT_GATT_CHRC_WRITE;
    }
    if (BLEWriteWithoutResponse & properties)
    {
        _gatt_chrc.properties |= BT_GATT_CHRC_WRITE_WITHOUT_RESP;
    }
    if (BLENotify & properties)
    {
        _gatt_chrc.properties |= BT_GATT_CHRC_NOTIFY;
        _sub_params.value |= BT_GATT_CCC_NOTIFY;
    }
    if (BLEIndicate & properties)
    {
        _gatt_chrc.properties |= BT_GATT_CHRC_INDICATE;
        _sub_params.value |= BT_GATT_CCC_INDICATE;
    }
    _gatt_chrc.uuid = (bt_uuid_t*)this->bt_uuid();//&_characteristic_uuid;//this->uuid();

    memcpy(_event_handlers, characteristic._event_handlers, sizeof(_event_handlers));
    memcpy(_oldevent_handlers, characteristic._oldevent_handlers, sizeof(_oldevent_handlers));
    
    _sub_params.notify = profile_notify_process;
    
    if (NULL != characteristic._value)
    {
        memcpy(_value, characteristic._value, _value_size);
    }
        
    // Update BLE device object
    _ble_device.setAddress(*bledevice.bt_le_address());
    
    characteristic.setBLECharacteristicImp(this);
    memset(&_descriptors_header, 0, sizeof(_descriptors_header));
}
Exemple #13
0
void tick(void)
{
    bool send_threshold = threshold_update;
    int last_compare = current_compare;
    current_input = sensor.read();

    if (threshold_update) {
        threshold_update = 0;

        input_threshold = (single_click_input + double_click_input) / 2.0;
        invert_output = (double_click_input < single_click_input);

        force_update = true;

        DEBUG("threshold: %f\n\r", input_threshold);
    }


    if (0 == current_compare && current_input > input_threshold) {
        float extra_input = sensor.read();
        if (extra_input > input_threshold) {
            current_compare = 1;
        }
    } else if (1 == current_compare && current_input < input_threshold) {
        float extra_input = sensor.read();
        if (extra_input < input_threshold) {
            current_compare = 0;
        }
    }

    current_output = current_compare;
    if ((last_compare != current_compare) || force_update) {
        if (invert_output) {
            current_output = 1 - current_compare;
        }

        actuator = current_output;
    }

    DEBUG("in: %f, out: %d, invert: %d\n\r", current_input, current_output, invert_output);

    int txPayloadLength;
    if (send_threshold) {
        txPayloadLength = snprintf((char*)txPayload, 20, "%c %d", invert_output ? '<' : '>', (int)(input_threshold * 10000));
    } else {
        txPayloadLength = snprintf((char*)txPayload, 20, "* %d %d", (int)(current_input * 10000), current_output);

    }

    ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), txPayload, txPayloadLength);

    if (blue_led_time_to_off) {
        blue_led_time_to_off--;
        if (blue_led_blink) {
            blue = (blue_led_time_to_off & 1) ? LED_ON : LED_OFF;
        }

        if (0 == blue_led_time_to_off) {
            blue_led_blink = false;
            blue = LED_OFF;
        }
    }

    if (green_led_time_to_off) {
        green_led_time_to_off--;
        if (green_led_blink) {
            green = (green_led_time_to_off & 1) ? LED_ON : LED_OFF;
        }

        if (0 == green_led_time_to_off) {
            green_led_blink = false;
            green = LED_OFF;
        }
    }
}
void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason)
{
    ble.startAdvertising();
}
Exemple #15
0
void onDisconnection(const Gap::DisconnectionCallbackParams_t *params) {
  echoer.detach();
  ble.startAdvertising();
}
Exemple #16
0
void echo() {
  ble.updateCharacteristicValue(
      uartServicePtr->getRXCharacteristicHandle(),
      data, len);
}
Exemple #17
0
int main(void)
{
    blue  = LED_ON;
    green = LED_OFF;

#if BUTTON_DOWN
    button.mode(PullDown);
    button.rise(button_wakeup);
#else
    button.mode(PullUp);
    button.fall(button_wakeup);
#endif

    DEBUG("Initialising the nRF51822\n\r");
    ble.init();
    ble.onConnection(connectionCallback);
    ble.onDisconnection(disconnectionCallback);
    ble.onDataWritten(onDataWritten);

    /* setup advertising */
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
                                    (const uint8_t *)BLE_NAME, sizeof(BLE_NAME));

    ble.setAdvertisingInterval(160); /* 100ms; in multiples of 0.625ms. */
    ble.startAdvertising();

    /* Enable over-the-air firmware updates. Instantiating DFUSservice introduces a
     * control characteristic which can be used to trigger the application to
     * handover control to a resident bootloader. */
    DFUService dfu(ble);

    UARTService uartService(ble);
    uartServicePtr = &uartService;

    blue_led_time_to_off = 3000 / TICK_PERIOD_MS;

    Ticker ticker;
    ticker.attach_us(tick, TICK_PERIOD_MS * 1000);

    while (true) {
        if (button_event) {
            int click;

            blue = LED_ON;
            click = button_detect();
            blue = LED_OFF;
            DEBUG("click type: %d\n\r", click);

            button_event = false;

            if (1 == click) {
                single_click_input = current_input;
            } else if (2 == click) {
                double_click_input = current_input;
                green = LED_ON;
                green_led_time_to_off = 1000 / TICK_PERIOD_MS;
            } else if (-1 == click) {
                while (BUTTON_DOWN == button.read()) {

                }
                nrf_delay_us(3000);

                power_down();
            } else {
                continue;
            }

            DEBUG("typical input: %f, %f\n\r", single_click_input, double_click_input);

            threshold_update = 1;
        } else {
            ble.waitForEvent();
        }
    }
}
Exemple #18
0
int main(){
    //pc.wait(1);
    gatt_characteristics[CHARACTERISTIC_LED] =
        new GattCharacteristic(
            nRF51_GATT_CHAR_LED,
            &gatt_char_value[CHARACTERISTIC_LED], 1, 1,
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ |
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE |
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);

    gatt_service = new GattService(nRF51_GATT_SERVICE, gatt_characteristics, CHARACTERISTIC_COUNT);
    //Initialize BLE Device
    ble.init();

    ble.setDeviceName((uint8_t *)DEVICE_NAME);

    // configure our advertising type, payload and interval00
    ble.accumulateAdvertisingPayload(
          GapAdvertisingData::BREDR_NOT_SUPPORTED |
          GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.accumulateAdvertisingPayload(
          GapAdvertisingData::COMPLETE_LOCAL_NAME,
          (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));

    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.setAdvertisingInterval(160); // 100ms

    /*
    led1.write(1);
    led3.write(1);
    led2.write(1);
    led4.write(1);
    */
    for(int i=0; i<10; i++)
        pc.printf("Hello World\n");
    ble.onConnection((Gap::ConnectionEventCallback_t)connectionCallback);
    ble.onDisconnection(disconnectionCallback);
    ble.gattServer().onDataWritten(onDataWritten);

    ble.addService(*gatt_service);

    ble.startAdvertising();

    /* Adding below for scanning */
        ble.setScanParams(500 /* scan interval */, 200 /* scan window */);
        ble.startScan(advertisementCallback);
    /**END OF PART FOR SCANNING**/

    for (;;)
    {
      ble.waitForEvent();
    }
}
Exemple #19
0
void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason)
{
    DEBUG("Disconnected!\n\r");
    DEBUG("Restarting the advertising process\n\r");
    ble.startAdvertising();
}
int main(void)
{
    led1 = 1;

    DEBUG("Initialising the nRF51822\n\r");
    ble.init(); // Initialise the BLE radio

    /* Register callbacks */
    ble.onDisconnection(disconnectionCallback);
    ble.onDataWritten(writeCharCallback);

    //uart = new UARTService(ble);

    /* Setup Advertising */
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
                                     (const uint8_t *)"BLE NOTIF", sizeof("BLE NOTIF") - 1);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
    ble.setAdvertisingInterval(1600); // 1000ms; in multiples of 0.625ms.

    ble.addService(customService);

    ble.startAdvertising();

    while (true) {
        ble.waitForEvent();
    }
}
bool BLEPeripheral::connected(void)
{
    BLEDevice centralBle = BLE.central();
    return centralBle.connected();
}