From 1c07973c377dc5fec933201b52cd79a5d9573949 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 1 Aug 2021 07:53:21 +0700 Subject: [PATCH] Restuructured bc_protocol to increase modulaitry --- crates/core/src/bc_protocol.rs | 392 +------------------------ crates/core/src/bc_protocol/errors.rs | 61 ++++ crates/core/src/bc_protocol/login.rs | 141 +++++++++ crates/core/src/bc_protocol/logout.rs | 12 + crates/core/src/bc_protocol/ping.rs | 31 ++ crates/core/src/bc_protocol/stream.rs | 110 +++++++ crates/core/src/bc_protocol/version.rs | 52 ++++ 7 files changed, 415 insertions(+), 384 deletions(-) create mode 100644 crates/core/src/bc_protocol/errors.rs create mode 100644 crates/core/src/bc_protocol/login.rs create mode 100644 crates/core/src/bc_protocol/logout.rs create mode 100644 crates/core/src/bc_protocol/ping.rs create mode 100644 crates/core/src/bc_protocol/stream.rs create mode 100644 crates/core/src/bc_protocol/version.rs diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 02de3ef..1ea49b4 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -1,8 +1,5 @@ use self::connection::BcConnection; -use self::media_packet::{MediaDataKind, MediaDataSubscriber}; use crate::bc; -use crate::bc::{model::*, xml::*}; -use err_derive::Error; use log::*; use std::convert::TryInto; use std::net::ToSocketAddrs; @@ -12,74 +9,22 @@ use std::time::Duration; use Md5Trunc::*; mod connection; +mod errors; +mod login; +mod logout; mod media_packet; +mod ping; +mod stream; mod time; +mod version; -use crate::Never; +pub use errors::Error; +pub use stream::{StreamFormat, StreamOutput, StreamOutputError}; type Result = std::result::Result; const RX_TIMEOUT: Duration = Duration::from_secs(5); -/// This is the primary error type of the library -#[derive(Debug, Error)] -#[allow(clippy::large_enum_variant)] -pub enum Error { - /// Error raised when IO fails such as when the connection is lost - #[error(display = "Communication error")] - Communication(#[error(source)] std::io::Error), - - /// Errors raised during deserlization - #[error(display = "Deserialization error")] - Deserialization(#[error(source)] bc::de::Error), - - /// Errors raised during serlization - #[error(display = "Serialization error")] - Serialization(#[error(source)] bc::ser::Error), - - /// A connection error such as Simultaneous subscription - #[error(display = "Connection error")] - ConnectionError(#[error(source)] self::connection::Error), - - /// Raised when a Bc reply was not understood - #[error(display = "Communication error")] - UnintelligibleReply { - /// The Bc packet that was not understood - reply: Bc, - /// The message attached to the error - why: &'static str, - }, - - /// Raised when a connection is dropped. This can be for many reasons - /// and is usually not helpful - #[error(display = "Dropped connection")] - DroppedConnection(#[error(source)] std::sync::mpsc::RecvError), - - /// Raised when the RX_TIMEOUT is reach - #[error(display = "Timeout")] - Timeout, - - /// Raised when connection is dropped because the RX_TIMEOUT is reach - #[error(display = "Dropped connection")] - TimeoutDisconnected, - - /// Raised when failed to login to the camera - #[error(display = "Credential error")] - AuthFailed, - - /// Raised when the given camera url could not be resolved - #[error(display = "Failed to translate camera address")] - AddrResolutionError, - - /// A generic catch all error - #[error(display = "Other error")] - Other(&'static str), - - /// A generic catch all error - #[error(display = "Other error")] - OtherString(String), -} - impl<'a> From for Error { fn from(k: std::sync::mpsc::RecvTimeoutError) -> Self { match k { @@ -99,31 +44,6 @@ pub struct BcCamera { message_num: AtomicU16, } -/// The stream from the camera will be using one of these formats -#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] -pub enum StreamFormat { - /// H264 (AVC) video format - H264, - /// H265 (HEVC) video format - H265, - /// AAC audio - AAC, - /// ADPCM in DVI-4 format - ADPCM, -} - -/// Convience type for the error raised by the StreamOutput trait -pub type StreamOutputError = Result<()>; - -/// The method `start_stream` requires a structure with this trait to pass the -/// audio and video data back to -pub trait StreamOutput { - /// This is the callback raised when audio data is received - fn write_audio(&mut self, data: &[u8], format: StreamFormat) -> StreamOutputError; - /// This is the callback raised when video data is received - fn write_video(&mut self, data: &[u8], format: StreamFormat) -> StreamOutputError; -} - impl Drop for BcCamera { fn drop(&mut self) { self.disconnect(); @@ -189,302 +109,6 @@ impl BcCamera { } self.connection = None; } - - /// Will try to login to the camera. - /// - /// This should be called before most other commands - pub fn login(&mut self, username: &str, password: Option<&str>) -> Result { - let connection = self - .connection - .as_ref() - .expect("Must be connected to log in"); - let sub_login = connection.subscribe(MSG_ID_LOGIN)?; - - // Login flow is: Send legacy login message, expect back a modern message with Encryption - // details. Then, re-send the login as a modern login message. Expect back a device info - // congratulating us on logging in. - - // In the legacy scheme, username/password are MD5'd if they are encrypted (which they need - // to be to "upgrade" to the modern login flow), then the hex of the MD5 is sent. - // Note: I suspect there may be a buffer overflow opportunity in the firmware since in the - // Baichuan library, these strings are capped at 32 bytes with a null terminator. This - // could also be a mistake in the library, the effect being it only compares 31 chars, not 32. - let md5_username = md5_string(username, ZeroLast); - let md5_password = password - .map(|p| md5_string(p, ZeroLast)) - .unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned()); - - let legacy_login = Bc { - meta: BcMeta { - msg_id: MSG_ID_LOGIN, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0xdc03, - class: 0x6514, - }, - body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { - username: md5_username, - password: md5_password, - }), - }; - - sub_login.send(legacy_login)?; - - let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; - - let nonce; - match legacy_reply.body { - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - encryption: Some(encryption), - .. - })), - .. - }) => { - nonce = encryption.nonce; - } - _ => { - return Err(Error::UnintelligibleReply { - reply: legacy_reply, - why: "Expected an Encryption message back", - }) - } - } - - // In the modern login flow, the username/password are concat'd with the server's nonce - // string, then MD5'd, then the hex of this MD5 is sent as the password. This nonce - // prevents replay attacks if the server were to require modern flow, but not rainbow table - // attacks (since the plain user/password MD5s have already been sent). The upshot is that - // you should use a very strong random password that is not found in a rainbow table and - // not feasibly crackable with John the Ripper. - - let modern_password = password.unwrap_or(""); - let concat_username = format!("{}{}", username, nonce); - let concat_password = format!("{}{}", modern_password, nonce); - let md5_username = md5_string(&concat_username, Truncate); - let md5_password = md5_string(&concat_password, Truncate); - - let modern_login = Bc::new_from_xml( - BcMeta { - msg_id: MSG_ID_LOGIN, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, - }, - BcXml { - login_user: Some(LoginUser { - version: xml_ver(), - user_name: md5_username, - password: md5_password, - user_ver: 1, - }), - login_net: Some(LoginNet::default()), - ..Default::default() - }, - ); - - sub_login.send(modern_login)?; - let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; - - let device_info; - match modern_reply.body { - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - device_info: Some(info), - .. - })), - .. - }) => { - // Login succeeded! - self.logged_in = true; - device_info = info; - } - BcBody::ModernMsg(ModernMsg { - extension: None, - payload: None, - }) => return Err(Error::AuthFailed), - _ => { - return Err(Error::UnintelligibleReply { - reply: modern_reply, - why: "Expected a DeviceInfo message back from login", - }) - } - } - - if let EncryptionProtocol::Aes(_) = connection.get_encrypted() { - // We setup the data for the AES key now - // as all subsequent communications will use it - let passwd = password.unwrap_or(""); - let full_key = make_aes_key(&nonce, passwd); - connection.set_encrypted(EncryptionProtocol::Aes(Some(full_key))); - } - - Ok(device_info) - } - - /// Will logout from the camera - pub fn logout(&mut self) -> Result<()> { - if self.logged_in { - // TODO: Send message ID 2 - } - self.logged_in = false; - Ok(()) - } - - /// Request the VersionInfo xml - pub fn version(&self) -> Result { - let connection = self - .connection - .as_ref() - .expect("Must be connected to get version info"); - let sub_version = connection.subscribe(MSG_ID_VERSION)?; - - let version = Bc { - meta: BcMeta { - msg_id: MSG_ID_VERSION, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, // IDK why - }, - body: BcBody::ModernMsg(ModernMsg { - ..Default::default() - }), - }; - - sub_version.send(version)?; - - let modern_reply = sub_version.rx.recv_timeout(RX_TIMEOUT)?; - let version_info; - match modern_reply.body { - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - version_info: Some(info), - .. - })), - .. - }) => { - version_info = info; - } - _ => { - return Err(Error::UnintelligibleReply { - reply: modern_reply, - why: "Expected a VersionInfo message", - }) - } - } - - Ok(version_info) - } - - /// Ping the camera will either return Ok(()) which means a sucess reply - /// or error - pub fn ping(&self) -> Result<()> { - let connection = self.connection.as_ref().expect("Must be connected to ping"); - let sub_ping = connection.subscribe(MSG_ID_PING)?; - - let ping = Bc { - meta: BcMeta { - msg_id: MSG_ID_PING, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, - }, - body: BcBody::ModernMsg(ModernMsg { - ..Default::default() - }), - }; - - sub_ping.send(ping)?; - - sub_ping.rx.recv_timeout(RX_TIMEOUT)?; - - Ok(()) - } - - /// - /// Starts the video stream - /// - /// # Parameters - /// - /// * `data_outs` - This should be a struct that implements the `StreamOutput` trait - /// - /// * `stream_name` - The name of the stream either `"mainStream"` for HD or `"subStream"` for SD - /// - /// # Returns - /// - /// This will block forever or return an error when the camera connection is dropped - /// - pub fn start_video(&self, data_outs: &mut Outputs, stream_name: &str) -> Result - where - Outputs: StreamOutput, - { - let connection = self - .connection - .as_ref() - .expect("Must be connected to start video"); - let sub_video = connection.subscribe(MSG_ID_VIDEO)?; - - let stream_num = match stream_name { - "mainStream" => 0, - "subStream" => 1, - _ => 0, - }; - - let start_video = Bc::new_from_xml( - BcMeta { - msg_id: MSG_ID_VIDEO, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: stream_num, - response_code: 0, - class: 0x6414, // IDK why - }, - BcXml { - preview: Some(Preview { - version: xml_ver(), - channel_id: self.channel_id, - handle: 0, - stream_type: stream_name.to_string(), - }), - ..Default::default() - }, - ); - - sub_video.send(start_video)?; - - let mut media_sub = MediaDataSubscriber::from_bc_sub(&sub_video); - - loop { - let binary_data = media_sub.next_media_packet()?; - // We now have a complete interesting packet. Send it to gst. - // Process the packet - match (binary_data.kind(), binary_data.media_format()) { - ( - MediaDataKind::VideoDataIframe | MediaDataKind::VideoDataPframe, - Some(media_format), - ) => { - data_outs.write_video(binary_data.body(), media_format)?; - } - (MediaDataKind::AudioDataAac, Some(media_format)) => { - data_outs.write_audio(binary_data.body(), media_format)?; - } - (MediaDataKind::AudioDataAdpcm, Some(media_format)) => { - data_outs.write_audio(binary_data.body(), media_format)?; - } - _ => {} - }; - } - } } /// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I diff --git a/crates/core/src/bc_protocol/errors.rs b/crates/core/src/bc_protocol/errors.rs new file mode 100644 index 0000000..3eb3434 --- /dev/null +++ b/crates/core/src/bc_protocol/errors.rs @@ -0,0 +1,61 @@ +use super::bc::model::Bc; +use err_derive::Error; + +/// This is the primary error type of the library +#[derive(Debug, Error)] +#[allow(clippy::large_enum_variant)] +pub enum Error { + /// Error raised when IO fails such as when the connection is lost + #[error(display = "Communication error")] + Communication(#[error(source)] std::io::Error), + + /// Errors raised during deserlization + #[error(display = "Deserialization error")] + Deserialization(#[error(source)] super::bc::de::Error), + + /// Errors raised during serlization + #[error(display = "Serialization error")] + Serialization(#[error(source)] super::bc::ser::Error), + + /// A connection error such as Simultaneous subscription + #[error(display = "Connection error")] + ConnectionError(#[error(source)] super::connection::Error), + + /// Raised when a Bc reply was not understood + #[error(display = "Communication error")] + UnintelligibleReply { + /// The Bc packet that was not understood + reply: Bc, + /// The message attached to the error + why: &'static str, + }, + + /// Raised when a connection is dropped. This can be for many reasons + /// and is usually not helpful + #[error(display = "Dropped connection")] + DroppedConnection(#[error(source)] std::sync::mpsc::RecvError), + + /// Raised when the RX_TIMEOUT is reach + #[error(display = "Timeout")] + Timeout, + + /// Raised when connection is dropped because the RX_TIMEOUT is reach + #[error(display = "Dropped connection")] + TimeoutDisconnected, + + /// Raised when failed to login to the camera + #[error(display = "Credential error")] + AuthFailed, + + /// Raised when the given camera url could not be resolved + #[error(display = "Failed to translate camera address")] + AddrResolutionError, + + /// A generic catch all error + #[error(display = "Other error")] + Other(&'static str), + + /// A generic catch all error + #[error(display = "Other error")] + OtherString(String), +} diff --git a/crates/core/src/bc_protocol/login.rs b/crates/core/src/bc_protocol/login.rs new file mode 100644 index 0000000..b6ff9dc --- /dev/null +++ b/crates/core/src/bc_protocol/login.rs @@ -0,0 +1,141 @@ +use super::{make_aes_key, md5_string, BcCamera, Error, Result, Truncate, ZeroLast, RX_TIMEOUT}; +use crate::bc::{model::*, xml::*}; + +impl BcCamera { + /// Will try to login to the camera. + /// + /// This should be called before most other commands + pub fn login(&mut self, username: &str, password: Option<&str>) -> Result { + let connection = self + .connection + .as_ref() + .expect("Must be connected to log in"); + let sub_login = connection.subscribe(MSG_ID_LOGIN)?; + + // Login flow is: Send legacy login message, expect back a modern message with Encryption + // details. Then, re-send the login as a modern login message. Expect back a device info + // congratulating us on logging in. + + // In the legacy scheme, username/password are MD5'd if they are encrypted (which they need + // to be to "upgrade" to the modern login flow), then the hex of the MD5 is sent. + // Note: I suspect there may be a buffer overflow opportunity in the firmware since in the + // Baichuan library, these strings are capped at 32 bytes with a null terminator. This + // could also be a mistake in the library, the effect being it only compares 31 chars, not 32. + let md5_username = md5_string(username, ZeroLast); + let md5_password = password + .map(|p| md5_string(p, ZeroLast)) + .unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned()); + + let legacy_login = Bc { + meta: BcMeta { + msg_id: MSG_ID_LOGIN, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0xdc03, + class: 0x6514, + }, + body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { + username: md5_username, + password: md5_password, + }), + }; + + sub_login.send(legacy_login)?; + + let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; + + let nonce; + match legacy_reply.body { + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + encryption: Some(encryption), + .. + })), + .. + }) => { + nonce = encryption.nonce; + } + _ => { + return Err(Error::UnintelligibleReply { + reply: legacy_reply, + why: "Expected an Encryption message back", + }) + } + } + + // In the modern login flow, the username/password are concat'd with the server's nonce + // string, then MD5'd, then the hex of this MD5 is sent as the password. This nonce + // prevents replay attacks if the server were to require modern flow, but not rainbow table + // attacks (since the plain user/password MD5s have already been sent). The upshot is that + // you should use a very strong random password that is not found in a rainbow table and + // not feasibly crackable with John the Ripper. + + let modern_password = password.unwrap_or(""); + let concat_username = format!("{}{}", username, nonce); + let concat_password = format!("{}{}", modern_password, nonce); + let md5_username = md5_string(&concat_username, Truncate); + let md5_password = md5_string(&concat_password, Truncate); + + let modern_login = Bc::new_from_xml( + BcMeta { + msg_id: MSG_ID_LOGIN, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + BcXml { + login_user: Some(LoginUser { + version: xml_ver(), + user_name: md5_username, + password: md5_password, + user_ver: 1, + }), + login_net: Some(LoginNet::default()), + ..Default::default() + }, + ); + + sub_login.send(modern_login)?; + let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; + + let device_info; + match modern_reply.body { + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + device_info: Some(info), + .. + })), + .. + }) => { + // Login succeeded! + self.logged_in = true; + device_info = info; + } + BcBody::ModernMsg(ModernMsg { + extension: None, + payload: None, + }) => return Err(Error::AuthFailed), + _ => { + return Err(Error::UnintelligibleReply { + reply: modern_reply, + why: "Expected a DeviceInfo message back from login", + }) + } + } + + if let EncryptionProtocol::Aes(_) = connection.get_encrypted() { + // We setup the data for the AES key now + // as all subsequent communications will use it + let passwd = password.unwrap_or(""); + let full_key = make_aes_key(&nonce, passwd); + connection.set_encrypted(EncryptionProtocol::Aes(Some(full_key))); + } + + Ok(device_info) + } +} diff --git a/crates/core/src/bc_protocol/logout.rs b/crates/core/src/bc_protocol/logout.rs new file mode 100644 index 0000000..f963a23 --- /dev/null +++ b/crates/core/src/bc_protocol/logout.rs @@ -0,0 +1,12 @@ +use super::{BcCamera, Result}; + +impl BcCamera { + /// Logout from the camera + pub fn logout(&mut self) -> Result<()> { + if self.logged_in { + // TODO: Send message ID 2 + } + self.logged_in = false; + Ok(()) + } +} diff --git a/crates/core/src/bc_protocol/ping.rs b/crates/core/src/bc_protocol/ping.rs new file mode 100644 index 0000000..0c63b0e --- /dev/null +++ b/crates/core/src/bc_protocol/ping.rs @@ -0,0 +1,31 @@ +use super::{BcCamera, Result, RX_TIMEOUT}; +use crate::bc::model::*; + +impl BcCamera { + /// Ping the camera will either return Ok(()) which means a sucess reply + /// or error + pub fn ping(&self) -> Result<()> { + let connection = self.connection.as_ref().expect("Must be connected to ping"); + let sub_ping = connection.subscribe(MSG_ID_PING)?; + + let ping = Bc { + meta: BcMeta { + msg_id: MSG_ID_PING, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; + + sub_ping.send(ping)?; + + sub_ping.rx.recv_timeout(RX_TIMEOUT)?; + + Ok(()) + } +} diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs new file mode 100644 index 0000000..94d70c5 --- /dev/null +++ b/crates/core/src/bc_protocol/stream.rs @@ -0,0 +1,110 @@ +use super::{ + media_packet::{MediaDataKind, MediaDataSubscriber}, + BcCamera, Result, +}; +use crate::{ + bc::{model::*, xml::*}, + Never, +}; + +/// The stream from the camera will be using one of these formats +#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] +pub enum StreamFormat { + /// H264 (AVC) video format + H264, + /// H265 (HEVC) video format + H265, + /// AAC audio + AAC, + /// ADPCM in DVI-4 format + ADPCM, +} + +/// Convience type for the error raised by the StreamOutput trait +pub type StreamOutputError = Result<()>; + +/// The method `start_stream` requires a structure with this trait to pass the +/// audio and video data back to +pub trait StreamOutput { + /// This is the callback raised when audio data is received + fn write_audio(&mut self, data: &[u8], format: StreamFormat) -> StreamOutputError; + /// This is the callback raised when video data is received + fn write_video(&mut self, data: &[u8], format: StreamFormat) -> StreamOutputError; +} + +impl BcCamera { + /// + /// Starts the video stream + /// + /// # Parameters + /// + /// * `data_outs` - This should be a struct that implements the `StreamOutput` trait + /// + /// * `stream_name` - The name of the stream either `"mainStream"` for HD or `"subStream"` for SD + /// + /// # Returns + /// + /// This will block forever or return an error when the camera connection is dropped + /// + pub fn start_video(&self, data_outs: &mut Outputs, stream_name: &str) -> Result + where + Outputs: StreamOutput, + { + let connection = self + .connection + .as_ref() + .expect("Must be connected to start video"); + let sub_video = connection.subscribe(MSG_ID_VIDEO)?; + + let stream_num = match stream_name { + "mainStream" => 0, + "subStream" => 1, + _ => 0, + }; + + let start_video = Bc::new_from_xml( + BcMeta { + msg_id: MSG_ID_VIDEO, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: stream_num, + response_code: 0, + class: 0x6414, // IDK why + }, + BcXml { + preview: Some(Preview { + version: xml_ver(), + channel_id: self.channel_id, + handle: 0, + stream_type: stream_name.to_string(), + }), + ..Default::default() + }, + ); + + sub_video.send(start_video)?; + + let mut media_sub = MediaDataSubscriber::from_bc_sub(&sub_video); + + loop { + let binary_data = media_sub.next_media_packet()?; + // We now have a complete interesting packet. Send it to gst. + // Process the packet + match (binary_data.kind(), binary_data.media_format()) { + ( + MediaDataKind::VideoDataIframe | MediaDataKind::VideoDataPframe, + Some(media_format), + ) => { + data_outs.write_video(binary_data.body(), media_format)?; + } + (MediaDataKind::AudioDataAac, Some(media_format)) => { + data_outs.write_audio(binary_data.body(), media_format)?; + } + (MediaDataKind::AudioDataAdpcm, Some(media_format)) => { + data_outs.write_audio(binary_data.body(), media_format)?; + } + _ => {} + }; + } + } +} diff --git a/crates/core/src/bc_protocol/version.rs b/crates/core/src/bc_protocol/version.rs new file mode 100644 index 0000000..870e61e --- /dev/null +++ b/crates/core/src/bc_protocol/version.rs @@ -0,0 +1,52 @@ +use super::{BcCamera, Error, Result, RX_TIMEOUT}; +use crate::bc::{model::*, xml::*}; + +impl BcCamera { + /// Request the VersionInfo xml + pub fn version(&self) -> Result { + let connection = self + .connection + .as_ref() + .expect("Must be connected to get version info"); + let sub_version = connection.subscribe(MSG_ID_VERSION)?; + + let version = Bc { + meta: BcMeta { + msg_id: MSG_ID_VERSION, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, // IDK why + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; + + sub_version.send(version)?; + + let modern_reply = sub_version.rx.recv_timeout(RX_TIMEOUT)?; + let version_info; + match modern_reply.body { + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + version_info: Some(info), + .. + })), + .. + }) => { + version_info = info; + } + _ => { + return Err(Error::UnintelligibleReply { + reply: modern_reply, + why: "Expected a VersionInfo message", + }) + } + } + + Ok(version_info) + } +}