[
  {
    "path": ".github/ISSUE_TEMPLATE.md",
    "content": "Thank you for opening an issue on an Adafruit Arduino library repository.  To\nimprove the speed of resolution please review the following guidelines and\ncommon troubleshooting steps below before creating the issue:\n\n- **Do not use GitHub issues for troubleshooting projects and issues.**  Instead use\n  the forums at http://forums.adafruit.com to ask questions and troubleshoot why\n  something isn't working as expected.  In many cases the problem is a common issue\n  that you will more quickly receive help from the forum community.  GitHub issues\n  are meant for known defects in the code.  If you don't know if there is a defect\n  in the code then start with troubleshooting on the forum first.\n\n- **If following a tutorial or guide be sure you didn't miss a step.** Carefully\n  check all of the steps and commands to run have been followed.  Consult the\n  forum if you're unsure or have questions about steps in a guide/tutorial.\n\n- **For Arduino projects check these very common issues to ensure they don't apply**:\n\n  - For uploading sketches or communicating with the board make sure you're using\n    a **USB data cable** and **not** a **USB charge-only cable**.  It is sometimes\n    very hard to tell the difference between a data and charge cable!  Try using the\n    cable with other devices or swapping to another cable to confirm it is not\n    the problem.\n\n  - **Be sure you are supplying adequate power to the board.**  Check the specs of\n    your board and plug in an external power supply.  In many cases just\n    plugging a board into your computer is not enough to power it and other\n    peripherals.\n\n  - **Double check all soldering joints and connections.**  Flakey connections\n    cause many mysterious problems.  See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints.\n\n  - **Ensure you are using an official Arduino or Adafruit board.** We can't\n    guarantee a clone board will have the same functionality and work as expected\n    with this code and don't support them.\n\nIf you're sure this issue is a defect in the code and checked the steps above\nplease fill in the following fields to provide enough troubleshooting information.\nYou may delete the guideline and text above to just leave the following details:\n\n- Arduino board:  **INSERT ARDUINO BOARD NAME/TYPE HERE**\n\n- Arduino IDE version (found in Arduino -> About Arduino menu):  **INSERT ARDUINO\n  VERSION HERE**\n\n- List the steps to reproduce the problem below (if possible attach a sketch or\n  copy the sketch code in too): **LIST REPRO STEPS BELOW**\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "Thank you for creating a pull request to contribute to Adafruit's GitHub code!\nBefore you open the request please review the following guidelines and tips to\nhelp it be more easily integrated:\n\n- **Describe the scope of your change--i.e. what the change does and what parts\n  of the code were modified.**  This will help us understand any risks of integrating\n  the code.\n\n- **Describe any known limitations with your change.**  For example if the change\n  doesn't apply to a supported platform of the library please mention it.\n\n- **Please run any tests or examples that can exercise your modified code.**  We\n  strive to not break users of the code and running tests/examples helps with this\n  process.\n\nThank you again for contributing!  We will try to test and integrate the change\nas soon as we can, but be aware we have many GitHub repositories to manage and\ncan't immediately respond to every request.  There is no need to bump or check in\non a pull request (it will clutter the discussion of the request).\n\nAlso don't be worried if the request is closed or not integrated--sometimes the\npriorities of Adafruit's GitHub code (education, ease of use) might not match the\npriorities of the pull request.  Don't fret, the open source community thrives on\nforks and GitHub makes it easy to keep your changes in a forked repo.\n\nAfter reviewing the guidelines above you can delete this text from the pull request.\n"
  },
  {
    "path": "Adafruit_ATParser.cpp",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_ATParser.cpp\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#include \"Adafruit_ATParser.h\"\n\nstatic inline char digit2ascii(uint8_t digit)\n{\n  return ( digit + ((digit) < 10 ? '0' : ('A'-10)) );\n}\n\n/******************************************************************************/\n/*!\n    @brief Constructor\n*/\n/******************************************************************************/\nAdafruit_ATParser::Adafruit_ATParser(void)\n{\n  _mode    = BLUEFRUIT_MODE_COMMAND;\n  _verbose = false;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Read the whole response and check if it ended up with OK.\n    @return true if response is ended with \"OK\". Otherwise it could be \"ERROR\"\n*/\n/******************************************************************************/\nbool Adafruit_ATParser::waitForOK(void)\n{\n  if (_verbose) SerialDebug.print( F(\"\\n<- \") );\n\n  // Use temp buffer to avoid overwrite returned result if any\n  char tempbuf[BLE_BUFSIZE+1];\n\n  while ( readline(tempbuf, BLE_BUFSIZE) ) {\n    if ( strcmp(tempbuf, \"OK\") == 0 ) return true;\n    if ( strcmp(tempbuf, \"ERROR\") == 0 ) return false;\n\n    // Copy to internal buffer if not OK or ERROR\n    strcpy(this->buffer, tempbuf);\n  }\n  return false;\n}\n\n/******************************************************************************/\n/*!\n    @brief\n    @param\n*/\n/******************************************************************************/\nbool Adafruit_ATParser::send_arg_get_resp(int32_t* reply, uint8_t argcount, uint16_t argtype[], uint32_t args[])\n{\n  // Command arguments according to its type\n  for(uint8_t i=0; i<argcount; i++)\n  {\n    // print '=' for WRITE mode\n    if (i==0) print('=');\n\n    switch (argtype[i] & 0xFF00)\n    {\n      case AT_ARGTYPE_STRING:\n        this->print( (char const*) args[i] );\n      break;\n\n      case AT_ARGTYPE_BYTEARRAY:\n      {\n        uint8_t count        = lowByte(argtype[i]);\n        this->printByteArray( (uint8_t const*) args[i], count );\n      }\n      break;\n\n      case AT_ARGTYPE_UINT32:\n        print( (uint32_t) args[i] );\n      break;\n\n      case AT_ARGTYPE_INT32:\n        print( (int32_t) args[i] );\n      break;\n\n      case AT_ARGTYPE_UINT16:\n        print( (uint16_t) args[i] );\n      break;\n\n      case AT_ARGTYPE_INT16:\n        print( (int16_t) args[i] );\n      break;\n\n      case AT_ARGTYPE_UINT8:\n        print( (uint8_t) ((uint32_t)args[i]) );\n      break;\n\n      case AT_ARGTYPE_INT8:\n        print( (int8_t) ((int32_t) args[i]) );\n      break;\n\n      default: break;\n    }\n\n    if (i != argcount-1) print(',');\n  }\n  println(); // execute command\n\n  // parse integer response if required\n  if (reply)\n  {\n    if (_verbose) SerialDebug.print( F(\"\\n<- \") );\n    (*reply) = readline_parseInt();\n  }\n\n  // check OK or ERROR status\n  return waitForOK();\n}\n\n/******************************************************************************/\n/*!\n    @brief\n    @param\n*/\n/******************************************************************************/\nbool Adafruit_ATParser::atcommand_full(const char cmd[], int32_t* reply, uint8_t argcount, uint16_t argtype[], uint32_t args[])\n{\n  bool result;\n  uint8_t current_mode = _mode;\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // Execute command with parameter and get response\n  print(cmd);\n  result = this->send_arg_get_resp(reply, argcount, argtype, args);\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n\n  return result;\n}\n\n/******************************************************************************/\n/*!\n    @brief\n    @param\n*/\n/******************************************************************************/\nbool Adafruit_ATParser::atcommand_full(const __FlashStringHelper *cmd, int32_t* reply, uint8_t argcount, uint16_t argtype[], uint32_t args[])\n{\n  bool result;\n  uint8_t current_mode = _mode;\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // Execute command with parameter and get response\n  print(cmd);\n  result = this->send_arg_get_resp(reply, argcount, argtype, args);\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n\n  return result;\n}\n\n/******************************************************************************/\n/*!\n    @brief Send an AT command and get multiline string response into\n           user-provided buffer.\n\n    @param[in] cmd Command\n    @param[in] buf Provided buffer\n    @param[in] bufsize buffer size\n    @param[in] timeout timeout in milliseconds\n\n*/\n/******************************************************************************/\nuint16_t Adafruit_ATParser::atcommandStrReply(const char cmd[], char* buf, uint16_t bufsize, uint16_t timeout)\n{\n  uint16_t result_bytes;\n  uint8_t current_mode = _mode;\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // Execute command with parameter and get response\n  println(cmd);\n  result_bytes = this->readline(buf, bufsize, timeout, true);\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n\n  return result_bytes;\n}\n\nuint16_t Adafruit_ATParser::atcommandStrReply(const __FlashStringHelper *cmd, char* buf, uint16_t bufsize, uint16_t timeout)\n{\n  uint16_t result_bytes;\n  uint8_t current_mode = _mode;\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // Execute command with parameter and get response\n  println(cmd);\n  result_bytes = this->readline(buf, bufsize, timeout, true);\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n\n  return result_bytes;\n}\n\n/******************************************************************************/\n/*!\n    @brief Send an AT command and process a multiline string response\n           by a user-provided callback executed per line.\n\n    @param[in] cmd Command\n    @param[in] linebuf Buffer to hold text of each line at a time\n    @param[in] bufsize buffer size\n    @param[in] timeout timeout in milliseconds to wait for each line\n    @param[in] line_callback function called for each line\n    @param[in] callback_data user-provided state for callback\n\n*/\n/******************************************************************************/\nuint16_t Adafruit_ATParser::atcommandStrReplyPerLine(\n    const char cmd[],\n    char* linebuf, uint16_t bufsize, uint16_t timeout,\n    void (*line_callback)(void*, char*, uint16_t), void* callback_data)\n{\n  uint16_t result_bytes;\n  uint8_t current_mode = _mode;\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // Execute command with parameter, get response, process line-by-line\n  println(cmd);\n  do {\n    result_bytes = this->readline(linebuf, bufsize, timeout, false);\n    if (0 == strncmp(linebuf, \"OK\", 2) ||\n        0 == strncmp(linebuf, \"ERROR\", 5)) break;\n    (*line_callback)(callback_data, linebuf, result_bytes);\n  } while (result_bytes > 0);\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n\n  return result_bytes;\n}\n\nuint16_t Adafruit_ATParser::atcommandStrReplyPerLine(\n    const __FlashStringHelper *cmd,\n    char* linebuf, uint16_t bufsize, uint16_t timeout,\n    void (*line_callback)(void*, char*, uint16_t), void* callback_data)\n{\n  uint16_t result_bytes;\n  uint8_t current_mode = _mode;\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // Execute command with parameter, get response, process line-by-line\n  println(cmd);\n  do {\n    result_bytes = this->readline(linebuf, bufsize, timeout, false);\n    if (0 == strncmp(linebuf, \"OK\", 2) ||\n        0 == strncmp(linebuf, \"ERROR\", 5)) break;\n    (*line_callback)(callback_data, linebuf, result_bytes);\n  } while (result_bytes > 0);\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n\n  return result_bytes;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Get a line of response data (see \\ref readline) and try to interpret\n            it to an integer number. If the number is prefix with '0x', it will\n            be interpreted as hex number. This function also drop the rest of\n            data to the end of the line.\n*/\n/******************************************************************************/\nint32_t Adafruit_ATParser::readline_parseInt(void)\n{\n  uint16_t len = readline();\n  if (len == 0) return 0;\n\n  // also parsed hex number e.g 0xADAF\n  int32_t val = strtol(buffer, NULL, 0);\n\n  return val;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Get a line of response data into provided buffer.\n\n    @param[in] buf Provided buffer\n    @param[in] bufsize buffer size\n    @param[in] timeout timeout in milliseconds\n    @param[in] multiline Read multiple line if true, otherwise only read 1 line\n\n    @note '\\r' and '\\n' are not included in returned buffer.\n*/\n/******************************************************************************/\nuint16_t Adafruit_ATParser::readline(char * buf, uint16_t bufsize, uint16_t timeout, boolean multiline)\n{\n  uint16_t replyidx = 0;\n\n  while (timeout--) {\n    while(available()) {\n      char c = read();\n      //SerialDebug.println(c);\n\n      if (c == '\\r') continue;\n\n      if (c == '\\n') {\n        // the first '\\n' is ignored\n        if (replyidx == 0) continue;\n\n        if (!multiline) {\n          timeout = 0;\n          break;\n        }\n      }\n      buf[replyidx] = c;\n      replyidx++;\n\n      // Buffer is full\n      if (replyidx >= bufsize) {\n        //if (_verbose) { SerialDebug.println(\"*overflow*\"); }  // for my debuggin' only!\n        timeout = 0;\n        break;\n      }\n    }\n\n    // delay if needed\n    if (timeout) delay(1);\n  }\n\n  buf[replyidx] = 0;  // null term\n\n  // Print out if is verbose\n  if (_verbose && replyidx > 0)\n  {\n    SerialDebug.print(buf);\n    if (replyidx < bufsize) SerialDebug.println();\n  }\n\n  return replyidx;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Get raw binary data to internal buffer, only stop when encountering\n            either \"OK\\r\\n\" or \"ERROR\\r\\n\" or timed out. Buffer does not contain\n            OK or ERROR\n\n    @param[in] timeout\n               Timeout for each read() operation\n\n    @return    The number of bytes read excluding OK, ERROR ending.\n               0 usually means error\n*/\n/******************************************************************************/\nuint16_t Adafruit_ATParser::readraw(uint16_t timeout)\n{\n  uint16_t replyidx = 0;\n\n  while (timeout--) {\n    while(available()) {\n      char c =  read();\n\n      if (c == '\\n')\n      {\n        // done if ends with \"OK\\r\\n\"\n        if ( (replyidx >= 3) && !strncmp(this->buffer + replyidx-3, \"OK\\r\", 3) )\n        {\n          replyidx -= 3; // chop OK\\r\n          timeout = 0;\n          break;\n        }\n        // done if ends with \"ERROR\\r\\n\"\n        else if ((replyidx >= 6) && !strncmp(this->buffer + replyidx-6, \"ERROR\\r\", 6))\n        {\n          replyidx -= 6; // chop ERROR\\r\n          timeout = 0;\n          break;\n        }\n      }\n\n      this->buffer[replyidx] = c;\n      replyidx++;\n\n      // Buffer is full\n      if (replyidx >= BLE_BUFSIZE) {\n        //if (_verbose) { SerialDebug.println(\"*overflow*\"); }  // for my debuggin' only!\n        timeout = 0;\n        break;\n      }\n    }\n\n    if (timeout == 0) break;\n    delay(1);\n  }\n  this->buffer[replyidx] = 0;  // null term\n\n  // Print out if is verbose\n//  if (_verbose && replyidx > 0)\n//  {\n//    SerialDebug.print(buffer);\n//    if (replyidx < BLE_BUFSIZE) SerialDebug.println();\n//  }\n\n  return replyidx;\n}\n\n/******************************************************************************/\n/*!\n    @brief Print a buffer to BYTE ARRAY format e.g 11-22-33-44-55\n    @param bytearray buffer to print\n    @param size number of byte\n    @return number of printed characters\n*/\n/******************************************************************************/\nint Adafruit_ATParser::printByteArray(uint8_t const bytearray[], int size)\n{\n  while(size--)\n  {\n    uint8_t byte = *bytearray++;\n    write( digit2ascii((byte & 0xF0) >> 4) );\n    write( digit2ascii(byte & 0x0F) );\n    if ( size!=0 ) write('-');\n  }\n\n  return (size*3) - 1;\n}\n"
  },
  {
    "path": "Adafruit_ATParser.h",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_ATParser.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#ifndef _ADAFRUIT_ATPARSER_H_\n#define _ADAFRUIT_ATPARSER_H_\n\n#include <Arduino.h>\n#include \"utility/sdep.h\"\n\n// Class to facilitate sending AT Command and check response\n\n#define BLUEFRUIT_MODE_COMMAND   HIGH\n#define BLUEFRUIT_MODE_DATA      LOW\n#define BLE_BUFSIZE              4*SDEP_MAX_PACKETSIZE\n\n\n#if defined(ARDUINO_SAMD_ZERO) && defined(SERIAL_PORT_USBVIRTUAL)\n#define SerialDebug SERIAL_PORT_USBVIRTUAL\n#else\n#define SerialDebug Serial\n#endif\n\n// High byte is type, Low byte is datacount\n// datacount is needed when passing ByteArray argument\nenum\n{\n  AT_ARGTYPE_STRING    = 0x0100,\n  AT_ARGTYPE_BYTEARRAY = 0x0200,\n  AT_ARGTYPE_INT32     = 0x0300,\n  AT_ARGTYPE_UINT32    = 0x0400,\n  AT_ARGTYPE_INT16     = 0x0500,\n  AT_ARGTYPE_UINT16    = 0x0600,\n  AT_ARGTYPE_INT8      = 0x0700,\n  AT_ARGTYPE_UINT8     = 0x0800,\n};\n\nclass Adafruit_ATParser : public Stream\n{\nprotected:\n  uint8_t _mode;\n  bool     _verbose;\n\n  // internal function\n  bool send_arg_get_resp(int32_t* reply, uint8_t argcount, uint16_t argtype[], uint32_t args[]);\n\npublic:\n  Adafruit_ATParser(void);\n\n  char buffer[BLE_BUFSIZE+1];\n\n  uint8_t      getMode(void) { return _mode; }\n  virtual bool setMode(uint8_t mode) = 0;\n\n  // Auto print out TX & RX data to normal Serial\n  void verbose(bool enable) { _verbose = enable; }\n\n  bool atcommand_full(const char cmd[]               , int32_t* reply, uint8_t argcount, uint16_t argtype[], uint32_t args[]);\n  bool atcommand_full(const __FlashStringHelper *cmd , int32_t* reply, uint8_t argcount, uint16_t argtype[], uint32_t args[]);\n\n  //--------------------------------------------------------------------+\n  // Without Reply\n  //--------------------------------------------------------------------+\n  bool atcommand(const char cmd[]               ) { return this->atcommand_full(cmd, NULL, 0, NULL, NULL); }\n  bool atcommand(const __FlashStringHelper *cmd ) { return this->atcommand_full(cmd, NULL, 0, NULL, NULL); }\n\n  //------------- One integer argument -------------//\n  bool atcommand(const char cmd[]              , int32_t para1)\n  {\n    uint16_t type[] = { AT_ARGTYPE_INT32 };\n    uint32_t args[] = { (uint32_t) para1 };\n    return this->atcommand_full(cmd, NULL, 1, type, args);\n  }\n\n  bool atcommand(const __FlashStringHelper *cmd, int32_t para1)\n  {\n    uint16_t type[] = { AT_ARGTYPE_INT32 };\n    uint32_t args[] = { (uint32_t) para1 };\n    return this->atcommand_full(cmd, NULL, 1, type, args);\n  }\n\n  //------------- Two integer arguments -------------//\n  bool atcommand(const char cmd[]              , int32_t para1, int32_t para2)\n  {\n    uint16_t type[] = { AT_ARGTYPE_INT32, AT_ARGTYPE_INT32 };\n    uint32_t args[] = { (uint32_t) para1, (uint32_t) para2 };\n    return this->atcommand_full(cmd, NULL, 2, type, args);\n  }\n\n  bool atcommand(const __FlashStringHelper *cmd, int32_t para1, int32_t para2)\n  {\n    uint16_t type[] = { AT_ARGTYPE_INT32, AT_ARGTYPE_INT32 };\n    uint32_t args[] = { (uint32_t) para1, (uint32_t) para2 };\n    return this->atcommand_full(cmd, NULL, 2, type, args);\n  }\n\n  //------------- One ByteArray arguments -------------//\n  bool atcommand(const char cmd[]              , const uint8_t bytearray[], uint16_t count)\n  {\n    uint16_t type[] = { (uint16_t) (AT_ARGTYPE_BYTEARRAY+count) };\n    uint32_t args[] = { (uint32_t) bytearray };\n    return this->atcommand_full(cmd, NULL, 1, type, args);\n  }\n\n  bool atcommand(const __FlashStringHelper *cmd, const uint8_t bytearray[], uint16_t count)\n  {\n    uint16_t type[] = { (uint16_t) (AT_ARGTYPE_BYTEARRAY+count) };\n    uint32_t args[] = { (uint32_t) bytearray };\n    return this->atcommand_full(cmd, NULL, 1, type, args);\n  }\n\n  //------------- One String argument -------------//\n  bool atcommand(const char cmd[]              , const char* str)\n  {\n    uint16_t type[] = { AT_ARGTYPE_STRING };\n    uint32_t args[] = { (uint32_t) str };\n    return this->atcommand_full(cmd, NULL, 1, type, args);\n  }\n\n  bool atcommand(const __FlashStringHelper *cmd, const char* str)\n  {\n    uint16_t type[] = { AT_ARGTYPE_STRING };\n    uint32_t args[] = { (uint32_t) str };\n    return this->atcommand_full(cmd, NULL, 1, type, args);\n  }\n\n  //--------------------------------------------------------------------+\n  // With Reply\n  //--------------------------------------------------------------------+\n  bool atcommandIntReply(const char cmd[], int32_t* reply)               { return this->atcommand_full(cmd, reply, 0, NULL, NULL); }\n  bool atcommandIntReply(const __FlashStringHelper *cmd, int32_t* reply) { return this->atcommand_full(cmd, reply, 0, NULL, NULL); }\n\n  uint16_t atcommandStrReply(const char cmd[], char* buf, uint16_t bufsize, uint16_t timeout);\n  uint16_t atcommandStrReply(const __FlashStringHelper *cmd, char* buf, uint16_t bufsize, uint16_t timeout);\n\n  uint16_t atcommandStrReplyPerLine(const char cmd[], char* linebuf, uint16_t bufsize, uint16_t timeout, void (*line_callback)(void*, char*, uint16_t), void* callback_data);\n  uint16_t atcommandStrReplyPerLine(const __FlashStringHelper *cmd, char* linebuf, uint16_t bufsize, uint16_t timeout, void (*line_callback)(void*, char*, uint16_t), void* callback_data);\n\n\n\n  //------------- One integer argument -------------//\n  bool atcommandIntReply(const char cmd[]              , int32_t* reply, int32_t para1)\n  {\n    uint16_t type[] = { AT_ARGTYPE_INT32 };\n    uint32_t args[] = { (uint32_t) para1 };\n    return this->atcommand_full(cmd, reply, 1, type, args);\n  }\n\n  bool atcommandIntReply(const __FlashStringHelper *cmd, int32_t* reply, int32_t para1)\n  {\n    uint16_t type[] = { AT_ARGTYPE_INT32 };\n    uint32_t args[] = { (uint32_t) para1 };\n    return this->atcommand_full(cmd, reply, 1, type, args);\n  }\n\n  //------------- Two integer arguments -------------//\n  bool atcommandIntReply(const char cmd[]              , int32_t* reply, int32_t para1, int32_t para2)\n  {\n    uint16_t type[] = { AT_ARGTYPE_INT32, AT_ARGTYPE_INT32 };\n    uint32_t args[] = { (uint32_t) para1, (uint32_t) para2 };\n    return this->atcommand_full(cmd, reply, 2, type, args);\n  }\n\n  bool atcommandIntReply(const __FlashStringHelper *cmd, int32_t* reply, int32_t para1, int32_t para2)\n  {\n    uint16_t type[] = { AT_ARGTYPE_INT32, AT_ARGTYPE_INT32 };\n    uint32_t args[] = { (uint32_t) para1, (uint32_t) para2 };\n    return this->atcommand_full(cmd, reply, 2, type, args);\n  }\n\n  //------------- One ByteArray arguments -------------//\n  bool atcommandIntReply(const char cmd[]              , int32_t* reply, const uint8_t bytearray[], uint16_t count)\n  {\n    uint16_t type[] = { (uint16_t) (AT_ARGTYPE_BYTEARRAY+count) };\n    uint32_t args[] = { (uint32_t) bytearray };\n    return this->atcommand_full(cmd, reply, 1, type, args);\n  }\n\n  bool atcommandIntReply(const __FlashStringHelper *cmd, int32_t* reply, const uint8_t bytearray[], uint16_t count)\n  {\n    uint16_t type[] = { (uint16_t) (AT_ARGTYPE_BYTEARRAY+count) };\n    uint32_t args[] = { (uint32_t) bytearray };\n    return this->atcommand_full(cmd, reply, 1, type, args);\n  }\n\n  //------------- One String argument -------------//\n  bool atcommandIntReply(const char cmd[]              , int32_t* reply, const char* str)\n  {\n    uint16_t type[] = { AT_ARGTYPE_STRING };\n    uint32_t args[] = { (uint32_t) str };\n    return this->atcommand_full(cmd, reply, 1, type, args);\n  }\n\n  bool atcommandIntReply(const __FlashStringHelper *cmd, int32_t* reply, const char* str)\n  {\n    uint16_t type[] = { AT_ARGTYPE_STRING };\n    uint32_t args[] = { (uint32_t) str };\n    return this->atcommand_full(cmd, reply, 1, type, args);\n  }\n\n  //--------------------------------------------------------------------+\n  // RESPONSE PROCESSING\n  //--------------------------------------------------------------------+\n  bool waitForOK(void);\n\n  // Read one line of response into internal buffer TODO use below API\n\n  // Read one line of response into provided buffer\n  uint16_t readline(char    * buf, uint16_t bufsize, uint16_t timeout, boolean multiline = false);\n  uint16_t readline(uint8_t * buf, uint16_t bufsize, uint16_t timeout, boolean multiline = false)\n  {\n    return readline( (char*) buf, bufsize, timeout, multiline );\n  }\n\n  uint16_t readline(char    * buf, uint16_t bufsize) { return readline(buf, bufsize, _timeout, false); }\n  uint16_t readline(uint8_t * buf, uint16_t bufsize) { return readline(buf, bufsize, _timeout, false); }\n\n  uint16_t readline(uint16_t timeout, boolean multiline = false)\n  {\n    return readline(this->buffer, BLE_BUFSIZE, timeout, multiline);\n  }\n\n  uint16_t readline(void)\n  {\n    return this->readline(this->buffer, BLE_BUFSIZE, _timeout, false);\n  }\n\n\n  // read one line and convert the string to integer number\n  int32_t readline_parseInt(void);\n\n  uint16_t readraw(uint16_t timeout);\n  uint16_t readraw(void)\n  {\n    return readraw(_timeout);\n  }\n\n  //--------------------------------------------------------------------+\n  // HELPER\n  //--------------------------------------------------------------------+\n  int printByteArray(uint8_t const bytearray[], int size);\n};\n\n#endif /* _ADAFRUIT_ATPARSER_H_ */\n"
  },
  {
    "path": "Adafruit_BLE.cpp",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BLE.c\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2014, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BLEMIDI.h\"\n\n#ifndef min\n  #define min(a,b) ((a) < (b) ? (a) : (b))\n#endif\n\nenum {\n  EVENT_SYSTEM_CONNECT     = 0,\n  EVENT_SYSTEM_DISCONNECT  = 1,\n\n  EVENT_SYSTEM_BLE_UART_RX = 8,\n  // 9 reserved\n\n  EVENT_SYSTEM_BLE_MIDI_RX = 10,\n  //  11 reserved\n};\n\nenum {\n  NVM_USERDATA_SIZE = 256\n};\n\n/******************************************************************************/\n/*!\n    @brief  Constructor\n*/\n/******************************************************************************/\nAdafruit_BLE::Adafruit_BLE(void)\n{\n  _timeout = BLE_DEFAULT_TIMEOUT;\n\n  _reset_started_timestamp = 0;\n\n  _disconnect_callback  = NULL;\n  _connect_callback     = NULL;\n  _ble_uart_rx_callback = NULL;\n  _ble_midi_rx_callback = NULL;\n  _ble_gatt_rx_callback = NULL;\n}\n\n/******************************************************************************/\n/*!\n    @brief Helper to install callback\n    @param\n*/\n/******************************************************************************/\nvoid Adafruit_BLE::install_callback(bool enable, int8_t system_id, int8_t gatts_id)\n{\n  uint8_t current_mode = _mode;\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  print( enable ?  F(\"AT+EVENTENABLE=0x\") : F(\"AT+EVENTDISABLE=0x\") );\n  print( (system_id < 0) ? 0 : bit(system_id), HEX );\n\n  if ( gatts_id >= 0 )\n  {\n    print( F(\",0x\") );\n    println( bit(gatts_id), HEX );\n  }\n\n  println();\n\n  waitForOK();\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n}\n\n/******************************************************************************/\n/*!\n    @brief  Performs a system reset using AT command\n    @param blocking blocking until bluefruit is ready, will take 1 second mostly\n*/\n/******************************************************************************/\nbool Adafruit_BLE::reset(boolean blocking)\n{\n  bool isOK;\n  // println();\n  for (uint8_t t=0; t < 5; t++) {\n    isOK = atcommand(F(\"ATZ\"));\n\n    if (isOK) break;\n  }\n\n  if (! isOK) {\n    // ok we're going to get desperate\n    delay(50);\n    setMode(BLUEFRUIT_MODE_COMMAND);\n    delay(50);\n    \n    for (uint8_t t=0; t < 5; t++) {\n      isOK = atcommand(F(\"ATZ\"));\n      \n      if (isOK) break;\n    }\n\n    if (!isOK) return false;\n  }\n\n  _reset_started_timestamp = millis();\n\n  // Bluefruit need 1 second to reboot\n  if (blocking)\n  {\n    delay(1000);\n  }\n\n  // flush all left over\n  flush();\n\n  return isOK;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Performs a factory reset\n*/\n/******************************************************************************/\nbool Adafruit_BLE::factoryReset(boolean blocking)\n{\n  println( F(\"AT+FACTORYRESET\") );\n  bool isOK = waitForOK();\n\n  _reset_started_timestamp = millis();\n\n  // Bluefruit need 1 second to reboot\n  if (blocking)\n  {\n    delay(1000);\n  }\n\n  // flush all left over\n  flush();\n\n  return isOK;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Check if the reset process is completed, should be used if user\n    reset Bluefruit with non-blocking aka reset(false)\n*/\n/******************************************************************************/\nbool Adafruit_BLE::resetCompleted(void)\n{\n  return millis() > (_reset_started_timestamp + 1000);\n}\n\n/******************************************************************************/\n/*!\n    @brief  Enable or disable AT Command echo from Bluefruit\n\n    @parma[in] enable\n               true to enable (default), false to disable\n*/\n/******************************************************************************/\nbool Adafruit_BLE::echo(bool enable)\n{\n  return atcommand(F(\"ATE\"), (int32_t) enable);\n}\n\n/******************************************************************************/\n/*!\n    @brief  Check connection state, returns true is connected!\n*/\n/******************************************************************************/\nbool Adafruit_BLE::isConnected(void)\n{\n  int32_t connected = 0;\n  atcommandIntReply(F(\"AT+GAPGETCONN\"), &connected);\n  return connected;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Disconnect if currently connected\n*/\n/******************************************************************************/\nvoid Adafruit_BLE::disconnect(void)\n{\n  atcommand( F(\"AT+GAPDISCONNECT\") );\n}\n\n/******************************************************************************/\n/*!\n    @brief  Print Bluefruit's information retrieved by ATI command\n*/\n/******************************************************************************/\nvoid Adafruit_BLE::info(void)\n{\n  uint8_t current_mode = _mode;\n\n  bool v = _verbose;\n  _verbose = false;\n\n  SerialDebug.println(F(\"----------------\"));\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  println(F(\"ATI\"));\n\n  while ( readline() ) {\n    if ( !strcmp(buffer, \"OK\") || !strcmp(buffer, \"ERROR\")  ) break;\n    SerialDebug.println(buffer);\n  }\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n\n  SerialDebug.println(F(\"----------------\"));\n\n  _verbose = v;\n}\n\n/**************************************************************************/\n/*!\n    @brief  Checks if firmware is equal or later than specified version\n*/\n/**************************************************************************/\nbool Adafruit_BLE::isVersionAtLeast(const char * versionString)\n{\n  uint8_t current_mode = _mode;\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // requesting version number\n  println(F(\"ATI=4\"));\n\n  readline();\n  bool result = ( strcmp(buffer, versionString) >= 0 );\n  waitForOK();\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n\n  return result;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Get (multiple) lines of response data into internal buffer.\n\n    @param[in] period_ms\n               period in milliseconds between each event scanning\n    @return    None\n*/\n/******************************************************************************/\nvoid Adafruit_BLE::update(uint32_t period_ms)\n{\n  static TimeoutTimer tt;\n\n  if ( tt.expired() )\n  {\n    tt.set(period_ms);\n\n    bool v = _verbose;\n    _verbose = false;\n\n    uint8_t current_mode = _mode;\n\n    // switch mode if necessary to execute command\n    if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n    println( F(\"AT+EVENTSTATUS\") );\n    readline();\n    waitForOK();\n\n    // parse event status system_event, gatts_event\n    uint8_t tempbuf[BLE_BUFSIZE+1];\n    uint32_t system_event, gatts_event;\n    char * p_comma = NULL;\n\n    system_event = strtoul(this->buffer, &p_comma, 16);\n    gatts_event  = strtoul(p_comma+1, NULL, 16);\n\n    //--------------------------------------------------------------------+\n    // System Event\n    //--------------------------------------------------------------------+\n    if ( this->_connect_callback    && bitRead(system_event, EVENT_SYSTEM_CONNECT   ) ) this->_connect_callback();\n    if ( this->_disconnect_callback && bitRead(system_event, EVENT_SYSTEM_DISCONNECT) ) this->_disconnect_callback();\n\n    if ( this->_ble_uart_rx_callback && bitRead(system_event, EVENT_SYSTEM_BLE_UART_RX) )\n    {\n      // _verbose = true;\n      println( F(\"AT+BLEUARTRX\") );\n      uint16_t len = readline(tempbuf, BLE_BUFSIZE);\n      waitForOK();\n\n      this->_ble_uart_rx_callback( (char*) tempbuf, len);\n    }\n\n    if ( this->_ble_midi_rx_callback && bitRead(system_event, EVENT_SYSTEM_BLE_MIDI_RX) )\n    {\n//      _verbose = true;\n      while(1)\n      {\n        // use RAW command version\n        println( F(\"AT+BLEMIDIRXRAW\") );\n\n        // readraw swallow OK/ERROR already\n        uint16_t len = readraw();\n\n        // break if there is no more MIDI event\n        if ( len == 0 ) break;\n\n        // copy to internal buffer for other usage !\n        memcpy(tempbuf, this->buffer, len);\n\n        Adafruit_BLEMIDI::processRxCallback(tempbuf, len, this->_ble_midi_rx_callback);\n      }\n    }\n\n    //--------------------------------------------------------------------+\n    // Gatt Event\n    //--------------------------------------------------------------------+\n    if ( this->_ble_gatt_rx_callback && gatts_event )\n    {\n//      _verbose = true;\n      for(uint8_t charid=1; charid < 30; charid++)\n      {\n        if ( bitRead(gatts_event, charid-1) )\n        {\n          print( F(\"AT+GATTCHARRAW=\") ); // use RAW command version\n          println(charid);\n\n          uint16_t len = readraw(); // readraw swallow OK/ERROR already\n          memcpy(tempbuf, this->buffer, len);\n\n          this->_ble_gatt_rx_callback(charid, tempbuf, len);\n        }\n      }\n    }\n\n    // switch back if necessary\n    if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n\n    _verbose = v;\n  }\n}\n\n/******************************************************************************/\n/*!\n    @brief Set custom ADV data packet\n    @param\n*/\n/******************************************************************************/\nbool Adafruit_BLE::setAdvData(uint8_t advdata[], uint8_t size)\n{\n  return this->atcommand(F(\"AT+GAPSETADVDATA\"), advdata, size);\n}\n\n/******************************************************************************/\n/*!\n    @brief Save user information to NVM section, current size limit is 256 bytes\n    @param data buffer holding data\n    @param size number of bytes\n    @param offset relative offset in the NVM section\n*/\n/******************************************************************************/\nbool Adafruit_BLE::writeNVM(uint16_t offset, uint8_t const data[], uint16_t size)\n{\n  VERIFY_(offset + size <= NVM_USERDATA_SIZE );\n\n  uint16_t type[] = { AT_ARGTYPE_UINT16, AT_ARGTYPE_UINT8, (uint16_t) (AT_ARGTYPE_BYTEARRAY + size) };\n  uint32_t args[] = { offset, BLE_DATATYPE_BYTEARRAY, (uint32_t) data };\n\n  return this->atcommand_full(F(\"AT+NVMWRITE\"), NULL, 3, type, args);\n}\n\n/******************************************************************************/\n/*!\n    @brief Save String to NVM section, current size limit is 256 bytes\n    @param data buffer holding data\n    @param size number of bytes\n    @param offset relative offset in the NVM section\n*/\n/******************************************************************************/\nbool Adafruit_BLE::writeNVM(uint16_t offset, char const* str)\n{\n  VERIFY_(offset + strlen(str) <= NVM_USERDATA_SIZE );\n\n  uint16_t type[] = { AT_ARGTYPE_UINT16, AT_ARGTYPE_UINT8, AT_ARGTYPE_STRING };\n  uint32_t args[] = { offset, BLE_DATATYPE_STRING, (uint32_t) str };\n\n  return this->atcommand_full(F(\"AT+NVMWRITE\"), NULL, 3, type, args);\n}\n\n/******************************************************************************/\n/*!\n    @brief Save an 32-bit number to NVM\n    @param number Number to be saved\n    @param offset relative offset in the NVM section\n*/\n/******************************************************************************/\nbool Adafruit_BLE::writeNVM(uint16_t offset, int32_t number)\n{\n  VERIFY_(offset + 4 <= NVM_USERDATA_SIZE );\n\n  uint16_t type[] = { AT_ARGTYPE_UINT16, AT_ARGTYPE_UINT8, AT_ARGTYPE_INT32 };\n  uint32_t args[] = { offset, BLE_DATATYPE_INTEGER, (uint32_t) number };\n\n  return this->atcommand_full(F(\"AT+NVMWRITE\"), NULL, 3, type, args);\n}\n\n/******************************************************************************/\n/*!\n    @brief Read an number of bytes from NVM at offset to buffer\n    @param\n*/\n/******************************************************************************/\nbool Adafruit_BLE::readNVM(uint16_t offset, uint8_t data[], uint16_t size)\n{\n  VERIFY_(offset < NVM_USERDATA_SIZE);\n\n  uint8_t current_mode = _mode;\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // use RAW command version\n  print( F(\"AT+NVMREADRAW=\") );\n  print(offset);\n\n  print(',');\n  println(size);\n\n  uint16_t len = readraw(); // readraw swallow OK/ERROR already\n\n  // Check for an error reading\n  if ( len != size ) return false;\n\n  // skip if NULL is entered\n  if (data) memcpy(data, this->buffer, min(size, BLE_BUFSIZE));\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief Read a string from NVM at offset to buffer\n    @param\n*/\n/******************************************************************************/\nbool Adafruit_BLE::readNVM(uint16_t offset, char* str, uint16_t size)\n{\n  VERIFY_(offset < NVM_USERDATA_SIZE);\n\n  uint16_t type[] = { AT_ARGTYPE_UINT16, AT_ARGTYPE_UINT16, AT_ARGTYPE_UINT8 };\n  uint32_t args[] = { offset, size, BLE_DATATYPE_STRING};\n\n  bool isOK =  this->atcommand_full(F(\"AT+NVMREAD\"), NULL, 3, type, args);\n\n  // skip if NULL is entered\n  if ( isOK && str ) strncpy(str, this->buffer, min(size, BLE_BUFSIZE));\n\n  return isOK;\n}\n\n/******************************************************************************/\n/*!\n    @brief Read an 32-bit number from NVM\n    @param\n*/\n/******************************************************************************/\nbool Adafruit_BLE::readNVM(uint16_t offset, int32_t* number)\n{\n  return this->readNVM(offset, (uint8_t*)number, 4);\n}\n\n/**\n *\n * @param buffer\n * @param size\n * @return\n */\nint Adafruit_BLE::writeBLEUart(uint8_t const * buffer, int size)\n{\n  uint8_t current_mode = _mode;\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_COMMAND ) setMode(BLUEFRUIT_MODE_DATA);\n\n  size_t n = write(buffer, size);\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_COMMAND ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  return n;\n}\n\n/**\n *\n * @param buffer\n * @param size\n * @return\n */\nint  Adafruit_BLE::readBLEUart(uint8_t* buffer, int size)\n{\n  uint8_t current_mode = _mode;\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_COMMAND ) setMode(BLUEFRUIT_MODE_DATA);\n\n  size_t n = readBytes(buffer, size);\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_COMMAND ) setMode(BLUEFRUIT_MODE_COMMAND);\n\n  return n;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Set handle for connect callback\n\n    @param[in] fp function pointer, NULL will discard callback\n*/\n/******************************************************************************/\nvoid Adafruit_BLE::setConnectCallback( void (*fp) (void) )\n{\n  this->_connect_callback = fp;\n  install_callback(fp != NULL, EVENT_SYSTEM_CONNECT, -1);\n}\n\n/******************************************************************************/\n/*!\n    @brief  Set handle for disconnection callback\n\n    @param[in] fp function pointer, NULL will discard callback\n*/\n/******************************************************************************/\nvoid Adafruit_BLE::setDisconnectCallback( void (*fp) (void) )\n{\n  this->_disconnect_callback = fp;\n  install_callback(fp != NULL, EVENT_SYSTEM_DISCONNECT, -1);\n}\n\n/******************************************************************************/\n/*!\n    @brief  Set handle for BLE Uart Rx callback\n\n    @param[in] fp function pointer, NULL will discard callback\n*/\n/******************************************************************************/\nvoid Adafruit_BLE::setBleUartRxCallback( void (*fp) (char data[], uint16_t len) )\n{\n  this->_ble_uart_rx_callback = fp;\n  install_callback(fp != NULL, EVENT_SYSTEM_BLE_UART_RX, -1);\n}\n\n/******************************************************************************/\n/*!\n    @brief  Set handle for BLE MIDI Rx callback\n\n    @param[in] fp function pointer, NULL will discard callback\n*/\n/******************************************************************************/\nvoid Adafruit_BLE::setBleMidiRxCallback( midiRxCallback_t fp )\n{\n  this->_ble_midi_rx_callback = fp;\n  install_callback(fp != NULL, EVENT_SYSTEM_BLE_MIDI_RX, -1);\n}\n\n/******************************************************************************/\n/*!\n    @brief  Set handle for BLE Gatt Rx callback\n\n    @param[in] fp function pointer, NULL will discard callback\n*/\n/******************************************************************************/\nvoid Adafruit_BLE::setBleGattRxCallback(int32_t chars_idx,  void (*fp) (int32_t, uint8_t[], uint16_t) )\n{\n  if ( chars_idx == 0) return;\n\n  this->_ble_gatt_rx_callback = fp;\n  install_callback(fp != NULL, -1, chars_idx-1);\n}\n\n"
  },
  {
    "path": "Adafruit_BLE.h",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BLE.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2014, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#ifndef _Adafruit_BLE_H_\n#define _Adafruit_BLE_H_\n\n#include <stdint.h>\n#include <Arduino.h>\n#include \"utility/common_header.h\"\n#include \"utility/errors.h\"\n#include \"utility/TimeoutTimer.h\"\n#include \"Adafruit_ATParser.h\"\n\n#define BLE_DEFAULT_TIMEOUT      250\n\nenum BLEDataType_t\n{\n  BLE_DATATYPE_AUTO = 0,\n  BLE_DATATYPE_STRING,\n  BLE_DATATYPE_BYTEARRAY,\n  BLE_DATATYPE_INTEGER,\n};\n\n\nclass Adafruit_BLE : public Adafruit_ATParser\n{\n  protected:\n    enum\n    {\n      BLUEFRUIT_TRANSPORT_INVALID,\n      BLUEFRUIT_TRANSPORT_HWUART,\n      BLUEFRUIT_TRANSPORT_SWUART,\n      BLUEFRUIT_TRANSPORT_HWSPI,\n      BLUEFRUIT_TRANSPORT_SWSPI,\n    };\n\n//    uint8_t  _mode;\n//    uint16_t _timeout;\n    uint8_t  _physical_transport;\n    uint32_t _reset_started_timestamp;\n\n  public:\n    typedef void (*midiRxCallback_t) (uint16_t timestamp, uint8_t status, uint8_t byte1, uint8_t byte2);\n\n    // Constructor\n    Adafruit_BLE(void);\n\n    // Functions implemented in this base class\n    bool reset(boolean blocking = true);\n    bool factoryReset(boolean blocking = true);\n    bool resetCompleted(void);\n\n    void info(void);\n    bool echo(bool enable);\n\n    bool isConnected(void);\n    bool isVersionAtLeast(const char * versionString);\n    void disconnect(void);\n\n    bool setAdvData(uint8_t advdata[], uint8_t size);\n\n    bool writeNVM(uint16_t offset, uint8_t const  data[], uint16_t size);\n    bool writeNVM(uint16_t offset, char    const* str);\n    bool writeNVM(uint16_t offset, int32_t number);\n\n    bool readNVM(uint16_t offset, uint8_t data[], uint16_t size);\n    bool readNVM(uint16_t offset, char  * str   , uint16_t size);\n    bool readNVM(uint16_t offset, int32_t* number);\n\n    // helper with bleuart\n    int writeBLEUart(uint8_t const * buffer, int size);\n    int writeBLEUart(char const * str) { return writeBLEUart( (uint8_t const*) str, strlen(str)); }\n\n    int readBLEUart(uint8_t* buffer, int size);\n\n\n    // No parameters\n    bool sendCommandCheckOK(const __FlashStringHelper *cmd) { return this->atcommand(cmd); }\n    bool sendCommandCheckOK(const char cmd[])               { return this->atcommand(cmd); }\n\n    bool sendCommandWithIntReply(const __FlashStringHelper *cmd, int32_t *reply) { return this->atcommandIntReply(cmd, reply); }\n    bool sendCommandWithIntReply(const char cmd[]              , int32_t *reply) { return this->atcommandIntReply(cmd, reply); }\n\n    // Physical transportation checking\n    bool isTransportHwUart (void) { return _physical_transport == BLUEFRUIT_TRANSPORT_HWUART; }\n    bool isTransportSwUart (void) { return _physical_transport == BLUEFRUIT_TRANSPORT_SWUART; }\n    bool isTransportUart   (void) { return isTransportHwUart() || isTransportSwUart();        }\n\n    bool isTransportHwSpi  (void) { return _physical_transport == BLUEFRUIT_TRANSPORT_HWSPI;  }\n    bool isTransportSwSpi  (void) { return _physical_transport == BLUEFRUIT_TRANSPORT_SWSPI;  }\n    bool isTransportSpi    (void) { return isTransportHwSpi() || isTransportSwSpi();          }\n\n    /////////////////////\n    // callback functions\n    /////////////////////\n    void update(uint32_t period_ms = 200);\n    void handleDfuIrq(void)\n    {\n      this->update(0);\n    }\n\n    void setDisconnectCallback( void (*fp) (void) );\n    void setConnectCallback   ( void (*fp) (void) );\n\n    void setBleUartRxCallback( void (*fp) (char data[], uint16_t len) );\n    void setBleMidiRxCallback( midiRxCallback_t fp );\n    void setBleGattRxCallback( int32_t chars_idx, void (*fp) (int32_t, uint8_t[], uint16_t) );\n\n  protected:\n    // helper\n    void install_callback(bool enable, int8_t system_id, int8_t gatts_id);\n\n    void (*_disconnect_callback) (void);\n    void (*_connect_callback) (void);\n\n    void (*_ble_uart_rx_callback) (char data[], uint16_t len);\n    midiRxCallback_t _ble_midi_rx_callback;\n\n    void (*_ble_gatt_rx_callback) (int32_t chars_id, uint8_t data[], uint16_t len);\n};\n\n//--------------------------------------------------------------------+\n// DEBUG HELPER\n//--------------------------------------------------------------------+\n#ifndef DBG_ENABLE\n#define DBG_ENABLE      0\n#endif\n\n#if DBG_ENABLE\n  #define DBG_LOCATION()  Serial.printf(\"%s: %d: \\r\\n\", __PRETTY_FUNCTION__, __LINE__)\n  #define DBG_INT(x)      do { Serial.print(#x \" = \"); Serial.println(x); } while(0)\n  #define DBG_HEX(x)      do { Serial.print(#x \" = \"); Serial.println(x, HEX); } while(0)\n  #define DBG_STR(x)      Serial.printf(#x \" = %s\\r\\n\", (char*)(x) )\n  #define DBG_BUFFER(buf, n) \\\n    do {\\\n      uint8_t* p8 = (uint8_t*) (buf);\\\n      Serial.print(#buf \": \");\\\n      for(uint32_t i=0; i<(n); i++) Serial.printf(\"%02x \", p8[i]);\\\n      Serial.print(\"\\r\\n\");\\\n    }while(0)\n#endif\n\n#endif /* _Adafruit_BLE_H_ */\n"
  },
  {
    "path": "Adafruit_BLEBattery.cpp",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BLEBatterry.cpp\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#include \"Adafruit_BLEBattery.h\"\n\n/******************************************************************************/\n/*!\n    @brief Constructor\n*/\n/******************************************************************************/\nAdafruit_BLEBattery::Adafruit_BLEBattery(Adafruit_BLE& ble) :\n  _ble(ble)\n{\n\n}\n\n/******************************************************************************/\n/*!\n    @brief Enable Battery service if not already enabled\n    @param reset true will reset Bluefruit\n*/\n/******************************************************************************/\nbool Adafruit_BLEBattery::begin(bool reset)\n{\n  int32_t enabled = 0;\n  VERIFY_( _ble.atcommandIntReply( F(\"AT+BLEBATTEN\"), &enabled) );\n  if ( enabled ) return true;\n\n  VERIFY_( _ble.atcommand( F(\"AT+BLEBATTEN=1\") ) );\n\n  // Perform Bluefruit reset if needed\n  if (reset) _ble.reset();\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief Stop Battery service if it is enabled\n    @param reset true will reset Bluefruit\n*/\n/******************************************************************************/\nbool Adafruit_BLEBattery::stop(bool reset)\n{\n  int32_t enabled = 0;\n  VERIFY_( _ble.atcommandIntReply( F(\"AT+BLEBATTEN\"), &enabled) );\n  if ( !enabled ) return true;\n\n  VERIFY_( _ble.atcommand( F(\"AT+BLEBATTEN=0\") ) );\n\n  // Perform Bluefruit reset if needed\n  if (reset) _ble.reset();\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief Update Battery level value\n    @param percent Battery value in percentage 0-100\n*/\n/******************************************************************************/\nbool Adafruit_BLEBattery::update(uint8_t percent)\n{\n  VERIFY_( is_within(0, percent, 100) );\n  return _ble.atcommand( F(\"AT+BLEBATTVAL\"), percent ) ;\n}\n\n"
  },
  {
    "path": "Adafruit_BLEBattery.h",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BLEBatterry.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#ifndef _ADAFRUIT_BLEBATTERY_H_\n#define _ADAFRUIT_BLEBATTERY_H_\n\n#include <Arduino.h>\n#include \"Adafruit_BLE.h\"\n\nclass Adafruit_BLEBattery\n{\nprivate:\n  Adafruit_BLE& _ble;\n\npublic:\n  Adafruit_BLEBattery(Adafruit_BLE& ble);\n\n  bool begin(bool reset = true);\n  bool stop (bool reset = true);\n\n  bool update(uint8_t percent);\n};\n\n#endif /* _ADAFRUIT_BLEBATTERY_H_ */\n"
  },
  {
    "path": "Adafruit_BLEEddystone.cpp",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BLEEddystone.cpp\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#include \"Adafruit_BLEEddystone.h\"\n\n#define EDDYSTONE_MINIMUM_FIRMWARE_VERSION    \"0.7.0\"\n\n\n/******************************************************************************/\n/*!\n    @brief Constructor\n*/\n/******************************************************************************/\nAdafruit_BLEEddystone::Adafruit_BLEEddystone(Adafruit_BLE& ble) :\n  _ble(ble)\n{\n}\n\n/******************************************************************************/\n/*!\n    @brief Enable Eddystone service if not already enabled\n    @param reset true will reset Bluefruit\n*/\n/******************************************************************************/\nbool Adafruit_BLEEddystone::begin(bool reset)\n{\n  VERIFY_( _ble.isVersionAtLeast(EDDYSTONE_MINIMUM_FIRMWARE_VERSION) );\n\n  int32_t enabled = 0;\n  VERIFY_( _ble.atcommandIntReply( F(\"AT+EDDYSTONESERVICEEN\"), &enabled) );\n\n  if ( enabled ) return true;\n  VERIFY_( _ble.atcommand( F(\"AT+EDDYSTONESERVICEEN=1\") ) );\n\n  // Perform Bluefruit reset if needed\n  if (reset) _ble.reset();\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief Stop Eddystone service if it is enabled\n    @param reset true will reset Bluefruit\n*/\n/******************************************************************************/\nbool Adafruit_BLEEddystone::stop(bool reset)\n{\n  int32_t enabled = 0;\n  VERIFY_( _ble.atcommandIntReply( F(\"AT+EDDYSTONESERVICEEN\"), &enabled) );\n  if ( !enabled ) return true;\n\n  VERIFY_( _ble.atcommand( F(\"AT+EDDYSTONESERVICEEN=0\") ) );\n\n  // Perform Bluefruit reset if needed\n  if (reset) _ble.reset();\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief Change Bluefruit's URL setting in NVM\n    @param url  URL to be advertized\n    @param broadcastEvenConnect Keep broadcasting even Bluefruit is connected\n    @param rssi_at_0m RSSI value at 0m (check out EddyStone specs)\n*/\n/******************************************************************************/\nbool Adafruit_BLEEddystone::setURL(const char* url, bool broadcastEvenConnect, int8_t rssi_at_0m)\n{\n  bool result;\n  uint8_t current_mode = _ble.getMode();\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) _ble.setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // send command and integer parameters separated by comma\n  _ble.print(  F(\"AT+EDDYSTONEURL=\") );\n  _ble.print(url);\n\n  _ble.print(','); _ble.print(broadcastEvenConnect, DEC);\n  _ble.print(','); _ble.print(rssi_at_0m);\n\n  _ble.println(); // execute command\n\n  result = _ble.waitForOK();\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) _ble.setMode(BLUEFRUIT_MODE_DATA);\n\n  return result;\n}\n\n/******************************************************************************/\n/*!\n    @brief Start Broadcasting (advertising) specified URL\n*/\n/******************************************************************************/\nbool Adafruit_BLEEddystone::startBroadcast(void)\n{\n  return _ble.atcommand( F(\"AT+EDDYSTONEBROADCAST=1\") );\n}\n\n/******************************************************************************/\n/*!\n    @brief Stop Broadcasting (advertising) specified URL\n*/\n/******************************************************************************/\nbool Adafruit_BLEEddystone::stopBroadcast(void)\n{\n  return _ble.atcommand( F(\"AT+EDDYSTONEBROADCAST=0\") );\n}\n\n/******************************************************************************/\n/*!\n    @brief Broadcast (advertising) specified URL\n*/\n/******************************************************************************/\nbool Adafruit_BLEEddystone::startConfigMode(uint32_t seconds)\n{\n  return _ble.atcommand( F(\"AT+EDDYSTONECONFIGEN\"), (int32_t) seconds );\n}\n"
  },
  {
    "path": "Adafruit_BLEEddystone.h",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BLEEddystone.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#ifndef _ADAFRUIT_BLEEDDYSTONE_H_\n#define _ADAFRUIT_BLEEDDYSTONE_H_\n\n#include <Arduino.h>\n#include \"Adafruit_BLE.h\"\n\n#define EDDYSTONE_DEFAULT_RSSI0M              (-18)\n\nclass Adafruit_BLEEddystone\n{\nprivate:\n  Adafruit_BLE& _ble;\n\npublic:\n  Adafruit_BLEEddystone(Adafruit_BLE& ble);\n\n  bool begin(bool reset = true);\n  bool stop (bool reset = true);\n\n  bool setURL(const char* url, bool broadcastEvenConnect = false, int8_t rssi_at_0m = EDDYSTONE_DEFAULT_RSSI0M);\n\n  bool startBroadcast(void);\n  bool stopBroadcast(void);\n\n  bool startConfigMode(uint32_t seconds);\n\n};\n\n#endif /* _ADAFRUIT_BLEEDDYSTONE_H_ */\n"
  },
  {
    "path": "Adafruit_BLEGatt.cpp",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BLEGatt.cpp\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#include \"Adafruit_BLEGatt.h\"\n\n\n/******************************************************************************/\n/*!\n    @brief Constructor\n*/\n/******************************************************************************/\nAdafruit_BLEGatt::Adafruit_BLEGatt(Adafruit_BLE& ble) :\n  _ble(ble)\n{\n  this->buffer = _ble.buffer;\n}\n\n/******************************************************************************/\n/*!\n    @brief Clear all GATT data\n*/\n/******************************************************************************/\nbool Adafruit_BLEGatt::clear(void)\n{\n  return _ble.atcommand( F(\"AT+GATTCLEAR\") );\n}\n\n/******************************************************************************/\n/*!\n    @brief Add a service with 16-bit UUID\n    @return Service ID (starting from 1). If failed 0 is returned\n*/\n/******************************************************************************/\nuint8_t Adafruit_BLEGatt::addService(uint16_t uuid16)\n{\n  int32_t service_id;\n  VERIFY_RETURN_( _ble.atcommandIntReply( F(\"AT+GATTADDSERVICE=UUID\"), &service_id, uuid16), 0 );\n  return (uint8_t) service_id;\n}\n\n/******************************************************************************/\n/*!\n    @brief Add a service with 128-bit UUID\n    @return Service ID (starting from 1). If failed 0 is returned\n*/\n/******************************************************************************/\nuint8_t Adafruit_BLEGatt::addService(uint8_t uuid128[])\n{\n  int32_t service_id;\n  VERIFY_RETURN_( _ble.atcommandIntReply( F(\"AT+GATTADDSERVICE=UUID128\"), &service_id, uuid128, 16), 0 );\n  return (uint8_t) service_id;\n}\n\n/******************************************************************************/\n/*!\n    @brief Internal function to add Characteristic\n    @return Chars ID (starting from 1). If failed 0 is returned\n*/\n/******************************************************************************/\nuint8_t Adafruit_BLEGatt::addChar_internal(uint8_t uuid[], uint8_t uuid_len, uint8_t properties, uint8_t min_len, uint8_t max_len, BLEDataType_t datatype, const char* description, const GattPresentationFormat* presentFormat)\n{\n  bool isOK;\n  int32_t chars_id;\n  uint8_t current_mode = _ble.getMode();\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) _ble.setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // Standard UUID or UUID128\n  if ( uuid_len == 2 )\n  {\n    uint16_t uuid16;\n    memcpy(&uuid16, uuid, 2);\n\n    _ble.print( F(\"AT+GATTADDCHAR=UUID=\") );\n    _ble.print(uuid16);\n  }else\n  {\n    _ble.print( F(\"AT+GATTADDCHAR=UUID128=\") );\n    _ble.printByteArray(uuid, 16);\n  }\n\n  _ble.print( F(\",PROPERTIES=\") );\n  _ble.print(properties);\n\n  _ble.print( F(\",MIN_LEN=\") );\n  _ble.print(min_len);\n\n  _ble.print( F(\",MAX_LEN=\") );\n  _ble.print(max_len);\n\n  _ble.print( F(\",DATATYPE=\") );\n  _ble.print((uint8_t) datatype);\n\n  if (description)\n  {\n    _ble.print( F(\",DESCRIPTION=\") );\n    _ble.print(description);\n  }\n\n  if (presentFormat && presentFormat->format)\n  {\n    // presentation format is packed 7 bytes, use tempbuf to avoid mis-aligned memory\n    uint8_t tempbuf[7];\n    memcpy(tempbuf, presentFormat, 5);\n    memcpy(tempbuf+5, &presentFormat->desc, 2);\n\n    _ble.print( F(\",PRESENTATION=\") );\n    _ble.printByteArray(tempbuf, 7);\n  }\n\n  _ble.println(); // execute command\n\n//  if (_verbose) SerialDebug.print( F(\"\\n<- \") );\n  chars_id = _ble.readline_parseInt();\n\n  isOK = _ble.waitForOK();\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) _ble.setMode(BLUEFRUIT_MODE_DATA);\n\n  return isOK ? chars_id : 0;\n}\n\n/******************************************************************************/\n/*!\n    @brief Add a characteristics with UUID16 to a newly added service\n    @param\n    @return Chars ID (starting from 1). If failed 0 is returned\n*/\n/******************************************************************************/\nuint8_t Adafruit_BLEGatt::addCharacteristic(uint16_t uuid16, uint8_t properties, uint8_t min_len, uint8_t max_len, BLEDataType_t datatype, const char* description, const GattPresentationFormat* presentFormat)\n{\n  return addChar_internal((uint8_t*) &uuid16, 2, properties, min_len, max_len, datatype, description, presentFormat);\n}\n\n/******************************************************************************/\n/*!\n    @brief Add a characteristics with UUID128 to a newly added service\n    @param\n    @return Chars ID (starting from 1). If failed 0 is returned\n*/\n/******************************************************************************/\nuint8_t Adafruit_BLEGatt::addCharacteristic(uint8_t uuid128[], uint8_t properties, uint8_t min_len, uint8_t max_len, BLEDataType_t datatype, const char* description, const GattPresentationFormat* presentFormat)\n{\n  return addChar_internal(uuid128, 16, properties, min_len, max_len, datatype, description, presentFormat);\n}\n\n/******************************************************************************/\n/*!\n    @brief Set Characteristics value with data buffer\n    @param\n*/\n/******************************************************************************/\nbool Adafruit_BLEGatt::setChar(uint8_t charID, uint8_t const data[], uint8_t size)\n{\n  uint16_t argtype[] = { AT_ARGTYPE_UINT8, (uint16_t) (AT_ARGTYPE_BYTEARRAY+ size) };\n  uint32_t args[] = { charID, (uint32_t) data };\n\n  return _ble.atcommand_full(F(\"AT+GATTCHAR\"), NULL, 2, argtype, args);\n}\n\n/******************************************************************************/\n/*!\n    @brief Set Characteristics value with data buffer\n    @param\n*/\n/******************************************************************************/\nbool Adafruit_BLEGatt::setChar(uint8_t charID, char const* str)\n{\n  uint16_t argtype[] = { AT_ARGTYPE_UINT8, AT_ARGTYPE_STRING };\n  uint32_t args[] = { charID, (uint32_t) str };\n\n  return _ble.atcommand_full(F(\"AT+GATTCHAR\"), NULL, 2, argtype, args);\n}\n\n/******************************************************************************/\n/*!\n    @brief Read Characteristics value to internal buffer\n    @param charID Characteristics ID\n    @return number of bytes copied to buffer (up to bufsize).\n            0 usually means error.\n\n*/\n/******************************************************************************/\nuint8_t Adafruit_BLEGatt::getChar(uint8_t charID)\n{\n  uint8_t current_mode = _ble.getMode();\n\n  // switch mode if necessary to execute command\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) _ble.setMode(BLUEFRUIT_MODE_COMMAND);\n\n  // use RAW command version\n  _ble.print( F(\"AT+GATTCHARRAW=\") );\n  _ble.println(charID);\n  uint16_t len = _ble.readraw(); // readraw swallow OK/ERROR already\n\n  // switch back if necessary\n  if ( current_mode == BLUEFRUIT_MODE_DATA ) _ble.setMode(BLUEFRUIT_MODE_DATA);\n\n  return len;\n}\n\n/******************************************************************************/\n/*!\n    @brief Read Characteristics value to user's buffer\n    @param charID Characteristics ID\n    @param buf buffer to hold data\n    @param bufsize size of buffer\n    @return number of bytes copied to buffer (up to bufsize).\n            0 usually means error.\n*/\n/******************************************************************************/\nuint8_t Adafruit_BLEGatt::getChar(uint8_t charID, uint8_t* buf, uint8_t bufsize)\n{\n  uint8_t len = this->getChar(charID);\n  len = min(len, bufsize);\n  memcpy(buf, _ble.buffer, len);\n\n  return len;\n}\n"
  },
  {
    "path": "Adafruit_BLEGatt.h",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BLEGatt.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#ifndef _ADAFRUIT_BLEGATT_H_\n#define _ADAFRUIT_BLEGATT_H_\n\n#include <Arduino.h>\n#include \"Adafruit_BLE.h\"\n\n#define GATT_CHARS_PROPERTIES_BROADCAST       bit(0)\n#define GATT_CHARS_PROPERTIES_READ            bit(1)\n#define GATT_CHARS_PROPERTIES_WRITE_WO_RESP   bit(2)\n#define GATT_CHARS_PROPERTIES_WRITE           bit(3)\n#define GATT_CHARS_PROPERTIES_NOTIFY          bit(4)\n#define GATT_CHARS_PROPERTIES_INDICATE        bit(5)\n\nstruct GattPresentationFormat\n{\n  uint8_t  format;\n  int8_t   exponent;\n  uint16_t unit;\n  uint8_t  name_space;\n  uint16_t desc;\n};\n\nclass Adafruit_BLEGatt\n{\nprivate:\n  Adafruit_BLE& _ble;\n\n  uint8_t addChar_internal(uint8_t uuid[], uint8_t uuid_len, uint8_t properties, uint8_t min_len, uint8_t max_len, BLEDataType_t datatype, const char* description, const GattPresentationFormat* presentFormat);\n\npublic:\n  char* buffer; // alias to ble's buffer\n\n  Adafruit_BLEGatt(Adafruit_BLE& ble);\n\n  bool    clear(void);\n\n  uint8_t addService(uint16_t uuid16);\n  uint8_t addService(uint8_t uuid128[]);\n\n  uint8_t addCharacteristic(uint16_t uuid16  , uint8_t properties, uint8_t min_len, uint8_t max_len, BLEDataType_t datatype, const char* description = NULL, const GattPresentationFormat* presentFormat = NULL);\n  uint8_t addCharacteristic(uint8_t uuid128[], uint8_t properties, uint8_t min_len, uint8_t max_len, BLEDataType_t datatype, const char* description = NULL, const GattPresentationFormat* presentFormat = NULL);\n\n  //------------- Get Characteristic -------------//\n  uint8_t  getChar(uint8_t charID);\n  uint8_t  getChar(uint8_t charID, uint8_t* buf, uint8_t bufsize);\n\n  uint8_t  getCharInt8(uint8_t charID)\n  {\n    if ( this->getChar(charID) < sizeof(uint8_t) ) return 0;\n    uint8_t result;\n    memcpy(&result, this->buffer, sizeof(result));\n    return result;\n  }\n\n  uint16_t getCharInt16(uint8_t charID)\n  {\n    if ( this->getChar(charID) < sizeof(uint16_t) ) return 0;\n    uint16_t result;\n    memcpy(&result, this->buffer, sizeof(result));\n    return result;\n  }\n\n  uint32_t getCharInt32(uint8_t charID)\n  {\n    if ( this->getChar(charID) < sizeof(uint32_t) ) return 0;\n    uint32_t result;\n    memcpy(&result, this->buffer, sizeof(result));\n    return result;\n  }\n\n  char*    getCharStr(uint8_t charID)\n  {\n    if ( this->getChar(charID) == 0 ) return NULL;\n    return this->buffer;\n  }\n\n  //------------- Set Characteristic -------------//\n  bool    setChar(uint8_t charID, uint8_t const data[], uint8_t size);\n  bool    setChar(uint8_t charID, char const *  str);\n\n  bool    setChar(uint8_t charID, uint8_t  data8 ) { return this->setChar(charID, (uint8_t*) &data8, 1); }\n  bool    setChar(uint8_t charID, int8_t   data8 ) { return this->setChar(charID, (uint8_t*) &data8, 1); }\n\n  bool    setChar(uint8_t charID, uint16_t data16) { return this->setChar(charID, (uint8_t*) &data16, 2); }\n  bool    setChar(uint8_t charID, int16_t  data16) { return this->setChar(charID, (uint8_t*) &data16, 2); }\n\n  bool    setChar(uint8_t charID, uint32_t data32) { return this->setChar(charID, (uint8_t*) &data32, 4); }\n  bool    setChar(uint8_t charID, int32_t  data32) { return this->setChar(charID, (uint8_t*) &data32, 4); }\n};\n\nenum\n{\n  GATT_PRESENT_FORMAT_BOOLEAN = 0x01,\n  GATT_PRESENT_FORMAT_2BIT    = 0x02,\n  GATT_PRESENT_FORMAT_4BIT    = 0x03,\n  GATT_PRESENT_FORMAT_UINT8   = 0x04,\n  GATT_PRESENT_FORMAT_UINT12  = 0x05,\n  GATT_PRESENT_FORMAT_UINT16  = 0x06,\n  GATT_PRESENT_FORMAT_UINT24  = 0x07,\n  GATT_PRESENT_FORMAT_UINT32  = 0x08,\n  GATT_PRESENT_FORMAT_UINT48  = 0x09,\n  GATT_PRESENT_FORMAT_UINT64  = 0x0A,\n  GATT_PRESENT_FORMAT_UINT128 = 0x0B,\n  GATT_PRESENT_FORMAT_SINT8   = 0x0C,\n  GATT_PRESENT_FORMAT_SINT12  = 0x0D,\n  GATT_PRESENT_FORMAT_SINT16  = 0x0E,\n  GATT_PRESENT_FORMAT_SINT24  = 0x0F,\n  GATT_PRESENT_FORMAT_SINT32  = 0x10,\n  GATT_PRESENT_FORMAT_SINT48  = 0x11,\n  GATT_PRESENT_FORMAT_SINT64  = 0x12,\n  GATT_PRESENT_FORMAT_SINT128 = 0x13,\n  GATT_PRESENT_FORMAT_FLOAT32 = 0x14,\n  GATT_PRESENT_FORMAT_FLOAT64 = 0x15,\n  GATT_PRESENT_FORMAT_SFLOAT  = 0x16,\n  GATT_PRESENT_FORMAT_FLOAT   = 0x17,\n  GATT_PRESENT_FORMAT_DUINT16 = 0x18,\n  GATT_PRESENT_FORMAT_UTF8S   = 0x19,\n  GATT_PRESENT_FORMAT_UTF16S  = 0x1A,\n  GATT_PRESENT_FORMAT_STRUCT  = 0x1B,\n};\n\n/* See https://developer.bluetooth.org/gatt/units/Pages/default.aspx */\nenum\n{\n  GATT_PRESENT_UNIT_NONE                                                   = 0x2700,\n  GATT_PRESENT_UNIT_LENGTH_METRE                                           = 0x2701,\n  GATT_PRESENT_UNIT_MASS_KILOGRAM                                          = 0x2702,\n  GATT_PRESENT_UNIT_TIME_SECOND                                            = 0x2703,\n  GATT_PRESENT_UNIT_ELECTRIC_CURRENT_AMPERE                                = 0x2704,\n  GATT_PRESENT_UNIT_THERMODYNAMIC_TEMPERATURE_KELVIN                       = 0x2705,\n  GATT_PRESENT_UNIT_AMOUNT_OF_SUBSTANCE_MOLE                               = 0x2706,\n  GATT_PRESENT_UNIT_LUMINOUS_INTENSITY_CANDELA                             = 0x2707,\n  GATT_PRESENT_UNIT_AREA_SQUARE_METRES                                     = 0x2710,\n  GATT_PRESENT_UNIT_VOLUME_CUBIC_METRES                                    = 0x2711,\n  GATT_PRESENT_UNIT_VELOCITY_METRES_PER_SECOND                             = 0x2712,\n  GATT_PRESENT_UNIT_ACCELERATION_METRES_PER_SECOND_SQUARED                 = 0x2713,\n  GATT_PRESENT_UNIT_WAVENUMBER_RECIPROCAL_METRE                            = 0x2714,\n  GATT_PRESENT_UNIT_DENSITY_KILOGRAM_PER_CUBIC_METRE                       = 0x2715,\n  GATT_PRESENT_UNIT_SURFACE_DENSITY_KILOGRAM_PER_SQUARE_METRE              = 0x2716,\n  GATT_PRESENT_UNIT_SPECIFIC_VOLUME_CUBIC_METRE_PER_KILOGRAM               = 0x2717,\n  GATT_PRESENT_UNIT_CURRENT_DENSITY_AMPERE_PER_SQUARE_METRE                = 0x2718,\n  GATT_PRESENT_UNIT_MAGNETIC_FIELD_STRENGTH_AMPERE_PER_METRE               = 0x2719,\n  GATT_PRESENT_UNIT_AMOUNT_CONCENTRATION_MOLE_PER_CUBIC_METRE              = 0x271A,\n  GATT_PRESENT_UNIT_MASS_CONCENTRATION_KILOGRAM_PER_CUBIC_METRE            = 0x271B,\n  GATT_PRESENT_UNIT_LUMINANCE_CANDELA_PER_SQUARE_METRE                     = 0x271C,\n  GATT_PRESENT_UNIT_REFRACTIVE_INDEX                                       = 0x271D,\n  GATT_PRESENT_UNIT_RELATIVE_PERMEABILITY                                  = 0x271E,\n  GATT_PRESENT_UNIT_PLANE_ANGLE_RADIAN                                     = 0x2720,\n  GATT_PRESENT_UNIT_SOLID_ANGLE_STERADIAN                                  = 0x2721,\n  GATT_PRESENT_UNIT_FREQUENCY_HERTZ                                        = 0x2722,\n  GATT_PRESENT_UNIT_FORCE_NEWTON                                           = 0x2723,\n  GATT_PRESENT_UNIT_PRESSURE_PASCAL                                        = 0x2724,\n  GATT_PRESENT_UNIT_ENERGY_JOULE                                           = 0x2725,\n  GATT_PRESENT_UNIT_POWER_WATT                                             = 0x2726,\n  GATT_PRESENT_UNIT_ELECTRIC_CHARGE_COULOMB                                = 0x2727,\n  GATT_PRESENT_UNIT_ELECTRIC_POTENTIAL_DIFFERENCE_VOLT                     = 0x2728,\n  GATT_PRESENT_UNIT_CAPACITANCE_FARAD                                      = 0x2729,\n  GATT_PRESENT_UNIT_ELECTRIC_RESISTANCE_OHM                                = 0x272A,\n  GATT_PRESENT_UNIT_ELECTRIC_CONDUCTANCE_SIEMENS                           = 0x272B,\n  GATT_PRESENT_UNIT_MAGNETIC_FLEX_WEBER                                    = 0x272C,\n  GATT_PRESENT_UNIT_MAGNETIC_FLEX_DENSITY_TESLA                            = 0x272D,\n  GATT_PRESENT_UNIT_INDUCTANCE_HENRY                                       = 0x272E,\n  GATT_PRESENT_UNIT_THERMODYNAMIC_TEMPERATURE_DEGREE_CELSIUS               = 0x272F,\n  GATT_PRESENT_UNIT_LUMINOUS_FLUX_LUMEN                                    = 0x2730,\n  GATT_PRESENT_UNIT_ILLUMINANCE_LUX                                        = 0x2731,\n  GATT_PRESENT_UNIT_ACTIVITY_REFERRED_TO_A_RADIONUCLIDE_BECQUEREL          = 0x2732,\n  GATT_PRESENT_UNIT_ABSORBED_DOSE_GRAY                                     = 0x2733,\n  GATT_PRESENT_UNIT_DOSE_EQUIVALENT_SIEVERT                                = 0x2734,\n  GATT_PRESENT_UNIT_CATALYTIC_ACTIVITY_KATAL                               = 0x2735,\n  GATT_PRESENT_UNIT_DYNAMIC_VISCOSITY_PASCAL_SECOND                        = 0x2740,\n  GATT_PRESENT_UNIT_MOMENT_OF_FORCE_NEWTON_METRE                           = 0x2741,\n  GATT_PRESENT_UNIT_SURFACE_TENSION_NEWTON_PER_METRE                       = 0x2742,\n  GATT_PRESENT_UNIT_ANGULAR_VELOCITY_RADIAN_PER_SECOND                     = 0x2743,\n  GATT_PRESENT_UNIT_ANGULAR_ACCELERATION_RADIAN_PER_SECOND_SQUARED         = 0x2744,\n  GATT_PRESENT_UNIT_HEAT_FLUX_DENSITY_WATT_PER_SQUARE_METRE                = 0x2745,\n  GATT_PRESENT_UNIT_HEAT_CAPACITY_JOULE_PER_KELVIN                         = 0x2746,\n  GATT_PRESENT_UNIT_SPECIFIC_HEAT_CAPACITY_JOULE_PER_KILOGRAM_KELVIN       = 0x2747,\n  GATT_PRESENT_UNIT_SPECIFIC_ENERGY_JOULE_PER_KILOGRAM                     = 0x2748,\n  GATT_PRESENT_UNIT_THERMAL_CONDUCTIVITY_WATT_PER_METRE_KELVIN             = 0x2749,\n  GATT_PRESENT_UNIT_ENERGY_DENSITY_JOULE_PER_CUBIC_METRE                   = 0x274A,\n  GATT_PRESENT_UNIT_ELECTRIC_FIELD_STRENGTH_VOLT_PER_METRE                 = 0x274B,\n  GATT_PRESENT_UNIT_ELECTRIC_CHARGE_DENSITY_COULOMB_PER_CUBIC_METRE        = 0x274C,\n  GATT_PRESENT_UNIT_SURFACE_CHARGE_DENSITY_COULOMB_PER_SQUARE_METRE        = 0x274D,\n  GATT_PRESENT_UNIT_ELECTRIC_FLUX_DENSITY_COULOMB_PER_SQUARE_METRE         = 0x274E,\n  GATT_PRESENT_UNIT_PERMITTIVITY_FARAD_PER_METRE                           = 0x274F,\n  GATT_PRESENT_UNIT_PERMEABILITY_HENRY_PER_METRE                           = 0x2750,\n  GATT_PRESENT_UNIT_MOLAR_ENERGY_JOULE_PER_MOLE                            = 0x2751,\n  GATT_PRESENT_UNIT_MOLAR_ENTROPY_JOULE_PER_MOLE_KELVIN                    = 0x2752,\n  GATT_PRESENT_UNIT_EXPOSURE_COULOMB_PER_KILOGRAM                          = 0x2753,\n  GATT_PRESENT_UNIT_ABSORBED_DOSE_RATE_GRAY_PER_SECOND                     = 0x2754,\n  GATT_PRESENT_UNIT_RADIANT_INTENSITY_WATT_PER_STERADIAN                   = 0x2755,\n  GATT_PRESENT_UNIT_RADIANCE_WATT_PER_SQUARE_METRE_STERADIAN               = 0x2756,\n  GATT_PRESENT_UNIT_CATALYTIC_ACTIVITY_CONCENTRATION_KATAL_PER_CUBIC_METRE = 0x2757,\n  GATT_PRESENT_UNIT_TIME_MINUTE                                            = 0x2760,\n  GATT_PRESENT_UNIT_TIME_HOUR                                              = 0x2761,\n  GATT_PRESENT_UNIT_TIME_DAY                                               = 0x2762,\n  GATT_PRESENT_UNIT_PLANE_ANGLE_DEGREE                                     = 0x2763,\n  GATT_PRESENT_UNIT_PLANE_ANGLE_MINUTE                                     = 0x2764,\n  GATT_PRESENT_UNIT_PLANE_ANGLE_SECOND                                     = 0x2765,\n  GATT_PRESENT_UNIT_AREA_HECTARE                                           = 0x2766,\n  GATT_PRESENT_UNIT_VOLUME_LITRE                                           = 0x2767,\n  GATT_PRESENT_UNIT_MASS_TONNE                                             = 0x2768,\n  GATT_PRESENT_UNIT_PRESSURE_BAR                                           = 0x2780,\n  GATT_PRESENT_UNIT_PRESSURE_MILLIMETRE_OF_MERCURY                         = 0x2781,\n  GATT_PRESENT_UNIT_LENGTH_ANGSTROM                                        = 0x2782,\n  GATT_PRESENT_UNIT_LENGTH_NAUTICAL_MILE                                   = 0x2783,\n  GATT_PRESENT_UNIT_AREA_BARN                                              = 0x2784,\n  GATT_PRESENT_UNIT_VELOCITY_KNOT                                          = 0x2785,\n  GATT_PRESENT_UNIT_LOGARITHMIC_RADIO_QUANTITY_NEPER                       = 0x2786,\n  GATT_PRESENT_UNIT_LOGARITHMIC_RADIO_QUANTITY_BEL                         = 0x2787,\n  GATT_PRESENT_UNIT_LENGTH_YARD                                            = 0x27A0,\n  GATT_PRESENT_UNIT_LENGTH_PARSEC                                          = 0x27A1,\n  GATT_PRESENT_UNIT_LENGTH_INCH                                            = 0x27A2,\n  GATT_PRESENT_UNIT_LENGTH_FOOT                                            = 0x27A3,\n  GATT_PRESENT_UNIT_LENGTH_MILE                                            = 0x27A4,\n  GATT_PRESENT_UNIT_PRESSURE_POUND_FORCE_PER_SQUARE_INCH                   = 0x27A5,\n  GATT_PRESENT_UNIT_VELOCITY_KILOMETRE_PER_HOUR                            = 0x27A6,\n  GATT_PRESENT_UNIT_VELOCITY_MILE_PER_HOUR                                 = 0x27A7,\n  GATT_PRESENT_UNIT_ANGULAR_VELOCITY_REVOLUTION_PER_MINUTE                 = 0x27A8,\n  GATT_PRESENT_UNIT_ENERGY_GRAM_CALORIE                                    = 0x27A9,\n  GATT_PRESENT_UNIT_ENERGY_KILOGRAM_CALORIE                                = 0x27AA,\n  GATT_PRESENT_UNIT_ENERGY_KILOWATT_HOUR                                   = 0x27AB,\n  GATT_PRESENT_UNIT_THERMODYNAMIC_TEMPERATURE_DEGREE_FAHRENHEIT            = 0x27AC,\n  GATT_PRESENT_UNIT_PERCENTAGE                                             = 0x27AD,\n  GATT_PRESENT_UNIT_PER_MILLE                                              = 0x27AE,\n  GATT_PRESENT_UNIT_PERIOD_BEATS_PER_MINUTE                                = 0x27AF,\n  GATT_PRESENT_UNIT_ELECTRIC_CHARGE_AMPERE_HOURS                           = 0x27B0,\n  GATT_PRESENT_UNIT_MASS_DENSITY_MILLIGRAM_PER_DECILITRE                   = 0x27B1,\n  GATT_PRESENT_UNIT_MASS_DENSITY_MILLIMOLE_PER_LITRE                       = 0x27B2,\n  GATT_PRESENT_UNIT_TIME_YEAR                                              = 0x27B3,\n  GATT_PRESENT_UNIT_TIME_MONTH                                             = 0x27B4,\n  GATT_PRESENT_UNIT_CONCENTRATION_COUNT_PER_CUBIC_METRE                    = 0x27B5,\n  GATT_PRESENT_UNIT_IRRADIANCE_WATT_PER_SQUARE_METRE                       = 0x27B6\n};\n\n#endif /* _ADAFRUIT_BLEGATT_H_ */\n"
  },
  {
    "path": "Adafruit_BLEMIDI.cpp",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BLEMIDI.cpp\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#include \"Adafruit_BLEMIDI.h\"\n\n#define MIDI_MINIMUM_FIRMWARE_VERSION    \"0.7.0\"\n\n/******************************************************************************/\n/*!\n    @brief Constructor\n*/\n/******************************************************************************/\nAdafruit_BLEMIDI::Adafruit_BLEMIDI(Adafruit_BLE& ble) :\n  _ble(ble)\n{\n}\n\n/******************************************************************************/\n/*!\n    @brief Set callback\n*/\n/******************************************************************************/\nvoid Adafruit_BLEMIDI::setRxCallback(midiRxCallback_t fp)\n{\n  _ble.setBleMidiRxCallback(fp);\n}\n\n\n/******************************************************************************/\n/*!\n    @brief Enable MIDI service if not already enabled\n    @param reset true will reset Bluefruit\n*/\n/******************************************************************************/\nbool Adafruit_BLEMIDI::begin(bool reset)\n{\n  VERIFY_( _ble.isVersionAtLeast(MIDI_MINIMUM_FIRMWARE_VERSION) );\n\n  int32_t enabled = 0;\n  VERIFY_( _ble.atcommandIntReply( F(\"AT+BLEMIDIEN\"), &enabled) );\n\n  if ( enabled ) return true;\n  VERIFY_( _ble.atcommand( F(\"AT+BLEMIDIEN=1\") ) );\n\n  // Perform Bluefruit reset if needed\n  if (reset) _ble.reset();\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief Stop MIDI service if it is enabled\n    @param reset true will reset Bluefruit\n*/\n/******************************************************************************/\nbool Adafruit_BLEMIDI::stop(bool reset)\n{\n  int32_t enabled = 0;\n  VERIFY_( _ble.atcommandIntReply( F(\"AT+BLEMIDIEN\"), &enabled) );\n  if ( !enabled ) return true;\n\n  VERIFY_( _ble.atcommand( F(\"AT+BLEMIDIEN=0\") ) );\n\n  // Perform Bluefruit reset if needed\n  if (reset) _ble.reset();\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief Send a MIDI event data\n    @param bytes MIDI event data\n*/\n/******************************************************************************/\nbool Adafruit_BLEMIDI::send(const uint8_t bytes[3])\n{\n  return _ble.atcommand( F(\"AT+BLEMIDITX\"), bytes, 3);\n}\n\n/******************************************************************************/\n/*!\n    @brief Send multiple MIDI event which shared the same status\n    @param status MIDI status\n    @param bytes MIDI events data\n    @param count number of data in bytes (must be multiple of 2)\n\n    @note count + 1 must less than (20-3) --> count <= 16\n*/\n/******************************************************************************/\nbool Adafruit_BLEMIDI::send_n(uint8_t status, const uint8_t bytes[], uint8_t count)\n{\n  VERIFY_(count <= 16);\n\n  uint8_t data[17] = { status };\n  memcpy(data+1, bytes, count);\n\n  return _ble.atcommand( F(\"AT+BLEMIDITX\"), data, count+1);\n}\n\n/******************************************************************************/\n/*!\n    @brief\n    @param\n*/\n/******************************************************************************/\nvoid Adafruit_BLEMIDI::processRxCallback(uint8_t data[], uint16_t len, Adafruit_BLE::midiRxCallback_t callback_func)\n{\n  if ( len < 3 ) return;\n\n  // First 3 bytes is always : Header + Timestamp + Status\n  midi_header_t header;\n  uint16_t tstamp = 0;\n  uint8_t status = 0;\n\n  header.byte = *data++;\n  len--;\n\n  while (len)\n  {\n    /* event : 0x00 - 0x7F\n       status: 0x80 - 0xEF\n       sysex : 0xF0 - 0xFF\n     */\n\n    if ( bitRead(data[0], 7) )\n    {\n      // Start of new full event\n      midi_timestamp_t timestamp;\n      timestamp.byte = *data++;\n\n      tstamp = (header.timestamp_hi << 7) | timestamp.timestamp_low;\n      status = *data++;\n\n      // Status must have 7th-bit set, must have something wrong\n      if ( !bitRead(status, 7) ) return;\n\n      callback_func( tstamp, status, data[0], data[1]);\n\n      len  -= 4;\n      data += 2;\n    }\n    else\n    {\n      // Running event\n      callback_func( tstamp, status, data[0], data[1]);\n\n      len  -= 2;\n      data += 2;\n    }\n  }\n}\n"
  },
  {
    "path": "Adafruit_BLEMIDI.h",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BLEMIDI.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#ifndef _ADAFRUIT_BLEMIDI_H_\n#define _ADAFRUIT_BLEMIDI_H_\n\n#include <Arduino.h>\n#include \"Adafruit_BLE.h\"\n\ntypedef struct ATTR_PACKED\n{\n  union {\n    struct {\n      uint8_t timestamp_hi : 6;\n      uint8_t reserved     : 1;\n      uint8_t start_bit    : 1;\n    };\n\n    uint8_t byte;\n  };\n} midi_header_t;\n\nASSERT_STATIC_ ( sizeof(midi_header_t) == 1 );\n\ntypedef struct ATTR_PACKED\n{\n  union {\n    struct {\n      uint8_t timestamp_low : 7;\n      uint8_t start_bit : 1;\n    };\n\n    uint8_t byte;\n  };\n} midi_timestamp_t;\n\nASSERT_STATIC_ ( sizeof(midi_timestamp_t) == 1 );\n\nclass Adafruit_BLEMIDI\n{\nprivate:\n  Adafruit_BLE& _ble;\n\npublic:\n  typedef Adafruit_BLE::midiRxCallback_t midiRxCallback_t;\n  Adafruit_BLEMIDI(Adafruit_BLE& ble);\n\n  bool begin(bool reset = true);\n  bool stop (bool reset = true);\n\n  bool send(const uint8_t bytes[3]);\n\n  bool send(uint8_t status, const uint8_t bytes[2])\n  {\n    uint8_t buffer[3] = { status, bytes[0], bytes[1] };\n    return send(buffer);\n  }\n\n  bool send(uint8_t status, uint8_t byte1, uint8_t byte2)\n  {\n    uint8_t buffer[3] = { status, byte1, byte2 };\n    return send(buffer);\n  }\n\n  bool send_n(uint8_t status, const uint8_t bytes[], uint8_t count);\n\n  void setRxCallback(midiRxCallback_t fp);\n\n  static void processRxCallback(uint8_t data[], uint16_t len, Adafruit_BLE::midiRxCallback_t callback_func);\n};\n\n#endif /* _ADAFRUIT_BLEMIDI_H_ */\n"
  },
  {
    "path": "Adafruit_BluefruitLE_SPI.cpp",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BluefruitLE_SPI.cpp\n    @author   hathach, ktown (Adafruit Industries)\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2015, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include <Arduino.h>\n#include <stdlib.h>\n\n#ifndef min\n  #define min(a,b) ((a) < (b) ? (a) : (b))\n#endif\n\n\nSPISettings bluefruitSPI(4000000, MSBFIRST, SPI_MODE0);\n\n\n/******************************************************************************/\n/*!\n    @brief Instantiates a new instance of the Adafruit_BluefruitLE_SPI class\n\n    @param[in]  csPin\n                The location of the CS pin for the SPI interface\n    @param[in]  irqPin\n                The location of the HW IRQ pin (pin 2 or pin 3 on the Arduino\n                Uno). This must be a HW interrupt pin!\n    @param[in]  rstPin\n*/\n/******************************************************************************/\nAdafruit_BluefruitLE_SPI::Adafruit_BluefruitLE_SPI(int8_t csPin, int8_t irqPin, int8_t rstPin) :\n    m_rx_fifo(m_rx_buffer, sizeof(m_rx_buffer), 1, true)\n{\n  _physical_transport = BLUEFRUIT_TRANSPORT_HWSPI;\n\n  m_cs_pin  = csPin;\n  m_irq_pin = irqPin;\n  m_rst_pin = rstPin;\n\n  m_miso_pin = m_mosi_pin = m_sck_pin = -1;\n\n  m_tx_count = 0;\n\n  m_mode_switch_command_enabled = true;\n}\n\n/******************************************************************************/\n/*!\n    @brief Instantiates a new instance of the Adafruit_BluefruitLE_SPI class\n           using software SPI\n\n    @param[in]  clkPin\n                The location of the SCK/clock pin for the SPI interface\n    @param[in]  misoPin\n                The location of the MISO pin for the SPI interface\n    @param[in]  mosiPin\n                The location of the MOSI pin for the SPI interface\n    @param[in]  csPin\n                The location of the CS pin for the SPI interface\n    @param[in]  irqPin\n                The location of the HW IRQ pin (pin 2 or pin 3 on the Arduino\n                Uno). This must be a HW interrupt pin!\n    @param[in]  rstPin\n*/\n/******************************************************************************/\nAdafruit_BluefruitLE_SPI::Adafruit_BluefruitLE_SPI(int8_t clkPin, int8_t misoPin,\n    int8_t mosiPin, int8_t csPin, int8_t irqPin, int8_t rstPin) :\n    m_rx_fifo(m_rx_buffer, sizeof(m_rx_buffer), 1, true)\n{\n  _physical_transport = BLUEFRUIT_TRANSPORT_SWSPI;\n\n  m_sck_pin  = clkPin;\n  m_miso_pin = misoPin;\n  m_mosi_pin = mosiPin;\n  m_cs_pin   = csPin;\n  m_irq_pin  = irqPin;\n  m_rst_pin  = rstPin;\n\n  m_tx_count = 0;\n\n  m_mode_switch_command_enabled = true;\n}\n\n\n/******************************************************************************/\n/*!\n    @brief Initialize the HW to enable communication with the BLE module\n\n    @return Returns 'true' if everything initialised correctly, otherwise\n            'false' if there was a problem during HW initialisation. If\n            'irqPin' is not a HW interrupt pin false will be returned.\n*/\n/******************************************************************************/\nbool Adafruit_BluefruitLE_SPI::begin(boolean v, boolean blocking)\n{\n  _verbose = v;\n\n  pinMode(m_irq_pin, INPUT);\n\n  // Set CS pin to output and de-assert by default\n  pinMode(m_cs_pin, OUTPUT);\n  digitalWrite(m_cs_pin, HIGH);\n\n  if (m_sck_pin == -1) {\n    // hardware SPI\n    SPI.begin();\n  } else {\n    pinMode(m_sck_pin, OUTPUT);\n    digitalWrite(m_sck_pin, LOW);\n    pinMode(m_miso_pin, INPUT);\n    pinMode(m_mosi_pin, OUTPUT);\n  }\n\n  bool isOK;\n\n  // Always try to send Initialize command to reset\n  // Bluefruit since user can define but not wiring RST signal\n  isOK = sendInitializePattern();\n\n  // use hardware reset if available\n  if (m_rst_pin >= 0)\n  {\n    // pull the RST to GND for 10 ms\n    pinMode(m_rst_pin, OUTPUT);\n    digitalWrite(m_rst_pin, HIGH);\n    digitalWrite(m_rst_pin, LOW);\n    delay(10);\n    digitalWrite(m_rst_pin, HIGH);\n\n    isOK= true;\n  }\n\n  _reset_started_timestamp = millis();\n\n  // Bluefruit takes 1 second to reboot\n  if (blocking)\n  {\n    delay(1000);\n  }\n\n  return isOK;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Uninitializes the SPI interface\n*/\n/******************************************************************************/\nvoid Adafruit_BluefruitLE_SPI::end(void)\n{\n  if (m_sck_pin == -1) {\n    SPI.end();\n  }\n}\n\n/******************************************************************************/\n/*!\n    @brief Handle direct \"+++\" input command from user.\n           User should use setMode instead\n*/\n/******************************************************************************/\nvoid Adafruit_BluefruitLE_SPI::simulateSwitchMode(void)\n{\n  _mode = 1 - _mode;\n\n  char ch = '0' + _mode;\n  m_rx_fifo.write(&ch);\n  m_rx_fifo.write_n(\"\\r\\nOK\\r\\n\", 6);\n}\n\n/******************************************************************************/\n/*!\n    @brief Simulate \"+++\" switch mode command\n*/\n/******************************************************************************/\nbool Adafruit_BluefruitLE_SPI::setMode(uint8_t new_mode)\n{\n  // invalid mode\n  if ( !(new_mode == BLUEFRUIT_MODE_COMMAND || new_mode == BLUEFRUIT_MODE_DATA) ) return false;\n\n  // Already in the wanted mode\n  if ( _mode == new_mode ) return true;\n\n  // SPI use different SDEP command when in DATA/COMMAND mode.\n  // --> does not switch using +++ command\n  _mode = new_mode;\n\n  // If we're entering DATA mode, flush any old response, so that it isn't\n  // interpreted as incoming UART data\n  if (_mode == BLUEFRUIT_MODE_DATA) flush();\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief Enable/disable recognition of \"+++\" switch mode command.\n           Usage of setMode is not affected.\n*/\n/******************************************************************************/\nvoid Adafruit_BluefruitLE_SPI::enableModeSwitchCommand(bool enabled)\n{\n  m_mode_switch_command_enabled = enabled;\n}\n\n/******************************************************************************/\n/*!\n    @brief Send initialize pattern to Bluefruit LE to force a reset. This pattern\n    follow the SDEP command syntax with command_id = SDEP_CMDTYPE_INITIALIZE.\n    The command has NO response, and is expected to complete within 1 second\n*/\n/******************************************************************************/\nbool Adafruit_BluefruitLE_SPI::sendInitializePattern(void)\n{\n  return sendPacket(SDEP_CMDTYPE_INITIALIZE, NULL, 0, 0);\n}\n\n/******************************************************************************/\n/*!\n    @brief  Send out an packet with data in m_tx_buffer\n\n    @param[in]  more_data\n                More Data bitfield, 0 indicates this is not end of transfer yet\n*/\n/******************************************************************************/\nbool Adafruit_BluefruitLE_SPI::sendPacket(uint16_t command, const uint8_t* buf, uint8_t count, uint8_t more_data)\n{\n  // flush old response before sending the new command, but only if we're *not*\n  // in DATA mode, as the RX FIFO may containg incoming UART data that hasn't\n  // been read yet\n  if (more_data == 0 && _mode != BLUEFRUIT_MODE_DATA) flush();\n\n  sdepMsgCommand_t msgCmd;\n\n  msgCmd.header.msg_type    = SDEP_MSGTYPE_COMMAND;\n  msgCmd.header.cmd_id_high = highByte(command);\n  msgCmd.header.cmd_id_low  = lowByte(command);\n  msgCmd.header.length      = count;\n  msgCmd.header.more_data   = (count == SDEP_MAX_PACKETSIZE) ? more_data : 0;\n\n  // Copy payload\n  if ( buf != NULL && count > 0) memcpy(msgCmd.payload, buf, count);\n\n  // Starting SPI transaction\n  if (m_sck_pin == -1)\n    SPI.beginTransaction(bluefruitSPI);\n\n  SPI_CS_ENABLE();\n\n  TimeoutTimer tt(_timeout);\n\n  // Bluefruit may not be ready\n  while ( ( spixfer(msgCmd.header.msg_type) == SPI_IGNORED_BYTE ) && !tt.expired() )\n  {\n    // Disable & Re-enable CS with a bit of delay for Bluefruit to ready itself\n    SPI_CS_DISABLE();\n    delayMicroseconds(SPI_DEFAULT_DELAY_US);\n    SPI_CS_ENABLE();\n  }\n\n  bool result = !tt.expired();\n  if ( result )\n  {\n    // transfer the rest of the data\n    spixfer((void*) (((uint8_t*)&msgCmd) +1), sizeof(sdepMsgHeader_t)+count-1);\n  }\n\n  SPI_CS_DISABLE();\n  if (m_sck_pin == -1)\n    SPI.endTransaction();\n\n  return result;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Print API. Either buffer the data internally or send it to bus\n            if possible. \\r and \\n are command terminators and will force the\n            packet to be sent to the Bluefruit LE module.\n\n    @param[in]  c\n                Character to send\n*/\n/******************************************************************************/\nsize_t Adafruit_BluefruitLE_SPI::write(uint8_t c)\n{\n  if (_mode == BLUEFRUIT_MODE_DATA)\n  {\n    sendPacket(SDEP_CMDTYPE_BLE_UARTTX, &c, 1, 0);\n    getResponse();\n    return 1;\n  }\n\n  // Following code handle BLUEFRUIT_MODE_COMMAND\n\n  // Final packet due to \\r or \\n terminator\n  if (c == '\\r' || c == '\\n')\n  {\n    if (m_tx_count > 0)\n    {\n      // +++ command to switch mode\n      if (m_mode_switch_command_enabled && memcmp(m_tx_buffer, \"+++\", 3) == 0)\n      {\n        simulateSwitchMode();\n      }else\n      {\n        sendPacket(SDEP_CMDTYPE_AT_WRAPPER, m_tx_buffer, m_tx_count, 0);\n      }\n      m_tx_count = 0;\n    }\n  }\n  // More than max packet buffered --> send with more_data = 1\n  else if (m_tx_count == SDEP_MAX_PACKETSIZE)\n  {\n    sendPacket(SDEP_CMDTYPE_AT_WRAPPER, m_tx_buffer, m_tx_count, 1);\n\n    m_tx_buffer[0] = c;\n    m_tx_count = 1;\n  }\n  // Not enough data, continue to buffer\n  else\n  {\n    m_tx_buffer[m_tx_count++] = c;\n  }\n\n  if (_verbose) SerialDebug.print((char) c);\n\n  return 1;\n}\n\n/******************************************************************************/\n/*!\n\n*/\n/******************************************************************************/\nsize_t Adafruit_BluefruitLE_SPI::write(const uint8_t *buf, size_t size)\n{\n  if ( _mode == BLUEFRUIT_MODE_DATA )\n  {\n    if (m_mode_switch_command_enabled &&\n        (size >= 3) &&\n        !memcmp(buf, \"+++\", 3) &&\n        !(size > 3 && buf[3] != '\\r' && buf[3] != '\\n') )\n    {\n      simulateSwitchMode();\n    }else\n    {\n      size_t remain = size;\n      while(remain)\n      {\n        size_t len = min(remain, SDEP_MAX_PACKETSIZE);\n        remain -= len;\n\n        sendPacket(SDEP_CMDTYPE_BLE_UARTTX, buf, (uint8_t) len, remain ? 1 : 0);\n        buf += len;\n      }\n\n      getResponse();\n    }\n\n    return size;\n  }\n  // Command mode\n  else\n  {\n    size_t n = 0;\n    while (size--) {\n      n += write(*buf++);\n    }\n    return n;\n  }\n}\n\n/******************************************************************************/\n/*!\n    @brief Check if the response from the previous command is ready\n\n    @return 'true' if a response is ready, otherwise 'false'\n*/\n/******************************************************************************/\nint Adafruit_BluefruitLE_SPI::available(void)\n{\n  if (! m_rx_fifo.empty() ) {\n    return m_rx_fifo.count();\n  }\n\n  if ( _mode == BLUEFRUIT_MODE_DATA )\n  {\n    // DATA Mode: query for BLE UART data\n    sendPacket(SDEP_CMDTYPE_BLE_UARTRX, NULL, 0, 0);\n\n    // Waiting to get response from Bluefruit\n    getResponse();\n\n    return m_rx_fifo.count();\n  }else\n  {\n    return (digitalRead(m_irq_pin));\n  }\n}\n\n/******************************************************************************/\n/*!\n    @brief Get a byte from response data, perform SPI transaction if needed\n\n    @return -1 if no data is available\n*/\n/******************************************************************************/\nint Adafruit_BluefruitLE_SPI::read(void)\n{\n  uint8_t ch;\n\n  // try to grab from buffer first...\n  if (!m_rx_fifo.empty()) {\n    m_rx_fifo.read(&ch);\n    return (int)ch;\n  }\n\n  if ( _mode == BLUEFRUIT_MODE_DATA )\n  {\n    // DATA Mode: query for BLE UART data\n    sendPacket(SDEP_CMDTYPE_BLE_UARTRX, NULL, 0, 0);\n\n    // Waiting to get response from Bluefruit\n    getResponse();\n  }else\n  {\n    // COMMAND Mode: Only read data from Bluefruit if IRQ is raised\n    if ( digitalRead(m_irq_pin) ) getResponse();\n  }\n\n  return m_rx_fifo.read(&ch) ? ((int) ch) : EOF;\n\n}\n\n/******************************************************************************/\n/*!\n    @brief Get a byte from response without removing it, perform SPI transaction\n           if needed\n\n    @return -1 if no data is available\n*/\n/******************************************************************************/\nint Adafruit_BluefruitLE_SPI::peek(void)\n{\n  uint8_t ch;\n\n  // try to grab from buffer first...\n  if ( m_rx_fifo.peek(&ch) ) {\n    return (int)ch;\n  }\n\n  if ( _mode == BLUEFRUIT_MODE_DATA )\n  {\n    // DATA Mode: query for BLE UART data\n    sendPacket(SDEP_CMDTYPE_BLE_UARTRX, NULL, 0, 0);\n\n    // Waiting to get response from Bluefruit\n    getResponse();\n  }else\n  {\n    // Read data from Bluefruit if possible\n    if ( digitalRead(m_irq_pin) ) getResponse();\n  }\n\n  return m_rx_fifo.peek(&ch) ? ch : EOF;\n}\n\n/******************************************************************************/\n/*!\n    @brief Flush current response data in the internal FIFO\n\n    @return -1 if no data is available\n*/\n/******************************************************************************/\nvoid Adafruit_BluefruitLE_SPI::flush(void)\n{\n  m_rx_fifo.clear();\n}\n\n/******************************************************************************/\n/*!\n    @brief  Try to perform an full AT response transfer from Bluefruit, or execute\n            as many SPI transaction as internal FIFO can hold up.\n\n    @note   If verbose is enabled, all the received data will be print to Serial\n\n    @return\n      - true  : if succeeded\n      - false : if failed\n*/\n/******************************************************************************/\nbool Adafruit_BluefruitLE_SPI::getResponse(void)\n{\n  // Try to read data from Bluefruit if there is enough room in the fifo\n  while ( m_rx_fifo.remaining() >= SDEP_MAX_PACKETSIZE )\n  {\n    // Get a SDEP packet\n    sdepMsgResponse_t msg_response;\n    memclr(&msg_response, sizeof(sdepMsgResponse_t));\n\n    if ( !getPacket(&msg_response) ) return false;\n\n    // Write to fifo\n    if ( msg_response.header.length > 0)\n    {\n      m_rx_fifo.write_n(msg_response.payload, msg_response.header.length);\n    }\n\n    // No more packet data\n    if ( !msg_response.header.more_data ) break;\n\n    // It takes a bit since all Data received to IRQ to get LOW\n    // May need to delay a bit for it to be stable before the next try\n    // delayMicroseconds(SPI_DEFAULT_DELAY_US);\n  }\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief      Perform a single SPI SDEP transaction and is used by getReponse to\n                get a full response composed of multiple packets.\n\n    @param[in]  buf\n                Memory location where payload is copied to\n\n    @return number of bytes in SDEP payload\n*/\n/******************************************************************************/\nbool Adafruit_BluefruitLE_SPI::getPacket(sdepMsgResponse_t* p_response)\n{\n  // Wait until IRQ is asserted, double timeout since some commands take long time to start responding\n  TimeoutTimer tt(2*_timeout);\n  \n  while ( !digitalRead(m_irq_pin) ) {\n    if (tt.expired()) return false;\n  }\n  \n  sdepMsgHeader_t* p_header = &p_response->header;\n\n  if (m_sck_pin == -1)\n    SPI.beginTransaction(bluefruitSPI);\n  SPI_CS_ENABLE();\n\n  tt.set(_timeout);\n\n  do {\n    if ( tt.expired() ) break;\n\n    p_header->msg_type = spixfer(0xff);\n\n    if (p_header->msg_type == SPI_IGNORED_BYTE)\n    {\n      // Bluefruit may not be ready\n      // Disable & Re-enable CS with a bit of delay for Bluefruit to ready itself\n      SPI_CS_DISABLE();\n      delayMicroseconds(SPI_DEFAULT_DELAY_US);\n      SPI_CS_ENABLE();\n    }\n    else if (p_header->msg_type == SPI_OVERREAD_BYTE)\n    {\n      // IRQ may not be pulled down by Bluefruit when returning all data in previous transfer.\n      // This could happen when Arduino MCU is running at fast rate comparing to Bluefruit's MCU,\n      // causing an SPI_OVERREAD_BYTE to be returned at stage.\n      //\n      // Walkaround: Disable & Re-enable CS with a bit of delay and keep waiting\n      // TODO IRQ is supposed to be OFF then ON, it is better to use GPIO trigger interrupt.\n\n      SPI_CS_DISABLE();\n      // wait for the clock to be enabled..\n//      while (!digitalRead(m_irq_pin)) {\n//        if ( tt.expired() ) break;\n//      }\n//      if (!digitalRead(m_irq_pin)) break;\n      delayMicroseconds(SPI_DEFAULT_DELAY_US);\n      SPI_CS_ENABLE();\n    }\n  }  while (p_header->msg_type == SPI_IGNORED_BYTE || p_header->msg_type == SPI_OVERREAD_BYTE);\n\n  bool result=false;\n\n  // Not a loop, just a way to avoid goto with error handling\n  do\n  {\n    // Look for the header\n    // note that we should always get the right header at this point, and not doing so will really mess up things.\n    while ( p_header->msg_type != SDEP_MSGTYPE_RESPONSE && p_header->msg_type != SDEP_MSGTYPE_ERROR && !tt.expired() )\n    {\n      p_header->msg_type = spixfer(0xff);\n    }\n    \n    if ( tt.expired() ) break;\n    \n    memset( (&p_header->msg_type)+1, 0xff, sizeof(sdepMsgHeader_t) - 1);\n    spixfer((&p_header->msg_type)+1, sizeof(sdepMsgHeader_t) - 1);\n\n    // Command is 16-bit at odd address, may have alignment issue with 32-bit chip\n    uint16_t cmd_id = word(p_header->cmd_id_high, p_header->cmd_id_low);\n\n    // Error Message Response\n    if ( p_header->msg_type == SDEP_MSGTYPE_ERROR ) break;\n\n    // Invalid command\n    if (!(cmd_id == SDEP_CMDTYPE_AT_WRAPPER ||\n          cmd_id == SDEP_CMDTYPE_BLE_UARTTX ||\n          cmd_id == SDEP_CMDTYPE_BLE_UARTRX) )\n    {\n      break;\n    }\n\n    // Invalid length\n    if(p_header->length > SDEP_MAX_PACKETSIZE) break;\n\n    // read payload\n    memset(p_response->payload, 0xff, p_header->length);\n    spixfer(p_response->payload, p_header->length);\n\n    result = true;\n  }while(0);\n\n  SPI_CS_DISABLE();\n  if (m_sck_pin == -1)\n    SPI.endTransaction();\n\n  return result;\n}\n\n/******************************************************************************/\n/*!\n\n*/\n/******************************************************************************/\nvoid Adafruit_BluefruitLE_SPI::spixfer(void *buff, size_t len) {\n  uint8_t *p = (uint8_t *)buff;\n\n  while (len--) {\n    p[0] = spixfer(p[0]);\n    p++;\n  }\n}\n\n/******************************************************************************/\n/*!\n\n*/\n/******************************************************************************/\nuint8_t Adafruit_BluefruitLE_SPI::spixfer(uint8_t x) {\n  if (m_sck_pin == -1) {\n    uint8_t reply = SPI.transfer(x);\n    //SerialDebug.println(reply, HEX);\n    return reply;\n  }\n\n  // software spi\n  uint8_t reply = 0;\n  for (int i=7; i>=0; i--) {\n    reply <<= 1;\n    digitalWrite(m_sck_pin, LOW);\n    digitalWrite(m_mosi_pin, x & (1<<i));\n    digitalWrite(m_sck_pin, HIGH);\n    if (digitalRead(m_miso_pin))\n      reply |= 1;\n  }\n  digitalWrite(m_sck_pin, LOW);\n  //SerialDebug.println(reply, HEX);\n  return reply;\n}\n"
  },
  {
    "path": "Adafruit_BluefruitLE_SPI.h",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BluefruiLE_SPI.h\n    @author   hathach, ktown (Adafruit Industries)\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2015, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n#ifndef _ADAFRUIT_BLE_SPI_H_\n#define _ADAFRUIT_BLE_SPI_H_\n\n#include <Adafruit_BLE.h>\n#include <SPI.h>\n#include \"utility/Adafruit_FIFO.h\"\n\n#define SPI_CS_ENABLE()           digitalWrite(m_cs_pin, LOW)\n#define SPI_CS_DISABLE()          digitalWrite(m_cs_pin, HIGH)\n\n#define SPI_IGNORED_BYTE          0xFEu /**< SPI default character. Character clocked out in case of an ignored transaction. */\n#define SPI_OVERREAD_BYTE         0xFFu /**< SPI over-read character. Character clocked out after an over-read of the transmit buffer. */\n#define SPI_DEFAULT_DELAY_US      50\n\n#define memclr(buffer, size)  memset(buffer, 0, size)\n\n\nclass Adafruit_BluefruitLE_SPI : public Adafruit_BLE\n{\n  private:\n    // Hardware Pin\n    int8_t          m_cs_pin;\n    int8_t          m_irq_pin;\n    int8_t          m_rst_pin;\n\n    // software SPI pins\n    int8_t          m_sck_pin;\n    int8_t          m_mosi_pin;\n    int8_t          m_miso_pin;\n\n    // TX\n    uint8_t         m_tx_buffer[SDEP_MAX_PACKETSIZE];\n    uint8_t         m_tx_count;\n\n    // RX\n    uint8_t         m_rx_buffer[BLE_BUFSIZE];\n    Adafruit_FIFO   m_rx_fifo;\n\n    bool            m_mode_switch_command_enabled;\n\n    // Low level transportation I/O functions\n    bool    sendInitializePattern(void);\n    bool    sendPacket(uint16_t command, const uint8_t* buffer, uint8_t count, uint8_t more_data);\n    bool    getPacket(sdepMsgResponse_t* p_response);\n\n    bool    getResponse(void);\n    void    simulateSwitchMode(void);\n//    bool    handleSwitchCmdInDataMode(uint8_t ch);\n\n    uint8_t spixfer(uint8_t x);\n    void spixfer(void *x, size_t len);\n\n  public:\n    // Constructor\n    Adafruit_BluefruitLE_SPI(int8_t csPin, int8_t irqPin, int8_t rstPin = -1);\n    Adafruit_BluefruitLE_SPI(int8_t clkPin, int8_t misoPin, int8_t mosiPin, int8_t csPin, int8_t irqPin, int8_t rstPin);\n\n    // HW initialisation\n    bool begin(boolean v = false, boolean blocking = true);\n    void end(void);\n\n    bool setMode(uint8_t new_mode);\n    void enableModeSwitchCommand(bool enabled);\n\n    // Class Print virtual function Interface\n    virtual size_t write(uint8_t c);\n    virtual size_t write(const uint8_t *buffer, size_t size);\n\n    // pull in write(str) and write(buf, size) from Print\n    using Print::write;\n\n    // Class Stream interface\n    virtual int  available(void);\n    virtual int  read(void);\n    virtual void flush(void);\n    virtual int  peek(void);\n};\n\n#endif\n"
  },
  {
    "path": "Adafruit_BluefruitLE_UART.cpp",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BluefruitLE_UART.cpp\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2015, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n/******************************************************************************/\n/*!\n    @brief Instantiates a new instance of the Adafruit_BluefruitLE_UART class\n*/\n/******************************************************************************/\nAdafruit_BluefruitLE_UART::Adafruit_BluefruitLE_UART(HardwareSerial &port, int8_t mode_pin, int8_t cts_pin, int8_t rts_pin) :\n  _mode_pin(mode_pin), _cts_pin(cts_pin), _rts_pin(rts_pin)\n{\n  _physical_transport = BLUEFRUIT_TRANSPORT_HWUART;\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  ss = 0;\n#endif\n\n  hs = &port;\n  mySerial = &port;\n}\n\n#if SOFTWARE_SERIAL_AVAILABLE\n/******************************************************************************/\n/*!\n    @brief Instantiates a new instance of the Adafruit_BluefruitLE_UART class\n           using software serial\n*/\n/******************************************************************************/\nAdafruit_BluefruitLE_UART::Adafruit_BluefruitLE_UART(SoftwareSerial &port, int8_t mode_pin, int8_t cts_pin, int8_t rts_pin) :\n  _mode_pin(mode_pin), _cts_pin(cts_pin), _rts_pin(rts_pin)\n{\n  _physical_transport = BLUEFRUIT_TRANSPORT_SWUART;\n\n  hs = 0;\n  ss = &port;\n  mySerial = &port;\n}\n#endif\n\n\n/******************************************************************************/\n/*!\n    @brief Class's Destructor\n*/\n/******************************************************************************/\nAdafruit_BluefruitLE_UART::~Adafruit_BluefruitLE_UART()\n{\n  end();\n}\n\n/******************************************************************************/\n/*!\n    @brief Initialize the HW to enable communication with the BLE module\n\n    @return Returns 'true' if everything initialised correctly, otherwise\n            'false' if there was a problem during HW initialisation. If\n            'irqPin' is not a HW interrupt pin false will be returned.\n*/\n/******************************************************************************/\nbool Adafruit_BluefruitLE_UART::begin(boolean debug, boolean blocking)\n{\n  _verbose = debug;\n  _intercharwritedelay = 0;\n\n  // If hardware mode pin is enabled, set it to CMD first\n  if ( _mode_pin >= 0)\n  {\n    pinMode(_mode_pin, OUTPUT);\n    digitalWrite(_mode_pin, BLUEFRUIT_MODE_COMMAND);\n\n    // A bit of delay to make sure mode change take effect\n    delay(1);\n  }\n\n  // Bluefruit baudrate is fixed to 9600\n  if (hs) {\n    hs->begin(9600);\n\n    #ifdef ARDUINO_STM32_FEATHER\n    hs->enableFlowControl();\n    #endif\n  } else {\n#if SOFTWARE_SERIAL_AVAILABLE\n    ss->begin(9600);\n#endif\n  }\n\n  if (_cts_pin > 0) {\n    pinMode(_cts_pin, OUTPUT);\n    digitalWrite(_cts_pin, HIGH);  // turn off txo\n  }\n    \n  if (_rts_pin > 0) {\n    pinMode(_rts_pin, INPUT);\n  }\n\n  mySerial->setTimeout(_timeout);\n  // reset Bluefruit module upon connect\n  return reset(blocking);\n}\n\n/******************************************************************************/\n/*!\n    @brief  Uninitializes the SPI interface\n*/\n/******************************************************************************/\nvoid Adafruit_BluefruitLE_UART::end(void)\n{\n  if (hs) {\n    hs->end();\n  } else {\n#if SOFTWARE_SERIAL_AVAILABLE\n    ss->end();\n#endif\n  }\n}\n\n/******************************************************************************/\n/*!\n    @brief  Set the hardware MODE Pin if it is enabled, or performs a SW based\n            mode switch if no MODE pin is available (SPI Friend, etc.)\n\n    @param[in]  mode\n                The mode to change to, either BLUEFRUIT_MODE_COMMAND or\n                BLUEFRUIT_MODE_DATA\n\n    @return     true if the mode switch was successful, otherwise false\n*/\n/******************************************************************************/\nbool Adafruit_BluefruitLE_UART::setMode(uint8_t new_mode)\n{\n  // invalid mode\n  if ( !(new_mode == BLUEFRUIT_MODE_COMMAND || new_mode == BLUEFRUIT_MODE_DATA) ) return false;\n\n  bool isOK;\n\n  if ( _mode_pin >= 0 )\n  {\n    // Switch mode using hardware pin\n    digitalWrite(_mode_pin, new_mode);\n    delay(1);\n    isOK = true;\n  } else\n  {\n    // Switch mode using +++ command, at worst switch 2 times\n    int32_t updated_mode;\n\n    isOK = atcommandIntReply(F(\"+++\"), &updated_mode);\n\n    if ( isOK )\n    {\n      // Ahhh, we are already in the wanted mode before sending +++\n      // Switch again. This is required to make sure it is always correct\n      if ( updated_mode != new_mode )\n      {\n        isOK = atcommandIntReply(F(\"+++\"), &updated_mode);\n        // Still does not match -> give up\n        if ( updated_mode != new_mode ) return false;\n      }\n    }\n  }\n\n  _mode = new_mode;\n\n  return isOK;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Print API. Either buffer the data internally or send it to bus\n            if possible. \\r and \\n are command terminators and will force the\n            packet to be sent to the Bluefruit LE module.\n\n    @param[in]  c\n                Character to send\n*/\n/******************************************************************************/\nsize_t Adafruit_BluefruitLE_UART::write(uint8_t c)\n{\n  // flush left-over before a new command\n//  if (c == '\\r') flush();\n\n  if (_verbose) SerialDebug.print((char) c);\n\n  if (_rts_pin >= 0) {\n    while (digitalRead(_rts_pin)) {\n      delay(1);\n    }\n  } else {\n    delay(_intercharwritedelay);\n  }\n\n  delayMicroseconds(50);\n  return mySerial->write(c);\n}\n\n/******************************************************************************/\n/*!\n    @brief Check if the response from the previous command is ready\n\n    @return 'true' if a response is ready, otherwise 'false'\n*/\n/******************************************************************************/\nint Adafruit_BluefruitLE_UART::available(void)\n{\n  if (!  mySerial->available() & (_cts_pin > 0)) {\n    // toggle flow control to get more byteses\n    digitalWrite(_cts_pin, LOW);\n    delay(1);\n    digitalWrite(_cts_pin, HIGH);\n  }\n  return mySerial->available();\n}\n\n/******************************************************************************/\n/*!\n    @brief Get a byte from response data, perform SPI transaction if needed\n\n    @return -1 if no data is available\n*/\n/******************************************************************************/\nint Adafruit_BluefruitLE_UART::read(void)\n{\n  int c = mySerial->read();\n  return c;\n}\n\n/******************************************************************************/\n/*!\n    @brief Get a byte from response without removing it, perform SPI transaction\n           if needed\n\n    @return -1 if no data is available\n*/\n/******************************************************************************/\nint Adafruit_BluefruitLE_UART::peek(void)\n{\n  return mySerial->peek();\n}\n\n/******************************************************************************/\n/*!\n    @brief Flush current response data in the internal FIFO\n\n    @return -1 if no data is available\n*/\n/******************************************************************************/\nvoid Adafruit_BluefruitLE_UART::flush(void)\n{\n  mySerial->flush();\n}\n"
  },
  {
    "path": "Adafruit_BluefruitLE_UART.h",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_BluefruitLE_UART.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2015, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#ifndef _ADAFRUIT_BLE_UART_H_\n#define _ADAFRUIT_BLE_UART_H_\n\n#include \"Arduino.h\"\n#include <Adafruit_BLE.h>\n\n#define SOFTWARE_SERIAL_AVAILABLE   ( ! (defined (_VARIANT_ARDUINO_DUE_X_) || defined (ARDUINO_ARCH_SAMD) || defined (ARDUINO_STM32_FEATHER)) )\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\nclass Adafruit_BluefruitLE_UART : public Adafruit_BLE\n{\n  private:\n    // Hardware Pins\n    int8_t  _mode_pin, _cts_pin, _rts_pin;\n    Stream *mySerial;\n#if SOFTWARE_SERIAL_AVAILABLE\n    SoftwareSerial *ss;\n#endif\n    HardwareSerial *hs;\n    boolean _debug;\n    uint8_t _intercharwritedelay;\n\n  public:\n    // Software Serial Constructor (0, 1, 2, or 3 pins)\n    Adafruit_BluefruitLE_UART(HardwareSerial &port,\n\t\t      int8_t mode_pin = -1, \n\t\t      int8_t cts_pin = -1, \n\t\t      int8_t rts_pin = -1);\n#if SOFTWARE_SERIAL_AVAILABLE\n    Adafruit_BluefruitLE_UART(SoftwareSerial &port,\n\t\t      int8_t mode_pin = -1, \n\t\t      int8_t cts_pin = -1, \n\t\t      int8_t rts_pin = -1);\n#endif\n\n    void setInterCharWriteDelay(uint8_t x) { _intercharwritedelay = x; };\n\n    virtual ~Adafruit_BluefruitLE_UART();\n\n    // HW initialisation\n    bool begin(boolean debug = false, boolean blocking = true);\n    void end(void);\n\n    bool setMode(uint8_t new_mode);\n\n    // Class Print virtual function Interface\n    virtual size_t write(uint8_t c);\n\n    // pull in write(str) and write(buf, size) from Print\n    using Print::write;\n\n    // Class Stream interface\n    virtual int  available(void);\n    virtual int  read(void);\n    virtual void flush(void);\n    virtual int  peek(void);\n};\n\n#endif\n"
  },
  {
    "path": "README.md",
    "content": "This library is for all nRF51 based Adafruit Bluefruit LE modules that use SPI or UART.\n\nCurrent nRF51 based Bluefruit LE products include:\n\n* [Bluefruit LE Friend](https://www.adafruit.com/product/2267)\n* [Bluefruit LE UART Friend](https://www.adafruit.com/product/2479)\n* [Bluefruit LE SPI Friend](https://www.adafruit.com/product/2633)\n* [Bluefruit LE Shield](https://www.adafruit.com/products/2746)\n* [Bluefruit LE Micro](https://www.adafruit.com/product/2661)\n* [Feather 32u4 Bluefruit LE](https://www.adafruit.com/product/2829)\n* [Feather M0 Bluefruit LE](https://www.adafruit.com/products/2995)\n\n# AT Commands\n\nThe Bluefruit LE modules this library talks to use AT-style commands and responses.\n\nIf you are using a UART board, the commands are sent directly as text using a SW serial transport.\n\nIf your are using an SPI board, the AT commands are wrapped in a thin **[SDEP](SDEP.md)** (Simple Data Exchange Protocol) wrapper to transmit and received text data over the binary SPI transport.  Details of this SPI transport layer are detailed in [SDEP.md](SDEP.md) in this same folder.\n\n# Hardware Setup\n\nThere are two variants of the nRF51 Bluefruit LE modules.  One uses SPI to communicate, the other uses UART with flow control (TXD, RXD, CTS, RTS).  The wiring you use will depend on the module you are trying to connect.\n\nOn both boards, power should be connected as shown below:\n\nBluefruit LE | Arduino Uno\n-------------|------------\nVIN          | 5V (assuming a 5V board)\nGND          | GND\n\n## Software UART Pinout\n\nIf you are using a UART Bluefruit LE board, your Arduino should be connected to the Bluefruit LE UART module using the following pinout:\n\nBluefruit LE UART | Arduino Uno\n------------------|------------\nRTS               | 8\nRXI               | 9\nTXO               | 10\nCTS               | 11\n\nOptional Pins\n\nBluefruit LE UART | Arduino Uno\n------------------|------------\nMODE              | 12\n\n## SPI Pinout\n\nIf you are using an SPI Bluefruit LE board, your Arduino should be connected to the Bluefruit LE SPI module using the following pinout:\n\nBluefruit LE SPI | Arduino Uno\n-----------------|------------\nSCLK             | 13\nMISO             | 12\nMOSI             | 11\nCS               | 8\nIRQ              | 7\n\nOptional Pins (enable these in the sample sketches)\n\nBluefruit LE SPI | Arduino Uno\n-----------------|------------\nRESET            | 6\n"
  },
  {
    "path": "SDEP.md",
    "content": "# SPI AT Command Transport Layer (SDEP)\n\nThis library transmits AT-style commands to the Bluefruit LE module over SPI using a custom protocol we've defined called SDEP, which stands for the **_Simple Data Exchange Protocol_**. \n\nSDEP is used to handle messages and responses, including error responses, and was designed to be _bus neutral_, meaning that we can use SDEP regardless of the transport mechanism (USB HID, SPI, I2C, Wireless data over the air, etc.).\n\nSDEP messages have a four byte header, and up to a 16 byte payload, and larger messages are broken into several message chunks which are rebuilt at either end of the transport bus.  The 20 byte limit (4 byte header + 16 byte payload) was chosen to take into account the size limitations present in some transport layers.\n\n# SPI Setup\n\nThe SPI interface uses the standard four SPI pins (MISO, MOSI, SCK and CS/SSEL), as well as an additional **IRQ** line (output from the nRF51822 to the SPI Master MCU).\n\n## IRQ Pin\n\nThe IRQ line is asserted as long as an entire SDEP packet is available in the buffer on the nRF51822, at which point you should read the packet, keeping the CS line asserted for the entire transaction (as detailed below).  \n\nThe IRQ line will remain asserted as long as one or more packets are available, so the line may stay high after reading a packet, meaning that more packets are still available in the FIFO on the SPI slave side.\n\n## SPI Bus Hardware Requirements\n\nThe SPI peripheral block on the nRF51822 MCU has some specific limitations that need to be taken into account when communicating with it as an SPI slave:\n\n* The SPI clock should run <=2MHz\n* A 100us delay should be added between the moment that the CS line is asserted, and before any data is transmitted on the SPI bus\n* The CS line should remain asserted for the entire packet, rather than toggling CS every byte\n\n## SDEP Packet and SPI Error Identifier\n\nOnce CS has been asserted and the mandatory 100us delay has passed, a single byte should be read from the SPI bus which will indicate the type of payload available on the nRF51822 (see **Message Type Indicator** below for more information on SDEP message types). Keep CS asserted after this byte has been read in case you need to continue reading the rest of the frame.\n\nIf a standard SDEP message type indicators (0x10, 0x20, 0x40 or 0x80) is encountered, keep reading as normal.  There are two other indicators that should be taken into account, though, which indicate a problem on the nRF51822 SPI slave side:\n\n* **0xFE**: Slave device not ready (wait a bit and try again)\n* **0xFF**: Slave device read overflow indicator (you've read more data than is available)\n\n## Sample Transaction\n\nThe following image shows a sample SDEP response that is spread over two packets (since the response is > 20 bytes in size). Notice that the IRQ line stays asserted between the packets since more than one was available in the FIFO on the nRF51822 side:\n\n![sdepexample_twopackets](https://cloud.githubusercontent.com/assets/181073/8234310/646b7498-15db-11e5-9c69-6366c5dd433a.png)\n\n# SDEP (Simple Data Exchange Protocol)\n\nThe Simple Data Exchange Protocol (SDEP) can be used to send and receive binary messages between two connected devices using any binary serial bus (USB HID, USB Bulk, SPI, I2C, Wireless, etc.), exchanging data using one of four distinct message types (Command, Response, Alert and Error messages).\n\nThe protocol is designed to be flexible and extensible, with the only requirement being that **individual messages are 20 bytes or smaller**, and that the first byte of every message is a one byte (U8) identifier that indicates the message type, which defines the format for the remainder of the payload.\n\n## Endianness\n\nAll values larger than 8-bits are encoded in little endian format.  Any deviation from this rule should be clearly documented.\n\n## Message Type Indicator\n\nThe first byte of every message is an 8-bit identifier called the **Message Type Indicator**. This value indicates the type of message being sent, and allows us to determine the format for the remainder of the message.\n\n| Message Type | ID (U8) | Description |\n| ------------ | ------- | ----------- |\n| Command      | 0x10    |             |\n| Response     | 0x20    |             |\n| Alert        | 0x40    |             |\n| Error        | 0x80    |             |\n\n## SDEP Data Transactions\n\nEither connected device can initiate SDEP transactions, though certain transport protocols imposes restrictions on who can initiate a transfer. The _master_ device, for example, always initiates transactions with Bluetooth Low Energy or USB, meaning that _slave_ devices can only reply to incoming commands.\n\nEvery device that receives a _Command Message_ must reply with a _Response Message_, _Error Message_ or _Alert message_.\n\nThe following diagram illustrates how an SDEP exchange typically takes place. A Command Message is sent, and a reply will be generated based on whether the command was accepted (in which case a Response Message will be sent in reply), if the command was invalid or rejected (in which case an Error Message reply will be sent), or if the command was valid but some specific condition occurred that should be indicated to the master device (in which case an Alert Message will be sent):\n\n**ToDo: Insert two line master/slave chart showing message flow in different scenarios**\n\n## Message Types\n\n### Command Messages\n\nCommand messages (Message Type = 0x10) have the following structure:\n\n| Name            | Type | Meaning                                           |\n| --------------- | ---- | ------------------------------------------------- |\n| Message Type    | U8   | Always '0x10'                                     |\n| Command ID      | U16  | Unique command identifier                         |\n| Payload Length  | U8   | [7] More data <br> [6-5] Reserved <br> [4-0] Payload length (0..16) |\n| Payload         | ...  | Optional command payload (parameters, etc.)       |\n\n**Command ID** (bytes 1-2) and **Payload Length** (byte 3) are mandatory in any command message.  The message payload is optional, and will be ignored if Payload Length is set to 0 bytes.  When a message payload is present, it’s length can be anywhere from 1..16 bytes, to stay within the 20-byte maximum message length.\n\nA long command (>16 bytes payload) must be divided into multiple packets. To facilitate this, the **More data** field (bit 7 of byte 3) is used to indicate whether additional packets are available for the same command. The SDEP receiver must continue to reads packets until it finds a packet with **More data == 0**, then assemble all sub-packets into one command if necessary.\n\nThe contents of the payload are user defined, and can change from one command to another.\n\nA sample command message would be:\n\n| 0: Message Type (U8) | 1+2: Command ID (U16) | 3: Payload Len (U8) | 4: Payload (...) |\n| -------------------- | --------------------- | ------------------- | ---------------- |\n| 10                   | 34 12                 | 01                  | FF               |\n\n- The first byte is the Message Type (0x10), which identifies this as a command message.\n- The second and third bytes are 0x1234 (34 12 in little-endian notation), which is the unique command ID. This value will be compared against the command lookup table and redirected to an appropriate command handler function if a matching entry was found.\n- The fourth byte indicates that we have a message payload of 1 byte\n- The fifth byte is the 1 byte payload: 0xFF\n\n### Response Messages\n\nResponse messages (Message Type = 0x20) are generated in response to an incoming command, and have the following structure:\n\n| Name            | Type | Meaning                                           |\n| --------------- | ---- | ------------------------------------------------- |\n| Message Type    | U8   | Always '0x20'                                     |\n| Command ID      | U16  | Command ID of the command this message is a response to, to correlated responses and commands |\n| Payload Length  | U8   | [7] More data <br> [6-5] Reserved <br> [4-0] Payload length (0..16) |\n| Payload         | ...  | Optional response payload (parameters, etc.)      |\n\nBy including the **Command ID** that this response message is related to, the recipient can more easily correlate responses and commands.  This is useful in situations where multiple commands are sent, and some commands may take a longer period of time to execute than subsequent commands with a different command ID.\n\nResponse messages can only be generate in response to a command message, so the Command ID field should always be present.\n\nA long response (>16 bytes payload) must be divided into multiple packets. Similar to long commands, the **More data** field (bit 7 of byte 3) is used to indicate whether additional packets are available for the same response. On responses that span more than one packet, the **More data** bit on the final packet will be set to `0` to indicate that this is the last packet in the sequence. The SDEP receiver must re-assemble all sub-packets in into one payload when necessary.\n\nIf more precise command/response correlation is required a custom protocol should be developed, where a unique message identifier is included in the payload of each command/response, but this is beyond the scope of this high-level protocol definition.\n\nA sample response message would be:\n\n| 0: Message Type (U8) | 1+2: Command ID (U16) | 3: Payload Len (U8) | 4: Payload (...) |\n| -------------------- | --------------------- | ------------------- | ---------------- |\n| 20                   | 34 12                 | 01                  | FF               |\n\n- The first byte is the Message Type (0x20), which identifies this as a response message.\n- The second and third bytes are 0x1234, which is the unique command ID that this response is related to.\n- The fourth byte indicates that we have a message payload of 1 byte.\n- The fifth byte is the 1 byte payload: 0xFF\n\n### Alert Messages\n\nAlert messages (Message Type = 0x40) are sent whenever an alert condition is present on the system (low battery, etc.), and have the following structure:\n\n| Name            | Type | Meaning                                           |\n| --------------- | ---- | ------------------------------------------------- |\n| Message Type    | U8   | Always '0x40'                                     |\n| Alert ID        | U16  | Unique ID for the alert condition                 |\n| Payload Length  | U8   | Payload length (0..16)                            |\n| Payload         | ...  | Optional response payload (parameters, etc.)      |\n\nA sample alert message would be:\n\n| 0: Message Type (U8) | 1+2: Alert ID (U16)   | 3: Payload Len (U8) | 4+5+6+7: Payload  |\n| -------------------- | --------------------- | ------------------- | ----------------- |\n| 40                   | CD AB                 | 04                  | 42 07 00 10       |\n\n- The first byte is the Message Type (0x40), which identifies this as an alert message.\n- The second and third bytes are 0xABCD, which is the unique alert ID.\n- The fourth byte indicates that we have a message payload of 4 bytes.\n- The last four bytes are the actual payload: `0x10000742` in this case, assuming we were transmitting a 32-bit value in little-endian format.\n\n#### Standard Alert IDs\n\nAlert IDs in the range of 0x0000 to 0x00FF are reserved for standard SDEP alerts, and may not be used by custom alerts.\n\nThe following alerts have been defined as a standard part of the protocol:\n\n| ID     | Alert Description | Description                          |\n| ------ | ----------------- | ------------------------------------ |\n| 0x0000 | Reserved          | Reserved for future use              |\n| 0x0001 | System Reset      | The system is about the reset        |\n| 0x0002 | Battery Low       | The battery level is low             |\n| 0x0003 | Battery Critical  | The battery level is critically low  |\n\n### Error Messages\n\nError messages (Message Type = 0x80) are returned whenever an error condition is present on the system, and have the following structure:\n\n| Name            | Type | Meaning                                           |\n| --------------- | ---- | ------------------------------------------------- |\n| Message Type    | U8   | Always '0x80'                                     |\n| Error ID        | U16  | Unique ID for the error condition                 |\n| Reserved        | U8   | Reserved for future use                           |\n\nWhenever an error condition is present and the system needs to be alerted (such as a failed request, an attempt to access a non-existing resource, etc.) the system can return a specific error message with an appropriate Error ID.\n\nA sample error message would be:\n\n| 0: Message Type (U8) | 1+2: Error ID (U16)   | 3: Reserved (U8) |\n| -------------------- | --------------------- | ---------------- |\n| 80                   | 01 00                 | 00               |\n\n- The first byte is the Message Type (0x80), which identifies this as an error message.\n- The second and third bytes are 0x0001 (01 00 in little-endian notation), which indicates that the supplied Command ID was invalid (see Standard Error IDs below).\n- The last byte is reserved and should be 0x00 and ignored.\n\n#### Standard Error IDs\n\nError IDs in the range of 0x0000 to 0x00FF are reserved for standard SDEP errors, and may not be used by custom errors.\n\nThe following errors have been defined as a standard part of the protocol:\n\n| ID     | Error Description | Description                                     |\n| ------ | ----------------- | ----------------------------------------------- |\n| 0x0000 | Reserved          | Reserved for future use                         |\n| 0x0001 | Invalid Cmd ID    | The command ID wasn't found in the lookup table |\n| 0x0003 | Invalid Payload   | The message payload was invalid                 |\n"
  },
  {
    "path": "changelog.md",
    "content": "# Arduino Changelog\n\n## 1.10\n\n- Add non-blokcing option for .reset(blocking) & .factoryReset(blocking). The reset progress can be polled by .resetCompleted()\n- Add callback using dfu as irq pin example, .handleDfuIrq() is expected to be call in loop()\n\n## 1.9\n\n### Features\n\n- Added **Adafruit_ATParser** helper class to facilitate sending and receiving AT commands:\n\t- `.atcommand()` : Send a command without reply (several variants defined for various input parameters)\n\t- `.atcommandIntReply()` : Send a command with integer reply (several variants defined for various input parameters)\n\t- `.atcommand_full()` : General purpose command execution with a pointer to the reply buffer\n\t- `.printByteArray()` : Outputs a byte array in the `AA-BB-CC` format from a buffer. Useful for executing AT commands.\n\t- `.waitForOK()` : Uses a separate temporary buffer to avoid overwriting response content.\n- Callback support in **Adafruit_BLE** class\n\t- Supported Events are:\n\t\t- **Connect**: Set using `setConnectCallback()`\n\t\t- **Disconnect**: Set using `setDisconnectCallback()`\n\t\t- **BLE UART RX**: Set using `.setBleUartRxCallback()`\n\t\t- **MIDI RX**: Set using `.setBleMidiRxCallback()`\n\t\t- **GATT Characteristic RX**: Set using `.setBleGattRxCallback()`\n\t- `.update(ms)` must be placed in the loop() function to fire the callbacks, where `ms` is the interval in milliseconds to poll for new events\n\t- See 'examples/callbacks' for more details\n- Added **Adafruit_BLEGatt** helper class to make working with custom GATT services and characteristics easier:\n\t- Helpers to add custom GATT services and characteristics\n\t- Helpers to read/write previously defined characteristics\n\t- Callback support for characteristic updates\n\t- Added **User Description** and **Presentation Format** support for GATT characteristics\n\t- Add `BLEDataType_t` typedef for GATT characteristics\n\t- See 'example/healththermometer' for an example of using the Adafruit_BLEGatt class\n- Added BLE MIDI service support with the **Adafruit_BLEMIDI** class\n\t-  See 'examples/midi' for details\n- Added BLE Battery service support via the **Adafruit_BLEBattery** class\n\t- See 'example/battery' for more details\n- Added BLE Eddystone helper class to facilitate using Eddystone beacon\n\t- See 'example/eddystone' for more details\n- Add a 256 byte user NVM data section that can be accessed via `.writeNVM()` and `.readNVM()` in **Adafruit_BLE**. User can use this small chunk of NVM memory to store application specific data.\n\t- See 'example/nvmdata' for more details\n- Additional **Adafruit_BLE** class changes:\n\t- Added a `setAdvData()` helper to advertise custom data payloads\n"
  },
  {
    "path": "changelog_firmware.md",
    "content": "# Firmware Changelog\n\n## 0.8.0\n\n- improve stability of nvm\n\n## 0.7.7\n\n### Features\n\n- Add `AT+BLEUARTTXF` (F for force) to immediately send data as it is in an BLE Packet\n- Adjust bleuart sending interval based on min connection interval\n- Add `AT+DFUIRQ` to enable using DFU Pin for IRQ purpose when there is new events from nrf51\n- Enable CS pull up for Bluefruit SPI\n- Add `AT+MODESWITCHEN` to enable/disable +++ mode switch from local (serial/spi) or bleuart. Default local = enabled, ble = disable. Command can only be executed via local interface.\n- Implement '\\+' escape to immediate send '+' without trigger +++ waiting\n- Add `AT+BLEHIDGAMEPADEN` to separately enable HID Gamepad, since iOS/OSX conflict with gamepad device that cause the HID keyboard not working properly.\n\n### Bug fixes\n\n- fix factory reset after a long time no reset in app_error_handler()\n- fix Strings truncated at 64 chars in UART\n- fix HID keyboard does not work with iOS 9 & 10\n\n## 0.7.0\n\n### Features\n\n- BTLE UART speed and stability improvements\n- HW UART\n\t- `AT+Baudrate` to change HW UART baud rate\n\t- `AT+uartflow` to enable/disable HW UART flow control\n- MIDI (work in progress)\n\t- `AT+BLEMIDIEN=on/off/0/1` to enable/disable MIDI service, requires a reset to take affect\n\t- `AT+BLEMIDITX=midi event` to send MIDI event(s)\n\t- `AT+BLEMIDIRX` to receive MIDI event(s)\n- GATT server\n\t- Added `DATATYPE` option to `AT+GATTADDCHAR`. Valid options are : AUTO (0, default), STRING (1), BYTEARRAY (2), INTEGER (3) \n\t- Added `AT+GATTCHARRAW` (read-only) to read binary data (instead of ascii) from a characteristic. It is non-printable but has less overhead and is easier to use when writing libraries for Arduino. \n\t- Reworked memory management for Service & Characteristics in NVM\n\t- Increased MAX_LEN for each characteristic from 20 to 32 bytes\n\t- Added Characteristic User Description support via the `DESCRIPTION` flag\n\t- Added Characteristic Presentation Format support via the `PRESENTATION` flag\n- NVM user data allowing users to store data in a dedicated NVM section (up to 256 bytes)\n\t- `AT+NVMWRITE=offset,datatype,data` where datatype must be STRING (1), BYTEARRAY (2), or INTEGER (3)\n\t- `AT+NVMREAD=offset,size,datatype` to read data back\n\t- `AT+NVMREADRAW=offset,size`  binary data (instead of ascii) is returned ended with OK\\r\\n. It is non-printable but less overhead and easier to use when writing libraries in Arduino. \n- Simple callback implementation (work in progress)\n\t- BLTE UART rx\n\t- GATT chars rx\n\t- MIDI rx\n\t- Connect/Disconnect\n- HID Service: \n\t- Added pre-defined consumer \"EJECT\" which can be used to hide/show keyboard layout on iOS\n\t- Added HID Gamepad `at+blehidgamepad=x,y.buttons` where\n\t\t- X corresponds to LEFT, RIGHT: X=-1 means LEFT is pressed, X=1 means RIGHT is pressed, X=0 nothing pressed\n\t\t- Y corresponds to UP, DOWN: Y=-1 means UP, Y=1 means DOWN, Y=0 nothing pressed\n\t\t- Button [0x00-0xFF] is a bit mask for 8 buttons, 0-7 \n- GAP: changed default parameters\n\t- ADV interval = 20 ms\n\t- Min connection interval = 20 ms\n\t- Max connection interval = 40 ms\n\t- Added `AT+GAPCONNECTABLE=on/off/1/0` to allow/disallow connection to device.\n\t- Added LOW Power Adv Interval to `AT+GAPINTERVALS=min_conn,max_conn,adv_interval,adv_timeout,adv_lowpower_interval`, default is 417.5 ms\n\t- Increased maximum number of CCCD records saved to flash from 8 to 16\n- EddyStone Service\n\t- Eddystone config service disabled by default\n\t- Removed AT+EDDYSTONEENABLE to avoid confusion due to name (use AT+EDDYSTONESERVICEEN)\n\t- Added AT+EDDYSTONESERVICEEN to add/remove EddyStone service to GATT table (requires a reset)\n\t- Added AT+EDDYSTONEBROADCAST=on/off/0/1 to start/stop broadcasting url using nvm saved setting\n\t- Changed adv timeout for Eddystone to unlimited\n- Battery Service\n\t- Added `AT+BLEBATTEN=on/off/1/0` to enable Battery service. Reset required.\n\t- Added `AT+BLEBATTVAL=percent` to update the Battery level, percent is 0 to 100\n\n### Bug Fixes\n\n- Fixed a bug where 'Write-No-Response' characteristic properties weren't being handled properly\n- Fixed timing constraints to meet Apple design guidelines\n- Corrected systick to ms calculation, optimized 64bit division by using shifter\n- Fixed all the tests with google Eddystone validator except for writing tx_power = 1 dB (not valid on nrf51)\n- Fixed a big where writing from a central does not update value on characteristic correctly\n- Fixed an issue with HID examples, where when paired with a central, a disconnect then reconnect meant you could not send reports anymore.\n\n## 0.6.7\n\n### Features\n\n- EddyStone/Uribeacon\n\t- Add TX Power to AT+EddyStoneUrl: `AT+EDDYSTONEURL=URL,[ADVWHENCONNECTED=0],[RSSI@0M=-18]`\n\t- Enable reading the current url: `AT+EDDYSTONEURL`\n- Increase FIFO size for \n\t- AT command fifo from 160 to 256 byte\n\t- BLE UART TX fifo from 160 to 1024 bytes\n\t- SPI RX fifo from 160 to 1024 bytes\n- Add command to return free FIFO size for BLE UART:\n\tAT+BLEUARTFIFO\n\t0,1024\n\tAT+BLEUARTFIFO=TX\n\t0\n\tAT+BLEUARTFIFO=RX\n\t1024\n- Keep URI UUID\n\t- AT+BLEURIBEACON will use the legacy uuid 0xFED8\n\t- AT+EDDYSTONEURL will use the eddystone uuid 0xFEAA\n- Add escape '\\' when sending A SINGLE '?' due to conflict with AT command existence test mode\n\t- AT+BLEUARTTX=\\?\n\t- AT+BLEKEYBOARD=\\?\n\n### Bug Fixes\n\n- Fix and improve BLE UART TX fifo overflow, wait up to 200 ms for fifo to free up some spaces, return ERROR if timed out. Note: a single BLE UART TX command can have ~200 bytes, the command may need to wait several turns (each is 200ms timeout), thus the total timeout can be longer depending on the FIFO state and the sending rate from the Central/Host device. Arudino's library has its own timer and can be timeout before the sending is done !!!!!\n- Fix the factory reset issue if the Bluefruit is running for a long time (> 4 hours).\n- fix a problem with gatt server: incorrect value_len parsing for characteristics's integer with max_len >4 \n\n## 0.6.6\n\n### Features\n\n- Added basic [Eddystone](https://github.com/google/eddystone) support (currently [URL mode](https://github.com/google/eddystone/tree/master/eddystone-url) only):\n\t- AT+EDDYSTONEURL : Update the url for the beacon and go to beacon mode\n\t- AT+EDDYSTONEENABLE : Enable/disable beacon mode using the configured url\n\t- AT+EDDYSTONECONFIGEN : Enable the Eddystone configuration service \n- AT+HWMODELED enhancements. The MODE LED can now be set to:\n\t- DISABLE - No LED activity (to save power)\n\t- UART/DATA Mode - Indicate current operating mode (command or DATA) - DEFAULT\n\t- HWUART - LED toggles on HW UART activity\n\t- BLEUART - LED toggles on nRF/BLE UART activity (the Nordic UART Service)\n\t- SPI - LED toggles on SPI activity\n\t- MANUAL - Allows manual control of the LED via a second ON/OFF/TOGGLE parameter\n- Added HID Keyboard Consumer Control support via AT+BLECONTROLKEY\n- Added HID mouse support:\n\t- AT+BLEHIDEN=on/off/0/1 added to enable all HID devices (including keyboard & mouse).\n\t- AT+BLEKEYBOARDEN is now an alias to AT+BLEHIDEN\n\t- AT+BLEMOUSEMOVE to move the cursor (does not affect mouse buttons)\n\t- AT+BLEMOUSEBUTTON to perform button actions\n- Added `uuid128` option for AT+GATTADDCHAR: Custom characteristics can now have a different UUID base than the parent service UUID.\n- Lower requirement of at+blekeyboardcode to minimum 1 parameter instead of 2\n\n### Bug Fixes\n\n- Fixed #156 UriBeacon Resets After n Hours\n- Fixed issues with long beacon URLs, e.g at+bleuribeacon=http://www.adafruit.com/012345678\n- Fixed big endian issue in at+blebeacon for major & minor number\n\n### Known Issues\n\n- It seems Windows 10 has a limited number of characteristics for DIS service. We had to disable the Serial Number characteristic to enable HID support with windows 10. \n\n## 0.6.5\n\n* **AT Parser**: Fixed https://github.com/adafruit/Adafruit_BluefruitLE_nRF51/issues/2 (When resetting, dynamic GATT characteristics always use min_len when repopulating char values, not the actual value length.)\n* **SDEP/SPIS**: rework SPI slave communication implementation to increase performance and stability.\n"
  },
  {
    "path": "examples/atcommand/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        160   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/atcommand/atcommand.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n? ? FACTORYRESET_ENABLE? ?  Perform a factory reset when running this sketch\n? ?\n? ?                         Enabling this will put your Bluefruit LE module\n                            in a 'known good' state and clear any config\n                            data set in previous sketches or projects, so\n? ?                         running this at least once is a good idea.\n? ?\n? ?                         When deploying your project, however, you will\n                            want to disable factory reset by setting this\n                            value to 0.? If you are making changes to your\n? ?                         Bluefruit LE device via AT commands, and those\n                            changes aren't persisting across resets, this\n                            is the reason why.? Factory reset will erase\n                            the non-volatile memory where config data is\n                            stored, setting it back to factory default\n                            values.\n? ? ? ?\n? ?                         Some sketches that require you to bond to a\n                            central device (HID mouse, keyboard, etc.)\n                            won't work at all with this feature enabled\n                            since the factory reset will clear all of the\n                            bonding data stored on the chip, meaning the\n                            central device won't be able to reconnect.\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE      1\n/*=========================================================================*/\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit AT Command Example\"));\n  Serial.println(F(\"-------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  // Display command prompt\n  Serial.print(F(\"AT > \"));\n\n  // Check for user input and echo it back if anything was found\n  char command[BUFSIZE+1];\n  getUserInput(command, BUFSIZE);\n\n  // Send command\n  ble.println(command);\n\n  // Check response status\n  ble.waitForOK();\n}\n\n/**************************************************************************/\n/*!\n    @brief  Checks for user input (via the Serial Monitor)\n*/\n/**************************************************************************/\nvoid getUserInput(char buffer[], uint8_t maxSize)\n{\n  memset(buffer, 0, maxSize);\n  while( Serial.available() == 0 ) {\n    delay(1);\n  }\n\n  uint8_t count=0;\n\n  do\n  {\n    count += Serial.readBytes(buffer+count, maxSize);\n    delay(2);\n  } while( (count < maxSize) && !(Serial.available() == 0) );\n}\n"
  },
  {
    "path": "examples/battery/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/battery/battery.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#include \"Adafruit_BLEBattery.h\"\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE     Perform a factory reset when running this sketch\n   \n                            Enabling this will put your Bluefruit LE module\n                            in a 'known good' state and clear any config\n                            data set in previous sketches or projects, so\n                            running this at least once is a good idea.\n   \n                            When deploying your project, however, you will\n                            want to disable factory reset by setting this\n                            value to 0.  If you are making changes to your\n                            Bluefruit LE device via AT commands, and those\n                            changes aren't persisting across resets, this\n                            is the reason why.  Factory reset will erase\n                            the non-volatile memory where config data is\n                            stored, setting it back to factory default\n                            values.\n       \n                            Some sketches that require you to bond to a\n                            central device (HID mouse, keyboard, etc.)\n                            won't work at all with this feature enabled\n                            since the factory reset will clear all of the\n                            bonding data stored on the chip, meaning the\n                            central device won't be able to reconnect.\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE      1\n/*=========================================================================*/\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\nAdafruit_BLEBattery battery(ble);\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\nint value = 100;\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit AT Command Example\"));\n  Serial.println(F(\"-------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  // Enable Battery service and reset Bluefruit\n  battery.begin(true);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  // Should get Battery value from LIPO and update\n  Serial.print(\"Update battery level = \");\n  Serial.println(value);\n  \n  battery.update(value);\n  \n  value--;\n  if (value == 0) value = 100;\n  \n  delay(5000);\n}\n\n"
  },
  {
    "path": "examples/beacon/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/beacon/beacon.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE     Perform a factory reset when running this sketch\n    \n                            Enabling this will put your Bluefruit LE module\n                            in a 'known good' state and clear any config\n                            data set in previous sketches or projects, so\n                            running this at least once is a good idea.\n   \n                            When deploying your project, however, you will\n                            want to disable factory reset by setting this\n                            value to 0.  If you are making changes to your\n                            Bluefruit LE device via AT commands, and those\n                            changes aren't persisting across resets, this\n                            is the reason why.  Factory reset will erase\n                            the non-volatile memory where config data is\n                            stored, setting it back to factory default\n                            values.\n       \n                            Some sketches that require you to bond to a\n                            central device (HID mouse, keyboard, etc.)\n                            won't work at all with this feature enabled\n                            since the factory reset will clear all of the\n                            bonding data stored on the chip, meaning the\n                            central device won't be able to reconnect.\n\n    BEACON_MANUFACTURER_ID  Company Identifier assigned by Bluetooth SIG\n                            Full list of Manufacturer ID can be found here\n                            https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers\n    BEACON_UUID             16-bytes UUID in hex format AA-BB-...\n    BEACON_MAJOR            16-bit major nunber\n    BEACON_MINOR            16-bit minor nunber\n    BEACON_RSSI_1M\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE      1\n\n    #define MANUFACTURER_APPLE         \"0x004C\"\n    #define MANUFACTURER_NORDIC        \"0x0059\"\n\n    #define BEACON_MANUFACTURER_ID     MANUFACTURER_APPLE\n    #define BEACON_UUID                \"01-12-23-34-45-56-67-78-89-9A-AB-BC-CD-DE-EF-F0\"\n    #define BEACON_MAJOR               \"0x0000\"\n    #define BEACON_MINOR               \"0x0000\"\n    #define BEACON_RSSI_1M             \"-54\"\n/*=========================================================================*/\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit Beacon Example\"));\n  Serial.println(F(\"---------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  Serial.println(F(\"Setting beacon configuration details: \"));\n\n  // AT+BLEBEACON=0x004C,01-12-23-34-45-56-67-78-89-9A-AB-BC-CD-DE-EF-F0,0x0000,0x0000,-54\n  ble.print(\"AT+BLEBEACON=\"        );\n  ble.print(BEACON_MANUFACTURER_ID ); ble.print(',');\n  ble.print(BEACON_UUID            ); ble.print(',');\n  ble.print(BEACON_MAJOR           ); ble.print(',');\n  ble.print(BEACON_MINOR           ); ble.print(',');\n  ble.print(BEACON_RSSI_1M         );\n  ble.println(); // print line causes the command to execute\n\n  // check response status\n  if (! ble.waitForOK() ) {\n    error(F(\"Didn't get the OK\"));\n  }\n\n  Serial.println();\n  Serial.println(F(\"Open your beacon app to test\"));\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n}\n"
  },
  {
    "path": "examples/bleuart_cmdmode/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/bleuart_cmdmode/bleuart_cmdmode.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE       Perform a factory reset when running this sketch\n   \n                              Enabling this will put your Bluefruit LE module\n                              in a 'known good' state and clear any config\n                              data set in previous sketches or projects, so\n                              running this at least once is a good idea.\n   \n                              When deploying your project, however, you will\n                              want to disable factory reset by setting this\n                              value to 0.  If you are making changes to your\n                              Bluefruit LE device via AT commands, and those\n                              changes aren't persisting across resets, this\n                              is the reason why.  Factory reset will erase\n                              the non-volatile memory where config data is\n                              stored, setting it back to factory default\n                              values.\n       \n                              Some sketches that require you to bond to a\n                              central device (HID mouse, keyboard, etc.)\n                              won't work at all with this feature enabled\n                              since the factory reset will clear all of the\n                              bonding data stored on the chip, meaning the\n                              central device won't be able to reconnect.\n    MINIMUM_FIRMWARE_VERSION  Minimum firmware version to have some new features\n    MODE_LED_BEHAVIOUR        LED activity, valid options are\n                              \"DISABLE\" or \"MODE\" or \"BLEUART\" or\n                              \"HWUART\"  or \"SPI\"  or \"MANUAL\"\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE         1\n    #define MINIMUM_FIRMWARE_VERSION    \"0.6.6\"\n    #define MODE_LED_BEHAVIOUR          \"MODE\"\n/*=========================================================================*/\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(Serial1, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit Command Mode Example\"));\n  Serial.println(F(\"---------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  Serial.println(F(\"Please use Adafruit Bluefruit LE app to connect in UART mode\"));\n  Serial.println(F(\"Then Enter characters to send to Bluefruit\"));\n  Serial.println();\n\n  ble.verbose(false);  // debug info is a little annoying after this point!\n\n  /* Wait for connection */\n  while (! ble.isConnected()) {\n      delay(500);\n  }\n\n  // LED Activity command is only supported from 0.6.6\n  if ( ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )\n  {\n    // Change Mode LED Activity\n    Serial.println(F(\"******************************\"));\n    Serial.println(F(\"Change LED activity to \" MODE_LED_BEHAVIOUR));\n    ble.sendCommandCheckOK(\"AT+HWModeLED=\" MODE_LED_BEHAVIOUR);\n    Serial.println(F(\"******************************\"));\n  }\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  // Check for user input\n  char inputs[BUFSIZE+1];\n\n  if ( getUserInput(inputs, BUFSIZE) )\n  {\n    // Send characters to Bluefruit\n    Serial.print(\"[Send] \");\n    Serial.println(inputs);\n\n    ble.print(\"AT+BLEUARTTX=\");\n    ble.println(inputs);\n\n    // check response stastus\n    if (! ble.waitForOK() ) {\n      Serial.println(F(\"Failed to send?\"));\n    }\n  }\n\n  // Check for incoming characters from Bluefruit\n  ble.println(\"AT+BLEUARTRX\");\n  ble.readline();\n  if (strcmp(ble.buffer, \"OK\") == 0) {\n    // no data\n    return;\n  }\n  // Some data was found, its in the buffer\n  Serial.print(F(\"[Recv] \")); Serial.println(ble.buffer);\n  ble.waitForOK();\n}\n\n/**************************************************************************/\n/*!\n    @brief  Checks for user input (via the Serial Monitor)\n*/\n/**************************************************************************/\nbool getUserInput(char buffer[], uint8_t maxSize)\n{\n  // timeout in 100 milliseconds\n  TimeoutTimer timeout(100);\n\n  memset(buffer, 0, maxSize);\n  while( (!Serial.available()) && !timeout.expired() ) { delay(1); }\n\n  if ( timeout.expired() ) return false;\n\n  delay(2);\n  uint8_t count=0;\n  do\n  {\n    count += Serial.readBytes(buffer+count, maxSize);\n    delay(2);\n  } while( (count < maxSize) && (Serial.available()) );\n\n  return true;\n}\n"
  },
  {
    "path": "examples/bleuart_datamode/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/bleuart_datamode/bleuart_datamode.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE       Perform a factory reset when running this sketch\n   \n                              Enabling this will put your Bluefruit LE module\n                              in a 'known good' state and clear any config\n                              data set in previous sketches or projects, so\n                              running this at least once is a good idea.\n   \n                              When deploying your project, however, you will\n                              want to disable factory reset by setting this\n                              value to 0.  If you are making changes to your\n                              Bluefruit LE device via AT commands, and those\n                              changes aren't persisting across resets, this\n                              is the reason why.  Factory reset will erase\n                              the non-volatile memory where config data is\n                              stored, setting it back to factory default\n                              values.\n       \n                              Some sketches that require you to bond to a\n                              central device (HID mouse, keyboard, etc.)\n                              won't work at all with this feature enabled\n                              since the factory reset will clear all of the\n                              bonding data stored on the chip, meaning the\n                              central device won't be able to reconnect.\n    MINIMUM_FIRMWARE_VERSION  Minimum firmware version to have some new features\n    MODE_LED_BEHAVIOUR        LED activity, valid options are\n                              \"DISABLE\" or \"MODE\" or \"BLEUART\" or\n                              \"HWUART\"  or \"SPI\"  or \"MANUAL\"\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE         1\n    #define MINIMUM_FIRMWARE_VERSION    \"0.6.6\"\n    #define MODE_LED_BEHAVIOUR          \"MODE\"\n/*=========================================================================*/\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit Command <-> Data Mode Example\"));\n  Serial.println(F(\"------------------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  Serial.println(F(\"Please use Adafruit Bluefruit LE app to connect in UART mode\"));\n  Serial.println(F(\"Then Enter characters to send to Bluefruit\"));\n  Serial.println();\n\n  ble.verbose(false);  // debug info is a little annoying after this point!\n\n  /* Wait for connection */\n  while (! ble.isConnected()) {\n      delay(500);\n  }\n\n  Serial.println(F(\"******************************\"));\n\n  // LED Activity command is only supported from 0.6.6\n  if ( ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )\n  {\n    // Change Mode LED Activity\n    Serial.println(F(\"Change LED activity to \" MODE_LED_BEHAVIOUR));\n    ble.sendCommandCheckOK(\"AT+HWModeLED=\" MODE_LED_BEHAVIOUR);\n  }\n\n  // Set module to DATA mode\n  Serial.println( F(\"Switching to DATA mode!\") );\n  ble.setMode(BLUEFRUIT_MODE_DATA);\n\n  Serial.println(F(\"******************************\"));\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  // Check for user input\n  char n, inputs[BUFSIZE+1];\n\n  if (Serial.available())\n  {\n    n = Serial.readBytes(inputs, BUFSIZE);\n    inputs[n] = 0;\n    // Send characters to Bluefruit\n    Serial.print(\"Sending: \");\n    Serial.println(inputs);\n\n    // Send input data to host via Bluefruit\n    ble.print(inputs);\n  }\n\n  // Echo received data\n  while ( ble.available() )\n  {\n    int c = ble.read();\n\n    Serial.print((char)c);\n\n    // Hex output too, helps w/debugging!\n    Serial.print(\" [0x\");\n    if (c <= 0xF) Serial.print(F(\"0\"));\n    Serial.print(c, HEX);\n    Serial.print(\"] \");\n  }\n}\n"
  },
  {
    "path": "examples/callbacks/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              6    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/callbacks/callbacks.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/* This example demonstrates how to use Bluefruit callback API :\n * - setConnectCallback(), setDisconnectCallback(), setBleUartRxCallback(),\n * setBleGattRxCallback() are used to install callback function for specific\n * event. \n * - Furthermore, update() must be called inside loop() for callback to\n * be executed.\n * \n * The sketch will add an custom service with 2 writable characteristics,\n * and install callback to execute when there is an update from central device\n * - one hold string\n * - one hold a 4-byte integer\n  */\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE     Perform a factory reset when running this sketch\n   \n                            Enabling this will put your Bluefruit LE module\n                            in a 'known good' state and clear any config\n                            data set in previous sketches or projects, so\n                            running this at least once is a good idea.\n   \n                            When deploying your project, however, you will\n                            want to disable factory reset by setting this\n                            value to 0.  If you are making changes to your\n                            Bluefruit LE device via AT commands, and those\n                            changes aren't persisting across resets, this\n                            is the reason why.  Factory reset will erase\n                            the non-volatile memory where config data is\n                            stored, setting it back to factory default\n                            values.\n       \n                            Some sketches that require you to bond to a\n                            central device (HID mouse, keyboard, etc.)\n                            won't work at all with this feature enabled\n                            since the factory reset will clear all of the\n                            bonding data stored on the chip, meaning the\n                            central device won't be able to reconnect.\n                            \n    MINIMUM_FIRMWARE_VERSION  Minimum firmware version to have some new features    \n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE        1\n    #define MINIMUM_FIRMWARE_VERSION   \"0.7.0\"\n/*=========================================================================*/\n\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\nint32_t charid_string;\nint32_t charid_number;\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\nvoid connected(void)\n{\n  Serial.println( F(\"Connected\") );\n}\n\nvoid disconnected(void)\n{\n  Serial.println( F(\"Disconnected\") );\n}\n\nvoid BleUartRX(char data[], uint16_t len)\n{\n  Serial.print( F(\"[BLE UART RX]\" ) );\n  Serial.write(data, len);\n  Serial.println();\n}\n\nvoid BleGattRX(int32_t chars_id, uint8_t data[], uint16_t len)\n{\n  Serial.print( F(\"[BLE GATT RX] (\" ) );\n  Serial.print(chars_id);\n  Serial.print(\") \");\n  \n  if (chars_id == charid_string)\n  {  \n    Serial.write(data, len);\n    Serial.println();\n  }else if (chars_id == charid_number)\n  {\n    int32_t val;\n    memcpy(&val, data, len);\n    Serial.println(val);\n  }\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit Callbacks Example\"));\n  Serial.println(F(\"-------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n  \n  if ( !ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )\n  {\n    error( F(\"Callback requires at least 0.7.0\") );\n  }\n\n  Serial.println( F(\"Adding Service 0x1234 with 2 chars 0x2345 & 0x6789\") );\n  ble.sendCommandCheckOK( F(\"AT+GATTADDSERVICE=uuid=0x1234\") );\n  ble.sendCommandWithIntReply( F(\"AT+GATTADDCHAR=UUID=0x2345,PROPERTIES=0x08,MIN_LEN=1,MAX_LEN=6,DATATYPE=string,DESCRIPTION=string,VALUE=abc\"), &charid_string);\n  ble.sendCommandWithIntReply( F(\"AT+GATTADDCHAR=UUID=0x6789,PROPERTIES=0x08,MIN_LEN=4,MAX_LEN=4,DATATYPE=INTEGER,DESCRIPTION=number,VALUE=0\"), &charid_number);\n\n  ble.reset();\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n  \n  /* Set callbacks */\n  ble.setConnectCallback(connected);\n  ble.setDisconnectCallback(disconnected);\n  ble.setBleUartRxCallback(BleUartRX);\n  \n  /* Only one BLE GATT function should be set, it is possible to set it \n  multiple times for multiple Chars ID  */\n  ble.setBleGattRxCallback(charid_string, BleGattRX);\n  ble.setBleGattRxCallback(charid_number, BleGattRX);\n}\n\n\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{  \n  ble.update(200);\n}\n\n"
  },
  {
    "path": "examples/callbacks_dfuirq/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              6    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/callbacks_dfuirq/callbacks_dfuirq.ino",
    "content": "/*********************************************************************\n  This is an example for our nRF51822 based Bluefruit LE modules\n\n  Pick one up today in the adafruit shop!\n\n  Adafruit invests time and resources providing this open source code,\n  please support Adafruit and open-source hardware by purchasing\n  products from Adafruit!\n\n  MIT license, check LICENSE for more information\n  All text above, and the splash screen below must be included in\n  any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#include \"Adafruit_BLEGatt.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/* This example demonstrates how to use Bluefruit callback API :\n   - setConnectCallback(), setDisconnectCallback(), setBleUartRxCallback(),\n   setBleGattRxCallback() are used to install callback function for specific\n   event.\n   - Furthermore, update() must be called inside loop() for callback to\n   be executed.\n\n   The sketch will add an custom service with 2 writable characteristics,\n   and install callback to execute when there is an update from central device\n   - one hold string\n   - one hold a 4-byte integer\n*/\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n      FACTORYRESET_ENABLE     Perform a factory reset when running this sketch\n     \n                              Enabling this will put your Bluefruit LE module\n                            in a 'known good' state and clear any config\n                            data set in previous sketches or projects, so\n                              running this at least once is a good idea.\n     \n                              When deploying your project, however, you will\n                            want to disable factory reset by setting this\n                            value to 0.  If you are making changes to your\n                              Bluefruit LE device via AT commands, and those\n                            changes aren't persisting across resets, this\n                            is the reason why.  Factory reset will erase\n                            the non-volatile memory where config data is\n                            stored, setting it back to factory default\n                            values.\n         \n                              Some sketches that require you to bond to a\n                            central device (HID mouse, keyboard, etc.)\n                            won't work at all with this feature enabled\n                            since the factory reset will clear all of the\n                            bonding data stored on the chip, meaning the\n                            central device won't be able to reconnect.\n\n    MINIMUM_FIRMWARE_VERSION  Minimum firmware version to have some new features\n    -----------------------------------------------------------------------*/\n#define FACTORYRESET_ENABLE        1\n#define MINIMUM_FIRMWARE_VERSION   \"0.7.1\"\n/*=========================================================================*/\n\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\n  SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\n  Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\nAdafruit_BLEGatt gatt(ble);\n\nint32_t charid_string;\nint32_t charid_number;\n\n// Wire DFU pin to interruptable pin\nint irq_pin = 1;\n\n// use boolean variable to signal loop() to call ble.update()\n// You could call ble.update() is ISR but it will increase ISR lattency\nvolatile boolean irq_event_available = false;\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\nvoid connected(void)\n{\n  Serial.println( F(\"Connected\") );\n}\n\nvoid disconnected(void)\n{\n  Serial.println( F(\"Disconnected\") );\n}\n\nvoid BleUartRX(char data[], uint16_t len)\n{\n  Serial.print( F(\"[BLE UART RX]\" ) );\n  Serial.write(data, len);\n  Serial.println();\n}\n\nvoid BleGattRX(int32_t chars_id, uint8_t data[], uint16_t len)\n{\n  Serial.print( F(\"[BLE GATT RX] (\" ) );\n  Serial.print(chars_id);\n  Serial.print(\") \");\n\n  if (chars_id == charid_string)\n  {\n    Serial.write(data, len);\n    Serial.println();\n  } else if (chars_id == charid_number)\n  {\n    int32_t val;\n    memcpy(&val, data, len);\n    Serial.println(val);\n  }\n}\n\nvoid DfuIrqHandle(void)\n{\n  // signal loop() to handle event\n  irq_event_available = true;\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit Callback with DFU IRQ Example\"));\n  Serial.println(F(\"-------------------------------------\"));\n\n  pinMode(irq_pin, INPUT_PULLUP);\n  attachInterrupt(digitalPinToInterrupt(irq_pin), DfuIrqHandle, FALLING);\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ) {\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  if ( !ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )\n  {\n    error( F(\"Callback with DFU Pin as IRQ requires at least 0.7.1\") );\n  }\n\n  Serial.println( F(\"Adding Service 0x1234 with 2 chars 0x2345 & 0x6789\") );\n  gatt.addService(0x1234);\n  charid_string = gatt.addCharacteristic(0x2345, GATT_CHARS_PROPERTIES_WRITE, 1, 6, BLE_DATATYPE_STRING, \"string\");\n  charid_number = gatt.addCharacteristic(0x6789, GATT_CHARS_PROPERTIES_WRITE, 4, 4, BLE_DATATYPE_INTEGER, \"number\");\n\n  /* Reset the device for the new service setting changes to take effect */\n  Serial.print(F(\"Performing a SW reset (service changes require a reset): \"));\n  ble.reset();\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  /* Change DFU Pin to IRQ mode */\n  Serial.println( F(\"Change DFU Pin to IRQ Mode\") );\n  ble.sendCommandCheckOK( F(\"AT+DFUIRQ=on\") );\n\n  /* Set callbacks */\n  ble.setConnectCallback(connected);\n  ble.setDisconnectCallback(disconnected);\n  ble.setBleUartRxCallback(BleUartRX);\n\n  /* Only one BLE GATT function should be set, it is possible to set it\n    multiple times for multiple Chars ID  */\n  ble.setBleGattRxCallback(charid_string, BleGattRX);\n  ble.setBleGattRxCallback(charid_number, BleGattRX);\n}\n\n\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  if (irq_event_available)\n  {\n    // Registered callbacks for the event will be fired accordingly\n    ble.handleDfuIrq();\n  }\n}\n\n"
  },
  {
    "path": "examples/controller/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n#define BLE_READPACKET_TIMEOUT         500   // Timeout in ms waiting to read a response\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/controller/controller.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <string.h>\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE       Perform a factory reset when running this sketch\n   \n                              Enabling this will put your Bluefruit LE module\n                              in a 'known good' state and clear any config\n                              data set in previous sketches or projects, so\n                              running this at least once is a good idea.\n   \n                              When deploying your project, however, you will\n                              want to disable factory reset by setting this\n                              value to 0.  If you are making changes to your\n                              Bluefruit LE device via AT commands, and those\n                              changes aren't persisting across resets, this\n                              is the reason why.  Factory reset will erase\n                              the non-volatile memory where config data is\n                              stored, setting it back to factory default\n                              values.\n       \n                              Some sketches that require you to bond to a\n                              central device (HID mouse, keyboard, etc.)\n                              won't work at all with this feature enabled\n                              since the factory reset will clear all of the\n                              bonding data stored on the chip, meaning the\n                              central device won't be able to reconnect.\n    MINIMUM_FIRMWARE_VERSION  Minimum firmware version to have some new features\n    MODE_LED_BEHAVIOUR        LED activity, valid options are\n                              \"DISABLE\" or \"MODE\" or \"BLEUART\" or\n                              \"HWUART\"  or \"SPI\"  or \"MANUAL\"\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE         1\n    #define MINIMUM_FIRMWARE_VERSION    \"0.6.6\"\n    #define MODE_LED_BEHAVIOUR          \"MODE\"\n/*=========================================================================*/\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n// function prototypes over in packetparser.cpp\nuint8_t readPacket(Adafruit_BLE *ble, uint16_t timeout);\nfloat parsefloat(uint8_t *buffer);\nvoid printHex(const uint8_t * data, const uint32_t numBytes);\n\n// the packet buffer\nextern uint8_t packetbuffer[];\n\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit App Controller Example\"));\n  Serial.println(F(\"-----------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  Serial.println(F(\"Please use Adafruit Bluefruit LE app to connect in Controller mode\"));\n  Serial.println(F(\"Then activate/use the sensors, color picker, game controller, etc!\"));\n  Serial.println();\n\n  ble.verbose(false);  // debug info is a little annoying after this point!\n\n  /* Wait for connection */\n  while (! ble.isConnected()) {\n      delay(500);\n  }\n\n  Serial.println(F(\"******************************\"));\n\n  // LED Activity command is only supported from 0.6.6\n  if ( ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )\n  {\n    // Change Mode LED Activity\n    Serial.println(F(\"Change LED activity to \" MODE_LED_BEHAVIOUR));\n    ble.sendCommandCheckOK(\"AT+HWModeLED=\" MODE_LED_BEHAVIOUR);\n  }\n\n  // Set Bluefruit to DATA mode\n  Serial.println( F(\"Switching to DATA mode!\") );\n  ble.setMode(BLUEFRUIT_MODE_DATA);\n\n  Serial.println(F(\"******************************\"));\n\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  /* Wait for new data to arrive */\n  uint8_t len = readPacket(&ble, BLE_READPACKET_TIMEOUT);\n  if (len == 0) return;\n\n  /* Got a packet! */\n  // printHex(packetbuffer, len);\n\n  // Color\n  if (packetbuffer[1] == 'C') {\n    uint8_t red = packetbuffer[2];\n    uint8_t green = packetbuffer[3];\n    uint8_t blue = packetbuffer[4];\n    Serial.print (\"RGB #\");\n    if (red < 0x10) Serial.print(\"0\");\n    Serial.print(red, HEX);\n    if (green < 0x10) Serial.print(\"0\");\n    Serial.print(green, HEX);\n    if (blue < 0x10) Serial.print(\"0\");\n    Serial.println(blue, HEX);\n  }\n\n  // Buttons\n  if (packetbuffer[1] == 'B') {\n    uint8_t buttnum = packetbuffer[2] - '0';\n    boolean pressed = packetbuffer[3] - '0';\n    Serial.print (\"Button \"); Serial.print(buttnum);\n    if (pressed) {\n      Serial.println(\" pressed\");\n    } else {\n      Serial.println(\" released\");\n    }\n  }\n\n  // GPS Location\n  if (packetbuffer[1] == 'L') {\n    float lat, lon, alt;\n    lat = parsefloat(packetbuffer+2);\n    lon = parsefloat(packetbuffer+6);\n    alt = parsefloat(packetbuffer+10);\n    Serial.print(\"GPS Location\\t\");\n    Serial.print(\"Lat: \"); Serial.print(lat, 4); // 4 digits of precision!\n    Serial.print('\\t');\n    Serial.print(\"Lon: \"); Serial.print(lon, 4); // 4 digits of precision!\n    Serial.print('\\t');\n    Serial.print(alt, 4); Serial.println(\" meters\");\n  }\n\n  // Accelerometer\n  if (packetbuffer[1] == 'A') {\n    float x, y, z;\n    x = parsefloat(packetbuffer+2);\n    y = parsefloat(packetbuffer+6);\n    z = parsefloat(packetbuffer+10);\n    Serial.print(\"Accel\\t\");\n    Serial.print(x); Serial.print('\\t');\n    Serial.print(y); Serial.print('\\t');\n    Serial.print(z); Serial.println();\n  }\n\n  // Magnetometer\n  if (packetbuffer[1] == 'M') {\n    float x, y, z;\n    x = parsefloat(packetbuffer+2);\n    y = parsefloat(packetbuffer+6);\n    z = parsefloat(packetbuffer+10);\n    Serial.print(\"Mag\\t\");\n    Serial.print(x); Serial.print('\\t');\n    Serial.print(y); Serial.print('\\t');\n    Serial.print(z); Serial.println();\n  }\n\n  // Gyroscope\n  if (packetbuffer[1] == 'G') {\n    float x, y, z;\n    x = parsefloat(packetbuffer+2);\n    y = parsefloat(packetbuffer+6);\n    z = parsefloat(packetbuffer+10);\n    Serial.print(\"Gyro\\t\");\n    Serial.print(x); Serial.print('\\t');\n    Serial.print(y); Serial.print('\\t');\n    Serial.print(z); Serial.println();\n  }\n\n  // Quaternions\n  if (packetbuffer[1] == 'Q') {\n    float x, y, z, w;\n    x = parsefloat(packetbuffer+2);\n    y = parsefloat(packetbuffer+6);\n    z = parsefloat(packetbuffer+10);\n    w = parsefloat(packetbuffer+14);\n    Serial.print(\"Quat\\t\");\n    Serial.print(x); Serial.print('\\t');\n    Serial.print(y); Serial.print('\\t');\n    Serial.print(z); Serial.print('\\t');\n    Serial.print(w); Serial.println();\n  }\n}\n"
  },
  {
    "path": "examples/controller/packetParser.cpp",
    "content": "#include <string.h>\n#include <Arduino.h>\n#include <SPI.h>\n#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_) && not defined(__SAMD51__)\n  #include <SoftwareSerial.h>\n#endif\n\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n\n#define PACKET_ACC_LEN                  (15)\n#define PACKET_GYRO_LEN                 (15)\n#define PACKET_MAG_LEN                  (15)\n#define PACKET_QUAT_LEN                 (19)\n#define PACKET_BUTTON_LEN               (5)\n#define PACKET_COLOR_LEN                (6)\n#define PACKET_LOCATION_LEN             (15)\n\n//    READ_BUFSIZE            Size of the read buffer for incoming packets\n#define READ_BUFSIZE                    (20)\n\n\n/* Buffer to hold incoming characters */\nuint8_t packetbuffer[READ_BUFSIZE+1];\n\n/**************************************************************************/\n/*!\n    @brief  Casts the four bytes at the specified address to a float\n*/\n/**************************************************************************/\nfloat parsefloat(uint8_t *buffer) \n{\n  float f;\n  memcpy(&f, buffer, 4);\n  return f;\n}\n\n/**************************************************************************/\n/*! \n    @brief  Prints a hexadecimal value in plain characters\n    @param  data      Pointer to the byte data\n    @param  numBytes  Data length in bytes\n*/\n/**************************************************************************/\nvoid printHex(const uint8_t * data, const uint32_t numBytes)\n{\n  uint32_t szPos;\n  for (szPos=0; szPos < numBytes; szPos++) \n  {\n    Serial.print(F(\"0x\"));\n    // Append leading 0 for small values\n    if (data[szPos] <= 0xF)\n    {\n      Serial.print(F(\"0\"));\n      Serial.print(data[szPos] & 0xf, HEX);\n    }\n    else\n    {\n      Serial.print(data[szPos] & 0xff, HEX);\n    }\n    // Add a trailing space if appropriate\n    if ((numBytes > 1) && (szPos != numBytes - 1))\n    {\n      Serial.print(F(\" \"));\n    }\n  }\n  Serial.println();\n}\n\n/**************************************************************************/\n/*!\n    @brief  Waits for incoming data and parses it\n*/\n/**************************************************************************/\nuint8_t readPacket(Adafruit_BLE *ble, uint16_t timeout) \n{\n  uint16_t origtimeout = timeout, replyidx = 0;\n\n  memset(packetbuffer, 0, READ_BUFSIZE);\n\n  while (timeout--) {\n    if (replyidx >= 20) break;\n    if ((packetbuffer[1] == 'A') && (replyidx == PACKET_ACC_LEN))\n      break;\n    if ((packetbuffer[1] == 'G') && (replyidx == PACKET_GYRO_LEN))\n      break;\n    if ((packetbuffer[1] == 'M') && (replyidx == PACKET_MAG_LEN))\n      break;\n    if ((packetbuffer[1] == 'Q') && (replyidx == PACKET_QUAT_LEN))\n      break;\n    if ((packetbuffer[1] == 'B') && (replyidx == PACKET_BUTTON_LEN))\n      break;\n    if ((packetbuffer[1] == 'C') && (replyidx == PACKET_COLOR_LEN))\n      break;\n    if ((packetbuffer[1] == 'L') && (replyidx == PACKET_LOCATION_LEN))\n      break;\n\n    while (ble->available()) {\n      char c =  ble->read();\n      if (c == '!') {\n        replyidx = 0;\n      }\n      packetbuffer[replyidx] = c;\n      replyidx++;\n      timeout = origtimeout;\n    }\n    \n    if (timeout == 0) break;\n    delay(1);\n  }\n\n  packetbuffer[replyidx] = 0;  // null term\n\n  if (!replyidx)  // no data or timeout \n    return 0;\n  if (packetbuffer[0] != '!')  // doesn't start with '!' packet beginning\n    return 0;\n  \n  // check checksum!\n  uint8_t xsum = 0;\n  uint8_t checksum = packetbuffer[replyidx-1];\n  \n  for (uint8_t i=0; i<replyidx-1; i++) {\n    xsum += packetbuffer[i];\n  }\n  xsum = ~xsum;\n\n  // Throw an error message if the checksum's don't match\n  if (xsum != checksum)\n  {\n    Serial.print(\"Checksum mismatch in packet : \");\n    printHex(packetbuffer, replyidx+1);\n    return 0;\n  }\n  \n  // checksum passed!\n  return replyidx;\n}\n\n"
  },
  {
    "path": "examples/cplay_neopixel_picker/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n#define BLE_READPACKET_TIMEOUT         500   // Timeout in ms waiting to read a response\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_HWSERIAL_NAME      Serial1\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/cplay_neopixel_picker/cplay_neopixel_picker.ino",
    "content": "/*********************************************************************\n Circuit Playground NeoPixel color picker.\n \n This is an example for our nRF51822 based Bluefruit LE modules connected\n to the Circuit Playground developer edition board.  Load the sketch and\n then use the Controller mode of the Bluefruit LE app to change the color\n (in the color picker) and the left/right controller buttons to change\n which pixels are lit up.\n\n Pick up a Circuit Playground & Flora Bluefruit LE module today in the \n Adafruit shop!\n - https://www.adafruit.com/product/3000\n - https://www.adafruit.com/product/2487\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <string.h>\n#include <Arduino.h>\n#include <SPI.h>\n\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n#include <Adafruit_CircuitPlayground.h>\n\n// Configuration (you don't need to change these, but can!):\n#define FACTORYRESET_ENABLE     1   // Set to 1 to factory reset the Bluefruit LE\n                                    // module.  In general this is a smart idea to\n                                    // put the module into a known good state.\n                                    // A value of 1 means perform a factory reset\n                                    // on start, and 0 means no factory reset.\n\n#define NUMPIXELS               10  // Number of NeoPixels on the board.\n\n#define BRIGHTNESS              255 // NeoPixel brightness (0...255, low to max brightness)\n\n/*=========================================================================*/\n\n// Create the bluefruit object, for Circuit Playground this needs to be\n// hardware serial.\nAdafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n// function prototypes over in packetparser.cpp\nuint8_t readPacket(Adafruit_BLE *ble, uint16_t timeout);\nfloat parsefloat(uint8_t *buffer);\nvoid printHex(const uint8_t * data, const uint32_t numBytes);\n\n// the packet buffer\nextern uint8_t packetbuffer[];\n\n// Offset that controls which pixels are turned on/off.\n// Pressing the left/right controller button moves this offset\n// up/down and 'slides' the chain of 10 pixels around.\nint currentOffset = 0;\n\n// Last selected color.\nuint8_t currentRed, currentGreen, currentBlue;\n\n// Light up a chain of 10 pixels starting at offset global variable value.\nvoid lightPixels(uint8_t red, uint8_t green, uint8_t blue, int offset) {\n  CircuitPlayground.strip.clear();\n  for (int i = offset; i < offset+NUMPIXELS; ++i) {\n    if ((i >= 0) && (i < NUMPIXELS)) {\n      CircuitPlayground.strip.setPixelColor(i, red, green, blue);\n    }\n  }\n  CircuitPlayground.strip.show();\n}\n\nvoid setup() {\n  // Wait for serial port before starting.  Not required but helps with debugging.\n  //while (!Serial);\n  //delay(500);\n  \n  // Initialize Circuit Playground library and turn off the Pixels.\n  CircuitPlayground.begin(BRIGHTNESS);\n  CircuitPlayground.clearPixels();\n\n  // Initialize serial output.\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Circuit Playground Bluefruit Neopixel Color Picker Example\"));\n  Serial.println(F(\"-------------------------------------------------------------------\"));\n\n  // Initialise the module\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in DATA mode & check wiring....\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    // Perform a factory reset to make sure everything is in a known state\n    Serial.println(F(\"Performing a factory reset: \"));\n    if (!ble.factoryReset()) {\n      Serial.println(F(\"Couldn't factory reset, making another attempt...\"));\n      delay(1000);\n      if (!ble.factoryReset()) {\n        error(F(\"Couldn't factory reset!\"));\n      }\n    }\n  }\n\n  // Disable command echo from Bluefruit\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  // Print Bluefruit information\n  ble.info();\n\n  // Change advertised name to Circuit_Playground_BLE\n  ble.println(\"AT+GAPDEVNAME=CPlay_BLE\");\n  delay(100);\n  ble.println(\"ATZ\");\n  delay(100);\n\n  Serial.println(F(\"Please use Adafruit Bluefruit LE app to connect in Controller mode\"));\n  Serial.println(F(\"Then activate/use the sensors, color picker, game controller, etc!\"));\n  Serial.println();\n\n  ble.verbose(false);  // debug info is a little annoying after this point!\n\n  // Wait for connection\n  while (! ble.isConnected()) {\n      delay(500);\n  }\n\n  Serial.println(F(\"***********************\"));\n\n  // Set Bluefruit to DATA mode\n  Serial.println( F(\"Switching to DATA mode!\") );\n  ble.setMode(BLUEFRUIT_MODE_DATA);\n\n  Serial.println(F(\"***********************\"));\n\n}\n\nvoid loop()\n{\n  /* Wait for new data to arrive */\n  uint8_t len = readPacket(&ble, BLE_READPACKET_TIMEOUT);\n  if (len == 0) {\n    return;\n  }\n\n  /* Got a packet! */\n  //printHex(packetbuffer, len);\n\n  // Color\n  if (packetbuffer[1] == 'C') {\n    // Parse out the red, green, blue values and save them.\n    uint8_t red = packetbuffer[2];\n    uint8_t green = packetbuffer[3];\n    uint8_t blue = packetbuffer[4];\n    // Change the color.\n    currentRed = red;\n    currentGreen = green;\n    currentBlue = blue;\n  }\n\n  // Left/right adjust the offset that turns on/off pixels.\n  if (packetbuffer[1] == 'B') {\n    if (memcmp(packetbuffer, \"!B705\", 5) == 0) {\n      // Left button release.\n      currentOffset -= 1;\n    }\n    else if (memcmp(packetbuffer, \"!B804\", 5) == 0) {\n      // Right button release.\n      currentOffset += 1;\n    }\n    currentOffset = constrain(currentOffset, -NUMPIXELS, NUMPIXELS);\n  }\n\n  // Update the pixels again since either the color or offset position\n  // must have changed above.\n  lightPixels(currentRed, currentGreen, currentBlue, currentOffset);\n}\n"
  },
  {
    "path": "examples/cplay_neopixel_picker/packetParser.cpp",
    "content": "#include <string.h>\n#include <Arduino.h>\n#include <SPI.h>\n#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)\n  #include <SoftwareSerial.h>\n#endif\n\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n\n#define PACKET_ACC_LEN                  (15)\n#define PACKET_GYRO_LEN                 (15)\n#define PACKET_MAG_LEN                  (15)\n#define PACKET_QUAT_LEN                 (19)\n#define PACKET_BUTTON_LEN               (5)\n#define PACKET_COLOR_LEN                (6)\n#define PACKET_LOCATION_LEN             (15)\n\n//    READ_BUFSIZE            Size of the read buffer for incoming packets\n#define READ_BUFSIZE                    (20)\n\n\n/* Buffer to hold incoming characters */\nuint8_t packetbuffer[READ_BUFSIZE+1];\n\n/**************************************************************************/\n/*!\n    @brief  Casts the four bytes at the specified address to a float\n*/\n/**************************************************************************/\nfloat parsefloat(uint8_t *buffer) \n{\n  float f = ((float *)buffer)[0];\n  return f;\n}\n\n/**************************************************************************/\n/*! \n    @brief  Prints a hexadecimal value in plain characters\n    @param  data      Pointer to the byte data\n    @param  numBytes  Data length in bytes\n*/\n/**************************************************************************/\nvoid printHex(const uint8_t * data, const uint32_t numBytes)\n{\n  uint32_t szPos;\n  for (szPos=0; szPos < numBytes; szPos++) \n  {\n    Serial.print(F(\"0x\"));\n    // Append leading 0 for small values\n    if (data[szPos] <= 0xF)\n    {\n      Serial.print(F(\"0\"));\n      Serial.print(data[szPos] & 0xf, HEX);\n    }\n    else\n    {\n      Serial.print(data[szPos] & 0xff, HEX);\n    }\n    // Add a trailing space if appropriate\n    if ((numBytes > 1) && (szPos != numBytes - 1))\n    {\n      Serial.print(F(\" \"));\n    }\n  }\n  Serial.println();\n}\n\n/**************************************************************************/\n/*!\n    @brief  Waits for incoming data and parses it\n*/\n/**************************************************************************/\nuint8_t readPacket(Adafruit_BLE *ble, uint16_t timeout) \n{\n  uint16_t origtimeout = timeout, replyidx = 0;\n\n  memset(packetbuffer, 0, READ_BUFSIZE);\n\n  while (timeout--) {\n    if (replyidx >= 20) break;\n    if ((packetbuffer[1] == 'A') && (replyidx == PACKET_ACC_LEN))\n      break;\n    if ((packetbuffer[1] == 'G') && (replyidx == PACKET_GYRO_LEN))\n      break;\n    if ((packetbuffer[1] == 'M') && (replyidx == PACKET_MAG_LEN))\n      break;\n    if ((packetbuffer[1] == 'Q') && (replyidx == PACKET_QUAT_LEN))\n      break;\n    if ((packetbuffer[1] == 'B') && (replyidx == PACKET_BUTTON_LEN))\n      break;\n    if ((packetbuffer[1] == 'C') && (replyidx == PACKET_COLOR_LEN))\n      break;\n    if ((packetbuffer[1] == 'L') && (replyidx == PACKET_LOCATION_LEN))\n      break;\n\n    while (ble->available()) {\n      char c =  ble->read();\n      if (c == '!') {\n        replyidx = 0;\n      }\n      packetbuffer[replyidx] = c;\n      replyidx++;\n      timeout = origtimeout;\n    }\n    \n    if (timeout == 0) break;\n    delay(1);\n  }\n\n  packetbuffer[replyidx] = 0;  // null term\n\n  if (!replyidx)  // no data or timeout \n    return 0;\n  if (packetbuffer[0] != '!')  // doesn't start with '!' packet beginning\n    return 0;\n  \n  // check checksum!\n  uint8_t xsum = 0;\n  uint8_t checksum = packetbuffer[replyidx-1];\n  \n  for (uint8_t i=0; i<replyidx-1; i++) {\n    xsum += packetbuffer[i];\n  }\n  xsum = ~xsum;\n\n  // Throw an error message if the checksum's don't match\n  if (xsum != checksum)\n  {\n    Serial.print(\"Checksum mismatch in packet : \");\n    printHex(packetbuffer, replyidx+1);\n    return 0;\n  }\n  \n  // checksum passed!\n  return replyidx;\n}\n\n"
  },
  {
    "path": "examples/eddystone/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/eddystone/eddystone.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#include \"Adafruit_BLEEddystone.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE       Perform a factory reset when running this sketch\n\n                              Enabling this will put your Bluefruit LE module\n                              in a 'known good' state and clear any config\n                              data set in previous sketches or projects, so\n                              running this at least once is a good idea.\n\n                              When deploying your project, however, you will\n                              want to disable factory reset by setting this\n                              value to 0.  If you are making changes to your\n                              Bluefruit LE device via AT commands, and those\n                              changes aren't persisting across resets, this\n                              is the reason why.  Factory reset will erase\n                              the non-volatile memory where config data is\n                              stored, setting it back to factory default\n                              values.\n\n                              Some sketches that require you to bond to a\n                              central device (HID mouse, keyboard, etc.)\n                              won't work at all with this feature enabled\n                              since the factory reset will clear all of the\n                              bonding data stored on the chip, meaning the\n                              central device won't be able to reconnect.\n    MINIMUM_FIRMWARE_VERSION  Minimum firmware version to have some new features\n    URL                       The URL that is advertised. It must not longer\n                              than 17 bytes (excluding http:// and www.).\n                              Note: \".com/\" \".net/\" count as 1\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE         1\n    #define MINIMUM_FIRMWARE_VERSION    \"0.7.0\"\n    #define URL                         \"http://www.adafruit.com\"\n/*=========================================================================*/\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\nAdafruit_BLEEddystone eddyBeacon(ble);\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit EddyStone Example\"));\n  Serial.println(F(\"------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  // EddyStone commands are added from firmware 0.6.6\n  if ( !ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )\n  {\n    error(F(\"EddyStone is only available from 0.6.6. Please perform firmware upgrade\"));\n  }\n\n  // Enable Eddystone beacon service and reset Bluefruit if needed\n  eddyBeacon.begin(true);\n\n  /* Set EddyStone URL beacon data */\n  Serial.println(F(\"Setting EddyStone-url to Adafruit website: \"));\n\n  if ( !eddyBeacon.setURL(URL) ) {\n    error(F(\"Couldnt set, is URL too long !?\"));\n  }\n\n  Serial.println(F(\"**************************************************\"));\n  Serial.println(F(\"Please use Google Physical Web application to test\"));\n  Serial.println(F(\"**************************************************\"));\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  // Print user's option\n  Serial.println(F(\"Please choose:\"));\n  Serial.println(F(\"0 : Stop broadcasting EddyStone URL\"));\n  Serial.println(F(\"1 : Start broadcasting EddyStone URL\"));\n  Serial.println(F(\"2 : Put EddyStone URL to Config Mode\"));\n\n  // Get User's input\n  char option[BUFSIZE+1];\n  getUserInput(option, BUFSIZE);\n\n  // Proccess option\n  switch ( option[0] - '0' )\n  {\n    case 0:\n      eddyBeacon.stopBroadcast();      \n      break;\n\n    case 1:\n      eddyBeacon.startBroadcast();\n      break;\n\n    case 2:\n      Serial.println(F(\"EddyStone config's mode is enabled for 300 seconds\"));\n      Serial.println(F(\"Please use Physical Web app to edit URL\"));\n      eddyBeacon.startConfigMode(300);\n      break;\n\n    default:\n      Serial.print(F(\"Invalid input; \"));\n      Serial.println(option);\n      break;\n  }\n}\n\n/**************************************************************************/\n/*!\n    @brief  Checks for user input (via the Serial Monitor)\n*/\n/**************************************************************************/\nvoid getUserInput(char buffer[], uint8_t maxSize)\n{\n  memset(buffer, 0, maxSize);\n  while( Serial.available() == 0 ) {\n    delay(1);\n  }\n\n  uint8_t count=0;\n\n  do\n  {\n    count += Serial.readBytes(buffer+count, maxSize);\n    delay(2);\n  } while( (count < maxSize) && !(Serial.available() == 0) );\n}\n"
  },
  {
    "path": "examples/factoryreset/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/factoryreset/factoryreset.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Factory Reset Example\"));\n  Serial.println(F(\"------------------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  /* Perform a factory reset to make sure everything is in a known state */\n  Serial.println(F(\"Performing a factory reset: \"));\n  if (! ble.factoryReset() ){\n       error(F(\"Couldn't factory reset\"));\n  }\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  Serial.println(F(\"DONE!\"));\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n}\n"
  },
  {
    "path": "examples/feathertester/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        160   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   false // If set to 'true' enables debug output\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/feathertester/feathertester.ino",
    "content": "/*\n  Bluefruit Feather Tester\n\n  This sketch provides a simple tester for Bluefruit Feather boards from Adafruit\n\n  created 31 Jan. 2016\n  by K. Townsend (KTOWN)\n*/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/**************************************************************************/\n/*!\n\n*/\n/**************************************************************************/\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n\n*/\n/**************************************************************************/\nvoid setup()\n{\n  Serial.begin(115200);\n\n  // Wait for the Serial Monitor to open\n  while (!Serial) { yield(); }\n\n  // Initialise the BLE module\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n\n  // Display the test suite selection menu\n  display_menu();\n}\n\n/**************************************************************************/\n/*!\n    Reads and prints the AT response buffer until we reach OK or ERROR\n\n    Returns 'true' if an error occurred, otherwise 'false'\n*/\n/**************************************************************************/\nbool display_response(void)\n{\n  // Read the response until we get OK or ERROR\n  while (ble.readline())\n  {\n    Serial.print(ble.buffer);\n    if ( strcmp(ble.buffer, \"OK\") == 0 )\n    {\n      return false;\n    }\n    if ( strcmp(ble.buffer, \"ERROR\") == 0 )\n    {\n      return true;\n    }\n  }\n\n  return true;\n}\n\n/**************************************************************************/\n/*!\n\n*/\n/**************************************************************************/\nvoid display_menu()\n{\n  delay(500);  // Short delay for cosmetic reasons\n  Serial.println(\"\");\n  Serial.println(\"Bluefruit Feather Tester\");\n  Serial.println(\"-------------------------------------------------------------------------------\");\n  Serial.println(\"Select a menu option below:\");\n  Serial.println(\"\");\n  Serial.println(\"[1]  - System Info\");\n  Serial.println(\"[2]  - AT+HELP\");\n  Serial.println(\"\");\n  Serial.println(\"Enter your selection in the Serial Monitor and press <enter>\");\n  Serial.println(\"\");\n}\n\n/**************************************************************************/\n/*!\n\n*/\n/**************************************************************************/\nvoid loop()\n{\n  String user_input = \"\";\n  int selection = 0;\n\n  // Wait for user feedback, then parse feedback one byte at a time\n  while((Serial.available()) && !selection)\n  {\n    char incoming = Serial.read();\n    if (isdigit(incoming))\n    {\n      // Append the current digit to the string placeholder\n      user_input += (char)incoming;\n    }\n    // Parse the string on new-line\n    if (incoming == '\\n')\n    {\n      selection = user_input.toInt();\n    }\n    delay(2);\n  }\n\n  // Run the appropriate test suite if we have a number\n  if (selection)\n  {\n    bool error = false;\n    switch(selection)\n    {\n      case 1:\n        ble.info();\n        break;\n      case 2:\n        ble.println(\"AT+HELP\");\n        error = display_response();\n        break;\n      default:\n        Serial.print(\"Invalid selection: \");\n        Serial.println(selection);\n        break;\n    }\n\n    // Catch any error responses here\n    if (error) Serial.println(\"ERROR!\");\n\n    // Display the main menu again\n    Serial.println(\"\");\n    display_menu();\n  }\n}\n"
  },
  {
    "path": "examples/healththermometer/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         8    // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/healththermometer/IEEE11073float.cpp",
    "content": "/**************************************************************************/\n/*!\n    @file     IEEE11073float.h\n*/\n/**************************************************************************/\n\n/**\n * \\file bytelib.c\n * \\brief Byte manipulation module implementation.\n * Copyright (C) 2010 Signove Tecnologia Corporation.\n * All rights reserved.\n * Contact: Signove Tecnologia Corporation (contact@signove.com)\n *\n * $LICENSE_TEXT:BEGIN$\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation and appearing\n * in the file LICENSE included in the packaging of this file; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA\n * $LICENSE_TEXT:END$\n *\n * \\author Walter Guerra, Mateus Lima\n * \\date Jun 14, 2010\n */\n\n#include <Arduino.h>\n#include \"IEEE11073float.h\"\n\nuint32_t float2IEEE11073(double data, uint8_t output[4])\n{\n  uint32_t result = MDER_NaN;\n\n\n  if (isnan(data)) {\n    goto finally;\n  }/* else if (data > MDER_FLOAT_MAX) {\n    result = MDER_POSITIVE_INFINITY;\n    goto finally;\n  } else if (data < MDER_FLOAT_MIN) {\n    result = MDER_NEGATIVE_INFINITY;\n    goto finally;\n  } else if (data >= -MDER_FLOAT_EPSILON &&\n    data <= MDER_FLOAT_EPSILON) {\n    result = 0;\n    goto finally;\n  }*/\n\n  double sgn; sgn = data > 0 ? +1 : -1;\n  double mantissa; mantissa = fabs(data);\n  int32_t exponent; exponent = 0; // Note: 10**x exponent, not 2**x\n\n  // scale up if number is too big\n  while (mantissa > MDER_FLOAT_MANTISSA_MAX) {\n    mantissa /= 10.0;\n    ++exponent;\n    if (exponent > MDER_FLOAT_EXPONENT_MAX) {\n      // argh, should not happen\n      if (sgn > 0) {\n        result = MDER_POSITIVE_INFINITY;\n      } else {\n        result = MDER_NEGATIVE_INFINITY;\n      }\n      goto finally;\n    }\n  }\n\n  // scale down if number is too small\n  while (mantissa < 1) {\n    mantissa *= 10;\n    --exponent;\n    if (exponent < MDER_FLOAT_EXPONENT_MIN) {\n      // argh, should not happen\n      result = 0;\n      goto finally;\n    }\n  }\n\n  // scale down if number needs more precision\n  double smantissa; smantissa = round(mantissa * MDER_FLOAT_PRECISION);\n  double rmantissa; rmantissa = round(mantissa) * MDER_FLOAT_PRECISION;\n  double mdiff; mdiff = abs(smantissa - rmantissa);\n  while (mdiff > 0.5 && exponent > MDER_FLOAT_EXPONENT_MIN &&\n      (mantissa * 10) <= MDER_FLOAT_MANTISSA_MAX) {\n    mantissa *= 10;\n    --exponent;\n    smantissa = round(mantissa * MDER_FLOAT_PRECISION);\n    rmantissa = round(mantissa) * MDER_FLOAT_PRECISION;\n    mdiff = abs(smantissa - rmantissa);\n  }\n\n  uint32_t int_mantissa; int_mantissa = (int) round(sgn * mantissa);\n  result = (exponent << 24) | (int_mantissa & 0xFFFFFF);\n\nfinally:\n  if ( output ) memcpy(output, &result, 4);\n  return result;\n}\r\n"
  },
  {
    "path": "examples/healththermometer/IEEE11073float.h",
    "content": "/**************************************************************************/\n/*!\n    @file     IEEE11073float.h\n*/\n/**************************************************************************/\n\n/**\n * \\file bytelib.c\n * \\brief Byte manipulation module implementation.\n * Copyright (C) 2010 Signove Tecnologia Corporation.\n * All rights reserved.\n * Contact: Signove Tecnologia Corporation (contact@signove.com)\n *\n * $LICENSE_TEXT:BEGIN$\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation and appearing\n * in the file LICENSE included in the packaging of this file; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA\n * $LICENSE_TEXT:END$\n *\n * \\author Walter Guerra, Mateus Lima\n * \\date Jun 14, 2010\n */\n\n#ifndef _IEEE11073FLOAT_H_\n#define _IEEE11073FLOAT_H_\n\n#include <stdint.h>\n\ntypedef enum {\n  MDER_POSITIVE_INFINITY = 0x007FFFFE,\n  MDER_NaN = 0x007FFFFF,\n  MDER_NRes = 0x00800000,\n  MDER_RESERVED_VALUE = 0x00800001,\n  MDER_NEGATIVE_INFINITY = 0x00800002\n} ReservedFloatValues;\nstatic const int32_t FIRST_RESERVED_VALUE = MDER_POSITIVE_INFINITY;\n\n// (2 ** 23 - 3)\n#define MDER_FLOAT_MANTISSA_MAX 0x007FFFFD\n// 2 ** 7 - 1\n#define MDER_FLOAT_EXPONENT_MAX 127\n#define MDER_FLOAT_EXPONENT_MIN -128\n// (2 ** 23 - 3) * 10 ** 127\n#define MDER_FLOAT_MAX 8.388604999999999e+133\n// -(2 ** 23 - 3) * 10 ** 127\n#define MDER_FLOAT_MIN (-MDER_FLOAT_MAX)\n// 10 ** -128\n#define MDER_FLOAT_EPSILON 1e-128\n// 10 ** upper(23 * log(2) / log(10))\n// precision for a number 1.0000xxx\n#define MDER_FLOAT_PRECISION 10000000\n\ntypedef enum {\n  MDER_S_POSITIVE_INFINITY = 0x07FE,\n  MDER_S_NaN = 0x07FF,\n  MDER_S_NRes = 0x0800,\n  MDER_S_RESERVED_VALUE = 0x0801,\n  MDER_S_NEGATIVE_INFINITY = 0x0802\n} ReservedSFloatValues;\nstatic const uint32_t FIRST_S_RESERVED_VALUE = MDER_S_POSITIVE_INFINITY;\n\n// (2 ** 11 - 3)\n#define MDER_SFLOAT_MANTISSA_MAX 0x07FD\n// 2 ** 3 - 1\n#define MDER_SFLOAT_EXPONENT_MAX 7\n#define MDER_SFLOAT_EXPONENT_MIN -8\n// (2 ** 11 - 3) * 10 ** 7\n#define MDER_SFLOAT_MAX 20450000000.0\n// -(2 ** 11 - 3) * 10 ** 7\n#define MDER_SFLOAT_MIN (-MDER_SFLOAT_MAX)\n// 10 ** -8\n#define MDER_SFLOAT_EPSILON 1e-8\n// 10 ** upper(11 * log(2) / log(10))\n#define MDER_SFLOAT_PRECISION 10000\n\nuint32_t float2IEEE11073(double data, uint8_t output[4]);\n\n#endif /* _IEEE11073FLOAT_H_ */\r\n"
  },
  {
    "path": "examples/healththermometer/healththermometer.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n/*\n    Please note the long strings of data sent mean the *RTS* pin is\n    required with UART to slow down data sent to the Bluefruit LE!  \n*/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#include \"Adafruit_BLEGatt.h\"\n#include \"IEEE11073float.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\nAdafruit_BLEGatt gatt(ble);\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/* The service information */\n\nint32_t htsServiceId;\nint32_t htsMeasureCharId;\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial); // required for Flora & Micro\n  delay(500);\n\n  boolean success;\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit Health Thermometer Example\"));\n  Serial.println(F(\"--------------------------------------------\"));\n\n  randomSeed(micros());\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  /* Perform a factory reset to make sure everything is in a known state */\n  Serial.println(F(\"Performing a factory reset: \"));\n  if (! ble.factoryReset() ){\n       error(F(\"Couldn't factory reset\"));\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  // this line is particularly required for Flora, but is a good idea\n  // anyways for the super long lines ahead!\n  // ble.setInterCharWriteDelay(5); // 5 ms\n\n  /* Add the Heart Rate Service definition */\n  /* Service ID should be 1 */\n  Serial.println(F(\"Adding the Health Thermometer Service definition (UUID = 0x1809): \"));\n  htsServiceId = gatt.addService(0x1809);\n  if (htsServiceId == 0) {\n    error(F(\"Could not add Thermometer service\"));\n  }\n  \n  /* Add the Temperature Measurement characteristic which is composed of\n   * 1 byte flags + 4 float */\n  /* Chars ID for Measurement should be 1 */\n  Serial.println(F(\"Adding the Temperature Measurement characteristic (UUID = 0x2A1C): \"));\n  htsMeasureCharId = gatt.addCharacteristic(0x2A1C, GATT_CHARS_PROPERTIES_INDICATE, 5, 5, BLE_DATATYPE_BYTEARRAY);\n  if (htsMeasureCharId == 0) {\n    error(F(\"Could not add Temperature characteristic\"));\n  }\n\n  /* Add the Health Thermometer Service to the advertising data (needed for Nordic apps to detect the service) */\n  Serial.print(F(\"Adding Health Thermometer Service UUID to the advertising payload: \"));\n  uint8_t advdata[] { 0x02, 0x01, 0x06, 0x05, 0x02, 0x09, 0x18, 0x0a, 0x18 };\n  ble.setAdvData( advdata, sizeof(advdata) );\n\n  /* Reset the device for the new service setting changes to take effect */\n  Serial.print(F(\"Performing a SW reset (service changes require a reset): \"));\n  ble.reset();\n\n  Serial.println();\n}\n\n/** Send randomized heart rate data continuously **/\nvoid loop(void)\n{\n  double temp = random(0, 100) / 10.0;\n\n  Serial.print(F(\"Updating Temperature value to \"));\n  Serial.print(temp);\n  Serial.println(F(\" Fahrenheit\"));\n\n  // https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.temperature_measurement.xml\n  // Chars value is 1 flag + 4 float value. Tempearature is in Fahrenheit unit\n  uint8_t temp_measurement [5] = { bit(0) };\n  \n  float2IEEE11073(temp, temp_measurement+1);\n\n  // TODO temperature is not correct due to Bluetooth use IEEE-11073 format\n  gatt.setChar(htsMeasureCharId, temp_measurement, 5);\n\n  /* Delay before next measurement update */\n  delay(1000);\n}\n"
  },
  {
    "path": "examples/heartratemonitor/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         8    // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/heartratemonitor/heartratemonitor.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n/*\n    Please note the long strings of data sent mean the *RTS* pin is\n    required with UART to slow down data sent to the Bluefruit LE!\n*/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/* The service information */\n\nint32_t hrmServiceId;\nint32_t hrmMeasureCharId;\nint32_t hrmLocationCharId;\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial); // required for Flora & Micro\n  delay(500);\n\n  boolean success;\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit Heart Rate Monitor (HRM) Example\"));\n  Serial.println(F(\"---------------------------------------------------\"));\n\n  randomSeed(micros());\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  /* Perform a factory reset to make sure everything is in a known state */\n  Serial.println(F(\"Performing a factory reset: \"));\n  if (! ble.factoryReset() ){\n       error(F(\"Couldn't factory reset\"));\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  // this line is particularly required for Flora, but is a good idea\n  // anyways for the super long lines ahead!\n  // ble.setInterCharWriteDelay(5); // 5 ms\n\n  /* Change the device name to make it easier to find */\n  Serial.println(F(\"Setting device name to 'Bluefruit HRM': \"));\n\n  if (! ble.sendCommandCheckOK(F(\"AT+GAPDEVNAME=Bluefruit HRM\")) ) {\n    error(F(\"Could not set device name?\"));\n  }\n\n  /* Add the Heart Rate Service definition */\n  /* Service ID should be 1 */\n  Serial.println(F(\"Adding the Heart Rate Service definition (UUID = 0x180D): \"));\n  success = ble.sendCommandWithIntReply( F(\"AT+GATTADDSERVICE=UUID=0x180D\"), &hrmServiceId);\n  if (! success) {\n    error(F(\"Could not add HRM service\"));\n  }\n\n  /* Add the Heart Rate Measurement characteristic */\n  /* Chars ID for Measurement should be 1 */\n  Serial.println(F(\"Adding the Heart Rate Measurement characteristic (UUID = 0x2A37): \"));\n  success = ble.sendCommandWithIntReply( F(\"AT+GATTADDCHAR=UUID=0x2A37, PROPERTIES=0x10, MIN_LEN=2, MAX_LEN=3, VALUE=00-40\"), &hrmMeasureCharId);\n    if (! success) {\n    error(F(\"Could not add HRM characteristic\"));\n  }\n\n  /* Add the Body Sensor Location characteristic */\n  /* Chars ID for Body should be 2 */\n  Serial.println(F(\"Adding the Body Sensor Location characteristic (UUID = 0x2A38): \"));\n  success = ble.sendCommandWithIntReply( F(\"AT+GATTADDCHAR=UUID=0x2A38, PROPERTIES=0x02, MIN_LEN=1, VALUE=3\"), &hrmLocationCharId);\n    if (! success) {\n    error(F(\"Could not add BSL characteristic\"));\n  }\n\n  /* Add the Heart Rate Service to the advertising data (needed for Nordic apps to detect the service) */\n  Serial.print(F(\"Adding Heart Rate Service UUID to the advertising payload: \"));\n  ble.sendCommandCheckOK( F(\"AT+GAPSETADVDATA=02-01-06-05-02-0d-18-0a-18\") );\n\n  /* Reset the device for the new service setting changes to take effect */\n  Serial.print(F(\"Performing a SW reset (service changes require a reset): \"));\n  ble.reset();\n\n  Serial.println();\n}\n\n/** Send randomized heart rate data continuously **/\nvoid loop(void)\n{\n  int heart_rate = random(50, 100);\n\n  Serial.print(F(\"Updating HRM value to \"));\n  Serial.print(heart_rate);\n  Serial.println(F(\" BPM\"));\n\n  /* Command is sent when \\n (\\r) or println is called */\n  /* AT+GATTCHAR=CharacteristicID,value */\n  ble.print( F(\"AT+GATTCHAR=\") );\n  ble.print( hrmMeasureCharId );\n  ble.print( F(\",00-\") );\n  ble.println(heart_rate, HEX);\n\n  /* Check if command executed OK */\n  if ( !ble.waitForOK() )\n  {\n    Serial.println(F(\"Failed to get response!\"));\n  }\n\n  /* Delay before next measurement update */\n  delay(1000);\n}\n"
  },
  {
    "path": "examples/hidcontrolkey/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// HARDWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno, etc.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI.\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n"
  },
  {
    "path": "examples/hidcontrolkey/hidcontrolkey.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n/*\n  This example shows how to send HID Consumer Control Keys,\n  ncluding the following control key definitions:\n\n  System Control (works on most systems: Windows/OS X/Android/iOS)\n    - Sound Mute\n    - Brightness Increase, decrease\n  Media Control (works on most systems)\n    - PlayPause\n    - MediaNext\n  Application Launchers (works mainly on Windows 8/10)\n    - EmailReader\n    - Calculator\n  Browser Specific (Firefox, file explorer: mainly on Windows 8/10)\n    - Back\n    - Forward\n    - Refresh\n    - Search\n*/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE       Perform a factory reset when running this sketch\n   \n                              Enabling this will put your Bluefruit LE module\n                              in a 'known good' state and clear any config\n                              data set in previous sketches or projects, so\n                              running this at least once is a good idea.\n   \n                              When deploying your project, however, you will\n                              want to disable factory reset by setting this\n                              value to 0.  If you are making changes to your\n                              Bluefruit LE device via AT commands, and those\n                              changes aren't persisting across resets, this\n                              is the reason why.  Factory reset will erase\n                              the non-volatile memory where config data is\n                              stored, setting it back to factory default\n                              values.\n       \n                              Some sketches that require you to bond to a\n                              central device (HID mouse, keyboard, etc.)\n                              won't work at all with this feature enabled\n                              since the factory reset will clear all of the\n                              bonding data stored on the chip, meaning the\n                              central device won't be able to reconnect.\n    MINIMUM_FIRMWARE_VERSION  Minimum firmware version to have some new features\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE         0\n    #define MINIMUM_FIRMWARE_VERSION    \"0.6.6\"\n/*=========================================================================*/\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // Required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit HID Control Key Example\"));\n  Serial.println(F(\"---------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Factory reset failed!\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  // This demo only works with firmware 0.6.6 and higher!\n  // Request the Bluefruit firmware rev and check if it is valid\n  if ( !ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )\n  {\n    error(F(\"This sketch requires firmware version \" MINIMUM_FIRMWARE_VERSION \" or higher!\"));\n  }\n\n  /* Enable HID Service */\n  Serial.println(F(\"Enable HID Services (including Control Key): \"));\n  if (! ble.sendCommandCheckOK(F( \"AT+BLEHIDEN=On\"  ))) {\n    error(F(\"Failed to enable HID (firmware >=0.6.6?)\"));\n  }\n\n  /* Adding or removing services requires a reset */\n  Serial.println(F(\"Performing a SW reset (service changes require a reset): \"));\n  if (! ble.reset() ) {\n    error(F(\"Couldn't reset??\"));\n  }\n\n  Serial.println();\n  Serial.println(F(\"**********************************************************\"));\n  Serial.println(F(\"Go to your phone's Bluetooth settings to pair your device\"));\n  Serial.println(F(\"Some Control Key works system-wide: mute, brightness ...\"));\n  Serial.println(F(\"Some are application specific: Media play/pause\"));\n  Serial.println(F(\"**********************************************************\"));\n\n  // Print pre-defined control keys\n  printDefinedControlKey();\n\n  Serial.println();\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  // Display prompt\n  Serial.print(F(\"Control (? for help) > \"));\n\n  // Check for user input and echo it back if anything was found\n  char keys[BUFSIZE+1];\n  getUserInput(keys, BUFSIZE);\n\n  Serial.println(keys);\n\n  if ( keys[0] == '?')\n  {\n    printDefinedControlKey();\n  }else\n  {\n    ble.print(\"AT+BleHidControlKey=\");\n    ble.println(keys);\n\n    if( ble.waitForOK() )\n    {\n      Serial.println( F(\"OK!\") );\n    }else\n    {\n      Serial.println( F(\"FAILED!\") );\n      // Failed, probably pairing is not complete yet\n      Serial.println( F(\"Please make sure Bluefruit is paired and try again\") );\n    }\n  }\n}\n\n/**************************************************************************/\n/*!\n    @brief  Checks for user input (via the Serial Monitor)\n*/\n/**************************************************************************/\nvoid getUserInput(char buffer[], uint8_t maxSize)\n{\n  memset(buffer, 0, maxSize);\n  while( Serial.available() == 0 ) {\n    delay(1);\n  }\n\n  uint8_t count=0;\n\n  do\n  {\n    count += Serial.readBytes(buffer+count, maxSize);\n    delay(2);\n  } while( (count < maxSize) && !(Serial.available() == 0) );\n}\n\n/**************************************************************************/\n/*!\n    @brief  Print pre-defined control keys\n*/\n/**************************************************************************/\nvoid printDefinedControlKey(void)\n{\n  Serial.println();\n  Serial.println(F(\"You can send a raw 16-bit (e.g 0x1234) usage key from the USB\" \"\\n\"\n                    \"HID Consumer Control Page or use one of the the following keys:\"));\n\n  Serial.println(F(\"List of pre-defined control keys:\"));\n  Serial.print(F(\n    \"- BRIGHTNESS+\" \"\\n\"\n    \"- BRIGHTNESS-\" \"\\n\"\n    \"- PLAYPAUSE\" \"\\n\"\n    \"- MEDIANEXT\" \"\\n\"\n    \"- MEDIAPREVIOUS\" \"\\n\"\n    \"- MEDIASTOP\" \"\\n\"\n    \"- VOLUME\" \"\\n\"\n    \"- MUTE\" \"\\n\"\n    \"- BASS\" \"\\n\"\n    \"- TREBLE\" \"\\n\"\n    \"- BASS_BOOST\" \"\\n\"\n    \"- VOLUME+\" \"\\n\"\n    \"- VOLUME-\" \"\\n\"\n    \"- BASS+\" \"\\n\"\n    \"- BASS-\" \"\\n\"\n    \"- TREBLE+\" \"\\n\"\n    \"- TREBLE-\" \"\\n\"\n    \"- EMAILREADER\" \"\\n\"\n    \"- CALCULATOR\" \"\\n\"\n    \"- FILEBROWSER\" \"\\n\"\n    \"- SEARCH\" \"\\n\"\n    \"- HOME\" \"\\n\"\n    \"- BACK\" \"\\n\"\n    \"- FORWARD\" \"\\n\"\n    \"- STOP\" \"\\n\"\n    \"- REFRESH\" \"\\n\"\n    \"- BOOKMARKS\" \"\\n\"\n  ));\n}\n"
  },
  {
    "path": "examples/hidkeyboard/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// HARDWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno, etc.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI.\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n"
  },
  {
    "path": "examples/hidkeyboard/hidkeyboard.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n/*\n  This example shows how to send HID (keyboard/mouse/etc) data via BLE\n  Note that not all devices support BLE keyboard! BLE Keyboard != Bluetooth Keyboard\n*/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE       Perform a factory reset when running this sketch\n   \n                              Enabling this will put your Bluefruit LE module\n                              in a 'known good' state and clear any config\n                              data set in previous sketches or projects, so\n                              running this at least once is a good idea.\n   \n                              When deploying your project, however, you will\n                              want to disable factory reset by setting this\n                              value to 0.  If you are making changes to your\n                              Bluefruit LE device via AT commands, and those\n                              changes aren't persisting across resets, this\n                              is the reason why.  Factory reset will erase\n                              the non-volatile memory where config data is\n                              stored, setting it back to factory default\n                              values.\n       \n                              Some sketches that require you to bond to a\n                              central device (HID mouse, keyboard, etc.)\n                              won't work at all with this feature enabled\n                              since the factory reset will clear all of the\n                              bonding data stored on the chip, meaning the\n                              central device won't be able to reconnect.\n    MINIMUM_FIRMWARE_VERSION  Minimum firmware version to have some new features\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE         0\n    #define MINIMUM_FIRMWARE_VERSION    \"0.6.6\"\n/*=========================================================================*/\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit HID Keyboard Example\"));\n  Serial.println(F(\"---------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  /* Change the device name to make it easier to find */\n  Serial.println(F(\"Setting device name to 'Bluefruit Keyboard': \"));\n  if (! ble.sendCommandCheckOK(F( \"AT+GAPDEVNAME=Bluefruit Keyboard\" )) ) {\n    error(F(\"Could not set device name?\"));\n  }\n\n  /* Enable HID Service */\n  Serial.println(F(\"Enable HID Service (including Keyboard): \"));\n  if ( ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )\n  {\n    if ( !ble.sendCommandCheckOK(F( \"AT+BleHIDEn=On\" ))) {\n      error(F(\"Could not enable Keyboard\"));\n    }\n  }else\n  {\n    if (! ble.sendCommandCheckOK(F( \"AT+BleKeyboardEn=On\"  ))) {\n      error(F(\"Could not enable Keyboard\"));\n    }\n  }\n\n  /* Add or remove service requires a reset */\n  Serial.println(F(\"Performing a SW reset (service changes require a reset): \"));\n  if (! ble.reset() ) {\n    error(F(\"Couldn't reset??\"));\n  }\n\n  Serial.println();\n  Serial.println(F(\"Go to your phone's Bluetooth settings to pair your device\"));\n  Serial.println(F(\"then open an application that accepts keyboard input\"));\n\n  Serial.println();\n  Serial.println(F(\"Enter the character(s) to send:\"));\n  Serial.println(F(\"- \\\\r for Enter\"));\n  Serial.println(F(\"- \\\\n for newline\"));\n  Serial.println(F(\"- \\\\t for tab\"));\n  Serial.println(F(\"- \\\\b for backspace\"));\n\n  Serial.println();\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  // Display prompt\n  Serial.print(F(\"keyboard > \"));\n\n  // Check for user input and echo it back if anything was found\n  char keys[BUFSIZE+1];\n  getUserInput(keys, BUFSIZE);\n\n  Serial.print(\"\\nSending \");\n  Serial.println(keys);\n\n  ble.print(\"AT+BleKeyboard=\");\n  ble.println(keys);\n\n  if( ble.waitForOK() )\n  {\n    Serial.println( F(\"OK!\") );\n  }else\n  {\n    Serial.println( F(\"FAILED!\") );\n  }\n}\n\n/**************************************************************************/\n/*!\n    @brief  Checks for user input (via the Serial Monitor)\n*/\n/**************************************************************************/\nvoid getUserInput(char buffer[], uint8_t maxSize)\n{\n  memset(buffer, 0, maxSize);\n  while( Serial.available() == 0 ) {\n    delay(1);\n  }\n\n  uint8_t count=0;\n\n  do\n  {\n    count += Serial.readBytes(buffer+count, maxSize);\n    delay(2);\n  } while( (count < maxSize) && !(Serial.available() == 0) );\n}\n"
  },
  {
    "path": "examples/hidmouse/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// HARDWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno, etc.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI.\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n"
  },
  {
    "path": "examples/hidmouse/hidmouse.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n/*\n  This example shows how to send HID (keyboard/mouse/etc) data via BLE\n  Note that not all devices support BLE Mouse!\n  - OSX, Windows 10 both work\n  - Android has limited support\n  - iOS completely ignores mouse\n*/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n#include \"BluefruitConfig.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE       Perform a factory reset when running this sketch\n   \n                              Enabling this will put your Bluefruit LE module\n                              in a 'known good' state and clear any config\n                              data set in previous sketches or projects, so\n                              running this at least once is a good idea.\n   \n                              When deploying your project, however, you will\n                              want to disable factory reset by setting this\n                              value to 0.  If you are making changes to your\n                              Bluefruit LE device via AT commands, and those\n                              changes aren't persisting across resets, this\n                              is the reason why.  Factory reset will erase\n                              the non-volatile memory where config data is\n                              stored, setting it back to factory default\n                              values.\n       \n                              Some sketches that require you to bond to a\n                              central device (HID mouse, keyboard, etc.)\n                              won't work at all with this feature enabled\n                              since the factory reset will clear all of the\n                              bonding data stored on the chip, meaning the\n                              central device won't be able to reconnect.\n    MINIMUM_FIRMWARE_VERSION  Minimum firmware version to have some new features\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE         0\n    #define MINIMUM_FIRMWARE_VERSION    \"0.6.6\"\n/*=========================================================================*/\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit HID Mouse Example\"));\n  Serial.println(F(\"---------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  // This demo only available for firmware from 0.6.6\n  if ( !ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )\n  {\n    error(F(\"This sketch requires firmware version \" MINIMUM_FIRMWARE_VERSION \" or higher!\"));\n  }\n\n  /* Enable HID Service (including Mouse) */\n  Serial.println(F(\"Enable HID Service (including Mouse): \"));\n  if (! ble.sendCommandCheckOK(F( \"AT+BleHIDEn=On\"  ))) {\n    error(F(\"Failed to enable HID (firmware >=0.6.6?)\"));\n  }\n\n  /* Add or remove service requires a reset */\n  Serial.println(F(\"Performing a SW reset (service changes require a reset): \"));\n  if (! ble.reset() ) {\n    error(F(\"Could not reset??\"));\n  }\n\n  Serial.println();\n  Serial.println(F(\"Go to your phone's Bluetooth settings to pair your device\"));\n  Serial.println(F(\"then open an application that accepts mouse input\"));\n  Serial.println();\n\n  Serial.println(F(\"The example will try to draw a rectangle using the left mouse button with your input\"));\n  Serial.println(F(\"Parameters are a pair of 8-bit signed numbers (x,y) e.g:\"));\n  Serial.println(F(\"  100,100  : draw toward bottom right corner\"));\n  Serial.println(F(\"  -100,-100: draw toward top left corner\"));\n\n  Serial.println();\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  Serial.println(F(\"x,y = \"));\n\n  // Check for user input and echo it back if anything was found\n  char input[BUFSIZE+1];\n  getUserInput(input, BUFSIZE);\n\n  Serial.println(input);\n\n  // Press (and hold) the Left mouse's button\n  if ( ble.sendCommandCheckOK(F(\"AT+BleHidMouseButton=L,press\")) )\n  {\n    // delay a bit\n    delay(250);\n\n    // Mouse moves according to the user's input\n    ble.print(F(\"AT+BleHidMouseMove=\"));\n    ble.println(input);\n\n    if( ble.waitForOK() )\n    {\n      Serial.println( F(\"OK!\") );\n    }else\n    {\n      Serial.println( F(\"FAILED!\") );\n    }\n\n    // Way for user to release left button\n    Serial.println( F(\"Enter anything to release Left Button\") );\n    getUserInput(input, BUFSIZE);\n\n    // Release the Left mouse's button\n    ble.sendCommandCheckOK(F(\"AT+BleHidMouseButton=0\"));\n  }else\n  {\n    // Failed, probably pairing is not complete yet\n    Serial.println( F(\"Please make sure Bluefruit is paired and try again\") );\n  }\n}\n\n/**************************************************************************/\n/*!\n    @brief  Checks for user input (via the Serial Monitor)\n*/\n/**************************************************************************/\nvoid getUserInput(char buffer[], uint8_t maxSize)\n{\n  memset(buffer, 0, maxSize);\n  while( Serial.available() == 0 ) {\n    delay(1);\n  }\n\n  uint8_t count=0;\n\n  do\n  {\n    count += Serial.readBytes(buffer+count, maxSize);\n    delay(2);\n  } while( (count < maxSize) && !(Serial.available() == 0) );\n}\n"
  },
  {
    "path": "examples/midi/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         12   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        -1    // Set to -1 if unused\n\n\n// HARDWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno, etc.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI.\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              6    // Optional but recommended, set to -1 if unused\n"
  },
  {
    "path": "examples/midi/midi.ino",
    "content": "#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#include \"Adafruit_BLEMIDI.h\"\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n#include \"BluefruitConfig.h\"\n\n#define FACTORYRESET_ENABLE         1\n#define MINIMUM_FIRMWARE_VERSION    \"0.7.0\"\n\n// This app was tested on iOS with the following apps:\n//\n// https://itunes.apple.com/us/app/midimittr/id925495245?mt=8\n// https://itunes.apple.com/us/app/igrand-piano-free-for-ipad/id562914032?mt=8\n//\n// To test:\n// - Run this sketch and open the Serial Monitor\n// - Open the iGrand Piano Free app\n// - Open the midimittr app on your phone and under Clients select \"Adafruit Bluefruit LE\"\n// - When you see the 'Connected' label switch to the Routing panel\n// - Set the Destination to 'iGrand Piano'\n// - Switch to the iGrand Piano Free app and you should see notes playing one by one\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                              BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\nAdafruit_BLEMIDI midi(ble);\n\nbool isConnected = false;\nint current_note = 60;\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n// callback\nvoid connected(void)\n{\n  isConnected = true;\n\n  Serial.println(F(\" CONNECTED!\"));\n  delay(1000);\n\n}\n\nvoid disconnected(void)\n{\n  Serial.println(\"disconnected\");\n  isConnected = false;\n}\n\nvoid BleMidiRX(uint16_t timestamp, uint8_t status, uint8_t byte1, uint8_t byte2)\n{\n  Serial.print(\"[MIDI \");\n  Serial.print(timestamp);\n  Serial.print(\" ] \");\n\n  Serial.print(status, HEX); Serial.print(\" \");\n  Serial.print(byte1 , HEX); Serial.print(\" \");\n  Serial.print(byte2 , HEX); Serial.print(\" \");\n\n  Serial.println();\n}\n\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit MIDI Example\"));\n  Serial.println(F(\"---------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ) {\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  //ble.sendCommandCheckOK(F(\"AT+uartflow=off\"));\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  /* Set BLE callbacks */\n  ble.setConnectCallback(connected);\n  ble.setDisconnectCallback(disconnected);\n\n  // Set MIDI RX callback\n  midi.setRxCallback(BleMidiRX);\n\n  Serial.println(F(\"Enable MIDI: \"));\n  if ( ! midi.begin(true) )\n  {\n    error(F(\"Could not enable MIDI\"));\n  }\n\n  ble.verbose(false);\n  Serial.print(F(\"Waiting for a connection...\"));\n}\n\nvoid loop(void)\n{\n  // interval for each scanning ~ 500ms (non blocking)\n  ble.update(500);\n\n  // bail if not connected\n  if (! isConnected)\n    return;\n\n  Serial.print(\"Sending pitch \");\n  Serial.println(current_note, HEX);\n\n  // send note on\n  midi.send(0x90, current_note, 0x64);\n  delay(500);\n\n  // send note off\n  midi.send(0x80, current_note, 0x64);\n  delay(500);\n\n  // increment note pitch\n  current_note++;\n\n  // only do one octave\n  if(current_note > 72)\n    current_note = 60;\n\n}\n"
  },
  {
    "path": "examples/ndof_bno055/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/ndof_bno055/README.md",
    "content": "# NDOF BNO055 Example\n\nThis example is intended to be used with a board like the [Bluefruit LE Micro](https://www.adafruit.com/product/2661).\n\nIt will read data samples from the [BNO055](https://www.adafruit.com/products/2472)\nat a fixed rate, and transmit the data over the air using the BLE UART service.\n\n# Requirements\n\nTo use this example, you will also need the following libraries installed on\nyour system:\n\n- [Adafruit_Sensor](https://github.com/adafruit/Adafruit_Sensor)\n- [Adafruit_BNO055](https://github.com/adafruit/Adafruit_BNO055)\n\n## Wiring\n\nConnect your Bluefruit LE Micro to the BNO055 breakout using I2C as follows:\n\n- VIN on the BNO055 to USB on the Bluefruit LE Micro\n- GND on the BNO055 to GND on the Bluefruit LE Micro\n- SDA on the BNO055 to SDA on the Bluefruit LE Micro\n- SCL on the BNO055 to SCL on the Bluefruit LE Micro\n"
  },
  {
    "path": "examples/ndof_bno055/ndof_bno055.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include <Wire.h>\n#include <Adafruit_Sensor.h>\n#include <Adafruit_BNO055.h>\n#include <utility/imumaths.h>\n\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n#include \"BluefruitConfig.h\"\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* Set the delay between fresh samples (not too fast, BLE UART is slow!) */\n/* Firware <=0.6.6 should use 500ms, >=0.6.7 can use 200ms */\n#define BNO055_SAMPLERATE_DELAY_MS (500)\n\nAdafruit_BNO055 bno = Adafruit_BNO055(55);\n\n/**************************************************************************/\n/*!\n    @brief  A small helper function for error messages\n*/\n/**************************************************************************/\nvoid error(const __FlashStringHelper*err)\n{\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*\n    Displays some basic information on this sensor from the unified\n    sensor API sensor_t type (see Adafruit_Sensor for more information)\n*/\n/**************************************************************************/\nvoid displaySensorDetails(void)\n{\n  sensor_t sensor;\n  bno.getSensor(&sensor);\n  Serial.println(\"------------------------------------\");\n  Serial.print  (\"Sensor:       \"); Serial.println(sensor.name);\n  Serial.print  (\"Driver Ver:   \"); Serial.println(sensor.version);\n  Serial.print  (\"Unique ID:    \"); Serial.println(sensor.sensor_id);\n  Serial.print  (\"Max Value:    \"); Serial.print(sensor.max_value); Serial.println(\" xxx\");\n  Serial.print  (\"Min Value:    \"); Serial.print(sensor.min_value); Serial.println(\" xxx\");\n  Serial.print  (\"Resolution:   \"); Serial.print(sensor.resolution); Serial.println(\" xxx\");\n  Serial.println(\"------------------------------------\");\n  Serial.println(\"\");\n  delay(500);\n}\n\n/**************************************************************************/\n/*\n    Display some basic info about the sensor status\n*/\n/**************************************************************************/\nvoid displaySensorStatus(void)\n{\n  // Get the system status values (mostly for debugging purposes)\n  uint8_t system_status, self_test_results, system_error;\n  system_status = self_test_results = system_error = 0;\n  bno.getSystemStatus(&system_status, &self_test_results, &system_error);\n\n  // Display the results in the Serial Monitor\n  Serial.print(\"System Status: 0x\");\n  Serial.println(system_status, HEX);\n  Serial.print(\"Self Test:     0x\");\n  Serial.println(self_test_results, HEX);\n  Serial.print(\"System Error:  0x\");\n  Serial.println(system_error, HEX);\n  Serial.println(\"\");\n  delay(500);\n}\n\n/**************************************************************************/\n/*\n    Display sensor calibration status\n*/\n/**************************************************************************/\nvoid displayCalStatus(void)\n{\n  // Get the four calibration values (0..3)\n  // 3 means 'fully calibrated\"\n  uint8_t system, gyro, accel, mag;\n  system = gyro = accel = mag = 0;\n  bno.getCalibration(&system, &gyro, &accel, &mag);\n\n  // The data should be ignored until the system calibration is > 0\n  Serial.print(\"\\t\");\n  if (!system)\n  {\n    Serial.print(\"! \");\n  }\n\n  // Display the individual values\n  Serial.print(\"Sys:\");\n  Serial.print(system, DEC);\n  Serial.print(\" G:\");\n  Serial.print(gyro, DEC);\n  Serial.print(\" A:\");\n  Serial.print(accel, DEC);\n  Serial.print(\" M:\");\n  Serial.print(mag, DEC);\n}\n\n/**************************************************************************/\n/*\n    Sends sensor calibration status out over BLE UART\n*/\n/**************************************************************************/\nvoid transmitCalStatus(void)\n{\n  uint8_t system, gyro, accel, mag;\n  system = gyro = accel = mag = 0;\n\n  // Get the four calibration values (0..3)\n  // 3 means 'fully calibrated\"\n  bno.getCalibration(&system, &gyro, &accel, &mag);\n\n  /* Prepare the AT command */\n  ble.print(\"AT+BLEUARTTX=\");\n\n  // Transmit individual values\n  // Note: The values are abbreviated compared to the Serial Monitor\n  // to save space since BLE UART is quite slow */\n  ble.print(\",\");\n  ble.print(system, DEC);\n  ble.print(gyro, DEC);\n  ble.print(accel, DEC);\n  ble.println(mag, DEC);\n\n  if (! ble.waitForOK() )\n  {\n    Serial.println(F(\"Failed to send?\"));\n  }\n}\n\n/**************************************************************************/\n/*!\n    @brief  Initializes the one wire temperature sensor\n*/\n/**************************************************************************/\nvoid initSensor(void)\n{\n  if(!bno.begin())\n  {\n    // There was a problem detecting the BNO055 ... check your connections\n    Serial.print(\"Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!\");\n    while(1);\n  }\n\n  delay(1000);\n\n  // Display some basic information on this sensor\n  displaySensorDetails();\n\n  // Optional: Display current status\n  displaySensorStatus();\n\n  bno.setExtCrystalUse(true);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit Command Mode Example\"));\n  Serial.println(F(\"---------------------------------------\"));\n\n  // Initialise the module\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  // Perform a factory reset to make sure everything is in a known state\n  Serial.println(F(\"Performing a factory reset: \"));\n  if (! ble.factoryReset() ){\n       error(F(\"Couldn't factory reset\"));\n  }\n\n  // Disable command echo from Bluefruit\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  // Print Bluefruit information\n  ble.info();\n\n  ble.verbose(false);  // debug info is a little annoying after this point!\n\n  // Setup the BNO055 sensor\n  initSensor();\n\n  Serial.println(\"Waiting for a BLE connection to continue ...\");\n\n  // Wait for connection to finish\n  while (! ble.isConnected()) {\n      delay(5000);\n  }\n\n  Serial.println(F(\"CONNECTED!\"));\n  Serial.println(F(\"**********\"));\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  // Check for user input\n  char inputs[BUFSIZE+1];\n\n  // Send sensor data out\n  if (ble.isConnected())\n  {\n    // Get Quaternion data (no 'Gimbal Lock' like with Euler angles)\n    imu::Quaternion quat = bno.getQuat();\n\n    // Display the full data in Serial Monitor\n    Serial.print(\"qW: \");\n    Serial.print(quat.w(), 4);\n    Serial.print(\" qX: \");\n    Serial.print(quat.y(), 4);\n    Serial.print(\" qY: \");\n    Serial.print(quat.x(), 4);\n    Serial.print(\" qZ: \");\n    Serial.print(quat.z(), 4);\n    displayCalStatus();\n    Serial.println(\"\");\n\n    // Send abbreviated integer data out over BLE UART\n    ble.print(\"AT+BLEUARTTX=\");\n    ble.print(quat.w(), 4);\n    ble.print(\",\");\n    ble.print(quat.y(), 4);\n    ble.print(\",\");\n    ble.print(quat.x(), 4);\n    ble.print(\",\");\n    ble.println(quat.z(), 4);\n    if (! ble.waitForOK() )\n    {\n      Serial.println(F(\"Failed to send?\"));\n    }\n\n    // Optional: Send the calibration data as well\n    transmitCalStatus();\n\n    // Send a new line character for the next record\n    ble.println(\"AT+BLEUARTTX=\\\\r\\\\n\");\n    if (! ble.waitForOK() )\n    {\n      Serial.println(F(\"Failed to send?\"));\n    }\n\n    /*\n    // Display the buffer size (firmware 0.6.7 and higher only!)\n    ble.println(\"AT+BLEUARTFIFO=TX\");\n    ble.readline();\n    Serial.print(\"TX FIFO: \");\n    Serial.println(ble.buffer);\n    */\n\n    // Wait a bit ...\n    delay(BNO055_SAMPLERATE_DELAY_MS);\n  }\n\n  // Check for incoming characters from Bluefruit\n  if (ble.isConnected())\n  {\n    ble.println(\"AT+BLEUARTRX\");\n    ble.readline();\n    if (strcmp(ble.buffer, \"OK\") == 0) {\n      // no data\n      return;\n    }\n    // Some data was found, its in the buffer\n    Serial.print(F(\"[Recv] \")); Serial.println(ble.buffer);\n    ble.waitForOK();\n  }\n}\n"
  },
  {
    "path": "examples/neopixel/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n#define BLE_READPACKET_TIMEOUT         500   // Timeout in ms waiting to read a response\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/neopixel/neopixel.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n// This sketch is intended to be used with the NeoPixel control\n// surface in Adafruit's Bluefruit LE Connect mobile application.\n//\n// - Compile and flash this sketch to a board connected to/bundled with a nRF51\n// - Open the Bluefruit LE Connect app\n// - Switch to the NeoPixel utility\n// - Click the 'connect' button to establish a connection and\n//   send the meta-data about the pixel layout\n// - Use the NeoPixel utility to update the pixels on your device\n\n/* NOTE: This sketch required at least version 1.1.0 of Adafruit_Neopixel !!! */\n\n#include <string.h>\n#include <Arduino.h>\n#include <SPI.h>\n#include <Adafruit_NeoPixel.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n#include \"BluefruitConfig.h\"\n\n#define FACTORYRESET_ENABLE     1\n#define NEOPIXEL_VERSION_STRING \"Neopixel v2.0\"\n#define PIN                     6   /* Pin used to drive the NeoPixels */\n\n#define MAXCOMPONENTS  4\nuint8_t *pixelBuffer = NULL;\nuint8_t width = 0;\nuint8_t height = 0;\nuint8_t stride;\nuint8_t componentsValue;\nbool is400Hz;\nuint8_t components = 3;     // only 3 and 4 are valid values\n\nAdafruit_NeoPixel neopixel = Adafruit_NeoPixel();\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\nvoid serial_printf(const char * format, ...) {\n  char buffer [48];\n  va_list args;\n  va_start(args, format);\n  vsnprintf(buffer, sizeof(buffer), format, args);\n  va_end(args);\n  Serial.print(buffer);\n}\n\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  Serial.begin(115200);\n  Serial.println(\"Adafruit Bluefruit Neopixel Test\");\n  Serial.println(\"--------------------------------\");\n\n  Serial.println();\n  Serial.println(\"Please connect using the Bluefruit Connect LE application\");\n\n  // Config Neopixels\n  neopixel.begin();\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  ble.verbose(false);  // debug info is a little annoying after this point!\n\n    /* Wait for connection */\n  while (! ble.isConnected()) {\n      delay(500);\n  }\n\n  Serial.println(F(\"***********************\"));\n\n  // Set Bluefruit to DATA mode\n  Serial.println( F(\"Switching to DATA mode!\") );\n  ble.setMode(BLUEFRUIT_MODE_DATA);\n\n  Serial.println(F(\"***********************\"));\n\n}\n\nvoid loop()\n{\n  // Echo received data\n  if ( ble.isConnected() )\n  {\n    int command = ble.read();\n\n    switch (command) {\n      case 'V': {   // Get Version\n          commandVersion();\n          break;\n        }\n  \n      case 'S': {   // Setup dimensions, components, stride...\n          commandSetup();\n          break;\n       }\n\n      case 'C': {   // Clear with color\n          commandClearColor();\n          break;\n      }\n\n      case 'B': {   // Set Brightness\n          commandSetBrightness();\n          break;\n      }\n            \n      case 'P': {   // Set Pixel\n          commandSetPixel();\n          break;\n      }\n  \n      case 'I': {   // Receive new image\n          commandImage();\n          break;\n       }\n\n    }\n  }\n}\n\nvoid swapBuffers()\n{\n  uint8_t *base_addr = pixelBuffer;\n  int pixelIndex = 0;\n  for (int j = 0; j < height; j++)\n  {\n    for (int i = 0; i < width; i++) {\n      if (components == 3) {\n        neopixel.setPixelColor(pixelIndex, neopixel.Color(*base_addr, *(base_addr+1), *(base_addr+2)));\n      }\n      else {\n        neopixel.setPixelColor(pixelIndex, neopixel.Color(*base_addr, *(base_addr+1), *(base_addr+2), *(base_addr+3) ));\n      }\n      base_addr+=components;\n      pixelIndex++;\n    }\n    pixelIndex += stride - width;   // Move pixelIndex to the next row (take into account the stride)\n  }\n  neopixel.show();\n\n}\n\nvoid commandVersion() {\n  Serial.println(F(\"Command: Version check\"));\n  sendResponse(NEOPIXEL_VERSION_STRING);\n}\n\nvoid commandSetup() {\n  Serial.println(F(\"Command: Setup\"));\n\n  width = ble.read();\n  height = ble.read();\n  stride = ble.read();\n  componentsValue = ble.read();\n  is400Hz = ble.read();\n\n  neoPixelType pixelType;\n  pixelType = componentsValue + (is400Hz ? NEO_KHZ400 : NEO_KHZ800);\n\n  components = (componentsValue == NEO_RGB || componentsValue == NEO_RBG || componentsValue == NEO_GRB || componentsValue == NEO_GBR || componentsValue == NEO_BRG || componentsValue == NEO_BGR) ? 3:4;\n\n  serial_printf(\"\\tsize: %dx%d\\n\", width, height);\n  serial_printf(\"\\tstride: %d\\n\", stride);\n  serial_printf(\"\\tpixelType %d\\n\", pixelType);\n  serial_printf(\"\\tcomponents: %d\\n\", components);\n\n  if (pixelBuffer != NULL) {\n      delete[] pixelBuffer;\n  }\n\n  uint32_t size = width*height;\n  pixelBuffer = new uint8_t[size*components];\n  neopixel.updateLength(size);\n  neopixel.updateType(pixelType);\n  neopixel.setPin(PIN);\n\n  // Done\n  sendResponse(\"OK\");\n}\n\nvoid commandSetBrightness() {\n  Serial.println(F(\"Command: SetBrightness\"));\n\n   // Read value\n  uint8_t brightness = ble.read();\n\n  // Set brightness\n  neopixel.setBrightness(brightness);\n\n  // Refresh pixels\n  swapBuffers();\n\n  // Done\n  sendResponse(\"OK\");\n}\n\nvoid commandClearColor() {\n  Serial.println(F(\"Command: ClearColor\"));\n\n  // Read color\n  uint8_t color[MAXCOMPONENTS];\n  for (int j = 0; j < components;) {\n    if (ble.available()) {\n      color[j] = ble.read();\n      j++;\n    }\n  }\n\n  // Set all leds to color\n  int size = width * height;\n  uint8_t *base_addr = pixelBuffer;\n  for (int i = 0; i < size; i++) {\n    for (int j = 0; j < components; j++) {\n      *base_addr = color[j];\n      base_addr++;\n    }\n  }\n\n  // Swap buffers\n  Serial.println(F(\"ClearColor completed\"));\n  swapBuffers();\n\n\n  if (components == 3) {\n    serial_printf(\"\\tclear (%d, %d, %d)\\n\", color[0], color[1], color[2] );\n  }\n  else {\n    serial_printf(\"\\tclear (%d, %d, %d, %d)\\n\", color[0], color[1], color[2], color[3] );\n  }\n  \n  // Done\n  sendResponse(\"OK\");\n}\n\nvoid commandSetPixel() {\n  Serial.println(F(\"Command: SetPixel\"));\n\n  // Read position\n  uint8_t x = ble.read();\n  uint8_t y = ble.read();\n\n  // Read colors\n  uint32_t pixelOffset = y*width+x;\n  uint32_t pixelDataOffset = pixelOffset*components;\n  uint8_t *base_addr = pixelBuffer+pixelDataOffset;\n  for (int j = 0; j < components;) {\n    if (ble.available()) {\n      *base_addr = ble.read();\n      base_addr++;\n      j++;\n    }\n  }\n\n  // Set colors\n  uint32_t neopixelIndex = y*stride+x;\n  uint8_t *pixelBufferPointer = pixelBuffer + pixelDataOffset;\n  uint32_t color;\n  if (components == 3) {\n    color = neopixel.Color( *pixelBufferPointer, *(pixelBufferPointer+1), *(pixelBufferPointer+2) );\n    serial_printf(\"\\tcolor (%d, %d, %d)\\n\",*pixelBufferPointer, *(pixelBufferPointer+1), *(pixelBufferPointer+2) );\n  }\n  else {\n    color = neopixel.Color( *pixelBufferPointer, *(pixelBufferPointer+1), *(pixelBufferPointer+2), *(pixelBufferPointer+3) );\n    serial_printf(\"\\tcolor (%d, %d, %d, %d)\\n\", *pixelBufferPointer, *(pixelBufferPointer+1), *(pixelBufferPointer+2), *(pixelBufferPointer+3) );    \n  }\n  neopixel.setPixelColor(neopixelIndex, color);\n  neopixel.show();\n\n  // Done\n  sendResponse(\"OK\");\n}\n\nvoid commandImage() {\n  serial_printf(\"Command: Image %dx%d, %d, %d\\n\", width, height, components, stride);\n  \n  // Receive new pixel buffer\n  int size = width * height;\n  uint8_t *base_addr = pixelBuffer;\n  for (int i = 0; i < size; i++) {\n    for (int j = 0; j < components;) {\n      if (ble.available()) {\n        *base_addr = ble.read();\n        base_addr++;\n        j++;\n      }\n    }\n\n/*\n    if (components == 3) {\n      uint32_t index = i*components;\n      Serial.printf(\"\\tp%d (%d, %d, %d)\\n\", i, pixelBuffer[index], pixelBuffer[index+1], pixelBuffer[index+2] );\n    }\n    */\n  }\n\n  // Swap buffers\n  Serial.println(F(\"Image received\"));\n  swapBuffers();\n\n  // Done\n  sendResponse(\"OK\");\n}\n\nvoid sendResponse(char const *response) {\n    serial_printf(\"Send Response: %s\\n\", response);\n    ble.write(response, strlen(response)*sizeof(char));\n}\n"
  },
  {
    "path": "examples/neopixel_picker/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n#define BLE_READPACKET_TIMEOUT         500   // Timeout in ms waiting to read a response\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/neopixel_picker/neopixel_picker.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <string.h>\n#include <Arduino.h>\n#include <SPI.h>\n#include <Adafruit_NeoPixel.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n#include \"BluefruitConfig.h\"\n\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE       Perform a factory reset when running this sketch\n   \n                              Enabling this will put your Bluefruit LE module\n                              in a 'known good' state and clear any config\n                              data set in previous sketches or projects, so\n                              running this at least once is a good idea.\n   \n                              When deploying your project, however, you will\n                              want to disable factory reset by setting this\n                              value to 0.  If you are making changes to your\n                              Bluefruit LE device via AT commands, and those\n                              changes aren't persisting across resets, this\n                              is the reason why.  Factory reset will erase\n                              the non-volatile memory where config data is\n                              stored, setting it back to factory default\n                              values.\n       \n                              Some sketches that require you to bond to a\n                              central device (HID mouse, keyboard, etc.)\n                              won't work at all with this feature enabled\n                              since the factory reset will clear all of the\n                              bonding data stored on the chip, meaning the\n                              central device won't be able to reconnect.\n    PIN                       Which pin on the Arduino is connected to the NeoPixels?\n    NUMPIXELS                 How many NeoPixels are attached to the Arduino?\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE     1\n\n    #define PIN                     5\n    #define NUMPIXELS               1\n/*=========================================================================*/\n\nAdafruit_NeoPixel pixel = Adafruit_NeoPixel(NUMPIXELS, PIN);\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n// function prototypes over in packetparser.cpp\nuint8_t readPacket(Adafruit_BLE *ble, uint16_t timeout);\nfloat parsefloat(uint8_t *buffer);\nvoid printHex(const uint8_t * data, const uint32_t numBytes);\n\n// the packet buffer\nextern uint8_t packetbuffer[];\n\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  // turn off neopixel\n  pixel.begin(); // This initializes the NeoPixel library.\n  for(uint8_t i=0; i<NUMPIXELS; i++) {\n    pixel.setPixelColor(i, pixel.Color(0,0,0)); // off\n  }\n  pixel.show();\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit Neopixel Color Picker Example\"));\n  Serial.println(F(\"------------------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  Serial.println(F(\"Please use Adafruit Bluefruit LE app to connect in Controller mode\"));\n  Serial.println(F(\"Then activate/use the sensors, color picker, game controller, etc!\"));\n  Serial.println();\n\n  ble.verbose(false);  // debug info is a little annoying after this point!\n\n  /* Wait for connection */\n  while (! ble.isConnected()) {\n      delay(500);\n  }\n\n  Serial.println(F(\"***********************\"));\n\n  // Set Bluefruit to DATA mode\n  Serial.println( F(\"Switching to DATA mode!\") );\n  ble.setMode(BLUEFRUIT_MODE_DATA);\n\n  Serial.println(F(\"***********************\"));\n\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  /* Wait for new data to arrive */\n  uint8_t len = readPacket(&ble, BLE_READPACKET_TIMEOUT);\n  if (len == 0) return;\n\n  /* Got a packet! */\n  // printHex(packetbuffer, len);\n\n  // Color\n  if (packetbuffer[1] == 'C') {\n    uint8_t red = packetbuffer[2];\n    uint8_t green = packetbuffer[3];\n    uint8_t blue = packetbuffer[4];\n    Serial.print (\"RGB #\");\n    if (red < 0x10) Serial.print(\"0\");\n    Serial.print(red, HEX);\n    if (green < 0x10) Serial.print(\"0\");\n    Serial.print(green, HEX);\n    if (blue < 0x10) Serial.print(\"0\");\n    Serial.println(blue, HEX);\n\n    for(uint8_t i=0; i<NUMPIXELS; i++) {\n      pixel.setPixelColor(i, pixel.Color(red,green,blue));\n    }\n    pixel.show(); // This sends the updated pixel color to the hardware.\n  }\n\n}\n"
  },
  {
    "path": "examples/neopixel_picker/packetParser.cpp",
    "content": "#include <string.h>\n#include <Arduino.h>\n#include <SPI.h>\n#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)\n  #include <SoftwareSerial.h>\n#endif\n\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n\n\n#define PACKET_ACC_LEN                  (15)\n#define PACKET_GYRO_LEN                 (15)\n#define PACKET_MAG_LEN                  (15)\n#define PACKET_QUAT_LEN                 (19)\n#define PACKET_BUTTON_LEN               (5)\n#define PACKET_COLOR_LEN                (6)\n#define PACKET_LOCATION_LEN             (15)\n\n//    READ_BUFSIZE            Size of the read buffer for incoming packets\n#define READ_BUFSIZE                    (20)\n\n\n/* Buffer to hold incoming characters */\nuint8_t packetbuffer[READ_BUFSIZE+1];\n\n/**************************************************************************/\n/*!\n    @brief  Casts the four bytes at the specified address to a float\n*/\n/**************************************************************************/\nfloat parsefloat(uint8_t *buffer) \n{\n  float f = ((float *)buffer)[0];\n  return f;\n}\n\n/**************************************************************************/\n/*! \n    @brief  Prints a hexadecimal value in plain characters\n    @param  data      Pointer to the byte data\n    @param  numBytes  Data length in bytes\n*/\n/**************************************************************************/\nvoid printHex(const uint8_t * data, const uint32_t numBytes)\n{\n  uint32_t szPos;\n  for (szPos=0; szPos < numBytes; szPos++) \n  {\n    Serial.print(F(\"0x\"));\n    // Append leading 0 for small values\n    if (data[szPos] <= 0xF)\n    {\n      Serial.print(F(\"0\"));\n      Serial.print(data[szPos] & 0xf, HEX);\n    }\n    else\n    {\n      Serial.print(data[szPos] & 0xff, HEX);\n    }\n    // Add a trailing space if appropriate\n    if ((numBytes > 1) && (szPos != numBytes - 1))\n    {\n      Serial.print(F(\" \"));\n    }\n  }\n  Serial.println();\n}\n\n/**************************************************************************/\n/*!\n    @brief  Waits for incoming data and parses it\n*/\n/**************************************************************************/\nuint8_t readPacket(Adafruit_BLE *ble, uint16_t timeout) \n{\n  uint16_t origtimeout = timeout, replyidx = 0;\n\n  memset(packetbuffer, 0, READ_BUFSIZE);\n\n  while (timeout--) {\n    if (replyidx >= 20) break;\n    if ((packetbuffer[1] == 'A') && (replyidx == PACKET_ACC_LEN))\n      break;\n    if ((packetbuffer[1] == 'G') && (replyidx == PACKET_GYRO_LEN))\n      break;\n    if ((packetbuffer[1] == 'M') && (replyidx == PACKET_MAG_LEN))\n      break;\n    if ((packetbuffer[1] == 'Q') && (replyidx == PACKET_QUAT_LEN))\n      break;\n    if ((packetbuffer[1] == 'B') && (replyidx == PACKET_BUTTON_LEN))\n      break;\n    if ((packetbuffer[1] == 'C') && (replyidx == PACKET_COLOR_LEN))\n      break;\n    if ((packetbuffer[1] == 'L') && (replyidx == PACKET_LOCATION_LEN))\n      break;\n\n    while (ble->available()) {\n      char c =  ble->read();\n      if (c == '!') {\n        replyidx = 0;\n      }\n      packetbuffer[replyidx] = c;\n      replyidx++;\n      timeout = origtimeout;\n    }\n    \n    if (timeout == 0) break;\n    delay(1);\n  }\n\n  packetbuffer[replyidx] = 0;  // null term\n\n  if (!replyidx)  // no data or timeout \n    return 0;\n  if (packetbuffer[0] != '!')  // doesn't start with '!' packet beginning\n    return 0;\n  \n  // check checksum!\n  uint8_t xsum = 0;\n  uint8_t checksum = packetbuffer[replyidx-1];\n  \n  for (uint8_t i=0; i<replyidx-1; i++) {\n    xsum += packetbuffer[i];\n  }\n  xsum = ~xsum;\n\n  // Throw an error message if the checksum's don't match\n  if (xsum != checksum)\n  {\n    Serial.print(\"Checksum mismatch in packet : \");\n    printHex(packetbuffer, replyidx+1);\n    return 0;\n  }\n  \n  // checksum passed!\n  return replyidx;\n}\n\n"
  },
  {
    "path": "examples/nvmdata/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        160   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/nvmdata/nvmdata.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n#include \"BluefruitConfig.h\"\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/* This demo perform factory reset on the first run then\n * - Write a defined magic number at offset 0\n * - Write a DATE string at offset 16\n * - Dump the whole NVM section, User's NVM is started at 0x0640\n */\n\n#define MAGIC_NUMBER  0xC0FFEE\n#define MAGIC_STRING  __DATE__\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit NVM DATA Example\"));\n  Serial.println(F(\"-------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  /* Disable command echo from Bluefruit */\n//  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  int32_t magic_number;\n  ble.readNVM(0, &magic_number);\n\n  if ( magic_number != MAGIC_NUMBER )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Magic not found: performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n\n    // Write data to NVM\n    Serial.println( F(\"Write defined data to NVM\") );\n    ble.writeNVM(0 , MAGIC_NUMBER);\n    ble.writeNVM(16, MAGIC_STRING);\n  }else\n  {\n    Serial.println(F(\"Magic found\"));\n  }\n\n  // Read from NVM and print out\n  ble.readNVM(0, &magic_number);\n  Serial.print( F(\"Magic Number: \") );\n  Serial.println( magic_number );\n\n  char magic_str[32];\n  ble.readNVM(16, magic_str, sizeof(magic_str));\n  Serial.print( F(\"Magic String: \") );\n  Serial.println( magic_str );\n\n  // Dump the whole NVM section\n  Serial.println();\n  Serial.println(\"Dumping the whole NVM contents\");\n  ble.atcommand(F(\"AT+DBGNVMRD\"));\n  Serial.println(\"User NVM data is at offset 0x0640\");\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  // Display command prompt\n  Serial.print(F(\"AT > \"));\n\n  // Check for user input and echo it back if anything was found\n  char command[BUFSIZE+1];\n  getUserInput(command, BUFSIZE);\n\n  // Send command\n  ble.atcommand(command);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Checks for user input (via the Serial Monitor)\n*/\n/**************************************************************************/\nvoid getUserInput(char buffer[], uint8_t maxSize)\n{\n  memset(buffer, 0, maxSize);\n  while( Serial.available() == 0 ) {\n    delay(1);\n  }\n\n  uint8_t count=0;\n\n  do\n  {\n    count += Serial.readBytes(buffer+count, maxSize);\n    delay(2);\n  } while( (count < maxSize) && !(Serial.available() == 0) );\n}\n"
  },
  {
    "path": "examples/throughput/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/throughput/throughput.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n#include \"BluefruitConfig.h\"\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE     Perform a factory reset when running this sketch\n   \n                            Enabling this will put your Bluefruit LE module\n                            in a 'known good' state and clear any config\n                            data set in previous sketches or projects, so\n                            running this at least once is a good idea.\n   \n                            When deploying your project, however, you will\n                            want to disable factory reset by setting this\n                            value to 0.  If you are making changes to your\n                            Bluefruit LE device via AT commands, and those\n                            changes aren't persisting across resets, this\n                            is the reason why.  Factory reset will erase\n                            the non-volatile memory where config data is\n                            stored, setting it back to factory default\n                            values.\n       \n                            Some sketches that require you to bond to a\n                            central device (HID mouse, keyboard, etc.)\n                            won't work at all with this feature enabled\n                            since the factory reset will clear all of the\n                            bonding data stored on the chip, meaning the\n                            central device won't be able to reconnect.\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE      1\n/*=========================================================================*/\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n// String to send in the throughput test\n#define TEST_STRING     \"01234567899876543210\"\n\n// Number of total data sent ( 1024 times the test string)\n#define TOTAL_BYTES     (1024 * strlen(TEST_STRING))\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit Throughput Tester\"));\n  Serial.println(F(\"------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  /* Switch to DATA mode to have a better throughput */\n  Serial.println(\"Switch to DATA mode to have a better throughput ...\");\n\n  /* Wait for a connection before starting the test */\n  Serial.println(\"Waiting for a BLE connection to continue ...\");\n  ble.setMode(BLUEFRUIT_MODE_DATA);\n\n  ble.verbose(false);  // debug info is a little annoying after this point!\n\n  // Wait for connection to finish\n  while (! ble.isConnected()) {\n      delay(5000);\n  }\n\n  // Wait for the connection to complete\n  delay(1000);\n\n  Serial.println(F(\"CONNECTED!\"));\n  Serial.println(F(\"**********\"));\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n  uint32_t start, stop, sent;\n  uint32_t remaining = TOTAL_BYTES;\n  start = stop = sent = 0;\n\n  if (ble.isConnected())\n  {\n    // Wait for user input before trying again\n    Serial.println(\"Connected. Send a key and press enter to start test\");\n    char command[BUFSIZE+1];\n    getUserInput(command, BUFSIZE);\n\n    Serial.print(\"Sending \");\n    Serial.print(remaining);\n    Serial.println(\" bytes ...\");\n\n    start = millis();\n    while (remaining > 0)\n    {\n//      ble.print(\"AT+BLEUARTTX=\");\n//      ble.println(TEST_STRING);\n//      if (! ble.waitForOK() )\n//      {\n//        Serial.println(F(\"Failed to send?\"));\n//      }\n\n      ble.writeBLEUart(TEST_STRING);\n      \n      sent      += strlen(TEST_STRING);\n      remaining -= strlen(TEST_STRING);\n\n      // Only print every 1KB sent\n      if ( (sent % 2000) == 0 )\n      {\n        Serial.print(\"Sent: \"); Serial.print(sent);\n        Serial.print(\" Remaining: \"); Serial.println(remaining);\n      }\n\n      /* Optional: Test for lost connection every packet */\n      /* Note that this will slow things down a bit! */\n      /*\n      if (!ble.isConnected())\n      {\n        Serial.println(\"Connection lost\");\n        remaining = 0;\n      }\n      */\n    }\n    stop = millis() - start;\n\n    Serial.print(\"Sent \");\n    Serial.print(sent);\n    Serial.print(\" bytes in \");\n    Serial.print(stop/1000.0F, 2);\n    Serial.println(\" seconds.\");\n    \n    Serial.println(\"Speed \");\n    Serial.print( (sent/1000.0F) / (stop/1000.0F), 2);\n    Serial.println(\" KB/s.\\r\\n\");\n  }\n}\n\n/**************************************************************************/\n/*!\n    @brief  Checks for user input (via the Serial Monitor)\n*/\n/**************************************************************************/\nvoid getUserInput(char buffer[], uint8_t maxSize)\n{\n  memset(buffer, 0, maxSize);\n  while( Serial.available() == 0 ) {\n    delay(1);\n  }\n\n  uint8_t count=0;\n\n  do\n  {\n    count += Serial.readBytes(buffer+count, maxSize);\n    delay(2);\n  } while( (count < maxSize) && !(Serial.available() == 0) );\n}\n"
  },
  {
    "path": "examples/uribeacon/BluefruitConfig.h",
    "content": "// COMMON SETTINGS\n// ----------------------------------------------------------------------------------------------\n// These settings are used in both SW UART, HW UART and SPI mode\n// ----------------------------------------------------------------------------------------------\n#define BUFSIZE                        128   // Size of the read buffer for incoming data\n#define VERBOSE_MODE                   true  // If set to 'true' enables debug output\n\n\n// SOFTWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins that will be used for 'SW' serial.\n// You should use this option if you are connecting the UART Friend to an UNO\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!\n#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!\n#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!\n#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused\n\n\n// HARDWARE UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the HW serial port you are using. Uncomment\n// this line if you are connecting the BLE to Leonardo/Micro or Flora\n// ----------------------------------------------------------------------------------------------\n#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1\n  #define BLUEFRUIT_HWSERIAL_NAME      Serial1\n#endif\n\n\n// SHARED UART SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following sets the optional Mode pin, its recommended but not required\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused\n\n\n// SHARED SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for HW and SW SPI communication.\n// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when\n// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules\n// that use SPI (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_CS               8\n#define BLUEFRUIT_SPI_IRQ              7\n#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused\n\n// SOFTWARE SPI SETTINGS\n// ----------------------------------------------------------------------------------------------\n// The following macros declare the pins to use for SW SPI communication.\n// This should be used with nRF51822 based Bluefruit LE modules that use SPI\n// (Bluefruit LE SPI Friend).\n// ----------------------------------------------------------------------------------------------\n#define BLUEFRUIT_SPI_SCK              13\n#define BLUEFRUIT_SPI_MISO             12\n#define BLUEFRUIT_SPI_MOSI             11\n"
  },
  {
    "path": "examples/uribeacon/uribeacon.ino",
    "content": "/*********************************************************************\n This is an example for our nRF51822 based Bluefruit LE modules\n\n Pick one up today in the adafruit shop!\n\n Adafruit invests time and resources providing this open source code,\n please support Adafruit and open-source hardware by purchasing\n products from Adafruit!\n\n MIT license, check LICENSE for more information\n All text above, and the splash screen below must be included in\n any redistribution\n*********************************************************************/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n#if SOFTWARE_SERIAL_AVAILABLE\n  #include <SoftwareSerial.h>\n#endif\n\n#include \"BluefruitConfig.h\"\n\n/*=========================================================================\n    APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE       Perform a factory reset when running this sketch\n\n                              Enabling this will put your Bluefruit LE module\n                              in a 'known good' state and clear any config\n                              data set in previous sketches or projects, so\n                              running this at least once is a good idea.\n\n                              When deploying your project, however, you will\n                              want to disable factory reset by setting this\n                              value to 0.  If you are making changes to your\n                              Bluefruit LE device via AT commands, and those\n                              changes aren't persisting across resets, this\n                              is the reason why.  Factory reset will erase\n                              the non-volatile memory where config data is\n                              stored, setting it back to factory default\n                              values.\n    -----------------------------------------------------------------------*/\n    #define FACTORYRESET_ENABLE         1\n    #define URL                         \"http://www.adafruit.com\"\n/*=========================================================================*/\n\n\n// Create the bluefruit object, either software serial...uncomment these lines\n/*\nSoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);\n\nAdafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,\n                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);\n*/\n\n/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */\n// Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);\n\n/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */\nAdafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */\n//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,\n//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,\n//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);\n\n// A small helper\nvoid error(const __FlashStringHelper*err) {\n  Serial.println(err);\n  while (1);\n}\n\n/**************************************************************************/\n/*!\n    @brief  Sets up the HW an the BLE module (this function is called\n            automatically on startup)\n*/\n/**************************************************************************/\nvoid setup(void)\n{\n  while (!Serial);  // required for Flora & Micro\n  delay(500);\n\n  Serial.begin(115200);\n  Serial.println(F(\"Adafruit Bluefruit UriBeacon Example\"));\n  Serial.println(F(\"------------------------------------\"));\n\n  /* Initialise the module */\n  Serial.print(F(\"Initialising the Bluefruit LE module: \"));\n\n  if ( !ble.begin(VERBOSE_MODE) )\n  {\n    error(F(\"Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?\"));\n  }\n  Serial.println( F(\"OK!\") );\n\n  if ( FACTORYRESET_ENABLE )\n  {\n    /* Perform a factory reset to make sure everything is in a known state */\n    Serial.println(F(\"Performing a factory reset: \"));\n    if ( ! ble.factoryReset() ){\n      error(F(\"Couldn't factory reset\"));\n    }\n  }\n\n  /* Disable command echo from Bluefruit */\n  ble.echo(false);\n\n  Serial.println(\"Requesting Bluefruit info:\");\n  /* Print Bluefruit information */\n  ble.info();\n\n  // Prompt user to migrate to EddyStone\n  Serial.println(F(\"Please consider to migrate to EddyStone since Google has retired uribeacon\"));\n\n  /* Set EddyStone URL beacon data */\n  Serial.println(F(\"Setting uri beacon to Adafruit website: \"));\n\n  // Older firmware use AT+BLEURIBEACON command\n  if (! ble.sendCommandCheckOK(F( \"AT+BLEURIBEACON=\" URL ))) {\n    error(F(\"Couldnt set, is URL too long !?\"));\n  }\n\n  Serial.println(F(\"**************************************************\"));\n  Serial.println(F(\"Please use Google Physical Web application to test\"));\n  Serial.println(F(\"**************************************************\"));\n}\n\n/**************************************************************************/\n/*!\n    @brief  Constantly poll for new command or response data\n*/\n/**************************************************************************/\nvoid loop(void)\n{\n\n}\n\n/**************************************************************************/\n/*!\n    @brief  Checks for user input (via the Serial Monitor)\n*/\n/**************************************************************************/\nvoid getUserInput(char buffer[], uint8_t maxSize)\n{\n  memset(buffer, 0, maxSize);\n  while( Serial.available() == 0 ) {\n    delay(1);\n  }\n\n  uint8_t count=0;\n\n  do\n  {\n    count += Serial.readBytes(buffer+count, maxSize);\n    delay(2);\n  } while( (count < maxSize) && !(Serial.available() == 0) );\n}\n"
  },
  {
    "path": "keywords.txt",
    "content": "#######################################\r\n# Syntax Coloring Map For Bluefruit\r\n#######################################\r\n\r\n#######################################\r\n# Datatypes (KEYWORD1)\r\n#######################################\r\n\r\nAdafruit_BLE\tKEYWORD1\r\nAdafruit_BluefruitLE_SPI\tKEYWORD1\r\nAdafruit_BluefruitLE_UART\tKEYWORD1\r\nAdafruit_ATParser\tKEYWORD1\r\n\r\nAdafruit_BLEBattery\tKEYWORD1\r\nAdafruit_BLEEddystone\tKEYWORD1\r\nAdafruit_BLEGatt\tKEYWORD1\r\nAdafruit_BLEMIDI\tKEYWORD1\r\n\r\nAdafruit_FIFO\tKEYWORD1\r\nTimeoutTimer\tKEYWORD1\r\n\r\n#######################################\r\n# Adafruit_BLE\r\n#######################################\r\nreset\tKEYWORD2\r\nfactoryReset\tKEYWORD2\r\ninfo\tKEYWORD2\r\necho\tKEYWORD2\r\nisConnected\tKEYWORD2\r\nisVersionAtLeast\tKEYWORD2\r\ndisconnect\tKEYWORD2\r\n\r\nsetAdvData\tKEYWORD2\r\nwriteNVM\tKEYWORD2\r\nreadNVM\tKEYWORD2\r\nupdate\tKEYWORD2\r\nwriteBLEUart\tKEYWORD2\r\nreadBLEUart\tKEYWORD2\r\nsetDisconnectCallback\tKEYWORD2\r\nsetConnectCallback\tKEYWORD2\r\nsetBleUartRxCallback\tKEYWORD2\r\nsetBleMidiRxCallback\tKEYWORD2\r\nsetBleGattRxCallback\tKEYWORD2\r\n\r\nsendCommandCheckOK\tKEYWORD2\r\nsendCommandWithIntReply\tKEYWORD2\r\n\r\n#######################################\r\n# Adafruit_ATParser\r\n#######################################\r\natcommand\tKEYWORD2\r\natcommandIntReply\tKEYWORD2\r\natcommand_full\tKEYWORD2\r\ngetMode\tKEYWORD2\r\nsetMode\tKEYWORD2\r\nverbose\tKEYWORD2\r\nreadline\tKEYWORD2\r\nreadline_parseInt\tKEYWORD2\r\nwaitForOK\tKEYWORD2\r\nreadraw\tKEYWORD2\r\nprintByteArray\tKEYWORD2\r\n\r\n#######################################\r\n# Adafruit_BLEBattery\r\n#######################################\r\nupdate\tKEYWORD2\r\n\r\n#######################################\r\n# Adafruit_BLEEddystone\r\n#######################################\r\nsetURL\tKEYWORD2\r\nstartBroadcast\tKEYWORD2\r\nstopBroadcast\tKEYWORD2\r\nstartConfigMode\tKEYWORD2\r\n\r\n#######################################\r\n# Adafruit_BLEGatt\r\n#######################################\r\naddService\tKEYWORD2\r\naddCharacteristic\tKEYWORD2\r\ngetChar\tKEYWORD2\r\ngetCharInt8\tKEYWORD2\r\ngetCharInt16\tKEYWORD2\r\ngetCharInt32\tKEYWORD2\r\ngetCharStr\tKEYWORD2\r\nsetChar\tKEYWORD2\r\n\r\n# Constants (LITERAL1)\r\nGATT_CHARS_PROPERTIES_BROADCAST\tLITERAL1\r\nGATT_CHARS_PROPERTIES_READ\tLITERAL1\r\nGATT_CHARS_PROPERTIES_WRITE_WO_RESP\tLITERAL1\r\nGATT_CHARS_PROPERTIES_WRITE\tLITERAL1\r\nGATT_CHARS_PROPERTIES_NOTIFY\tLITERAL1\r\nGATT_CHARS_PROPERTIES_INDICATE\tLITERAL1\r\n\r\n#######################################\r\n# Adafruit_BLEMIDI\r\n#######################################\r\nsend\tKEYWORD2\r\nsend_n\tKEYWORD2\r\nsetRxCallback\tKEYWORD2\r\n\r\n#######################################\r\n# Constants (LITERAL1)\r\n#######################################\r\nBLUEFRUIT_MODE_COMMAND\tLITERAL1\r\nBLUEFRUIT_MODE_DATA\tLITERAL1\r\n"
  },
  {
    "path": "library.properties",
    "content": "name=Adafruit BluefruitLE nRF51\nversion=1.10.0\nauthor=Adafruit\nmaintainer=Adafruit <info@adafruit.com>\nsentence=Arduino library for nRF51822-based Adafruit Bluefruit LE modules\nparagraph=Arduino library for nRF51822-based Adafruit Bluefruit LE modules\ncategory=Communication\nurl=https://github.com/adafruit/Adafruit_BluefruitLE_nRF51\narchitectures=*\n"
  },
  {
    "path": "utility/Adafruit_FIFO.cpp",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_FIFO.cpp\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2015, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#include \"Adafruit_FIFO.h\"\n#include <string.h>\n\n/******************************************************************************/\n/*!\n    @brief  Constructor\n\n    @param[in] buffer\n               Memory location to store data\n    @param[in] depth\n               Maximum number of items can be hold in buffer\n    @param[in] item_size\n               Number of bytes of each item\n    @param[in] overwrite\n               Should the buffer is overwitten to the first item when it is full\n*/\n/******************************************************************************/\nAdafruit_FIFO::Adafruit_FIFO(void* buffer, uint16_t depth, uint8_t item_size, bool overwrite)\n{\n  m_buffer       = (uint8_t*) buffer;\n  m_depth        = depth;\n  m_item_size    = item_size;\n  m_overwritable = overwrite;\n\n  m_count = m_wr_idx = m_rd_idx = 0;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Clear the FIFO\n*/\n/******************************************************************************/\nvoid Adafruit_FIFO::clear(void)\n{\n  m_rd_idx = m_wr_idx = m_count = 0;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Write an item to the FIFO\n\n    @param[in] item\n               Memory address of the item\n*/\n/******************************************************************************/\nbool Adafruit_FIFO::write(void const* item)\n{\n  if ( full() && !m_overwritable ) return false;\n\n  memcpy( m_buffer + (m_wr_idx * m_item_size),\n          item,\n          m_item_size);\n\n  m_wr_idx = (m_wr_idx + 1) % m_depth;\n\n  if ( full() )\n  {\n    m_rd_idx = m_wr_idx; // keep the full state (rd == wr && len = size)\n  }\n  else\n  {\n    m_count++;\n  }\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Write array of items to the FIFO\n\n    @param[in] data\n               Memory address of the item's array\n    @param[in] n\n               Number of items to write\n\n    @return    Number of written items\n*/\n/******************************************************************************/\nuint16_t Adafruit_FIFO::write_n(void const * data, uint16_t n)\n{\n  if ( n == 0 ) return 0;\n\n  uint8_t* buf = (uint8_t*) data;\n\n  uint16_t len = 0;\n  while( (len < n) && write(buf) )\n  {\n    len++;\n    buf += m_item_size;\n  }\n\n  return len;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Read an item from FIFO\n\n    @param[in] buffer\n               Memory address to store item\n*/\n/******************************************************************************/\nbool Adafruit_FIFO::read(void* buffer)\n{\n  if( empty() ) return false;\n\n  memcpy(buffer,\n         m_buffer + (m_rd_idx * m_item_size),\n         m_item_size);\n  m_rd_idx = (m_rd_idx + 1) % m_depth;\n  m_count--;\n\n  return true;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Read multiple items to an array\n\n    @param[in] buffer\n               Memory address of the item's array\n    @param[in] n\n               Number of items to read\n\n    @return    Number of read items\n*/\n/******************************************************************************/\n\nuint16_t Adafruit_FIFO::read_n (void * buffer, uint16_t n)\n{\n  if( n == 0 ) return 0;\n\n  uint8_t* buf = (uint8_t*) buffer;\n\n  uint16_t len = 0;\n  while( (len < n) && read(buf) )\n  {\n    len++;\n    buf += m_item_size;\n  }\n\n  return len;\n}\n\n/******************************************************************************/\n/*!\n    @brief  Read an item without removing it from the FIFO\n\n    @param[in] buffer\n               Memory address to store item\n*/\n/******************************************************************************/\nbool Adafruit_FIFO::peek(void* buffer)\n{\n  if( empty() ) return false;\n\n  memcpy(buffer,\n         m_buffer + (m_rd_idx * m_item_size),\n         m_item_size);\n\n  return true;\n}\n\n\n/******************************************************************************/\n/*!\n    @brief  Read an item without removing it from the FIFO at the specific index\n\n    @param[in] position\n               Position to read from in the FIFO buffer\n\n    @param[in] buffer\n               Memory address to store item\n*/\n/******************************************************************************/\nbool Adafruit_FIFO::peekAt(uint16_t position, void * p_buffer)\n{\n  if( empty() || (position >= m_count) ) return false;\n\n  uint16_t index = (m_rd_idx + position) % m_depth; // rd_idx is position=0\n  memcpy(p_buffer,\n         m_buffer + (index * m_item_size),\n         m_item_size);\n\n  return true;\n}\n\n"
  },
  {
    "path": "utility/Adafruit_FIFO.h",
    "content": "/**************************************************************************/\n/*!\n    @file     Adafruit_FIFO.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2015, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#ifndef _Adafruit_FIFO_H_\n#define _Adafruit_FIFO_H_\n\n#include <stdint.h>\n#include <stdbool.h>\n\nclass Adafruit_FIFO\n{\n  private:\n             uint8_t* m_buffer       ; ///< buffer pointer\n             uint16_t m_depth        ; ///< max items\n             uint8_t  m_item_size    ; ///< size of each item\n             bool     m_overwritable ;\n    volatile uint16_t m_count        ; ///< number of items in queue\n    volatile uint16_t m_wr_idx       ; ///< write pointer\n    volatile uint16_t m_rd_idx       ; ///< read pointer\n\n  public:\n    // Constructor\n    Adafruit_FIFO(void* buffer, uint16_t depth, uint8_t item_size, bool overwrite);\n\n    void clear(void);\n    bool peek(void* buffer);\n    bool peekAt(uint16_t position, void * p_buffer);\n\n    bool write(void const* item);\n    uint16_t write_n(void const * data, uint16_t n);\n\n    bool read(void* buffer);\n    uint16_t read_n (void * buffer, uint16_t n);\n\n    inline bool     empty(void)     { return m_count == 0; }\n    inline bool     full(void)      { return m_count == m_depth; }\n    inline uint16_t count(void)     { return m_count; }\n    inline uint16_t remaining(void) { return m_depth - m_count; }\n};\n\n#endif /* _Adafruit_FIFO_H_ */\n"
  },
  {
    "path": "utility/TimeoutTimer.h",
    "content": "/**************************************************************************/\n/*!\n    @file     TimeoutTimer.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2014, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n/** \n *  @{\n */\n\n#ifndef _TIMEOUT_TIMER_H_\n#define _TIMEOUT_TIMER_H_\n\nclass TimeoutTimer\n{\n  private:\n    uint32_t start;\n    uint32_t interval;\n\n  public:\n    TimeoutTimer()              { start = millis(); interval = 0; }\n    TimeoutTimer(uint32_t msec) { set(msec); }\n\n    void set(uint32_t msec)     { start = millis(); interval = msec; }\n    bool expired(void)  const   { return (millis() - start) >= interval; }\n    void restart(void)          { start = millis(); }\n    void reset(void)            { start += interval; } // used for periodic invoke to prevent drift\n};\n\n#endif /* _TIMEOUT_TIMER_H_ */\n\n/** @} */\n"
  },
  {
    "path": "utility/common_header.h",
    "content": "/**************************************************************************/\n/*!\n    @file     common_header.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2016, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/**************************************************************************/\n\n#ifndef _COMMON_HEADER_H_\n#define _COMMON_HEADER_H_\n\n#include <stdint.h>\n#include <stdbool.h>\n\n//--------------------------------------------------------------------+\n// COMPILER\n//--------------------------------------------------------------------+\n#define STRING_(x)                  #x                   // stringify without expand\n#define XSTRING_(x)                 STRING_(x)           // expand then stringify\n#define STRING_CONCAT_(a, b)        a##b                 // concat without expand\n#define XSTRING_CONCAT_(a, b)       STRING_CONCAT_(a, b) // expand then concat\n\n#define ATTR_PACKED               __attribute__ ((packed))\n\n//--------------------------------------------------------------------+\n// ASSERT & VERIFY\n//--------------------------------------------------------------------+\n//#define ASSERT(condition, err)    if ( !(condition) ) return err;\n\n//------------- Compile-time Assert -------------//\n#if defined __COUNTER__ && __COUNTER__ != __COUNTER__\n  #define _ASSERT_COUNTER __COUNTER__\n#else\n  #define _ASSERT_COUNTER __LINE__\n#endif\n\n#define ASSERT_STATIC_(const_expr) enum { XSTRING_CONCAT_(static_assert_, _ASSERT_COUNTER) = 1/(!!(const_expr)) }\n\n\n#define VERIFY_(condition)                if ( !(condition) ) return false;\n#define VERIFY_RETURN_(condition, error)  if ( !(condition) ) return error;\n\n//--------------------------------------------------------------------+\n// INLINE FUNCTION\n//--------------------------------------------------------------------+\nstatic inline bool is_within(uint32_t lower, uint32_t value, uint32_t upper)\n{\n  return (lower <= value) && (value <= upper);\n}\n\n#endif /* _COMMON_HEADER_H_ */\n"
  },
  {
    "path": "utility/errors.h",
    "content": "/******************************************************************************/\n/*!\n    @file     errors.h\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2014, Adafruit Industries (adafruit.com)\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/******************************************************************************/\n#ifndef _ERRORS_H_\n#define _ERRORS_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/******************************************************************************/\n/*!\n    @brief  Standard error codes used throughout this codebase\n*/\n/******************************************************************************/\ntypedef enum\n{\n  /*=======================================================================\n    CUSTOM GLOBAL ERRORS                                   0x8000 .. 0x801F\n    -----------------------------------------------------------------------\n    Custom global errors (not defined by Nordic)\n    -----------------------------------------------------------------------*/\n    ERROR_INITFAILED                              = 0x8001,   ///< Function or driver initialisation failed\n    ERROR_NOT_INITIALISED                         = 0x8002,   ///< Attempted to call a function in an unitialised device/driver\n    ERROR_I2C_XFER_FAILED                         = 0x8003,   ///< I2C transfer failure\n  /*=======================================================================*/\n\n\n  /*=======================================================================\n    SIMPLE BINARY PROTOCOL ERRORS                          0x8020 .. 0x803F\n    -----------------------------------------------------------------------\n    Errors relating to the simple binary protocol\n    -----------------------------------------------------------------------*/\n    ERROR_SDEP_INVALIDMSGTYPE                     = 0x8021,    ///< Unexpected msg type encountered\n    ERROR_SDEP_INVALIDCOMMANDID                   = 0x8022,    ///< Unknown or out of range command ID\n    ERROR_SDEP_INVALIDPAYLOAD                     = 0x8023,    ///< Message payload has a problem (invalid len, etc.)\n  /*=======================================================================*/\n\n\n  /*=======================================================================\n    COMMAND LINE INTERFACE ERRORS                          0x8040 .. 0x805F\n    -----------------------------------------------------------------------\n    Errors relating to the simple binary protocol\n    -----------------------------------------------------------------------*/\n    ERROR_CLI_UNKNOWN_COMMAND                     = 0x8041,    ///< Unknown Command entered\n    ERROR_CLI_TOO_FEW_ARGUMENTS                   = 0x8042,    ///< Too Few Arguments\n    ERROR_CLI_TOO_MANY_ARGUMENTS                  = 0x8043,    ///< Too Few Arguments\n  /*=======================================================================*/\n\n  /*=======================================================================\n    AT PARSER ERRORS                                       0x8060 .. 0x807F\n    -----------------------------------------------------------------------\n    Errors relating to AT Command\n    -----------------------------------------------------------------------*/\n    ERROR_AT_INVALID_INPUT                        = 0x8060,\n    ERROR_AT_UNKNOWN_COMMAND                      = 0x8061,\n    ERROR_AT_INVALID_PARAMETER                    = 0x8062,\n  /*=======================================================================*/\n\n  /*=======================================================================\n    NVM ERRORS                                              0x8080 .. 0x809F\n    -----------------------------------------------------------------------\n    Errors relating to the NVM\n    -----------------------------------------------------------------------*/\n    ERROR_NVM_BUSY                                = 0x8060,\n  /*=======================================================================*/\n\n  /*=======================================================================\n    OS Abstraction Layer                                   0x80A0 .. 0x80BF\n    -----------------------------------------------------------------------\n    Errors relating to the NVM\n    -----------------------------------------------------------------------*/\n    ERROR_OSAL_WAITING                            = 0x80A0,\n  /*=======================================================================*/\n\n  /*=======================================================================\n    NORDIC GLOBAL ERRORS                                   0x0000 .. 0x00FF\n    -----------------------------------------------------------------------\n    Errors mapped from nrf_error.h\n    -----------------------------------------------------------------------*/\n    ERROR_NONE                                    = 0x0000,   ///< Successful command\n    ERROR_SVC_HANDLER_MISSING                     = 0x0001,   ///< SVC handler is missing\n    ERROR_SOFTDEVICE_NOT_ENABLED                  = 0x0002,   ///< SoftDevice has not been enabled\n    ERROR_INTERNAL                                = 0x0003,   ///< Internal Error\n    ERROR_NO_MEM                                  = 0x0004,   ///< No Memory for operation\n    ERROR_NOT_FOUND                               = 0x0005,   ///< Not found\n    ERROR_NOT_SUPPORTED                           = 0x0006,   ///< Not supported\n    ERROR_INVALID_PARAM                           = 0x0007,   ///< Invalid Parameter\n    ERROR_INVALID_STATE                           = 0x0008,   ///< Invalid state, operation disallowed in this state\n    ERROR_INVALID_LENGTH                          = 0x0009,   ///< Invalid Length\n    ERROR_INVALID_FLAGS                           = 0x000A,   ///< Invalid Flags\n    ERROR_INVALID_DATA                            = 0x000B,   ///< Invalid Data\n    ERROR_DATA_SIZE                               = 0x000C,   ///< Data size exceeds limit\n    ERROR_TIMEOUT                                 = 0x000D,   ///< Operation timed out\n    ERROR_NULL                                    = 0x000E,   ///< Null Pointer\n    ERROR_FORBIDDEN                               = 0x000F,   ///< Forbidden Operation\n    ERROR_INVALID_ADDR                            = 0x0010,   ///< Bad Memory Address\n    ERROR_BUSY                                    = 0x0011,   ///< Busy\n  /*=======================================================================*/\n\n\n  /*=======================================================================\n    NORDIC SDM ERRORS                                      0x1000 .. 0x1FFF\n    -----------------------------------------------------------------------\n    Errors based on Nordic's SDM nrf_error_sdm.h\n    -----------------------------------------------------------------------*/\n    ERROR_SDM_LFCLK_SOURCE_UNKNOWN                = 0x1000,   ///< Unknown lfclk source\n    ERROR_SDM_INCORRECT_INTERRUPT_CONFIGURATION   = 0x1001,   ///< Incorrect interrupt configuration (can be caused by using illegal priority levels, or having enabled SoftDevice interrupts)\n    ERROR_SDM_INCORRECT_CLENR0                    = 0x1002,   ///< Incorrect CLENR0 (can be caused by erronous SoftDevice flashing)\n  /*=======================================================================*/\n\n\n  /*=======================================================================\n    NORDIC SOC ERRORS                                      0x2000 .. 0x2FFF\n    -----------------------------------------------------------------------\n    Errors based on Nordic's nrf_error_soc.h\n    -----------------------------------------------------------------------*/\n    /* Mutex Errors */\n    ERROR_SOC_MUTEX_ALREADY_TAKEN                 = 0x2000,   ///< Mutex already taken\n\n    /* NVIC errors */\n    ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE        = 0x2001,   ///< NVIC interrupt not available\n    ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED = 0x2002,   ///< NVIC interrupt priority not allowed\n    ERROR_SOC_NVIC_SHOULD_NOT_RETURN              = 0x2003,   ///< NVIC should not return\n\n    /* Power errors */\n    ERROR_SOC_POWER_MODE_UNKNOWN                  = 0x2004,   ///< Power mode unknown\n    ERROR_SOC_POWER_POF_THRESHOLD_UNKNOWN         = 0x2005,   ///< Power POF threshold unknown\n    ERROR_SOC_POWER_OFF_SHOULD_NOT_RETURN         = 0x2006,   ///< Power off should not return\n\n    /* Rand errors */\n    ERROR_SOC_RAND_NOT_ENOUGH_VALUES              = 0x2007,   ///< RAND not enough values\n\n    /* PPI errors */\n    ERROR_SOC_PPI_INVALID_CHANNEL                 = 0x2008,   ///< Invalid PPI Channel\n    ERROR_SOC_PPI_INVALID_GROUP                   = 0x2009,   ///< Invalid PPI Group\n  /*=======================================================================*/\n\n\n  /*=======================================================================\n    NORDIC BLE ERRORS                                      0x3000 .. 0x3FFF\n    -----------------------------------------------------------------------\n    Errors based on Nordic's ble_err.h\n    -----------------------------------------------------------------------*/\n    ERROR_BLE_NOT_ENABLED                         = 0x3001,\n    ERROR_BLE_INVALID_CONN_HANDLE                 = 0x3002,   ///< Invalid connection handle.\n    ERROR_BLE_INVALID_ATTR_HANDLE                 = 0x3003,   ///< Invalid attribute handle.\n    ERROR_BLE_NO_TX_BUFFERS                       = 0x3004,   ///< Buffer capacity exceeded.\n\n    /* L2CAP */\n    ERROR_BLE_L2CAP_CID_IN_USE                    = 0x3100,   ///< CID already in use.\n\n    /* GAP */\n    ERROR_BLE_GAP_UUID_LIST_MISMATCH              = 0x3200,   ///< UUID list does not contain an integral number of UUIDs.\n    ERROR_BLE_GAP_DISCOVERABLE_WITH_WHITELIST     = 0x3201,   ///< Use of Whitelist not permitted with discoverable advertising.\n    ERROR_BLE_GAP_INVALID_BLE_ADDR                = 0x3202,   ///< The upper two bits of the address do not correspond to the specified address type.\n\n    /* GATTC */\n    ERROR_BLE_GATTC_PROC_NOT_PERMITTED            = 0x3300,\n\n    /* GATTS */\n    ERROR_BLEGATTS_INVALID_ATTR_TYPE              = 0x3400,   ///< Invalid attribute type.\n    ERROR_BLEGATTS_SYS_ATTR_MISSING               = 0x3401,   ///< System Attributes missing.\n  /*=======================================================================*/\n} err_t;\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* _ERROR_H_ */\n"
  },
  {
    "path": "utility/sdep.h",
    "content": "/******************************************************************************/\n/*!\n    @file     sdep.h\n    @author   hathach\n\n    @section LICENSE\n\n    Software License Agreement (BSD License)\n\n    Copyright (c) 2013, K. Townsend (microBuilder.eu)\n    Copyright (c) 2014, Adafruit Industries (adafruit.com)\n\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n    1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n    3. Neither the name of the copyright holders nor the\n    names of its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n    THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/******************************************************************************/\n#ifndef _SDEP_H_\n#define _SDEP_H_\n\n#include \"common_header.h\"\n\n#define SDEP_MAX_PACKETSIZE       16 // Maximum payload per packet\n\n/******************************************************************************/\n/*!\n    This enumeration is used to make sure that each command has a unique\n    ID, and is used to create the command lookup table enum further down\n*/\n/******************************************************************************/\ntypedef enum\n{\n  SDEP_CMDTYPE_INITIALIZE     = 0xBEEF,   /**< Controls the on board LED(s) */\n  SDEP_CMDTYPE_AT_WRAPPER     = 0x0A00,\n  SDEP_CMDTYPE_BLE_UARTTX     = 0x0A01,\n  SDEP_CMDTYPE_BLE_UARTRX     = 0x0A02,\n} sdepCmdType_t;\n\n/******************************************************************************/\n/*!\n    The first byte of every transfer defines the message type\n*/\n/******************************************************************************/\ntypedef enum\n{\n  SDEP_MSGTYPE_COMMAND          = 0x10,\n  SDEP_MSGTYPE_RESPONSE         = 0x20,\n  SDEP_MSGTYPE_ALERT            = 0x40,\n  SDEP_MSGTYPE_ERROR            = 0x80\n} sdepMsgType_t;\n\n/******************************************************************************/\n/*!\n    4-byte header for SDEP messages\n*/\n/******************************************************************************/\ntypedef struct ATTR_PACKED {\n  uint8_t msg_type;           // 8-bit message type indicator (sdepMsgType_t)\n\n  union\n  {\n    uint16_t cmd_id;          // 16-bit command ID\n    struct\n    {\n      uint8_t cmd_id_low;\n      uint8_t cmd_id_high;\n    };\n  };\n\n  struct ATTR_PACKED\n  {\n    uint8_t length    : 7;    // Payload length (for this packet)\n    uint8_t more_data : 1;    // 'more' bit for multiple packet transfers\n  };\n} sdepMsgHeader_t;\n\n/******************************************************************************/\n/*!\n    SDEP command message\n*/\n/******************************************************************************/\ntypedef struct ATTR_PACKED \n{\n  sdepMsgHeader_t header;\n  uint8_t payload[SDEP_MAX_PACKETSIZE];\n} sdepMsgCommand_t;\n\n/******************************************************************************/\n/*!\n    Response message struct (same as sdepMsgCommand_t)\n*/\n/******************************************************************************/\ntypedef sdepMsgCommand_t sdepMsgResponse_t;\n\n/******************************************************************************/\n/*!\n    Alert message struct\n*/\n/******************************************************************************/\ntypedef sdepMsgCommand_t sdepMsgAlert_t;\n\n#endif\n"
  }
]