Merge pull request #249 from adafruit/develop

Multiple peripheral connection support
This commit is contained in:
hathach authored and GitHub committed 2019-04-07 22:38:59 -07:00
commit 68400a7666
107 files changed
+7138 -6261

No files matched your search

+1 -44
View File
@@ -51,18 +51,6 @@ There are two methods that you can use to install this BSP. We highly recommend
- [SiLabs CP2104 driver](http://www.silabs.com/products/mcu/pages/usbtouartbridgevcpdrivers.aspx) is required for USB to Serial when using with Feather nRF52832
## Arduino BLE Application Support
This Arduino core contains basic BLE peripheral mode helper classes and an initial peripheral mode
API. These helper classes and APIs aim to make it easier to work with the Nordic SoftDevice that
contains Nordic's official Bluetooth Low Energy stack. You are also free to use the Nordic SDK to
generate your own example code, since all of the SoftDevice header files are included in your
projects by default.
To see a list of example sketches that make use of these helper classes, select the appropriate
board from the `Tools > Board` menu item, and then in the `Examples` menu look for the list of
examples sketched for the selected board.
## Bootloader Support
### Upgrade existing Bootloader
@@ -74,7 +62,7 @@ Bluefruit's Bootloader is self-upgradable, you could upgrade to the latest Bootl
- Select `Tools > Burn Bootloader`
- **WAIT** until the process complete ~30 seconds
Note: close the Serial Monitor before you click "Burn Bootloader". Afterwards, you shouldn't close the Arduino IDE, unplug the Feather, launch Serial Monitor etc ... to abort the process. There is a high chance it will brick your device! Do this with care and caution.
**Note: close the Serial Monitor before you click "Burn Bootloader". Afterwards, you shouldn't close the Arduino IDE, unplug the Feather, launch Serial Monitor etc ... to abort the process. There is a high chance it will brick your device! Do this with care and caution.**
### Burning new Bootloader
@@ -111,36 +99,6 @@ $ nrfjprog --program feather_nrf52832_bootloader.hex -f nrf52
$ nrfjprog --reset -f nrf52
```
## Misc Notes
#### nRF52DK Jlink Issue on macOS
If developing with the nRF52DK on macOS, there is a bug where only 64 bytes can be sent
over the USB CDC interface, which will prevent you from using the serial bootloader from
the Arduino IDE with an error like this:
```
Upgrading target on /dev/cu.usbmodem1421 with DFU package /private/var/folders/86/hb2vp14n5_5_yvdz_z8w9x_c0000gn/T/arduino_build_267869/nRF51Blinky.ino.zip. Flow control is disabled.
Timed out waiting for acknowledgement from device.
Failed to upgrade target. Error is: No data received on serial port. Not able to proceed.
Possible causes:
- bootloader, SoftDevice or application on target does not match the requirements in the DFU package.
- baud rate or flow control is not the same as in the target bootloader.
- target is not in DFU mode. If using the SDK examples, press Button 4 and RESET and release both to enter DFU mode.
```
To resolve this and enable 512 byte packets over USB serial, you must disable the
Mass Storage Device interface on the JLink-OB, which will free up two of the 512 byte
USB end points. (For details see [this article](https://wiki.segger.com/index.php?title=J-Link-OB_SAM3U).)
You can do so by running `JLinkExe` from the command line, and then entering the
`MSDDisable` command, and power cycling your nRF52DK. To re-enable MSD support, do the same
but enter the `MSDEnable` command.
## Credits
This core is based on [Arduino-nRF5](https://github.com/sandeepmistry/arduino-nRF5) by Sandeep Mistry,
@@ -154,4 +112,3 @@ The following libraries are used:
- [nrfx](https://github.com/NordicSemiconductor/nrfx) for peripherals driver
- [littlefs](https://github.com/ARMmbed/littlefs) for internal file system
- [fatfs by elm-chan](http://elm-chan.org/fsw/ff/00index_e.html) for external file system
- Segger Sysview for debugging.
+31 -31
View File
@@ -43,7 +43,7 @@ feather52832.build.extra_flags=-DNRF52832_XXAA -DNRF52 -DARDUINO_NRF52_FEATHER
# SofDevice Menu
# Ram & ROM size varies depending on SoftDevice (check linker script)
feather52832.menu.softdevice.s132v6=0.2.7 (s132 6.1.1)
feather52832.menu.softdevice.s132v6=0.2.9 (s132 6.1.1)
feather52832.menu.softdevice.s132v6.build.sd_flags=-DS132
feather52832.menu.softdevice.s132v6.build.sd_name=s132
feather52832.menu.softdevice.s132v6.build.sd_version=6.1.1
@@ -103,7 +103,7 @@ feather52840.build.extra_flags=-DNRF52840_XXAA -DARDUINO_NRF52_FEATHER
# SofDevice Menu
# Ram & ROM size varies depending on SoftDevice (check linker script)
feather52840.menu.softdevice.s140v6=0.2.7 (s140 6.1.1)
feather52840.menu.softdevice.s140v6=0.2.9 (s140 6.1.1)
feather52840.menu.softdevice.s140v6.build.sd_flags=-DS140
feather52840.menu.softdevice.s140v6.build.sd_name=s140
feather52840.menu.softdevice.s140v6.build.sd_version=6.1.1
@@ -125,44 +125,44 @@ feather52840.menu.debug.l3.build.debug_flags=-DCFG_DEBUG=3 -Os
#**********************************************
# Bluefruit Metro nRF52840 Express Board
#**********************************************
metro52840.name=Adafruit Bluefruit nRF52840 Metro Express
metro52840.bootloader.tool=bootburn
#metro52840.name=Adafruit Bluefruit nRF52840 Metro Express
#metro52840.bootloader.tool=bootburn
# Upload
metro52840.upload.tool=nrfutil
metro52840.upload.protocol=nrfutil
metro52840.upload.use_1200bps_touch=true
metro52840.upload.wait_for_upload_port=true
#metro52840.upload.tool=nrfutil
#metro52840.upload.protocol=nrfutil
#metro52840.upload.use_1200bps_touch=true
#metro52840.upload.wait_for_upload_port=true
# Build
metro52840.build.mcu=cortex-m4
metro52840.build.f_cpu=64000000
metro52840.build.board=NRF52840_METRO
metro52840.build.core=nRF5
metro52840.build.variant=metro_nrf52840_express
metro52840.build.extra_flags=-DNRF52840_XXAA
#metro52840.build.mcu=cortex-m4
#metro52840.build.f_cpu=64000000
#metro52840.build.board=NRF52840_METRO
#metro52840.build.core=nRF5
#metro52840.build.variant=metro_nrf52840_express
#metro52840.build.extra_flags=-DNRF52840_XXAA
# SofDevice Menu
# Ram & ROM size varies depending on SoftDevice (check linker script)
metro52840.menu.softdevice.s140v6=0.2.7 (s140 6.1.1)
metro52840.menu.softdevice.s140v6.build.sd_flags=-DS140
metro52840.menu.softdevice.s140v6.build.sd_name=s140
metro52840.menu.softdevice.s140v6.build.sd_version=6.1.1
metro52840.menu.softdevice.s140v6.build.sd_fwid=0x00B6
metro52840.menu.softdevice.s140v6.build.ldscript=nrf52840_s140_v6.ld
metro52840.menu.softdevice.s140v6.upload.maximum_size=815104
metro52840.menu.softdevice.s140v6.upload.maximum_data_size=248832
#metro52840.menu.softdevice.s140v6=0.2.9 (s140 6.1.1)
#metro52840.menu.softdevice.s140v6.build.sd_flags=-DS140
#metro52840.menu.softdevice.s140v6.build.sd_name=s140
#metro52840.menu.softdevice.s140v6.build.sd_version=6.1.1
#metro52840.menu.softdevice.s140v6.build.sd_fwid=0x00B6
#metro52840.menu.softdevice.s140v6.build.ldscript=nrf52840_s140_v6.ld
#metro52840.menu.softdevice.s140v6.upload.maximum_size=815104
#metro52840.menu.softdevice.s140v6.upload.maximum_data_size=248832
# Debug Menu
metro52840.menu.debug.l0=Level 0 (Release)
metro52840.menu.debug.l0.build.debug_flags=-DCFG_DEBUG=0 -Os
metro52840.menu.debug.l1=Level 1 (Error Message)
metro52840.menu.debug.l1.build.debug_flags=-DCFG_DEBUG=1 -Os
metro52840.menu.debug.l2=Level 2 (Full Debug)
metro52840.menu.debug.l2.build.debug_flags=-DCFG_DEBUG=2 -Os
metro52840.menu.debug.l3=Level 3 (Segger SystemView)
metro52840.menu.debug.l3.build.debug_flags=-DCFG_DEBUG=3 -Os
#metro52840.menu.debug.l0=Level 0 (Release)
#metro52840.menu.debug.l0.build.debug_flags=-DCFG_DEBUG=0 -Os
#metro52840.menu.debug.l1=Level 1 (Error Message)
#metro52840.menu.debug.l1.build.debug_flags=-DCFG_DEBUG=1 -Os
#metro52840.menu.debug.l2=Level 2 (Full Debug)
#metro52840.menu.debug.l2.build.debug_flags=-DCFG_DEBUG=2 -Os
#metro52840.menu.debug.l3=Level 3 (Segger SystemView)
#metro52840.menu.debug.l3.build.debug_flags=-DCFG_DEBUG=3 -Os
#**********************************************
# Nordic nRF52840DK (PCA10056)
@@ -187,7 +187,7 @@ pca10056.build.extra_flags=-DNRF52840_XXAA
# SofDevice Menu
# Ram & ROM size varies depending on SoftDevice (check linker script)
pca10056.menu.softdevice.s140v6=0.2.7 (s140 6.1.1)
pca10056.menu.softdevice.s140v6=0.2.9 (s140 6.1.1)
pca10056.menu.softdevice.s140v6.build.sd_flags=-DS140
pca10056.menu.softdevice.s140v6.build.sd_name=s140
pca10056.menu.softdevice.s140v6.build.sd_version=6.1.1
@@ -9457,7 +9457,7 @@
:10427000002104000D000D48002802D00C48AFF3C7
:10428000008000F02BF82000290000F0A7F800F0D3
:1042900011F800BF000008007C7F00200000000033
:1042A0000000000090300020945100200000000029
:1042A0000000000090300020045B002000000000AF
:1042B0000000000008B5074B044613B10021AFF31E
:1042C0000080054B1868836A03B19847204600F0C8
:1042D00031F800BF00000000A896070070B50D4E31
@@ -9520,7 +9520,7 @@
:1046600080030B6073E7022000F074F9012000F072
:1046700071F9C4E7AD30002064300020D51A5A002B
:1046800000A000400101060014100010AC960700C5
:104690007D43070000E100E084510020003000204D
:104690007D43070000E100E0F45A002000300020D4
:1046A00010B5FEB04FF4FA730DF1020101A8ADF898
:1046B0000230FFF761FE044640B9BDF80430102B0C
:1046C00007D0112B0CD001A800F02EFF20467EB0A1
@@ -9569,7 +9569,7 @@
:1049700018604FF47F4303F0103323F080539942C3
:1049800018BF13607047104B4FF4967018604FF4C7
:104990007F03F0E70C4B64221A6070470A4B40F625
:1049A000B83018600B46E6E7084B4FF4FA70186011
:1049A000B83018600B46E6E7084B40F6B8301860A0
:1049B000FF23E0E7054B4FF4967018604FF0FF13AC
:1049C000D9E700BFB0320020AC320020B432002062
:1049D00038B50C4C21684B1C054612D04FF4805260
@@ -10259,57 +10259,57 @@
:10749000108672B60C4A946801239CB993600B4B1A
:1074A0000B4DD3F8801029401160C3F88050D3F8F9
:1074B000841051604FF0FF32C3F88420047006B985
:1074C00062B670BD0370FAE78451002000E100E06D
:1074C00062B670BD0370FAE7F45A002000E100E0F4
:1074D000FC06FFBD10B5084B9A685AB150B9EFF3DE
:1074E000108172B6054A1C6814605C68546098602C
:1074F00001B962B610BD00BF8451002000E100E078
:1074F00001B962B610BD00BFF45A002000E100E0FF
:107500002AB113880144884204D1184670474FF6C7
:10751000FF73F7E75BBA10F8012B9BB25A40C2F336
:107520000313534083EA03331BB25A0102F4FF52A0
:1075300053409BB2E7E70000064B074A0020187053
:10754000064B1A600422C3E90120C3E90300C3E922
:1075500005007047494700204C470020BC500020E0
:10754000064B1A600822C3E90120C3E90300C3E91E
:1075500005007047494700204C4700202C5A002066
:107560000020704730B5F9B1124B5C6800220A6008
:10757000E4B1B0F5167F1BD8D8681D680130013C16
:10758000D86018695C604FF4177404FB00540C60F9
:10759000012101FA00F49969013000F00300214350
:10759000012101FA00F49969013000F0070021434C
:1075A00018619961104630BD0E20FCE70420FAE70F
:1075B0000C20F8E7BC500020F0B51D4B9A68A2B330
:1075C00059691E688D1A05F003052C464FF417778C
:1075B0000C20F8E72C5A0020F0B51D4B9A68A2B3B6
:1075C00059691E688D1A05F007052C464FF4177788
:1075D00007FB046C604512D1012101FA04F099699E
:1075E00041409961002021465E68D3F818C04FF0F1
:1075F000010E71440024164401F003010AE0013435
:1076000004F00304A142E3D11020EDE74AB1013AAE
:1075F000010E71440024164401F007010AE0013431
:1076000004F00704A142E3D11020EDE74AB1013AAA
:107610000D4601240EFA05F515EA0C0FA6EB02073C
:10762000F4D00CB1C3E90172F0BD0420FCE700BF47
:10763000BC500020064A13691268013B4FF41771D1
:1076400003F0030301FB0323C3F858020020704733
:10765000BC50002030B5C0B1B9B10E4BDA68B2B140
:107630002C5A0020064A13691268013B4FF4177157
:1076400003F0070301FB0323C3F85802002070472F
:107650002C5A002030B5C0B1B9B10E4BDA68B2B1C6
:10766000013ADA609A681D6801329A605A694FF4EB
:10767000177404FB025404600132D4F85802086005
:1076800002F003025A61002030BD0E20FCE7042006
:10769000FAE700BFBC5000203FB40C49086890B125
:1076800002F007025A61002030BD0E20FCE7042002
:10769000FAE700BF2C5A00203FB40C49086890B1AB
:1076A0000B4B1C687CB10B4A1568CDE902500023D6
:1076B0008DF804300B60136004AB13E90700234618
:1076C00004B030BC184704B030BC7047E050002014
:1076D000E4500020F0500020DC2810B509D0DD284F
:1076C00004B030BC184704B030BC7047505A00209A
:1076D000545A0020605A0020DC2810B509D0DD285B
:1076E00010D0C02816D1FFF7D7FF0E4B0E4A1A60F4
:1076F00010BD0E4A0E4B19681368581C1060C0224A
:10770000CA54F2E7094A0A4B19681368581C1060FA
:10771000DB22F5E7064B054A196813685C1C146008
:10772000C854E2E77430002065770700E05000207D
:10773000F0500020C02802BF014B024A1A60704777
:10772000C854E2E77430002065770700505A002003
:10773000605A0020C02802BF014B024A1A607047FD
:10774000743000206577070008B5DB2000F042FDAB
:1077500010B9024B024A1A6008BD00BF7830002001
:1077600001790700C02810B409D0DB280BD0094BE1
:10777000094A196813685C1C1460C85406E05DF877
:10778000044BFFF789BF054B054A1A605DF8044BAF
:10779000704700BFF0500020E050002074300020FF
:10779000704700BF605A0020505A0020743000200B
:1077A000D976070010B5064A064C12682368D05CEB
:1077B00000F010FD10B923680133236010BD00BF35
:1077C000F4500020E850002008B5C02000F002FD71
:1077C000645A0020585A002008B5C02000F002FD7D
:1077D00028B9034B1B6813B9024B034A1A6008BD52
:1077E000E850002078300020A57707007FB51C4CBA
:1077E000585A002078300020A57707007FB51C4C40
:1077F0001C4E1D4D226833689A4219D31B4B2B60D7
:10780000FFF7E2FF002829D1194B01221A70194B0A
:107810001B681BB38DF80420174A12680292226875
@@ -10317,37 +10317,37 @@
:10783000114B22681B689A5CC02A03D022689B5CAB
:10784000DB2B05D10D4B2A689A4204BF0C4B2B60F1
:107850002B689847042801D01128CBD104B070BD03
:10786000E8500020EC50002078300020C977070055
:10787000D8500020E4500020F4500020A5770700E5
:10786000585A00205C5A002078300020C977070061
:10787000485A0020545A0020645A0020A577070077
:10788000497707001FB50378032B044605D1164B33
:107890001B78022B01D1FFF7A9FF2378042B20D1FD
:1078A000124B1A6862B1124B1968124B1B6899424D
:1078B00006D2114B20791B6804B0BDE81040184770
:1078C0000E4B1B686BB10292094A022112680392A7
:1078D0008DF8041004AA12E9070004B0BDE81040B6
:1078E000184704B010BD00BFD8500020F050002051
:1078F000E0500020DC50002074300020E4500020D4
:1078E000184704B010BD00BF485A0020605A00205D
:1078F000505A00204C5A002074300020545A002066
:1079000010B50C4A0C4C12682368D35CC02B03D012
:10791000DB2B0CD0042009E0DC2000F05BFC28B954
:107920002368064A01332360054B1A6010BDDD2031
:10793000F3E700BFF4500020E8500020A5770700CF
:1079400078300020014B186000207047E450002080
:10793000F3E700BF645A0020585A0020A5770700DB
:1079400078300020014B186000207047545A002006
:10795000F0B50C4E377887B097B90B4D0FCD6C460C
:107960000FC495E80300072384E80300074A39465B
:10797000684600F0E1FB08B90123337007B0F0BDA1
:107980000020FBE7D85000202897070085780700E3
:10799000024B00221A7000F031BC00BFD85000200A
:107980000020FBE7485A0020289707008578070069
:10799000024B00221A7000F031BC00BF485A002090
:1079A00010B5C0B10D4B1A78012A04D0022A0CBFC1
:1079B0000420082010BD0A4A00241460094A1160FE
:1079C000094A106002221A70084B094A1A60FFF730
:1079D0000DFF2046EEE71020ECE700BFD850002056
:1079E000E8500020EC500020F450002078300020B7
:1079D0000DFF2046EEE71020ECE700BF485A0020DC
:1079E000585A00205C5A0020645A00207830002049
:1079F000C9770700054B064A1860064B1960064B0D
:107A000000201860054B1A60704700BFF05000203E
:107A100035770700DC500020E05000207430002053
:107A000000201860054B1A60704700BF605A0020C4
:107A1000357707004C5A0020505A0020743000205F
:107A2000064B07481B68DB00DBB200220370042111
:107A30005B4242708270C370FFF7B2BF20510020DA
:107A4000F850002070B52D4C2D4E02462546237867
:107A30005B4242708270C370FFF7B2BF905A002061
:107A4000685A002070B52D4C2D4E024625462378ED
:107A5000012B14D002D3022B20D070BD002AFCD100
:107A60002848FFF739FC08B1FFF702FD264B1B68D9
:107A7000002BF2D0254ABDE8704010781847012A43
@@ -10358,9 +10358,9 @@
:107AC000D7BC154A1368013303F007031360002382
:107AD0002370E1E70F4A1368052B0AD001331360C6
:107AE000074B19680A4B06311868BDE87040FFF76C
:107AF00057BF064B01221A70E9E700BF445100202E
:107B000038510020FC500020345100203C5100200E
:107B10004C5100204051002024510020F0B585B088
:107AF00057BF064B01221A70E9E700BFB45A0020B5
:107B0000A85A00206C5A0020A45A0020AC5A002029
:107B1000BC5A0020B05A0020945A0020F0B585B01D
:107B200004AB03E907009DF80400032878D8DFE8D8
:107B300000F00802A7AA012005B0BDE8F040FFF759
:107B400081BF039E564C032E40F28680029D6B78C7
@@ -10385,28 +10385,28 @@
:107C7000042802D02846FFF7FBFB0C480521CBE780
:107C800005210A48C8E70320CAE720684FF41671A7
:107C9000A3E720684FF41671BEE705B0F0BD00BF42
:107CA00048510020205100201C5100202851002064
:107CB00030510020245100203C5100200220FFF7C9
:107CA000B85A0020905A00208C5A0020985A002080
:107CB000A05A0020945A0020AC5A00200220FFF75E
:107CC000C1BE0000074B10B5044618600648FFF718
:107CD00039FE08B1FFF7CCFB002C0CBF0E200020B2
:107CE00010BD00BF305100201D7B0700184A194805
:107CE00010BD00BFA05A00201D7B0700184A19488C
:107CF000002310B51360184A1360184A1360184A1D
:107D00001370184A1370184B184A01211960184B48
:107D10001960184B1970FFF789FA08B1032010BDDC
:107D2000FFF70AFC0028FAD1FFF712FE0028F6D16F
:107D3000114C4FF416702146FFF714FC0028EDD1CA
:107D400020684FF41671BDE81040FFF753BE00BF26
:107D50004C5100204097070038510020405100202E
:107D60001C5100204451002020510020BD7C070000
:107D7000245100203C510020485100200C4A08B5F5
:107D5000BC5A002040970700A85A0020B05A0020C3
:107D60008C5A0020B45A0020905A0020BD7C070095
:107D7000945A0020AC5A0020B85A00200C4A08B58A
:107D8000002313600B4A1360FFF7EAFB08B1FFF70B
:107D90006FFBFFF7FDFD08B1FFF76AFB0648FFF731
:107DA0009BFA042802D10020FFF762FB002008BDE7
:107DB0003451002030510020FC50002037B50D46D2
:107DB000A45A0020A05A00206C5A002037B50D4666
:107DC000044698B191B10A4B19780022019259B139
:107DD00001A91A70FFF73EFC019B063B2B8023682C
:107DE0000433236003B030BD0420FBE70E20F9E725
:107DF0001C5100200438FFF7DFBB00000C4B1B7840
:107DF0008C5A00200438FFF7DFBB00000C4B1B78C7
:107E0000062B10D10B4B1B681A070CD10A4B1868B4
:107E100000F0F003302B08D000F0E000A0F14003A8
:107E2000584258417047002070470120704700BFFA
@@ -10457,8 +10457,8 @@
:1080F000104B1B686846984702B010BD022C09D18E
:10810000C368094909488DF800400122019300F035
:10811000B1FAEDE7002CEFD102A8032300F8083DE7
:10812000044B1B68E7E700BF54510020803000205B
:108130005551002050510020F0B5204D06461746FD
:10812000044B1B68E7E700BFC45A002080300020E2
:10813000C55A0020C05A0020F0B5204D064617460B
:108140009C460FCD89B06C460FC495E80F0084E8BB
:108150000F0073690693337C8DF81CC0003318BF81
:1081600001238DF81430737C1548002B14BF0E23A7
@@ -10467,10 +10467,10 @@
:1081900069460E4A00F0A4F868B9336801330AD082
:1081A0009DF81D3013B9064800F026FB012208494E
:1081B000034800F05FFA09B0F0BD00BF4497070024
:1081C000803000205051002055510020CD80070004
:1081D00054510020074908B501220870064800F0F4
:1081C00080300020C05A0020C55A0020CD80070012
:1081D000C45A0020074908B501220870064800F07B
:1081E000C7F9112804D0002814BF0320002008BDBF
:1081F0000420FCE7565100208030002008B50248DA
:1081F0000420FCE7C65A00208030002008B5024861
:1082000000F038F9002008BD8030002000234350E2
:1082100082B043580193019B02B070470023435042
:1082200082B043580193019B02B070470A4610B5D3
@@ -10484,7 +10484,7 @@
:1082A000183510BDFFF7B2FF537ED168D0F818051E
:1082B000C854537E0133DBB25376F2E71FB5012376
:1082C0008DF80030054B8DF8080001916846D3E920
:1082D0000012904705B05DF804FB00BF5851002024
:1082D0000012904705B05DF804FB00BFC85A0020AB
:1082E000F8B50679604D7601AB190446D87E0028B2
:1082F00040F0B880487F18770868471C0BD00123EE
:1083000083404FF0A0400327C0F808350B6803F501
@@ -10509,7 +10509,7 @@
:108430000CC50B7D012BB3D18B68581C9AD003F56A
:10844000E0734FF0A04093E74FF48E71FFF7DEFE2C
:108450004FF4A2712068FFF7D9FE23680449C1E7F1
:108460000423CEE70820D6E758510020100302006D
:108460000423CEE70820D6E7C85A002010030200F4
:1084700080000200F0B50179394A036849015418B7
:10848000247F04B10024C3F8004553185B68B3B1DE
:108490000379046802EB43131B7F002B53D0314B4D
@@ -10525,7 +10525,7 @@
:1085300004F5E0740A441CBF022043F82400002321
:10854000D3765360F0BD094BAAE74FF0FF3CD3F858
:108550000845D3F81055C3F814C5C3F80CC5C3E7D4
:10856000585100201003020000E100E084020200E4
:10856000C85A00201003020000E100E0840202006B
:108570002DE9F04103793E4E5B010446F018007F7F
:1085800020B101F06040B0F1005F6DD13344987DBF
:1085900000286BD19A759960988294F804804FEA0C
@@ -10542,7 +10542,7 @@
:108640000020D8E72068D0F81C3123B9AB8A9BB250
:10865000B3F5807FF7D1AB8A9BB2B3F5807FE0D0D2
:108660004146FFF7E3FDDBE71020B4E71120B2E756
:10867000585100202DE9F84303795E4D5B010F4608
:10867000C85A00202DE9F84303795E4D5B010F468F
:10868000E91806460C7F2CB107F06041B1F1005F9C
:1086900040F0AB80E918486828B13168BCB14FF4AC
:1086A0000474C1F808432B44DC7DB4B1197E002961
@@ -10566,9 +10566,9 @@
:1087C000D5E7002BF1D1002CEFD14946FFF75FFD33
:1087D0007B7EFA7D9A42DDD82346E6E75A60C6E7FB
:1087E0004FF40173C0F80433C1E710206DE7032094
:1087F0006BE700BF5851002038B50379074C04EBF4
:1087F0006BE700BFC85A002038B50379074C04EB7B
:10880000431305461A7F42B99B7E33B9FFF72FFD0C
:108810002B7904EB43140123A37638BD5851002073
:108810002B7904EB43140123A37638BDC85A0020FA
:108820007FB5774C774A237F002B64D0D2F8246140
:10883000002E3FD04FF492711046FFF7EFFC022359
:108840008DF80030D2F88034C2F880340393D2F827
@@ -10599,7 +10599,7 @@
:1089D00001236B600B4B4FF40172C3F80823002393
:1089E000E375607EE168EEE74FF48E71FFF70EFCF1
:1089F000A17D0029B4D00248FFF729FCB0E700BFF1
:108A000058510020002000400028C3B2A8BF00F148
:108A0000C85A0020002000400028C3B2A8BF00F1CF
:108A100060424FEA501010B5BABF0D4A03F00F0480
:108A200002F561424FEA41114FEA8000C9B200F1FC
:108A30006040B4BF115582F8001300F5614003F0A7
@@ -10778,7 +10778,7 @@
:1095000020680144581882421960DDD11068526801
:109510005A6001441960D7E702D90C232B60D3E7C6
:10952000206821188A4204BF11685268626004BF33
:10953000091821605C60C7E738BD00BF7851002082
:10953000091821605C60C7E738BD00BFE85A002009
:1095400070B5CD1C25F0030508350C2D38BF0C2552
:10955000002D064601DBA94203D90C23336000200D
:1095600070BD00F07DF8214A1468214691B9204C65
@@ -10789,17 +10789,17 @@
:1095B00020F00700C31AD3D05A42E250D0E78C42C1
:1095C0004B6816BF636013600C46EBE70C464968B6
:1095D000CCE7C41C24F00304A04205D0211A304675
:1095E00000F02EF80130CFD02560DBE77851002065
:1095F0007C510020F8B5074614460E4621B91146A5
:1095E00000F02EF80130CFD02560DBE7E85A0020EC
:1095F000EC5A0020F8B5074614460E4621B911462C
:10960000BDE8F840FFF79CBF22B9FFF74BFF2546A6
:109610002846F8BD00F026F8A0420FD22146384671
:10962000FFF78EFF05460028F2D031462246FFF7AD
:10963000BEFB31463846FFF735FFE9E73546E7E739
:1096400038B5064C002305460846236000F012F8A2
:10965000431C02D1236803B12B6038BD9051002018
:10965000431C02D1236803B12B6038BD005B00209E
:109660007047704751F8043C181F002BBCBF0B58C3
:10967000C0187047044A05491368002B08BF0B4601
:1096800018441060184670478051002098510020FF
:109680001844106018467047F05A0020085B00200C
:10969000F8B500BFF8BC08BC9E467047F8B500BFDF
:1096A000F8BC08BC9E467047043000200010020041
:1096B0000338FDD870470000CC42002000000000B5
@@ -10811,7 +10811,7 @@
:10971000640000002044002023D1BCEA5F782315B8
:10972000DEEF12120000000008000000060000003A
:1097300000000000000000000000000000E0D70171
:10974000FC500020FFFFFFFFFFFFFFFFFFFFFFFFB9
:109740006C5A0020FFFFFFFFFFFFFFFFFFFFFFFF3F
:10975000FFFFFFFF000000000000000000E0D70155
:1097600007010000232D302B2000686C4C0065663B
:109770006745464700303132333435363738394162
+43 -1
View File
@@ -1,12 +1,54 @@
# Adafruit nRF52 Arduino Core Changelog
# 0.10.0
This release added multiple concurrent peripheral connections support, allow Bluefruit device to multiple central (phones/PC) simultaneously. It introduces new BLE class: BLEPeriph, BLEConnection, remove BLEGap, refactor/rename/move functions and callbacks.
- Fixed Servo detach issue
- Fixed pulseIn() compile issue: implement countPulseASM() using C instead of ASM
- Update bootloader to 0.2.9 which fixed OTA issue with latest BLE5 central such as iPhone X
- Added Metro nRF52840 Board support
- Fixed various warnings, thanks @brijohn
- Added ARDUINO_NRF52832_FEATHER for feather 832, ARDUINO_NRF52840_FEATHER for feather 840, ARDUINO_NRF52_FEATHER for both
- Fixed an memory leak with LFS, also extend to allow it to be used with SPI flash on other boards. Thanks @jeremypoulter
- Seperate OTA DFU service from Bluefruit.begin(), sketch must explicit add it if needed.
- Added multiple peripheral-role connections support, example sketch is at `examples/Peripherals/bleuart_multi`
- Introduce BLEPeriph class (Bluefruit.Periph) to mange peripheral role's connection
- setConnInterval(), setConnIntervalMS(), setConnSupervisionTimeout(), setConnSupervisionTimeoutMS()
- setConnectCallback(), setDisconnectCallback()
- Bluefruit
- Bluefruit.getPeerAddr() is replaced by BLEConnection's getPeerAddr()
- Bluefruit.connInterval() is replaced by BLEConnection's getConnInterval()
- Bluefruit.Central.disconnect() is repalced by Bluefruit.disconnect()
- Bluefruit.begin() return type is changed from err_t to bool
- Bluefruit.setConnectCallback()/setDisconnectCallback() are replaced by BLEPeriph's setConnectCallback()/setDisconnectCallback()
- Introduce BLEConnection class (Bluefruit.Connection(conn)) to mange both peripheral and central connections
- Added setRssiCallback(), monitorRssi(), getRssi(), stopRssi() for tracking rssi of a connection. `rssi_poll` and `rssi_callback` are added as example sketches
- Remove BLEGap, API functions are taken by Bluefruit, BLEPeriph, BLECentral, BLEConnection
- Gap.setAddr()/getAddr() are replaced by Bluefruit.setAddr()/getAddr()
- Gap.requestPairing() is replaced by Bluefruit.requestPairing(), conn_handle parameter is also added
- Most of other functions of BLEGap are replaced by BLEConnection's one
- BLECharacteristic
- Change callback signature's parameter from `BLECharacteristic&` to `BLECharacteristic*`
- conn_handle is added to all callbacks to support multiple peripheral's link
- Use AdaCallback thread for BLECharacteristic callbacks
- Support LONG WRITE a.k.a send more than MTU ( default = 20 bytes) per request. This fixed issue #91, #220
- Fixed read32(), thanks @techno
- Removed offset parameter in write callback signature
- BLEUart
- Added conn_handle to API and callbacks
- Removed auto flush TXD() with timer, user must call flushTXD() should bufferTXD() is enabled.
- BLEHidAdafruit
- Removed keyboardReport() variant with flat keycode parameters
- Added conn_handle parameter to keyboard led callback
# 0.9.3
- Correct bootloader version text in IDE to 0.2.6
- Fixed #173 bleuart return incorrect value when failed to send (PR #178 thanks Nenik)
- Added Client Battery support BLEClientBas
- Added BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST event support for Central
- Added Jlink as programmer to upload sketch #133
- Added Jlink as programmer to upload sketch #133. Though at least one serial DFU upload is needed to disable firmware crc checking
- Fixed issue with high speed uart baud ~ 1 Mbps (PR #158 thanks Ureloc)
- Add HardwardPWM removePin(), refactor hwpwm.ino sketch
- Fixed print float issue with precision > 10
+1 -1
View File
@@ -145,7 +145,7 @@ void GPIOTE_IRQHandler()
if (channelMap[ch] != -1 && callbacksInt[ch]) {
if ( callbackDeferred[ch] ) {
// Adafruit defer callback to non-isr if configured so
ada_callback_fromISR(NULL, callbacksInt[ch]);
ada_callback_fromISR(NULL, 0, callbacksInt[ch]);
}else{
callbacksInt[ch]();
}
+15 -15
View File
@@ -115,7 +115,7 @@
// DEBUG HELPER
//--------------------------------------------------------------------+
#if CFG_DEBUG == 2
#define malloc_named( name, size ) ({ printf("[malloc] %s : %d\r\n", name, size); malloc(size); })
#define malloc_named( name, size ) ({ ::printf("[malloc] %s : %d\r\n", name, size); malloc(size); })
#else
#define malloc_named( name, size ) malloc ( size )
#endif
@@ -140,38 +140,38 @@ const char* dbg_err_str(int32_t err_id); // TODO move to other place
#if CFG_DEBUG
#define PRINT_LOCATION() printf("%s: %d:\n", __PRETTY_FUNCTION__, __LINE__)
#define PRINT_MESS(x) printf("%s: %d: %s \n" , __FUNCTION__, __LINE__, (char*)(x))
#define PRTNT_HEAP() if (CFG_DEBUG == 3) printf("\n%s: %d: Heap free: %d\n", __FUNCTION__, __LINE__, util_heap_get_free_size())
#define PRINT_STR(x) printf("%s: %d: " #x " = %s\n" , __FUNCTION__, __LINE__, (char*)(x) )
#define PRINT_INT(x) printf("%s: %d: " #x " = %ld\n" , __FUNCTION__, __LINE__, (uint32_t) (x) )
#define PRINT_LOCATION() ::printf("%s: %d:\n", __PRETTY_FUNCTION__, __LINE__)
#define PRINT_MESS(x) ::printf("%s: %d: %s \n" , __FUNCTION__, __LINE__, (char*)(x))
#define PRTNT_HEAP() if (CFG_DEBUG == 3) ::printf("\n%s: %d: Heap free: %d\n", __FUNCTION__, __LINE__, util_heap_get_free_size())
#define PRINT_STR(x) ::printf("%s: %d: " #x " = %s\n" , __FUNCTION__, __LINE__, (char*)(x) )
#define PRINT_INT(x) ::printf("%s: %d: " #x " = %ld\n" , __FUNCTION__, __LINE__, (uint32_t) (x) )
#define PRINT_HEX(x) \
do {\
printf("%s: %d: " #x " = 0x", __PRETTY_FUNCTION__, __LINE__);\
::printf("%s: %d: " #x " = 0x", __PRETTY_FUNCTION__, __LINE__);\
char fmt[] = "%00X\n";\
fmt[2] += 2*sizeof(x); /* Hex with correct size */\
printf(fmt, (x) );\
::printf(fmt, (x) );\
}while(0)
#define PRINT_BUFFER(buf, n) \
do {\
uint8_t const* p8 = (uint8_t const*) (buf);\
printf(#buf ": ");\
for(uint32_t i=0; i<(n); i++) printf("%02x ", p8[i]);\
printf("\n");\
::printf(#buf ": ");\
for(uint32_t i=0; i<(n); i++) ::printf("%02x ", p8[i]);\
::printf("\n");\
}while(0)
#define ADALOG(tag, ...) \
do { \
if ( tag ) printf("[%-6s] ", tag);\
printf(__VA_ARGS__);\
printf("\n");\
if ( tag ) ::printf("[%-6s] ", tag);\
::printf(__VA_ARGS__);\
::printf("\n");\
}while(0)
#define ADALOG_BUFFER(_tag, _buf, _n) \
do {\
if ( _tag ) printf("%-6s: len = %d\n", _tag, _n);\
if ( _tag ) ::printf("%-6s: len = %d\n", _tag, _n);\
dbgDumpMemory(_buf, 1, _n, true);\
}while(0)
+22
View File
@@ -23,6 +23,28 @@
// See pulse_asm.S
extern unsigned long countPulseASM(const volatile uint32_t *port, uint32_t bit, uint32_t stateMask, unsigned long maxloops);
unsigned long countPulseASM(const volatile uint32_t *port, uint32_t bit, uint32_t stateMask, unsigned long maxloops)
{
unsigned long width = 0;
// wait for any previous pulse to end
while ((*port & bit) == stateMask)
if (--maxloops == 0)
return 0;
// wait for the pulse to start
while ((*port & bit) != stateMask)
if (--maxloops == 0)
return 0;
// wait for the pulse to stop
while ((*port & bit) == stateMask) {
if (++width == maxloops)
return 0;
}
return width;
}
/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH
* or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds
* to 3 minutes in length, but must be called at least a few dozen microseconds
+4 -3
View File
@@ -58,9 +58,9 @@ using the command line:
The result has been slightly edited to increase readability.
*/
.cpu cortex-m0plus
.fpu softvfp
/*
.cpu cortex-m4
.fpu fpv4-sp-d16
.eabi_attribute 20, 1 @ Tag_ABI_FP_denormal
.eabi_attribute 21, 1 @ Tag_ABI_FP_exceptions
.eabi_attribute 23, 3 @ Tag_ABI_FP_number_model
@@ -173,3 +173,4 @@ countPulseASM:
pop {r4, r5, pc}
.size countPulseASM, .-countPulseASM
.ident "GCC: (GNU Tools for ARM Embedded Processors (Arduino build)) 4.8.3 20140228 (release) [ARM/embedded-4_8-branch revision 208322]"
*/
-5
View File
@@ -76,17 +76,12 @@ caddr_t _sbrk( int incr )
void __malloc_lock(struct _reent *ptr)
{
(void) ptr;
ledOn(LED_RED);
vTaskSuspendAll();
}
void __malloc_unlock(struct _reent *ptr)
{
(void) ptr;
ledOn(LED_BLUE);
xTaskResumeAll();
}
+4
View File
@@ -63,6 +63,10 @@ void usb_init(void)
nrfx_power_usbevt_enable();
// Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice
// 2 is highest for application
NVIC_SetPriority(USBD_IRQn, 2);
// USB power may already be ready at this time -> no event generated
// We need to invoke the handler based on the status initially
uint32_t usb_reg = NRF_POWER->USBREGSTATUS;
+27 -17
View File
@@ -62,7 +62,6 @@ typedef struct
uint8_t arg_count;
bool from_isr;
// uint8_t callback_type;
// uint8_t _reserved[2];
uint32_t arguments[1]; // flexible array holder
@@ -94,27 +93,38 @@ typedef void (*adacb_5arg_t) (uint32_t, uint32_t, uint32_t, uint32_t, uint32_t);
/**
* Macro function is called by other module with all intended parameters.
* The first parameter is malloced Pointer (NULL if not), so that callback could know to free memory
*/
#define _cb_setup(_from_isr, _malloced, _func, ... ) \
do { \
uint8_t const _count = VA_ARGS_NUM(__VA_ARGS__);\
ada_callback_t* cb_data = (ada_callback_t*) rtos_malloc( sizeof(ada_callback_t) + (_count ? (_count-1)*4 : 0) ); \
cb_data->malloced_data = _malloced;\
cb_data->callback_func = (void*)_func;\
cb_data->arg_count = _count;\
if ( _count ) {\
uint32_t arguments[] = { _ADA_CB_ARGS(__VA_ARGS__) };\
memcpy(cb_data->arguments, arguments, 4*_count);\
}\
ada_callback_queue(cb_data, _from_isr);\
#define _cb_setup(_from_isr, _mdata, _mlen, _func, ... ) \
do { \
uint8_t const _count = VA_ARGS_NUM(__VA_ARGS__); \
ada_callback_t* cb_data = (ada_callback_t*) rtos_malloc( sizeof(ada_callback_t) + (_count ? (_count-1)*4 : 0) );\
cb_data->malloced_data = NULL; \
if ( (_mdata) && (_mlen) ) { \
cb_data->malloced_data = rtos_malloc(_mlen); \
memcpy(cb_data->malloced_data, _mdata, _mlen); \
} \
cb_data->callback_func = (void*)_func; \
cb_data->arg_count = _count; \
if ( _count ) { \
uint32_t arguments[] = { _ADA_CB_ARGS(__VA_ARGS__) }; \
/* argument most likely is _mdata if used, change it to malloced one */\
if ( (_mdata) && (_mlen) ) { \
for(uint8_t i=0; i<_count; i++) {\
if (arguments[i] == ((uint32_t) (_mdata))) { arguments[i] = ((uint32_t) cb_data->malloced_data); } \
}\
}\
memcpy(cb_data->arguments, arguments, 4*_count); \
} \
ada_callback_queue(cb_data, _from_isr); \
} while(0)
/**
* Schedule an function and parameters to be invoked in Ada Callback Task
* Macro can take at least 2 and at max 7 arguments
* - 1st arg : pointer data that need to be freed with free(pointer) after function is invoked
* - 2nd arg : function to be invoked
* - 1st arg : data pointer that need to be allocated and copied (e.g local variable). NULL if not used
* Ada callback will malloc, copy and free after complete.
* - 2nd arg : data pointer length, zero if not used
* - 3rd arg : function to be invoked
* - 3rd-7th arg : function argument, will be cast to uint32_t
*/
#define ada_callback(... ) _cb_setup(false, __VA_ARGS__)
@@ -122,7 +132,7 @@ typedef void (*adacb_5arg_t) (uint32_t, uint32_t, uint32_t, uint32_t, uint32_t);
/**
* Similar to ada_callback() but invoke in ISR-context
*/
#define ada_callback_fromISR(... ) _cb_setup(true , __VA_ARGS__)
#define ada_callback_fromISR(... ) _cb_setup(true, __VA_ARGS__)
void ada_callback_init(void);
void ada_callback_queue(ada_callback_t* cb_data, bool from_isr);
+1 -2
View File
@@ -80,8 +80,7 @@ const char* getBootloaderVersion(void)
uint32_t const ver2 = (sd_version % 1000000)/1000;
uint32_t const ver3 = sd_version % 1000;
sprintf(fw_str, "s%d %d.%d.%d r%d", sd_id,
ver1, ver2, ver3, U32_BYTE4(bootloaderVersion) );
sprintf(fw_str, "s%d %d.%d.%d", sd_id, ver1, ver2, ver3);
}
return fw_str;
+1 -1
View File
@@ -107,7 +107,7 @@ bool BLEHomekit::setAdv(BLEAdvertisingData& adv_ref)
.compatible_version = 2 // protocol version
};
Bluefruit.Gap.getAddr(data.dev_id);
Bluefruit.getAddr(data.dev_id);
VERIFY_STATIC( sizeof(data) == 17);
@@ -195,11 +195,13 @@ uint16_t HAPCharacteristic::writeHapValue(uint32_t num)
void HAPCharacteristic::createHapResponse(uint16_t conn_hdl, uint8_t status, TLV8_t tlv_para[], uint8_t count)
{
BLEConnection* conn = Bluefruit.Connection( conn_hdl );
// Determine body len (not including 2 byte length itself)
uint16_t body_len = tlv8_encode_calculate_len(tlv_para, count);
// Determine the response length including fragmentation scheme
uint16_t const gatt_mtu = Bluefruit.Gap.getMTU(conn_hdl) - 3;
uint16_t const gatt_mtu = conn->getMtu() - 3;
uint16_t resp_len = sizeof(HAPResponseHeader_t) + 2 + body_len;
uint16_t nfrag = 0; // number of fragments (excluding the first)
@@ -356,7 +358,8 @@ void HAPCharacteristic::processGattWrite(uint16_t conn_hdl, ble_gatts_evt_write_
LOG_LV2("GATTS", "Write Op = %d, len = %d, offset = %d, uuid = 0x%04X", gatt_req->op, gatt_req->len, gatt_req->offset, gatt_req->uuid.uuid);
LOG_LV2_BUFFER(NULL, gatt_req->data, gatt_req->len);
uint16_t const gatt_mtu = Bluefruit.Gap.getMTU(conn_hdl) - 3;
BLEConnection* conn = Bluefruit.Connection( conn_hdl );
uint16_t const gatt_mtu = conn->getMtu() - 3;
ble_gatts_rw_authorize_reply_params_t reply =
{
@@ -459,7 +462,8 @@ void HAPCharacteristic::processGattWrite(uint16_t conn_hdl, ble_gatts_evt_write_
void HAPCharacteristic::processGattRead(uint16_t conn_hdl, ble_gatts_evt_read_t* gatt_req)
{
uint16_t const gatt_mtu = Bluefruit.Gap.getMTU(conn_hdl) - 3;
BLEConnection* conn = Bluefruit.Connection( conn_hdl );
uint16_t const gatt_mtu = conn->getMtu() - 3;
LOG_LV2("GATTS", "Read uuid = 0x%04X, offset = %d", gatt_req->uuid.uuid, gatt_req->offset);
@@ -552,7 +556,7 @@ void HAPCharacteristic::_eventHandler(ble_evt_t* event)
{
uint16_t value;
memcpy(&value, request->data, 2);
_cccd_wr_cb(*this, value);
_cccd_wr_cb(conn_hdl, this, value);
}
}
}
+1 -1
View File
@@ -136,7 +136,7 @@ static uint8_t crypto_loadKeys(void)
void crypto_scheduleStoreKeys(void)
{
// crypto_storing = 1;
ada_callback(NULL, crypto_storeKeys);
ada_callback(NULL, 0, crypto_storeKeys);
}
void crypto_storeKeys(void)
+2 -2
View File
@@ -232,7 +232,7 @@ void srp_start(void)
srp.serverM1 = 0;
}
uint8_t srp_setA(uint8_t* abuf, uint16_t length, moretime_t moretime)
uint8_t srp_setA(uint8_t* abuf, uint16_t length, moretime_t moretime, uint16_t conn_hdl)
{
int err_code;
@@ -280,7 +280,7 @@ uint8_t srp_setA(uint8_t* abuf, uint16_t length, moretime_t moretime)
// These calculations take a long time. To avoid the connection dying we ask for more time now.
if (moretime)
{
moretime();
moretime(conn_hdl);
}
{
+2 -2
View File
@@ -36,11 +36,11 @@ extern "C"
extern srp_keys_t srp;
typedef void (*moretime_t)(void);
typedef void (*moretime_t)(uint16_t);
extern void srp_init(void);
extern void srp_start(void);
extern uint8_t srp_setA(uint8_t* a, uint16_t length, moretime_t moretime);
extern uint8_t srp_setA(uint8_t* a, uint16_t length, moretime_t moretime, uint16_t conn_hdl);
extern uint8_t srp_checkM1(uint8_t* m1, uint16_t length);
extern uint8_t* srp_getSalt(void);
extern uint8_t* srp_getB(void);
@@ -105,8 +105,7 @@ static const char* pairing_type_str[] =
void _pair_setup_write_cb (uint16_t conn_hdl, HAPCharacteristic* chr, HAPRequest_t const* hap_req);
void _pair_verify_write_cb (uint16_t conn_hdl, HAPCharacteristic* chr, HAPRequest_t const* hap_req);
// TODO add connection handle parameter
void gatt_reply_now(void)
void gatt_reply_now(uint16_t conn_hdl)
{
ble_gatts_rw_authorize_reply_params_t reply =
{
@@ -118,7 +117,7 @@ void gatt_reply_now(void)
}
}
};
VERIFY_STATUS( sd_ble_gatts_rw_authorize_reply(Bluefruit.connHandle(), &reply), );
VERIFY_STATUS( sd_ble_gatts_rw_authorize_reply(conn_hdl, &reply), );
}
HAPPairing::HAPPairing(void)
@@ -155,7 +154,7 @@ err_t HAPPairing::begin(void)
// Make PairID based on MAC address
uint8_t mac[6];
Bluefruit.Gap.getAddr(mac);
Bluefruit.getAddr(mac);
setDeviceID(mac);
// Init cryptography
@@ -243,7 +242,7 @@ void HAPPairing::pair_setup_m3(uint16_t conn_hdl, HAPRequest_t const* hap_req, T
#endif
// Set iOS public key
srp_setA( (uint8_t*) pubkey.value, pubkey.len, gatt_reply_now);
srp_setA( (uint8_t*) pubkey.value, pubkey.len, gatt_reply_now, conn_hdl);
// Check proof
if ( srp_checkM1( (uint8_t*) proof.value, proof.len) )
@@ -148,8 +148,8 @@ void connect_callback(uint16_t conn_handle)
{
Serial.println("Found NONE");
// disconect since we couldn't find bleuart service
Bluefruit.Central.disconnect(conn_handle);
// disconnect since we couldn't find bleuart service
Bluefruit.disconnect(conn_handle);
}
}
@@ -157,7 +157,6 @@ void connect_callback(uint16_t conn_handle)
* Callback invoked when a connection is dropped
* @param conn_handle
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -31,17 +31,17 @@
*
* Connection Handle Explanation
* -----------------------------
* The total number of connections is BLE_MAX_CONN = BLE_PRPH_MAX_CONN + BLE_CENTRAL_MAX_CONN.
* The total number of connections is BLE_MAX_CONNECTION (20)
*
* The 'connection handle' is an integer number assigned by the SoftDevice
* (Nordic's proprietary BLE stack). Each connection will receive it's own
* numeric 'handle' starting from 0 to BLE_MAX_CONN-1, depending on the order
* numeric 'handle' starting from 0 to BLE_MAX_CONNECTION-1, depending on the order
* of connection(s).
*
* - E.g If our Central board connects to a mobile phone first (running as a peripheral),
* then afterwards connects to another Bluefruit board running in peripheral mode, then
* the connection handle of mobile phone is 0, and the handle for the Bluefruit
* board is 1, and so on.
* then afterwards connects to another Bluefruit board running in peripheral mode, then
* the connection handle of mobile phone is 0, and the handle for the Bluefruit
* board is 1, and so on.
*/
/* LED PATTERNS
@@ -55,7 +55,7 @@
// Struct containing peripheral info
typedef struct
{
char name[32];
char name[16+1];
uint16_t conn_handle;
@@ -65,16 +65,16 @@ typedef struct
/* Peripheral info array (one per peripheral device)
*
* There are 'BLE_CENTRAL_MAX_CONN' central connections, but the
* There are 'BLE_MAX_CONNECTION' central connections, but the
* the connection handle can be numerically larger (for example if
* the peripheral role is also used, such as connecting to a mobile
* device). As such, we need to convert connection handles <-> the array
* index where appropriate to prevent out of array accesses.
*
* Note: One can simply declares the array with BLE_MAX_CONN and use connection
* Note: One can simply declares the array with BLE_MAX_CONNECTION and use connection
* handle as index directly with the expense of SRAM.
*/
prph_info_t prphs[BLE_CENTRAL_MAX_CONN];
prph_info_t prphs[BLE_MAX_CONNECTION];
// Software Timer for blinking the RED LED
SoftwareTimer blinkTimer;
@@ -92,7 +92,7 @@ void setup()
Serial.println("Bluefruit52 Central Multi BLEUART Example");
Serial.println("-----------------------------------------\n");
// Initialize Bluefruit with max concurrent connections as Peripheral = 1, Central = 1
// Initialize Bluefruit with max concurrent connections as Peripheral = 0, Central = 4
// SRAM usage required by SoftDevice will increase with number of connections
Bluefruit.begin(0, 4);
@@ -100,7 +100,7 @@ void setup()
Bluefruit.setName("Bluefruit52 Central");
// Init peripheral pool
for (uint8_t idx=0; idx<BLE_CENTRAL_MAX_CONN; idx++)
for (uint8_t idx=0; idx<BLE_MAX_CONNECTION; idx++)
{
// Invalid all connection handle
prphs[idx].conn_handle = BLE_CONN_HANDLE_INVALID;
@@ -156,7 +156,7 @@ void connect_callback(uint16_t conn_handle)
prph_info_t* peer = &prphs[id];
peer->conn_handle = conn_handle;
Bluefruit.Gap.getPeerName(conn_handle, peer->name, 32);
Bluefruit.Connection(conn_handle)->getPeerName(peer->name, sizeof(peer->name)-1);
Serial.print("Connected to ");
Serial.println(peer->name);
@@ -177,8 +177,8 @@ void connect_callback(uint16_t conn_handle)
{
Serial.println("Found ... NOTHING!");
// disconect since we couldn't find bleuart service
Bluefruit.Central.disconnect(conn_handle);
// disconnect since we couldn't find bleuart service
Bluefruit.disconnect(conn_handle);
}
connection_num++;
@@ -188,7 +188,6 @@ void connect_callback(uint16_t conn_handle)
* Callback invoked when a connection is dropped
* @param conn_handle
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -248,7 +247,7 @@ void sendAll(const char* str)
Serial.print("[Send to All]: ");
Serial.println(str);
for(uint8_t id=0; id < BLE_CENTRAL_MAX_CONN; id++)
for(uint8_t id=0; id < BLE_MAX_CONNECTION; id++)
{
prph_info_t* peer = &prphs[id];
@@ -282,7 +281,7 @@ void loop()
*/
int findConnHandle(uint16_t conn_handle)
{
for(int id=0; id<BLE_CENTRAL_MAX_CONN; id++)
for(int id=0; id<BLE_MAX_CONNECTION; id++)
{
if (conn_handle == prphs[id].conn_handle)
{
@@ -110,8 +110,8 @@ void connect_callback(uint16_t conn_handle)
{
Serial.println("Found NONE");
// disconect since we couldn't find HRM service
Bluefruit.Central.disconnect(conn_handle);
// disconnect since we couldn't find HRM service
Bluefruit.disconnect(conn_handle);
return;
}
@@ -125,7 +125,7 @@ void connect_callback(uint16_t conn_handle)
// Measurement chr is mandatory, if it is not found (valid), then disconnect
Serial.println("not found !!!");
Serial.println("Measurement characteristic is mandatory but not found");
Bluefruit.Central.disconnect(conn_handle);
Bluefruit.disconnect(conn_handle);
return;
}
Serial.println("Found it");
@@ -165,7 +165,6 @@ void connect_callback(uint16_t conn_handle)
* Callback invoked when a connection is dropped
* @param conn_handle
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -97,7 +97,7 @@ void connect_callback(uint16_t conn_handle)
Serial.println("Found it");
// HID device mostly require pairing/bonding
if ( !Bluefruit.Gap.requestPairing(conn_handle) )
if ( !Bluefruit.requestPairing(conn_handle) )
{
Serial.print("Failed to paired");
return;
@@ -126,8 +126,8 @@ void connect_callback(uint16_t conn_handle)
{
Serial.println("Found NONE");
// disconect since we couldn't find bleuart service
Bluefruit.Central.disconnect(conn_handle);
// disconnect since we couldn't find bleuart service
Bluefruit.disconnect(conn_handle);
}
}
@@ -135,7 +135,6 @@ void connect_callback(uint16_t conn_handle)
* Callback invoked when a connection is dropped
* @param conn_handle
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -25,9 +25,7 @@ void setup()
// Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1
// SRAM usage required by SoftDevice will increase dramatically with number of connections
Bluefruit.begin(0, 1);
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// Start Central Scan
@@ -29,9 +29,7 @@ void setup()
// Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1
// SRAM usage required by SoftDevice will increase dramatically with number of connections
Bluefruit.begin(0, 1);
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
/* Set the device name */
Bluefruit.setName("Bluefruit52");
@@ -176,8 +176,8 @@ void connect_callback(uint16_t conn_handle)
{
Serial.println("No Service Found");
// disconect since we couldn't find service
Bluefruit.Central.disconnect(conn_handle);
// disconnect since we couldn't find service
Bluefruit.disconnect(conn_handle);
return;
}
@@ -189,7 +189,7 @@ void connect_callback(uint16_t conn_handle)
{
// Measurement chr is mandatory, if it is not found (valid), then disconnect
Serial.println("No Characteristic Found. Characteristic is mandatory but not found. ");
Bluefruit.Central.disconnect(conn_handle);
Bluefruit.disconnect(conn_handle);
return;
}
Serial.println("Characteristic Found");
@@ -201,7 +201,7 @@ void connect_callback(uint16_t conn_handle)
if ( !opticalCharacteristicDataCollectionEnabler.discover() )
{
Serial.println("No Characteristic Found. Characteristic is mandatory but not found.");
Bluefruit.Central.disconnect(conn_handle);
Bluefruit.disconnect(conn_handle);
return;
}
Serial.println("Characteristic Found");
@@ -238,7 +238,6 @@ void connect_callback(uint16_t conn_handle)
* Callback invoked when a connection is dropped
* @param conn_handle
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -21,6 +21,9 @@
*/
#include <bluefruit.h>
// OTA DFU service
BLEDfu bledfu;
// Peripheral uart service
BLEUart bleuart;
@@ -38,18 +41,20 @@ void setup()
// Initialize Bluefruit with max concurrent connections as Peripheral = 1, Central = 1
// SRAM usage required by SoftDevice will increase with number of connections
Bluefruit.begin(1, 1);
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52 duo");
// Callbacks for Peripheral
Bluefruit.setConnectCallback(prph_connect_callback);
Bluefruit.setDisconnectCallback(prph_disconnect_callback);
Bluefruit.Periph.setConnectCallback(prph_connect_callback);
Bluefruit.Periph.setDisconnectCallback(prph_disconnect_callback);
// Callbacks for Central
Bluefruit.Central.setConnectCallback(cent_connect_callback);
Bluefruit.Central.setDisconnectCallback(cent_disconnect_callback);
// To be consistent OTA DFU should be added first if it exists
bledfu.begin();
// Configure and Start BLE Uart Service
bleuart.begin();
bleuart.setRxCallback(prph_bleuart_rx_callback);
@@ -115,8 +120,11 @@ void loop()
*------------------------------------------------------------------*/
void prph_connect_callback(uint16_t conn_handle)
{
// Get the reference to current connection
BLEConnection* connection = Bluefruit.Connection(conn_handle);
char peer_name[32] = { 0 };
Bluefruit.Gap.getPeerName(conn_handle, peer_name, sizeof(peer_name));
connection->getPeerName(peer_name, sizeof(peer_name));
Serial.print("[Prph] Connected to ");
Serial.println(peer_name);
@@ -131,8 +139,10 @@ void prph_disconnect_callback(uint16_t conn_handle, uint8_t reason)
Serial.println("[Prph] Disconnected");
}
void prph_bleuart_rx_callback(void)
void prph_bleuart_rx_callback(uint16_t conn_handle)
{
(void) conn_handle;
// Forward data from Mobile to our peripheral
char str[20+1] = { 0 };
bleuart.read(str, 20);
@@ -162,8 +172,11 @@ void scan_callback(ble_gap_evt_adv_report_t* report)
void cent_connect_callback(uint16_t conn_handle)
{
// Get the reference to current connection
BLEConnection* connection = Bluefruit.Connection(conn_handle);
char peer_name[32] = { 0 };
Bluefruit.Gap.getPeerName(conn_handle, peer_name, sizeof(peer_name));
connection->getPeerName(peer_name, sizeof(peer_name));
Serial.print("[Cent] Connected to ");
Serial.println(peer_name);;
@@ -174,8 +187,8 @@ void cent_connect_callback(uint16_t conn_handle)
clientUart.enableTXD();
}else
{
// disconect since we couldn't find bleuart service
Bluefruit.Central.disconnect(conn_handle);
// disconnect since we couldn't find bleuart service
Bluefruit.disconnect(conn_handle);
}
}
@@ -791,13 +791,11 @@ void setup()
Bluefruit.begin();
Bluefruit.setName("Bluefruit52");
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
// try to go as fast as possible, could be rejected by some central, increase it if needed
// iOS won't negotitate and will mostly use 30ms
Bluefruit.setConnInterval(9, 24); // min = 9*1.25=11.25 ms, max = 23*1.25=30ms
Bluefruit.Periph.setConnInterval(9, 24); // min = 9*1.25=11.25 ms, max = 23*1.25=30ms
// Configure and Start BLE Uart Service
// Firmata use several small write(1) --> buffering TXD is required to run smoothly
@@ -869,13 +867,8 @@ void startAdv(void)
*============================================================================*/
void loop()
{
// Skip if not connected and bleuart notification is enabled
if ( !(Bluefruit.connected() && bleuart.notifyEnabled()) )
{
// go to low power mode since there is nothing to do
waitForEvent();
return;
}
// Skip if not connected and bleuart notification is not enabled
if ( !(Bluefruit.connected() && bleuart.notifyEnabled()) ) return;
byte pin, analogPin;
@@ -913,4 +906,7 @@ void loop()
#ifdef FIRMATA_SERIAL_FEATURE
serialFeature.update();
#endif
// flush TXD since we use bufferTXD()
bleuart.flushTXD();
}
@@ -12,7 +12,7 @@
any redistribution
*********************************************************************/
/* This sketches demontrates the Bluefruit.Advertising API(). When powered up,
/* This sketch demonstrates the Bluefruit.Advertising API(). When powered up,
* the Bluefruit module will start advertising for ADV_TIMEOUT seconds (by
* default 30 seconds in fast mode, the remaining time slow mode) and then
* stop advertising completely. The module will start advertising again if
@@ -35,8 +35,7 @@ void setup()
Serial.println("----------------------------------------\n");
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// Set up and start advertising
@@ -51,12 +51,10 @@ void setup()
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.setDisconnectCallback(disconnect_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// Configure DIS client
bleClientDis.begin();
@@ -143,7 +141,7 @@ void connect_callback(uint16_t conn_handle)
// ANCS requires pairing to work, it makes sense to request security here as well
Serial.print("Attempting to PAIR with the iOS device, please press PAIR on your phone ... ");
if ( Bluefruit.requestPairing() )
if ( Bluefruit.requestPairing(conn_handle) )
{
Serial.println("Done");
Serial.println("Enabling notifications");
@@ -206,7 +204,6 @@ void ancs_notification_callback(AncsNotification_t* notif)
* Callback invoked when a connection is dropped
* @param conn_handle
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -96,11 +96,10 @@ void setup()
//Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.setDisconnectCallback(disconnect_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// Configure and Start Service
bleancs.begin();
@@ -276,7 +275,7 @@ void connect_callback(uint16_t conn_handle)
oled.display();
if ( Bluefruit.requestPairing() )
if ( Bluefruit.requestPairing(conn_handle) )
{
oled.println("OK");
@@ -380,7 +379,6 @@ void ancs_notification_callback(AncsNotification_t* notif)
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -43,9 +43,7 @@ void setup()
// off Blue LED for lowest power consumption
Bluefruit.autoConnLed(false);
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(0);
Bluefruit.setTxPower(0); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// Manufacturer ID is required for Manufacturer Specific Data
@@ -51,7 +51,7 @@ void setup()
Bluefruit.begin();
Bluefruit.setName("Bluefruit52 MIDI");
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
// Setup the on board blue LED to be enabled on CONNECT
Bluefruit.autoConnLed(true);
@@ -14,6 +14,7 @@
#include <bluefruit.h>
// BLE Service
BLEDfu bledfu; // OTA DFU service
BLEDis bledis; // device information
BLEUart bleuart; // uart over ble
BLEBas blebas; // battery
@@ -37,12 +38,14 @@ void setup()
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
//Bluefruit.setName(getMcuUniqueID()); // useful testing with multiple central connections
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.setDisconnectCallback(disconnect_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// To be consistent OTA DFU should be added first if it exists
bledfu.begin();
// Configure and Start Device Information Service
bledis.setManufacturer("Adafruit Industries");
@@ -111,16 +114,16 @@ void loop()
ch = (uint8_t) bleuart.read();
Serial.write(ch);
}
// Request CPU to enter low-power mode until an event/interrupt occurs
waitForEvent();
}
// callback invoked when central connects
void connect_callback(uint16_t conn_handle)
{
// Get the reference to current connection
BLEConnection* connection = Bluefruit.Connection(conn_handle);
char central_name[32] = { 0 };
Bluefruit.Gap.getPeerName(conn_handle, central_name, sizeof(central_name));
connection->getPeerName(central_name, sizeof(central_name));
Serial.print("Connected to ");
Serial.println(central_name);
@@ -130,7 +133,6 @@ void connect_callback(uint16_t conn_handle)
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -0,0 +1,165 @@
/*********************************************************************
This is an example for our nRF52 based Bluefruit LE modules
Pick one up today in the adafruit shop!
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in
any redistribution
*********************************************************************/
#include <bluefruit.h>
#define MAX_PRPH_CONNECTION 2
uint8_t connection_count = 0;
// BLE Service
BLEDfu bledfu; // OTA DFU service
BLEDis bledis; // device information
BLEUart bleuart; // uart over ble
void setup()
{
Serial.begin(115200);
while ( !Serial ) delay(10); // for nrf52840 with native usb
Serial.println("Bluefruit52 BLEUART Example");
Serial.println("---------------------------\n");
// Setup the BLE LED to be enabled on CONNECT
// Note: This is actually the default behaviour, but provided
// here in case you want to control this LED manually via PIN 19
Bluefruit.autoConnLed(true);
// Initialize Bluefruit with max concurrent connections as Peripheral = 2, Central = 0
Bluefruit.begin(MAX_PRPH_CONNECTION, 0);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// To be consistent OTA DFU should be added first if it exists
bledfu.begin();
// Configure and Start Device Information Service
bledis.setManufacturer("Adafruit Industries");
bledis.setModel("Bluefruit Feather52");
bledis.begin();
// Configure and Start BLE Uart Service
bleuart.begin();
// Set up and start advertising
startAdv();
Serial.println("Please use Adafruit's Bluefruit LE app to connect in UART mode");
Serial.println("Once connected, enter character(s) that you wish to send");
}
void startAdv(void)
{
// Advertising packet
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
// Include bleuart 128-bit uuid
Bluefruit.Advertising.addService(bleuart);
// Secondary Scan Response packet (optional)
// Since there is no room for 'Name' in Advertising packet
Bluefruit.ScanResponse.addName();
/* Start Advertising
* - Enable auto advertising if disconnected
* - Interval: fast mode = 20 ms, slow mode = 152.5 ms
* - Timeout for fast mode is 30 seconds
* - Start(timeout) with timeout = 0 will advertise forever (until connected)
*
* For recommended advertising interval
* https://developer.apple.com/library/content/qa/qa1931/_index.html
*/
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds
}
// print a string to Serial Uart and all connected BLE Uart
void printAll(uint8_t* buf, int count)
{
Serial.write(buf, count);
// Send to all connected centrals
for (uint8_t conn_hdl=0; conn_hdl < MAX_PRPH_CONNECTION; conn_hdl++)
{
bleuart.write(conn_hdl, buf, count);
}
}
void loop()
{
uint8_t buf[64];
int count;
// Forward data from HW Serial to BLEUART
while (Serial.available())
{
// Delay to wait for enough input
delay(2);
count = Serial.readBytes(buf, sizeof(buf));
printAll(buf, count);
}
// Forward from BLEUART to HW Serial
while ( bleuart.available() )
{
count = bleuart.read(buf, sizeof(buf));
printAll(buf, count);
}
}
// callback invoked when central connects
void connect_callback(uint16_t conn_handle)
{
// Get the reference to current connection
BLEConnection* connection = Bluefruit.Connection(conn_handle);
char central_name[32] = { 0 };
connection->getPeerName(central_name, sizeof(central_name));
Serial.print("Connected to ");
Serial.println(central_name);
connection_count++;
Serial.print("Connection count: ");
Serial.println(connection_count);
// Keep advertising if not reaching max
if (connection_count < MAX_PRPH_CONNECTION)
{
Serial.println("Keep advertising");
Bluefruit.Advertising.start(0);
}
}
/**
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
(void) conn_handle;
(void) reason;
Serial.println();
Serial.println("Disconnected");
connection_count--;
}
@@ -14,6 +14,9 @@
#include <bluefruit.h>
// OTA DFU service
BLEDfu bledfu;
void setup()
{
Serial.begin(115200);
@@ -23,10 +26,12 @@ void setup()
Serial.println("--------------------------\n");
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// To be consistent OTA DFU should be added first if it exists
bledfu.begin();
// Set up and start advertising
startAdv();
}
@@ -47,11 +47,10 @@ void setup()
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.setDisconnectCallback(disconnect_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// Configure CTS client
bleCTime.begin();
@@ -120,7 +119,7 @@ void connect_callback(uint16_t conn_handle)
// iOS requires pairing to work, it makes sense to request security here as well
Serial.print("Attempting to PAIR with the iOS device, please press PAIR on your phone ... ");
if ( Bluefruit.requestPairing() )
if ( Bluefruit.requestPairing(conn_handle) )
{
Serial.println("Done");
Serial.println("Enabling Time Adjust Notify");
@@ -165,7 +164,6 @@ void printTime(void)
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -53,11 +53,10 @@ void setup()
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.setDisconnectCallback(disconnect_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// Configure CTS client
bleCTime.begin();
@@ -136,7 +135,7 @@ void connect_callback(uint16_t conn_handle)
oled.display();
if ( Bluefruit.requestPairing() )
if ( Bluefruit.requestPairing(conn_handle) )
{
oled.println("OK");
@@ -180,7 +179,6 @@ void printTime(void)
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -14,6 +14,10 @@
#include <bluefruit.h>
// OTA DFU service
BLEDfu bledfu;
// Uart over BLE service
BLEUart bleuart;
// Function prototypes for packetparser.cpp
@@ -33,10 +37,12 @@ void setup(void)
Serial.println(F("-------------------------------------------"));
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// To be consistent OTA DFU should be added first if it exists
bledfu.begin();
// Configure and start the BLE Uart service
bleuart.begin();
@@ -44,8 +44,8 @@ void setup()
Bluefruit.setName("Bluefruit52 HRM");
// Set the connect/disconnect callback handlers
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.setDisconnectCallback(disconnect_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// Configure and Start the Device Information Service
Serial.println("Configuring the Device Information Service");
@@ -136,7 +136,7 @@ void setupHRM(void)
hrmc.setCccdWriteCallback(cccd_callback); // Optionally capture CCCD updates
hrmc.begin();
uint8_t hrmdata[2] = { 0b00000110, 0x40 }; // Set the characteristic to use 8-bit values, with the sensor connected and detected
hrmc.notify(hrmdata, 2); // Use .notify instead of .write!
hrmc.write(hrmdata, 2);
// Configure the Body Sensor Location characteristic
// See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.body_sensor_location.xml
@@ -161,8 +161,11 @@ void setupHRM(void)
void connect_callback(uint16_t conn_handle)
{
// Get the reference to current connection
BLEConnection* connection = Bluefruit.Connection(conn_handle);
char central_name[32] = { 0 };
Bluefruit.Gap.getPeerName(conn_handle, central_name, sizeof(central_name));
connection->getPeerName(central_name, sizeof(central_name));
Serial.print("Connected to ");
Serial.println(central_name);
@@ -172,7 +175,6 @@ void connect_callback(uint16_t conn_handle)
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -183,7 +185,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
Serial.println("Advertising!");
}
void cccd_callback(BLECharacteristic& chr, uint16_t cccd_value)
void cccd_callback(uint16_t conn_hdl, BLECharacteristic* chr, uint16_t cccd_value)
{
// Display the raw request packet
Serial.print("CCCD Updated: ");
@@ -193,8 +195,8 @@ void cccd_callback(BLECharacteristic& chr, uint16_t cccd_value)
// Check the characteristic this CCCD update is associated with in case
// this handler is used for multiple CCCD records.
if (chr.uuid == hrmc.uuid) {
if (chr.notifyEnabled()) {
if (chr->uuid == hrmc.uuid) {
if (chr->notifyEnabled(conn_hdl)) {
Serial.println("Heart Rate Measurement 'Notify' enabled");
} else {
Serial.println("Heart Rate Measurement 'Notify' disabled");
@@ -45,8 +45,8 @@ void setup()
Bluefruit.setName("Bluefruit52");
// Set the connect/disconnect callback handlers
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.setDisconnectCallback(disconnect_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// Configure and Start the Device Information Service
Serial.println("Configuring the Device Information Service");
@@ -151,8 +151,11 @@ void setupHTM(void)
void connect_callback(uint16_t conn_handle)
{
// Get the reference to current connection
BLEConnection* connection = Bluefruit.Connection(conn_handle);
char central_name[32] = { 0 };
Bluefruit.Gap.getPeerName(conn_handle, central_name, sizeof(central_name));
connection->getPeerName(central_name, sizeof(central_name));
Serial.print("Connected to ");
Serial.println(central_name);
@@ -162,7 +165,6 @@ void connect_callback(uint16_t conn_handle)
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -173,7 +175,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
Serial.println("Advertising!");
}
void cccd_callback(BLECharacteristic& chr, uint16_t cccd_value)
void cccd_callback(uint16_t conn_hdl, BLECharacteristic* chr, uint16_t cccd_value)
{
// Display the raw request packet
Serial.print("CCCD Updated: ");
@@ -183,8 +185,8 @@ void cccd_callback(BLECharacteristic& chr, uint16_t cccd_value)
// Check the characteristic this CCCD update is associated with in case
// this handler is used for multiple CCCD records.
if (chr.uuid == htmc.uuid) {
if (chr.indicateEnabled()) {
if (chr->uuid == htmc.uuid) {
if (chr->indicateEnabled(conn_hdl)) {
Serial.println("Temperature Measurement 'Indicate' enabled");
} else {
Serial.println("Temperature Measurement 'Indicate' disabled");
@@ -203,7 +205,7 @@ void loop()
// Note: We use .indicate instead of .write!
// If it is connected but CCCD is not enabled
// The characteristic's value is still updated although notification is not sent
// The characteristic's value is still updated although indicate is not sent
if ( htmc.indicate(htmdata, sizeof(htmdata)) ){
Serial.print("Temperature Measurement updated to: "); Serial.println(tempvalue);
}else{
@@ -216,4 +218,3 @@ void loop()
// Only send update once per second
delay(1000);
}
@@ -27,8 +27,7 @@ void setup()
Serial.println("---------------------------------\n");
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// Setup the advertising packet
@@ -43,8 +43,7 @@ void setup()
Serial.println();
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// Configure and start DIS (Device Information Service)
@@ -66,7 +65,7 @@ void setup()
* Note: It is already set by BLEHidAdafruit::begin() to 11.25ms - 15ms
* min = 9*1.25=11.25 ms, max = 12*1.25= 15 ms
*/
/* Bluefruit.setConnInterval(9, 12); */
/* Bluefruit.Periph.setConnInterval(9, 12); */
// Set up and start advertising
startAdv();
@@ -35,8 +35,7 @@ void setup()
Serial.println();
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// Configure and Start Device Information Service
@@ -60,7 +59,7 @@ void setup()
* Note: It is already set by BLEHidAdafruit::begin() to 11.25ms - 15ms
* min = 9*1.25=11.25 ms, max = 12*1.25= 15 ms
*/
/* Bluefruit.setConnInterval(9, 12); */
/* Bluefruit.Periph.setConnInterval(9, 12); */
// Set up and start advertising
startAdv();
@@ -120,9 +119,6 @@ void loop()
// Delay a bit after a report
delay(5);
}
// Request CPU to enter low-power mode until an event/interrupt occurs
waitForEvent();
}
/**
@@ -132,8 +128,10 @@ void loop()
* The LED bit map is as follows: (also defined by KEYBOARD_LED_* )
* Kana (4) | Compose (3) | ScrollLock (2) | CapsLock (1) | Numlock (0)
*/
void set_keyboard_led(uint8_t led_bitmap)
void set_keyboard_led(uint16_t conn_handle, uint8_t led_bitmap)
{
(void) conn_handle;
// light up Red Led if any bits is set
if ( led_bitmap )
{
@@ -53,8 +53,7 @@ void setup()
Serial.println();
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// Configure and Start Device Information Service
@@ -87,7 +86,7 @@ void setup()
* Note: It is already set by BLEHidAdafruit::begin() to 11.25ms - 15ms
* min = 9*1.25=11.25 ms, max = 12*1.25= 15 ms
*/
/* Bluefruit.setConnInterval(9, 12); */
/* Bluefruit.Periph.setConnInterval(9, 12); */
// Set up and start advertising
startAdv();
@@ -186,8 +185,10 @@ void loop()
* The LED bit map is as follows: (also defined by KEYBOARD_LED_* )
* Kana (4) | Compose (3) | ScrollLock (2) | CapsLock (1) | Numlock (0)
*/
void set_keyboard_led(uint8_t led_bitmap)
void set_keyboard_led(uint16_t conn_handle, uint8_t led_bitmap)
{
(void) conn_handle;
// light up Red Led if any bits is set
if ( led_bitmap )
{
@@ -36,9 +36,8 @@ void setup()
Bluefruit.begin();
// HID Device can have a min connection interval of 9*1.25 = 11.25 ms
Bluefruit.setConnInterval(9, 16); // min = 9*1.25=11.25 ms, max = 16*1.25=20ms
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.Periph.setConnInterval(9, 16); // min = 9*1.25=11.25 ms, max = 16*1.25=20ms
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// Configure and Start Device Information Service
@@ -86,10 +86,9 @@ void setup()
// Init Bluefruit
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
// Configure and Start Device Information Service
bledis.setManufacturer("Adafruit Industries");
@@ -133,8 +132,11 @@ void startAdv(void)
void connect_callback(uint16_t conn_handle)
{
// Get the reference to current connection
BLEConnection* connection = Bluefruit.Connection(conn_handle);
char central_name[32] = { 0 };
Bluefruit.Gap.getPeerName(conn_handle, central_name, sizeof(central_name));
connection->getPeerName(central_name, sizeof(central_name));
Serial.print("Connected to ");
Serial.println(central_name);
@@ -43,6 +43,7 @@ uint8_t components = 3; // only 3 and 4 are valid values
Adafruit_NeoPixel neopixel = Adafruit_NeoPixel();
// BLE Service
BLEDfu bledfu;
BLEDis bledis;
BLEUart bleuart;
@@ -62,10 +63,12 @@ void setup()
// Init Bluefruit
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
// To be consistent OTA DFU should be added first if it exists
bledfu.begin();
// Configure and Start Device Information Service
bledis.setManufacturer("Adafruit Industries");
@@ -109,8 +112,11 @@ void startAdv(void)
void connect_callback(uint16_t conn_handle)
{
// Get the reference to current connection
BLEConnection* connection = Bluefruit.Connection(conn_handle);
char central_name[32] = { 0 };
Bluefruit.Gap.getPeerName(conn_handle, central_name, sizeof(central_name));
connection->getPeerName(central_name, sizeof(central_name));
Serial.print("Connected to ");
Serial.println(central_name);
@@ -0,0 +1,119 @@
/*********************************************************************
This is an example for our nRF52 based Bluefruit LE modules
Pick one up today in the adafruit shop!
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in
any redistribution
*********************************************************************/
#include <bluefruit.h>
BLEUart bleuart; // uart over ble
void setup()
{
Serial.begin(115200);
while ( !Serial ) delay(10); // for nrf52840 with native usb
Serial.println("Bluefruit52 RSSI Example");
Serial.println("------------------------\n");
// Setup the BLE LED to be enabled on CONNECT
// Note: This is actually the default behaviour, but provided
// here in case you want to control this LED manually
Bluefruit.autoConnLed(true);
// Config the peripheral connection with maximum bandwidth
// more SRAM required by SoftDevice
// Note: All config***() function must be called before begin()
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// Configure and Start BLE Uart Service
bleuart.begin();
// Set up Rssi changed callback
Bluefruit.setRssiCallback(rssi_changed_callback);
// Set up and start advertising
startAdv();
Serial.println("Please use Adafruit's Bluefruit LE app to connect");
}
void startAdv(void)
{
// Advertising packet
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
// Include bleuart 128-bit uuid
Bluefruit.Advertising.addService(bleuart);
// Secondary Scan Response packet (optional)
// Since there is no room for 'Name' in Advertising packet
Bluefruit.ScanResponse.addName();
/* Start Advertising
* - Enable auto advertising if disconnected
* - Interval: fast mode = 20 ms, slow mode = 152.5 ms
* - Timeout for fast mode is 30 seconds
* - Start(timeout) with timeout = 0 will advertise forever (until connected)
*
* For recommended advertising interval
* https://developer.apple.com/library/content/qa/qa1931/_index.html
*/
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds
}
void loop()
{
// do nothing
}
void connect_callback(uint16_t conn_handle)
{
Serial.println("Connected");
// Get the reference to current connection
BLEConnection* connection = Bluefruit.Connection(conn_handle);
// Start monitoring rssi of this connection
// This function should be called in connect callback
// Input argument is value difference (to current rssi) that triggers callback
connection->monitorRssi(10);
}
void rssi_changed_callback(uint16_t conn_hdl, int8_t rssi)
{
(void) conn_hdl;
Serial.printf("Rssi = %d", rssi);
Serial.println();
}
/**
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
(void) conn_handle;
(void) reason;
Serial.println();
Serial.println("Disconnected");
}
@@ -0,0 +1,125 @@
/*********************************************************************
This is an example for our nRF52 based Bluefruit LE modules
Pick one up today in the adafruit shop!
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in
any redistribution
*********************************************************************/
#include <bluefruit.h>
BLEUart bleuart; // uart over ble
void setup()
{
Serial.begin(115200);
while ( !Serial ) delay(10); // for nrf52840 with native usb
Serial.println("Bluefruit52 RSSI Example");
Serial.println("------------------------\n");
// Setup the BLE LED to be enabled on CONNECT
// Note: This is actually the default behaviour, but provided
// here in case you want to control this LED manually
Bluefruit.autoConnLed(true);
// Config the peripheral connection with maximum bandwidth
// more SRAM required by SoftDevice
// Note: All config***() function must be called before begin()
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// Configure and Start BLE Uart Service
bleuart.begin();
// Set up and start advertising
startAdv();
Serial.println("Please use Adafruit's Bluefruit LE app to connect");
}
void startAdv(void)
{
// Advertising packet
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
// Include bleuart 128-bit uuid
Bluefruit.Advertising.addService(bleuart);
// Secondary Scan Response packet (optional)
// Since there is no room for 'Name' in Advertising packet
Bluefruit.ScanResponse.addName();
/* Start Advertising
* - Enable auto advertising if disconnected
* - Interval: fast mode = 20 ms, slow mode = 152.5 ms
* - Timeout for fast mode is 30 seconds
* - Start(timeout) with timeout = 0 will advertise forever (until connected)
*
* For recommended advertising interval
* https://developer.apple.com/library/content/qa/qa1931/_index.html
*/
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds
}
void loop()
{
if ( Bluefruit.connected() )
{
uint16_t conn_hdl = Bluefruit.connHandle();
// Get the reference to current connected connection
BLEConnection* connection = Bluefruit.Connection(conn_hdl);
// get the RSSI value of this connection
// monitorRssi() must be called previously (in connect callback)
int8_t rssi = connection->getRssi();
Serial.printf("Rssi = %d", rssi);
Serial.println();
// print one per second
delay(1000);
}
}
void connect_callback(uint16_t conn_handle)
{
Serial.println("Connected");
// Get the reference to current connection
BLEConnection* conn = Bluefruit.Connection(conn_handle);
// Start monitoring rssi of this connection
// This function should be called in connect callback
// no parameters means we don't use rssi changed callback
conn->monitorRssi();
}
/**
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
(void) conn_handle;
(void) reason;
Serial.println();
Serial.println("Disconnected");
}
@@ -44,11 +44,10 @@ void setup(void)
Bluefruit.autoConnLed(true);
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.setDisconnectCallback(disconnect_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// Configure and Start Device Information Service
bledis.setManufacturer("Adafruit Industries");
@@ -99,7 +98,6 @@ void connect_callback(uint16_t conn_handle)
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
* https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/cores/nRF5/nordic/softdevice/s140_nrf52_6.1.1_API/include/ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
@@ -120,9 +120,7 @@ void setup()
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
//InternalFS.remove(CRYPTO_KEYFILE);
@@ -170,12 +170,9 @@ void setup()
}
/* Enable both peripheral and central modes */
err_t err = Bluefruit.begin(true, true);
if (err)
if ( !Bluefruit.begin(1, 1) )
{
Serial.print("Unable to init Bluefruit (ERROR CODE: ");
Serial.print(err);
Serial.println(")");
Serial.println("Unable to init Bluefruit");
while(1)
{
digitalToggle(LED_RED);
@@ -187,8 +184,7 @@ void setup()
Serial.println("Bluefruit initialized (central mode)");
}
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
/* Set the device name */
Bluefruit.setName("Bluefruit52");
@@ -60,12 +60,9 @@ void setup()
blinkTimer.begin(1000, blink_timer_callback);
blinkTimer.start();
err_t err = Bluefruit.begin();
if (err)
if (Bluefruit.begin())
{
Serial.print("Unable to init Bluefruit (ERROR CODE: ");
Serial.print(err);
Serial.println(")");
Serial.println("Unable to init Bluefruit");
while(1)
{
digitalToggle(LED_RED);
@@ -77,8 +74,7 @@ void setup()
Serial.println("Bluefruit initialized (peripheral mode)");
}
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
// Set up and start advertising
+1 -5
View File
@@ -109,8 +109,6 @@ configPrphConn KEYWORD2
configCentralConn KEYWORD2
getMaxMtuByConnCfg KEYWORD2
getMaxMtu KEYWORD2
getHvnQueueSize KEYWORD2
getWriteCmdQueueSize KEYWORD2
getMTU KEYWORD2
getHvnPacket KEYWORD2
@@ -441,9 +439,7 @@ LED_CONN LITERAL1
#######################################
# BLE Constants (LITERAL1)
#######################################
BLE_MAX_CONN LITERAL1
BLE_CENTRAL_MAX_CONN LITERAL1
BLE_PRPH_MAX_CONN LITERAL1
BLE_MAX_CONNECTION LITERAL1
BLE_CONN_HANDLE_INVALID LITERAL1
+1 -1
View File
@@ -1,5 +1,5 @@
name=Adafruit Bluefruit nRF52 Libraries
version=0.9.3
version=0.10.0
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for nRF52-based Adafruit Bluefruit LE modules
+13 -11
View File
@@ -255,6 +255,8 @@ BLEAdvertising::BLEAdvertising(void)
_start_if_disconnect = true;
_runnning = false;
_conn_mask = 0;
_fast_interval = BLE_ADV_INTERVAL_FAST_DFLT;
_slow_interval = BLE_ADV_INTERVAL_SLOW_DFLT;
_active_interval = _fast_interval;
@@ -397,31 +399,31 @@ bool BLEAdvertising::stop(void)
void BLEAdvertising::_eventHandler(ble_evt_t* evt)
{
// conn handle has fixed offset for all events
uint16_t const conn_hdl = evt->evt.common_evt.conn_handle;
switch ( evt->header.evt_id )
{
case BLE_GAP_EVT_CONNECTED:
{
ble_gap_evt_connected_t const * para = &evt->evt.gap_evt.params.connected;
if ( para->role == BLE_GAP_ROLE_PERIPH)
if ( para->role == BLE_GAP_ROLE_PERIPH )
{
_runnning = false;
bitSet(_conn_mask, conn_hdl);
// Turn on Conn LED
Bluefruit._stopConnLed();
Bluefruit._setConnLed(true);
_runnning = false;
}
}
break;
case BLE_GAP_EVT_DISCONNECTED:
if ( BLE_GAP_ROLE_PERIPH == Bluefruit.Gap.getRole(evt->evt.common_evt.conn_handle) )
if ( bitRead(_conn_mask, conn_hdl) && (0 == Bluefruit.connected()) )
{
// Turn off Conn LED
Bluefruit._setConnLed(false);
bitClear(_conn_mask, conn_hdl);
// Auto start if enabled
if ( _start_if_disconnect ) start(_stop_timeout);
// Auto start if enabled and not connected to any central
if ( !_runnning && _start_if_disconnect ) start(_stop_timeout);
}
break;
@@ -455,7 +457,7 @@ void BLEAdvertising::_eventHandler(ble_evt_t* evt)
Bluefruit._stopConnLed(); // stop blinking
// invoke stop callback
if (_stop_cb) ada_callback(NULL, _stop_cb);
if (_stop_cb) ada_callback(NULL, 0, _stop_cb);
}
}
}
@@ -153,6 +153,8 @@ private:
bool _start_if_disconnect;
bool _runnning;
uint32_t _conn_mask;
uint16_t _fast_interval; // in 0.625 ms
uint16_t _slow_interval; // in 0.625 ms
uint16_t _active_interval; // in 0.625 ms
+15 -34
View File
@@ -42,12 +42,12 @@
*/
BLECentral::BLECentral(void)
{
_connect_cb = NULL;
_disconnect_cb = NULL;
_conn_param.min_conn_interval = _conn_param.max_conn_interval = BLE_GAP_CONN_MIN_INTERVAL_DFLT;
_conn_param.slave_latency = BLE_GAP_CONN_SLAVE_LATENCY;
_conn_param.conn_sup_timeout = BLE_GAP_CONN_SUPERVISION_TIMEOUT_MS/10;
_connect_cb = NULL;
_disconnect_cb = NULL;
}
void BLECentral::begin(void)
@@ -85,46 +85,37 @@ bool BLECentral::connect(const ble_gap_evt_adv_report_t* adv_report)
return connect(&adv_report->peer_addr);
}
bool BLECentral::disconnect(uint16_t conn_handle)
{
return ERROR_NONE == sd_ble_gap_disconnect(conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
}
/**
* Check if connected to a specific peripheral
* @param conn_handle
* @return
*/
bool BLECentral::connected(uint16_t conn_handle)
bool BLECentral::connected(uint16_t conn_hdl)
{
return Bluefruit.Gap.connected(conn_handle);
BLEConnection* conn = Bluefruit.Connection(conn_hdl);
return conn && conn->connected() && (conn->getRole() == BLE_GAP_ROLE_CENTRAL);
}
/**
* Check if connected to ANY peripherals
* @param conn_handle
* @return
* @return number of peripherals
*/
bool BLECentral::connected(void)
uint8_t BLECentral::connected(void)
{
for (uint8_t conn=0; conn<BLE_MAX_CONN; conn++)
uint8_t count = 0;
for (uint16_t c=0; c<BLE_MAX_CONNECTION; c++)
{
// skip Peripheral Role handle
if ( Bluefruit.Gap.connected(conn) && (Bluefruit.Gap.getRole(conn) == BLE_GAP_ROLE_CENTRAL) )
{
return true;
}
if ( this->connected(c) ) count++;
}
return false;
return count;
}
void BLECentral::setConnectCallback( BLEGap::connect_callback_t fp)
void BLECentral::setConnectCallback( ble_connect_callback_t fp )
{
_connect_cb = fp;
}
void BLECentral::setDisconnectCallback( BLEGap::disconnect_callback_t fp)
void BLECentral::setDisconnectCallback( ble_disconnect_callback_t fp )
{
_disconnect_cb = fp;
}
@@ -138,7 +129,7 @@ void BLECentral::clearBonds(void)
* Event is forwarded from Bluefruit Poll() method
* @param event
*/
void BLECentral::_event_handler(ble_evt_t* evt)
void BLECentral::_eventHandler(ble_evt_t* evt)
{
// conn handle has fixed offset regardless of event type
const uint16_t conn_hdl = evt->evt.common_evt.conn_handle;
@@ -148,19 +139,9 @@ void BLECentral::_event_handler(ble_evt_t* evt)
switch ( evt->header.evt_id )
{
case BLE_GAP_EVT_CONNECTED:
if ( Bluefruit.Gap.getRole(conn_hdl) == BLE_GAP_ROLE_CENTRAL)
{
// Invoke callback
if ( _connect_cb) ada_callback(NULL, _connect_cb, conn_hdl);
}
break;
case BLE_GAP_EVT_DISCONNECTED:
if ( Bluefruit.Gap.getRole(conn_hdl) == BLE_GAP_ROLE_CENTRAL)
{
// Invoke callback reason is BLE_HCI_STATUS code
if ( _disconnect_cb) ada_callback(NULL, _disconnect_cb, conn_hdl, evt->evt.gap_evt.params.disconnected.reason);
}
break;
case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+13 -21
View File
@@ -39,51 +39,43 @@
#include <Arduino.h>
#include "bluefruit_common.h"
#include "BLEGap.h"
#include "BLEGatt.h"
#include "BLEUuid.h"
#include "BLECharacteristic.h"
#include "BLEClientCharacteristic.h"
#include "BLEService.h"
#include "BLEClientService.h"
class AdafruitBluefruit;
class BLECentral
{
public:
BLECentral(void); // Constructor
void begin(void);
/*------------------------------------------------------------------*/
/* GAP
*------------------------------------------------------------------*/
bool setConnInterval(uint16_t min, uint16_t max);
bool setConnIntervalMS (uint16_t min_ms, uint16_t max_ms);
bool setConnIntervalMS(uint16_t min_ms, uint16_t max_ms);
bool connect(const ble_gap_evt_adv_report_t* adv_report);
bool connect(const ble_gap_addr_t *peer_addr);
bool disconnect(uint16_t conn_handle);
bool connected (uint16_t conn_handle); // If connected to a specific peripheral
bool connected (void); // If connected to any peripherals
bool connected(uint16_t conn_hdl); // Connected as central to this connection
uint8_t connected(void); // Number of connected as central
void clearBonds (void);
/*------------- Callbacks -------------*/
void setConnectCallback ( BLEGap::connect_callback_t fp);
void setDisconnectCallback( BLEGap::disconnect_callback_t fp);
void setConnectCallback ( ble_connect_callback_t fp);
void setDisconnectCallback( ble_disconnect_callback_t fp);
/*------------------------------------------------------------------*/
/* INTERNAL USAGE ONLY
* Although declare as public, it is meant to be invoked by internal code.
*------------------------------------------------------------------*/
void _eventHandler(ble_evt_t* evt);
private:
ble_gap_conn_params_t _conn_param;
BLEGap::connect_callback_t _connect_cb;
BLEGap::disconnect_callback_t _disconnect_cb;
void _event_handler(ble_evt_t* evt);
ble_connect_callback_t _connect_cb;
ble_disconnect_callback_t _disconnect_cb;
friend class AdafruitBluefruit;
};
@@ -38,6 +38,7 @@
void BLECharacteristic::_init(void)
{
varclr(&_use_ada_cb);
_is_temp = false;
_max_len = BLE_GATT_ATT_MTU_DEFAULT-3;
_service = NULL;
@@ -138,26 +139,32 @@ void BLECharacteristic::setPermission(BleSecurityMode read_perm, BleSecurityMode
memcpy(&_attr_meta.write_perm, &write_perm, 1);
}
void BLECharacteristic::setWriteCallback(write_cb_t fp)
void BLECharacteristic::setWriteCallback(write_cb_t fp, bool useAdaCallback)
{
_wr_cb = fp;
_use_ada_cb.write = useAdaCallback;
}
void BLECharacteristic::setCccdWriteCallback(write_cccd_cb_t fp)
void BLECharacteristic::setCccdWriteCallback(write_cccd_cb_t fp, bool useAdaCallback)
{
_cccd_wr_cb = fp;
_use_ada_cb.cccd_write = useAdaCallback;
}
void BLECharacteristic::setReadAuthorizeCallback(read_authorize_cb_t fp)
void BLECharacteristic::setReadAuthorizeCallback(read_authorize_cb_t fp, bool useAdaCallback)
{
_attr_meta.rd_auth = (fp ? 1 : 0);
_rd_authorize_cb = fp;
_use_ada_cb.read_authorize = useAdaCallback;
}
void BLECharacteristic::setWriteAuthorizeCallback(write_authorize_cb_t fp)
void BLECharacteristic::setWriteAuthorizeCallback(write_authorize_cb_t fp, bool useAdaCallback)
{
_attr_meta.wr_auth = (fp ? 1 : 0);
_wr_authorize_cb = fp;
_use_ada_cb.write_authorize = useAdaCallback;
}
void BLECharacteristic::setUserDescriptor(const char* descriptor)
@@ -349,12 +356,42 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event)
{
ble_gatts_evt_rw_authorize_request_t * request = &event->evt.gatts_evt.params.authorize_request;
// Read authorization
if ( (request->type == BLE_GATTS_AUTHORIZE_TYPE_READ) && (_rd_authorize_cb != NULL))
{
ble_gatts_evt_read_t * rd_req = &request->request.read;
if ( _use_ada_cb.read_authorize )
{
ada_callback(rd_req, sizeof(*rd_req), _rd_authorize_cb, conn_hdl, this, rd_req);
}
else
{
_rd_authorize_cb(conn_hdl, this, rd_req);
}
}
// Write Authorization and Long Write sequence handling
if (request->type == BLE_GATTS_AUTHORIZE_TYPE_WRITE)
{
ble_gatts_evt_write_t * wr_req = &request->request.write;
switch(wr_req->op)
{
case BLE_GATTS_OP_WRITE_REQ:
// Write Request with authorization
if (_wr_authorize_cb != NULL)
{
if ( _use_ada_cb.write_authorize )
{
ada_callback(wr_req, sizeof(*wr_req), _wr_authorize_cb, conn_hdl, this, wr_req);
}else
{
_wr_authorize_cb(conn_hdl, this, wr_req);
}
}
break;
case BLE_GATTS_OP_PREP_WRITE_REQ:
{
// Prepare Long Write
@@ -399,7 +436,16 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event)
sd_ble_gatts_rw_authorize_reply(conn_hdl, &reply);
// Long write complete, call write callback if set
if (_wr_cb) _wr_cb(*this, _long_wr.buffer, _long_wr.count, 0);
if (_wr_cb)
{
if (_use_ada_cb.write)
{
ada_callback(_long_wr.buffer, _long_wr.count, _wr_cb, conn_hdl, this, _long_wr.buffer, _long_wr.count);
}else
{
_wr_cb(conn_hdl, this, _long_wr.buffer, _long_wr.count);
}
}
// free up memory
rtos_free(_long_wr.buffer);
@@ -412,19 +458,9 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event)
// Cancel Long Write
break;
case BLE_GATTS_OP_WRITE_REQ:
// Write Request with authorization
if (_wr_authorize_cb != NULL) _wr_authorize_cb(*this, &request->request.write);
break;
default: break;
}
}
if ( (request->type == BLE_GATTS_AUTHORIZE_TYPE_READ) && (_rd_authorize_cb != NULL))
{
_rd_authorize_cb(*this, &request->request.read);
}
}
break;
@@ -438,18 +474,15 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event)
if (request->handle == _handles.value_handle)
{
LOG_LV2("GATTS", "attr's value, uuid = 0x%04X", request->uuid.uuid);
// TODO Ada callback
if (_wr_cb)
{
// uint8_t* data = (uint8_t*) rtos_malloc(request->len);
//
// if (data)
// {
// ada_callback(data, _wr_cb, *this, data, request->len, request->offset);
// }else
if (_use_ada_cb.write)
{
// invoke directly if cannot allocate memory for data
_wr_cb(*this, request->data, request->len, request->offset);
ada_callback(request->data, request->len, _wr_cb, conn_hdl, this, request->data, request->len);
}else
{
_wr_cb(conn_hdl, this, request->data, request->len);
}
}
}
@@ -459,12 +492,19 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event)
{
LOG_LV2("GATTS", "attr's cccd");
// Invoke callback if set
if (_cccd_wr_cb)
{
uint16_t value;
memcpy(&value, request->data, 2);
_cccd_wr_cb(*this, value);
if ( _use_ada_cb.cccd_write )
{
ada_callback(NULL, 0, _cccd_wr_cb, conn_hdl, this, value);
}
else
{
_cccd_wr_cb(conn_hdl, this, value);
}
}
}
}
@@ -560,10 +600,9 @@ uint32_t BLECharacteristic::read32(void)
return read(&num, sizeof(num)) ? num : 0;
}
uint16_t BLECharacteristic::getCccd(void)
uint16_t BLECharacteristic::getCccd(uint16_t conn_hdl)
{
VERIFY( Bluefruit.connected() && (_handles.cccd_handle != BLE_GATT_HANDLE_INVALID), 0 );
VERIFY( Bluefruit.connected(conn_hdl) && (_handles.cccd_handle != BLE_GATT_HANDLE_INVALID), 0 );
uint16_t cccd;
ble_gatts_value_t value =
@@ -573,7 +612,7 @@ uint16_t BLECharacteristic::getCccd(void)
.p_value = (uint8_t*) &cccd
};
err_t err = sd_ble_gatts_value_get(Bluefruit.connHandle(), _handles.cccd_handle, &value);
err_t err = sd_ble_gatts_value_get(conn_hdl, _handles.cccd_handle, &value);
// CCCD is not set, count as not enabled
if ( BLE_ERROR_GATTS_SYS_ATTR_MISSING == err )
@@ -592,27 +631,37 @@ uint16_t BLECharacteristic::getCccd(void)
*------------------------------------------------------------------*/
bool BLECharacteristic::notifyEnabled(void)
{
VERIFY( _properties.notify );
return (getCccd() & BLE_GATT_HVX_NOTIFICATION);
return this->notifyEnabled(Bluefruit.connHandle());
}
bool BLECharacteristic::notify(const void* data, uint16_t len)
bool BLECharacteristic::notifyEnabled(uint16_t conn_hdl)
{
VERIFY( _properties.notify );
return (getCccd(conn_hdl) & BLE_GATT_HVX_NOTIFICATION);
}
bool BLECharacteristic::notify(uint16_t conn_hdl, const void* data, uint16_t len)
{
VERIFY( _properties.notify );
// use default conn handle if not passed
if ( conn_hdl == BLE_CONN_HANDLE_INVALID ) conn_hdl = Bluefruit.connHandle();
// could not exceed max len
uint16_t remaining = min16(len, _max_len);
if ( notifyEnabled() )
if ( notifyEnabled(conn_hdl) )
{
uint16_t const max_payload = Bluefruit.Gap.getMTU( Bluefruit.connHandle() ) - 3;
BLEConnection* conn = Bluefruit.Connection( conn_hdl );
VERIFY(conn);
uint16_t const max_payload = conn->getMtu() - 3;
const uint8_t* u8data = (const uint8_t*) data;
while ( remaining )
{
// TODO multiple connection support
// Failed if there is no free buffer
if ( !Bluefruit.Gap.getHvnPacket( Bluefruit.connHandle() ) ) return false;
if ( !conn->getHvnPacket() ) return false;
uint16_t packet_len = min16(max_payload, remaining);
@@ -626,7 +675,7 @@ bool BLECharacteristic::notify(const void* data, uint16_t len)
};
LOG_LV2("CHR", "Notify %d bytes", packet_len);
VERIFY_STATUS( sd_ble_gatts_hvx(Bluefruit.connHandle(), &hvx_params), false );
VERIFY_STATUS( sd_ble_gatts_hvx(conn_hdl, &hvx_params), false );
remaining -= packet_len;
u8data += packet_len;
@@ -641,52 +690,95 @@ bool BLECharacteristic::notify(const void* data, uint16_t len)
return true;
}
bool BLECharacteristic::notify(const char * str)
bool BLECharacteristic::notify(uint16_t conn_hdl, const char * str)
{
return notify( (const uint8_t*) str, strlen(str) );
return notify(conn_hdl, (const uint8_t*) str, strlen(str));
}
bool BLECharacteristic::notify8(uint16_t conn_hdl, uint8_t num)
{
return notify(conn_hdl, (uint8_t*) &num, sizeof(num));
}
bool BLECharacteristic::notify16(uint16_t conn_hdl, uint16_t num)
{
return notify(conn_hdl, (uint8_t*) &num, sizeof(num));
}
bool BLECharacteristic::notify32(uint16_t conn_hdl, uint32_t num)
{
return notify(conn_hdl, (uint8_t*) &num, sizeof(num));
}
bool BLECharacteristic::notify32(uint16_t conn_hdl, int num)
{
return notify32((uint32_t) num, conn_hdl);
}
//--------------------------------------------------------------------+
// Notify with single connection
//--------------------------------------------------------------------+
bool BLECharacteristic::notify(const void* data, uint16_t len)
{
return notify(BLE_CONN_HANDLE_INVALID, data, len);
}
bool BLECharacteristic::notify(const char* str)
{
return notify(BLE_CONN_HANDLE_INVALID, str);
}
bool BLECharacteristic::notify8(uint8_t num)
{
return notify( (uint8_t*) &num, sizeof(num));
return notify8(BLE_CONN_HANDLE_INVALID, num);
}
bool BLECharacteristic::notify16(uint16_t num)
{
return notify( (uint8_t*) &num, sizeof(num));
return notify16(BLE_CONN_HANDLE_INVALID, num);
}
bool BLECharacteristic::notify32(uint32_t num)
{
return notify( (uint8_t*) &num, sizeof(num));
return notify32(BLE_CONN_HANDLE_INVALID, num);
}
bool BLECharacteristic::notify32(int num)
{
return notify32( (uint32_t) num);
return notify32(BLE_CONN_HANDLE_INVALID, num);
}
/*------------------------------------------------------------------*/
/* INDICATE
/* INDICATE multiple connections
*------------------------------------------------------------------*/
bool BLECharacteristic::indicateEnabled(void)
{
VERIFY( _properties.indicate );
return (getCccd() & BLE_GATT_HVX_INDICATION);
return this->indicateEnabled(Bluefruit.connHandle());
}
bool BLECharacteristic::indicate(const void* data, uint16_t len)
bool BLECharacteristic::indicateEnabled(uint16_t conn_hdl)
{
VERIFY( _properties.indicate );
return (getCccd(conn_hdl) & BLE_GATT_HVX_INDICATION);
}
bool BLECharacteristic::indicate(uint16_t conn_hdl, const void* data, uint16_t len)
{
VERIFY( _properties.indicate );
// use default conn handle if not passed
if ( conn_hdl == BLE_CONN_HANDLE_INVALID ) conn_hdl = Bluefruit.connHandle();
// could not exceed max len
uint16_t remaining = min16(len, _max_len);
if ( indicateEnabled() )
if ( indicateEnabled(conn_hdl) )
{
uint16_t conn_hdl = Bluefruit.connHandle();
BLEConnection* conn = Bluefruit.Connection( conn_hdl );
VERIFY(conn);
uint16_t const max_payload = Bluefruit.Gap.getMTU( conn_hdl ) - 3;
uint16_t const max_payload = conn->getMtu() - 3;
const uint8_t* u8data = (const uint8_t*) data;
while ( remaining )
@@ -705,8 +797,8 @@ bool BLECharacteristic::indicate(const void* data, uint16_t len)
LOG_LV2("CHR", "Indicate %d bytes", packet_len);
// Blocking wait until receiving confirmation from peer
VERIFY_STATUS( sd_ble_gatts_hvx( conn_hdl, &hvx_params), false );
VERIFY ( Bluefruit.Gatt.waitForIndicateConfirm(conn_hdl) );
VERIFY_STATUS( sd_ble_gatts_hvx(conn_hdl, &hvx_params), false );
VERIFY ( conn->waitForIndicateConfirm() );
remaining -= packet_len;
u8data += packet_len;
@@ -721,27 +813,60 @@ bool BLECharacteristic::indicate(const void* data, uint16_t len)
return true;
}
bool BLECharacteristic::indicate(const char * str)
bool BLECharacteristic::indicate(uint16_t conn_hdl, const char * str)
{
return indicate( (const uint8_t*) str, strlen(str) );
return indicate(conn_hdl, (const uint8_t*) str, strlen(str));
}
bool BLECharacteristic::indicate8(uint16_t conn_hdl, uint8_t num)
{
return indicate(conn_hdl, (uint8_t*) &num, sizeof(num));
}
bool BLECharacteristic::indicate16(uint16_t conn_hdl, uint16_t num)
{
return indicate(conn_hdl, (uint8_t*) &num, sizeof(num));
}
bool BLECharacteristic::indicate32(uint16_t conn_hdl, uint32_t num)
{
return indicate(conn_hdl, (uint8_t*) &num, sizeof(num));
}
bool BLECharacteristic::indicate32(uint16_t conn_hdl, int num)
{
return indicate32(conn_hdl, (uint32_t) num);
}
/*------------------------------------------------------------------*/
/* INDICATE single connections
*------------------------------------------------------------------*/
bool BLECharacteristic::indicate(const void* data, uint16_t len)
{
return indicate(BLE_CONN_HANDLE_INVALID, data, len);
}
bool BLECharacteristic::indicate(const char* str)
{
return indicate(BLE_CONN_HANDLE_INVALID, str);
}
bool BLECharacteristic::indicate8(uint8_t num)
{
return indicate( (uint8_t*) &num, sizeof(num));
return indicate8(BLE_CONN_HANDLE_INVALID, num);
}
bool BLECharacteristic::indicate16(uint16_t num)
{
return indicate( (uint8_t*) &num, sizeof(num));
return indicate16(BLE_CONN_HANDLE_INVALID, num);
}
bool BLECharacteristic::indicate32(uint32_t num)
{
return indicate( (uint8_t*) &num, sizeof(num));
return indicate32(BLE_CONN_HANDLE_INVALID, num);
}
bool BLECharacteristic::indicate32(int num)
{
return indicate32( (uint32_t) num);
return indicate32(BLE_CONN_HANDLE_INVALID, num);
}
@@ -74,10 +74,10 @@ class BLECharacteristic
{
public:
/*--------- Callback Signatures ----------*/
typedef void (*read_authorize_cb_t) (BLECharacteristic& chr, ble_gatts_evt_read_t * request);
typedef void (*write_authorize_cb_t) (BLECharacteristic& chr, ble_gatts_evt_write_t* request);
typedef void (*write_cb_t) (BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset);
typedef void (*write_cccd_cb_t) (BLECharacteristic& chr, uint16_t value);
typedef void (*read_authorize_cb_t) (uint16_t conn_hdl, BLECharacteristic* chr, ble_gatts_evt_read_t * request);
typedef void (*write_authorize_cb_t) (uint16_t conn_hdl, BLECharacteristic* chr, ble_gatts_evt_write_t* request);
typedef void (*write_cb_t) (uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len);
typedef void (*write_cccd_cb_t) (uint16_t conn_hdl, BLECharacteristic* chr, uint16_t value);
BLEUuid uuid;
@@ -105,10 +105,10 @@ class BLECharacteristic
void setPresentationFormatDescriptor(uint8_t type, int8_t exponent, uint16_t unit, uint8_t name_space = 1, uint16_t descritpor = 0);
/*------------- Callbacks -------------*/
void setWriteCallback (write_cb_t fp);
void setCccdWriteCallback (write_cccd_cb_t fp);
void setReadAuthorizeCallback(read_authorize_cb_t fp);
void setWriteAuthorizeCallback(write_authorize_cb_t fp);
void setWriteCallback (write_cb_t fp, bool useAdaCallback = true);
void setCccdWriteCallback (write_cccd_cb_t fp, bool useAdaCallback = true);
void setReadAuthorizeCallback(read_authorize_cb_t fp, bool useAdaCallback = true);
void setWriteAuthorizeCallback(write_authorize_cb_t fp, bool useAdaCallback = true);
virtual err_t begin(void);
@@ -118,50 +118,76 @@ class BLECharacteristic
ble_gatts_char_handles_t handles(void);
/*------------- Write -------------*/
uint16_t write(const void* data, uint16_t len);
uint16_t write(const char* str);
uint16_t write8 (uint8_t num);
uint16_t write16 (uint16_t num);
uint16_t write32 (uint32_t num);
uint16_t write32 (int num);
uint16_t write (const void* data, uint16_t len);
uint16_t write (const char* str);
uint16_t write8 (uint8_t num);
uint16_t write16 (uint16_t num);
uint16_t write32 (uint32_t num);
uint16_t write32 (int num);
/*------------- Read -------------*/
uint16_t read(void* buffer, uint16_t bufsize, uint16_t offset = 0);
uint16_t read (void* buffer, uint16_t bufsize, uint16_t offset = 0);
uint8_t read8 (void);
uint16_t read16(void);
uint32_t read32(void);
/*------------- Notify -------------*/
uint16_t getCccd(void);
uint16_t getCccd(uint16_t conn_hdl);
bool notifyEnabled(void);
bool notifyEnabled(uint16_t conn_hdl);
bool notify(const void* data, uint16_t len);
bool notify(const char* str);
/*------------- Notify -------------*/
bool notify (const void* data, uint16_t len);
bool notify (const char* str);
bool notify8 (uint8_t num);
bool notify16 (uint16_t num);
bool notify32 (uint32_t num);
bool notify32 (int num);
bool notify8 (uint8_t num);
bool notify16 (uint16_t num);
bool notify32 (uint32_t num);
bool notify32 (int num);
/*------------- Notify multiple connections -------------*/
bool notify (uint16_t conn_hdl, const void* data, uint16_t len);
bool notify (uint16_t conn_hdl, const char* str);
bool notify8 (uint16_t conn_hdl, uint8_t num);
bool notify16 (uint16_t conn_hdl, uint16_t num);
bool notify32 (uint16_t conn_hdl, uint32_t num);
bool notify32 (uint16_t conn_hdl, int num);
/*------------- Indicate -------------*/
bool indicateEnabled(void);
bool indicateEnabled(uint16_t conn_hdl);
bool indicate(const void* data, uint16_t len);
bool indicate(const char* str);
bool indicate (const void* data, uint16_t len);
bool indicate (const char* str);
bool indicate8 (uint8_t num);
bool indicate16 (uint16_t num);
bool indicate32 (uint32_t num);
bool indicate32 (int num);
bool indicate8 (uint8_t num);
bool indicate16 (uint16_t num);
bool indicate32 (uint32_t num);
bool indicate32 (int num);
/*------------- Indicate multiple connections -------------*/
bool indicate (uint16_t conn_hdl, const void* data, uint16_t len);
bool indicate (uint16_t conn_hdl, const char* str);
bool indicate8 (uint16_t conn_hdl, uint8_t num);
bool indicate16 (uint16_t conn_hdl, uint16_t num);
bool indicate32 (uint16_t conn_hdl, uint32_t num);
bool indicate32 (uint16_t conn_hdl, int num);
/*------------- Internal Functions -------------*/
virtual void _eventHandler(ble_evt_t* event);
protected:
struct ATTR_PACKED {
uint8_t write : 1;
uint8_t cccd_write : 1;
uint8_t read_authorize : 1;
uint8_t write_authorize : 1;
} _use_ada_cb;
bool _is_temp;
uint16_t _max_len;
BLEService* _service; // pointer to parent's service
@@ -168,7 +168,10 @@ uint16_t BLEClientCharacteristic::read(void* buffer, uint16_t bufsize)
{
VERIFY( _chr.char_props.read, 0 );
uint16_t const max_payload = Bluefruit.Gap.getMTU( _service->connHandle() ) - 3;
BLEConnection* conn = Bluefruit.Connection( _service->connHandle() );
VERIFY(conn, 0);
uint16_t const max_payload = conn->getMtu() - 3;
_adamsg.prepare(buffer, bufsize);
VERIFY_STATUS( sd_ble_gattc_read(_service->connHandle(), _chr.handle_value, 0), 0);
@@ -202,7 +205,10 @@ uint16_t BLEClientCharacteristic::write_resp(const void* data, uint16_t len)
{
VERIFY( _chr.char_props.write, 0 );
uint16_t const max_payload = Bluefruit.Gap.getMTU( _service->connHandle() ) - 3;
BLEConnection* conn = Bluefruit.Connection( _service->connHandle() );
VERIFY(conn, 0);
uint16_t const max_payload = conn->getMtu() - 3;
const bool long_write = (len > max_payload);
int32_t count = 0;
@@ -275,7 +281,10 @@ uint16_t BLEClientCharacteristic::write(const void* data, uint16_t len)
{
// VERIFY( _chr.char_props.write_wo_resp, 0 );
uint16_t const max_payload = Bluefruit.Gap.getMTU( _service->connHandle() ) - 3;
BLEConnection* conn = Bluefruit.Connection( _service->connHandle() );
VERIFY(conn, 0);
uint16_t const max_payload = conn->getMtu() - 3;
const uint8_t* u8data = (const uint8_t*) data;
// Break into multiple packet if needed
@@ -283,7 +292,7 @@ uint16_t BLEClientCharacteristic::write(const void* data, uint16_t len)
while( remaining )
{
// TODO only Write without response consume a TX buffer
if ( !Bluefruit.Gap.getWriteCmdPacket(_service->connHandle()) ) break;
if ( !conn->getWriteCmdPacket() ) break;
uint16_t packet_len = min16(max_payload, remaining);
@@ -326,7 +335,6 @@ uint16_t BLEClientCharacteristic::write32(int value)
return write32( (uint32_t) value);
}
void BLEClientCharacteristic::setNotifyCallback(notify_cb_t fp, bool useAdaCallback)
{
_notify_cb = fp;
@@ -354,7 +362,8 @@ bool BLEClientCharacteristic::writeCCCD(uint16_t value)
};
// TODO only Write without response consume a TX buffer
if ( !Bluefruit.Gap.getWriteCmdPacket(conn_handle) ) return NRF_ERROR_RESOURCES; //BLE_ERROR_NO_TX_PACKETS;
BLEConnection* conn = Bluefruit.Connection(conn_handle);
VERIFY( conn && conn->getWriteCmdPacket() );
VERIFY_STATUS( sd_ble_gattc_write(conn_handle, &param), false );
@@ -404,12 +413,7 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt)
// use AdaCallback or invoke directly
if (_use_ada_cb.notify)
{
uint8_t* data = (uint8_t*) rtos_malloc(hvx->len);
if (!data) return;
memcpy(data, hvx->data, hvx->len);
// data is free by callback
ada_callback(data, _notify_cb, this, data, hvx->len);
ada_callback(hvx->data, hvx->len, _notify_cb, this, hvx->data, hvx->len);
}else
{
_notify_cb(this, hvx->data, hvx->len);
@@ -423,12 +427,7 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt)
// use AdaCallback or invoke directly
if (_use_ada_cb.indicate)
{
uint8_t* data = (uint8_t*) rtos_malloc(hvx->len);
if (!data) return;
memcpy(data, hvx->data, hvx->len);
// data is free by callback
ada_callback(data, _indicate_cb, this, data, hvx->len);
ada_callback(hvx->data, hvx->len, _indicate_cb, this, hvx->data, hvx->len);
}else
{
_indicate_cb(this, hvx->data, hvx->len);
@@ -464,7 +463,9 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt)
}
else if ( wr_rsp->write_op == BLE_GATT_OP_PREP_WRITE_REQ)
{
uint16_t const max_payload = Bluefruit.Gap.getMTU( _service->connHandle() ) - 3;
BLEConnection* conn = Bluefruit.Connection( _service->connHandle() );
uint16_t const max_payload = conn->getMtu() - 3;
uint16_t packet_len = min16(_adamsg.remaining, max_payload-2);
if ( packet_len )
@@ -511,7 +512,9 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt)
case BLE_GATTC_EVT_READ_RSP:
{
uint16_t const max_payload = Bluefruit.Gap.getMTU( _service->connHandle() ) - 3;
BLEConnection* conn = Bluefruit.Connection( _service->connHandle() );
uint16_t const max_payload = conn->getMtu() - 3;
ble_gattc_evt_read_rsp_t* rd_rsp = (ble_gattc_evt_read_rsp_t*) &evt->evt.gattc_evt.params.read_rsp;
// Give up if failed (BLE_GATT_STATUS_ATTERR_INVALID_OFFSET usually)
@@ -91,21 +91,21 @@ class BLEClientCharacteristic
uint16_t write32_resp (int value);
/*------------- Notify -------------*/
bool writeCCCD (uint16_t value);
bool writeCCCD (uint16_t value);
bool enableNotify (void);
bool disableNotify (void);
bool enableNotify (void);
bool disableNotify (void);
bool enableIndicate (void);
bool disableIndicate (void);
bool enableIndicate (void);
bool disableIndicate (void);
/*------------- Callbacks -------------*/
void setNotifyCallback(notify_cb_t fp, bool useAdaCallback = true);
void setIndicateCallback(indicate_cb_t fp, bool useAdaCallback = true);
void setNotifyCallback(notify_cb_t fp, bool useAdaCallback = true);
void setIndicateCallback(indicate_cb_t fp, bool useAdaCallback = true);
/*------------- Internal usage -------------*/
void _assign(ble_gattc_char_t* gattc_chr);
bool _discoverDescriptor(uint16_t conn_handle, ble_gattc_handle_range_t hdl_range);
void _assign(ble_gattc_char_t* gattc_chr);
bool _discoverDescriptor(uint16_t conn_handle, ble_gattc_handle_range_t hdl_range);
private:
ble_gattc_char_t _chr;
@@ -123,7 +123,6 @@ class BLEClientCharacteristic
uint8_t indicate : 1;
} _use_ada_cb;
void _init (void);
void _eventHandler (ble_evt_t* event);
@@ -0,0 +1,462 @@
/**************************************************************************/
/*!
@file BLEConnection.cpp
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2019, Adafruit Industries (adafruit.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#include "bluefruit.h"
//--------------------------------------------------------------------+
// MACRO TYPEDEF CONSTANT ENUM DECLARATION
//--------------------------------------------------------------------+
BLEConnection::BLEConnection(uint16_t conn_hdl, ble_gap_evt_connected_t const* evt_connected, uint8_t hvn_qsize, uint8_t wrcmd_qsize)
{
_conn_hdl = conn_hdl;
_connected = true;
_mtu = BLE_GATT_ATT_MTU_DEFAULT;
_conn_interval = 0;
_peer_addr = evt_connected->peer_addr;
_role = evt_connected->role;
_hvn_sem = xSemaphoreCreateCounting(hvn_qsize, hvn_qsize);
_wrcmd_sem = xSemaphoreCreateCounting(wrcmd_qsize, wrcmd_qsize);
_paired = false;
_hvc_sem = NULL;
_hvc_received = false;
_pair_sem = NULL;
_ediv = 0xFFFF; // invalid ediv value
_bond_keys = NULL;
}
BLEConnection::~BLEConnection()
{
vSemaphoreDelete( _hvn_sem );
vSemaphoreDelete( _wrcmd_sem );
if ( _hvc_sem ) vSemaphoreDelete( _hvc_sem );
}
uint16_t BLEConnection::handle (void)
{
return _conn_hdl;
}
bool BLEConnection::connected(void)
{
return _connected;
}
bool BLEConnection::paired (void)
{
return _paired;
}
uint8_t BLEConnection::getRole (void)
{
return _role;
}
uint16_t BLEConnection::getMtu (void)
{
return _mtu;
}
uint16_t BLEConnection::getConnInterval(void)
{
return _conn_interval;
}
ble_gap_addr_t BLEConnection::getPeerAddr (void)
{
return _peer_addr;
}
uint16_t BLEConnection::getPeerName(char* buf, uint16_t bufsize)
{
return Bluefruit.Gatt.readCharByUuid(_conn_hdl, BLEUuid(BLE_UUID_GAP_CHARACTERISTIC_DEVICE_NAME), buf, bufsize);
}
static inline bool is_tx_power_valid(int8_t power)
{
#if defined(NRF52832_XXAA)
int8_t const accepted[] = { -40, -20, -16, -12, -8, -4, 0, 3, 4 };
#elif defined( NRF52840_XXAA)
int8_t const accepted[] = { -40, -20, -16, -12, -8, -4, 0, 2, 3, 4, 5, 6, 7, 8 };
#endif
for (uint32_t i=0; i<sizeof(accepted); i++)
{
if (accepted[i] == power) return true;
}
return false;
}
bool BLEConnection::setTxPower(int8_t power)
{
VERIFY(is_tx_power_valid(power));
VERIFY_STATUS(sd_ble_gap_tx_power_set(BLE_GAP_TX_POWER_ROLE_CONN, _conn_hdl, power), false);
return true;
}
bool BLEConnection::disconnect(void)
{
return ERROR_NONE == sd_ble_gap_disconnect(_conn_hdl, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
}
bool BLEConnection::monitorRssi(uint8_t threshold)
{
// number of samples is 3
VERIFY_STATUS(sd_ble_gap_rssi_start(_conn_hdl, threshold, 3), false);
return true;
}
int8_t BLEConnection::getRssi(void)
{
int8_t rssi;
uint8_t channel_idx;
VERIFY_STATUS(sd_ble_gap_rssi_get(_conn_hdl, &rssi, &channel_idx), 0);
(void) channel_idx;
return rssi;
}
void BLEConnection::stopRssi(void)
{
sd_ble_gap_rssi_stop(_conn_hdl);
}
bool BLEConnection::getHvnPacket (void)
{
return xSemaphoreTake(_hvn_sem, ms2tick(BLE_GENERIC_TIMEOUT));
}
bool BLEConnection::getWriteCmdPacket (void)
{
return xSemaphoreTake(_wrcmd_sem, ms2tick(BLE_GENERIC_TIMEOUT));
}
bool BLEConnection::storeCccd(void)
{
return bond_save_cccd( _role, _conn_hdl, _ediv);
}
bool BLEConnection::loadKeys(bond_keys_t* bkeys)
{
return bond_load_keys(_role, _ediv, bkeys);
}
bool BLEConnection::requestPairing(void)
{
// skip if already paired
if ( _paired ) return true;
ble_gap_sec_params_t sec_param = Bluefruit.getSecureParam();
// on-the-fly semaphore
_pair_sem = xSemaphoreCreateBinary();
if ( _role == BLE_GAP_ROLE_PERIPH )
{
VERIFY_STATUS( sd_ble_gap_authenticate(_conn_hdl, &sec_param ), false);
xSemaphoreTake(_pair_sem, portMAX_DELAY);
}
else
{
uint16_t cntr_ediv = 0xFFFF;
bond_keys_t bkeys;
// Check to see if we did bonded with current prph previously
// TODO currently only matches key using fixed address
if ( bond_find_cntr(&_peer_addr, &bkeys) )
{
cntr_ediv = bkeys.peer_enc.master_id.ediv;
LOG_LV2("BOND", "Load Keys from file " BOND_FNAME_CNTR, cntr_ediv);
VERIFY_STATUS( sd_ble_gap_encrypt(_conn_hdl, &bkeys.peer_enc.master_id, &bkeys.peer_enc.enc_info), false);
}else
{
VERIFY_STATUS( sd_ble_gap_authenticate(_conn_hdl, &sec_param ), false);
}
xSemaphoreTake(_pair_sem, portMAX_DELAY);
// Failed to pair using central stored keys, this happens when
// Prph delete bonds while we did not --> let's remove the obsolete keyfile and retry
if ( !_paired && (cntr_ediv != 0xffff) )
{
bond_remove_key(BLE_GAP_ROLE_CENTRAL, cntr_ediv);
// Re-try with a fresh session
VERIFY_STATUS( sd_ble_gap_authenticate(_conn_hdl, &sec_param ), false);
xSemaphoreTake(_pair_sem, portMAX_DELAY);
}
}
vSemaphoreDelete(_pair_sem);
_pair_sem = NULL;
return _paired;
}
bool BLEConnection::waitForIndicateConfirm(void)
{
// on the fly semaphore
_hvc_sem = xSemaphoreCreateBinary();
_hvc_received = false;
xSemaphoreTake(_hvc_sem, portMAX_DELAY);
vSemaphoreDelete(_hvc_sem);
_hvc_sem = NULL;
return _hvc_received;
}
void BLEConnection::_eventHandler(ble_evt_t* evt)
{
switch(evt->header.evt_id)
{
case BLE_GAP_EVT_DISCONNECTED:
// mark as disconnected
_connected = false;
break;
//--------------------------------------------------------------------+
/* First-time Pairing
* Connect -> SEC_PARAMS_REQUEST -> CONN_SEC_UPDATE -> AUTH_STATUS
* 1. Either we or peer initiate the process
* 2. Peer ask for Secure Parameter ( I/O Caps ) BLE_GAP_EVT_SEC_PARAMS_REQUEST
* 3. Pair Key exchange ( PIN code)
* 4. Connection is secured BLE_GAP_EVT_CONN_SEC_UPDATE
* 5. Long term Keys exchanged BLE_GAP_EVT_AUTH_STATUS
*
* Reconnect using bonded key
* Connect -> SEC_INFO_REQUEST -> CONN_SEC_UPDATE
* 1. Either we or peer initiate the process
* 2. Peer ask for Secure Info ( bond keys ) BLE_GAP_EVT_SEC_INFO_REQUEST
* 3. Connection is secured BLE_GAP_EVT_CONN_SEC_UPDATE
*/
//--------------------------------------------------------------------+
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
{
// Pairing in progress, Peer asking for our info
_bond_keys = (bond_keys_t*) rtos_malloc( sizeof(bond_keys_t));
VERIFY(_bond_keys, );
memclr(_bond_keys, sizeof(bond_keys_t));
_ediv = 0xFFFF; // invalid value for ediv
/* Step 1: Pairing/Bonding
* - Central supplies its parameters
* - We replies with our security parameters
*/
// ble_gap_sec_params_t* peer = &evt->evt.gap_evt.params.sec_params_request.peer_params;
COMMENT_OUT(
// Change security parameter according to authentication type
if ( _auth_type == BLE_GAP_AUTH_KEY_TYPE_PASSKEY)
{
sec_para.mitm = 1;
sec_para.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
}
)
ble_gap_sec_keyset_t keyset =
{
.keys_own = {
.p_enc_key = &_bond_keys->own_enc,
.p_id_key = NULL,
.p_sign_key = NULL,
.p_pk = NULL
},
.keys_peer = {
.p_enc_key = &_bond_keys->peer_enc,
.p_id_key = &_bond_keys->peer_id,
.p_sign_key = NULL,
.p_pk = NULL
}
};
ble_gap_sec_params_t sec_param = Bluefruit.getSecureParam();
VERIFY_STATUS(sd_ble_gap_sec_params_reply(_conn_hdl,
BLE_GAP_SEC_STATUS_SUCCESS,
_role == BLE_GAP_ROLE_PERIPH ? &sec_param : NULL,
&keyset),
);
}
break;
case BLE_GAP_EVT_AUTH_STATUS:
{
// Pairing process completed
ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status;
// Pairing succeeded --> save encryption keys ( Bonding )
if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status)
{
_paired = true;
_ediv = _bond_keys->own_enc.master_id.ediv;
bond_save_keys(_role, _conn_hdl, _bond_keys);
}else
{
PRINT_HEX(status->auth_status);
}
rtos_free(_bond_keys);
_bond_keys = NULL;
}
break;
case BLE_GAP_EVT_SEC_INFO_REQUEST:
{
// Peer asks for the stored keys.
// - load key and return if bonded previously.
// - Else return NULL --> Initiate key exchange
ble_gap_evt_sec_info_request_t* sec_req = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request;
bond_keys_t bkeys;
varclr(&bkeys);
if ( bond_load_keys(_role, sec_req->master_id.ediv, &bkeys) )
{
sd_ble_gap_sec_info_reply(_conn_hdl, &bkeys.own_enc.enc_info, &bkeys.peer_id.id_info, NULL);
_ediv = bkeys.own_enc.master_id.ediv;
} else
{
sd_ble_gap_sec_info_reply(_conn_hdl, NULL, NULL, NULL);
}
}
break;
case BLE_GAP_EVT_PASSKEY_DISPLAY:
{
// ble_gap_evt_passkey_display_t const* passkey_display = &evt->evt.gap_evt.params.passkey_display;
// PRINT_INT(passkey_display->match_request);
// PRINT_BUFFER(passkey_display->passkey, 6);
// sd_ble_gap_auth_key_reply
}
break;
case BLE_GAP_EVT_CONN_SEC_UPDATE:
{
const ble_gap_conn_sec_t* conn_sec = &evt->evt.gap_evt.params.conn_sec_update.conn_sec;
// Connection is secured (paired) if encryption level > 1
if ( !( conn_sec->sec_mode.sm == 1 && conn_sec->sec_mode.lv == 1) )
{
// Previously bonded --> secure by re-connection process --> Load & Set SysAttr (Apply Service Context)
// Else Init SysAttr (first bonded)
if ( !bond_load_cccd(_role, _conn_hdl, _ediv) )
{
sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0);
}
_paired = true;
}
if (_pair_sem) xSemaphoreGive(_pair_sem);
}
break;
//--------------------------------------------------------------------+
// GAP parameter negotiation
//--------------------------------------------------------------------+
case BLE_GAP_EVT_CONN_PARAM_UPDATE:
{
ble_gap_conn_params_t* param = &evt->evt.gap_evt.params.conn_param_update.conn_params;
_conn_interval = param->max_conn_interval;
LOG_LV2("GAP", "Conn Interval= %f", _conn_interval*1.25f);
}
break;
case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
{
uint16_t const max_mtu = Bluefruit.getMaxMtu(_role);
_mtu = minof(evt->evt.gatts_evt.params.exchange_mtu_request.client_rx_mtu, max_mtu);
VERIFY_STATUS( sd_ble_gatts_exchange_mtu_reply(_conn_hdl, _mtu), );
LOG_LV1("GAP", "ATT MTU is changed to %d", _mtu);
}
break;
//--------------------------------------------------------------------+
//
//--------------------------------------------------------------------+
case BLE_GATTS_EVT_HVN_TX_COMPLETE:
for(uint8_t i=0; i<evt->evt.gatts_evt.params.hvn_tx_complete.count; i++) xSemaphoreGive(_hvn_sem);
break;
case BLE_GATTC_EVT_WRITE_CMD_TX_COMPLETE:
for(uint8_t i=0; i<evt->evt.gattc_evt.params.write_cmd_tx_complete.count; i++) xSemaphoreGive(_wrcmd_sem);
break;
case BLE_GATTS_EVT_HVC:
{
LOG_LV2("GATTS", "Confirm received handle = 0x%04X", evt->evt.gatts_evt.params.hvc.handle);
_hvc_received = true;
if ( _hvc_sem ) xSemaphoreGive(_hvc_sem);
}
break;
case BLE_GATTS_EVT_TIMEOUT:
{
uint8_t timeout_src = evt->evt.gatts_evt.params.timeout.src;
LOG_LV2("GATTS", "Timeout Source = %d", timeout_src);
if (BLE_GATT_TIMEOUT_SRC_PROTOCOL == timeout_src)
{
_hvc_received = false;
if ( _hvc_sem ) xSemaphoreGive(_hvc_sem);
}
}
break;
case BLE_GATTS_EVT_SYS_ATTR_MISSING:
sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0);
break;
default: break;
}
}
@@ -0,0 +1,107 @@
/**************************************************************************/
/*!
@file BLEConnection.h
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2019, Adafruit Industries (adafruit.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#ifndef BLECONNECTION_H_
#define BLECONNECTION_H_
#include <Arduino.h>
#include "bluefruit_common.h"
#include "utility/bonding.h"
class BLEConnection
{
private:
uint16_t _conn_hdl;
uint16_t _mtu;
uint16_t _conn_interval;
uint16_t _ediv;
uint8_t _role;
bool _connected;
bool _paired;
bool _hvc_received;
ble_gap_addr_t _peer_addr;
SemaphoreHandle_t _hvn_sem;
SemaphoreHandle_t _wrcmd_sem;
// On-demand semaphore/data that are created on the fly
SemaphoreHandle_t _hvc_sem;
SemaphoreHandle_t _pair_sem;
bond_keys_t* _bond_keys; // Shared keys with bonded device, size ~ 80 bytes
public:
BLEConnection(uint16_t conn_hdl, ble_gap_evt_connected_t const * evt_connected, uint8_t hvn_qsize, uint8_t wrcmd_qsize);
virtual ~BLEConnection();
uint16_t handle(void);
bool connected(void);
bool paired(void);
uint8_t getRole(void);
uint16_t getMtu (void);
uint16_t getConnInterval(void);
ble_gap_addr_t getPeerAddr(void);
uint16_t getPeerName(char* buf, uint16_t bufsize);
bool disconnect(void);
bool setTxPower(int8_t power); // set power for this connection
bool monitorRssi(uint8_t threshold = BLE_GAP_RSSI_THRESHOLD_INVALID);
int8_t getRssi(void);
void stopRssi(void);
bool getHvnPacket(void);
bool getWriteCmdPacket(void);
bool waitForIndicateConfirm(void);
bool requestPairing(void);
bool storeCccd(void);
bool loadKeys(bond_keys_t* bkeys);
/*------------------------------------------------------------------*/
/* INTERNAL USAGE ONLY
* Although declare as public, it is meant to be invoked by internal code.
*------------------------------------------------------------------*/
void _eventHandler(ble_evt_t* evt);
};
#endif /* BLECONNECTION_H_ */
@@ -196,7 +196,7 @@ uint16_t BLEDiscovery::_discoverDescriptor(uint16_t conn_handle, ble_gattc_evt_d
}
void BLEDiscovery::_event_handler(ble_evt_t* evt)
void BLEDiscovery::_eventHandler(ble_evt_t* evt)
{
ble_gattc_evt_t* gattc = &evt->evt.gattc_evt;
+1 -1
View File
@@ -52,7 +52,7 @@ class BLEDiscovery
AdaMsg _adamsg;
bool _begun;
void _event_handler(ble_evt_t* evt);
void _eventHandler(ble_evt_t* evt);
public:
BLEDiscovery(void);
-501
View File
@@ -1,501 +0,0 @@
/**************************************************************************/
/*!
@file BLEGap.cpp
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2018, Adafruit Industries (adafruit.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#include "bluefruit.h"
BLEGap::BLEGap(void)
{
memclr(_peers, sizeof(_peers));
_cfg_prph.mtu_max = BLE_GATT_ATT_MTU_DEFAULT;
_cfg_central.mtu_max = BLE_GATT_ATT_MTU_DEFAULT;
_cfg_prph.event_len = BLE_GAP_EVENT_LENGTH_DEFAULT;
_cfg_prph.hvn_tx_qsize = BLE_GATTS_HVN_TX_QUEUE_SIZE_DEFAULT;
_cfg_prph.wr_cmd_qsize = BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT;
_cfg_central.event_len = BLE_GAP_EVENT_LENGTH_DEFAULT;
_cfg_central.hvn_tx_qsize = BLE_GATTS_HVN_TX_QUEUE_SIZE_DEFAULT;
_cfg_central.wr_cmd_qsize = BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT;
_sec_param = (ble_gap_sec_params_t)
{
.bond = 1,
.mitm = 0,
.lesc = 0,
.keypress = 0,
.io_caps = BLE_GAP_IO_CAPS_NONE,
.oob = 0,
.min_key_size = 7,
.max_key_size = 16,
.kdist_own = { .enc = 1, .id = 1},
.kdist_peer = { .enc = 1, .id = 1},
};
}
void BLEGap::configPrphConn(uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize)
{
_cfg_prph.mtu_max = maxof(mtu_max, BLE_GATT_ATT_MTU_DEFAULT);
_cfg_prph.event_len = maxof(event_len, BLE_GAP_EVENT_LENGTH_MIN);
_cfg_prph.hvn_tx_qsize = hvn_qsize;
_cfg_prph.wr_cmd_qsize = wrcmd_qsize;
}
void BLEGap::configCentralConn(uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize)
{
_cfg_central.mtu_max = maxof(mtu_max, BLE_GATT_ATT_MTU_DEFAULT);
_cfg_central.event_len = maxof(event_len, BLE_GAP_EVENT_LENGTH_MIN);
_cfg_central.hvn_tx_qsize = hvn_qsize;
_cfg_central.wr_cmd_qsize = wrcmd_qsize;
}
uint16_t BLEGap::getMaxMtuByConnCfg(uint8_t conn_cfg)
{
return (conn_cfg == CONN_CFG_PERIPHERAL) ? _cfg_prph.mtu_max : _cfg_central.mtu_max;
}
uint16_t BLEGap::getMaxMtu (uint8_t conn_hdl)
{
return (getRole(conn_hdl) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.mtu_max : _cfg_central.mtu_max;
}
uint8_t BLEGap::getHvnQueueSize (uint8_t conn_hdl)
{
return (getRole(conn_hdl) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.hvn_tx_qsize : _cfg_central.hvn_tx_qsize;
}
uint8_t BLEGap::getWriteCmdQueueSize (uint8_t conn_hdl)
{
return (getRole(conn_hdl) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.wr_cmd_qsize : _cfg_central.wr_cmd_qsize;
}
/**
* Get current Mac address and its type
* @param mac address
* @return Address type e.g BLE_GAP_ADDR_TYPE_RANDOM_STATIC
*/
uint8_t BLEGap::getAddr(uint8_t mac[6])
{
ble_gap_addr_t addr;
sd_ble_gap_addr_get(&addr);
memcpy(mac, addr.addr, 6);
return addr.addr_type;
}
/**
* Set the MAC address
* @param mac Bluetooth MAC Address
* @param type Must be either BLE_GAP_ADDR_TYPE_PUBLIC or BLE_GAP_ADDR_TYPE_RANDOM_STATIC
* @return true if success
*/
bool BLEGap::setAddr(uint8_t mac[6], uint8_t type)
{
ble_gap_addr_t addr;
addr.addr_type = type;
memcpy(addr.addr, mac, 6);
VERIFY_STATUS( sd_ble_gap_addr_set(&addr), false );
return true;
}
bool BLEGap::connected(uint16_t conn_hdl)
{
return _peers[conn_hdl].connected;
}
bool BLEGap::paired(uint16_t conn_hdl)
{
return _peers[conn_hdl].paired;
}
bool BLEGap::requestPairing(uint16_t conn_hdl)
{
gap_peer_t* peer = &_peers[conn_hdl];
// skip if already paired
if ( peer->paired ) return true;
uint16_t cntr_ediv = 0xFFFF;
if ( peer->role == BLE_GAP_ROLE_CENTRAL )
{
// Check to see if we did bonded with current prph previously
bond_keys_t bkeys;
if ( bond_find_cntr(&peer->addr, &bkeys) )
{
cntr_ediv = bkeys.peer_enc.master_id.ediv;
LOG_LV2("BOND", "Load Keys from file " BOND_FNAME_CNTR, cntr_ediv);
VERIFY_STATUS( sd_ble_gap_encrypt(conn_hdl, &bkeys.peer_enc.master_id, &bkeys.peer_enc.enc_info), false);
}else
{
VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false);
}
}else
{
VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false);
}
// Wait for pairing process using on-the-fly semaphore
peer->pair_sem = xSemaphoreCreateBinary();
xSemaphoreTake(peer->pair_sem, portMAX_DELAY);
// Failed to pair using central stored keys, this happens when
// Prph delete bonds while we did not --> let's remove the obsolete keyfile and move on
if ( !peer->paired && (cntr_ediv != 0xffff) )
{
bond_remove_key(BLE_GAP_ROLE_CENTRAL, cntr_ediv);
// Re-try with a fresh session
VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false);
xSemaphoreTake(peer->pair_sem, portMAX_DELAY);
}
vSemaphoreDelete(peer->pair_sem);
peer->pair_sem = NULL;
return peer->paired;
}
uint8_t BLEGap::getRole(uint16_t conn_hdl)
{
return _peers[conn_hdl].role;
}
uint8_t BLEGap::getPeerAddr(uint16_t conn_hdl, uint8_t addr[6])
{
memcpy(addr, _peers[conn_hdl].addr.addr, BLE_GAP_ADDR_LEN);
return _peers[conn_hdl].addr.addr_type;
}
ble_gap_addr_t BLEGap::getPeerAddr(uint16_t conn_hdl)
{
return _peers[conn_hdl].addr;
}
bool BLEGap::getHvnPacket(uint16_t conn_hdl)
{
VERIFY( (conn_hdl < BLE_MAX_CONN) && (_peers[conn_hdl].hvn_tx_sem != NULL) );
return xSemaphoreTake(_peers[conn_hdl].hvn_tx_sem, ms2tick(BLE_GENERIC_TIMEOUT));
}
bool BLEGap::getWriteCmdPacket(uint16_t conn_hdl)
{
VERIFY( (conn_hdl < BLE_MAX_CONN) && (_peers[conn_hdl].wrcmd_tx_sem != NULL) );
return xSemaphoreTake(_peers[conn_hdl].wrcmd_tx_sem, ms2tick(BLE_GENERIC_TIMEOUT));
}
uint16_t BLEGap::getMTU (uint16_t conn_hdl)
{
return _peers[conn_hdl].att_mtu;
}
uint16_t BLEGap::getPeerName(uint16_t conn_hdl, char* buf, uint16_t bufsize)
{
return Bluefruit.Gatt.readCharByUuid(conn_hdl, BLEUuid(BLE_UUID_GAP_CHARACTERISTIC_DEVICE_NAME), buf, bufsize);
}
/**
* Event handler
* @param evt
*/
void BLEGap::_eventHandler(ble_evt_t* evt)
{
// conn handle has fixed offset regardless of event type
const uint16_t conn_hdl = evt->evt.common_evt.conn_handle;
gap_peer_t* peer = (conn_hdl == BLE_CONN_HANDLE_INVALID) ? NULL : &_peers[conn_hdl];
switch(evt->header.evt_id)
{
case BLE_GAP_EVT_CONNECTED:
{
ble_gap_evt_connected_t const * para = &evt->evt.gap_evt.params.connected;
peer->connected = true;
peer->role = para->role;
peer->addr = para->peer_addr;
peer->att_mtu = BLE_GATT_ATT_MTU_DEFAULT;
// Init transmission buffer for notification
peer->hvn_tx_sem = xSemaphoreCreateCounting(getHvnQueueSize(conn_hdl), getHvnQueueSize(conn_hdl));
peer->wrcmd_tx_sem = xSemaphoreCreateCounting(getWriteCmdQueueSize(conn_hdl), getWriteCmdQueueSize(conn_hdl));
LOG_LV2("GAP", "Conn Interval= %f", para->conn_params.min_conn_interval*1.25f);
}
break;
case BLE_GAP_EVT_DISCONNECTED:
{
ble_gap_evt_disconnected_t const* para = &evt->evt.gap_evt.params.disconnected;
// mark as disconnected, but keep the role for sub sequence event handler
peer->connected = peer->paired = false;
vSemaphoreDelete( peer->hvn_tx_sem );
peer->hvn_tx_sem = NULL;
vSemaphoreDelete( peer->wrcmd_tx_sem );
peer->wrcmd_tx_sem = NULL;
}
break;
case BLE_GAP_EVT_CONN_PARAM_UPDATE:
{
ble_gap_conn_params_t* param = &evt->evt.gap_evt.params.conn_param_update.conn_params;
LOG_LV2("GAP", "Conn Interval= %f", param->min_conn_interval*1.25f);
}
break;
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
{
// Pairing in progress, Peer asking for our info
peer->bond_keys = (bond_keys_t*) rtos_malloc( sizeof(bond_keys_t));
VERIFY(peer->bond_keys, );
bond_keys_t* bkeys = peer->bond_keys;
memclr(bkeys, sizeof(bond_keys_t));
peer->ediv = 0xFFFF; // invalid value for ediv
/* Step 1: Pairing/Bonding
* - Central supplies its parameters
* - We replies with our security parameters
*/
// ble_gap_sec_params_t* peer = &evt->evt.gap_evt.params.sec_params_request.peer_params;
COMMENT_OUT(
// Change security parameter according to authentication type
if ( _auth_type == BLE_GAP_AUTH_KEY_TYPE_PASSKEY)
{
sec_para.mitm = 1;
sec_para.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
}
)
ble_gap_sec_keyset_t keyset =
{
.keys_own = {
.p_enc_key = &bkeys->own_enc,
.p_id_key = NULL,
.p_sign_key = NULL,
.p_pk = NULL
},
.keys_peer = {
.p_enc_key = &bkeys->peer_enc,
.p_id_key = &bkeys->peer_id,
.p_sign_key = NULL,
.p_pk = NULL
}
};
VERIFY_STATUS(sd_ble_gap_sec_params_reply(conn_hdl,
BLE_GAP_SEC_STATUS_SUCCESS,
peer->role == BLE_GAP_ROLE_PERIPH ? &_sec_param : NULL,
&keyset),
);
}
break;
case BLE_GAP_EVT_AUTH_STATUS:
{
// Pairing process completed
ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status;
// Pairing succeeded --> save encryption keys ( Bonding )
if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status)
{
peer->paired = true;
peer->ediv = peer->bond_keys->own_enc.master_id.ediv;
bond_save_keys(peer->role, conn_hdl, peer->bond_keys);
}else
{
PRINT_HEX(status->auth_status);
}
rtos_free(peer->bond_keys);
peer->bond_keys = NULL;
}
break;
case BLE_GAP_EVT_SEC_INFO_REQUEST:
{
// Central ask for the stored keys.
// - load key and return if bonded previously.
// - Else return NULL --> Initiate key exchange
ble_gap_evt_sec_info_request_t* sec_req = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request;
bond_keys_t bkeys;
varclr(&bkeys);
if ( bond_load_keys(peer->role, sec_req->master_id.ediv, &bkeys) )
{
sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, &bkeys.own_enc.enc_info, &bkeys.peer_id.id_info, NULL);
peer->ediv = bkeys.own_enc.master_id.ediv;
} else
{
sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, NULL, NULL, NULL);
}
}
break;
case BLE_GAP_EVT_CONN_SEC_UPDATE:
{
const ble_gap_conn_sec_t* conn_sec = &evt->evt.gap_evt.params.conn_sec_update.conn_sec;
// Connection is secured (paired)
// Occurs if bonded + reconnection, or we initiate the pairing process
if ( !( conn_sec->sec_mode.sm == 1 && conn_sec->sec_mode.lv == 1) )
{
// Previously bonded --> secure by re-connection process --> Load & Set SysAttr (Apply Service Context)
// Else Init SysAttr (first bonded)
if ( !bond_load_cccd(peer->role, conn_hdl, peer->ediv) )
{
sd_ble_gatts_sys_attr_set(conn_hdl, NULL, 0, 0);
}
peer->paired = true;
}
if (peer->pair_sem) xSemaphoreGive(peer->pair_sem);
}
break;
case BLE_GAP_EVT_PASSKEY_DISPLAY:
{
// ble_gap_evt_passkey_display_t const* passkey_display = &evt->evt.gap_evt.params.passkey_display;
// PRINT_INT(passkey_display->match_request);
// PRINT_BUFFER(passkey_display->passkey, 6);
// sd_ble_gap_auth_key_reply
}
break;
case BLE_GATTS_EVT_HVN_TX_COMPLETE:
if ( peer->hvn_tx_sem )
{
for(uint8_t i=0; i<evt->evt.gatts_evt.params.hvn_tx_complete.count; i++)
{
xSemaphoreGive(peer->hvn_tx_sem);
}
}
break;
case BLE_GATTC_EVT_WRITE_CMD_TX_COMPLETE:
if ( peer->wrcmd_tx_sem )
{
for(uint8_t i=0; i<evt->evt.gattc_evt.params.write_cmd_tx_complete.count; i++)
{
xSemaphoreGive(peer->wrcmd_tx_sem);
}
}
break;
case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
{
ble_gap_data_length_params_t* param = &evt->evt.gap_evt.params.data_length_update_request.peer_params;
LOG_LV2("GAP", "Data Length Req is (tx, rx) octets = (%d, %d), (tx, rx) time = (%d, %d) us",
param->max_tx_octets, param->max_rx_octets, param->max_tx_time_us, param->max_rx_time_us);
// Let Softdevice decide the data length
VERIFY_STATUS( sd_ble_gap_data_length_update(conn_hdl, NULL, NULL), );
}
break;
case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
{
ble_gap_data_length_params_t* datalen = &evt->evt.gap_evt.params.data_length_update.effective_params;
LOG_LV2("GAP", "Data Length is (tx, rx) octets = (%d, %d), (tx, rx) time = (%d, %d) us",
datalen->max_tx_octets, datalen->max_rx_octets, datalen->max_tx_time_us, datalen->max_rx_time_us);
}
break;
case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
{
ble_gap_phys_t* req_phy = &evt->evt.gap_evt.params.phy_update_request.peer_preferred_phys;
#if CFG_DEBUG >= 1
char const *phy_str[] = { "Auto", "1 Mbps", "2 Mbps", "Coded" };
LOG_LV1("GAP", "PHY request tx: %s, rx: %s", phy_str[req_phy->tx_phys], phy_str[req_phy->rx_phys]);
#endif
// Tell SoftDevice to choose PHY automatically
ble_gap_phys_t phy = { BLE_GAP_PHY_AUTO, BLE_GAP_PHY_AUTO };
(void) sd_ble_gap_phy_update(conn_hdl, &phy);
}
break;
case BLE_GAP_EVT_PHY_UPDATE:
{
ble_gap_evt_phy_update_t* active_phy = &evt->evt.gap_evt.params.phy_update;
#if CFG_DEBUG >= 1
if ( active_phy->status != BLE_HCI_STATUS_CODE_SUCCESS )
{
LOG_LV1("GAP", "Failed HCI status = 0x%02X", active_phy->status);
}else
{
char const *phy_str[] = { "Auto", "1 Mbps", "2 Mbps", "Coded" };
LOG_LV1("GAP", "PHY active tx: %s, rx: %s", phy_str[active_phy->tx_phy], phy_str[active_phy->rx_phy]);
}
#endif
}
break;
case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
{
peer->att_mtu = minof(evt->evt.gatts_evt.params.exchange_mtu_request.client_rx_mtu, getMaxMtu(conn_hdl));
VERIFY_STATUS( sd_ble_gatts_exchange_mtu_reply(conn_hdl, peer->att_mtu), );
LOG_LV1("GAP", "ATT MTU is changed to %d", peer->att_mtu);
}
break;
default: break;
}
}
-132
View File
@@ -1,132 +0,0 @@
/**************************************************************************/
/*!
@file BLEGap.h
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2018, Adafruit Industries (adafruit.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#ifndef BLEGAP_H_
#define BLEGAP_H_
#include <Arduino.h>
#include "bluefruit_common.h"
#include "BLEUuid.h"
#include "utility/bonding.h"
enum
{
CONN_CFG_PERIPHERAL = 1,
CONN_CFG_CENTRAL = 2,
};
class BLEGap
{
public:
typedef void (*connect_callback_t ) (uint16_t conn_hdl);
typedef void (*disconnect_callback_t ) (uint16_t conn_hdl, uint8_t reason);
BLEGap(void);
uint8_t getAddr (uint8_t mac[6]);
bool setAddr (uint8_t mac[6], uint8_t type);
// bool setPrivacy (); sd_ble_gap_privacy_set()
bool connected (uint16_t conn_hdl);
bool paired (uint16_t conn_hdl);
bool requestPairing (uint16_t conn_hdl);
uint8_t getRole (uint16_t conn_hdl);
uint8_t getPeerAddr (uint16_t conn_hdl, uint8_t addr[6]);
ble_gap_addr_t getPeerAddr (uint16_t conn_hdl);
uint16_t getPeerName (uint16_t conn_hdl, char* buf, uint16_t bufsize);
uint16_t getMTU (uint16_t conn_hdl);
uint16_t getMaxMtuByConnCfg (uint8_t conn_cfg);
uint16_t getMaxMtu (uint8_t conn_hdl);
uint8_t getHvnQueueSize (uint8_t conn_hdl);
uint8_t getWriteCmdQueueSize (uint8_t conn_hdl);
bool getHvnPacket (uint16_t conn_hdl);
bool getWriteCmdPacket (uint16_t conn_hdl);
void configPrphConn (uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize);
void configCentralConn (uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize);
/*------------------------------------------------------------------*/
/* INTERNAL USAGE ONLY
* Although declare as public, it is meant to be invoked by internal
* code. User should not call these directly
*------------------------------------------------------------------*/
void _eventHandler(ble_evt_t* evt);
// Array of TX Packet semaphore, indexed by connection handle
// Peer info where conn_hdl serves as index
typedef struct {
bool connected;
bool paired;
uint8_t role;
uint16_t att_mtu;
ble_gap_addr_t addr;
uint16_t ediv;
bond_keys_t* bond_keys; // Shared keys with bonded device, size ~ 80 bytes
SemaphoreHandle_t hvn_tx_sem;
SemaphoreHandle_t wrcmd_tx_sem;
bool hvc_received;
// On-demand semaphore that are created on the fly
SemaphoreHandle_t hvc_sem;
SemaphoreHandle_t pair_sem;
} gap_peer_t;
gap_peer_t* _get_peer(uint16_t conn_hdl) { return &_peers[conn_hdl]; }
private:
struct {
uint16_t mtu_max;
uint8_t event_len;
uint8_t hvn_tx_qsize;
uint8_t wr_cmd_qsize;
} _cfg_prph, _cfg_central;
gap_peer_t _peers[BLE_MAX_CONN];
ble_gap_sec_params_t _sec_param;
friend class AdafruitBluefruit;
};
#endif /* BLEGAP_H_ */
+45 -87
View File
@@ -50,10 +50,11 @@ uint16_t BLEGatt::readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffe
int32_t count = 0;
ble_gattc_handle_range_t hdl_range = { .start_handle = start_hdl, .end_handle = end_hdl };
BLEConnection* conn = Bluefruit.Connection(conn_hdl);
while( _adamsg.isWaiting() )
{
// TODO multiple peripherals
delay( Bluefruit.connInterval() );
delay( conn->getConnInterval() );
}
_adamsg.begin(true);
@@ -75,95 +76,73 @@ uint16_t BLEGatt::readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffe
return (count < 0) ? 0 : count;
}
bool BLEGatt::waitForIndicateConfirm(uint16_t conn_hdl)
{
BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(conn_hdl);
// hvi confirm semaphore is created on the fly
peer->hvc_sem = xSemaphoreCreateBinary();
xSemaphoreTake(peer->hvc_sem, portMAX_DELAY);
vSemaphoreDelete(peer->hvc_sem);
peer->hvc_sem = NULL;
return peer->hvc_received;
}
void BLEGatt::_eventHandler(ble_evt_t* evt)
{
// conn handle has fixed offset regardless of event type
const uint16_t evt_conn_hdl = evt->evt.common_evt.conn_handle;
const uint16_t evt_id = evt->header.evt_id;
BLEConnection* conn = Bluefruit.Connection(evt_conn_hdl);
/*------------- Server service -------------*/
// TODO multiple peripherals
// if ( evt_conn_hdl == Bluefruit.connHandle() )
if ( evt_id == BLE_GAP_EVT_DISCONNECTED || evt_id == BLE_GAP_EVT_CONNECTED )
{
if ( evt_id == BLE_GAP_EVT_DISCONNECTED || evt_id == BLE_GAP_EVT_CONNECTED )
for(uint8_t i=0; i<_server.svc_count; i++)
{
for(uint8_t i=0; i<_server.svc_count; i++)
if ( evt_id == BLE_GAP_EVT_DISCONNECTED )
{
if ( evt_id == BLE_GAP_EVT_DISCONNECTED )
{
_server.svc_list[i]->_disconnect_cb();
}else
{
_server.svc_list[i]->_connect_cb();
}
_server.svc_list[i]->svc_disconnect_hdl(evt_conn_hdl);
}else
{
_server.svc_list[i]->svc_connect_hdl(evt_conn_hdl);
}
}
}
/*------------- Server Characteristics -------------*/
// TODO multiple prph connection
if ( evt_conn_hdl == Bluefruit.connHandle() )
for(uint8_t i=0; i<_server.chr_count; i++)
{
for(uint8_t i=0; i<_server.chr_count; i++)
BLECharacteristic* chr = _server.chr_list[i];
uint16_t req_handle = BLE_GATT_HANDLE_INVALID;
// BLE_GATTS_OP_EXEC_WRITE_REQ_NOW has no handle, uuid only command op
bool exec_write_now = false;
switch (evt_id)
{
BLECharacteristic* chr = _server.chr_list[i];
uint16_t req_handle = BLE_GATT_HANDLE_INVALID;
// BLE_GATTS_OP_EXEC_WRITE_REQ_NOW has no handle, uuid only command op
bool exec_write_now = false;
switch (evt_id)
case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
{
case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
{
// Handle has the same offset for read & write request
req_handle = evt->evt.gatts_evt.params.authorize_request.request.read.handle;
// Handle has the same offset for read & write request
req_handle = evt->evt.gatts_evt.params.authorize_request.request.read.handle;
if ( evt->evt.gatts_evt.params.authorize_request.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE )
if ( evt->evt.gatts_evt.params.authorize_request.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE )
{
ble_gatts_evt_write_t * wr_req = &evt->evt.gatts_evt.params.authorize_request.request.write;
if ( wr_req->op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW )
{
ble_gatts_evt_write_t * wr_req = &evt->evt.gatts_evt.params.authorize_request.request.write;
if ( wr_req->op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW )
{
exec_write_now = true;
}
exec_write_now = true;
}
}
break;
case BLE_GATTS_EVT_WRITE:
req_handle = evt->evt.gatts_evt.params.write.handle;
break;
default: break;
}
break;
// invoke characteristic handler if matched
if ( exec_write_now ||
((req_handle != BLE_GATT_HANDLE_INVALID) && (req_handle == chr->handles().value_handle || req_handle == chr->handles().cccd_handle)) )
case BLE_GATTS_EVT_WRITE:
req_handle = evt->evt.gatts_evt.params.write.handle;
break;
default: break;
}
// invoke characteristic handler if matched
if ( exec_write_now ||
((req_handle != BLE_GATT_HANDLE_INVALID) && (req_handle == chr->handles().value_handle || req_handle == chr->handles().cccd_handle)) )
{
chr->_eventHandler(evt);
// Save CCCD if paired
if ( conn->paired() && (evt_id == BLE_GATTS_EVT_WRITE) && (req_handle == chr->handles().cccd_handle) )
{
chr->_eventHandler(evt);
// Save CCCD if paired
if ( Bluefruit.connPaired() && (evt_id == BLE_GATTS_EVT_WRITE) && (req_handle == chr->handles().cccd_handle) )
{
BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl);
bond_save_cccd( peer->role, evt_conn_hdl, peer->ediv);
}
conn->storeCccd();
}
}
}
@@ -244,27 +223,6 @@ void BLEGatt::_eventHandler(ble_evt_t* evt)
}
break;
case BLE_GATTS_EVT_HVC:
{
LOG_LV2("GATTS", "Confirm received handle = 0x%04X", evt->evt.gatts_evt.params.hvc.handle);
BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl);
if ( peer->hvc_sem ) xSemaphoreGive(peer->hvc_sem);
peer->hvc_received = true;
}
break;
case BLE_GATTS_EVT_TIMEOUT:
{
LOG_LV2("GATTS", "Timeout Source = %d", evt->evt.gatts_evt.params.timeout.src);
BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl);
if ( peer->hvc_sem ) xSemaphoreGive(peer->hvc_sem);
peer->hvc_received = false;
}
break;
default: break;
}
}
-2
View File
@@ -60,8 +60,6 @@ class BLEGatt
uint16_t readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffer, uint16_t bufsize, uint16_t start_hdl = 1, uint16_t end_hdl = 0xffff);
bool waitForIndicateConfirm(uint16_t conn_hdl);
/*------------------------------------------------------------------*/
/* INTERNAL USAGE ONLY
* Although declare as public, it is meant to be invoked by internal
+164
View File
@@ -0,0 +1,164 @@
/**************************************************************************/
/*!
@file BLEPeriph.cpp
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2019, Adafruit Industries (adafruit.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#include "bluefruit.h"
// Constructor
BLEPeriph::BLEPeriph(void)
{
_connect_cb = NULL;
_disconnect_cb = NULL;
_ppcp = ((ble_gap_conn_params_t) {
.min_conn_interval = BLE_GAP_CONN_MIN_INTERVAL_DFLT,
.max_conn_interval = BLE_GAP_CONN_MAX_INTERVAL_DFLT,
.slave_latency = 0,
.conn_sup_timeout = BLE_GAP_CONN_SUPERVISION_TIMEOUT_MS / 10 // in 10ms unit
});
}
bool BLEPeriph::begin(void)
{
// Peripheral Preferred Connection Parameters
VERIFY_STATUS(sd_ble_gap_ppcp_set(&_ppcp), false);
VERIFY_STATUS( sd_ble_gap_appearance_set(BLE_APPEARANCE_UNKNOWN), false );
return true;
}
bool BLEPeriph::connected (uint16_t conn_hdl)
{
BLEConnection* conn = Bluefruit.Connection(conn_hdl);
return conn && conn->connected() && (conn->getRole() == BLE_GAP_ROLE_PERIPH);
}
uint8_t BLEPeriph::connected (void)
{
uint8_t count = 0;
for (uint16_t c=0; c<BLE_MAX_CONNECTION; c++)
{
if ( this->connected(c) ) count++;
}
return count;
}
bool BLEPeriph::setConnInterval (uint16_t min, uint16_t max)
{
_ppcp.min_conn_interval = min;
_ppcp.max_conn_interval = max;
VERIFY_STATUS( sd_ble_gap_ppcp_set(&_ppcp), false);
return true;
}
bool BLEPeriph::setConnIntervalMS (uint16_t min_ms, uint16_t max_ms)
{
return setConnInterval( MS100TO125(min_ms), MS100TO125(max_ms) );
}
bool BLEPeriph::setConnSupervisionTimeout(uint16_t timeout)
{
_ppcp.conn_sup_timeout = timeout;
VERIFY_STATUS( sd_ble_gap_ppcp_set(&_ppcp), false);
return true;
}
bool BLEPeriph::setConnSupervisionTimeoutMS(uint16_t timeout_ms)
{
return setConnSupervisionTimeout(timeout_ms / 10); // 10ms unit
}
void BLEPeriph::setConnectCallback( ble_connect_callback_t fp )
{
_connect_cb = fp;
}
void BLEPeriph::setDisconnectCallback( ble_disconnect_callback_t fp )
{
_disconnect_cb = fp;
}
void BLEPeriph::_eventHandler(ble_evt_t* evt)
{
uint16_t const conn_hdl = evt->evt.common_evt.conn_handle;
switch ( evt->header.evt_id )
{
case BLE_GAP_EVT_CONNECTED:
{
ble_gap_evt_connected_t* para = &evt->evt.gap_evt.params.connected;
if (para->role == BLE_GAP_ROLE_PERIPH)
{
// Connection interval set by Central is out of preferred range
// Try to negotiate with Central using our preferred values
if ( !is_within(_ppcp.min_conn_interval, para->conn_params.min_conn_interval, _ppcp.max_conn_interval) )
{
VERIFY_STATUS( sd_ble_gap_conn_param_update(conn_hdl, &_ppcp), );
}
}
}
break;
case BLE_GAP_EVT_DISCONNECTED:
break;
default: break;
}
}
void BLEPeriph::printInfo(void)
{
char const * title_fmt = "%-16s: ";
Serial.printf(title_fmt, "Conn Intervals");
Serial.printf("min = %.2f ms, ", _ppcp.min_conn_interval*1.25f);
Serial.printf("max = %.2f ms", _ppcp.max_conn_interval*1.25f);
Serial.println();
Serial.printf(title_fmt, "Conn Timeout");
Serial.printf("%.2f ms", _ppcp.conn_sup_timeout*10.0f);
Serial.println();
}
+79
View File
@@ -0,0 +1,79 @@
/**************************************************************************/
/*!
@file BLEPeriph.h
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2019, Adafruit Industries (adafruit.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#ifndef BLEPERIPH_H_
#define BLEPERIPH_H_
#include <Arduino.h>
#include "bluefruit_common.h"
class BLEPeriph
{
public:
BLEPeriph(void);
bool begin(void);
bool connected(uint16_t conn_hdl); // Connected as prph to this connection
uint8_t connected(void); // Number of connected as peripherals
bool setConnInterval (uint16_t min, uint16_t max);
bool setConnIntervalMS (uint16_t min_ms, uint16_t max_ms);
bool setConnSupervisionTimeout(uint16_t timeout);
bool setConnSupervisionTimeoutMS(uint16_t timeout_ms);
//------------- Callbacks -------------//
void setConnectCallback ( ble_connect_callback_t fp);
void setDisconnectCallback( ble_disconnect_callback_t fp);
/*------------------------------------------------------------------*/
/* INTERNAL USAGE ONLY
* Although declare as public, it is meant to be invoked by internal code.
*------------------------------------------------------------------*/
void _eventHandler(ble_evt_t* evt);
void printInfo(void);
private:
ble_gap_conn_params_t _ppcp;
ble_connect_callback_t _connect_cb;
ble_disconnect_callback_t _disconnect_cb;
friend class AdafruitBluefruit;
};
#endif /* BLEPERIPH_H_ */
+12 -24
View File
@@ -41,14 +41,13 @@ BLEScanner::BLEScanner(void)
_report_data.p_data = _scan_data;
_report_data.len = BLE_GAP_SCAN_BUFFER_MAX;
_conn_mask = 0;
_runnning = false;
_start_if_disconnect = true;
_filter_rssi = INT8_MIN;
_filter_msd_en = false;
_filter_msd_id = 0; // Irrelevant
_filter_uuid_count = 0;
_filter_uuid = NULL;
@@ -331,6 +330,9 @@ void BLEScanner::clearFilters(void)
*/
void BLEScanner::_eventHandler(ble_evt_t* evt)
{
// conn handle has fixed offset for all events
uint16_t const conn_hdl = evt->evt.common_evt.conn_handle;
switch ( evt->header.evt_id )
{
case BLE_GAP_EVT_ADV_REPORT:
@@ -368,11 +370,7 @@ void BLEScanner::_eventHandler(ble_evt_t* evt)
if ( invoke_cb )
{
ble_gap_evt_adv_report_t* adv_report = (ble_gap_evt_adv_report_t*) rtos_malloc( sizeof(ble_gap_evt_adv_report_t) );
VERIFY(adv_report,);
(*adv_report) = (*evt_report);
if (_rx_cb) ada_callback(adv_report, _rx_cb, adv_report);
if (_rx_cb) ada_callback(evt_report, sizeof(*evt_report), _rx_cb, evt_report);
}else
{
// continue scanning since report is filtered and callback is not invoked
@@ -387,30 +385,20 @@ void BLEScanner::_eventHandler(ble_evt_t* evt)
if ( para->role == BLE_GAP_ROLE_CENTRAL)
{
_runnning = false;
bitSet(_conn_mask, conn_hdl);
// Turn on Conn LED
Bluefruit._stopConnLed();
Bluefruit._setConnLed(true);
_runnning = false;
}
}
break;
case BLE_GAP_EVT_DISCONNECTED:
if ( BLE_GAP_ROLE_CENTRAL == Bluefruit.Gap.getRole(evt->evt.common_evt.conn_handle) )
if ( bitRead(_conn_mask, conn_hdl) && (0 == Bluefruit.Central.connected()) )
{
// skip if already running
if ( !_runnning )
{
// Turn off Conn LED
Bluefruit._setConnLed(false);
bitClear(_conn_mask, conn_hdl);
// Auto start if enabled
if ( _start_if_disconnect )
{
start(_param.timeout);
}
}
// Auto start if enabled and not connected to any peripherals
if ( !_runnning && _start_if_disconnect ) start(_param.timeout);
}
break;
@@ -418,7 +406,7 @@ void BLEScanner::_eventHandler(ble_evt_t* evt)
if (evt->evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_SCAN)
{
_runnning = false;
if (_stop_cb) ada_callback(NULL, _stop_cb);
if (_stop_cb) ada_callback(NULL, 0, _stop_cb);
}
break;
@@ -100,6 +100,8 @@ private:
uint8_t _scan_data[BLE_GAP_SCAN_BUFFER_MAX];
ble_data_t _report_data;
uint32_t _conn_mask;
bool _runnning;
bool _start_if_disconnect;
+2 -2
View File
@@ -74,12 +74,12 @@ err_t BLEService::begin(void)
return ERROR_NONE;
}
void BLEService::_disconnect_cb(void)
void BLEService::svc_disconnect_hdl(uint16_t conn_hdl)
{
// Template for inherited class
}
void BLEService::_connect_cb(void)
void BLEService::svc_connect_hdl(uint16_t conn_hdl)
{
// Template for inherited class
}
+3 -3
View File
@@ -42,12 +42,12 @@
class BLEService
{
protected:
uint16_t _handle;
uint16_t _handle; // service gatt handle
void _init(void);
virtual void _disconnect_cb(void);
virtual void _connect_cb(void);
virtual void svc_disconnect_hdl(uint16_t conn_hdl);
virtual void svc_connect_hdl(uint16_t conn_hdl);
public:
static BLEService* lastService;
+321 -230
View File
@@ -103,18 +103,12 @@ static void nrf_error_cb(uint32_t id, uint32_t pc, uint32_t info)
}
#if CFG_DEBUG
while(1)
{
}
while(1) { }
#endif
}
/**
* Constructor
*/
// Constructor
AdafruitBluefruit::AdafruitBluefruit(void)
: Central(), Gap()
{
/*------------------------------------------------------------------*/
/* SoftDevice Default Configuration
@@ -132,9 +126,21 @@ AdafruitBluefruit::AdafruitBluefruit(void)
_sd_cfg.uuid128_max = BLE_UUID_VS_COUNT_DEFAULT;
_sd_cfg.service_changed = 1;
_sd_cfg.prph.mtu_max = BLE_GATT_ATT_MTU_DEFAULT;
_sd_cfg.prph.event_len = BLE_GAP_EVENT_LENGTH_DEFAULT;
_sd_cfg.prph.hvn_qsize = BLE_GATTS_HVN_TX_QUEUE_SIZE_DEFAULT;
_sd_cfg.prph.wrcmd_qsize = BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT;
_sd_cfg.central.mtu_max = BLE_GATT_ATT_MTU_DEFAULT;
_sd_cfg.central.event_len = BLE_GAP_EVENT_LENGTH_DEFAULT;
_sd_cfg.central.hvn_qsize = BLE_GATTS_HVN_TX_QUEUE_SIZE_DEFAULT;
_sd_cfg.central.wrcmd_qsize = BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT;
_prph_count = 0;
_central_count = 0;
memclr(_connection, sizeof(_connection));
_ble_event_sem = NULL;
_soc_event_sem = NULL;
@@ -145,16 +151,22 @@ AdafruitBluefruit::AdafruitBluefruit(void)
_conn_hdl = BLE_CONN_HANDLE_INVALID;
_ppcp.min_conn_interval = BLE_GAP_CONN_MIN_INTERVAL_DFLT;
_ppcp.max_conn_interval = BLE_GAP_CONN_MAX_INTERVAL_DFLT;
_ppcp.slave_latency = 0;
_ppcp.conn_sup_timeout = BLE_GAP_CONN_SUPERVISION_TIMEOUT_MS / 10; // in 10ms unit
_conn_interval = 0;
_connect_cb = NULL;
_disconnect_cb = NULL;
_event_cb = NULL;
_rssi_cb = NULL;
_sec_param = (ble_gap_sec_params_t)
{
.bond = 1,
.mitm = 0,
.lesc = 0,
.keypress = 0,
.io_caps = BLE_GAP_IO_CAPS_NONE,
.oob = 0,
.min_key_size = 7,
.max_key_size = 16,
.kdist_own = { .enc = 1, .id = 1},
.kdist_peer = { .enc = 1, .id = 1},
};
COMMENT_OUT(
_auth_type = BLE_GAP_AUTH_KEY_TYPE_NONE;
@@ -179,12 +191,19 @@ void AdafruitBluefruit::configAttrTableSize(uint32_t attr_table_size)
void AdafruitBluefruit::configPrphConn(uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize)
{
Gap.configPrphConn(mtu_max, event_len, hvn_qsize, wrcmd_qsize);
_sd_cfg.prph.mtu_max = maxof(mtu_max, BLE_GATT_ATT_MTU_DEFAULT);;
_sd_cfg.prph.event_len = maxof(event_len, BLE_GAP_EVENT_LENGTH_MIN);
_sd_cfg.prph.hvn_qsize = hvn_qsize;
_sd_cfg.prph.wrcmd_qsize = wrcmd_qsize;
}
void AdafruitBluefruit::configCentralConn(uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize)
{
Gap.configCentralConn(mtu_max, event_len, hvn_qsize, wrcmd_qsize);
_sd_cfg.central.mtu_max = maxof(mtu_max, BLE_GATT_ATT_MTU_DEFAULT);;
_sd_cfg.central.event_len = maxof(event_len, BLE_GAP_EVENT_LENGTH_MIN);
_sd_cfg.central.hvn_qsize = hvn_qsize;
_sd_cfg.central.wrcmd_qsize = wrcmd_qsize;
}
void AdafruitBluefruit::configPrphBandwidth(uint8_t bw)
@@ -245,8 +264,7 @@ void AdafruitBluefruit::configCentralBandwidth(uint8_t bw)
}
}
err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
bool AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
{
_prph_count = prph_count;
_central_count = central_count;
@@ -278,7 +296,7 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
#error Clock Source is not configured, define USE_LFXO or USE_LFRC according to your board in variant.h
#endif
VERIFY_STATUS( sd_softdevice_enable(&clock_cfg, nrf_error_cb) );
VERIFY_STATUS( sd_softdevice_enable(&clock_cfg, nrf_error_cb), false );
#ifdef NRF52840_XXAA
usb_softdevice_post_enable();
@@ -303,20 +321,6 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
* Note: Value is left as it is if already configured by user.
*/
/*------------------------------------------------------------------*/
// if ( _prph_count )
// {
// // If not configured by user, set Attr Table Size large enough for
// // most peripheral applications
// if ( _sd_cfg.attr_table_size == 0 ) _sd_cfg.attr_table_size = 0x800;
// }
//
// if ( _central_count)
// {
//
// }
//
// // Not configure, default value are used
// if ( _sd_cfg.attr_table_size == 0 ) _sd_cfg.attr_table_size = BLE_GATTS_ATTR_TAB_SIZE_DEFAULT;
/*------------- Configure BLE params -------------*/
extern uint32_t __data_start__[]; // defined in linker
@@ -327,14 +331,14 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
// Vendor UUID count
varclr(&blecfg);
blecfg.common_cfg.vs_uuid_cfg.vs_uuid_count = _sd_cfg.uuid128_max;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_COMMON_CFG_VS_UUID, &blecfg, ram_start) );
VERIFY_STATUS ( sd_ble_cfg_set(BLE_COMMON_CFG_VS_UUID, &blecfg, ram_start), false );
// Roles
varclr(&blecfg);
blecfg.gap_cfg.role_count_cfg.periph_role_count = _prph_count;
blecfg.gap_cfg.role_count_cfg.central_role_count = _central_count; // ? BLE_CENTRAL_MAX_CONN : 0);
blecfg.gap_cfg.role_count_cfg.central_sec_count = (_central_count ? 1 : 0); // should be enough
VERIFY_STATUS( sd_ble_cfg_set(BLE_GAP_CFG_ROLE_COUNT, &blecfg, ram_start) );
blecfg.gap_cfg.role_count_cfg.central_role_count = _central_count;
blecfg.gap_cfg.role_count_cfg.central_sec_count = (_central_count ? 1 : 0); // 1 should be enough
VERIFY_STATUS( sd_ble_cfg_set(BLE_GAP_CFG_ROLE_COUNT, &blecfg, ram_start), false );
// Device Name
// varclr(&blecfg);
@@ -343,12 +347,12 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
varclr(&blecfg);
blecfg.gatts_cfg.service_changed.service_changed = _sd_cfg.service_changed;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_GATTS_CFG_SERVICE_CHANGED, &blecfg, ram_start) );
VERIFY_STATUS ( sd_ble_cfg_set(BLE_GATTS_CFG_SERVICE_CHANGED, &blecfg, ram_start), false );
// ATTR Table Size
varclr(&blecfg);
blecfg.gatts_cfg.attr_tab_size.attr_tab_size = _sd_cfg.attr_table_size;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_GATTS_CFG_ATTR_TAB_SIZE, &blecfg, ram_start) );
VERIFY_STATUS ( sd_ble_cfg_set(BLE_GATTS_CFG_ATTR_TAB_SIZE, &blecfg, ram_start), false );
/*------------- Event Length + MTU + HVN queue + WRITE CMD queue setting affecting bandwidth -------------*/
if ( _prph_count )
@@ -356,27 +360,27 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
// ATT MTU
varclr(&blecfg);
blecfg.conn_cfg.conn_cfg_tag = CONN_CFG_PERIPHERAL;
blecfg.conn_cfg.params.gatt_conn_cfg.att_mtu = Gap._cfg_prph.mtu_max;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATT, &blecfg, ram_start) );
blecfg.conn_cfg.params.gatt_conn_cfg.att_mtu = _sd_cfg.prph.mtu_max;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATT, &blecfg, ram_start), false );
// Event length and max connection for this config
varclr(&blecfg);
blecfg.conn_cfg.conn_cfg_tag = CONN_CFG_PERIPHERAL;
blecfg.conn_cfg.params.gap_conn_cfg.conn_count = _prph_count;
blecfg.conn_cfg.params.gap_conn_cfg.event_length = Gap._cfg_prph.event_len;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GAP, &blecfg, ram_start) );
blecfg.conn_cfg.params.gap_conn_cfg.event_length = _sd_cfg.prph.event_len;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GAP, &blecfg, ram_start), false );
// HVN queue size
varclr(&blecfg);
blecfg.conn_cfg.conn_cfg_tag = CONN_CFG_PERIPHERAL;
blecfg.conn_cfg.params.gatts_conn_cfg.hvn_tx_queue_size = Gap._cfg_prph.hvn_tx_qsize;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATTS, &blecfg, ram_start) );
blecfg.conn_cfg.params.gatts_conn_cfg.hvn_tx_queue_size = _sd_cfg.prph.hvn_qsize;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATTS, &blecfg, ram_start), false );
// WRITE COMMAND queue size
varclr(&blecfg);
blecfg.conn_cfg.conn_cfg_tag = CONN_CFG_PERIPHERAL;
blecfg.conn_cfg.params.gattc_conn_cfg.write_cmd_tx_queue_size = Gap._cfg_prph.wr_cmd_qsize;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATTC, &blecfg, ram_start) );
blecfg.conn_cfg.params.gattc_conn_cfg.write_cmd_tx_queue_size = _sd_cfg.prph.wrcmd_qsize;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATTC, &blecfg, ram_start), false );
}
if ( _central_count)
@@ -384,27 +388,27 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
// ATT MTU
varclr(&blecfg);
blecfg.conn_cfg.conn_cfg_tag = CONN_CFG_CENTRAL;
blecfg.conn_cfg.params.gatt_conn_cfg.att_mtu = Gap._cfg_central.mtu_max;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATT, &blecfg, ram_start) );
blecfg.conn_cfg.params.gatt_conn_cfg.att_mtu = _sd_cfg.central.mtu_max;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATT, &blecfg, ram_start), false );
// Event length and max connection for this config
varclr(&blecfg);
blecfg.conn_cfg.conn_cfg_tag = CONN_CFG_CENTRAL;
blecfg.conn_cfg.params.gap_conn_cfg.conn_count = _central_count;
blecfg.conn_cfg.params.gap_conn_cfg.event_length = Gap._cfg_central.event_len;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GAP, &blecfg, ram_start) );
blecfg.conn_cfg.params.gap_conn_cfg.event_length =_sd_cfg.central.event_len;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GAP, &blecfg, ram_start), false );
// HVN queue size
varclr(&blecfg);
blecfg.conn_cfg.conn_cfg_tag = CONN_CFG_CENTRAL;
blecfg.conn_cfg.params.gatts_conn_cfg.hvn_tx_queue_size = Gap._cfg_central.hvn_tx_qsize;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATTS, &blecfg, ram_start) );
blecfg.conn_cfg.params.gatts_conn_cfg.hvn_tx_queue_size = _sd_cfg.central.hvn_qsize;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATTS, &blecfg, ram_start), false );
// WRITE COMMAND queue size
varclr(&blecfg);
blecfg.conn_cfg.conn_cfg_tag = CONN_CFG_CENTRAL;
blecfg.conn_cfg.params.gattc_conn_cfg.write_cmd_tx_queue_size = Gap._cfg_central.wr_cmd_qsize;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATTC, &blecfg, ram_start) );
blecfg.conn_cfg.params.gattc_conn_cfg.write_cmd_tx_queue_size = _sd_cfg.central.wrcmd_qsize;
VERIFY_STATUS ( sd_ble_cfg_set(BLE_CONN_CFG_GATTC, &blecfg, ram_start), false );
}
// Enable BLE stack
@@ -419,25 +423,21 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
}
LOG_LV1("CFG", "SoftDevice's RAM requires: 0x%08X", ram_start);
VERIFY_STATUS(err);
VERIFY_STATUS(err, false);
/*------------- Configure BLE Option -------------*/
ble_opt_t opt;
varclr(&opt);
opt.common_opt.conn_evt_ext.enable = 1; // enable Data Length Extension
VERIFY_STATUS( sd_ble_opt_set(BLE_COMMON_OPT_CONN_EVT_EXT, &opt) );
VERIFY_STATUS( sd_ble_opt_set(BLE_COMMON_OPT_CONN_EVT_EXT, &opt), false );
/*------------- Configure GAP -------------*/
// Peripheral Preferred Connection Parameters
VERIFY_STATUS( sd_ble_gap_ppcp_set(&_ppcp) );
// Init Peripheral role
VERIFY( Periph.begin() );
// Default device name
ble_gap_conn_sec_mode_t sec_mode = BLE_SECMODE_OPEN;
VERIFY_STATUS(sd_ble_gap_device_name_set(&sec_mode, (uint8_t const *) CFG_DEFAULT_NAME, strlen(CFG_DEFAULT_NAME)));
VERIFY_STATUS( sd_ble_gap_appearance_set(BLE_APPEARANCE_UNKNOWN) );
VERIFY_STATUS(sd_ble_gap_device_name_set(&sec_mode, (uint8_t const *) CFG_DEFAULT_NAME, strlen(CFG_DEFAULT_NAME)), false);
//------------- USB -------------//
#if NRF52840_XXAA
@@ -446,28 +446,24 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
sd_power_usbremoved_enable(true);
#endif
/*------------- DFU OTA as built-in service -------------*/
_dfu_svc.begin();
if (_central_count) Central.begin(); // Init Central
// Init Central role
if (_central_count) Central.begin();
// Create RTOS Semaphore & Task for BLE Event
_ble_event_sem = xSemaphoreCreateBinary();
VERIFY(_ble_event_sem, NRF_ERROR_NO_MEM);
VERIFY(_ble_event_sem);
TaskHandle_t ble_task_hdl;
xTaskCreate( adafruit_ble_task, "BLE", CFG_BLE_TASK_STACKSIZE, NULL, TASK_PRIO_HIGH, &ble_task_hdl);
// Create RTOS Semaphore & Task for SOC Event
_soc_event_sem = xSemaphoreCreateBinary();
VERIFY(_soc_event_sem, NRF_ERROR_NO_MEM);
VERIFY(_soc_event_sem);
TaskHandle_t soc_task_hdl;
xTaskCreate( adafruit_soc_task, "SOC", CFG_SOC_TASK_STACKSIZE, NULL, TASK_PRIO_HIGH, &soc_task_hdl);
// Interrupt priority has already been set by the stack.
// NVIC_SetPriority(SD_EVT_IRQn, 6);
NVIC_EnableIRQ(SD_EVT_IRQn);
NVIC_EnableIRQ(SD_EVT_IRQn); // enable SD interrupt
// Create Timer for led advertising blinky
_led_blink_th = xTimerCreate(NULL, ms2tick(CFG_ADV_BLINKY_INTERVAL/2), true, NULL, bluefruit_blinky_cb);
@@ -475,16 +471,43 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
// Initialize bonding
bond_init();
return ERROR_NONE;
return true;
}
/*------------------------------------------------------------------*/
/* General Functions
*------------------------------------------------------------------*/
ble_gap_addr_t AdafruitBluefruit::getAddr (void)
{
ble_gap_addr_t gap_addr;
sd_ble_gap_addr_get(&gap_addr);
return gap_addr;
}
/**
* Get current Mac address and its type
* @param mac address
* @return Address type e.g BLE_GAP_ADDR_TYPE_RANDOM_STATIC
*/
uint8_t AdafruitBluefruit::getAddr (uint8_t mac[6])
{
ble_gap_addr_t gap_addr;
sd_ble_gap_addr_get(&gap_addr);
memcpy(mac, gap_addr.addr, 6);
return gap_addr.addr_type;
}
bool AdafruitBluefruit::setAddr (ble_gap_addr_t* gap_addr)
{
VERIFY_STATUS( sd_ble_gap_addr_set(gap_addr), false );
return true;
}
void AdafruitBluefruit::setName (char const * str)
{
ble_gap_conn_sec_mode_t sec_mode = BLE_SECMODE_OPEN;
sd_ble_gap_device_name_set(&sec_mode, (uint8_t const *) str, strlen(str));
sd_ble_gap_device_name_set(&sec_mode, (uint8_t const *) str, strlen(str));
}
uint8_t AdafruitBluefruit::getName(char* name, uint16_t bufsize)
@@ -493,29 +516,27 @@ uint8_t AdafruitBluefruit::getName(char* name, uint16_t bufsize)
return bufsize;
}
bool AdafruitBluefruit::setTxPower(int8_t power)
static inline bool is_tx_power_valid(int8_t power)
{
#if defined(NRF52832_XXAA)
int8_t const accepted[] = { -40, -20, -16, -12, -8, -4, 0, 3, 4 };
int8_t const accepted[] = { -40, -20, -16, -12, -8, -4, 0, 3, 4 };
#elif defined( NRF52840_XXAA)
int8_t const accepted[] = { -40, -20, -16, -12, -8, -4, 0, 2, 3, 4, 5, 6, 7, 8 };
int8_t const accepted[] = { -40, -20, -16, -12, -8, -4, 0, 2, 3, 4, 5, 6, 7, 8 };
#endif
// Check if TX Power is valid value
uint32_t i;
for (i=0; i<sizeof(accepted); i++)
for (uint32_t i=0; i<sizeof(accepted); i++)
{
if (accepted[i] == power) break;
if (accepted[i] == power) return true;
}
VERIFY(i < sizeof(accepted));
// Apply if connected
if ( _conn_hdl != BLE_CONN_HANDLE_INVALID )
{
VERIFY_STATUS( sd_ble_gap_tx_power_set(BLE_GAP_TX_POWER_ROLE_CONN, _conn_hdl, power), false );
}
return false;
}
bool AdafruitBluefruit::setTxPower(int8_t power)
{
VERIFY(is_tx_power_valid(power));
_tx_power = power;
return true;
}
@@ -553,62 +574,36 @@ uint16_t AdafruitBluefruit::getApperance(void)
/*------------------------------------------------------------------*/
/* GAP, Connections and Bonding
*------------------------------------------------------------------*/
bool AdafruitBluefruit::connected(void)
uint8_t AdafruitBluefruit::connected(void)
{
return ( _conn_hdl != BLE_CONN_HANDLE_INVALID );
uint8_t count = 0;
for (uint16_t c=0; c<BLE_MAX_CONNECTION; c++)
{
if ( this->connected(c) ) count++;
}
return count;
}
bool AdafruitBluefruit::disconnect(void)
bool AdafruitBluefruit::connected(uint16_t conn_hdl)
{
BLEConnection* conn = this->Connection(conn_hdl);
return conn && conn->connected();
}
bool AdafruitBluefruit::disconnect(uint16_t conn_hdl)
{
BLEConnection* conn = this->Connection(conn_hdl);
// disconnect if connected
if ( connected() )
if ( conn && conn->connected() )
{
return ERROR_NONE == sd_ble_gap_disconnect(_conn_hdl, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
return conn->disconnect();
}
return true; // not connected still return true
}
bool AdafruitBluefruit::setConnInterval(uint16_t min, uint16_t max)
{
_ppcp.min_conn_interval = min;
_ppcp.max_conn_interval = max;
VERIFY_STATUS( sd_ble_gap_ppcp_set(&_ppcp), false);
return true;
}
bool AdafruitBluefruit::setConnIntervalMS(uint16_t min_ms, uint16_t max_ms)
{
return setConnInterval( MS100TO125(min_ms), MS100TO125(max_ms) );
}
bool AdafruitBluefruit::setConnSupervisionTimeout(uint16_t timeout)
{
_ppcp.conn_sup_timeout = timeout;
VERIFY_STATUS( sd_ble_gap_ppcp_set(&_ppcp), false);
return true;
}
bool AdafruitBluefruit::setConnSupervisionTimeoutMS(uint16_t timeout_ms)
{
return setConnSupervisionTimeout(timeout_ms / 10); // 10ms unit
}
void AdafruitBluefruit::setConnectCallback( BLEGap::connect_callback_t fp )
{
_connect_cb = fp;
}
void AdafruitBluefruit::setDisconnectCallback( BLEGap::disconnect_callback_t fp )
{
_disconnect_cb = fp;
}
void AdafruitBluefruit::setEventCallback ( void (*fp) (ble_evt_t*) )
{
_event_cb = fp;
@@ -621,24 +616,26 @@ uint16_t AdafruitBluefruit::connHandle(void)
bool AdafruitBluefruit::connPaired(void)
{
return ( _conn_hdl != BLE_CONN_HANDLE_INVALID ) && Gap.paired(_conn_hdl);
BLEConnection* conn = Bluefruit.Connection(_conn_hdl);
return conn && conn->paired();
}
uint16_t AdafruitBluefruit::connInterval(void)
uint16_t AdafruitBluefruit::getMaxMtu(uint8_t role)
{
return _conn_interval;
return (role == BLE_GAP_ROLE_PERIPH) ? _sd_cfg.prph.mtu_max : _sd_cfg.central.mtu_max;
}
ble_gap_addr_t AdafruitBluefruit::getPeerAddr(void)
BLEConnection* AdafruitBluefruit::Connection(uint16_t conn_hdl)
{
return Gap.getPeerAddr(_conn_hdl);
return (conn_hdl < BLE_MAX_CONNECTION) ? _connection[conn_hdl] : NULL;
}
uint8_t AdafruitBluefruit::getPeerAddr(uint8_t addr[6])
void AdafruitBluefruit::setRssiCallback(rssi_callback_t fp)
{
return Gap.getPeerAddr(_conn_hdl, addr);
_rssi_cb = fp;
}
COMMENT_OUT (
bool AdafruitBluefruit::setPIN(const char* pin)
{
@@ -757,13 +754,156 @@ void adafruit_ble_task(void* arg)
*/
void AdafruitBluefruit::_ble_handler(ble_evt_t* evt)
{
// conn handle has fixed offset regardless of event type
uint16_t const evt_conn_hdl = evt->evt.common_evt.conn_handle;
// conn handle has fixed offset for all events
uint16_t const conn_hdl = evt->evt.common_evt.conn_handle;
BLEConnection* conn = this->Connection(conn_hdl);
LOG_LV1("BLE", "%s : Conn Handle = %d", dbg_ble_event_str(evt->header.evt_id), evt_conn_hdl);
LOG_LV1("BLE", "%s : Conn Handle = %d", dbg_ble_event_str(evt->header.evt_id), conn_hdl);
// GAP handler
Gap._eventHandler(evt);
if ( conn ) conn->_eventHandler(evt);
switch(evt->header.evt_id)
{
case BLE_GAP_EVT_CONNECTED:
{
// Turn on Conn LED
_stopConnLed();
_setConnLed(true);
ble_gap_evt_connected_t const * para = &evt->evt.gap_evt.params.connected;
if ( _connection[conn_hdl] )
{
LOG_LV1("GAP", "Connection is already in used, something wrong !!");
delete _connection[conn_hdl];
_connection[conn_hdl] = NULL;
}
// Transmission buffer pool
uint8_t const hvn_qsize = (para->role == BLE_GAP_ROLE_PERIPH) ? _sd_cfg.prph.hvn_qsize : _sd_cfg.central.hvn_qsize;
uint8_t const wrcmd_qsize = (para->role == BLE_GAP_ROLE_PERIPH) ? _sd_cfg.prph.wrcmd_qsize : _sd_cfg.central.wrcmd_qsize;
_connection[conn_hdl] = new BLEConnection(conn_hdl, para, hvn_qsize, wrcmd_qsize);
conn = _connection[conn_hdl];
// Invoke connect callback
if ( conn->getRole() == BLE_GAP_ROLE_PERIPH )
{
if ( Periph._connect_cb ) ada_callback(NULL, 0, Periph._connect_cb, conn_hdl);
}else
{
if ( Central._connect_cb ) ada_callback(NULL, 0, Central._connect_cb, conn_hdl);
}
}
break;
case BLE_GAP_EVT_DISCONNECTED:
{
ble_gap_evt_disconnected_t const* para = &evt->evt.gap_evt.params.disconnected;
LOG_LV2("GAP", "Disconnect Reason 0x%02X", evt->evt.gap_evt.params.disconnected.reason);
// Turn off Conn LED If not connected at all
bool still_connected = false;
for (uint8_t i=0; i<BLE_MAX_CONNECTION; i++)
{
if ( _connection[i] && _connection[i]->connected() )
{
still_connected = true;
break;
}
}
if ( !still_connected ) _setConnLed(false);
// Invoke disconnect callback
if ( conn->getRole() == BLE_GAP_ROLE_PERIPH )
{
if ( Periph._disconnect_cb ) ada_callback(NULL, 0, Periph._disconnect_cb, conn_hdl, para->reason);
}else
{
if ( Central._disconnect_cb ) ada_callback(NULL, 0, Central._disconnect_cb, conn_hdl, para->reason);
}
delete _connection[conn_hdl];
_connection[conn_hdl] = NULL;
}
break;
case BLE_GAP_EVT_RSSI_CHANGED:
{
ble_gap_evt_rssi_changed_t const * rssi_changed = &evt->evt.gap_evt.params.rssi_changed;
if ( _rssi_cb )
{
ada_callback(NULL, 0, _rssi_cb, conn_hdl, rssi_changed->rssi);
}
}
break;
case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
{
ble_gap_data_length_params_t* param = &evt->evt.gap_evt.params.data_length_update_request.peer_params;
LOG_LV2("GAP", "Data Length Req is (tx, rx) octets = (%d, %d), (tx, rx) time = (%d, %d) us",
param->max_tx_octets, param->max_rx_octets, param->max_tx_time_us, param->max_rx_time_us);
// Let Softdevice decide the data length
VERIFY_STATUS( sd_ble_gap_data_length_update(conn_hdl, NULL, NULL), );
}
break;
case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
{
ble_gap_data_length_params_t* datalen = &evt->evt.gap_evt.params.data_length_update.effective_params;
LOG_LV2("GAP", "Data Length is (tx, rx) octets = (%d, %d), (tx, rx) time = (%d, %d) us",
datalen->max_tx_octets, datalen->max_rx_octets, datalen->max_tx_time_us, datalen->max_rx_time_us);
}
break;
case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
{
ble_gap_phys_t* req_phy = &evt->evt.gap_evt.params.phy_update_request.peer_preferred_phys;
#if CFG_DEBUG >= 1
char const *phy_str[] = { "Auto", "1 Mbps", "2 Mbps", "Coded" };
LOG_LV1("GAP", "PHY request tx: %s, rx: %s", phy_str[req_phy->tx_phys], phy_str[req_phy->rx_phys]);
#endif
// Tell SoftDevice to choose PHY automatically
ble_gap_phys_t phy = { BLE_GAP_PHY_AUTO, BLE_GAP_PHY_AUTO };
(void) sd_ble_gap_phy_update(conn_hdl, &phy);
}
break;
case BLE_GAP_EVT_PHY_UPDATE:
{
ble_gap_evt_phy_update_t* active_phy = &evt->evt.gap_evt.params.phy_update;
#if CFG_DEBUG >= 1
if ( active_phy->status != BLE_HCI_STATUS_CODE_SUCCESS )
{
LOG_LV1("GAP", "Failed HCI status = 0x%02X", active_phy->status);
}else
{
char const *phy_str[] = { "Auto", "1 Mbps", "2 Mbps", "Coded" };
LOG_LV1("GAP", "PHY active tx: %s, rx: %s", phy_str[active_phy->tx_phy], phy_str[active_phy->rx_phy]);
}
#endif
}
break;
case BLE_EVT_USER_MEM_REQUEST:
// We will handle Long Write sequence (RW Authorize PREP_WRITE_REQ)
sd_ble_user_mem_reply(conn_hdl, NULL);
break;
case BLE_EVT_USER_MEM_RELEASE:
// nothing to do
break;
default: break;
}
Advertising._eventHandler(evt);
Scanner._eventHandler(evt);
@@ -772,88 +912,45 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt)
* or a few special one
* - Connected event
* - Advertising timeout (could be connected and advertising at the same time)
*
* Pairing procedure
* - Connect -> SEC_PARAMS_REQUEST -> CONN_SEC_UPDATE -> AUTH_STATUS
*
* Reconnect to a paired device
* - Connect -> SEC_INFO_REQUEST -> CONN_SEC_UPDATE
*/
if ( evt_conn_hdl == _conn_hdl ||
evt->header.evt_id == BLE_GAP_EVT_CONNECTED ||
evt->header.evt_id == BLE_GAP_EVT_TIMEOUT )
if ( conn_hdl == _conn_hdl ||
evt->header.evt_id == BLE_GAP_EVT_CONNECTED)
{
switch ( evt->header.evt_id )
{
case BLE_GAP_EVT_CONNECTED:
{ // Note callback is invoked by BLEGap
{
ble_gap_evt_connected_t* para = &evt->evt.gap_evt.params.connected;
if (para->role == BLE_GAP_ROLE_PERIPH)
{
_conn_hdl = evt->evt.gap_evt.conn_handle;
_conn_interval = para->conn_params.min_conn_interval;
// Connection interval set by Central is out of preferred range
// Try to negotiate with Central using our preferred values
if ( !is_within(_ppcp.min_conn_interval, para->conn_params.min_conn_interval, _ppcp.max_conn_interval) )
{
// Null, value is set by sd_ble_gap_ppcp_set will be used
VERIFY_STATUS( sd_ble_gap_conn_param_update(_conn_hdl, NULL), );
}
if (_connect_cb) ada_callback(NULL, _connect_cb, _conn_hdl);
_conn_hdl = evt->evt.gap_evt.conn_handle;
}
}
break;
case BLE_GAP_EVT_CONN_PARAM_UPDATE:
{
// Connection Parameter after negotiating with Central
// min conn = max conn = actual used interval
ble_gap_conn_params_t* param = &evt->evt.gap_evt.params.conn_param_update.conn_params;
_conn_interval = param->min_conn_interval;
}
break;
case BLE_GAP_EVT_DISCONNECTED:
if (_disconnect_cb) ada_callback(NULL, _disconnect_cb, _conn_hdl, evt->evt.gap_evt.params.disconnected.reason);
LOG_LV2("GAP", "Disconnect Reason 0x%02X", evt->evt.gap_evt.params.disconnected.reason);
_conn_hdl = BLE_CONN_HANDLE_INVALID;
break;
case BLE_GATTS_EVT_SYS_ATTR_MISSING:
sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0);
break;
case BLE_EVT_USER_MEM_REQUEST:
// We will handle Long Write sequence (RW Authorize PREP_WRITE_REQ)
sd_ble_user_mem_reply(evt_conn_hdl, NULL);
break;
case BLE_EVT_USER_MEM_RELEASE:
// nothing to do
break;
default: break;
}
}
// Central Event Handler
if (_central_count)
// Periph event handler (also handle generic non-connection event)
if ( (conn == NULL) || (conn->getRole() == BLE_GAP_ROLE_PERIPH) )
{
// Skip if not central connection
if (evt_conn_hdl != _conn_hdl ||
evt_conn_hdl == BLE_CONN_HANDLE_INVALID)
{
Central._event_handler(evt);
}
Periph._eventHandler(evt);
}
// Central Event Handler (also handle generic non-connection event)
if ( (conn == NULL) || (conn->getRole() == BLE_GAP_ROLE_CENTRAL) )
{
Central._eventHandler(evt);
}
// Discovery Event Handler
if ( Discovery.begun() ) Discovery._event_handler(evt);
if ( Discovery.begun() ) Discovery._eventHandler(evt);
// GATTs characteristics event handler
Gatt._eventHandler(evt);
@@ -886,9 +983,12 @@ void AdafruitBluefruit::_setConnLed (bool on_off)
/*------------------------------------------------------------------*/
/* Bonds
*------------------------------------------------------------------*/
bool AdafruitBluefruit::requestPairing(void)
bool AdafruitBluefruit::requestPairing(uint16_t conn_hdl)
{
return Gap.requestPairing(_conn_hdl);
BLEConnection* conn = this->Connection(conn_hdl);
VERIFY(conn);
return conn->requestPairing();
}
void AdafruitBluefruit::clearBonds(void)
@@ -936,19 +1036,19 @@ void AdafruitBluefruit::printInfo(void)
Serial.print(" - ");
Serial.printf(title_fmt, "Max MTU");
Serial.println(Gap._cfg_prph.mtu_max);
Serial.println(_sd_cfg.prph.mtu_max);
Serial.print(" - ");
Serial.printf(title_fmt, "Event Length");
Serial.println(Gap._cfg_prph.event_len);
Serial.println(_sd_cfg.prph.event_len);
Serial.print(" - ");
Serial.printf(title_fmt, "HVN Queue Size");
Serial.println(Gap._cfg_prph.hvn_tx_qsize);
Serial.println(_sd_cfg.prph.hvn_qsize);
Serial.print(" - ");
Serial.printf(title_fmt, "WrCmd Queue Size");
Serial.println(Gap._cfg_prph.wr_cmd_qsize);
Serial.println(_sd_cfg.prph.wrcmd_qsize);
}
if ( _central_count )
@@ -957,19 +1057,19 @@ void AdafruitBluefruit::printInfo(void)
Serial.print(" - ");
Serial.printf(title_fmt, "Max MTU");
Serial.println(Gap._cfg_central.mtu_max);
Serial.println(_sd_cfg.central.mtu_max);
Serial.print(" - ");
Serial.printf(title_fmt, "Event Length");
Serial.println(Gap._cfg_central.event_len);
Serial.println(_sd_cfg.central.event_len);
Serial.print(" - ");
Serial.printf(title_fmt, "HVN Queue Size");
Serial.println(Gap._cfg_central.hvn_tx_qsize);
Serial.println(_sd_cfg.central.hvn_qsize);
Serial.print(" - ");
Serial.printf(title_fmt, "WrCmd Queue Size");
Serial.println(Gap._cfg_central.wr_cmd_qsize);
Serial.println(_sd_cfg.central.wrcmd_qsize);
}
/*------------- Settings -------------*/
@@ -986,20 +1086,19 @@ void AdafruitBluefruit::printInfo(void)
// Max Connections
Serial.printf(title_fmt, "Max Connections");
Serial.printf("Peripheral = %d, ", _prph_count ? 1 : 0);
Serial.printf("Central = %d ", _central_count ? BLE_CENTRAL_MAX_CONN : 0);
Serial.printf("Peripheral = %d, ", _prph_count);
Serial.printf("Central = %d ", _central_count);
Serial.println();
// Address
Serial.printf(title_fmt, "Address");
{
char const * type_str[] = { "Public", "Static", "Private Resolvable", "Private Non Resolvable" };
uint8_t mac[6];
uint8_t type = Gap.getAddr(mac);
ble_gap_addr_t gap_addr = this->getAddr();
// MAC is in little endian --> print reverse
Serial.printBufferReverse(mac, 6, ':');
Serial.printf(" (%s)", type_str[type]);
Serial.printBufferReverse(gap_addr.addr, 6, ':');
Serial.printf(" (%s)", type_str[gap_addr.addr_type]);
}
Serial.println();
@@ -1008,15 +1107,7 @@ void AdafruitBluefruit::printInfo(void)
Serial.printf("%d dBm", _tx_power);
Serial.println();
// Connection Intervals
Serial.printf(title_fmt, "Conn Intervals");
Serial.printf("min = %.2f ms, ", _ppcp.min_conn_interval*1.25f);
Serial.printf("max = %.2f ms", _ppcp.max_conn_interval*1.25f);
Serial.println();
Serial.printf(title_fmt, "Conn Timeout");
Serial.printf("%.2f ms", _ppcp.conn_sup_timeout*10.0f);
Serial.println();
Periph.printInfo();
/*------------- List the paried device -------------*/
if ( _prph_count )
+63 -51
View File
@@ -39,30 +39,26 @@
#include <Arduino.h>
#include "bluefruit_common.h"
#define CFG_ADV_BLINKY_INTERVAL 500
#define CFG_ADV_BLINKY_INTERVAL 500
/* Note changing these parameters will affect APP_RAM_BASE
* --> need to update RAM region in linker file
* - BLE_GATT_ATT_MTU_MAX from 23 (default) to 247
*/
#define BLE_GATT_ATT_MTU_MAX 247
#define BLE_PRPH_MAX_CONN 1
#define BLE_CENTRAL_MAX_CONN 4
#define BLE_CENTRAL_MAX_SECURE_CONN 1 // should be enough
#define BLE_MAX_CONN (BLE_CENTRAL_MAX_CONN+BLE_PRPH_MAX_CONN)
#define BLE_GATT_ATT_MTU_MAX 247
#define BLE_MAX_CONNECTION 20 // SD support up to 20 connections
#include "BLEUuid.h"
#include "BLEAdvertising.h"
#include "BLECharacteristic.h"
#include "BLEService.h"
#include "BLEScanner.h"
#include "BLEPeriph.h"
#include "BLECentral.h"
#include "BLEClientCharacteristic.h"
#include "BLEClientService.h"
#include "BLEDiscovery.h"
#include "BLEGap.h"
#include "BLEConnection.h"
#include "BLEGatt.h"
// Services
@@ -95,6 +91,12 @@ enum
BANDWIDTH_MAX,
};
enum
{
CONN_CFG_PERIPHERAL = 1,
CONN_CFG_CENTRAL = 2,
};
extern "C"
{
void SD_EVT_IRQHandler(void);
@@ -103,17 +105,19 @@ extern "C"
class AdafruitBluefruit
{
public:
typedef void (*rssi_callback_t) (uint16_t conn_hdl, int8_t rssi);
AdafruitBluefruit(void); // Constructor
/*------------------------------------------------------------------*/
/* Lower Level Classes (Bluefruit.Advertising.*, etc.)
*------------------------------------------------------------------*/
BLEGap Gap;
BLEGatt Gatt;
BLEAdvertising Advertising;
BLEAdvertisingData ScanResponse;
BLEScanner Scanner;
BLEPeriph Periph;
BLECentral Central;
BLEDiscovery Discovery;
@@ -121,65 +125,69 @@ class AdafruitBluefruit
/* SoftDevice Configure Functions, must call before begin().
* These function affect the SRAM consumed by SoftDevice.
*------------------------------------------------------------------*/
void configServiceChanged (bool changed);
void configUuid128Count (uint8_t uuid128_max);
void configAttrTableSize (uint32_t attr_table_size);
void configServiceChanged (bool changed);
void configUuid128Count (uint8_t uuid128_max);
void configAttrTableSize (uint32_t attr_table_size);
// Config Bandwidth for connections
void configPrphConn (uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize);
void configCentralConn (uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize);
// Configure Bandwidth for connections
void configPrphConn (uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize);
void configCentralConn (uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize);
void configPrphBandwidth (uint8_t bw);
void configCentralBandwidth(uint8_t bw);
// Convenient function to config connection
void configPrphBandwidth (uint8_t bw);
void configCentralBandwidth(uint8_t bw);
err_t begin(uint8_t prph_count = 1, uint8_t central_count = 0);
bool begin(uint8_t prph_count = 1, uint8_t central_count = 0);
/*------------------------------------------------------------------*/
/* General Functions
*------------------------------------------------------------------*/
ble_gap_addr_t getAddr(void);
uint8_t getAddr(uint8_t mac[6]);
bool setAddr(ble_gap_addr_t* gap_addr);
void setName (const char* str);
uint8_t getName (char* name, uint16_t bufsize);
// Supported tx_power values depending on mcu:
// - nRF52832: -40dBm, -20dBm, -16dBm, -12dBm, -8dBm, -4dBm, 0dBm, +3dBm and +4dBm.
// - nRF52840: -40dBm, -20dBm, -16dBm, -12dBm, -8dBm, -4dBm, 0dBm, +2dBm, +3dBm, +4dBm, +5dBm, +6dBm, +7dBm and +8dBm.
bool setTxPower (int8_t power);
int8_t getTxPower (void);
bool setApperance (uint16_t appear);
uint16_t getApperance (void);
ble_gap_sec_params_t getSecureParam(void)
{
return _sec_param;
}
void autoConnLed (bool enabled);
void setConnLedInterval (uint32_t ms);
void clearBonds (void);
/*------------------------------------------------------------------*/
/* GAP, Connections and Bonding
*------------------------------------------------------------------*/
bool connected (void);
bool disconnect (void);
bool setConnInterval (uint16_t min, uint16_t max);
bool setConnIntervalMS (uint16_t min_ms, uint16_t max_ms);
bool setConnSupervisionTimeout(uint16_t timeout);
bool setConnSupervisionTimeoutMS(uint16_t timeout_ms);
uint8_t connected (void); // Number of connected
bool connected (uint16_t conn_hdl);
uint16_t connHandle (void);
bool connPaired (void);
uint16_t connInterval (void);
bool requestPairing (void);
void clearBonds (void);
// Alias to BLEConnection API()
bool disconnect (uint16_t conn_hdl);
bool requestPairing (uint16_t conn_hdl);
ble_gap_addr_t getPeerAddr (void);
uint8_t getPeerAddr (uint8_t addr[6]);
uint16_t getMaxMtu(uint8_t role);
void printInfo(void);
BLEConnection* Connection(uint16_t conn_hdl);
/*------------------------------------------------------------------*/
/* Callbacks
*------------------------------------------------------------------*/
void setConnectCallback ( BLEGap::connect_callback_t fp);
void setDisconnectCallback( BLEGap::disconnect_callback_t fp);
void setEventCallback ( void (*fp) (ble_evt_t*) );
void setRssiCallback(rssi_callback_t fp);
void setEventCallback( void (*fp) (ble_evt_t*) );
COMMENT_OUT ( bool setPIN(const char* pin); )
@@ -188,9 +196,11 @@ class AdafruitBluefruit
* Although declare as public, it is meant to be invoked by internal
* code. User should not call these directly
*------------------------------------------------------------------*/
void _startConnLed (void);
void _stopConnLed (void);
void _setConnLed (bool on_off);
void _startConnLed (void);
void _stopConnLed (void);
void _setConnLed (bool on_off);
void printInfo(void);
private:
/*------------- SoftDevice Configuration -------------*/
@@ -198,32 +208,34 @@ class AdafruitBluefruit
uint32_t attr_table_size;
uint8_t service_changed;
uint8_t uuid128_max;
// Bandwidth configuration
struct {
uint16_t mtu_max;
uint8_t event_len;
uint8_t hvn_qsize;
uint8_t wrcmd_qsize;
}prph, central;
}_sd_cfg;
uint8_t _prph_count;
uint8_t _central_count;
// Peripheral Preferred Connection Parameters (PPCP)
ble_gap_conn_params_t _ppcp;
// Actual connection interval in use
uint16_t _conn_interval;
int8_t _tx_power;
ble_gap_sec_params_t _sec_param;
SemaphoreHandle_t _ble_event_sem;
SemaphoreHandle_t _soc_event_sem;
TimerHandle_t _led_blink_th;
bool _led_conn;
BLEDfu _dfu_svc;
uint16_t _conn_hdl;
BLEGap::connect_callback_t _connect_cb;
BLEGap::disconnect_callback_t _disconnect_cb;
BLEConnection* _connection[BLE_MAX_CONNECTION];
rssi_callback_t _rssi_cb;
void (*_event_cb) (ble_evt_t*);
COMMENT_OUT(
@@ -64,4 +64,8 @@
// Converts an integer of 625ms units to msecs
#define MS625TO1000(u625) ( ((u625)*5) / 8 )
typedef void (*ble_connect_callback_t ) (uint16_t conn_hdl);
typedef void (*ble_disconnect_callback_t ) (uint16_t conn_hdl, uint8_t reason);
#endif /* BLUEFRUIT_COMMON_H_ */
@@ -47,7 +47,7 @@ err_t BLEBas::begin(void)
// Invoke base class begin()
VERIFY_STATUS( BLEService::begin() );
_battery.setProperties(CHR_PROPS_READ | CHR_PROPS_NOTIFY); // could support notify
_battery.setProperties(CHR_PROPS_READ | CHR_PROPS_NOTIFY);
_battery.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS);
_battery.setFixedLen(1);
VERIFY_STATUS( _battery.begin() );
@@ -64,3 +64,8 @@ bool BLEBas::notify(uint8_t level)
{
return _battery.notify8(level);
}
bool BLEBas::notify(uint16_t conn_hdl, uint8_t level)
{
return _battery.notify8(conn_hdl, level);
}
@@ -52,7 +52,9 @@ class BLEBas : public BLEService
virtual err_t begin(void);
bool write (uint8_t level);
bool notify(uint8_t level);
bool notify(uint16_t conn_hdl, uint8_t level);
};
@@ -85,18 +85,18 @@ static uint16_t crc16(const uint8_t* data_p, uint8_t length)
return crc;
}
static void bledfu_control_wr_authorize_cb(BLECharacteristic& chr, ble_gatts_evt_write_t* request)
static void bledfu_control_wr_authorize_cb(uint16_t conn_hdl, BLECharacteristic* chr, ble_gatts_evt_write_t* request)
{
if ( (request->handle == chr.handles().value_handle) &&
if ( (request->handle == chr->handles().value_handle) &&
(request->op != BLE_GATTS_OP_PREP_WRITE_REQ) &&
(request->op != BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) &&
(request->op != BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL))
{
uint16_t conn_hdl = Bluefruit.connHandle();
BLEConnection* conn = Bluefruit.Connection(conn_hdl);
ble_gatts_rw_authorize_reply_params_t reply = { .type = BLE_GATTS_AUTHORIZE_TYPE_WRITE };
if ( !chr.notifyEnabled() )
if ( !chr->notifyEnabled(conn_hdl) )
{
reply.params.write.gatt_status = BLE_GATT_STATUS_ATTERR_CPS_CCCD_CONFIG_ERROR;
sd_ble_gatts_rw_authorize_reply(conn_hdl, &reply);
@@ -135,13 +135,13 @@ static void bledfu_control_wr_authorize_cb(BLECharacteristic& chr, ble_gatts_evt
sd_ble_gatts_sys_attr_get(conn_hdl, peer_data->sys_attr, &sysattr_len, BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS);
// Get Bond Data or using Address if not bonded
peer_data->addr = Bluefruit.Gap.getPeerAddr(conn_hdl);
peer_data->addr = conn->getPeerAddr();
if ( Bluefruit.Gap.paired(conn_hdl) )
if ( conn->paired() )
{
bond_keys_t bkeys;
if ( bond_load_keys( BLE_GAP_ROLE_PERIPH, Bluefruit.Gap._get_peer(conn_hdl)->ediv, &bkeys ) )
if ( conn->loadKeys(&bkeys) )
{
peer_data->addr = bkeys.peer_id.id_addr_info;
peer_data->irk = bkeys.peer_id.id_info;
@@ -154,7 +154,7 @@ static void bledfu_control_wr_authorize_cb(BLECharacteristic& chr, ble_gatts_evt
// Initiate DFU Sequence and reboot into DFU OTA mode
Bluefruit.Advertising.restartOnDisconnect(false);
Bluefruit.disconnect();
conn->disconnect();
// Set GPReset to DFU OTA
enum { DFU_OTA_MAGIC = 0xB1 };
@@ -213,22 +213,20 @@ err_t BLEHidAdafruit::begin(void)
VERIFY_STATUS( BLEHidGeneric::begin() );
// Attempt to change the connection interval to 11.25-15 ms when starting HID
Bluefruit.setConnInterval(9, 12);
Bluefruit.Periph.setConnInterval(9, 12);
return ERROR_NONE;
}
/*------------------------------------------------------------------*/
/* Keyboard
/* Keyboard Multiple Connections
*------------------------------------------------------------------*/
void blehid_ada_keyboard_output_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset)
void BLEHidAdafruit::blehid_ada_keyboard_output_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len)
{
LOG_LV2("HID", "Keyboard LED : 0x%02X", data[0]);
VERIFY(len == 1, );
BLEHidAdafruit& svc = (BLEHidAdafruit&) chr.parentService();
if ( svc._kbd_led_cb ) svc._kbd_led_cb(data[0]);
BLEHidAdafruit& svc = (BLEHidAdafruit&) chr->parentService();
if ( svc._kbd_led_cb ) svc._kbd_led_cb(conn_hdl, data[0]);
}
void BLEHidAdafruit::setKeyboardLedCallback(kbd_led_cb_t fp)
@@ -242,18 +240,18 @@ void BLEHidAdafruit::setKeyboardLedCallback(kbd_led_cb_t fp)
_chr_boot_keyboard_output->setWriteCallback(fp ? blehid_ada_keyboard_output_cb : NULL);
}
bool BLEHidAdafruit::keyboardReport(hid_keyboard_report_t* report)
bool BLEHidAdafruit::keyboardReport(uint16_t conn_hdl, hid_keyboard_report_t* report)
{
if ( isBootMode() )
{
return bootKeyboardReport(report, sizeof(hid_keyboard_report_t));
return bootKeyboardReport(conn_hdl, report, sizeof(hid_keyboard_report_t));
}else
{
return inputReport( REPORT_ID_KEYBOARD, report, sizeof(hid_keyboard_report_t));
return inputReport(conn_hdl, REPORT_ID_KEYBOARD, report, sizeof(hid_keyboard_report_t));
}
}
bool BLEHidAdafruit::keyboardReport(uint8_t modifier, uint8_t keycode[6])
bool BLEHidAdafruit::keyboardReport(uint16_t conn_hdl, uint8_t modifier, uint8_t keycode[6])
{
hid_keyboard_report_t report =
{
@@ -261,22 +259,10 @@ bool BLEHidAdafruit::keyboardReport(uint8_t modifier, uint8_t keycode[6])
};
memcpy(report.keycode, keycode, 6);
return keyboardReport(&report);
return keyboardReport(conn_hdl, &report);
}
bool BLEHidAdafruit::keyboardReport(uint8_t modifier, uint8_t keycode0, uint8_t keycode1, uint8_t keycode2, uint8_t keycode3, uint8_t keycode4, uint8_t keycode5)
{
hid_keyboard_report_t report =
{
.modifier = modifier,
.reserved = 0,
.keycode = { keycode0, keycode1, keycode2, keycode3, keycode4, keycode5 }
};
return keyboardReport(&report);
}
bool BLEHidAdafruit::keyPress(char ch)
bool BLEHidAdafruit::keyPress(uint16_t conn_hdl, char ch)
{
hid_keyboard_report_t report;
varclr(&report);
@@ -284,18 +270,18 @@ bool BLEHidAdafruit::keyPress(char ch)
report.modifier = ( HID_ASCII_TO_KEYCODE[(uint8_t)ch].shift ) ? KEYBOARD_MODIFIER_LEFTSHIFT : 0;
report.keycode[0] = HID_ASCII_TO_KEYCODE[(uint8_t)ch].keycode;
return keyboardReport(&report);
return keyboardReport(conn_hdl, &report);
}
bool BLEHidAdafruit::keyRelease(void)
bool BLEHidAdafruit::keyRelease(uint16_t conn_hdl)
{
hid_keyboard_report_t report;
varclr(&report);
return keyboardReport(&report);
return keyboardReport(conn_hdl, &report);
}
bool BLEHidAdafruit::keySequence(const char* str, int interal)
bool BLEHidAdafruit::keySequence(uint16_t conn_hdl, const char* str, int interval)
{
// Send each key in sequence
char ch;
@@ -303,15 +289,15 @@ bool BLEHidAdafruit::keySequence(const char* str, int interal)
{
char lookahead = *str;
keyPress(ch);
delay(interal);
keyPress(conn_hdl, ch);
delay(interval);
/* Only need to empty report if the next character is NULL or the same with
* the current one, else no need to send */
if ( lookahead == ch || lookahead == 0 )
{
keyRelease();
delay(interal);
keyRelease(conn_hdl);
delay(interval);
}
}
@@ -321,37 +307,37 @@ bool BLEHidAdafruit::keySequence(const char* str, int interal)
/*------------------------------------------------------------------*/
/* Consumer Media Key
*------------------------------------------------------------------*/
bool BLEHidAdafruit::consumerReport(uint16_t usage_code)
bool BLEHidAdafruit::consumerReport(uint16_t conn_hdl, uint16_t usage_code)
{
return inputReport( REPORT_ID_CONSUMER_CONTROL, &usage_code, sizeof(usage_code));
return inputReport(conn_hdl, REPORT_ID_CONSUMER_CONTROL, &usage_code, sizeof(usage_code));
}
bool BLEHidAdafruit::consumerKeyPress(uint16_t usage_code)
bool BLEHidAdafruit::consumerKeyPress(uint16_t conn_hdl, uint16_t usage_code)
{
return consumerReport(usage_code);
return consumerReport(conn_hdl, usage_code);
}
bool BLEHidAdafruit::consumerKeyRelease(void)
bool BLEHidAdafruit::consumerKeyRelease(uint16_t conn_hdl)
{
uint16_t usage = 0;
return consumerReport(usage);
return consumerReport(conn_hdl, usage);
}
/*------------------------------------------------------------------*/
/* Mouse
*------------------------------------------------------------------*/
bool BLEHidAdafruit::mouseReport(hid_mouse_report_t* report)
bool BLEHidAdafruit::mouseReport(uint16_t conn_hdl, hid_mouse_report_t* report)
{
if ( isBootMode() )
{
return bootMouseReport(report, sizeof(hid_mouse_report_t));
return bootMouseReport(conn_hdl, report, sizeof(hid_mouse_report_t));
}else
{
return inputReport( REPORT_ID_MOUSE, report, sizeof(hid_mouse_report_t));
return inputReport(conn_hdl, REPORT_ID_MOUSE, report, sizeof(hid_mouse_report_t));
}
}
bool BLEHidAdafruit::mouseReport(uint8_t buttons, int8_t x, int8_t y, int8_t wheel, int8_t pan)
bool BLEHidAdafruit::mouseReport(uint16_t conn_hdl, uint8_t buttons, int8_t x, int8_t y, int8_t wheel, int8_t pan)
{
hid_mouse_report_t report =
{
@@ -364,31 +350,114 @@ bool BLEHidAdafruit::mouseReport(uint8_t buttons, int8_t x, int8_t y, int8_t whe
_mse_buttons = buttons;
return mouseReport(&report);
return mouseReport(conn_hdl, &report);
}
bool BLEHidAdafruit::mouseButtonPress(uint16_t conn_hdl, uint8_t buttons)
{
_mse_buttons = buttons;
return mouseReport(conn_hdl, buttons, 0, 0, 0, 0);
}
bool BLEHidAdafruit::mouseButtonRelease(uint16_t conn_hdl)
{
return mouseReport(conn_hdl, 0, 0, 0, 0, 0);
}
bool BLEHidAdafruit::mouseMove(uint16_t conn_hdl, int8_t x, int8_t y)
{
return mouseReport(conn_hdl, _mse_buttons, x, y, 0, 0);
}
bool BLEHidAdafruit::mouseScroll(uint16_t conn_hdl, int8_t scroll)
{
return mouseReport(conn_hdl, _mse_buttons, 0, 0, scroll, 0);
}
bool BLEHidAdafruit::mousePan(uint16_t conn_hdl, int8_t pan)
{
return mouseReport(conn_hdl, _mse_buttons, 0, 0, 0, pan);
}
/*------------------------------------------------------------------*/
/* Single Connections
*------------------------------------------------------------------*/
//------------- Keyboard -------------//
bool BLEHidAdafruit::keyboardReport(hid_keyboard_report_t* report)
{
return keyboardReport(BLE_GATT_HANDLE_INVALID, report);
}
bool BLEHidAdafruit::keyboardReport(uint8_t modifier, uint8_t keycode[6])
{
return keyboardReport(BLE_GATT_HANDLE_INVALID, modifier, keycode);
}
bool BLEHidAdafruit::keyPress(char ch)
{
return keyPress(BLE_GATT_HANDLE_INVALID, ch);
}
bool BLEHidAdafruit::keyRelease(void)
{
return keyRelease(BLE_GATT_HANDLE_INVALID);
}
bool BLEHidAdafruit::keySequence(const char* str, int interval)
{
return keySequence(BLE_GATT_HANDLE_INVALID, str, interval);
}
//------------- Consumer Media Keys -------------//
bool BLEHidAdafruit::consumerReport(uint16_t usage_code)
{
return consumerReport(BLE_GATT_HANDLE_INVALID, usage_code);
}
bool BLEHidAdafruit::consumerKeyPress(uint16_t usage_code)
{
return consumerKeyPress(BLE_GATT_HANDLE_INVALID, usage_code);
}
bool BLEHidAdafruit::consumerKeyRelease(void)
{
return consumerKeyRelease(BLE_GATT_HANDLE_INVALID);
}
//------------- Mouse -------------//
bool BLEHidAdafruit::mouseReport(hid_mouse_report_t* report)
{
return mouseReport(BLE_GATT_HANDLE_INVALID, report);
}
bool BLEHidAdafruit::mouseReport(uint8_t buttons, int8_t x, int8_t y, int8_t wheel, int8_t pan)
{
return mouseReport(BLE_GATT_HANDLE_INVALID, buttons, x, y, wheel, pan);
}
bool BLEHidAdafruit::mouseButtonPress(uint8_t buttons)
{
_mse_buttons = buttons;
return mouseReport(buttons, 0, 0, 0, 0);
return mouseButtonPress(BLE_GATT_HANDLE_INVALID, buttons);
}
bool BLEHidAdafruit::mouseButtonRelease(void)
{
return mouseReport(0, 0, 0, 0, 0);
return mouseButtonRelease(BLE_GATT_HANDLE_INVALID);
}
bool BLEHidAdafruit::mouseMove(int8_t x, int8_t y)
{
return mouseReport(_mse_buttons, x, y, 0, 0);
return mouseMove(BLE_GATT_HANDLE_INVALID, x, y);
}
bool BLEHidAdafruit::mouseScroll(int8_t scroll)
{
return mouseReport(_mse_buttons, 0, 0, scroll, 0);
return mouseScroll(BLE_GATT_HANDLE_INVALID, scroll);
}
bool BLEHidAdafruit::mousePan(int8_t pan)
{
return mouseReport(_mse_buttons, 0, 0, 0, pan);
return mousePan(BLE_GATT_HANDLE_INVALID, pan);
}
@@ -46,30 +46,45 @@
class BLEHidAdafruit : public BLEHidGeneric
{
public:
/*--------- Callback Signatures ----------*/
typedef void (*kbd_led_cb_t) (uint8_t leds_bitmap);
// Callback Signatures
typedef void (*kbd_led_cb_t) (uint16_t conn_hdl, uint8_t leds_bitmap);
BLEHidAdafruit(void);
virtual err_t begin(void);
// Keyboard
//------------- Keyboard -------------//
// Single connection
void setKeyboardLedCallback(kbd_led_cb_t fp);
bool keyboardReport(hid_keyboard_report_t* report);
bool keyboardReport(uint8_t modifier, uint8_t keycode[6]);
bool keyboardReport(uint8_t modifier, uint8_t keycode0, uint8_t keycode1=0, uint8_t keycode2=0, uint8_t keycode3=0, uint8_t keycode4=0, uint8_t keycode5=0);
void setKeyboardLedCallback(kbd_led_cb_t fp);
bool keyPress(char ch);
bool keyRelease(void);
bool keySequence(const char* str, int interal=5);
bool keySequence(const char* str, int interval=5);
// Consumer Media Keys
// Multiple connections
bool keyboardReport(uint16_t conn_hdl, hid_keyboard_report_t* report);
bool keyboardReport(uint16_t conn_hdl, uint8_t modifier, uint8_t keycode[6]);
bool keyPress(uint16_t conn_hdl, char ch);
bool keyRelease(uint16_t conn_hdl);
bool keySequence(uint16_t conn_hdl, const char* str, int interval=5);
//------------- Consumer Media Keys -------------//
// Single connection
bool consumerReport(uint16_t usage_code);
bool consumerKeyPress(uint16_t usage_code);
bool consumerKeyRelease(void);
// Mouse
// Multiple connections
bool consumerReport(uint16_t conn_hdl, uint16_t usage_code);
bool consumerKeyPress(uint16_t conn_hdl, uint16_t usage_code);
bool consumerKeyRelease(uint16_t conn_hdl);
//------------- Mouse -------------//
// Single connection
bool mouseReport(hid_mouse_report_t* report);
bool mouseReport(uint8_t buttons, int8_t x, int8_t y, int8_t wheel=0, int8_t pan=0);
@@ -80,11 +95,22 @@ class BLEHidAdafruit : public BLEHidGeneric
bool mouseScroll(int8_t scroll);
bool mousePan(int8_t pan);
// Multiple connections
bool mouseReport(uint16_t conn_hdl, hid_mouse_report_t* report);
bool mouseReport(uint16_t conn_hdl, uint8_t buttons, int8_t x, int8_t y, int8_t wheel=0, int8_t pan=0);
bool mouseButtonPress(uint16_t conn_hdl, uint8_t buttons);
bool mouseButtonRelease(uint16_t conn_hdl);
bool mouseMove(uint16_t conn_hdl, int8_t x, int8_t y);
bool mouseScroll(uint16_t conn_hdl, int8_t scroll);
bool mousePan(uint16_t conn_hdl, int8_t pan);
protected:
uint8_t _mse_buttons;
kbd_led_cb_t _kbd_led_cb;
friend void blehid_ada_keyboard_output_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset);
static void blehid_ada_keyboard_output_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len);
};
#endif /* BLEHIDADAFRUIT_H_ */
@@ -130,9 +130,11 @@ void BLEHidGeneric::setOutputReportCallback(uint8_t reportID, BLECharacteristic:
/*------------------------------------------------------------------*/
/* Callbacks
*------------------------------------------------------------------*/
void blehid_generic_protocol_mode_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset)
void BLEHidGeneric::blehid_generic_protocol_mode_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len)
{
BLEHidGeneric& svc = (BLEHidGeneric&) chr.parentService();
(void) conn_hdl;
BLEHidGeneric& svc = (BLEHidGeneric&) chr->parentService();
svc._protocol_mode = *data;
LOG_LV2("HID", "Protocol Mode : %d (0 Boot, 1 Report)", *data);
@@ -156,7 +158,7 @@ err_t BLEHidGeneric::begin(void)
_chr_protocol->setProperties(CHR_PROPS_READ | CHR_PROPS_WRITE_WO_RESP);
_chr_protocol->setFixedLen(1);
_chr_protocol->setWriteCallback(blehid_generic_protocol_mode_cb);
_chr_protocol->setWriteCallback(BLEHidGeneric::blehid_generic_protocol_mode_cb);
VERIFY_STATUS( _chr_protocol->begin() );
_chr_protocol->write8(_protocol_mode);
}
@@ -249,22 +251,36 @@ err_t BLEHidGeneric::begin(void)
/*------------------------------------------------------------------*/
/* Input Report
*------------------------------------------------------------------*/
bool BLEHidGeneric::inputReport(uint8_t reportID, void const* data, int len)
bool BLEHidGeneric::inputReport(uint16_t conn_hdl, uint8_t reportID, void const* data, int len)
{
// index is ID-1
uint8_t const idx = ( reportID ? (reportID-1) : 0 );
return _chr_inputs[idx].notify(conn_hdl, (uint8_t const*) data, len);
}
return _chr_inputs[idx].notify( (uint8_t const*) data, len);
bool BLEHidGeneric::bootKeyboardReport(uint16_t conn_hdl, void const* data, int len)
{
return _chr_boot_keyboard_input->notify(conn_hdl, data, len);
}
bool BLEHidGeneric::bootMouseReport(uint16_t conn_hdl, void const* data, int len)
{
return _chr_boot_mouse_input->notify(conn_hdl, data, len);
}
bool BLEHidGeneric::inputReport(uint8_t reportID, void const* data, int len)
{
return inputReport(BLE_CONN_HANDLE_INVALID, reportID, data, len);
}
bool BLEHidGeneric::bootKeyboardReport(void const* data, int len)
{
return _chr_boot_keyboard_input->notify(data, len);
return bootKeyboardReport(BLE_CONN_HANDLE_INVALID, data, len);
}
bool BLEHidGeneric::bootMouseReport(void const* data, int len)
{
return _chr_boot_mouse_input->notify(data, len);
return bootMouseReport(BLE_CONN_HANDLE_INVALID, data, len);
}
/*------------------------------------------------------------------*/
@@ -115,11 +115,16 @@ class BLEHidGeneric : public BLEService
bool isBootMode(void) { return _protocol_mode == HID_PROTOCOL_MODE_BOOT; }
// Report
// Send Report to default connection
bool inputReport(uint8_t reportID, void const* data, int len);
bool bootKeyboardReport(void const* data, int len);
bool bootMouseReport(void const* data, int len);
// Send report to specific connection
bool inputReport(uint16_t conn_hdl, uint8_t reportID, void const* data, int len);
bool bootKeyboardReport(uint16_t conn_hdl, void const* data, int len);
bool bootMouseReport(uint16_t conn_hdl, void const* data, int len);
protected:
uint8_t _num_input;
uint8_t _num_output;
@@ -149,7 +154,7 @@ class BLEHidGeneric : public BLEService
BLECharacteristic _chr_control;
friend void blehid_generic_protocol_mode_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset);
static void blehid_generic_protocol_mode_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len);
};
//--------------------------------------------------------------------+
@@ -106,8 +106,6 @@ typedef struct ATTR_PACKED
VERIFY_STATIC ( sizeof(midi_split_packet_t) == (BLE_MIDI_TX_BUFFER_SIZE + 1) );
void blemidi_write_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset);
/*------------------------------------------------------------------*/
/* IMPLEMENTATION
*------------------------------------------------------------------*/
@@ -120,7 +118,12 @@ BLEMidi::BLEMidi(uint16_t fifo_depth)
bool BLEMidi::notifyEnabled(void)
{
return Bluefruit.connPaired() && _io.notifyEnabled();
return _io.notifyEnabled();
}
bool BLEMidi::notifyEnabled(uint16_t conn_hdl)
{
return _io.notifyEnabled(conn_hdl);
}
void BLEMidi::setWriteCallback(midi_write_cb_t fp)
@@ -148,12 +151,12 @@ err_t BLEMidi::begin(void)
// IO characteristic
_io.setProperties(CHR_PROPS_READ | CHR_PROPS_WRITE | CHR_PROPS_WRITE_WO_RESP | CHR_PROPS_NOTIFY);
_io.setPermission(SECMODE_ENC_NO_MITM, SECMODE_ENC_NO_MITM);
_io.setWriteCallback(blemidi_write_cb);
_io.setWriteCallback(BLEMidi::blemidi_write_cb);
VERIFY_STATUS( _io.begin() );
// Attempt to change the connection interval to 11.25-15 ms when starting HID
Bluefruit.setConnInterval(9, 12);
Bluefruit.Periph.setConnInterval(9, 12);
return ERROR_NONE;
}
@@ -161,16 +164,15 @@ err_t BLEMidi::begin(void)
/*------------------------------------------------------------------*/
/* Callbacks
*------------------------------------------------------------------*/
void blemidi_write_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset)
void BLEMidi::blemidi_write_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len)
{
(void) offset;
if ( len < 3 ) return;
BLEMidi& midi_svc = (BLEMidi&) chr.parentService();
midi_svc._write_handler(data, len);
BLEMidi& midi_svc = (BLEMidi&) chr->parentService();
midi_svc._write_handler(conn_hdl, data, len);
}
void BLEMidi::_write_handler(uint8_t* data, uint16_t len)
void BLEMidi::_write_handler(uint16_t conn_hdl, uint8_t* data, uint16_t len)
{
// drop the BLE MIDI header byte
data++;
@@ -178,7 +180,6 @@ void BLEMidi::_write_handler(uint8_t* data, uint16_t len)
while (len)
{
// timestamp low byte followed by a MIDI status,
// so we drop the timestamp low byte
if ( isStatusByte(data[0]) && isStatusByte(data[1]) )
@@ -200,7 +201,7 @@ void BLEMidi::_write_handler(uint8_t* data, uint16_t len)
}
// Call write callback if configured
if ( _write_cb ) _write_cb();
if ( _write_cb ) _write_cb(conn_hdl);
#ifdef MIDI_LIB_INCLUDED
// read while possible if configured
@@ -52,13 +52,15 @@ extern const uint8_t BLEMIDI_UUID_CHR_IO[];
class BLEMidi: public BLEService, public Stream
{
public:
typedef void (*midi_write_cb_t) (void);
typedef void (*midi_write_cb_t) (uint16_t conn_hdl);
BLEMidi(uint16_t fifo_depth = BLE_MIDI_DEFAULT_FIFO_DEPTH);
virtual err_t begin(void);
void begin(int baudrate); // MidiInterface
bool notifyEnabled(void);
bool notifyEnabled(void);
bool notifyEnabled(uint16_t conn_hdl);
bool send(uint8_t data[], uint8_t len);
bool sendSplit(uint8_t data[], uint8_t len);
@@ -89,9 +91,9 @@ class BLEMidi: public BLEService, public Stream
void* _midilib_obj;
void _write_handler(uint8_t* data, uint16_t len);
void _write_handler(uint16_t conn_hdl, uint8_t* data, uint16_t len);
friend void blemidi_write_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset);
static void blemidi_write_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len);
};
@@ -60,41 +60,31 @@ const uint8_t BLEUART_UUID_CHR_TXD[] =
0x93, 0xF3, 0xA3, 0xB5, 0x03, 0x00, 0x40, 0x6E
};
/**
* Constructor
*/
// Constructor
BLEUart::BLEUart(uint16_t fifo_depth)
: BLEService(BLEUART_UUID_SERVICE), _txd(BLEUART_UUID_CHR_TXD), _rxd(BLEUART_UUID_CHR_RXD)
{
_rx_fifo = NULL;
_rx_cb = NULL;
_rx_fifo_depth = fifo_depth;
_rx_cb = NULL;
_notify_cb = NULL;
_tx_fifo = NULL;
_tx_buffered = 0;
_buffered_th = NULL;
_tx_buffered = false;
}
/**
* Destructor
*/
// Destructor
BLEUart::~BLEUart()
{
if ( _tx_fifo ) delete _tx_fifo;
}
/**
* Callback when received new data
* @param chr
* @param data
* @param len
* @param offset
*/
void bleuart_rxd_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset)
// Callback when received new data
void BLEUart::bleuart_rxd_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len)
{
(void) offset;
BLEUart& svc = (BLEUart&) chr->parentService();
BLEUart& svc = (BLEUart&) chr.parentService();
svc._rx_fifo->write(data, len);
#if CFG_DEBUG >= 2
@@ -103,38 +93,14 @@ void bleuart_rxd_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_
#endif
// invoke user callback
if ( svc._rx_cb ) svc._rx_cb();
if ( svc._rx_cb ) svc._rx_cb(conn_hdl);
}
/**
* Timer callback periodically to send TX packet (if enabled).
* @param timer
*/
void bleuart_txd_buffered_hdlr(TimerHandle_t timer)
void BLEUart::bleuart_txd_cccd_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint16_t value)
{
BLEUart* svc = (BLEUart*) pvTimerGetTimerID(timer);
BLEUart& svc = (BLEUart&) chr->parentService();
// skip if null (unlikely)
if ( !svc->_tx_fifo ) return;
// flush tx data
(void) svc->flush_tx_buffered();
}
void bleuart_txd_cccd_cb(BLECharacteristic& chr, uint16_t value)
{
BLEUart& svc = (BLEUart&) chr.parentService();
if ( svc._buffered_th == NULL) return;
// Enable TXD timer if configured
if (value & BLE_GATT_HVX_NOTIFICATION)
{
xTimerStart(svc._buffered_th, 0); // if started --> timer got reset
}else
{
xTimerStop(svc._buffered_th, 0);
}
if ( svc._notify_cb ) svc._notify_cb(conn_hdl, value & BLE_GATT_HVX_NOTIFICATION);
}
void BLEUart::setRxCallback( rx_callback_t fp)
@@ -142,30 +108,31 @@ void BLEUart::setRxCallback( rx_callback_t fp)
_rx_cb = fp;
}
void BLEUart::setNotifyCallback(notify_callback_t fp)
{
_notify_cb = fp;
_txd.setCccdWriteCallback( fp ? BLEUart::bleuart_txd_cccd_cb : NULL );
}
/**
* Enable packet buffered for TXD
* Note: packet is sent right away if it reach MTU bytes
* @param enable true or false
*/
void BLEUart::bufferTXD(uint8_t enable)
void BLEUart::bufferTXD(bool enable)
{
_tx_buffered = enable;
if ( enable )
{
// enable cccd callback to start timer when enabled
_txd.setCccdWriteCallback(bleuart_txd_cccd_cb);
// Create FIFO for TX TODO Larger MTU Size
// Create FIFO for TXD
if ( _tx_fifo == NULL )
{
_tx_fifo = new Adafruit_FIFO(1);
_tx_fifo->begin( Bluefruit.Gap.getMaxMtuByConnCfg(CONN_CFG_PERIPHERAL) );
_tx_fifo->begin( Bluefruit.getMaxMtu(BLE_GAP_ROLE_PERIPH) );
}
}else
{
_txd.setCccdWriteCallback(NULL);
if ( _tx_fifo ) delete _tx_fifo;
}
}
@@ -178,7 +145,7 @@ err_t BLEUart::begin(void)
// Invoke base class begin()
VERIFY_STATUS( BLEService::begin() );
uint16_t max_mtu = Bluefruit.Gap.getMaxMtuByConnCfg(CONN_CFG_PERIPHERAL);
uint16_t max_mtu = Bluefruit.getMaxMtu(BLE_GAP_ROLE_PERIPH);
// Add TXD Characteristic
_txd.setProperties(CHR_PROPS_NOTIFY);
@@ -190,7 +157,7 @@ err_t BLEUart::begin(void)
// Add RXD Characteristic
_rxd.setProperties(CHR_PROPS_WRITE | CHR_PROPS_WRITE_WO_RESP);
_rxd.setWriteCallback(bleuart_rxd_cb);
_rxd.setWriteCallback(BLEUart::bleuart_rxd_cb);
// TODO enable encryption when bonding is enabled
_rxd.setPermission(SECMODE_NO_ACCESS, SECMODE_OPEN);
@@ -203,31 +170,12 @@ err_t BLEUart::begin(void)
bool BLEUart::notifyEnabled(void)
{
return _txd.notifyEnabled();
return this->notifyEnabled(Bluefruit.connHandle());
}
void BLEUart::_disconnect_cb(void)
bool BLEUart::notifyEnabled(uint16_t conn_hdl)
{
if (_buffered_th)
{
xTimerDelete(_buffered_th, 0);
_buffered_th = NULL;
if (_tx_fifo) _tx_fifo->clear();
}
}
void BLEUart::_connect_cb (void)
{
if ( _tx_buffered )
{
// create TXD timer TODO take connInterval into account
// ((5*ms2tick(Bluefruit.connInterval())) / 4) / 2
_buffered_th = xTimerCreate(NULL, ms2tick(10), true, this, bleuart_txd_buffered_hdlr);
// Start the timer
xTimerStart(_buffered_th, 0);
}
return _txd.notifyEnabled(conn_hdl);
}
/*------------------------------------------------------------------*/
@@ -239,44 +187,56 @@ int BLEUart::read (void)
return read(&ch, 1) ? (int) ch : EOF;
}
int BLEUart::read (uint8_t * buf, size_t size)
int BLEUart::read(uint8_t * buf, size_t size)
{
return _rx_fifo->read(buf, size);
}
size_t BLEUart::write (uint8_t b)
size_t BLEUart::write(uint8_t b)
{
return write(&b, 1);
return this->write(Bluefruit.connHandle(), &b, 1);
}
size_t BLEUart::write (const uint8_t *content, size_t len)
size_t BLEUart::write(uint16_t conn_hdl, uint8_t b)
{
return this->write(conn_hdl, &b, 1);
}
size_t BLEUart::write(const uint8_t *content, size_t len)
{
return this->write(Bluefruit.connHandle(), content, len);
}
size_t BLEUart::write(uint16_t conn_hdl, const uint8_t *content, size_t len)
{
BLEConnection* conn = Bluefruit.Connection(conn_hdl);
VERIFY(conn, 0);
// skip if not enabled
if ( !notifyEnabled(conn_hdl) ) return 0;
// notify right away if txd buffered is not enabled
if ( !(_tx_buffered && _tx_fifo) )
{
return _txd.notify(content, len) ? len : 0;
return _txd.notify(conn_hdl, content, len) ? len : 0;
}else
{
// skip if not enabled
if ( !notifyEnabled() ) return 0;
uint16_t written = _tx_fifo->write(content, len);
// TODO multiple prph connections
// Not up to GATT MTU, notify will be sent later by TXD timer handler
if ( _tx_fifo->count() < (Bluefruit.Gap.getMTU( Bluefruit.connHandle() ) - 3) )
if ( _tx_fifo->count() < (conn->getMtu() - 3) )
{
return len;
}
else
{
// TX fifo has enough data, send notify right away
VERIFY( flush_tx_buffered(), 0);
VERIFY( flushTXD(conn_hdl), 0);
// still more data left, send them all
if ( written < len )
{
VERIFY( _txd.notify(content+written, len-written), written);
VERIFY(_txd.notify(conn_hdl, content+written, len-written), written);
}
return len;
@@ -300,19 +260,26 @@ void BLEUart::flush (void)
_rx_fifo->clear();
}
bool BLEUart::flush_tx_buffered(void)
bool BLEUart::flushTXD (void)
{
uint16_t max_hvx = Bluefruit.Gap.getMTU( Bluefruit.connHandle() ) - 3;
uint8_t* ff_data = (uint8_t*) rtos_malloc( max_hvx );
return flushTXD(Bluefruit.connHandle());
}
if (!ff_data) return false;
bool BLEUart::flushTXD(uint16_t conn_hdl)
{
BLEConnection* conn = Bluefruit.Connection(conn_hdl);
VERIFY(conn);
uint16_t len = _tx_fifo->read(ff_data, max_hvx);
uint16_t const gatt_mtu = conn->getMtu() - 3;
uint8_t* ff_data = (uint8_t*) rtos_malloc( gatt_mtu );
VERIFY(ff_data);
uint16_t len = _tx_fifo->read(ff_data, gatt_mtu);
bool result = true;
if ( len )
{
result = _txd.notify(ff_data, len);
result = _txd.notify(conn_hdl, ff_data, len);
}
rtos_free(ff_data);
+27 -20
View File
@@ -51,23 +51,36 @@ extern const uint8_t BLEUART_UUID_CHR_TXD[];
class BLEUart : public BLEService, public Stream
{
public:
typedef void (*rx_callback_t) (void);
typedef void (*rx_callback_t) (uint16_t conn_hdl);
typedef void (*notify_callback_t)(uint16_t conn_hdl, bool enabled);
BLEUart(uint16_t fifo_depth = BLE_UART_DEFAULT_FIFO_DEPTH);
virtual ~BLEUart();
virtual err_t begin(void);
bool notifyEnabled (void);
bool notifyEnabled(void);
bool notifyEnabled(uint16_t conn_hdl);
void setRxCallback (rx_callback_t fp);
void bufferTXD (uint8_t enable);
void setNotifyCallback(notify_callback_t fp);
void bufferTXD(bool enable);
bool flushTXD (void);
bool flushTXD (uint16_t conn_hdl);
// Stream API
virtual int read ( void );
virtual int read ( uint8_t * buf, size_t size );
int read ( char * buf, size_t size ) { return read( (uint8_t*) buf, size); }
virtual size_t write ( uint8_t b );
virtual size_t write ( const uint8_t *content, size_t len );
virtual size_t write ( const uint8_t *content, size_t len);
virtual size_t write (uint16_t conn_hdl, uint8_t b);
virtual size_t write (uint16_t conn_hdl, const uint8_t *content, size_t len);
virtual int available ( void );
virtual int peek ( void );
virtual void flush ( void );
@@ -80,26 +93,20 @@ class BLEUart : public BLEService, public Stream
BLECharacteristic _rxd;
// RXD
Adafruit_FIFO* _rx_fifo;
uint16_t _rx_fifo_depth;
rx_callback_t _rx_cb;
Adafruit_FIFO* _rx_fifo;
uint16_t _rx_fifo_depth;
// TXD
Adafruit_FIFO* _tx_fifo;
uint8_t _tx_buffered;
TimerHandle_t _buffered_th;
Adafruit_FIFO* _tx_fifo;
bool _tx_buffered; // default is false
bool flush_tx_buffered(void);
// Callbacks
rx_callback_t _rx_cb;
notify_callback_t _notify_cb;
// from BLEService
virtual void _disconnect_cb(void);
virtual void _connect_cb(void);
friend void bleuart_rxd_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset);
friend void bleuart_txd_cccd_cb(BLECharacteristic& chr, uint16_t value);
friend void bleuart_txd_buffered_hdlr(TimerHandle_t timer);
// Static Method for callbacks
static void bleuart_rxd_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len);
static void bleuart_txd_cccd_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint16_t value);
};
#endif /* BLEUART_H_ */
@@ -108,7 +108,7 @@ static void bond_save_keys_dfr (uint8_t role, uint16_t conn_hdl, bond_keys_t* bk
//------------- save device name -------------//
char devname[CFG_MAX_DEVNAME_LEN] = { 0 };
Bluefruit.Gap.getPeerName(conn_hdl, devname, CFG_MAX_DEVNAME_LEN);
Bluefruit.Connection(conn_hdl)->getPeerName(devname, CFG_MAX_DEVNAME_LEN);
// If couldn't get devname then use peer mac address
if ( !devname[0] )
@@ -126,13 +126,8 @@ static void bond_save_keys_dfr (uint8_t role, uint16_t conn_hdl, bond_keys_t* bk
bool bond_save_keys (uint8_t role, uint16_t conn_hdl, bond_keys_t* bkeys)
{
uint8_t* buf = (uint8_t*) rtos_malloc( sizeof(bond_keys_t) );
VERIFY(buf);
memcpy(buf, bkeys, sizeof(bond_keys_t));
// queue to execute in Ada Callback thread
ada_callback(buf, bond_save_keys_dfr, role, conn_hdl, buf);
ada_callback(bkeys, sizeof(bond_keys_t), bond_save_keys_dfr, role, conn_hdl, bkeys);
return true;
}
@@ -191,7 +186,7 @@ bool bond_save_cccd (uint8_t role, uint16_t conn_hdl, uint16_t ediv)
VERIFY(ediv != 0xFFFF);
// queue to execute in Ada Callback thread
ada_callback(NULL, bond_save_cccd_dfr, role, conn_hdl, ediv);
ada_callback(NULL, 0, bond_save_cccd_dfr, role, conn_hdl, ediv);
return true;
}
@@ -269,7 +264,7 @@ void bond_print_list(uint8_t role)
}
bool bond_find_cntr(ble_gap_addr_t* addr, bond_keys_t* bkeys)
bool bond_find_cntr(ble_gap_addr_t const * addr, bond_keys_t* bkeys)
{
bool found = false;
@@ -67,7 +67,7 @@ bool bond_load_cccd (uint8_t role, uint16_t conn_hdl, uint16_t ediv);
void bond_print_list(uint8_t role);
bool bond_find_cntr(ble_gap_addr_t* addr, bond_keys_t* bkeys);
bool bond_find_cntr(ble_gap_addr_t const * addr, bond_keys_t* bkeys);
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more