├── LICENSE ├── README.md ├── examples ├── diagnostics │ └── diagnostics.ino ├── heartbeat │ └── heartbeat.ino └── pingpong │ └── ping-pong-example.ino ├── library.properties └── src ├── BLE_Central.cpp ├── BLE_Group.cpp ├── BLE_Group.h └── BLE_Peripheral.cpp /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BLE_Group library 2 | 3 | A library that works with Particle Gen3 devices to create a local group over Bluetooth Low Energy (BLE) to publish/subscribe messages. 4 | 5 | The library works by connecting the devices over BLE. One of the devices in the group acts in the Central role, while the others act in the Peripheral role. 6 | 7 | Data is exchanged one to one from the Central to each Peripheral. However, when data is sent from a Peripheral to the Central, it both "consumes" the data locally, as well as forwarding the data to all the other Peripherals that it is connected with. 8 | 9 | ## Typical Usage 10 | 11 | You will need 2 or more devices. One will act as the Central, and the other(s) as Peripheral. 12 | 13 | On the Central device: 14 | 15 | ``` 16 | #include "BLE_Group.h" 17 | BLE_Group *group; 18 | 19 | void callbackFunc(const char *event, const char *data) 20 | { 21 | Log.info("Event: %s, Data: %s", event, data); 22 | } 23 | 24 | void setup() { 25 | group = new BLE_Group_Central(1); // The parameter is the groupID 26 | group->subscribe("test", callbackFunc); 27 | } 28 | 29 | void loop() { 30 | static uint32_t scan_time = millis(); 31 | static uint32_t publish_time = millis(); 32 | // Scan when the number of connected devices is less than the max 33 | if (group->devices_connected() < BLE_GROUP_MAX_PERIPHERALS && (millis() - scan_time) > 3000) { 34 | group->scan(); 35 | scan_time = millis(); 36 | } 37 | // Publish every 10 seconds 38 | if (group->devices_connected() > 0 && (millis() - publish_time) > 10000) { 39 | group->publish("test-central", "Some data"); 40 | publish_time = millis(); 41 | } 42 | } 43 | ``` 44 | 45 | On the peripheral device: 46 | 47 | ``` 48 | #include "BLE_Group.h" 49 | BLE_Group *group; 50 | 51 | void callbackFunc(const char *event, const char *data) 52 | { 53 | Log.info("Event: %s, Data: %s", event, data); 54 | } 55 | 56 | void setup() { 57 | group = new BLE_Group_Peripheral(1); // The parameter is the groupID 58 | group->subscribe("test", callbackFunc); 59 | } 60 | 61 | void loop() { 62 | static uint32_t publish_time = millis(); 63 | if ((millis() - publish_time) > 10000) { 64 | group->publish("test-periph", "Some Data"); 65 | publish_time = millis(); 66 | } 67 | } 68 | ``` 69 | 70 | It is also possible to use the same application on the Central and Peripheral devices, and use configuration variables stored in EEPROM to decide which is which. The examples provided with the library show how to do that. 71 | 72 | ## Examples 73 | 74 | * __Diagnostics:__ Cloud-started throughput test, as well as reporting of group health by publishing Connect/Disconnect events 75 | * __Heartbeat:__ Each device in the group will publish a heartbeat once per minute. The other devices will all receive it and use Particle.publish to send to the Particle cloud 76 | * __Ping-pong:__ For just 2 devices (one Central and one Peripheral), send a number of events with small data payload back and forth and publish the total amount of time it took, to test message latency. 77 | -------------------------------------------------------------------------------- /examples/diagnostics/diagnostics.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * Project ble-group-diagnostics 3 | * Description: Several diagnostic tools for a local BLE Group 4 | * Author: Mariano Goluboff 5 | * Date: January 24th, 2020 6 | * 7 | * Instructions: 8 | * - Deploy firmware to several Gen3 devices (Argon or Boron) 9 | * - Use the Particle Console to run SetCentral on one device and SetPeripheral on the others 10 | * all with the same numerical input (e.g. 5) 11 | * - Reboot all devices 12 | */ 13 | #include "BLE_Group.h" 14 | #include "Particle.h" 15 | #include 16 | 17 | SYSTEM_THREAD(ENABLED); 18 | 19 | SerialLogHandler logHandler; 20 | 21 | BLE_Group *group; 22 | 23 | int eeprom_address = 0; 24 | struct bleConfig { 25 | uint8_t is_central; 26 | uint32_t group_number; 27 | }; 28 | 29 | bool dev_configured; 30 | bool keep_scanning = true; 31 | 32 | unsigned long heartbeat_time, scan_time; 33 | 34 | // Set the device flash configuration to peripheral. 35 | // It is applied at the next reboot. 36 | int setAsPeripheral(String extra) 37 | { 38 | bleConfig myConfig = { 0, (uint32_t)std::atoi(extra)}; 39 | EEPROM.put(eeprom_address, myConfig); 40 | return 0; 41 | } 42 | 43 | // Set the device flash configuration to central. 44 | // It is applied at the next reboot 45 | int setAsCentral(String extra) 46 | { 47 | bleConfig myConfig = { 1, (uint32_t)std::atoi(extra)}; 48 | EEPROM.put(eeprom_address, myConfig); 49 | return 0; 50 | } 51 | 52 | /* 53 | * throughputTest is a function exposed to the Particle Cloud to publish 54 | * packets over the local BLE Group as fast as possible, to test the 55 | * throughput to other devices 56 | * 57 | * To start a test, call the ThroughputTest cloud function. The parameter 58 | * passed is the packet size that will be sent. 100 packets are sent. 59 | */ 60 | int throughputTest(String extra) 61 | { 62 | if (!dev_configured) return -1; 63 | keep_scanning = false; 64 | size_t packet_size = std::atoi(extra); 65 | char packet[packet_size]; 66 | memset(packet, 'A', packet_size-1); 67 | packet[packet_size-1] = '\0'; 68 | group->publish("tx-start", ""); 69 | for (size_t idx=0;idx<100;idx++) 70 | { 71 | group->publish("tx", packet); 72 | } 73 | group->publish("tx-end", ""); 74 | keep_scanning = true; 75 | return 0; 76 | } 77 | 78 | /* 79 | * throughputFunc is the callback function to be used to subscribe 80 | * to the "tx" event, which is used for the throughput testing. 81 | * 82 | * Once all the packets are received, it publishes to the Particle 83 | * Cloud the results of the test (total bytes and kbps) 84 | */ 85 | unsigned long throughtput_timer; 86 | uint32_t data_received; 87 | void throughputFunc(const char *event, const char *data) 88 | { 89 | if(strcmp(event, "tx-start") == 0) 90 | { 91 | throughtput_timer = millis(); 92 | data_received = 0; 93 | } else if (strcmp(event,"tx") == 0) 94 | { 95 | data_received += strlen(data)+1; 96 | } else if (strcmp(event,"tx-end") == 0) 97 | { 98 | unsigned long total_time = millis() - throughtput_timer; 99 | char buf[100]; 100 | snprintf(buf, sizeof(buf), "Bytes: %lu, Time: %lu, kbps: %lu", data_received, total_time, ( (data_received*8/1024)/(total_time/1000) )); 101 | Particle.publish("throughput", buf, PRIVATE); 102 | } 103 | } 104 | 105 | /* 106 | * Callback functions to monitor connection/disconnection from the 107 | * local BLE Group. 108 | */ 109 | void onConnect(const BlePeerDevice& peer, void* context) 110 | { 111 | Particle.publish("Connected", peer.address().toString(), PRIVATE); 112 | } 113 | void onDisconnect(const BlePeerDevice& peer, void* context) 114 | { 115 | Particle.publish("Disconnected", peer.address().toString(), PRIVATE); 116 | } 117 | 118 | /* 119 | * Callback to monitor RSSI of other BLE devices with our service 120 | */ 121 | void onScan(const BleScanResult& scan, void* context) 122 | { 123 | char buf[100]; 124 | #if defined(SYSTEM_VERSION_v300ALPHA1) && (SYSTEM_VERSION >= SYSTEM_VERSION_v300ALPHA1) 125 | snprintf(buf, sizeof(buf), "Address: %s, RSSI: %d", scan.address().toString().c_str(), scan.rssi()); 126 | #else 127 | snprintf(buf, sizeof(buf), "Address: %s, RSSI: %d", scan.address.toString().c_str(), scan.rssi); 128 | #endif 129 | Particle.publish("Scan Result", buf, PRIVATE); 130 | } 131 | 132 | // setup() runs once, when the device is first turned on. 133 | void setup() { 134 | Particle.function("SetPeripheral", setAsPeripheral); 135 | Particle.function("SetCentral", setAsCentral); 136 | Particle.function("ThroughputTest", throughputTest); 137 | bleConfig myConfig; 138 | EEPROM.get(eeprom_address, myConfig); 139 | if (myConfig.is_central == 0xFF) 140 | { 141 | dev_configured = false; 142 | } 143 | else if (myConfig.is_central == 1) 144 | { 145 | group = new BLE_Group_Central(myConfig.group_number); 146 | dev_configured = true; 147 | } 148 | else if (myConfig.is_central == 0) 149 | { 150 | group = new BLE_Group_Peripheral(myConfig.group_number); 151 | dev_configured = true; 152 | } 153 | if (dev_configured) 154 | { 155 | group->subscribe("tx", throughputFunc); 156 | group->onConnect(onConnect, NULL); 157 | group->onDisconnect(onDisconnect, NULL); 158 | } 159 | scan_time = 0; 160 | heartbeat_time = 0; 161 | // Speed up transmission (this works for Particle devices talking to Particle devices 162 | // but can break communications to iPhones as they have higher latencies) 163 | BLE.setPPCP(12, 12, 0, 200); 164 | // Increase transmit power to max 165 | BLE.setTxPower(8); 166 | } 167 | 168 | // loop() runs over and over again, as quickly as it can execute. 169 | void loop() { 170 | if (dev_configured && group->isCentral()) 171 | { 172 | // Scan for more devices to build the group if we're the Central device 173 | // and we haven't hit the maximum number of devices yet. 174 | if (keep_scanning && group->devices_connected() < BLE_GROUP_MAX_PERIPHERALS && (millis() - scan_time) > 3000) 175 | { 176 | group->scan(onScan, NULL); 177 | scan_time = millis(); 178 | } 179 | } 180 | } -------------------------------------------------------------------------------- /examples/heartbeat/heartbeat.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * Project ble-group-heart-beat-example 3 | * Description: Create local BLE communication among multiple devices and monitor long term connectivity 4 | * Author: Mariano Goluboff 5 | * Date: January 24th, 2020 6 | * 7 | * Instructions: 8 | * - Deploy firmware to several Gen3 devices (Argon or Boron) 9 | * - Use the Particle Console to run SetCentral on one device and SetPeripheral on the others 10 | * all with the same numerical input (e.g. 5) 11 | * - Reboot all devices 12 | */ 13 | #include "BLE_Group.h" 14 | #include "Particle.h" 15 | #include 16 | 17 | SYSTEM_THREAD(ENABLED); 18 | 19 | SerialLogHandler logHandler; 20 | 21 | BLE_Group *group; 22 | 23 | int eeprom_address = 0; 24 | struct bleConfig { 25 | uint8_t is_central; 26 | uint32_t group_number; 27 | }; 28 | 29 | bool dev_configured; 30 | 31 | unsigned long heartbeat_time, scan_time; 32 | 33 | // Set the device flash configuration to peripheral. 34 | // It is applied at the next reboot. 35 | int setAsPeripheral(String extra) 36 | { 37 | bleConfig myConfig = { 0, (uint32_t)std::atoi(extra)}; 38 | EEPROM.put(eeprom_address, myConfig); 39 | return 0; 40 | } 41 | 42 | // Set the device flash configuration to central. 43 | // It is applied at the next reboot 44 | int setAsCentral(String extra) 45 | { 46 | bleConfig myConfig = { 1, (uint32_t)std::atoi(extra)}; 47 | EEPROM.put(eeprom_address, myConfig); 48 | return 0; 49 | } 50 | 51 | void kickFunc(const char *event, const char *data) 52 | { 53 | Particle.publish("kick-received", data, PRIVATE); 54 | } 55 | 56 | /* 57 | * Callback functions to monitor connection/disconnection from the 58 | * local BLE Group. 59 | */ 60 | void onConnect(const BlePeerDevice& peer, void* context) 61 | { 62 | Particle.publish("Connected", peer.address().toString(), PRIVATE); 63 | } 64 | void onDisconnect(const BlePeerDevice& peer, void* context) 65 | { 66 | Particle.publish("Disconnected", peer.address().toString(), PRIVATE); 67 | } 68 | 69 | 70 | // setup() runs once, when the device is first turned on. 71 | void setup() { 72 | Particle.function("SetPeripheral", setAsPeripheral); 73 | Particle.function("SetCentral", setAsCentral); 74 | bleConfig myConfig; 75 | EEPROM.get(eeprom_address, myConfig); 76 | if (myConfig.is_central == 0xFF) 77 | { 78 | dev_configured = false; 79 | } 80 | else if (myConfig.is_central == 1) 81 | { 82 | group = new BLE_Group_Central(myConfig.group_number); 83 | dev_configured = true; 84 | } 85 | else if (myConfig.is_central == 0) 86 | { 87 | group = new BLE_Group_Peripheral(myConfig.group_number); 88 | dev_configured = true; 89 | } 90 | if (dev_configured) 91 | { 92 | group->subscribe("kick", kickFunc); 93 | group->onConnect(onConnect, NULL); 94 | group->onDisconnect(onDisconnect, NULL); 95 | } 96 | scan_time = 0; 97 | heartbeat_time = 0; 98 | // Speed up transmission (this works for Particle devices talking to Particle devices 99 | // but can break communications to iPhones as they have higher latencies) 100 | BLE.setPPCP(12, 12, 0, 200); 101 | // Increase transmit power to max 102 | BLE.setTxPower(8); 103 | } 104 | 105 | // loop() runs over and over again, as quickly as it can execute. 106 | void loop() { 107 | if (dev_configured && group->isCentral()) 108 | { 109 | // Scan for more devices to build the group if we're the Central device 110 | // and we haven't hit the maximum number of devices yet. 111 | if (group->devices_connected() < BLE_GROUP_MAX_PERIPHERALS && (millis() - scan_time) > 3000) 112 | { 113 | group->scan(); 114 | scan_time = millis(); 115 | } 116 | } 117 | if(dev_configured && (millis() - heartbeat_time) > 60000 ) 118 | { 119 | group->publish("kick", System.deviceID()); 120 | heartbeat_time = millis(); 121 | } 122 | } -------------------------------------------------------------------------------- /examples/pingpong/ping-pong-example.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * Project ble-group-ping-pong-example 3 | * Description: Create local BLE communication between two devices and run ping pong testing 4 | * Author: Mariano Goluboff 5 | * Date: January 24th, 2020 6 | * 7 | * Instructions: 8 | * - Deploy firmware to two Gen3 devices (Argon or Boron) 9 | * - Use the Particle Console to run SetPeripheral one one device and SetCentral on the other, 10 | * both with the same numerical input (e.g. 5) 11 | * - Reboot both devices 12 | * - Run PingPong on one of the devices, with a value of 10 or 100 13 | */ 14 | #include "BLE_Group.h" 15 | #include "Particle.h" 16 | #include 17 | 18 | SYSTEM_THREAD(ENABLED); 19 | 20 | SerialLogHandler logHandler; 21 | 22 | BLE_Group *group; 23 | 24 | int eeprom_address = 0; 25 | struct bleConfig { 26 | uint8_t is_central; 27 | uint32_t group_number; 28 | }; 29 | 30 | bool dev_configured; 31 | bool keep_scanning = true; 32 | 33 | unsigned long start_time; 34 | 35 | // Set the device flash configuration to peripheral. 36 | // It is applied at the next reboot. 37 | int setAsPeripheral(String extra) 38 | { 39 | bleConfig myConfig = { 0, (uint32_t)std::atoi(extra)}; 40 | EEPROM.put(eeprom_address, myConfig); 41 | return 0; 42 | } 43 | 44 | // Set the device flash configuration to central. 45 | // It is applied at the next reboot 46 | int setAsCentral(String extra) 47 | { 48 | bleConfig myConfig = { 1, (uint32_t)std::atoi(extra)}; 49 | EEPROM.put(eeprom_address, myConfig); 50 | return 0; 51 | } 52 | 53 | // Start a ping-pong test for the number of round trips 54 | // that is pased as argument 55 | int startTest(String extra) 56 | { 57 | start_time = millis(); 58 | return group->publish("ping", extra); 59 | } 60 | 61 | // Send a pong when we receive a ping 62 | void pingFunc(const char *event, const char *data) 63 | { 64 | group->publish("pong", data); 65 | } 66 | 67 | // Receive the pong response and process it. 68 | void pongFunc(const char *event, const char *data) 69 | { 70 | int count = std::atoi(data); 71 | if (count > 0) 72 | { 73 | // if we're not yet to 0 in the count, send a ping having reduced by 1 74 | char buf[10]; 75 | snprintf(buf, sizeof(buf), "%d", count - 1); 76 | group->publish("ping", buf); 77 | } 78 | else 79 | { 80 | // Get the end time and publish it 81 | unsigned long end_time = millis() - start_time; 82 | char buf[30]; 83 | snprintf(buf, sizeof(buf), "Total time: %lu", end_time); 84 | Particle.publish("PingPong", buf, PRIVATE); 85 | } 86 | } 87 | 88 | String isConnected; 89 | 90 | // setup() runs once, when the device is first turned on. 91 | void setup() { 92 | Particle.function("SetPeripheral", setAsPeripheral); 93 | Particle.function("PingPong", startTest); 94 | Particle.function("SetCentral", setAsCentral); 95 | bleConfig myConfig; 96 | EEPROM.get(eeprom_address, myConfig); 97 | if (myConfig.is_central == 0xFF) 98 | { 99 | dev_configured = false; 100 | } 101 | else if (myConfig.is_central == 1) 102 | { 103 | group = new BLE_Group_Central(myConfig.group_number); 104 | dev_configured = true; 105 | } 106 | else if (myConfig.is_central == 0) 107 | { 108 | group = new BLE_Group_Peripheral(myConfig.group_number); 109 | dev_configured = true; 110 | } 111 | if (dev_configured) 112 | { 113 | group->subscribe("ping", pingFunc); 114 | group->subscribe("pong", pongFunc); 115 | } 116 | // Speed up transmission (this works for Particle devices talking to Particle devices 117 | // but can break communications to iPhones as they have higher latencies) 118 | BLE.setPPCP(12, 12, 0, 200); 119 | // Increase transmit power to max 120 | BLE.setTxPower(8); 121 | } 122 | 123 | // loop() runs over and over again, as quickly as it can execute. 124 | void loop() { 125 | if (dev_configured && group->isCentral()) 126 | { 127 | // Since this is point to point communications, stop scanning when we have a connection 128 | keep_scanning = (group->devices_connected() > 0) ? false : true; 129 | // Scan for more devices to build the group if we're the Central device 130 | // and we haven't hit the maximum number of devices yet. 131 | if (keep_scanning && group->devices_connected() < BLE_GROUP_MAX_PERIPHERALS) 132 | { 133 | group->scan(); 134 | } 135 | } 136 | } -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | # Fill in information about your library then remove # from the start of lines 2 | # https://docs.particle.io/guide/tools-and-features/libraries/#library-properties-fields 3 | name=BLE_Group 4 | version=0.4.0 5 | author=Mariano Goluboff 6 | license=LGPL 7 | sentence=Create a group of Gen3 Particle devices that can communicate locally over BLE publish/subscribe. 8 | # paragraph=a longer description of this library, always prepended with sentence when shown 9 | # url=the URL of the project, like https://github.com/mygithub_user/my_repo 10 | repository=git repository for the project, like https://github.com/particle-iot/ble-group-library.git 11 | # architectures=a list of supported boards if this library is hardware dependent, like particle-photon,particle-electron 12 | -------------------------------------------------------------------------------- /src/BLE_Central.cpp: -------------------------------------------------------------------------------- 1 | #include "BLE_Group.h" 2 | 3 | #define SCAN_RESULT_MAX 30 4 | 5 | BleScanResult scanResults[SCAN_RESULT_MAX]; 6 | 7 | static void onDisconnected(const BlePeerDevice &peer, void *context) 8 | { 9 | BLE_Group_Central *ctx = (BLE_Group_Central *)context; 10 | Log.info("BLE Device disconnected: %02X:%02X:%02X:%02X:%02X:%02X", peer.address()[0], 11 | peer.address()[1], peer.address()[2], peer.address()[3], peer.address()[4], peer.address()[5]); 12 | for (uint8_t idx = 0; idx < BLE_GROUP_MAX_PERIPHERALS; idx++) 13 | { 14 | if (ctx->peripherals[idx].in_use && ctx->peripherals[idx].peer.address() == peer.address()) 15 | { 16 | ctx->peripherals[idx].in_use = false; 17 | } 18 | } 19 | if (ctx->_onDisconnectHandler != nullptr) 20 | { 21 | ctx->_onDisconnectHandler(peer, ctx->_onDisconnectContext); 22 | } 23 | } 24 | 25 | static void onDataReceived(const uint8_t *data, size_t len, const BlePeerDevice& peer, void* context) 26 | { 27 | BLE_Group_Central *ctx = (BLE_Group_Central *)context; 28 | ctx->receive((const char *)data, len); 29 | 30 | for (uint8_t idx = 0; idx < BLE_GROUP_MAX_PERIPHERALS; idx++) 31 | { 32 | if (ctx->peripherals[idx].in_use && !(ctx->peripherals[idx].peer.address() == peer.address()) ) 33 | { 34 | ctx->peripherals[idx]._rxCharacteristic.setValue(data, len); 35 | } 36 | } 37 | } 38 | 39 | BLE_Group_Central::BLE_Group_Central(uint32_t groupId) : BLE_Group(groupId) 40 | { 41 | BLE.onDisconnected(onDisconnected, this); 42 | } 43 | 44 | int BLE_Group_Central::scan(ScanEvent handler, void* context) 45 | { 46 | int count = BLE.scan(scanResults, SCAN_RESULT_MAX); 47 | 48 | for (int ii = 0; ii < count; ii++) 49 | { 50 | BleUuid foundService; 51 | uint8_t buf[6]; 52 | size_t len; 53 | 54 | #if defined(SYSTEM_VERSION_v300ALPHA1) && (SYSTEM_VERSION >= SYSTEM_VERSION_v300ALPHA1) 55 | len = scanResults[ii].advertisingData().serviceUUID(&foundService, 1); 56 | #else 57 | len = scanResults[ii].advertisingData.serviceUUID(&foundService, 1); 58 | #endif 59 | if (len > 0 && foundService == serviceUuid) 60 | { 61 | #if defined(SYSTEM_VERSION_v300ALPHA1) && (SYSTEM_VERSION >= SYSTEM_VERSION_v300ALPHA1) 62 | Log.info("Found our service with RSSI: %d", scanResults[ii].rssi()); 63 | #else 64 | Log.info("Found our service with RSSI: %d", scanResults[ii].rssi); 65 | #endif 66 | if(handler != NULL) 67 | { 68 | handler(scanResults[ii], context); 69 | } 70 | #if defined(SYSTEM_VERSION_v300ALPHA1) && (SYSTEM_VERSION >= SYSTEM_VERSION_v300ALPHA1) 71 | len = scanResults[ii].advertisingData().customData(buf, 6); 72 | #else 73 | len = scanResults[ii].advertisingData.customData(buf, 6); 74 | #endif 75 | if (len > 0 && memcmp(buf+2, &_groupID, 4) == 0) 76 | { 77 | bool connected = false; 78 | for (size_t kk = 0; kk < BLE_GROUP_MAX_PERIPHERALS; kk++) 79 | { 80 | #if defined(SYSTEM_VERSION_v300ALPHA1) && (SYSTEM_VERSION >= SYSTEM_VERSION_v300ALPHA1) 81 | if (peripherals[kk].in_use && peripherals[kk].peer.address() == scanResults[ii].address()) 82 | #else 83 | if (peripherals[kk].in_use && peripherals[kk].peer.address() == scanResults[ii].address) 84 | #endif 85 | { 86 | connected = true; 87 | break; 88 | } 89 | if (!connected) 90 | { 91 | for (size_t hh = 0; hh < BLE_GROUP_MAX_PERIPHERALS; hh++) 92 | { 93 | if (!peripherals[hh].in_use) 94 | { 95 | #if defined(SYSTEM_VERSION_v300ALPHA1) && (SYSTEM_VERSION >= SYSTEM_VERSION_v300ALPHA1) 96 | peripherals[hh].peer = BLE.connect(scanResults[ii].address()); 97 | #else 98 | peripherals[hh].peer = BLE.connect(scanResults[ii].address); 99 | #endif 100 | if (peripherals[hh].peer.connected()) 101 | { 102 | Log.info("successfully connected!"); 103 | if (_onConnectHandler != nullptr) 104 | { 105 | _onConnectHandler(peripherals[hh].peer, _onConnectContext); 106 | } 107 | connected = true; 108 | peripherals[hh].in_use = true; 109 | peripherals[hh].peer.getCharacteristicByUUID(peripherals[hh]._txCharacteristic, txUuid); 110 | peripherals[hh]._txCharacteristic.onDataReceived(onDataReceived, this); 111 | peripherals[hh].peer.getCharacteristicByUUID(peripherals[hh]._rxCharacteristic, rxUuid); 112 | } 113 | break; 114 | } 115 | } 116 | } 117 | } 118 | } 119 | else 120 | { 121 | Log.info("Found a device but has another Group ID: %lu, our ID: %lu", *(uint32_t *)(buf+2), _groupID); 122 | } 123 | } 124 | } 125 | return 0; 126 | } 127 | 128 | int BLE_Group_Central::scan() 129 | { 130 | return this->scan(NULL, NULL); 131 | } 132 | 133 | uint8_t BLE_Group_Central::devices_connected() 134 | { 135 | uint8_t count = 0; 136 | for (uint8_t idx = 0; idx < BLE_GROUP_MAX_PERIPHERALS; idx++) 137 | { 138 | if (peripherals[idx].in_use) 139 | count++; 140 | } 141 | return count; 142 | } 143 | 144 | int BLE_Group_Central::publish(const char *event, const char *data) 145 | { 146 | MessageQ new_item; 147 | int ret = 0; 148 | int intermediate; 149 | int packet_len = new_item.encode(event, data); 150 | for (uint8_t idx = 0; idx < BLE_GROUP_MAX_PERIPHERALS; idx++) 151 | { 152 | if (peripherals[idx].in_use) 153 | { 154 | intermediate = peripherals[idx]._rxCharacteristic.setValue((const uint8_t *)new_item._data, (size_t)std::min(packet_len,MESSAGE_SIZE)); 155 | if (intermediate < 0) ret = intermediate; 156 | } 157 | } 158 | return ret; 159 | } -------------------------------------------------------------------------------- /src/BLE_Group.cpp: -------------------------------------------------------------------------------- 1 | #include "BLE_Group.h" 2 | #include "string.h" 3 | 4 | 5 | BLE_Group::BLE_Group(uint32_t groupID) 6 | { 7 | _groupID = groupID; 8 | _onConnectHandler = nullptr; 9 | _onDisconnectHandler = nullptr; 10 | } 11 | 12 | void BLE_Group::subscribe(const char *event, EventHandler handler) 13 | { 14 | Subscriber item = Subscriber(event, handler); 15 | _sub_q.push_back(item); 16 | } 17 | 18 | BLE_Group::Subscriber::Subscriber(const char *event, EventHandler handler) 19 | { 20 | _event = event; 21 | _handler = handler; 22 | } 23 | 24 | int BLE_Group::MessageQ::encode(const char *event, const char *data) 25 | { 26 | uint8_t ev_len, dat_len; 27 | 28 | if ( (ev_len = strlen(event)) > EVENT_MAX) { 29 | Log.warn("Event length longer than max value, truncating."); 30 | ev_len = EVENT_MAX; 31 | } 32 | // Maximum data size is maximum message size (set by BLE) minus 2 33 | // because we're using 2 bytes to store the length of event and 34 | // the length of the data field 35 | if ( (dat_len = strlen(data)) > (MESSAGE_SIZE - 2 - ev_len)) { 36 | Log.warn("Data length too long, truncating"); 37 | dat_len = (MESSAGE_SIZE - 2 - ev_len); 38 | } 39 | // The data will look like this: 40 | // | Event Length | Event | ... | ... | Data length | Data | ... | ... | 41 | _data[0] = ev_len; 42 | memcpy(_data+1, event, ev_len); 43 | _data[1+ev_len] = dat_len; 44 | memcpy(_data+2+ev_len, data, dat_len); 45 | return ev_len+dat_len+2; 46 | } 47 | 48 | void BLE_Group::MessageQ::store(const char *data, size_t len) 49 | { 50 | memcpy(_data, data, std::min(len, (size_t)MESSAGE_SIZE)); 51 | if (_data[0] > EVENT_MAX) _data[0] = EVENT_MAX; 52 | } 53 | 54 | void BLE_Group::MessageQ::getEvent(char *event) 55 | { 56 | memcpy(event, _data+1, _data[0]); 57 | event[(uint8_t)_data[0]] = '\0'; 58 | } 59 | 60 | void BLE_Group::MessageQ::getData(char *ev_data) 61 | { 62 | uint8_t ev_len, dat_len; 63 | ev_len = (uint8_t)_data[0]; 64 | dat_len = (uint8_t)_data[1+ev_len]; 65 | memcpy(ev_data, _data+2+ev_len, dat_len); 66 | ev_data[dat_len] = '\0'; 67 | ev_data[MESSAGE_SIZE-1] = '\0'; 68 | } 69 | 70 | void BLE_Group::receive(const char *data, size_t len) 71 | { 72 | MessageQ new_item; 73 | char event[EVENT_MAX+1], ev_data[MESSAGE_SIZE-1]; 74 | new_item.store(data, len); 75 | new_item.getEvent(event); 76 | new_item.getData(ev_data); 77 | //Log.info("Event: %s, Data: %s", event, ev_data); 78 | for(Subscriber sub : _sub_q) 79 | { 80 | size_t sub_length = strlen(sub.getEvent()); 81 | if (strlen(event) >= sub_length && !strncmp(sub.getEvent(), event, sub_length)) 82 | { 83 | sub.getHandler()(event, ev_data); 84 | } 85 | } 86 | } 87 | 88 | void BLE_Group::onConnect(ConnectionEvent handler, void* context) 89 | { 90 | _onConnectHandler = handler; 91 | _onConnectContext = context; 92 | } 93 | void BLE_Group::onDisconnect(ConnectionEvent handler, void* context) 94 | { 95 | _onDisconnectHandler = handler; 96 | _onDisconnectContext = context; 97 | } 98 | 99 | int BLE_Group::scan() 100 | { 101 | Log.warn("Scan should be called as a Central"); 102 | return -1; 103 | } 104 | uint8_t BLE_Group::devices_connected() 105 | { 106 | Log.warn("Devices connected should be called as a Central"); 107 | return 0; 108 | } -------------------------------------------------------------------------------- /src/BLE_Group.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Library for creating a BLE Group for local exchange of data over BLE 3 | * among Gen3 Particle devices. 4 | */ 5 | 6 | #ifndef BleGroup_h 7 | #define BleGroup_h 8 | 9 | #include "Particle.h" 10 | #include 11 | 12 | #define MESSAGE_SIZE 244 13 | #define EVENT_MAX 63 14 | #define BLE_GROUP_MAX_PERIPHERALS 3 15 | 16 | const BleUuid serviceUuid("7030fed9-88ac-43d7-b1ca-ba8c9b2fc755"); 17 | const BleUuid rxUuid("7de067f3-f3a1-4c81-a02f-98777e099f21"); 18 | const BleUuid txUuid("4350f719-9d57-40e6-9cb5-9922e1bae48a"); 19 | 20 | typedef void (*EventHandler)(const char *event_name, const char *data); 21 | typedef void (*ConnectionEvent)(const BlePeerDevice& peer, void* context); 22 | typedef void (*ScanEvent)(const BleScanResult& result, void* context); 23 | 24 | class BLE_Group 25 | { 26 | public: 27 | BLE_Group(uint32_t groupID); 28 | ~BLE_Group(); 29 | 30 | void receive(const char *data, size_t len); 31 | virtual void subscribe(const char *event, EventHandler handler); 32 | virtual int publish(const char *event, const char *data) = 0; 33 | virtual int scan(); 34 | virtual int scan(ScanEvent handler, void* context) = 0; 35 | virtual uint8_t devices_connected(); 36 | virtual bool isCentral() = 0; 37 | void onConnect(ConnectionEvent handler, void* context); 38 | void onDisconnect(ConnectionEvent handler, void* context); 39 | 40 | ConnectionEvent _onConnectHandler; 41 | void* _onConnectContext; 42 | ConnectionEvent _onDisconnectHandler; 43 | void* _onDisconnectContext; 44 | 45 | class Subscriber 46 | { 47 | public: 48 | Subscriber(const char *event, EventHandler handler); 49 | const char* getEvent(void) {return _event;}; 50 | EventHandler getHandler(void) {return _handler;}; 51 | 52 | protected: 53 | const char *_event; 54 | EventHandler _handler; 55 | }; 56 | 57 | class MessageQ 58 | { 59 | public: 60 | int encode(const char *event, const char *data); 61 | void store(const char *data, size_t len); 62 | void getEvent(char *event); 63 | void getData(char *data); 64 | char _data[MESSAGE_SIZE]; 65 | }; 66 | 67 | protected: 68 | uint32_t _groupID; 69 | std::deque _sub_q; 70 | }; 71 | 72 | class BLE_Group_Central : public BLE_Group 73 | { 74 | public: 75 | BLE_Group_Central(uint32_t groupId); 76 | virtual int scan(); 77 | virtual int scan(ScanEvent handler, void* context); 78 | virtual int publish(const char *event, const char *data); 79 | virtual uint8_t devices_connected(); 80 | virtual bool isCentral() { return true; }; 81 | 82 | class GroupPeripheral 83 | { 84 | public: 85 | GroupPeripheral() { in_use = false;}; 86 | BlePeerDevice peer; 87 | bool in_use; 88 | BleCharacteristic _txCharacteristic; 89 | BleCharacteristic _rxCharacteristic; 90 | }; 91 | 92 | GroupPeripheral peripherals[BLE_GROUP_MAX_PERIPHERALS]; 93 | }; 94 | 95 | class BLE_Group_Peripheral : public BLE_Group 96 | { 97 | public: 98 | BLE_Group_Peripheral(uint32_t groupId); 99 | virtual int publish(const char *event, const char *data); 100 | virtual bool isCentral() {return false;}; 101 | virtual int scan(ScanEvent handler, void* context) {return -1;}; 102 | 103 | bool connected; 104 | private: 105 | BleCharacteristic _txCharacteristic, _rxCharacteristic; 106 | }; 107 | 108 | #endif -------------------------------------------------------------------------------- /src/BLE_Peripheral.cpp: -------------------------------------------------------------------------------- 1 | #include "BLE_Group.h" 2 | 3 | static void onDataReceived(const uint8_t *data, size_t len, const BlePeerDevice& peer, void* context) 4 | { 5 | BLE_Group_Peripheral *ctx = (BLE_Group_Peripheral *)context; 6 | ctx->receive((const char *)data, len); 7 | } 8 | 9 | static void onPeriphConnected(const BlePeerDevice& peer, void* context) 10 | { 11 | BLE_Group_Peripheral *ctx = (BLE_Group_Peripheral *)context; 12 | ctx->connected = true; 13 | Log.info("Connected to Central"); 14 | if (ctx->_onConnectHandler != nullptr) 15 | { 16 | ctx->_onConnectHandler(peer, ctx->_onConnectContext); 17 | } 18 | BLE.stopAdvertising(); 19 | } 20 | static void onPeriphDisconnected(const BlePeerDevice& peer, void* context) 21 | { 22 | BLE_Group_Peripheral *ctx = (BLE_Group_Peripheral *)context; 23 | ctx->connected = false; 24 | Log.info("Disconnected from Central"); 25 | if (ctx->_onDisconnectHandler != nullptr) 26 | { 27 | ctx->_onDisconnectHandler(peer, ctx->_onDisconnectContext); 28 | } 29 | BLE.advertise(); 30 | } 31 | 32 | BLE_Group_Peripheral::BLE_Group_Peripheral(uint32_t groupId): BLE_Group(groupId) 33 | { 34 | _txCharacteristic = BleCharacteristic("tx", BleCharacteristicProperty::INDICATE, 35 | txUuid, serviceUuid); 36 | _rxCharacteristic = BleCharacteristic("rx", BleCharacteristicProperty::WRITE, 37 | rxUuid, serviceUuid, onDataReceived, this); 38 | 39 | BLE.addCharacteristic(_txCharacteristic); 40 | BLE.addCharacteristic(_rxCharacteristic); 41 | 42 | BleAdvertisingData data; 43 | data.appendServiceUUID(serviceUuid); 44 | 45 | uint8_t custom_data[] = { 0x62, 0x06, 0, 0, 0, 0 }; 46 | memcpy(custom_data+2, &_groupID, 4); 47 | data.appendCustomData(custom_data, sizeof(custom_data), false); 48 | BLE.advertise(&data); 49 | BLE.onConnected(onPeriphConnected, this); 50 | BLE.onDisconnected(onPeriphDisconnected, this); 51 | } 52 | 53 | /* 54 | * Publish a message to the group. 55 | */ 56 | int BLE_Group_Peripheral::publish(const char *event, const char *data) 57 | { 58 | MessageQ new_item; 59 | int ret; 60 | // Create the packet that can be sent over BLE 61 | int packet_len = new_item.encode(event, data); 62 | // Indicate to central 63 | ret = _txCharacteristic.setValue((const uint8_t *)new_item._data, (size_t)std::min(packet_len, MESSAGE_SIZE)); 64 | if (ret != packet_len) { return ret;} 65 | return 0; 66 | } --------------------------------------------------------------------------------