Implement playback response

This commit is contained in:
Angel Yankov 2023-02-21 10:39:39 +02:00
parent 057bcb7860
commit d683aace8b

View file

@ -15,56 +15,73 @@
* limitations under the License. * limitations under the License.
*/ */
use super::objects::*; use super::objects::*;
use crate::{ use crate::{
error::*, error::*,
interaction_model::{command::CommandReq, core::IMStatusCode}, interaction_model::{
tlv::{TagType, TLVWriter}, command::CommandReq,
}; core::IMStatusCode,
use num_derive::FromPrimitive; messages::ib::{self},
use chrono::{NaiveDate, DateTime}; },
tlv::{TLVWriter, TagType, ToTLV},
};
use chrono::{DateTime, NaiveDate};
use num_derive::FromPrimitive;
pub const ID: u32 = 0x0506; pub const ID: u32 = 0x0506;
#[derive(FromPrimitive)] #[derive(FromPrimitive)]
pub enum Attributes { pub enum Attributes {
CurrentState = 0x0, CurrentState = 0x0,
StartTime = 0x1, StartTime = 0x1,
Duration = 0x2, Duration = 0x2,
SampledPosition = 0x3, SampledPosition = 0x3,
PlaybackSpeed = 0x4, PlaybackSpeed = 0x4,
SeekRangeEnd = 0x5, SeekRangeEnd = 0x5,
SeekRangeStart = 0x6 SeekRangeStart = 0x6,
} }
struct ClusterCallback { struct ClusterCallback {
name: Commands, name: Commands,
callback: Box<dyn FnMut()> callback: Box<dyn FnMut()>,
} }
enum FeatureMap { enum _FeatureMap {
AdvancedSeek = 0, AdvancedSeek = 0,
VariableSpeed = 1 VariableSpeed = 1,
} }
#[derive(FromPrimitive)] #[derive(FromPrimitive)]
enum PlaybackState { enum PlaybackState {
Playing = 0, Playing = 0,
Paused = 1, Paused = 1,
NotPlaying = 2, NotPlaying = 2,
BUFFERING = 3 BUFFERING = 3,
} }
#[derive(FromPrimitive)] #[derive(FromPrimitive)]
enum CommandStatus { enum CommandStatus {
Success = 0, Success = 0,
InvalidStateForCommand = 1, InvalidStateForCommand = 1,
NotAllowed = 2, NotAllowed = 2,
NotActive = 3, NotActive = 3,
SpeedOutOfRange = 4, SpeedOutOfRange = 4,
SeekOutOfRange = 5 SeekOutOfRange = 5,
} }
#[derive(FromPrimitive, PartialEq)] impl CommandStatus {
pub enum Commands { fn u8(&self) -> u8 {
match self {
CommandStatus::Success => 0,
CommandStatus::InvalidStateForCommand => 1,
CommandStatus::NotAllowed => 2,
CommandStatus::NotActive => 3,
CommandStatus::SpeedOutOfRange => 4,
CommandStatus::SeekOutOfRange => 5,
}
}
}
#[derive(FromPrimitive, PartialEq)]
pub enum Commands {
Play = 0x0, Play = 0x0,
Pause = 0x1, Pause = 0x1,
Stop = 0x2, Stop = 0x2,
@ -77,56 +94,62 @@ struct ClusterCallback {
SkipBackward = 0x9, SkipBackward = 0x9,
// Response is from us to server // Response is from us to server
PlaybackResponse = 0xa, PlaybackResponse = 0xa,
Seek = 0x0b Seek = 0x0b,
} }
struct PlaybackPosition { struct PlaybackPosition {
updated_at: u64, updated_at: u64,
position: u64 position: u64,
} }
// Get microseconds since 2000, Jan 1, 00:00:00 // Get microseconds since 2000, Jan 1, 00:00:00
pub fn get_epoch_us() -> u64 { pub fn get_epoch_us() -> u64 {
let epoch_start = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap().and_hms_micro_opt(0, 0, 0, 0).unwrap().and_local_timezone(chrono::Utc).unwrap(); let epoch_start = NaiveDate::from_ymd_opt(2000, 1, 1)
.unwrap()
.and_hms_micro_opt(0, 0, 0, 0)
.unwrap()
.and_local_timezone(chrono::Utc)
.unwrap();
DateTime::timestamp_micros(&epoch_start) as u64 DateTime::timestamp_micros(&epoch_start) as u64
} }
pub struct MediaPlaybackCluster { pub struct MediaPlaybackCluster {
base: Cluster, base: Cluster,
sampled_position: PlaybackPosition, sampled_position: PlaybackPosition,
callbacks: Vec<ClusterCallback> callbacks: Vec<ClusterCallback>,
} }
impl MediaPlaybackCluster { impl MediaPlaybackCluster {
pub fn new() -> Result<Box<Self>, Error> { pub fn new() -> Result<Box<Self>, Error> {
let mut cluster = Box::new(MediaPlaybackCluster { let mut cluster = Box::new(MediaPlaybackCluster {
base: Cluster::new(ID)?, base: Cluster::new(ID)?,
sampled_position: PlaybackPosition { updated_at: 0, position: 0 }, sampled_position: PlaybackPosition {
callbacks: vec!() updated_at: 0,
}); position: 0,
},
callbacks: vec![],
});
// List should be a Vec< // List should be a Vec<
let attrs = [ let attrs = [
Attribute::new( Attribute::new(
Attributes::CurrentState as u16, Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::NotPlaying as u8), AttrValue::Uint8(PlaybackState::NotPlaying as u8),
Access::RV, Access::RV,
Quality::PERSISTENT, Quality::PERSISTENT,
)?, )?,
// epoch-us
// epoch-us Attribute::new(
Attribute::new( Attributes::StartTime as u16,
Attributes::StartTime as u16, AttrValue::Uint64(0),
AttrValue::Uint64(0), Access::RV,
Access::RV, Quality::PERSISTENT,
Quality::PERSISTENT, )?,
)?, Attribute::new(
Attribute::new(
Attributes::Duration as u16, Attributes::Duration as u16,
AttrValue::Uint64(1), AttrValue::Uint64(1),
Access::RV, Access::RV,
Quality::PERSISTENT, Quality::PERSISTENT,
)?, )?,
// Playback-Position // Playback-Position
Attribute::new( Attribute::new(
Attributes::SampledPosition as u16, Attributes::SampledPosition as u16,
@ -134,7 +157,6 @@ struct ClusterCallback {
Access::RV, Access::RV,
Quality::PERSISTENT, Quality::PERSISTENT,
)?, )?,
// Float // Float
Attribute::new( Attribute::new(
Attributes::PlaybackSpeed as u16, Attributes::PlaybackSpeed as u16,
@ -154,184 +176,236 @@ struct ClusterCallback {
Access::RV, Access::RV,
Quality::PERSISTENT, Quality::PERSISTENT,
)?, )?,
// Options - probably want a custom type here for mapping cluster options to TLV bitmask // Options - probably want a custom type here for mapping cluster options to TLV bitmask
]; ];
cluster.base.add_attributes(&attrs)?; cluster.base.add_attributes(&attrs)?;
// For now disable all features by default // For now disable all features by default
cluster.base.set_feature_map(0)?; cluster.base.set_feature_map(0)?;
Ok(cluster) Ok(cluster)
} }
pub fn add_callback(&mut self, name: Commands, callback: Box<dyn FnMut()>) { pub fn add_callback(&mut self, name: Commands, callback: Box<dyn FnMut()>) {
self.callbacks.push(ClusterCallback { name, callback: callback}); self.callbacks.push(ClusterCallback {
} name,
callback: callback,
});
}
fn run_callback(&mut self, name: Commands) { fn run_callback(&mut self, name: Commands) {
for cmd in self.callbacks.iter_mut() { for cmd in self.callbacks.iter_mut() {
if cmd.name == name { if cmd.name == name {
(cmd.callback)() (cmd.callback)()
} }
} }
} }
fn _set_state_buffering(&mut self)-> Result<(), IMStatusCode>{ fn _set_state_buffering(&mut self) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Playing as u8))?; self.base.write_attribute_raw(
Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::Playing as u8),
)?;
Err(IMStatusCode::Sucess) Err(IMStatusCode::Sucess)
} }
fn _set_duration(&mut self, duration: u64)-> Result<(), IMStatusCode>{ fn _set_duration(&mut self, duration: u64) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(Attributes::Duration as u16, AttrValue::Uint64(duration))?; self.base
.write_attribute_raw(Attributes::Duration as u16, AttrValue::Uint64(duration))?;
Err(IMStatusCode::Sucess) Err(IMStatusCode::Sucess)
} }
// When rewinding / changing stream / etc we need to change absolute position and updateAt // When rewinding / changing stream / etc we need to change absolute position and updateAt
fn update_position(&mut self, new_pos: u64) -> Result<(), IMStatusCode>{ fn update_position(&mut self, new_pos: u64) -> Result<(), IMStatusCode> {
let now = get_epoch_us(); let now = get_epoch_us();
self.sampled_position.position = new_pos; self.sampled_position.position = new_pos;
self.sampled_position.updated_at = now; self.sampled_position.updated_at = now;
Err(IMStatusCode::Sucess) Err(IMStatusCode::Sucess)
} }
fn enocde_sampled_position(&self, tag: TagType, tw: &mut TLVWriter) { fn enocde_sampled_position(&self, tag: TagType, tw: &mut TLVWriter) {
let _ = tw.start_struct(tag); let _ = tw.start_struct(tag);
let _ = tw.u64(TagType::Context(0), self.sampled_position.position); let _ = tw.u64(TagType::Context(0), self.sampled_position.position);
let _ = tw.u64(TagType::Context(1), self.sampled_position.updated_at); let _ = tw.u64(TagType::Context(1), self.sampled_position.updated_at);
let _ = tw.end_container(); let _ = tw.end_container();
} }
}
} // Commmands
impl MediaPlaybackCluster {
fn handle_play(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(
Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::Playing as u8),
)?;
// Commmands
impl MediaPlaybackCluster {
fn handle_play(&mut self) -> Result<(), IMStatusCode>{
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Playing as u8))?;
self.run_callback(Commands::Play); self.run_callback(Commands::Play);
self.send_playback_response(CommandStatus::Success); self.send_playback_response(CommandStatus::Success, cmd_req);
Err(IMStatusCode::Sucess) Err(IMStatusCode::Sucess)
} }
fn handle_pause(&mut self) -> Result<(), IMStatusCode>{ fn handle_pause(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Paused as u8))?; self.base.write_attribute_raw(
Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::Paused as u8),
)?;
self.run_callback(Commands::Pause); self.run_callback(Commands::Pause);
self.send_playback_response(CommandStatus::Success); self.send_playback_response(CommandStatus::Success, cmd_req);
Err(IMStatusCode::Sucess) Err(IMStatusCode::Sucess)
} }
fn handle_stop(&mut self) -> Result<(), IMStatusCode>{ fn handle_stop(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::NotPlaying as u8))?; self.base.write_attribute_raw(
Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::NotPlaying as u8),
)?;
self.run_callback(Commands::Stop); self.run_callback(Commands::Stop);
self.send_playback_response(CommandStatus::Success); self.send_playback_response(CommandStatus::Success, cmd_req);
Err(IMStatusCode::Sucess) Err(IMStatusCode::Sucess)
} }
// Start current thinbg over // Start current thinbg over
fn handle_start_over(&mut self) -> Result<(), IMStatusCode>{ fn handle_start_over(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Playing as u8))?; self.base.write_attribute_raw(
self.update_position(0)?; Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::Playing as u8),
)?;
self.update_position(0)?;
self.run_callback(Commands::StartOver); self.run_callback(Commands::StartOver);
self.send_playback_response(CommandStatus::Success); self.send_playback_response(CommandStatus::Success, cmd_req);
Err(IMStatusCode::Sucess) Err(IMStatusCode::Sucess)
} }
fn handle_next(&mut self) -> Result<(), IMStatusCode>{ fn handle_next(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Playing as u8))?; self.base.write_attribute_raw(
Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::Playing as u8),
)?;
// self.update_position(0)?; // self.update_position(0)?;
self.send_playback_response(CommandStatus::NotAllowed); self.send_playback_response(CommandStatus::NotAllowed, cmd_req);
Err(IMStatusCode::UnsupportedCommand) Err(IMStatusCode::UnsupportedCommand)
} }
fn handle_previous(&mut self) -> Result<(), IMStatusCode>{ fn handle_previous(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Playing as u8))?; Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::Playing as u8),
)?;
// self.update_position(0)?; // self.update_position(0)?;
self.send_playback_response(CommandStatus::NotAllowed); self.send_playback_response(CommandStatus::NotAllowed, cmd_req);
Err(IMStatusCode::UnsupportedCommand) Err(IMStatusCode::UnsupportedCommand)
} }
fn handle_rewind(&mut self) -> Result<(), IMStatusCode>{ fn handle_rewind(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Playing as u8))?; self.base.write_attribute_raw(
self.send_playback_response(CommandStatus::NotAllowed); Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::Playing as u8),
)?;
self.send_playback_response(CommandStatus::NotAllowed, cmd_req);
Err(IMStatusCode::UnsupportedCommand) Err(IMStatusCode::UnsupportedCommand)
} }
fn handle_ff(&mut self) -> Result<(), IMStatusCode>{ fn handle_ff(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Playing as u8))?; self.base.write_attribute_raw(
self.send_playback_response(CommandStatus::NotAllowed); Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::Playing as u8),
)?;
self.send_playback_response(CommandStatus::NotAllowed, cmd_req);
Err(IMStatusCode::UnsupportedCommand) Err(IMStatusCode::UnsupportedCommand)
} }
fn handle_skip_forward(&mut self) -> Result<(), IMStatusCode>{ fn handle_skip_forward(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Playing as u8))?; self.base.write_attribute_raw(
self.send_playback_response(CommandStatus::NotAllowed); Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::Playing as u8),
)?;
self.send_playback_response(CommandStatus::NotAllowed, cmd_req);
Err(IMStatusCode::UnsupportedCommand) Err(IMStatusCode::UnsupportedCommand)
} }
fn handle_skip_backward(&mut self) -> Result<(), IMStatusCode>{ fn handle_skip_backward(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Playing as u8))?; self.base.write_attribute_raw(
self.send_playback_response(CommandStatus::NotAllowed); Attributes::CurrentState as u16,
AttrValue::Uint8(PlaybackState::Playing as u8),
)?;
self.send_playback_response(CommandStatus::NotAllowed, cmd_req);
Err(IMStatusCode::UnsupportedCommand) Err(IMStatusCode::UnsupportedCommand)
} }
fn handle_seek(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
fn handle_seek(&mut self) -> Result<(), IMStatusCode>{ self.base.write_attribute_raw(
self.base.write_attribute_raw(Attributes::CurrentState as u16, AttrValue::Uint8(PlaybackState::Playing as u8))?; Attributes::CurrentState as u16,
self.send_playback_response(CommandStatus::NotAllowed); AttrValue::Uint8(PlaybackState::Playing as u8),
)?;
self.send_playback_response(CommandStatus::NotAllowed, cmd_req);
Err(IMStatusCode::UnsupportedCommand) Err(IMStatusCode::UnsupportedCommand)
} }
// TODO: We send this to client // TODO: We send this to client
fn send_playback_response(&mut self, _status: CommandStatus) { fn send_playback_response(&mut self, status: CommandStatus, cmd_req: &mut CommandReq) {
// Write status as u8 let mut playback_response = cmd_req.cmd;
// Err(IMStatusCode::Sucess) playback_response.path.leaf = Some(Commands::PlaybackResponse as u32);
let resp = status.u8();
let cmd_data = |tag: TagType, t: &mut TLVWriter| {
let _ = t.start_struct(tag);
let _ = t.u8(TagType::Context(0), resp);
let _ = t.end_container();
};
let invoke_resp = ib::InvResp::Cmd(ib::CmdData::new(
playback_response,
EncodeValue::Closure(&cmd_data),
));
let _ = invoke_resp.to_tlv(cmd_req.resp, TagType::Anonymous);
cmd_req.trans.complete();
}
}
impl ClusterType for MediaPlaybackCluster {
fn base(&self) -> &Cluster {
&self.base
}
fn base_mut(&mut self) -> &mut Cluster {
&mut self.base
} }
} fn read_custom_attribute(&self, encoder: &mut dyn Encoder, attr: &AttrDetails) {
impl ClusterType for MediaPlaybackCluster {
fn base(&self) -> &Cluster {
&self.base
}
fn base_mut(&mut self) -> &mut Cluster {
&mut self.base
}
fn read_custom_attribute(&self, encoder: &mut dyn Encoder, attr: &AttrDetails) {
match num::FromPrimitive::from_u16(attr.attr_id) { match num::FromPrimitive::from_u16(attr.attr_id) {
Some(Attributes::SampledPosition) => encoder.encode(EncodeValue::Closure(&|tag, tw| { Some(Attributes::SampledPosition) => {
log::warn!("Encoding sampled position of self!"); encoder.encode(EncodeValue::Closure(&|tag, tw| {
self.enocde_sampled_position(tag, tw) log::warn!("Encoding sampled position of self!");
})), self.enocde_sampled_position(tag, tw)
_ => log::error!("Attribute not supported!") }))
}
_ => log::error!("Attribute not supported!"),
} }
} }
fn handle_command(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> { fn handle_command(&mut self, cmd_req: &mut CommandReq) -> Result<(), IMStatusCode> {
let cmd = cmd_req let cmd = cmd_req
.cmd .cmd
.path .path
.leaf .leaf
.map(num::FromPrimitive::from_u32) .map(num::FromPrimitive::from_u32)
.ok_or(IMStatusCode::UnsupportedCommand)? .ok_or(IMStatusCode::UnsupportedCommand)?
.ok_or(IMStatusCode::UnsupportedCommand)?; .ok_or(IMStatusCode::UnsupportedCommand)?;
match cmd { match cmd {
Commands::Play => self.handle_play(), Commands::Play => self.handle_play(cmd_req),
Commands::Pause => self.handle_pause(), Commands::Pause => self.handle_pause(cmd_req),
Commands::Stop => self.handle_stop(), Commands::Stop => self.handle_stop(cmd_req),
Commands::StartOver => self.handle_start_over(), Commands::StartOver => self.handle_start_over(cmd_req),
Commands::Previous => self.handle_previous(), Commands::Previous => self.handle_previous(cmd_req),
Commands::Next => self.handle_next(), Commands::Next => self.handle_next(cmd_req),
Commands::Rewind => self.handle_rewind(), Commands::Rewind => self.handle_rewind(cmd_req),
Commands::FastForward => self.handle_ff(), Commands::FastForward => self.handle_ff(cmd_req),
Commands::SkipForward => self.handle_skip_forward(), Commands::SkipForward => self.handle_skip_forward(cmd_req),
Commands::SkipBackward => self.handle_skip_backward(), Commands::SkipBackward => self.handle_skip_backward(cmd_req),
Commands::PlaybackResponse => Err(IMStatusCode::InvalidCommand), Commands::PlaybackResponse => Err(IMStatusCode::InvalidCommand),
Commands::Seek => self.handle_seek(), Commands::Seek => self.handle_seek(cmd_req),
} }
} }
} }