From 328b3ce2e1dc00542fad53fe18784bd84f1bcb7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Milenkovi=C4=87?= Date: Sun, 15 Jan 2023 12:18:04 +0000 Subject: [PATCH] Add possibility to send custom message (#16) --- src/channels/receiver.rs | 42 ++++++++++++++++++++++++++++++++++++++++ src/errors.rs | 4 ++++ 2 files changed, 46 insertions(+) diff --git a/src/channels/receiver.rs b/src/channels/receiver.rs index 7eb97995f..a5194feac 100644 --- a/src/channels/receiver.rs +++ b/src/channels/receiver.rs @@ -6,6 +6,8 @@ use std::{ string::ToString, }; +use serde::Serialize; + use crate::{ cast::proxies, errors::Error, @@ -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( + &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 diff --git a/src/errors.rs b/src/errors.rs index 0382e7552..daea05d4a 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -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 { @@ -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), } } } @@ -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, } } }