diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index a8ff8c2..05dffd4 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -198,13 +198,14 @@ fn bc_modern_msg<'a>( .unwrap_or("Not Text".to_string()) ); } - let xml = BcXml::try_parse(processed_payload_buf.as_slice()).map_err(|_| { + let xml = BcXml::try_parse(processed_payload_buf.as_slice()).map_err(|e| { error!("header.msg_id: {}", header.msg_id); error!( "processed_payload_buf: {:X?}::{:?}", processed_payload_buf, std::str::from_utf8(&processed_payload_buf) ); + log::error!("e: {:?}", e); Err::Error(make_error( buf, "Unable to parse Payload XML", @@ -258,9 +259,18 @@ mod tests { use super::*; use crate::bc::xml::*; use assert_matches::assert_matches; + use env_logger::Env; + + fn init() { + let _ = env_logger::Builder::from_env(Env::default().default_filter_or("info")) + .is_test(true) + .try_init(); + } #[test] fn test_bc_modern_login() { + init(); + let sample = include_bytes!("samples/model_sample_modern_login.bin"); let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt); @@ -289,45 +299,39 @@ mod tests { #[test] // This is an 0xdd03 encryption from an Argus 2 - // - // It is currently unsupported fn test_03_enc_login() { + init(); + let sample = include_bytes!("samples/battery_enc.bin"); let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt); let (buf, header) = bc_header(&sample[..]).unwrap(); - assert!(bc_body(&context, &header, buf).is_err()); - // It should error because we don't support it - // - // The following would be its contents if we - // did support it (maybe one day :) left it here - // for then) - // - // - // let (_, body) = bc_body(&mut context, &header, buf).unwrap(); - // assert_eq!(header.msg_id, 1); - // assert_eq!(header.body_len, 175); - // assert_eq!(header.channel_id, 0); - // assert_eq!(header.stream_type, 0); - // assert_eq!(header.payload_offset, None); - // assert_eq!(header.response_code, 0xdd03); - // assert_eq!(header.class, 0x6614); - // match body { - // BcBody::ModernMsg(ModernMsg { - // payload: - // Some(BcPayloads::BcXml(BcXml { - // encryption: Some(encryption), - // .. - // })), - // .. - // }) => assert_eq!(encryption.nonce, "0-AhnEZyUg6eKrJFIWgXPF"), - // _ => panic!(), - // } + let (_, body) = bc_body(&context, &header, buf).unwrap(); + assert_eq!(header.msg_id, 1); + assert_eq!(header.body_len, 175); + assert_eq!(header.channel_id, 0); + assert_eq!(header.stream_type, 0); + assert_eq!(header.payload_offset, None); + assert_eq!(header.response_code, 0xdd03); + assert_eq!(header.class, 0x6614); + match body { + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + encryption: Some(encryption), + .. + })), + .. + }) => assert_eq!(encryption.nonce, "0-AhnEZyUg6eKrJFIWgXPF"), + _ => panic!(), + } } #[test] fn test_bc_legacy_login() { + init(); + let sample = include_bytes!("samples/model_sample_legacy_login.bin"); let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt); @@ -352,6 +356,8 @@ mod tests { #[test] fn test_bc_modern_login_failed() { + init(); + let sample = include_bytes!("samples/modern_login_failed.bin"); let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt); @@ -376,6 +382,8 @@ mod tests { #[test] fn test_bc_modern_login_success() { + init(); + let sample = include_bytes!("samples/modern_login_success.bin"); let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt); @@ -403,6 +411,8 @@ mod tests { #[test] fn test_bc_binary_mode() { + init(); + let sample1 = include_bytes!("samples/modern_video_start1.bin"); let sample2 = include_bytes!("samples/modern_video_start2.bin"); @@ -442,6 +452,8 @@ mod tests { // // They also have extra streams fn test_bc_b800_externstream() { + init(); + let sample = include_bytes!("samples/xml_externstream_b800.bin"); let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt); @@ -484,6 +496,8 @@ mod tests { // // They also have extra streams fn test_bc_b800_substream() { + init(); + let sample = include_bytes!("samples/xml_substream_b800.bin"); let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt); @@ -526,6 +540,8 @@ mod tests { // // They also have extra streams fn test_bc_b800_mainstream() { + init(); + let sample = include_bytes!("samples/xml_mainstream_b800.bin"); let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt); diff --git a/crates/core/src/bc/ser.rs b/crates/core/src/bc/ser.rs index 5b5b24c..56c99db 100644 --- a/crates/core/src/bc/ser.rs +++ b/crates/core/src/bc/ser.rs @@ -78,7 +78,7 @@ fn bc_ext( xml: &Extension, encryption_protocol: &EncryptionProtocol, ) -> impl SerializeFn { - let xml_bytes = xml.serialize(bytes::BytesMut::new()).unwrap(); + let xml_bytes = xml.serialize(vec![]).unwrap(); let enc_bytes = xml_crypto::encrypt(enc_offset, &xml_bytes, encryption_protocol); slice(enc_bytes) } @@ -90,7 +90,11 @@ fn bc_payload( ) -> impl SerializeFn { let payload_bytes = match payload { BcPayloads::BcXml(x) => { - let xml_bytes = x.serialize(bytes::BytesMut::new()).unwrap(); + let xml_bytes = x.serialize(vec![]).unwrap(); + // log::debug!( + // "Seialised as: {:?}", + // std::str::from_utf8(xml_bytes.as_ref()) + // ); xml_crypto::encrypt(enc_offset, &xml_bytes, encryption_protocol) } BcPayloads::Binary(x) => x.to_owned(), diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index 4c214ad..8ff82ed 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -1,7 +1,7 @@ #![allow(non_snake_case)] use serde::{Deserialize, Serialize}; -use std::{fmt::Write, io::BufRead}; +use std::{io::BufRead, io::Write}; #[cfg(test)] use indoc::indoc; @@ -19,96 +19,100 @@ pub enum BcPayloads { /// The top level BC Xml #[derive(PartialEq, Default, Debug, Deserialize, Serialize)] +#[serde(rename = "body")] pub struct BcXml { /// Encryption xml is received during login and contain the NONCE - #[serde(rename = "Encryption")] + #[serde(rename = "Encryption", skip_serializing_if = "Option::is_none")] pub encryption: Option, /// LoginUser xml is used during modern login - #[serde(rename = "LoginUser")] + #[serde(rename = "LoginUser", skip_serializing_if = "Option::is_none")] pub login_user: Option, /// LoginNet xml is used during modern login - #[serde(rename = "LoginNet")] + #[serde(rename = "LoginNet", skip_serializing_if = "Option::is_none")] pub login_net: Option, /// The final part of a login sequence will return DeviceInfo xml - #[serde(rename = "DeviceInfo")] + #[serde(rename = "DeviceInfo", skip_serializing_if = "Option::is_none")] pub device_info: Option, /// The VersionInfo xml is recieved in reply to a version request - #[serde(rename = "VersionInfo")] + #[serde(rename = "VersionInfo", skip_serializing_if = "Option::is_none")] pub version_info: Option, /// Preview xml is used as part of the stream request to set the stream quality and channel - #[serde(rename = "Preview")] + #[serde(rename = "Preview", skip_serializing_if = "Option::is_none")] pub preview: Option, - #[serde(rename = "SystemGeneral")] + #[serde(rename = "SystemGeneral", skip_serializing_if = "Option::is_none")] /// SystemGeneral xml is sent or recieved as part of the clock get/setting pub system_general: Option, /// Received as part of the Genral system info request - #[serde(rename = "Norm")] + #[serde(rename = "Norm", skip_serializing_if = "Option::is_none")] pub norm: Option, /// Received as part of the LEDState info request - #[serde(rename = "LedState")] + #[serde(rename = "LedState", skip_serializing_if = "Option::is_none")] pub led_state: Option, /// Sent as part of the TalkConfig to prepare the camera for audio talk-back - #[serde(rename = "TalkConfig")] + #[serde(rename = "TalkConfig", skip_serializing_if = "Option::is_none")] pub talk_config: Option, /// rfAlarmCfg xml is sent or recieved as part of the PIR get/setting - #[serde(rename = "rfAlarmCfg")] + #[serde(rename = "rfAlarmCfg", skip_serializing_if = "Option::is_none")] pub rf_alarm_cfg: Option, /// Revieced as part of the TalkAbility request - #[serde(rename = "TalkAbility")] + #[serde(rename = "TalkAbility", skip_serializing_if = "Option::is_none")] pub talk_ability: Option, /// Received when motion is detected - #[serde(rename = "AlarmEventList")] + #[serde(rename = "AlarmEventList", skip_serializing_if = "Option::is_none")] pub alarm_event_list: Option, /// Sent to move the camera - #[serde(rename = "PtzControl")] + #[serde(rename = "PtzControl", skip_serializing_if = "Option::is_none")] pub ptz_control: Option, /// Sent to manually control the floodlight - #[serde(rename = "FloodlightManual")] + #[serde(rename = "FloodlightManual", skip_serializing_if = "Option::is_none")] pub floodlight_manual: Option, /// Received when the floodlight status is updated - #[serde(rename = "FloodlightStatusList")] + #[serde( + rename = "FloodlightStatusList", + skip_serializing_if = "Option::is_none" + )] pub floodlight_status_list: Option, /// Sent or received for the PTZ preset functionality - #[serde(rename = "PtzPreset")] + #[serde(rename = "PtzPreset", skip_serializing_if = "Option::is_none")] pub ptz_preset: Option, /// Recieved on login/low battery events - #[serde(rename = "BatteryList")] + #[serde(rename = "BatteryList", skip_serializing_if = "Option::is_none")] pub battery_list: Option, /// Recieved on request for battery info - #[serde(rename = "BatteryInfo")] + #[serde(rename = "BatteryInfo", skip_serializing_if = "Option::is_none")] pub battery_info: Option, /// Recieved on request for a users persmissions/capabilitoes - #[serde(rename = "AbilityInfo")] + #[serde(rename = "AbilityInfo", skip_serializing_if = "Option::is_none")] pub ability_info: Option, /// Recieved on request for a users persmissions/capabilitoes - #[serde(rename = "PushInfo")] + #[serde(rename = "PushInfo", skip_serializing_if = "Option::is_none")] pub push_info: Option, /// Recieved on request for a link type - #[serde(rename = "LinkType")] + #[serde(rename = "LinkType", skip_serializing_if = "Option::is_none")] pub link_type: Option, /// Recieved AND send for the snap message - #[serde(rename = "Snap")] + #[serde(rename = "Snap", skip_serializing_if = "Option::is_none")] pub snap: Option, /// The list of streams and their configuration - #[serde(rename = "StreamInfoList")] + #[serde(rename = "StreamInfoList", skip_serializing_if = "Option::is_none")] pub stream_info_list: Option, /// Thre list of streams and their configuration - #[serde(rename = "Uid")] + #[serde(rename = "Uid", skip_serializing_if = "Option::is_none")] pub uid: Option, /// The floodlight settings for automatically turning on/off on schedule/motion - #[serde(rename = "FloodlightTask")] + #[serde(rename = "FloodlightTask", skip_serializing_if = "Option::is_none")] pub floodlight_task: Option, /// For geting the zoom anf focus of the camera - #[serde(rename = "PtzZoomFocus")] + #[serde(rename = "PtzZoomFocus", skip_serializing_if = "Option::is_none")] pub ptz_zoom_focus: Option, /// For zooming the camera - #[serde(rename = "StartZoomFocus")] + #[serde(rename = "StartZoomFocus", skip_serializing_if = "Option::is_none")] pub start_zoom_focus: Option, /// Get the support xml - #[serde(rename = "Support")] + #[serde(rename = "Support", skip_serializing_if = "Option::is_none")] pub support: Option, /// Play a sound - #[serde(rename = "audioPlayInfo")] + #[serde(rename = "audioPlayInfo", skip_serializing_if = "Option::is_none")] pub audio_play_info: Option, } @@ -117,7 +121,13 @@ impl BcXml { quick_xml::de::from_reader(s) } pub(crate) fn serialize(&self, mut w: W) -> Result { - quick_xml::se::to_writer(&mut w, self)?; + let mut writer = quick_xml::writer::Writer::new(&mut w); + writer + .write_event(quick_xml::events::Event::Decl( + quick_xml::events::BytesDecl::new("1.0", Some("UTF-8"), None), + )) + .expect("Should be aboe to serialise a basic xml declation"); + writer.write_serializable("body", &self)?; Ok(w) } } @@ -126,8 +136,14 @@ impl Extension { pub(crate) fn try_parse(s: impl BufRead) -> Result { quick_xml::de::from_reader(s) } - pub(crate) fn serialize(&self, mut w: W) -> Result { - quick_xml::se::to_writer(&mut w, self)?; + pub(crate) fn serialize(&self, mut w: W) -> Result { + let mut writer = quick_xml::writer::Writer::new(&mut w); + writer.write_event(quick_xml::events::Event::Decl( + quick_xml::events::BytesDecl::new("1.0", Some("UTF-8"), None), + ))?; + writer + .write_serializable("body", &self) + .expect("Should be serialisable"); Ok(w) } } @@ -190,6 +206,9 @@ impl Default for LoginNet { /// There is more to this xml but we don't deserialize it all #[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)] pub struct DeviceInfo { + /// Version of device info + #[serde(rename = "@version")] + pub version: Option, /// The resolution xml block pub resolution: Resolution, } @@ -200,7 +219,7 @@ pub struct VersionInfo { /// Name assigned to the camera pub name: String, /// Model Name - #[serde(rename = "type")] + #[serde(rename = "type", skip_serializing_if = "Option::is_none")] pub model: Option, /// Camera's serial number pub serialNumber: String, @@ -244,7 +263,7 @@ pub struct Preview { /// Handle usually 0 for mainStream and 1 for subStream pub handle: u32, /// Either `"mainStream"` or `"subStream"` - #[serde(rename = "streamType")] + #[serde(rename = "streamType", skip_serializing_if = "Option::is_none")] pub stream_type: Option, } @@ -257,31 +276,32 @@ pub struct Extension { #[serde(rename = "@version")] pub version: String, /// If the subsequent payload is binary this will be set to 1. Otherwise it is ommited - #[serde(rename = "binaryData")] + #[serde(rename = "binaryData", skip_serializing_if = "Option::is_none")] pub binary_data: Option, /// Certain requests such `AbilitySupport` require to know which user this /// ability support request is for (why camera dosen't know this based on who /// is logged in is unknown... Possible security hole) - #[serde(rename = "userName")] + #[serde(rename = "userName", skip_serializing_if = "Option::is_none")] pub user_name: Option, /// Certain requests such as `AbilitySupport` require details such as what type of /// abilities are you intested in. This is a comma seperated list such as /// `"system, network, alarm, record, video, image"` + #[serde(skip_serializing_if = "Option::is_none")] pub token: Option, /// The channel ID. This is usually `0` unless using an NVR - #[serde(rename = "channelId")] + #[serde(rename = "channelId", skip_serializing_if = "Option::is_none")] pub channel_id: Option, /// The rfID used in the PIR - #[serde(rename = "rfId")] + #[serde(rename = "rfId", skip_serializing_if = "Option::is_none")] pub rf_id: Option, /// Encrypted binary has this to verify successful decryption - #[serde(rename = "checkPos")] + #[serde(rename = "checkPos", skip_serializing_if = "Option::is_none")] pub check_pos: Option, /// Encrypted binary has this to verify successful decryption - #[serde(rename = "checkValue")] + #[serde(rename = "checkValue", skip_serializing_if = "Option::is_none")] pub check_value: Option, /// Used in newer encrypted payload packets - #[serde(rename = "encryptLen")] + #[serde(rename = "encryptLen", skip_serializing_if = "Option::is_none")] pub encrypt_len: Option, } @@ -309,32 +329,39 @@ pub struct SystemGeneral { pub version: String, /// Time zone is negative seconds offset from UTC. So +7:00 is -25200 - #[serde(rename = "timeZone")] + #[serde(rename = "timeZone", skip_serializing_if = "Option::is_none")] pub time_zone: Option, /// Current year + #[serde(rename = "year", skip_serializing_if = "Option::is_none")] pub year: Option, /// Current month + #[serde(rename = "month", skip_serializing_if = "Option::is_none")] pub month: Option, /// Current day + #[serde(rename = "day", skip_serializing_if = "Option::is_none")] pub day: Option, /// Current hour + #[serde(skip_serializing_if = "Option::is_none")] pub hour: Option, /// Current minute + #[serde(skip_serializing_if = "Option::is_none")] pub minute: Option, /// Current second + #[serde(skip_serializing_if = "Option::is_none")] pub second: Option, /// Format to use for On Screen Display usually `"DMY"` - #[serde(rename = "osdFormat")] + #[serde(rename = "osdFormat", skip_serializing_if = "Option::is_none")] pub osd_format: Option, /// Unknown usually `0` - #[serde(rename = "timeFormat")] + #[serde(rename = "timeFormat", skip_serializing_if = "Option::is_none")] pub time_format: Option, /// Language e.g. `English` will set the language on the reolink app + #[serde(skip_serializing_if = "Option::is_none")] pub language: Option, /// Name assigned to the camera - #[serde(rename = "deviceName")] + #[serde(rename = "deviceName", skip_serializing_if = "Option::is_none")] pub device_name: Option, } @@ -358,7 +385,7 @@ pub struct LedState { #[serde(rename = "channelId")] pub channel_id: u8, /// LED Version, observed value is "2". Should be None when setting the LedState - #[serde(rename = "ledVersion")] + #[serde(rename = "ledVersion", skip_serializing_if = "Option::is_none")] pub led_version: Option, /// State of the IR LEDs values are "auto", "open", "close" pub state: String, @@ -495,6 +522,7 @@ pub struct TalkConfig { #[serde(rename = "audioConfig")] pub struct AudioConfig { /// Unknown only sent during TalkAbility request from the camera + #[serde(skip_serializing_if = "Option::is_none")] pub priority: Option, /// Audio type known values are `"adpcm"` /// @@ -580,7 +608,7 @@ pub struct AlarmEvent { /// Motion status. Known values are `"MD"` or `"none"` pub status: String, /// AI status. Known values are `"people"` or `"none"` - #[serde(rename = "AItype")] + #[serde(rename = "AItype", skip_serializing_if = "Option::is_none")] pub ai_type: Option, /// The recording status. Known values `0` or `1` pub recording: i32, @@ -632,6 +660,7 @@ pub struct Preset { /// The ID of the preset pub id: u8, /// The preset name + #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, /// Command: Known values: `"toPos"` and `"setPos"` pub command: String, @@ -685,26 +714,34 @@ pub struct AbilityInfo { #[serde(rename = "userName")] pub username: String, /// System permissions + #[serde(skip_serializing_if = "Option::is_none")] pub system: Option, /// Network permissions + #[serde(skip_serializing_if = "Option::is_none")] pub network: Option, /// Alarm permissions + #[serde(skip_serializing_if = "Option::is_none")] pub alarm: Option, /// Image permissions + #[serde(skip_serializing_if = "Option::is_none")] pub image: Option, /// Video permissions + #[serde(skip_serializing_if = "Option::is_none")] pub video: Option, /// Secutiry permissions + #[serde(skip_serializing_if = "Option::is_none")] pub security: Option, /// Replay permissions + #[serde(skip_serializing_if = "Option::is_none")] pub replay: Option, /// PTZ permissions - #[serde(rename = "PTZ")] + #[serde(rename = "PTZ", skip_serializing_if = "Option::is_none")] pub ptz: Option, /// IO permissions - #[serde(rename = "IO")] + #[serde(rename = "IO", skip_serializing_if = "Option::is_none")] pub io: Option, /// Streaming permissions + #[serde(skip_serializing_if = "Option::is_none")] pub streaming: Option, } @@ -721,7 +758,7 @@ pub struct AbilityInfoToken { #[serde(rename = "subModule")] pub struct AbilityInfoSubModule { /// The channel the for the camera usually 0 - #[serde(rename = "channelId")] + #[serde(rename = "channelId", skip_serializing_if = "Option::is_none")] pub channel_id: Option, /// The comma seperated list of permissions like this: `general_rw, norm_rw, version_ro` #[serde(rename = "abilityValue")] @@ -760,25 +797,25 @@ pub struct Snap { pub channel_id: u8, /// Unknown, observed values: 0 /// value is only set on request - #[serde(rename = "logicChannel")] + #[serde(rename = "logicChannel", skip_serializing_if = "Option::is_none")] pub logic_channel: Option, /// Time of snapshot, zero when requesting pub time: u32, /// Request a full frame, observed values: 0 /// value is only set on request - #[serde(rename = "fullFrame")] + #[serde(rename = "fullFrame", skip_serializing_if = "Option::is_none")] pub full_frame: Option, /// Stream name, observed values: `main`, `sub` /// value is only set on request - #[serde(rename = "streamType")] + #[serde(rename = "streamType", skip_serializing_if = "Option::is_none")] pub stream_type: Option, /// File name, usually of the form `01_20230518140240.jpg` /// value is only set on recieve - #[serde(rename = "fileName")] + #[serde(rename = "fileName", skip_serializing_if = "Option::is_none")] pub file_name: Option, /// Size in bytes of the picture /// value is only set on recieve - #[serde(rename = "pictureSize")] + #[serde(rename = "pictureSize", skip_serializing_if = "Option::is_none")] pub picture_size: Option, } @@ -817,10 +854,10 @@ pub struct EncodeTable { pub default_bitrate: u32, /// Table of valid framerates #[serde(rename = "framerateTable")] - pub framerate_table: Vec, + pub framerate_table: String, /// Table of valid bitrates #[serde(rename = "bitrateTable")] - pub bitrate_table: Vec, + pub bitrate_table: String, } /// The resolution of the stream @@ -865,8 +902,10 @@ pub struct FloodlightTask { /// Current brightness of floodlight (in %) pub brightness_cur: u32, /// Max brightness (in %) + #[serde(skip_serializing_if = "Option::is_none")] pub brightness_max: Option, /// Min brightness (in %) + #[serde(skip_serializing_if = "Option::is_none")] pub brightness_min: Option, /// Schedule fot auto floodlight pub schedule: Schedule, @@ -891,13 +930,13 @@ pub struct Schedule { #[serde(rename = "startHour")] pub start_hour: u32, /// startMin: Observed values 0 - #[serde(rename = "startMin")] + #[serde(rename = "startMin", skip_serializing_if = "Option::is_none")] pub start_min: Option, /// endHour #[serde(rename = "endHour")] pub end_hour: u32, /// endMin: Observed values 0 - #[serde(rename = "endMin")] + #[serde(rename = "endMin", skip_serializing_if = "Option::is_none")] pub end_min: Option, } @@ -905,8 +944,10 @@ pub struct Schedule { #[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)] pub struct LightSensThreshold { /// Min: Observed values 1000 + #[serde(skip_serializing_if = "Option::is_none")] pub min: Option, /// Max: OBserved values 2300 + #[serde(skip_serializing_if = "Option::is_none")] pub max: Option, /// Light Current Value: Observed Value 1000 #[serde(rename = "lightCur")] @@ -915,10 +956,10 @@ pub struct LightSensThreshold { #[serde(rename = "darkCur")] pub dark_cur: u32, /// Light Default: Observed Value 1000 - #[serde(rename = "lightDef")] + #[serde(rename = "lightDef", skip_serializing_if = "Option::is_none")] pub light_def: Option, /// Dark Default: Observed Value 1900 - #[serde(rename = "darkDef")] + #[serde(rename = "darkDef", skip_serializing_if = "Option::is_none")] pub dark_def: Option, } @@ -947,12 +988,15 @@ pub struct NightLongViewMultiBrightness { #[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)] pub struct AlarmBrightness { /// Min: Observed values 1 + #[serde(skip_serializing_if = "Option::is_none")] pub min: Option, /// Max: Observed values 100 + #[serde(skip_serializing_if = "Option::is_none")] pub max: Option, /// Current: Observed values 100 pub cur: u32, /// Default: Observed values 100 + #[serde(skip_serializing_if = "Option::is_none")] pub def: Option, } @@ -960,12 +1004,15 @@ pub struct AlarmBrightness { #[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)] pub struct AlarmDelay { /// Min: Observed values 5 + #[serde(skip_serializing_if = "Option::is_none")] pub min: Option, /// Max: Observed values 600 + #[serde(skip_serializing_if = "Option::is_none")] pub max: Option, /// Current: Observed values 10 pub cur: u32, /// Default: Observed values 10 + #[serde(skip_serializing_if = "Option::is_none")] pub def: Option, } @@ -1021,156 +1068,167 @@ pub struct Support { #[serde(rename = "@version")] pub version: String, /// IO port number (input) - #[serde(rename = "IOInputPortNum")] + #[serde(rename = "IOInputPortNum", skip_serializing_if = "Option::is_none")] pub io_input_port_num: Option, /// IO port number (output) - #[serde(rename = "IOOutputPortNum")] + #[serde(rename = "IOOutputPortNum", skip_serializing_if = "Option::is_none")] pub io_output_port_num: Option, #[serde(rename = "diskNum")] /// Number of disks + #[serde(skip_serializing_if = "Option::is_none")] pub disk_num: Option, /// Number of video channels - #[serde(rename = "channelNum")] + #[serde(rename = "channelNum", skip_serializing_if = "Option::is_none")] pub channel_num: Option, /// Number of audio channels - #[serde(rename = "audioNum")] + #[serde(rename = "audioNum", skip_serializing_if = "Option::is_none")] pub audio_num: Option, /// The supported PTZ Mode: pt - #[serde(rename = "ptzMode")] + #[serde(rename = "ptzMode", skip_serializing_if = "Option::is_none")] pub ptz_mode: Option, /// PTZ cfg: 0 - #[serde(rename = "ptzCfg")] + #[serde(rename = "ptzCfg", skip_serializing_if = "Option::is_none")] pub ptz_cfg: Option, /// Use b485 ptz - #[serde(rename = "")] + #[serde(rename = "b485", skip_serializing_if = "Option::is_none")] pub B485: Option, /// Support autoupdate - #[serde(rename = "autoUpdate")] + #[serde(rename = "autoUpdate", skip_serializing_if = "Option::is_none")] pub auto_update: Option, /// Support push notificaion alarms - #[serde(rename = "pushAlarm")] + #[serde(rename = "pushAlarm", skip_serializing_if = "Option::is_none")] pub push_alarm: Option, /// Support ftp + #[serde(skip_serializing_if = "Option::is_none")] pub ftp: Option, /// Support test for ftp - #[serde(rename = "ftpTest")] + #[serde(rename = "ftpTest", skip_serializing_if = "Option::is_none")] pub ftp_test: Option, /// Support email notification + #[serde(skip_serializing_if = "Option::is_none")] pub email: Option, /// Support wifi connections + #[serde(skip_serializing_if = "Option::is_none")] pub wifi: Option, /// Support recording + #[serde(skip_serializing_if = "Option::is_none")] pub record: Option, /// Support test for wifi - #[serde(rename = "wifiTest")] + #[serde(rename = "wifiTest", skip_serializing_if = "Option::is_none")] pub wifi_test: Option, /// Support rtsp + #[serde(skip_serializing_if = "Option::is_none")] pub rtsp: Option, /// Support onvif + #[serde(skip_serializing_if = "Option::is_none")] pub onvif: Option, /// Support audio talk - #[serde(rename = "audioTalk")] + #[serde(rename = "audioTalk", skip_serializing_if = "Option::is_none")] pub audio_talk: Option, /// RF version - #[serde(rename = "rfVersion")] + #[serde(rename = "rfVersion", skip_serializing_if = "Option::is_none")] pub rf_version: Option, /// Support rtmp + #[serde(skip_serializing_if = "Option::is_none")] pub rtmp: Option, /// Has external stream - #[serde(rename = "noExternStream")] + #[serde(rename = "noExternStream", skip_serializing_if = "Option::is_none")] pub no_extern_stream: Option, /// Time format - #[serde(rename = "timeFormat")] + #[serde(rename = "timeFormat", skip_serializing_if = "Option::is_none")] pub time_format: Option, /// DDNS version - #[serde(rename = "ddnsVersion")] + #[serde(rename = "ddnsVersion", skip_serializing_if = "Option::is_none")] pub ddns_version: Option, /// Email version - #[serde(rename = "emailVersion")] + #[serde(rename = "emailVersion", skip_serializing_if = "Option::is_none")] pub email_version: Option, /// Push notification version - #[serde(rename = "pushVersion")] + #[serde(rename = "pushVersion", skip_serializing_if = "Option::is_none")] pub push_version: Option, /// Push notification type: 1 - #[serde(rename = "pushType")] + #[serde(rename = "pushType", skip_serializing_if = "Option::is_none")] pub push_type: Option, /// Support audio alarm - #[serde(rename = "audioAlarm")] + #[serde(rename = "audioAlarm", skip_serializing_if = "Option::is_none")] pub audio_alarm: Option, /// Support AP - #[serde(rename = "apMode")] + #[serde(rename = "apMode", skip_serializing_if = "Option::is_none")] pub ap_mode: Option, /// Could version - #[serde(rename = "cloudVersion")] + #[serde(rename = "cloudVersion", skip_serializing_if = "Option::is_none")] pub cloud_version: Option, /// Replay version - #[serde(rename = "replayVersion")] + #[serde(rename = "replayVersion", skip_serializing_if = "Option::is_none")] pub replay_version: Option, /// mobComVersion - #[serde(rename = "mobComVersion")] + #[serde(rename = "mobComVersion", skip_serializing_if = "Option::is_none")] pub mob_com_version: Option, /// Export images - #[serde(rename = "ExportImport")] + #[serde(rename = "ExportImport", skip_serializing_if = "Option::is_none")] pub export_import: Option, /// Language version - #[serde(rename = "languageVer")] + #[serde(rename = "languageVer", skip_serializing_if = "Option::is_none")] pub language_ver: Option, /// Video standard - #[serde(rename = "videoStandard")] + #[serde(rename = "videoStandard", skip_serializing_if = "Option::is_none")] pub video_standard: Option, /// Support sync time - #[serde(rename = "syncTime")] + #[serde(rename = "syncTime", skip_serializing_if = "Option::is_none")] pub sync_time: Option, /// Support net port - #[serde(rename = "netPort")] + #[serde(rename = "netPort", skip_serializing_if = "Option::is_none")] pub net_port: Option, /// NAS version - #[serde(rename = "nasVersion")] + #[serde(rename = "nasVersion", skip_serializing_if = "Option::is_none")] pub nas_version: Option, /// Reboot required - #[serde(rename = "needReboot")] + #[serde(rename = "needReboot", skip_serializing_if = "Option::is_none")] pub need_reboot: Option, /// Support reboot + #[serde(skip_serializing_if = "Option::is_none")] pub reboot: Option, /// Support Audio config - #[serde(rename = "audioCfg")] + #[serde(rename = "audioCfg", skip_serializing_if = "Option::is_none")] pub audio_cfg: Option, /// Support network diagnosis - #[serde(rename = "networkDiagnosis")] + #[serde(rename = "networkDiagnosis", skip_serializing_if = "Option::is_none")] pub network_diagnosis: Option, /// Support height adjustment - #[serde(rename = "heightDiffAdjust")] + #[serde(rename = "heightDiffAdjust", skip_serializing_if = "Option::is_none")] pub height_diff_adjust: Option, /// Support upgrade + #[serde(skip_serializing_if = "Option::is_none")] pub upgrade: Option, /// Support GPS + #[serde(skip_serializing_if = "Option::is_none")] pub gps: Option, /// Support power save config - #[serde(rename = "powerSavingCfg")] + #[serde(rename = "powerSavingCfg", skip_serializing_if = "Option::is_none")] pub power_saving_cfg: Option, /// Login Locked - #[serde(rename = "loginLocked")] + #[serde(rename = "loginLocked", skip_serializing_if = "Option::is_none")] pub login_locked: Option, /// View plan - #[serde(rename = "viewPlan")] + #[serde(rename = "viewPlan", skip_serializing_if = "Option::is_none")] pub view_plan: Option, /// Preview replay limit - #[serde(rename = "previewReplayLimit")] + #[serde(rename = "previewReplayLimit", skip_serializing_if = "Option::is_none")] pub preview_replay_limit: Option, /// IOT link - #[serde(rename = "IOTLink")] + #[serde(rename = "IOTLink", skip_serializing_if = "Option::is_none")] pub iot_link: Option, /// IOT link maximum actions - #[serde(rename = "IOTLinkActionMax")] + #[serde(rename = "IOTLinkActionMax", skip_serializing_if = "Option::is_none")] pub iot_link_action_max: Option, /// Support record config - #[serde(rename = "recordCfg")] + #[serde(rename = "recordCfg", skip_serializing_if = "Option::is_none")] pub record_cfg: Option, /// Has large battery - #[serde(rename = "largeBattery")] + #[serde(rename = "largeBattery", skip_serializing_if = "Option::is_none")] pub large_battery: Option, /// Smart home config - #[serde(rename = "smartHome")] + #[serde(rename = "smartHome", skip_serializing_if = "Option::is_none")] pub smart_home: Option, /// Support config for specific channels #[serde(rename = "item")] @@ -1203,89 +1261,94 @@ pub struct SupportItem { #[serde(rename = "chnID")] pub chn_id: u32, /// PTZ type of the channel - #[serde(rename = "ptzType")] + #[serde(rename = "ptzType", skip_serializing_if = "Option::is_none")] pub ptz_type: Option, /// RF config - #[serde(rename = "rfCfg")] + #[serde(rename = "rfCfg", skip_serializing_if = "Option::is_none")] pub rf_cfg: Option, /// Support audio - #[serde(rename = "noAudio")] + #[serde(rename = "noAudio", skip_serializing_if = "Option::is_none")] pub no_audio: Option, /// Support auto focus - #[serde(rename = "autoFocus")] + #[serde(rename = "autoFocus", skip_serializing_if = "Option::is_none")] pub auto_focus: Option, /// Support video clip - #[serde(rename = "videoClip")] + #[serde(rename = "videoClip", skip_serializing_if = "Option::is_none")] pub video_clip: Option, /// Has battery + #[serde(skip_serializing_if = "Option::is_none")] pub battery: Option, /// ISP config - #[serde(rename = "ispCfg")] + #[serde(rename = "ispCfg", skip_serializing_if = "Option::is_none")] pub isp_cfg: Option, /// OSD config - #[serde(rename = "osdCfg")] + #[serde(rename = "osdCfg", skip_serializing_if = "Option::is_none")] pub osd_cfg: Option, /// Support battery analysis - #[serde(rename = "batAnalysis")] + #[serde(rename = "batAnalysis", skip_serializing_if = "Option::is_none")] pub bat_analysis: Option, /// Supports dynamic resolution - #[serde(rename = "dynamicReso")] + #[serde(rename = "dynamicReso", skip_serializing_if = "Option::is_none")] pub dynamic_reso: Option, /// Audio version - #[serde(rename = "audioVersion")] + #[serde(rename = "audioVersion", skip_serializing_if = "Option::is_none")] pub audio_version: Option, /// Supports LED control - #[serde(rename = "ledCtrl")] + #[serde(rename = "ledCtrl", skip_serializing_if = "Option::is_none")] pub led_ctrl: Option, /// Supports PTZ Control - #[serde(rename = "ptzControl")] + #[serde(rename = "ptzControl", skip_serializing_if = "Option::is_none")] pub ptz_control: Option, /// Supports new ISP config - #[serde(rename = "newIspCfg")] + #[serde(rename = "newIspCfg", skip_serializing_if = "Option::is_none")] pub new_isp_cfg: Option, /// Supports PTZ presets - #[serde(rename = "ptzPreset")] + #[serde(rename = "ptzPreset", skip_serializing_if = "Option::is_none")] pub ptz_preset: Option, /// Supports PTZ patrol - #[serde(rename = "ptzPatrol")] + #[serde(rename = "ptzPatrol", skip_serializing_if = "Option::is_none")] pub ptz_patrol: Option, /// Supports PTZ Tattern - #[serde(rename = "ptzTattern")] + #[serde(rename = "ptzTattern", skip_serializing_if = "Option::is_none")] pub ptz_tattern: Option, /// Supports Auto PT - #[serde(rename = "autoPt")] + #[serde(rename = "autoPt", skip_serializing_if = "Option::is_none")] pub auto_pt: Option, /// H264 Profile: 7 - #[serde(rename = "h264Profile")] + #[serde(rename = "h264Profile", skip_serializing_if = "Option::is_none")] pub h264_profile: Option, /// Supports motion alarm + #[serde(skip_serializing_if = "Option::is_none")] pub motion: Option, /// AI Type - #[serde(rename = "aitype")] + #[serde(rename = "aitype", skip_serializing_if = "Option::is_none")] pub ai_type: Option, /// Animal AI Type - #[serde(rename = "aiAnimalType")] + #[serde(rename = "aiAnimalType", skip_serializing_if = "Option::is_none")] pub ai_animal_type: Option, /// Supports time lapse + #[serde(skip_serializing_if = "Option::is_none")] pub timelapse: Option, /// Supports snap + #[serde(skip_serializing_if = "Option::is_none")] pub snap: Option, /// Supports encoding control - #[serde(rename = "encCtrl")] + #[serde(rename = "encCtrl", skip_serializing_if = "Option::is_none")] pub enc_ctrl: Option, /// Has Zoom focus backlash - #[serde(rename = "zfBacklash")] + #[serde(rename = "zfBacklash", skip_serializing_if = "Option::is_none")] pub zf_backlash: Option, /// Supports IOT Link Ability - #[serde(rename = "IOTLinkAbility")] + #[serde(rename = "IOTLinkAbility", skip_serializing_if = "Option::is_none")] pub iot_link_ability: Option, /// Supports IPC audio talk - #[serde(rename = "ipcAudioTalk")] + #[serde(rename = "ipcAudioTalk", skip_serializing_if = "Option::is_none")] pub ipc_audio_talk: Option, /// Supports Bino Config - #[serde(rename = "binoCfg")] + #[serde(rename = "binoCfg", skip_serializing_if = "Option::is_none")] pub bino_cfg: Option, /// Supports thumbnail + #[serde(skip_serializing_if = "Option::is_none")] pub thumbnail: Option, } @@ -1405,7 +1468,7 @@ fn test_login_ser() { }; let b2 = BcXml::try_parse(sample.as_bytes()).unwrap(); - let b3 = BcXml::try_parse(b.serialize(bytes::BytesMut::new()).unwrap().as_ref()).unwrap(); + let b3 = BcXml::try_parse(b.serialize(vec![]).unwrap().as_ref()).unwrap(); assert_eq!(b, b2); assert_eq!(b, b3); assert_eq!(b2, b3); @@ -1418,6 +1481,13 @@ fn test_deviceinfo_partial_deser() { + 00000000000000 + 0 + 0 + 0 + ipc + 1 + 1 0 1 @@ -1430,11 +1500,97 @@ fn test_deviceinfo_partial_deser() { none IPC 33554880 + 0 + 0 + 0 + 0 + 0 + 0 + NTSC + YMD 0 0 1 - "# + + + 1 + + mainStream + + 3840 + 2160 + + 20 + 6144 + 20,18,16,15,12,10,8,6,4,2 + 4096,5120,6144,7168,8192 + + + subStream + + 640 + 360 + + 7 + 160 + 15,10,7,4 + 64,128,160,192,256,384,512 + + + + 1 + + mainStream + + 2560 + 1440 + + 25 + 0 + 25,22,20,18,16,15,12,10,8,6,4,2 + 1024,1536,2048,3072,4096,5120,6144,7168,8192 + + + subStream + + 640 + 360 + + 7 + 160 + 15,10,7,4 + 64,128,160,192,256,384,512 + + + + 1 + + mainStream + + 2304 + 1296 + + 25 + 0 + 25,22,20,18,16,15,12,10,8,6,4,2 + 1024,1536,2048,3072,4096,5120,6144,7168,8192 + + + subStream + + 640 + 360 + + 7 + 160 + 15,10,7,4 + 64,128,160,192,256,384,512 + + + + +"# ); // Needs to ignore all the other crap that we don't care about diff --git a/crates/core/src/bcmedia/de.rs b/crates/core/src/bcmedia/de.rs index f3f1851..b538efc 100644 --- a/crates/core/src/bcmedia/de.rs +++ b/crates/core/src/bcmedia/de.rs @@ -331,14 +331,20 @@ mod tests { ] .concat(); + let mut buf = BytesMut::from(&sample[..]); + // Should derealise all of this loop { - let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..])); + let e = BcMedia::deserialize(&mut buf); match e { Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => { // Reach end of files break; } + Err(Error::NomIncomplete(_)) if buf.is_empty() => { + // EOF still (but parser looking for next magic) + break; + } Err(e) => { error!("{:?}", e); panic!(); @@ -364,14 +370,19 @@ mod tests { ] .concat(); + let mut buf = BytesMut::from(&sample[..]); // Should derealise all of this loop { - let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..])); + let e = BcMedia::deserialize(&mut buf); match e { Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => { // Reach end of files break; } + Err(Error::NomIncomplete(_)) if buf.is_empty() => { + // EOF still (but parser looking for next magic) + break; + } Err(e) => { error!("{:?}", e); panic!(); @@ -410,14 +421,20 @@ mod tests { ] .concat(); + let mut buf = BytesMut::from(&sample[..]); + // Should derealise all of this loop { - let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..])); + let e = BcMedia::deserialize(&mut buf); match e { Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => { // Reach end of files break; } + Err(Error::NomIncomplete(_)) if buf.is_empty() => { + // EOF still (but parser looking for next magic) + break; + } Err(e) => { error!("{:?}", e); panic!(); @@ -434,7 +451,9 @@ mod tests { let sample = include_bytes!("samples/info_v1.raw"); - let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..])); + let mut buf = BytesMut::from(&sample[..]); + + let e = BcMedia::deserialize(&mut buf); assert!(matches!( e, Ok(BcMedia::InfoV1(BcMediaInfoV1 { @@ -470,7 +489,9 @@ mod tests { ] .concat(); - let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..])); + let mut buf = BytesMut::from(&sample[..]); + + let e = BcMedia::deserialize(&mut buf); if let Ok(BcMedia::Iframe(BcMediaIframe { video_type: VideoType::H264, microseconds: 3557705112, @@ -494,7 +515,9 @@ mod tests { ] .concat(); - let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..])); + let mut buf = BytesMut::from(&sample[..]); + + let e = BcMedia::deserialize(&mut buf); if let Ok(BcMedia::Pframe(BcMediaPframe { video_type: VideoType::H264, microseconds: 3557767112, @@ -512,8 +535,9 @@ mod tests { init(); let sample = include_bytes!("samples/adpcm_0.raw"); + let mut buf = BytesMut::from(&sample[..]); - let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..])); + let e = BcMedia::deserialize(&mut buf); if let Ok(BcMedia::Adpcm(BcMediaAdpcm { data: d })) = e { assert_eq!(d.len(), 244); } else { diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs index d2daf13..a707973 100644 --- a/crates/core/src/bcudp/de.rs +++ b/crates/core/src/bcudp/de.rs @@ -74,7 +74,12 @@ fn udp_disc(buf: &[u8]) -> IResult<&[u8], UdpDiscovery> { assert_eq!(checksum, actual_checksum); let decrypted_payload = decrypt(tid, enc_data_slice); - let payload = UdpXml::try_parse(decrypted_payload.as_slice()).map_err(|_| { + log::error!( + "decrypted_payload: {:?}", + std::str::from_utf8(&decrypted_payload) + ); + let payload = UdpXml::try_parse(decrypted_payload.as_slice()).map_err(|e| { + log::error!("e: {:?}", e); Err::Error(make_error( buf, "DISC: Unable to decode UDPXml", @@ -295,15 +300,16 @@ mod tests { ] .concat(); + let mut buf = BytesMut::from(&sample[..]); // Should derealise all of this loop { - let e = BcUdp::deserialize(&mut BytesMut::from(&sample[..])); + let e = BcUdp::deserialize(&mut buf); match e { Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => { // Reach end of files break; } - Err(Error::NomIncomplete(_)) => { + Err(Error::NomIncomplete(_)) if buf.is_empty() => { // Reach end of files break; } diff --git a/crates/core/src/bcudp/ser.rs b/crates/core/src/bcudp/ser.rs index 1d35569..e99a9ba 100644 --- a/crates/core/src/bcudp/ser.rs +++ b/crates/core/src/bcudp/ser.rs @@ -1,6 +1,5 @@ use super::{crc::calc_crc, model::*, xml_crypto::encrypt}; use crate::Error; -use bytes::BytesMut; use cookie_factory::bytes::*; use cookie_factory::sequence::tuple; use cookie_factory::SerializeFn; @@ -11,10 +10,7 @@ impl BcUdp { pub(crate) fn serialize(&self, buf: W) -> Result { let (buf, _) = match &self { BcUdp::Discovery(payload) => { - let xml_payload = encrypt( - payload.tid, - &payload.payload.serialize(BytesMut::new()).unwrap(), - ); + let xml_payload = encrypt(payload.tid, &payload.payload.serialize(vec![]).unwrap()); gen(bcudp_disc(payload, &xml_payload), buf)? } BcUdp::Ack(payload) => { diff --git a/crates/core/src/bcudp/xml.rs b/crates/core/src/bcudp/xml.rs index 6bbf005..b60dead 100644 --- a/crates/core/src/bcudp/xml.rs +++ b/crates/core/src/bcudp/xml.rs @@ -1,9 +1,10 @@ use serde::{Deserialize, Serialize}; -use std::fmt::Write; use std::io::BufRead; +use std::io::Write; /// The top level of the UDP xml is P2P #[derive(PartialEq, Eq, Debug, Deserialize, Serialize, Clone)] +#[serde(rename = "P2P")] pub enum UdpXml { /// C2D_S xml Discovery of any client #[serde(rename = "C2D_S")] @@ -61,12 +62,31 @@ pub enum UdpXml { C2rHb(C2rHb), } +/// The top level holder for P2P we auto add/remove this at serde +#[derive(PartialEq, Eq, Debug, Deserialize, Serialize, Clone)] +struct P2P { + #[serde(rename = "$value")] + xml: UdpXml, +} + impl UdpXml { pub(crate) fn try_parse(s: impl BufRead) -> Result { - quick_xml::de::from_reader(s) + let p2p: Result = quick_xml::de::from_reader(s); + p2p.map(|i| i.xml) } pub(crate) fn serialize(&self, mut w: W) -> Result { - quick_xml::se::to_writer(&mut w, self)?; + let mut writer = quick_xml::writer::Writer::new(&mut w); + // No header on a UdpXml + // writer.write_event(quick_xml::events::Event::Decl( + // quick_xml::events::BytesDecl::new("1.0", Some("UTF-8"), None), + // ))?; + writer + .create_element("P2P") + .write_inner_content::<_, quick_xml::de::DeError>(|writer| { + writer.write_serializable("", &self)?; + Ok(()) + })?; + Ok(w) } } @@ -270,7 +290,7 @@ pub struct C2rC { #[serde(rename = "p")] pub os: String, /// The revision. Known values None and 3 - #[serde(rename = "r")] + #[serde(rename = "r", skip_serializing_if = "Option::is_none")] pub revision: Option, } @@ -281,8 +301,10 @@ pub struct C2rC { #[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)] pub struct R2cT { /// The location of the camera + #[serde(skip_serializing_if = "Option::is_none")] pub dmap: Option, /// The location of the camera + #[serde(skip_serializing_if = "Option::is_none")] pub dev: Option, /// The client id pub cid: i32, @@ -298,10 +320,13 @@ pub struct R2cT { #[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)] pub struct R2cCr { /// Dev camera location (actual local ip) + #[serde(skip_serializing_if = "Option::is_none")] pub dev: Option, /// Dmap camera location + #[serde(skip_serializing_if = "Option::is_none")] pub dmap: Option, /// The location of the relay + #[serde(skip_serializing_if = "Option::is_none")] pub relay: Option, /// The nat type. Known values `"NULL"` pub nat: String, diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 2eb8142..5c7f42b 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -9,18 +9,50 @@ //! A camera can be initialised with //! //! ```no_run -//! use neolink_core::bc_protocol::BcCamera; -//! let channel_id = 0; // Usually zero but can be non zero if uses a reolink NVR -//! let mut camera = BcCamera::new_with_addr("camera_ip_address", channel_id).unwrap(); +//! # tokio::runtime::Runtime::new().unwrap().block_on(async { +//! use neolink_core::bc_protocol::{BcCamera, BcCameraOpt, DiscoveryMethods, ConnectionProtocol, Credentials}; +//! let options = BcCameraOpt { +//! name: "CamName".to_string(), +//! channel_id: 0, +//! addrs: ["192.168.1.1".parse().unwrap()].to_vec(), +//! port: Some(9000), +//! uid: Some("CAMUID".to_string()), +//! protocol: ConnectionProtocol::TcpUdp, +//! discovery: DiscoveryMethods::Relay, +//! credentials: Credentials { +//! username: "username".to_string(), +//! password: Some("password".to_string()), +//! }, +//! debug: false, +//! max_discovery_retries: 10, +//! }; +//! let mut camera = BcCamera::new(&options).await.unwrap(); +//! # }) //! ``` //! //! After that login can be conducted with //! //! ```no_run -//! # use neolink_core::bc_protocol::BcCamera; -//! # let channel_id = 0; -//! # let mut camera = BcCamera::new_with_addr("camera_ip_address", channel_id).unwrap(); -//! camera.login("username", Some("password")); +//! # tokio::runtime::Runtime::new().unwrap().block_on(async { +//! # use neolink_core::bc_protocol::{BcCamera, BcCameraOpt, DiscoveryMethods, ConnectionProtocol, Credentials}; +//! # let options = BcCameraOpt { +//! # name: "CamName".to_string(), +//! # channel_id: 0, +//! # addrs: ["192.168.1.1".parse().unwrap()].to_vec(), +//! # port: Some(9000), +//! # uid: Some("CAMUID".to_string()), +//! # protocol: ConnectionProtocol::TcpUdp, +//! # discovery: DiscoveryMethods::Relay, +//! # credentials: Credentials { +//! # username: "username".to_string(), +//! # password: Some("password".to_string()), +//! # }, +//! # debug: false, +//! # max_discovery_retries: 10, +//! # }; +//! # let mut camera = BcCamera::new(&options).await.unwrap(); +//! camera.login().await; +//! # }) //! ``` //! For further commands see the [`bc_protocol::BcCamera`] struct. //! diff --git a/crates/pushnoti/src/utils.rs b/crates/pushnoti/src/utils.rs index 9a41f51..d3aa47c 100644 --- a/crates/pushnoti/src/utils.rs +++ b/crates/pushnoti/src/utils.rs @@ -15,7 +15,9 @@ use std::{ pub(crate) enum AddressOrUid { Address(String), + #[allow(dead_code)] Uid(String, DiscoveryMethods), + #[allow(dead_code)] AddressWithUid(String, String, DiscoveryMethods), } diff --git a/src/common/streamthread.rs b/src/common/streamthread.rs index 362de5d..5ec833f 100644 --- a/src/common/streamthread.rs +++ b/src/common/streamthread.rs @@ -339,20 +339,35 @@ impl StreamData { if let Some(encode) = infos.iter().find(|encode| encode.name == name.to_string()) { + let bitrate_table = encode + .bitrate_table + .split(',') + .filter_map(|c| { + let i: Result = c.parse(); + i.ok() + }) + .collect::>(); + let framerate_table = encode + .framerate_table + .split(',') + .filter_map(|c| { + let i: Result = c.parse(); + i.ok() + }) + .collect::>(); + Ok(( [encode.resolution.width, encode.resolution.height], - encode - .bitrate_table + bitrate_table .get(encode.default_bitrate as usize) .copied() .unwrap_or(encode.default_bitrate) * 1024, - encode - .framerate_table + framerate_table .get(encode.default_framerate as usize) .copied() .unwrap_or(encode.default_framerate), - encode.framerate_table.clone(), + framerate_table.clone(), )) } else { Ok(([0, 0], 0, 0, vec![]))