├── .gitignore ├── AUTHORS ├── LICENSE ├── Makefile ├── NOTICE ├── README.md ├── doc ├── overview.edoc ├── rbeacon.md └── utf8 │ └── README.md ├── rebar_dev.config └── src ├── rbeacon.app.src └── rbeacon.erl /.gitignore: -------------------------------------------------------------------------------- 1 | ebin 2 | *.swp 3 | *.dump 4 | edoc-info 5 | .DS_Store 6 | deps/ 7 | doc/*.html 8 | doc/*.css 9 | doc/erlang.png 10 | doc/edoc-info 11 | .rebar 12 | .eunit 13 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Copyright Statements 2 | ==================== 3 | 4 | Copyright (c) 2014 Benoît Chesneau and the contributors 5 | 6 | Contributors 7 | ============ 8 | 9 | Benoit Chesneau 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ERL ?= erl 2 | ERLC ?= erlc 3 | APP := rbeacon 4 | REBAR?= rebar 5 | 6 | .PHONY: deps doc 7 | 8 | all: deps compile 9 | 10 | dev: devbuild 11 | 12 | compile: 13 | @$(REBAR) compile 14 | 15 | deps: 16 | @$(REBAR) get-deps 17 | 18 | doc: dev 19 | $(REBAR) -C rebar_dev.config doc skip_deps=true 20 | 21 | 22 | clean: 23 | @$(REBAR) clean 24 | @rm -f t/*.beam 25 | @rm -f doc/*.html doc/*.css doc/edoc-info doc/*.png 26 | 27 | distclean: clean 28 | @$(REBAR) delete-deps 29 | @rm -rf deps 30 | 31 | dialyzer: compile 32 | @dialyzer -Wno_return -c ebin 33 | 34 | test: all 35 | @$(REBAR) eunit 36 | 37 | 38 | # development 39 | # 40 | devclean: 41 | $(REBAR) -C rebar_dev.config clean 42 | 43 | devbuild: devdeps 44 | $(REBAR) -C rebar_dev.config compile 45 | 46 | devdeps: 47 | $(REBAR) -C rebar_dev.config get-deps 48 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | rbeacon 2 | ------- 3 | 4 | 2014 (c) Benoît Chesneau 5 | 6 | rbeacon is released under the Mozilla Public License Version 2.0. See the LICENSE file for the complete license. 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # rbeacon - LAN discovery and presence. # 4 | 5 | Copyright (c) 2014 Benoît Chesneau. 6 | 7 | __Version:__ 0.3.0 8 | 9 | ## Description 10 | 11 | The rbeacon module implements a peer-to-peer discovery service for local 12 | networks. A beacon can broadcast and/or capture service announcements using UDP 13 | messages on the local area network. This implementation uses IPv4 UDP 14 | broadcasts. You can define the format of your outgoing beacons, and set a filter 15 | that validates incoming beacons. Beacons are sent and received asynchronously in 16 | the background. 17 | 18 | > Note: the current implementation is heavily inspired on 19 | [zbeacon](http://czmq.zeromq.org/manual:zbeacon) from zeromq. 20 | 21 | ## Usage 22 | 23 | Look at the [`rbeacon`](http://github.com/refuge/rbeacon/blob/master/doc/rbeacon.md) module for the API usage. 24 | 25 | > **Note:** You can set the interface on which you broadcast using the 26 | application environment setting `broadast_if` or the the OS environment variable 27 | `RBEACON_INTERFACE`. 28 | 29 | ## Example 30 | 31 | From the rbeacon_test function: 32 | 33 | ``` 34 | {ok, Service} = rbeacon:new(9999), 35 | ?assert(is_pid(Service)), 36 | 37 | ok = rbeacon:set_interval(Service, 100), 38 | ok = rbeacon:publish(Service, <<"announcement">>), 39 | 40 | {ok, Client} = rbeacon:new(9999), 41 | ok = rbeacon:subscribe(Client, <<>>), 42 | 43 | {ok, Msg, _Addr} = rbeacon:recv(Client), 44 | ?assertEqual(Msg, <<"announcement">>), 45 | ok = rbeacon:close(Service), 46 | ok = rbeacon:close(Client), 47 | 48 | {ok, Node1} = rbeacon:new(5670), 49 | {ok, Node2} = rbeacon:new(5670), 50 | {ok, Node3} = rbeacon:new(5670), 51 | 52 | ok = rbeacon:noecho(Node1), 53 | 54 | rbeacon:publish(Node1, <<"Node/1">>), 55 | rbeacon:publish(Node2, <<"Node/2">>), 56 | rbeacon:publish(Node3, <<"GARBAGE">>), 57 | rbeacon:subscribe(Node1, <<"Node">>), 58 | 59 | {ok, Msg2, _Addr} = rbeacon:recv(Node1), 60 | ?assertEqual(Msg2, <<"Node/2">>), 61 | 62 | rbeacon:close(Node1), 63 | rbeacon:close(Node2), 64 | rbeacon:close(Node3). 65 | ``` 66 | 67 | You can also receive from the beacon as message (from the rbeacon_active_test): 68 | 69 | ``` 70 | {ok, Service} = rbeacon:new(9999, [active, noecho]), 71 | ?assert(is_pid(Service)), 72 | 73 | ok = rbeacon:set_interval(Service, 100), 74 | ok = rbeacon:publish(Service, <<"announcement">>), 75 | 76 | {ok, Client} = rbeacon:new(9999, [active]), 77 | ok = rbeacon:subscribe(Client, <<>>), 78 | receive 79 | {rbeacon, Client, <<"announcement">>, _Addr} -> 80 | ok 81 | end, 82 | 83 | ok = rbeacon:close(Service), 84 | receive 85 | {rbeacon, Service, closed} -> ok 86 | end, 87 | 88 | ok = rbeacon:close(Client), 89 | receive 90 | {rbeacon, Client, closed} -> ok 91 | end, 92 | 93 | {ok, Node1} = rbeacon:new(5670, [active, noecho]), 94 | {ok, Node2} = rbeacon:new(5670, [active, noecho]), 95 | {ok, Node3} = rbeacon:new(5670, [active, noecho]), 96 | 97 | rbeacon:publish(Node1, <<"Node/1">>), 98 | rbeacon:publish(Node2, <<"Node/2">>), 99 | rbeacon:publish(Node3, <<"GARBAGE">>), 100 | rbeacon:subscribe(Node1, <<"Node">>), 101 | 102 | Result = loop_sub(Node1, [], 1), 103 | 104 | ?assert(lists:member(<<"Node/2">>, Result)), 105 | 106 | rbeacon:close(Node1), 107 | rbeacon:close(Node2), 108 | rbeacon:close(Node3), 109 | 110 | ok. 111 | ``` 112 | 113 | ## Ownership and License 114 | The contributors are listed in AUTHORS. This project uses the MPL v2 license, 115 | see LICENSE. 116 | 117 | rbeacon uses the 118 | [C4.1 (Collective Code Construction Contract)](http://rfc.zeromq.org/spec:22) 119 | process for contributions. 120 | 121 | ## Development 122 | 123 | Under C4.1 process, you are more than welcome to help us by: 124 | 125 | * join the discussion over anything from design to code style 126 | * try out and [submit issue reports](https://github.com/refuge/rbeacon/issues/new) or feature requests 127 | * pick a task in [issues](https://github.com/refuge/rbeacon/issues) and get it done 128 | * fork the repository and have your own fixes 129 | * send us pull requests 130 | * and even star this project ^_^ 131 | 132 | To run the test suite: 133 | $ rebar eunit 134 | 135 | 136 | ## Modules ## 137 | 138 | 139 | 140 |
rbeacon
141 | 142 | -------------------------------------------------------------------------------- /doc/overview.edoc: -------------------------------------------------------------------------------- 1 | %% -*- erlang -*- 2 | %% 3 | %% This file is part of rbeacon released under the MIT license. 4 | %% See the NOTICE for more information. 5 | 6 | 7 | 8 | @copyright 2014 Benoît Chesneau. 9 | @version 0.3.0 10 | @title rbeacon - LAN discovery and presence. 11 | 12 | @doc 13 | 14 | ## Description 15 | 16 | The rbeacon module implements a peer-to-peer discovery service for local 17 | networks. A beacon can broadcast and/or capture service announcements using UDP 18 | messages on the local area network. This implementation uses IPv4 UDP 19 | broadcasts. You can define the format of your outgoing beacons, and set a filter 20 | that validates incoming beacons. Beacons are sent and received asynchronously in 21 | the background. 22 | 23 | > Note: the current implementation is heavily inspired on 24 | [zbeacon](http://czmq.zeromq.org/manual:zbeacon) from zeromq. 25 | 26 | ## Usage 27 | 28 | Look at the {@link rbeacon} module for the API usage. 29 | 30 | > **Note:** You can set the interface on which you broadcast using the 31 | application environment setting `broadast_if' or the the OS environment variable 32 | `RBEACON_INTERFACE'. 33 | 34 | ## Example 35 | 36 | From the rbeacon_test function: 37 | 38 | ``` 39 | {ok, Service} = rbeacon:new(9999), 40 | ?assert(is_pid(Service)), 41 | 42 | ok = rbeacon:set_interval(Service, 100), 43 | ok = rbeacon:publish(Service, <<"announcement">>), 44 | 45 | {ok, Client} = rbeacon:new(9999), 46 | ok = rbeacon:subscribe(Client, <<>>), 47 | 48 | {ok, Msg, _Addr} = rbeacon:recv(Client), 49 | ?assertEqual(Msg, <<"announcement">>), 50 | 51 | 52 | ok = rbeacon:close(Service), 53 | ok = rbeacon:close(Client), 54 | 55 | {ok, Node1} = rbeacon:new(5670), 56 | {ok, Node2} = rbeacon:new(5670), 57 | {ok, Node3} = rbeacon:new(5670), 58 | 59 | ok = rbeacon:noecho(Node1), 60 | 61 | rbeacon:publish(Node1, <<"Node/1">>), 62 | rbeacon:publish(Node2, <<"Node/2">>), 63 | rbeacon:publish(Node3, <<"GARBAGE">>), 64 | rbeacon:subscribe(Node1, <<"Node">>), 65 | 66 | {ok, Msg2, _Addr} = rbeacon:recv(Node1), 67 | ?assertEqual(Msg2, <<"Node/2">>), 68 | 69 | rbeacon:close(Node1), 70 | rbeacon:close(Node2), 71 | rbeacon:close(Node3). 72 | ''' 73 | 74 | You can also receive from the beacon as message (from the rbeacon_active_test): 75 | 76 | ``` 77 | {ok, Service} = rbeacon:new(9999, [active, noecho]), 78 | ?assert(is_pid(Service)), 79 | 80 | ok = rbeacon:set_interval(Service, 100), 81 | ok = rbeacon:publish(Service, <<"announcement">>), 82 | 83 | {ok, Client} = rbeacon:new(9999, [active]), 84 | ok = rbeacon:subscribe(Client, <<>>), 85 | receive 86 | {rbeacon, Client, <<"announcement">>, _Addr} -> 87 | ok 88 | end, 89 | 90 | ok = rbeacon:close(Service), 91 | receive 92 | {rbeacon, Service, closed} -> ok 93 | end, 94 | 95 | ok = rbeacon:close(Client), 96 | receive 97 | {rbeacon, Client, closed} -> ok 98 | end, 99 | 100 | {ok, Node1} = rbeacon:new(5670, [active, noecho]), 101 | {ok, Node2} = rbeacon:new(5670, [active, noecho]), 102 | {ok, Node3} = rbeacon:new(5670, [active, noecho]), 103 | 104 | rbeacon:publish(Node1, <<"Node/1">>), 105 | rbeacon:publish(Node2, <<"Node/2">>), 106 | rbeacon:publish(Node3, <<"GARBAGE">>), 107 | rbeacon:subscribe(Node1, <<"Node">>), 108 | 109 | Result = loop_sub(Node1, [], 1), 110 | 111 | ?assert(lists:member(<<"Node/2">>, Result)), 112 | 113 | rbeacon:close(Node1), 114 | rbeacon:close(Node2), 115 | rbeacon:close(Node3), 116 | 117 | ok. 118 | ''' 119 | 120 | ## Ownership and License 121 | The contributors are listed in AUTHORS. This project uses the MPL v2 license, 122 | see LICENSE. 123 | 124 | rbeacon uses the 125 | [C4.1 (Collective Code Construction Contract)](http://rfc.zeromq.org/spec:22) 126 | process for contributions. 127 | 128 | ## Development 129 | 130 | Under C4.1 process, you are more than welcome to help us by: 131 | 132 | * join the discussion over anything from design to code style 133 | * try out and [submit issue reports](https://github.com/refuge/rbeacon/issues/new) or feature requests 134 | * pick a task in [issues](https://github.com/refuge/rbeacon/issues) and get it done 135 | * fork the repository and have your own fixes 136 | * send us pull requests 137 | * and even star this project ^_^ 138 | 139 | To run the test suite: 140 | 141 | $ rebar eunit 142 | -------------------------------------------------------------------------------- /doc/rbeacon.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Module rbeacon # 4 | * [Description](#description) 5 | * [Data Types](#types) 6 | * [Function Index](#index) 7 | * [Function Details](#functions) 8 | 9 | 10 | The rbeacon module implements a peer-to-peer discovery service for local 11 | networks. 12 | __Behaviours:__ [`gen_server`](gen_server.md). 13 | 14 | 15 | ## Description ## 16 | A beacon can broadcast and/or capture service announcements using 17 | UDP messages on the local area network. This implementation uses IPv4 UDP 18 | broadcasts. You can define the format of your outgoing beacons, and set a 19 | filter that validates incoming beacons. Beacons are sent and received 20 | asynchronously in the background. 21 | 22 | 23 | 24 | ## Data Types ## 25 | 26 | 27 | 28 | 29 | ### beacon() ### 30 | 31 | 32 | 33 |

 34 | beacon() = pid()
 35 | 
36 | 37 | 38 | 39 | 40 | 41 | ### beacon_opts() ### 42 | 43 | 44 | 45 |

 46 | beacon_opts() = [active | {active, true | false | once | integer()} | {interval, integer()} | noecho | {noecho, true | false}]
 47 | 
48 | 49 | 50 | 51 | 52 | ## Function Index ## 53 | 54 | 55 |
broadcast_ip/1Return our own Broadcast IP address as printable string.
close/1close a beacon 56 | Close a beacon.
control/2Assigns a new controlling process Pid to beacon 57 | The controlling process is the process which receives messages from the 58 | beacon.
hostname/1Return our own IP address as printable string.
new/1Create a new beacon on a certain UDP port.
new/2Create a new beacon on a certain UDP port with options.
noecho/1 Filter out any beacon that looks exactly like ours.
publish/2Start broadcasting beacon to peers at the specified interval.
recv/1wait to receive a beacon.
recv/2wait to receive a beacon with timeout.
set_interval/2Set broadcast interval in milliseconds (default is 1000 msec).
setopts/2set beacon options.
silence/1Stop broadcasting beacons.
subscribe/2Start listening to other peers; zero-sized filter means get everything 59 | All messages received by the peer will be then sent to the process owner.
unsubscribe/1Stop listening to other peers.
60 | 61 | 62 | 63 | 64 | ## Function Details ## 65 | 66 | 67 | 68 | ### broadcast_ip/1 ### 69 | 70 | 71 |

 72 | broadcast_ip(Ref::beacon()) -> string()
 73 | 
74 | 75 |

76 | 77 | 78 | Return our own Broadcast IP address as printable string 79 | 80 | 81 | ### close/1 ### 82 | 83 | 84 |

 85 | close(Ref::beacon()) -> ok
 86 | 
87 | 88 |

89 | 90 | 91 | close a beacon 92 | Close a beacon. 93 | 94 | 95 | ### control/2 ### 96 | 97 | 98 |

 99 | control(Ref::beacon(), Pid::pid()) -> ok | {error, not_owner}
100 | 
101 | 102 |

103 | 104 | 105 | Assigns a new controlling process Pid to beacon 106 | The controlling process is the process which receives messages from the 107 | beacon. If called by any other process than the current controlling process, 108 | `{error, not_owner}` is returned. 109 | 110 | 111 | ### hostname/1 ### 112 | 113 | 114 |

115 | hostname(Ref::beacon()) -> string()
116 | 
117 | 118 |

119 | 120 | 121 | Return our own IP address as printable string 122 | 123 | 124 | ### new/1 ### 125 | 126 | 127 |

128 | new(Port::integer()) -> {ok, beacon()} | {error, term()}
129 | 
130 | 131 |

132 | 133 | 134 | Create a new beacon on a certain UDP port. 135 | 136 | 137 | ### new/2 ### 138 | 139 | 140 |

141 | new(Port::integer(), Options::beacon_opts()) -> {ok, beacon()} | {error, term()}
142 | 
143 | 144 |

145 | 146 | 147 | Create a new beacon on a certain UDP port with options. 148 | 149 | 150 | ### noecho/1 ### 151 | 152 | 153 |

154 | noecho(Ref::beacon()) -> ok
155 | 
156 | 157 |

158 | 159 | 160 | Filter out any beacon that looks exactly like ours 161 | 162 | 163 | ### publish/2 ### 164 | 165 | 166 |

167 | publish(Ref::beacon(), Msg::binary()) -> ok | {error, term()}
168 | 
169 | 170 |

171 | 172 | 173 | Start broadcasting beacon to peers at the specified interval 174 | 175 | 176 | ### recv/1 ### 177 | 178 | 179 |

180 | recv(Ref::beacon()) -> {ok, Addr::string(), Msg::binary()} | {error, term()}
181 | 
182 | 183 |

184 | 185 | 186 | wait to receive a beacon 187 | 188 | 189 | ### recv/2 ### 190 | 191 | 192 |

193 | recv(Ref::beacon(), Timeout::integer() | infinity) -> {ok, Addr::string(), Msg::binary()} | {error, term()}
194 | 
195 | 196 |

197 | 198 | 199 | wait to receive a beacon with timeout. Timeout can be an integer in 200 | milliseconds or infinity. 201 | 202 | 203 | ### set_interval/2 ### 204 | 205 | 206 |

207 | set_interval(Ref::beacon(), Interval::integer()) -> ok | {error, term()}
208 | 
209 | 210 |

211 | 212 | 213 | Set broadcast interval in milliseconds (default is 1000 msec) 214 | 215 | 216 | ### setopts/2 ### 217 | 218 | 219 |

220 | setopts(Ref::beacon(), Options::beacon_opts()) -> ok
221 | 
222 | 223 |

224 | 225 | 226 | set beacon options. Valid options are: 227 | 228 | * `active`, `{active, true | false | once| N}`: like `inet:setopts/1` 229 | 230 | * `{interval, N}`: Set 231 | broadcast interval in milliseconds 232 | 233 | * `noecho | {noecho, true | false}`: Filter out any beacon that 234 | looks exactly like ours. 235 | 236 | 237 | 238 | 239 | ### silence/1 ### 240 | 241 | 242 |

243 | silence(Ref::beacon()) -> ok
244 | 
245 | 246 |

247 | 248 | 249 | Stop broadcasting beacons 250 | 251 | 252 | ### subscribe/2 ### 253 | 254 | 255 |

256 | subscribe(Ref::beacon(), Filter::binary() | string()) -> ok
257 | 
258 | 259 |

260 | 261 | 262 | 263 | Start listening to other peers; zero-sized filter means get everything 264 | All messages received by the peer will be then sent to the process owner. 265 | Incoming messages are: 266 | 267 | 268 | - `{rbeacon, Beacon, Message, SenderIp}` : when a subscription is received 269 | - `{rbeacon, Beacon, closed}` : when a beacon is closed 270 | - `{'EXIT', rbeacon, Beacon, Reason}`: when a beacon exit anormaly 271 | 272 | 273 | ### unsubscribe/1 ### 274 | 275 | 276 |

277 | unsubscribe(Ref::beacon()) -> ok
278 | 
279 | 280 |

281 | 282 | 283 | Stop listening to other peers 284 | -------------------------------------------------------------------------------- /doc/utf8/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # rbeacon - LAN discovery and presence. # 4 | 5 | Copyright (c) 2014 Benoît Chesneau. 6 | 7 | __Version:__ 0.3.0 8 | 9 | ## Description 10 | 11 | The rbeacon module implements a peer-to-peer discovery service for local 12 | networks. A beacon can broadcast and/or capture service announcements using UDP 13 | messages on the local area network. This implementation uses IPv4 UDP 14 | broadcasts. You can define the format of your outgoing beacons, and set a filter 15 | that validates incoming beacons. Beacons are sent and received asynchronously in 16 | the background. 17 | 18 | > Note: the current implementation is heavily inspired on 19 | [zbeacon](http://czmq.zeromq.org/manual:zbeacon) from zeromq. 20 | 21 | ## Usage 22 | 23 | Look at the [`rbeacon`](rbeacon.md) module for the API usage. 24 | 25 | > **Note:** You can set the interface on which you broadcast using the 26 | application environment setting `broadast_if` or the the OS environment variable 27 | `RBEACON_INTERFACE`. 28 | 29 | ## Example 30 | 31 | From the rbeacon_test function: 32 | 33 | ``` 34 | {ok, Service} = rbeacon:new(9999), 35 | ?assert(is_pid(Service)), 36 | 37 | ok = rbeacon:set_interval(Service, 100), 38 | ok = rbeacon:publish(Service, <<"announcement">>), 39 | 40 | {ok, Client} = rbeacon:new(9999), 41 | ok = rbeacon:subscribe(Client, <<>>), 42 | 43 | {ok, Msg, _Addr} = rbeacon:recv(Client), 44 | ?assertEqual(Msg, <<"announcement">>), 45 | ok = rbeacon:close(Service), 46 | ok = rbeacon:close(Client), 47 | 48 | {ok, Node1} = rbeacon:new(5670), 49 | {ok, Node2} = rbeacon:new(5670), 50 | {ok, Node3} = rbeacon:new(5670), 51 | 52 | ok = rbeacon:noecho(Node1), 53 | 54 | rbeacon:publish(Node1, <<"Node/1">>), 55 | rbeacon:publish(Node2, <<"Node/2">>), 56 | rbeacon:publish(Node3, <<"GARBAGE">>), 57 | rbeacon:subscribe(Node1, <<"Node">>), 58 | 59 | {ok, Msg2, _Addr} = rbeacon:recv(Node1), 60 | ?assertEqual(Msg2, <<"Node/2">>), 61 | 62 | rbeacon:close(Node1), 63 | rbeacon:close(Node2), 64 | rbeacon:close(Node3). 65 | ``` 66 | 67 | You can also receive from the beacon as message (from the rbeacon_active_test): 68 | 69 | ``` 70 | {ok, Service} = rbeacon:new(9999, [active, noecho]), 71 | ?assert(is_pid(Service)), 72 | 73 | ok = rbeacon:set_interval(Service, 100), 74 | ok = rbeacon:publish(Service, <<"announcement">>), 75 | 76 | {ok, Client} = rbeacon:new(9999, [active]), 77 | ok = rbeacon:subscribe(Client, <<>>), 78 | receive 79 | {rbeacon, Client, <<"announcement">>, _Addr} -> 80 | ok 81 | end, 82 | 83 | ok = rbeacon:close(Service), 84 | receive 85 | {rbeacon, Service, closed} -> ok 86 | end, 87 | 88 | ok = rbeacon:close(Client), 89 | receive 90 | {rbeacon, Client, closed} -> ok 91 | end, 92 | 93 | {ok, Node1} = rbeacon:new(5670, [active, noecho]), 94 | {ok, Node2} = rbeacon:new(5670, [active, noecho]), 95 | {ok, Node3} = rbeacon:new(5670, [active, noecho]), 96 | 97 | rbeacon:publish(Node1, <<"Node/1">>), 98 | rbeacon:publish(Node2, <<"Node/2">>), 99 | rbeacon:publish(Node3, <<"GARBAGE">>), 100 | rbeacon:subscribe(Node1, <<"Node">>), 101 | 102 | Result = loop_sub(Node1, [], 1), 103 | 104 | ?assert(lists:member(<<"Node/2">>, Result)), 105 | 106 | rbeacon:close(Node1), 107 | rbeacon:close(Node2), 108 | rbeacon:close(Node3), 109 | 110 | ok. 111 | ``` 112 | 113 | ## Ownership and License 114 | The contributors are listed in AUTHORS. This project uses the MPL v2 license, 115 | see LICENSE. 116 | 117 | rbeacon uses the 118 | [C4.1 (Collective Code Construction Contract)](http://rfc.zeromq.org/spec:22) 119 | process for contributions. 120 | 121 | ## Development 122 | 123 | Under C4.1 process, you are more than welcome to help us by: 124 | 125 | * join the discussion over anything from design to code style 126 | * try out and [submit issue reports](https://github.com/refuge/rbeacon/issues/new) or feature requests 127 | * pick a task in [issues](https://github.com/refuge/rbeacon/issues) and get it done 128 | * fork the repository and have your own fixes 129 | * send us pull requests 130 | * and even star this project ^_^ 131 | 132 | To run the test suite: 133 | $ rebar eunit 134 | 135 | 136 | ## Modules ## 137 | 138 | 139 | 140 |
rbeacon
141 | 142 | -------------------------------------------------------------------------------- /rebar_dev.config: -------------------------------------------------------------------------------- 1 | %%-*- mode: erlang -*- 2 | 3 | {lib_dirs, ["deps"]}. 4 | 5 | 6 | {erl_opts, 7 | [{i, "deps"}, 8 | {src_dirs, ["src"]}, 9 | debug_info 10 | ] 11 | }. 12 | 13 | {deps, [ 14 | 15 | 16 | {edown, ".*", 17 | {git, "git://github.com/esl/edown.git", {tag, "0.4"}}} 18 | ]}. 19 | 20 | {edoc_opts, [{application, ["rbeacon"]}, 21 | {doclet, edown_doclet}, 22 | {subpackages, false}, 23 | {top_level_readme, 24 | {"./README.md", "http://github.com/refuge/rbeacon"}}]}. 25 | -------------------------------------------------------------------------------- /src/rbeacon.app.src: -------------------------------------------------------------------------------- 1 | {application, rbeacon, 2 | [ 3 | {description, "LAN discovery and presence"}, 4 | {vsn, "0.3.0"}, 5 | {registered, []}, 6 | {applications, [ 7 | kernel, 8 | stdlib 9 | ]}, 10 | {env, []} 11 | ]}. 12 | -------------------------------------------------------------------------------- /src/rbeacon.erl: -------------------------------------------------------------------------------- 1 | %%% -*- erlang -*- 2 | %%% 3 | %%% This file is part of rbeacon released under the Mozilla Public License 4 | %%% Version 2.0. See the NOTICE for more information. 5 | 6 | %% @doc The rbeacon module implements a peer-to-peer discovery service for local 7 | %% networks. A beacon can broadcast and/or capture service announcements using 8 | %% UDP messages on the local area network. This implementation uses IPv4 UDP 9 | %% broadcasts. You can define the format of your outgoing beacons, and set a 10 | %% filter that validates incoming beacons. Beacons are sent and received 11 | %% asynchronously in the background. 12 | %% 13 | -module(rbeacon). 14 | -author('Benoît Chesneau '). 15 | -behaviour(gen_server). 16 | 17 | %% public api 18 | -export([new/1, new/2, 19 | close/1, 20 | control/2, 21 | publish/2, 22 | subscribe/2, 23 | unsubscribe/1, 24 | recv/1, recv/2, 25 | hostname/1, 26 | broadcast_ip/1, 27 | silence/1, 28 | noecho/1, 29 | set_interval/2, 30 | setopts/2]). 31 | 32 | %% gen server callbacks 33 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, 34 | terminate/2, code_change/3]). 35 | 36 | -record(state, {sock, 37 | port, 38 | addr, 39 | broadcast_addr, 40 | active=false, 41 | owner, 42 | filter, 43 | interval, 44 | transmit, 45 | noecho=false, 46 | tref=nil, 47 | pending_recv=nil}). 48 | 49 | %% default interval 50 | -define(DEFAULT_INTERVAL, 1000). 51 | 52 | %% reuse port option 53 | -define(SOL_SOCKET, 16#ffff). 54 | -define(SO_REUSEPORT, 16#0200). 55 | 56 | -type beacon() :: pid(). 57 | -export_type([beacon/0]). 58 | 59 | -type beacon_opts() :: [active | 60 | {active, true | false | once | integer()} | 61 | {interval, integer()} | 62 | noecho | 63 | {noecho, true | false}]. 64 | -export_type([beacon_opts/0]). 65 | 66 | 67 | %% @doc Create a new beacon on a certain UDP port. 68 | - spec new(Port::integer()) -> {ok, beacon()} | {error, term()}. 69 | new(Port) -> 70 | new(Port, []). 71 | 72 | %% @doc Create a new beacon on a certain UDP port with options. 73 | -spec new(Port::integer(), Options::beacon_opts()) 74 | -> {ok, beacon()} | {error, term()}. 75 | new(Port, Options) -> 76 | ok = validate_options(Options), 77 | gen_server:start_link(?MODULE, [Port, self(), Options], []). 78 | 79 | 80 | %% @doc close a beacon 81 | %% Close a beacon. 82 | -spec close(Ref::beacon()) -> ok. 83 | close(Ref) -> 84 | try 85 | gen_server:call(Ref, close, infinity) 86 | catch 87 | exit:{noproc,_} -> ok; 88 | exit:noproc -> ok; 89 | %% Handle the case where the monitor triggers 90 | exit:{normal, _} -> ok 91 | end. 92 | 93 | 94 | %% @doc Assigns a new controlling process Pid to beacon 95 | %% The controlling process is the process which receives messages from the 96 | %% beacon. If called by any other process than the current controlling process, 97 | %% `{error, not_owner}' is returned. 98 | -spec control(beacon(), pid()) -> ok | {error, not_owner}. 99 | control(Ref, Pid) -> 100 | gen_server:call(Ref, {control, Pid, self()}, infinity). 101 | 102 | %% @doc Start broadcasting beacon to peers at the specified interval 103 | -spec publish(beacon(), binary()) -> ok | {error, term()}. 104 | publish(Ref, Msg) -> 105 | gen_server:call(Ref, {publish, to_binary(Msg)}, infinity). 106 | 107 | %% @doc Start listening to other peers; zero-sized filter means get everything 108 | %% All messages received by the peer will be then sent to the process owner. 109 | %% Incoming messages are: 110 | %% 111 | %% - `{rbeacon, Beacon, Message, SenderIp}' : when a subscription is received 112 | %% - `{rbeacon, Beacon, closed}' : when a beacon is closed 113 | %% - {'EXIT', rbeacon, Beacon, Reason}: when a beacon exit anormaly 114 | 115 | %% 116 | %% Note: the filter allows you to filter a subscription by its prefix. 117 | -spec subscribe(beacon(), binary() | string()) -> ok. 118 | subscribe(Ref, Filter) when is_list(Filter) -> 119 | subscribe(Ref, list_to_binary(Filter)); 120 | subscribe(Ref, Filter0) when is_binary(Filter0) -> 121 | Filter = case Filter0 of 122 | <<"">> -> all; 123 | _ -> Filter0 124 | end, 125 | gen_server:call(Ref, {subscribe, Filter}, infinity). 126 | 127 | %% @doc Stop listening to other peers 128 | -spec unsubscribe(beacon()) -> ok. 129 | unsubscribe(Ref) -> 130 | gen_server:call(Ref, unsubscribe, infinity). 131 | 132 | %% @doc wait to receive a beacon 133 | -spec recv(beacon()) -> {ok, Addr::string(), Msg::binary()} | {error, term()}. 134 | recv(Ref) -> 135 | recv(Ref, infinity). 136 | 137 | %% @doc wait to receive a beacon with timeout. Timeout can be an integer in 138 | %% milliseconds or infinity. 139 | -spec recv(beacon(), integer() | infinity) -> 140 | {ok, Addr::string(), Msg::binary()} 141 | | {error, term()}. 142 | recv(Ref, Timeout) when is_integer(Timeout) orelse Timeout =:= infinity -> 143 | gen_server:call(Ref, {recv, Timeout}, infinity). 144 | 145 | 146 | %% @doc Return our own IP address as printable string 147 | -spec hostname(beacon()) -> string(). 148 | hostname(Ref) -> 149 | gen_server:call(Ref, hostname, infinity). 150 | 151 | %% @doc Return our own Broadcast IP address as printable string 152 | -spec broadcast_ip(beacon()) -> string(). 153 | broadcast_ip(Ref) -> 154 | gen_server:call(Ref, broadcast_ip, infinity). 155 | 156 | 157 | %% @doc Stop broadcasting beacons 158 | -spec silence(beacon()) -> ok. 159 | silence(Ref) -> 160 | gen_server:call(Ref, silence, infinity). 161 | 162 | %% @doc Filter out any beacon that looks exactly like ours 163 | -spec noecho(beacon()) -> ok. 164 | noecho(Ref) -> 165 | gen_server:call(Ref, noecho, infinity). 166 | 167 | 168 | %% @doc Set broadcast interval in milliseconds (default is 1000 msec) 169 | -spec set_interval(beacon(), integer()) -> ok | {error, term()}. 170 | set_interval(Ref, Interval) when is_integer(Interval) -> 171 | gen_server:call(Ref, {set_interval, Interval}); 172 | set_interval(_, _) -> 173 | {error, badarg}. 174 | 175 | %% @doc set beacon options. Valid options are: 176 | %% 183 | -spec setopts(beacon(), beacon_opts()) -> ok. 184 | setopts(Ref, Options) -> 185 | ok = validate_options(Options), 186 | gen_server:call(Ref, {setopts, Options}, infinity). 187 | 188 | 189 | 190 | %% gen server functions 191 | %% @private 192 | init([Port, Owner, Options]) -> 193 | Active = proplists:get_value(active, Options, false), 194 | Interval = proplists:get_value(interval, Options, ?DEFAULT_INTERVAL), 195 | NoEcho = proplists:get_value(noecho, Options, false), 196 | 197 | %% init the socket 198 | {ok, Sock} = open_udp_port(Port, Active), 199 | 200 | %% get broadcast address 201 | {Addr, BroadcastAddr} = broadcast_addr(), 202 | 203 | 204 | %% trap exit 205 | process_flag(trap_exit, true), 206 | 207 | {ok, #state{sock=Sock, 208 | port=Port, 209 | addr=Addr, 210 | broadcast_addr=BroadcastAddr, 211 | active=Active, 212 | interval=Interval, 213 | noecho=NoEcho, 214 | owner=Owner}}. 215 | %% @private 216 | handle_call(close, _From, State) -> 217 | ok = cancel_timer(State), 218 | {stop, normal, ok, State#state{tref=nil}}; 219 | 220 | handle_call({control, To, From}, _From, #state{owner=From}=State) -> 221 | {reply, ok, State#state{owner=To}}; 222 | handle_call({control, _, _}, _From, State) -> 223 | {reply, {error, not_owner}, State}; 224 | 225 | handle_call({publish, Msg}, _From, State) -> 226 | %% broadcast the new message now 227 | ok = transmit_msg(Msg, State), 228 | %% reset timer with the new message 229 | ok = cancel_timer(State), 230 | {ok, TRef} = timer:send_interval(State#state.interval, self(), 231 | {transmit, Msg}), 232 | {reply, ok, State#state{transmit=Msg, tref=TRef}}; 233 | 234 | handle_call({set_interval, Interval}, _From, #state{transmit=undefined}=State) -> 235 | {reply, ok, State#state{interval=Interval}}; 236 | handle_call({set_interval, Interval}, _From, #state{transmit=Msg}=State) -> 237 | ok = cancel_timer(State), 238 | {ok, TRef} = timer:send_interval(Interval, self(), {transmit, Msg}), 239 | {reply, ok, State#state{interval=Interval, tref=TRef}}; 240 | 241 | handle_call(hostname, _From, #state{addr=Addr}=State) -> 242 | {reply, Addr, State#state{tref=nil}}; 243 | 244 | handle_call(broadcast_ip, _From, #state{broadcast_addr=Addr}=State) -> 245 | {reply, Addr, State#state{tref=nil}}; 246 | 247 | handle_call(silence, _From, State) -> 248 | ok = cancel_timer(State), 249 | {reply, ok, State#state{tref=nil}}; 250 | 251 | handle_call(noecho, _From, State) -> 252 | {reply, ok, State#state{noecho=true}}; 253 | 254 | handle_call({setopts, Opts}, _From, State) -> 255 | {ok, NState} = do_setopts(Opts, State), 256 | {reply, ok, NState}; 257 | 258 | handle_call({subscribe, Filter}, _From, State) -> 259 | {reply, ok, State#state{filter=Filter}}; 260 | 261 | handle_call(unsubscribe, _From, State) -> 262 | {reply, ok, State#state{filter=nil}}; 263 | 264 | handle_call({recv, _}, _From, #state{active=Active}=State) 265 | when Active /= false -> 266 | {reply, {error, active}, State}; 267 | 268 | handle_call({recv, Timeout}, From, #state{pending_recv=nil}=State) -> 269 | {noreply, handle_recv(From, State, Timeout)}; 270 | 271 | handle_call({recv, _Timeout}, _From, State) -> 272 | {reply, {error, already_recv}, State}. 273 | 274 | %% @private 275 | handle_cast(_Msg, State) -> 276 | {noreply, State}. 277 | 278 | %% @private 279 | handle_info({transmit, Msg}, State) -> 280 | %% broadcast the message now 281 | ok = transmit_msg(Msg, State), 282 | {noreply, State}; 283 | 284 | handle_info({udp, Sock, _IP, _, Msg}, #state{sock=Sock, 285 | transmit=Msg, 286 | noecho=true}=State) -> 287 | %% echo, ignore it 288 | {noreply, State}; 289 | handle_info({udp, _Sock, _IP, _, _Msg}, #state{filter=nil}=State) -> 290 | %% no subscribtion 291 | {noreply, State}; 292 | handle_info({udp, _Sock, IP, _, Msg}, #state{active=Active, 293 | owner=Owner, 294 | filter=Filter}=State) -> 295 | 296 | %% decrement Active if needed 297 | Active1 = if is_integer(Active) -> Active - 1; 298 | true -> Active 299 | end, 300 | 301 | case filter_match(Msg, Filter) of 302 | true -> 303 | Owner ! {rbeacon, self(), Msg, IP}; 304 | false -> 305 | ok 306 | end, 307 | 308 | %% if active is once or null, then set it to false 309 | NState = case Active1 of 310 | once -> 311 | State#state{active=false}; 312 | 0 -> 313 | State#state{active=false}; 314 | 315 | _ -> 316 | State 317 | end, 318 | {noreply, NState}; 319 | 320 | handle_info({'EXIT', Pid, _Reason}, #state{pending_recv=Pid}=State) -> 321 | {noreply, State#state{pending_recv=nil}}; 322 | handle_info(_Msg, State) -> 323 | {noreply, State}. 324 | 325 | %% close 326 | %% @private 327 | terminate(normal, #state{active=false}) -> 328 | ok; 329 | terminate(normal, #state{owner=Owner}) -> 330 | Owner ! {rbeacon, self(), closed}, 331 | ok; 332 | %% exit 333 | terminate(Reason, #state{active=false}=State) -> 334 | error_logger:info_msg("got terminate(~p, ~p)~n", [Reason, State]), 335 | ok; 336 | terminate(Reason, #state{owner=Owner}=State) -> 337 | Owner ! {'EXIT', rbeacon, self(), Reason}, 338 | error_logger:info_msg("got terminate(~p, ~p)~n", [Reason, State]), 339 | ok. 340 | 341 | %% @private 342 | code_change(_OldVsn, State, _Extra) -> 343 | {ok, State}. 344 | 345 | 346 | 347 | cancel_timer(#state{tref=Tref}) -> 348 | if Tref /= nil -> timer:cancel(Tref); 349 | true -> ok 350 | end, 351 | ok. 352 | 353 | 354 | transmit_msg(Msg, #state{sock=Sock, port=Port, broadcast_addr=Addr}) -> 355 | gen_udp:send(Sock, Addr, Port, Msg). 356 | 357 | filter_match(_, all) -> true; 358 | filter_match(Msg, Filter) when byte_size(Msg) >= byte_size(Filter) -> 359 | case binary:split(Msg, Filter, [trim]) of 360 | [Msg] -> false; 361 | _ -> true 362 | end; 363 | filter_match(_, _) -> 364 | false. 365 | 366 | 367 | handle_recv(From, State, Timeout) -> 368 | Pid = spawn_link(fun() -> do_recv(From, State, Timeout) end), 369 | State#state{pending_recv=Pid}. 370 | 371 | 372 | do_recv(From, _State, Timeout) when 373 | Timeout =< 0, timeout /= infinity -> 374 | gen_server:reply(From, {error, timeout}); 375 | do_recv(From, #state{sock=Sock, filter=Filter, transmit=Msg, 376 | noecho=NoEcho}=State, Timeout) -> 377 | 378 | Start = os:timestamp(), 379 | case gen_udp:recv(Sock, 0, Timeout) of 380 | {ok, {Addr, _Port, Packet}} -> 381 | case filter_match(Packet, Filter) of 382 | true when Packet =:= Msg, NoEcho =:= true -> 383 | do_recv(From, State, new_recv_timeout(Timeout, Start)); 384 | true -> 385 | gen_server:reply(From, {ok, Packet, Addr}); 386 | false -> 387 | do_recv(From, State, new_recv_timeout(Timeout, Start)) 388 | end; 389 | Error -> 390 | gen_server:reply(From, Error) 391 | end. 392 | 393 | 394 | new_recv_timeout(infinity, _) -> 395 | infinity; 396 | new_recv_timeout(Timeout, From) -> 397 | TDiff = timer:now_diff(os:timestamp(), From), 398 | Timeout - TDiff. 399 | 400 | open_udp_port(Port, Active) -> 401 | %% defaullt options 402 | Options0 = [{active, Active}, 403 | {broadcast, true}, 404 | {reuseaddr, true}, 405 | inet, 406 | binary], 407 | %% reuse port ? 408 | Options = case reuseport() of 409 | false -> Options0; 410 | ReusePort -> Options0 ++ ReusePort 411 | end, 412 | gen_udp:open(Port, Options). 413 | 414 | reuseport() -> 415 | case os:type() of 416 | {unix, OsName} -> 417 | case lists:member(OsName, [darwin, freebsd, openbsd, netbsd]) of 418 | true -> 419 | [{raw, ?SOL_SOCKET, ?SO_REUSEPORT, <<1:32/native>>}]; 420 | false -> 421 | false 422 | end; 423 | _ -> 424 | false 425 | end. 426 | 427 | 428 | broadcast_addr() -> 429 | IfName = case os:getenv("RBEACON_INTERFACE") of 430 | false -> 431 | %% compatibility with zbeacon, handle the ZSYS_INTERFACE environment 432 | %% variable 433 | case os:getenv("ZSYS_INTERFACE") of 434 | false -> get_env("broadast_if", ""); 435 | Name -> Name 436 | end; 437 | Name -> Name 438 | end, 439 | 440 | case IfName of 441 | "*" -> "255.255.255.255"; 442 | _ -> broadcast_addr(IfName) 443 | end. 444 | 445 | 446 | broadcast_addr(Name) -> 447 | {ok, Interfaces} = inet:getifaddrs(), 448 | broadcast_addr(Interfaces, Name, []). 449 | 450 | 451 | broadcast_addr([], _Name, []) -> 452 | {any, "255.255.255.255"}; 453 | broadcast_addr([], _Name, [Addr | _]) -> 454 | Addr; 455 | broadcast_addr([Interface | Rest], Name, Acc) -> 456 | {IfName, Props} = Interface, 457 | Flags = proplists:get_value(flags, Props, []), 458 | Addr = parse_addr(Props), 459 | 460 | Up = lists:member(up, Flags), 461 | Broadcast = lists:member(broadcast, Flags), 462 | LoopBack = lists:member(loopback, Flags), 463 | P2P = lists:member(pointtopoint, Flags), 464 | 465 | if Up =:= true, Broadcast =:= true, LoopBack /= true andalso P2P /= true -> 466 | case proplists:get_value(broadaddr, Props) of 467 | A = {_, _, _, _} when IfName =:= Name -> 468 | {Addr, A}; 469 | A = {_, _, _, _} -> 470 | broadcast_addr(Rest, Name, [{Addr, A} | Acc]); 471 | _ -> 472 | broadcast_addr(Rest, Name, Acc) 473 | end; 474 | true -> 475 | broadcast_addr(Rest, Name, Acc) 476 | end. 477 | 478 | parse_addr([]) -> 479 | any; 480 | parse_addr([{addr, {_, _, _, _}=A} | _]) -> 481 | A; 482 | parse_addr([_ | Rest]) -> 483 | parse_addr(Rest). 484 | 485 | 486 | get_env(Key, Default) -> 487 | case application:get_env(?MODULE, Key) of 488 | {ok, Value} -> Value; 489 | _ -> Default 490 | end. 491 | 492 | 493 | to_binary(V) when is_list(V) -> 494 | list_to_binary(V); 495 | to_binary(V) when is_atom(V) -> 496 | atom_to_binary(V, latin1); 497 | to_binary(V) when is_integer(V) -> 498 | list_to_binary(integer_to_list(V)); 499 | to_binary(V) when is_binary(V) -> 500 | V. 501 | 502 | 503 | validate_options([]) -> 504 | ok; 505 | validate_options([{active, N} | Rest]) when is_integer(N) -> 506 | validate_options(Rest); 507 | validate_options([{active, once} | Rest]) -> 508 | validate_options(Rest); 509 | validate_options([{active, true} | Rest]) -> 510 | validate_options(Rest); 511 | validate_options([{active, false} | Rest]) -> 512 | validate_options(Rest); 513 | validate_options([active | Rest]) -> 514 | validate_options(Rest); 515 | validate_options([{interval, N} | Rest]) when is_integer(N) -> 516 | validate_options(Rest); 517 | validate_options([{noecho, _NoEcho} | Rest]) -> 518 | validate_options(Rest); 519 | validate_options([noecho | Rest]) -> 520 | validate_options(Rest); 521 | validate_options(_) -> 522 | badarg. 523 | 524 | 525 | do_setopts([], State) -> 526 | {ok, State}; 527 | do_setopts([{active, Active} | Rest], #state{sock=S}=State) -> 528 | ok = inet:setopts(S, [{active, Active}]), 529 | do_setopts(Rest, State#state{active=Active}); 530 | do_setopts([active | Rest], #state{sock=S}=State) -> 531 | ok = inet:setopts(S, [{active, true}]), 532 | do_setopts(Rest, State#state{active=true}); 533 | do_setopts([{interval, N} | Rest], #state{transmit=Msg}=State) -> 534 | State2 = case Msg of 535 | undefined -> State#state{interval=N}; 536 | _ -> 537 | ok = cancel_timer(State), 538 | {ok, TRef} = timer:send_interval(N, self(), {transmit, Msg}), 539 | State#state{interval=N, tref=TRef} 540 | end, 541 | do_setopts(Rest, State2); 542 | do_setopts([{noecho, NoEcho} | Rest], State) -> 543 | do_setopts(Rest, State#state{noecho=NoEcho}); 544 | do_setopts([noecho | Rest], State) -> 545 | do_setopts(Rest, State#state{noecho=true}); 546 | do_setopts(_, _State) -> 547 | badarg. 548 | 549 | 550 | 551 | -ifdef(TEST). 552 | -include_lib("eunit/include/eunit.hrl"). 553 | 554 | 555 | loop_sub(_Beacon, Acc, 0) -> 556 | Acc; 557 | loop_sub(Beacon, Acc, N) -> 558 | receive 559 | {rbeacon, Beacon, Msg, _} -> 560 | loop_sub(Beacon, [Msg | Acc], N-1) 561 | end. 562 | 563 | 564 | rbeacon_test() -> 565 | {ok, Service} = rbeacon:new(9999), 566 | ?assert(is_pid(Service)), 567 | 568 | ok = rbeacon:set_interval(Service, 100), 569 | ok = rbeacon:publish(Service, <<"announcement">>), 570 | 571 | {ok, Client} = rbeacon:new(9999), 572 | ok = rbeacon:subscribe(Client, <<>>), 573 | 574 | {ok, Msg, _Addr} = rbeacon:recv(Client), 575 | ?assertEqual(Msg, <<"announcement">>), 576 | 577 | 578 | ok = rbeacon:close(Service), 579 | ok = rbeacon:close(Client), 580 | 581 | {ok, Node1} = rbeacon:new(5670), 582 | {ok, Node2} = rbeacon:new(5670), 583 | {ok, Node3} = rbeacon:new(5670), 584 | 585 | ok = rbeacon:noecho(Node1), 586 | 587 | rbeacon:publish(Node1, <<"Node/1">>), 588 | rbeacon:publish(Node2, <<"Node/2">>), 589 | rbeacon:publish(Node3, <<"GARBAGE">>), 590 | rbeacon:subscribe(Node1, <<"Node">>), 591 | 592 | {ok, Msg2, _Addr} = rbeacon:recv(Node1), 593 | ?assertEqual(Msg2, <<"Node/2">>), 594 | 595 | rbeacon:close(Node1), 596 | rbeacon:close(Node2), 597 | rbeacon:close(Node3), 598 | 599 | ok. 600 | 601 | rbeacon_active_test() -> 602 | {ok, Service} = rbeacon:new(9999, [active, noecho]), 603 | ?assert(is_pid(Service)), 604 | 605 | ok = rbeacon:set_interval(Service, 100), 606 | ok = rbeacon:publish(Service, <<"announcement">>), 607 | 608 | {ok, Client} = rbeacon:new(9999, [active]), 609 | ok = rbeacon:subscribe(Client, <<>>), 610 | receive 611 | {rbeacon, Client, <<"announcement">>, _Addr} -> 612 | ok 613 | end, 614 | 615 | ok = rbeacon:close(Service), 616 | receive 617 | {rbeacon, Service, closed} -> ok 618 | end, 619 | 620 | ok = rbeacon:close(Client), 621 | receive 622 | {rbeacon, Client, closed} -> ok 623 | end, 624 | 625 | {ok, Node1} = rbeacon:new(5670, [active, noecho]), 626 | {ok, Node2} = rbeacon:new(5670, [active, noecho]), 627 | {ok, Node3} = rbeacon:new(5670, [active, noecho]), 628 | 629 | rbeacon:publish(Node1, <<"Node/1">>), 630 | rbeacon:publish(Node2, <<"Node/2">>), 631 | rbeacon:publish(Node3, <<"GARBAGE">>), 632 | rbeacon:subscribe(Node1, <<"Node">>), 633 | 634 | Result = loop_sub(Node1, [], 1), 635 | 636 | ?assert(lists:member(<<"Node/2">>, Result)), 637 | 638 | rbeacon:close(Node1), 639 | rbeacon:close(Node2), 640 | rbeacon:close(Node3), 641 | 642 | ok. 643 | 644 | -endif. 645 | --------------------------------------------------------------------------------