Skip to content

Commit

Permalink
Add possibility to send custom message (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
milenkovicm authored Jan 15, 2023
1 parent b831c4a commit 328b3ce
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/channels/receiver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use std::{
string::ToString,
};

use serde::Serialize;

use crate::{
cast::proxies,
errors::Error,
Expand Down Expand Up @@ -253,6 +255,46 @@ where
})
}

///
/// Sends message over chromecast message bus
///
/// Receiver can observe messages using `context.addCustomMessageListener` with custom namespace.
///
///```javascript, no_run
/// context.addCustomMessageListener('urn:x-cast:com.example.castdata', function(customEvent) {
/// // do something with message
/// });
///```
///
/// Namespace should start with `urn:x-cast:`
///
/// # Arguments
///
/// * `namespace` - Message namespace that should start with `urn:x-cast:`.
/// * `message` - Message instance to send.

pub fn broadcast_message<M: Serialize>(
&self,
namespace: &str,
message: &M,
) -> Result<(), Error> {
if !namespace.starts_with("urn:x-cast:") {
return Err(Error::Namespace(format!(
"'{}' should start with 'urn:x-cast:' prefix",
namespace
)));
}
let payload = serde_json::to_string(message)?;
self.message_manager.send(CastMessage {
namespace: namespace.to_string(),
source: self.sender.to_string(),
destination: "*".into(),
payload: CastMessagePayload::String(payload),
})?;

Ok(())
}

/// Stops currently active app using corresponding `session_id`.
///
/// # Arguments
Expand Down
4 changes: 4 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ pub enum Error {
Serialization(SerializationError),
/// This variant includes any error that comes from OpenSSL.
Ssl(SslError),
/// Problems with given namespace
Namespace(String),
}

impl Display for Error {
Expand All @@ -58,6 +60,7 @@ impl Display for Error {
Error::Protobuf(ref err) => Display::fmt(&err, f),
Error::Serialization(ref err) => Display::fmt(&err, f),
Error::Ssl(ref err) => Display::fmt(&err, f),
Error::Namespace(ref err) => Display::fmt(&err, f),
}
}
}
Expand All @@ -70,6 +73,7 @@ impl StdError for Error {
Error::Ssl(ref err) => Some(err),
Error::Serialization(ref err) => Some(err),
Error::Internal(_) => None,
Error::Namespace(_) => None,
}
}
}
Expand Down

0 comments on commit 328b3ce

Please sign in to comment.