├── .gitignore ├── src ├── error.rs ├── lib.rs ├── udp.rs ├── message.rs └── osc.rs ├── Cargo.toml ├── LICENSE-MIT ├── examples └── simple.rs ├── tests └── test.rs ├── .github ├── workflows │ └── ci.yaml ├── CONTRIBUTING.md └── CODE_OF_CONDUCT.md ├── README.md └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | tmp/ 3 | Cargo.lock 4 | .DS_Store 5 | SANDBOX 6 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | /// Error type for OSC operations. 2 | /// 3 | /// An error type for the errors that may happen while sending or receiving messages over an OSC 4 | /// socket. 5 | #[derive(thiserror::Error, Debug)] 6 | pub enum Error { 7 | /// IO error 8 | #[error("IO error")] 9 | Io(#[from] std::io::Error), 10 | /// OSC decode error 11 | #[error("Decode OSC packet failed")] 12 | Osc(rosc::OscError), 13 | } 14 | 15 | impl From for Error { 16 | fn from(error: rosc::OscError) -> Self { 17 | Self::Osc(error) 18 | } 19 | } 20 | 21 | /// Result type for OSC operations. 22 | pub type Result = std::result::Result; 23 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "async-osc" 3 | version = "0.2.0" 4 | license = "MIT OR Apache-2.0" 5 | repository = "https://github.com/Frando/async-osc" 6 | documentation = "https://docs.rs/async-osc" 7 | description = "Async library for the Open Sound Control (OSC) protocol" 8 | readme = "README.md" 9 | edition = "2018" 10 | keywords = ["osc", "audio", "async-std"] 11 | categories = ["network-programming", "asynchronous", "multimedia::audio"] 12 | authors = [ 13 | "Franz Heinzmann " 14 | ] 15 | 16 | [features] 17 | 18 | [dependencies] 19 | rosc = "0.4.2" 20 | async-std = { version = "1.9.0", features = ["unstable"] } 21 | log = "0.4.14" 22 | futures-lite = "1.11.3" 23 | thiserror = "1.0.24" 24 | 25 | [dev-dependencies] 26 | async-std = { version = "1.9.0", features = ["unstable", "attributes"] } 27 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Franz Heinzmann 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /examples/simple.rs: -------------------------------------------------------------------------------- 1 | use async_osc::{prelude::*, Error, OscPacket, OscSocket, OscType, Result}; 2 | use async_std::stream::StreamExt; 3 | 4 | #[async_std::main] 5 | async fn main() -> Result<()> { 6 | let mut socket = OscSocket::bind("localhost:5050").await?; 7 | 8 | // Open a second socket to send a test message. 9 | async_std::task::spawn(async move { 10 | let socket = OscSocket::bind("localhost:0").await?; 11 | socket.connect("localhost:5050").await?; 12 | socket 13 | .send(("/volume", (0.9f32, "foo".to_string()))) 14 | .await?; 15 | Ok::<(), Error>(()) 16 | }); 17 | 18 | // Listen for incoming packets on the first socket. 19 | while let Some(packet) = socket.next().await { 20 | let (packet, peer_addr) = packet?; 21 | eprintln!("Receive from {}: {:?}", peer_addr, packet); 22 | match packet { 23 | OscPacket::Bundle(_) => {} 24 | OscPacket::Message(message) => match &message.as_tuple() { 25 | ("/volume", &[OscType::Float(vol), OscType::String(ref s)]) => { 26 | eprintln!("Set volume: {} {}", vol, s); 27 | } 28 | _ => {} 29 | }, 30 | } 31 | } 32 | Ok(()) 33 | } 34 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | use async_osc::prelude::*; 2 | use async_osc::{OscMessage, OscPacket, OscSocket, OscType, Result}; 3 | use async_std::stream::StreamExt; 4 | use async_std::task::{self, JoinHandle}; 5 | 6 | #[async_std::test] 7 | async fn connect_send_recv() -> Result<()> { 8 | let mut socket1 = OscSocket::bind("localhost:0").await?; 9 | let mut socket2 = OscSocket::bind("localhost:0").await?; 10 | let addr1 = socket1.socket().local_addr()?; 11 | let addr2 = socket2.socket().local_addr()?; 12 | 13 | let task: JoinHandle> = task::spawn(async move { 14 | if let Some(packet) = socket2.next().await { 15 | let (packet, peer_addr) = packet?; 16 | let message = packet.message().unwrap(); 17 | assert_eq!(peer_addr, addr1); 18 | assert_eq!(&message.addr, "/glitch"); 19 | assert_eq!( 20 | &message.args, 21 | &[OscType::Float(0.17), OscType::String("ultra".to_string())] 22 | ); 23 | let reply = ("/ack", (1,)); 24 | socket2.send_to(reply, peer_addr).await?; 25 | } 26 | Ok(()) 27 | }); 28 | 29 | socket1.connect(addr2).await?; 30 | socket1.send(("/glitch", (0.17f32, "ultra"))).await?; 31 | 32 | if let Some(Ok((OscPacket::Message(message), peer_addr))) = socket1.next().await { 33 | assert_eq!(message, OscMessage::new("/ack", (1,))); 34 | assert_eq!(peer_addr, addr2); 35 | } 36 | 37 | task.await?; 38 | 39 | Ok(()) 40 | } 41 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - staging 8 | - trying 9 | 10 | env: 11 | RUSTFLAGS: -Dwarnings 12 | 13 | jobs: 14 | build_and_test: 15 | name: Build and test 16 | runs-on: ${{ matrix.os }} 17 | strategy: 18 | matrix: 19 | os: [ubuntu-latest, windows-latest, macOS-latest] 20 | rust: [stable] 21 | 22 | steps: 23 | - uses: actions/checkout@master 24 | 25 | - name: Install ${{ matrix.rust }} 26 | uses: actions-rs/toolchain@v1 27 | with: 28 | toolchain: ${{ matrix.rust }} 29 | override: true 30 | 31 | - name: check 32 | uses: actions-rs/cargo@v1 33 | with: 34 | command: check 35 | args: --all --bins --examples 36 | 37 | - name: check unstable 38 | uses: actions-rs/cargo@v1 39 | with: 40 | command: check 41 | args: --all --benches --bins --examples --tests 42 | 43 | - name: tests 44 | uses: actions-rs/cargo@v1 45 | with: 46 | command: test 47 | args: --all 48 | 49 | check_fmt_and_docs: 50 | name: Checking fmt and docs 51 | runs-on: ubuntu-latest 52 | steps: 53 | - uses: actions/checkout@master 54 | - uses: actions-rs/toolchain@v1 55 | with: 56 | toolchain: nightly 57 | components: rustfmt, clippy 58 | override: true 59 | 60 | - name: fmt 61 | run: cargo fmt --all -- --check 62 | 63 | - name: Docs 64 | run: cargo doc 65 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![forbid(unsafe_code, future_incompatible, rust_2018_idioms)] 2 | #![deny(missing_debug_implementations, nonstandard_style)] 3 | #![warn(missing_docs, missing_doc_code_examples, unreachable_pub)] 4 | 5 | //! Async library for the Open Sound Control (OSC) protocol 6 | //! 7 | //! # Examples 8 | //! 9 | //! ``` 10 | //! # #[async_std::main] 11 | //! # async fn main() -> async_osc::Result<()> { 12 | //! use async_std::stream::StreamExt; 13 | //! use async_osc::{prelude::*, OscSocket, OscPacket, OscType, Error, Result}; 14 | //! 15 | //! let mut socket = OscSocket::bind("localhost:5050").await?; 16 | //! 17 | //! // Open a second socket to send a test message. 18 | //! async_std::task::spawn(async move { 19 | //! let socket = OscSocket::bind("localhost:0").await?; 20 | //! socket.connect("localhost:5050").await?; 21 | //! socket.send(("/volume", (0.9f32,))).await?; 22 | //! Ok::<(), Error>(()) 23 | //! }); 24 | //! 25 | //! // Listen for incoming packets on the first socket. 26 | //! while let Some(packet) = socket.next().await { 27 | //! let (packet, peer_addr) = packet?; 28 | //! eprintln!("Receive from {}: {:?}", peer_addr, packet); 29 | //! match packet { 30 | //! OscPacket::Bundle(_) => {} 31 | //! OscPacket::Message(message) => match message.as_tuple() { 32 | //! ("/volume", &[OscType::Float(vol)]) => { 33 | //! eprintln!("Set volume: {}", vol); 34 | //! // Do something with the received data. 35 | //! // Here, just quit the doctest. 36 | //! assert_eq!(vol, 0.9f32); 37 | //! return Ok(()) 38 | //! } 39 | //! _ => {} 40 | //! }, 41 | //! } 42 | //! } 43 | //! # Ok(()) 44 | //! # } 45 | //! // tbi 46 | //! ``` 47 | 48 | /// Re-export the main OSC types from the [`rosc`] crate. 49 | pub mod rosc { 50 | pub use ::rosc::{OscBundle, OscMessage, OscPacket, OscType}; 51 | } 52 | 53 | pub use crate::rosc::*; 54 | 55 | mod error; 56 | mod message; 57 | mod osc; 58 | mod udp; 59 | 60 | pub use error::{Error, Result}; 61 | pub use osc::{OscSender, OscSocket}; 62 | // pub use udp::*; 63 | 64 | /// Prelude with extensions to [`rosc`] types. 65 | /// 66 | /// It is recommended to import everything from this module whenever working with these types. 67 | /// See [`preulude::OscMessageExt`] for details. 68 | pub mod prelude { 69 | pub use crate::message::{ 70 | IntoOscArgs, IntoOscMessage, IntoOscPacket, OscMessageExt, OscPacketExt, 71 | }; 72 | } 73 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | Contributions include code, documentation, answering user questions, running the 3 | project's infrastructure, and advocating for all types of users. 4 | 5 | The project welcomes all contributions from anyone willing to work in good faith 6 | with other contributors and the community. No contribution is too small and all 7 | contributions are valued. 8 | 9 | This guide explains the process for contributing to the project's GitHub 10 | Repository. 11 | 12 | - [Code of Conduct](#code-of-conduct) 13 | - [Bad Actors](#bad-actors) 14 | 15 | ## Code of Conduct 16 | The project has a [Code of Conduct](./CODE_OF_CONDUCT.md) that *all* 17 | contributors are expected to follow. This code describes the *minimum* behavior 18 | expectations for all contributors. 19 | 20 | As a contributor, how you choose to act and interact towards your 21 | fellow contributors, as well as to the community, will reflect back not only 22 | on yourself but on the project as a whole. The Code of Conduct is designed and 23 | intended, above all else, to help establish a culture within the project that 24 | allows anyone and everyone who wants to contribute to feel safe doing so. 25 | 26 | Should any individual act in any way that is considered in violation of the 27 | [Code of Conduct](./CODE_OF_CONDUCT.md), corrective actions will be taken. It is 28 | possible, however, for any individual to *act* in such a manner that is not in 29 | violation of the strict letter of the Code of Conduct guidelines while still 30 | going completely against the spirit of what that Code is intended to accomplish. 31 | 32 | Open, diverse, and inclusive communities live and die on the basis of trust. 33 | Contributors can disagree with one another so long as they trust that those 34 | disagreements are in good faith and everyone is working towards a common 35 | goal. 36 | 37 | ## Bad Actors 38 | All contributors to tacitly agree to abide by both the letter and 39 | spirit of the [Code of Conduct](./CODE_OF_CONDUCT.md). Failure, or 40 | unwillingness, to do so will result in contributions being respectfully 41 | declined. 42 | 43 | A *bad actor* is someone who repeatedly violates the *spirit* of the Code of 44 | Conduct through consistent failure to self-regulate the way in which they 45 | interact with other contributors in the project. In doing so, bad actors 46 | alienate other contributors, discourage collaboration, and generally reflect 47 | poorly on the project as a whole. 48 | 49 | Being a bad actor may be intentional or unintentional. Typically, unintentional 50 | bad behavior can be easily corrected by being quick to apologize and correct 51 | course *even if you are not entirely convinced you need to*. Giving other 52 | contributors the benefit of the doubt and having a sincere willingness to admit 53 | that you *might* be wrong is critical for any successful open collaboration. 54 | 55 | Don't be a bad actor. 56 | -------------------------------------------------------------------------------- /src/udp.rs: -------------------------------------------------------------------------------- 1 | #![allow(unreachable_pub)] 2 | 3 | use async_std::net::UdpSocket; 4 | use async_std::stream::Stream; 5 | use futures_lite::future::Future; 6 | use futures_lite::ready; 7 | use std::fmt; 8 | use std::io; 9 | use std::net::SocketAddr; 10 | use std::pin::Pin; 11 | use std::sync::Arc; 12 | use std::task::{Context, Poll}; 13 | 14 | pub(crate) type RecvFut = 15 | Pin, usize, SocketAddr)>> + Send + Sync>>; 16 | 17 | pub(crate) struct UdpSocketStream { 18 | pub(crate) socket: Arc, 19 | fut: Option, 20 | buf: Option>, 21 | } 22 | 23 | // TODO: Decide if Clone shold be enabled. 24 | // I'm not sure about the behavior of polling from different clones. 25 | impl Clone for UdpSocketStream { 26 | fn clone(&self) -> Self { 27 | Self::from_arc(self.socket.clone()) 28 | } 29 | } 30 | 31 | impl fmt::Debug for UdpSocketStream { 32 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 33 | f.debug_struct("UdpSocketStream") 34 | .field("socket", &*self.socket) 35 | .finish() 36 | } 37 | } 38 | 39 | impl UdpSocketStream { 40 | pub fn new(socket: UdpSocket) -> Self { 41 | let socket = Arc::new(socket); 42 | Self::from_arc(socket) 43 | } 44 | 45 | pub fn from_arc(socket: Arc) -> Self { 46 | let buf = vec![0u8; 1024 * 64]; 47 | Self { 48 | socket, 49 | fut: None, 50 | buf: Some(buf), 51 | } 52 | } 53 | 54 | pub fn get_ref(&self) -> &UdpSocket { 55 | &self.socket 56 | } 57 | 58 | pub fn clone_inner(&self) -> Arc { 59 | self.socket.clone() 60 | } 61 | } 62 | 63 | impl Stream for UdpSocketStream { 64 | type Item = io::Result<(Vec, SocketAddr)>; 65 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 66 | loop { 67 | if self.fut.is_none() { 68 | let buf = self.buf.take().unwrap(); 69 | let fut = recv_next(self.socket.clone(), buf); 70 | self.fut = Some(Box::pin(fut)); 71 | } 72 | 73 | if let Some(f) = &mut self.fut { 74 | let res = ready!(f.as_mut().poll(cx)); 75 | self.fut = None; 76 | return match res { 77 | Err(e) => Poll::Ready(Some(Err(e))), 78 | Ok((buf, n, addr)) => { 79 | let res_buf = buf[..n].to_vec(); 80 | self.buf = Some(buf); 81 | Poll::Ready(Some(Ok((res_buf, addr)))) 82 | } 83 | }; 84 | } 85 | } 86 | } 87 | } 88 | 89 | async fn recv_next( 90 | socket: Arc, 91 | mut buf: Vec, 92 | ) -> io::Result<(Vec, usize, SocketAddr)> { 93 | // let mut buf = vec![0u8; 1024]; 94 | let res = socket.recv_from(&mut buf).await; 95 | match res { 96 | Err(e) => Err(e), 97 | Ok((n, addr)) => Ok((buf, n, addr)), 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of 9 | experience, 10 | education, socio-economic status, nationality, personal appearance, race, 11 | religion, or sexual identity and orientation. 12 | 13 | ## Our Standards 14 | 15 | Examples of behavior that contributes to creating a positive environment 16 | include: 17 | 18 | - Using welcoming and inclusive language 19 | - Being respectful of differing viewpoints and experiences 20 | - Gracefully accepting constructive criticism 21 | - Focusing on what is best for the community 22 | - Showing empathy towards other community members 23 | 24 | Examples of unacceptable behavior by participants include: 25 | 26 | - The use of sexualized language or imagery and unwelcome sexual attention or 27 | advances 28 | - Trolling, insulting/derogatory comments, and personal or political attacks 29 | - Public or private harassment 30 | - Publishing others' private information, such as a physical or electronic 31 | address, without explicit permission 32 | - Other conduct which could reasonably be considered inappropriate in a 33 | professional setting 34 | 35 | 36 | ## Our Responsibilities 37 | 38 | Project maintainers are responsible for clarifying the standards of acceptable 39 | behavior and are expected to take appropriate and fair corrective action in 40 | response to any instances of unacceptable behavior. 41 | 42 | Project maintainers have the right and responsibility to remove, edit, or 43 | reject comments, commits, code, wiki edits, issues, and other contributions 44 | that are not aligned to this Code of Conduct, or to ban temporarily or 45 | permanently any contributor for other behaviors that they deem inappropriate, 46 | threatening, offensive, or harmful. 47 | 48 | ## Scope 49 | 50 | This Code of Conduct applies both within project spaces and in public spaces 51 | when an individual is representing the project or its community. Examples of 52 | representing a project or community include using an official project e-mail 53 | address, posting via an official social media account, or acting as an appointed 54 | representative at an online or offline event. Representation of a project may be 55 | further defined and clarified by project maintainers. 56 | 57 | ## Enforcement 58 | 59 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 60 | reported by contacting the project team at franz@arso.xyz, or through 61 | IRC. All complaints will be reviewed and investigated and will result in a 62 | response that is deemed necessary and appropriate to the circumstances. The 63 | project team is obligated to maintain confidentiality with regard to the 64 | reporter of an incident. 65 | Further details of specific enforcement policies may be posted separately. 66 | 67 | Project maintainers who do not follow or enforce the Code of Conduct in good 68 | faith may face temporary or permanent repercussions as determined by other 69 | members of the project's leadership. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, 74 | available at 75 | https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

async-osc

2 |
3 | 4 | Async Rust library for the Open Sound Control (OSC) protocol 5 | 6 |
7 | 8 |
9 | 10 |
11 | 12 | 13 | Crates.io version 15 | 16 | 17 | 18 | Download 20 | 21 | 22 | 23 | docs.rs docs 25 | 26 |
27 | 28 | 43 | 44 | This crate implements an async interface on the [OSC 1.0](https://web.archive.org/web/20201211193930/http://opensoundcontrol.org/spec-1_0) protocol. It uses [`async-std`](https://docs.rs/async-std) for async networking and [`rosc`](https://docs.rs/rosc) for OSC encoding and decoding. 45 | 46 | ## Installation 47 | ```sh 48 | $ cargo add async-osc 49 | ``` 50 | 51 | ## Example 52 | ```rust 53 | use async_osc::{prelude::*, Error, OscPacket, OscSocket, OscType, Result}; 54 | use async_std::stream::StreamExt; 55 | 56 | #[async_std::main] 57 | async fn main() -> Result<()> { 58 | let mut socket = OscSocket::bind("localhost:5050").await?; 59 | 60 | // Open a second socket to send a test message. 61 | async_std::task::spawn(async move { 62 | let socket = OscSocket::bind("localhost:0").await?; 63 | socket.connect("localhost:5050").await?; 64 | socket 65 | .send(("/volume", (0.9f32, "foo".to_string()))) 66 | .await?; 67 | Ok::<(), Error>(()) 68 | }); 69 | 70 | // Listen for incoming packets on the first socket. 71 | while let Some(packet) = socket.next().await { 72 | let (packet, peer_addr) = packet?; 73 | eprintln!("Receive from {}: {:?}", peer_addr, packet); 74 | match packet { 75 | OscPacket::Bundle(_) => {} 76 | OscPacket::Message(message) => match &message.as_tuple() { 77 | ("/volume", &[OscType::Float(vol), OscType::String(ref s)]) => { 78 | eprintln!("Set volume: {} {}", vol, s); 79 | } 80 | _ => {} 81 | }, 82 | } 83 | } 84 | Ok(()) 85 | } 86 | ``` 87 | 88 | ## Safety 89 | This crate uses ``#![deny(unsafe_code)]`` to ensure everything is implemented in 90 | 100% Safe Rust. 91 | 92 | ## Contributing 93 | Want to join us? Check out our ["Contributing" guide][contributing] and take a 94 | look at some of these issues: 95 | 96 | - [Issues labeled "good first issue"][good-first-issue] 97 | - [Issues labeled "help wanted"][help-wanted] 98 | 99 | [contributing]: https://github.com/Frando/async-osc/blob/master.github/CONTRIBUTING.md 100 | [good-first-issue]: https://github.com/Frando/async-osc/labels/good%20first%20issue 101 | [help-wanted]: https://github.com/Frando/async-osc/labels/help%20wanted 102 | 103 | ## License 104 | 105 | 106 | Licensed under either of Apache License, Version 107 | 2.0 or MIT license at your option. 108 | 109 | 110 |
111 | 112 | 113 | Unless you explicitly state otherwise, any contribution intentionally submitted 114 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 115 | be dual licensed as above, without any additional terms or conditions. 116 | 117 | -------------------------------------------------------------------------------- /src/message.rs: -------------------------------------------------------------------------------- 1 | use rosc::{OscBundle, OscMessage, OscPacket, OscType}; 2 | 3 | /// Extension methods for the [`rosc::OscMessage`] type. 4 | pub trait OscMessageExt { 5 | /// Create a new OscMessage from an address and args. 6 | /// The args can either be specified as a `Vec<[OscType]`, or as a tuple of regular Rust types 7 | /// that can be converted into [`OscType`]. 8 | fn new(addr: impl ToString, args: T) -> Self 9 | where 10 | T: IntoOscArgs; 11 | 12 | /// Returns `true` if the address starts with the given prefix. 13 | /// 14 | /// Returns `false` otherwise. 15 | fn starts_with(&self, prefix: &str) -> bool; 16 | 17 | /// Get a reference to the message in tuple form. 18 | /// 19 | /// This is useful for pattern matching. Example: 20 | /// 21 | /// ```no_run 22 | /// # use async_osc::{*, prelude::*}; 23 | /// let message = OscMessage::new("/foo", vec![ 24 | /// OscType::Float(1.0), OscType::String("bar".into()) 25 | /// ]); 26 | /// 27 | /// match message.as_tuple() { 28 | /// ("foo", &[OscType::Float(val), OscType::String(ref text)]) => { 29 | /// eprintln!("Got foo message with args: {}, {}", val, text); 30 | /// }, 31 | /// _ => {} 32 | /// } 33 | /// ``` 34 | fn as_tuple(&self) -> (&str, &[OscType]); 35 | } 36 | 37 | impl OscMessageExt for OscMessage { 38 | fn new(addr: impl ToString, args: T) -> Self 39 | where 40 | T: IntoOscArgs, 41 | { 42 | let args = args.into_osc_args(); 43 | let addr = addr.to_string(); 44 | OscMessage { addr, args } 45 | } 46 | 47 | fn starts_with(&self, prefix: &str) -> bool { 48 | self.addr.starts_with(prefix) 49 | } 50 | 51 | fn as_tuple(&self) -> (&str, &[OscType]) { 52 | (self.addr.as_str(), &self.args[..]) 53 | } 54 | } 55 | 56 | /// Extension methods for the [`rosc::OscMessage`] type. 57 | pub trait OscPacketExt { 58 | /// Return `Some(&message)` if the packet is 'OscPacket::Message`. 59 | /// 60 | /// Return None otherwise. 61 | fn message(&self) -> Option<&OscMessage>; 62 | 63 | /// Return `Some(message)` if the packet is 'OscPacket::Message`. 64 | /// 65 | /// Return None otherwise. 66 | fn into_message(self) -> Option; 67 | } 68 | 69 | impl OscPacketExt for OscPacket { 70 | fn message(&self) -> Option<&OscMessage> { 71 | match self { 72 | OscPacket::Message(message) => Some(message), 73 | _ => None, 74 | } 75 | } 76 | fn into_message(self) -> Option { 77 | match self { 78 | OscPacket::Message(message) => Some(message), 79 | _ => None, 80 | } 81 | } 82 | } 83 | 84 | /// Helper trait to convert types into `Vec<[OscType]>` 85 | pub trait IntoOscArgs { 86 | /// Convert self to OSC args. 87 | fn into_osc_args(self) -> Vec; 88 | } 89 | 90 | impl IntoOscArgs for Vec 91 | where 92 | T: Into, 93 | { 94 | fn into_osc_args(self) -> Vec { 95 | let args: Vec = self.into_iter().map(|a| a.into()).collect(); 96 | args 97 | } 98 | } 99 | 100 | // We cannot implement IntoOscArgs for T because it conflicts 101 | // with the impl for Vec above. 102 | // TODO: Find out if there is a solution. 103 | // impl IntoOscArgs for T 104 | // where 105 | // T: Into, 106 | // { 107 | // fn into_osc_args(self) -> Vec { 108 | // vec![self.into()] 109 | // } 110 | // } 111 | 112 | impl IntoOscArgs for (T1,) 113 | where 114 | T1: Into, 115 | { 116 | fn into_osc_args(self) -> Vec { 117 | vec![self.0.into()] 118 | } 119 | } 120 | 121 | impl IntoOscArgs for (T1, T2) 122 | where 123 | T1: Into, 124 | T2: Into, 125 | { 126 | fn into_osc_args(self) -> Vec { 127 | vec![self.0.into(), self.1.into()] 128 | } 129 | } 130 | 131 | impl IntoOscArgs for (T1, T2, T3) 132 | where 133 | T1: Into, 134 | T2: Into, 135 | T3: Into, 136 | { 137 | fn into_osc_args(self) -> Vec { 138 | vec![self.0.into(), self.1.into(), self.2.into()] 139 | } 140 | } 141 | 142 | impl IntoOscArgs for OscType { 143 | fn into_osc_args(self) -> Vec { 144 | vec![self] 145 | } 146 | } 147 | 148 | /// Helper trait to convert [`OscMessage`] and [`OscBundle`] into [`OscPacket`]. 149 | pub trait IntoOscPacket { 150 | /// Convert into [`OscPacket`]. 151 | fn into_osc_packet(self) -> OscPacket; 152 | } 153 | 154 | impl IntoOscPacket for OscMessage { 155 | fn into_osc_packet(self) -> OscPacket { 156 | OscPacket::Message(self) 157 | } 158 | } 159 | 160 | impl IntoOscPacket for OscBundle { 161 | fn into_osc_packet(self) -> OscPacket { 162 | OscPacket::Bundle(self) 163 | } 164 | } 165 | 166 | impl IntoOscPacket for OscPacket { 167 | fn into_osc_packet(self) -> OscPacket { 168 | self 169 | } 170 | } 171 | 172 | impl IntoOscPacket for T 173 | where 174 | T: IntoOscMessage, 175 | { 176 | fn into_osc_packet(self) -> OscPacket { 177 | OscPacket::Message(self.into_osc_message()) 178 | } 179 | } 180 | 181 | /// Helper trait to convert a `(impl ToString, impl IntoOscArgs)` tuple into [`OscMessage`]. 182 | pub trait IntoOscMessage { 183 | /// Convert to [`OscMessage`]. 184 | fn into_osc_message(self) -> OscMessage; 185 | } 186 | 187 | impl IntoOscMessage for (S, A) 188 | where 189 | S: ToString, 190 | A: IntoOscArgs, 191 | { 192 | fn into_osc_message(self) -> OscMessage { 193 | OscMessage::new(self.0, self.1) 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/osc.rs: -------------------------------------------------------------------------------- 1 | use async_std::net::{ToSocketAddrs, UdpSocket}; 2 | use async_std::stream::Stream; 3 | use futures_lite::ready; 4 | use rosc::OscPacket; 5 | use std::io; 6 | use std::net::SocketAddr; 7 | use std::pin::Pin; 8 | use std::sync::Arc; 9 | use std::task::{Context, Poll}; 10 | 11 | use crate::error::Error; 12 | use crate::prelude::IntoOscPacket; 13 | use crate::udp::UdpSocketStream; 14 | 15 | /// A UDP socket to send and receive OSC messages. 16 | #[derive(Debug)] 17 | pub struct OscSocket { 18 | socket: UdpSocketStream, 19 | } 20 | 21 | impl OscSocket { 22 | /// Creates a new OSC socket from a [`async_std::net::UdpSocket`]. 23 | pub fn new(socket: UdpSocket) -> Self { 24 | let socket = UdpSocketStream::new(socket); 25 | Self { socket } 26 | } 27 | 28 | /// Creates an OSC socket from the given address. 29 | /// 30 | /// Binding with a port number of 0 will request that the OS assigns a port to this socket. 31 | /// The port allocated can be queried via [`local_addr`] method. 32 | /// 33 | /// [`local_addr`]: #method.local_addr 34 | pub async fn bind(addr: A) -> Result { 35 | let socket = UdpSocket::bind(addr).await?; 36 | Ok(Self::new(socket)) 37 | } 38 | 39 | /// Connects the UDP socket to a remote address. 40 | /// 41 | /// When connected, only messages from this address will be received and the [`send`] method 42 | /// will use the specified address for sending. 43 | /// 44 | /// [`send`]: #method.send 45 | /// 46 | /// # Examples 47 | /// 48 | /// ```no_run 49 | /// # fn main() -> async_osc::Result<()> { async_std::task::block_on(async { 50 | /// # 51 | /// use async_osc::{prelude::*, OscSocket, OscMessage}; 52 | /// 53 | /// let socket = OscSocket::bind("127.0.0.1:0").await?; 54 | /// socket.connect("127.0.0.1:8080").await?; 55 | /// # 56 | /// # Ok(()) }) } 57 | /// ``` 58 | pub async fn connect(&self, addrs: A) -> Result<(), Error> { 59 | self.socket().connect(addrs).await?; 60 | Ok(()) 61 | } 62 | 63 | /// Sends an OSC packet on the socket to the given address. 64 | /// 65 | /// # Examples 66 | /// 67 | /// ```no_run 68 | /// # fn main() -> async_osc::Result<()> { async_std::task::block_on(async { 69 | /// # 70 | /// use async_osc::{prelude::*, OscSocket, OscMessage}; 71 | /// 72 | /// let socket = OscSocket::bind("127.0.0.1:0").await?; 73 | /// let addr = "127.0.0.1:5010"; 74 | /// let message = OscMessage::new("/volume", (0.8,)); 75 | /// socket.send_to(message, &addr).await?; 76 | /// # 77 | /// # Ok(()) }) } 78 | /// ``` 79 | pub async fn send_to( 80 | &self, 81 | packet: P, 82 | addrs: A, 83 | ) -> Result<(), Error> { 84 | let buf = rosc::encoder::encode(&packet.into_osc_packet())?; 85 | let n = self.socket().send_to(&buf[..], addrs).await?; 86 | check_len(&buf[..], n) 87 | } 88 | 89 | /// Sends a packet on the socket to the remote address to which it is connected. 90 | /// 91 | /// The [`connect`] method will connect this socket to a remote address. 92 | /// This method will fail if the socket is not connected. 93 | /// 94 | /// [`connect`]: #method.connect 95 | /// 96 | /// # Examples 97 | /// 98 | /// ```no_run 99 | /// # fn main() -> async_osc::Result<()> { async_std::task::block_on(async { 100 | /// # 101 | /// use async_osc::{prelude::*, OscSocket, OscMessage}; 102 | /// 103 | /// let socket = OscSocket::bind("127.0.0.1:34254").await?; 104 | /// socket.connect("127.0.0.1:8080").await?; 105 | /// socket.send(("/volume", (1.0f32,))).await?; 106 | /// # 107 | /// # Ok(()) }) } 108 | /// ``` 109 | pub async fn send(&self, packet: P) -> Result<(), Error> { 110 | let buf = rosc::encoder::encode(&packet.into_osc_packet())?; 111 | let n = self.socket().send(&buf[..]).await?; 112 | check_len(&buf[..], n) 113 | } 114 | 115 | /// Create a standalone sender for this socket. 116 | /// 117 | /// The sender can be moved to other threads or tasks. 118 | pub fn sender(&self) -> OscSender { 119 | OscSender::new(self.socket.clone_inner()) 120 | } 121 | 122 | /// Get a reference to the underling [`UdpSocket`]. 123 | pub fn socket(&self) -> &UdpSocket { 124 | self.socket.get_ref() 125 | } 126 | 127 | /// Returns the local address that this socket is bound to. 128 | /// 129 | /// This can be useful, for example, when binding to port 0 to figure out which port was 130 | /// actually bound. 131 | pub fn local_addr(&self) -> Result { 132 | let addr = self.socket().local_addr()?; 133 | Ok(addr) 134 | } 135 | } 136 | 137 | impl Stream for OscSocket { 138 | type Item = Result<(OscPacket, SocketAddr), Error>; 139 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 140 | let packet = ready!(Pin::new(&mut self.socket).poll_next(cx)); 141 | let message = match packet { 142 | None => None, 143 | Some(packet) => Some(match packet { 144 | Err(err) => Err(err.into()), 145 | Ok((buf, peer_addr)) => rosc::decoder::decode(&buf[..]) 146 | .map_err(|e| e.into()) 147 | .map(|p| (p, peer_addr)), 148 | }), 149 | }; 150 | Poll::Ready(message) 151 | } 152 | } 153 | 154 | /// A sender to send messages over an OSC socket. 155 | /// 156 | /// See [`OscSocket::sender`]. 157 | #[derive(Clone, Debug)] 158 | pub struct OscSender { 159 | socket: Arc, 160 | } 161 | 162 | impl OscSender { 163 | fn new(socket: Arc) -> Self { 164 | Self { socket } 165 | } 166 | 167 | /// Sends an OSC packet on the socket to the given address. 168 | /// 169 | /// See [`OscSocket::send_to`]. 170 | pub async fn send_to( 171 | &self, 172 | packet: P, 173 | addrs: A, 174 | ) -> Result<(), Error> { 175 | let buf = rosc::encoder::encode(&packet.into_osc_packet())?; 176 | let n = self.socket().send_to(&buf[..], addrs).await?; 177 | check_len(&buf[..], n) 178 | } 179 | 180 | /// Sends an OSC packet on the connected socket. 181 | /// 182 | /// See [`OscSocket::send`]. 183 | pub async fn send(&self, packet: P) -> Result<(), Error> { 184 | let buf = rosc::encoder::encode(&packet.into_osc_packet())?; 185 | let n = self.socket().send(&buf[..]).await?; 186 | check_len(&buf[..], n) 187 | } 188 | 189 | /// Get a reference to the underling [`UdpSocket`]. 190 | pub fn socket(&self) -> &UdpSocket { 191 | &*self.socket 192 | } 193 | } 194 | 195 | fn check_len(buf: &[u8], len: usize) -> Result<(), Error> { 196 | if len != buf.len() { 197 | Err(io::Error::new(io::ErrorKind::Interrupted, "UDP packet not fully sent").into()) 198 | } else { 199 | Ok(()) 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 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 | Copyright 2020 Franz Heinzmann 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | --------------------------------------------------------------------------------