WIP Mqtt using reactor

This commit is contained in:
QuantumEntangledAndy committed 2023-09-12 16:41:45 +07:00
1 parent 2a10236f91
commit 101f2ffaa9
12 files changed
+1284 -1498

No files matched your search

+1 -1
View File
@@ -102,7 +102,7 @@ pub struct BcCameraOpt {
///
/// Currently this is just the format of battery levels but if we ever got more status
/// messages then they will also use this information
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum PrintFormat {
/// None, don't print
None,
+1
View File
@@ -2,6 +2,7 @@ use super::{BcCamera, Error, Result};
use crate::bc::{model::*, xml::*};
/// Directions used for Ptz
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum Direction {
/// To move the camera Up
Up,
+1 -1
View File
@@ -11,7 +11,7 @@ use std::{
///
/// This is used for UID lookup, it is unused with
/// TPC/known ip address cameras
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum DiscoveryMethods {
/// Forbid all discovery methods. Only TCP connections with known addresses will work
#[serde(alias = "none")]
+4
View File
@@ -172,4 +172,8 @@ impl NeoInstance {
.await?;
Ok(instance_rx.await?)
}
pub(crate) fn camera(&self) -> WatchReceiver<Weak<BcCamera>> {
self.camera_watch.clone()
}
}
+26 -20
View File
@@ -33,6 +33,9 @@ pub(crate) struct Config {
#[serde(default = "default_certificate")]
pub(crate) certificate: Option<String>,
#[serde(default = "Default::default")]
pub(crate) mqtt: Option<MqttServerConfig>,
#[validate(regex(
path = "RE_TLS_CLIENT_AUTH",
message = "Incorrect tls auth",
@@ -46,6 +49,24 @@ pub(crate) struct Config {
pub(crate) users: Vec<UserConfig>,
}
#[derive(Debug, Deserialize, Clone, Validate, PartialEq, Eq)]
#[validate(schema(function = "validate_mqtt_server", skip_on_field_errors = true))]
pub(crate) struct MqttServerConfig {
#[serde(alias = "server")]
pub(crate) broker_addr: String,
pub(crate) port: u16,
#[serde(default)]
pub(crate) credentials: Option<(String, String)>,
#[serde(default)]
pub(crate) ca: Option<std::path::PathBuf>,
#[serde(default)]
pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>,
}
#[derive(Debug, Deserialize, Clone, Copy, Eq, PartialEq)]
pub(crate) enum StreamConfig {
#[serde(alias = "none")]
@@ -102,7 +123,7 @@ impl StreamConfig {
}
}
#[derive(Debug, Deserialize, Validate, Clone)]
#[derive(Debug, Deserialize, Validate, Clone, PartialEq)]
#[validate(schema(function = "validate_camera_config"))]
pub(crate) struct CameraConfig {
pub(crate) name: String,
@@ -177,7 +198,7 @@ pub(crate) struct CameraConfig {
pub(crate) max_discovery_retries: usize,
}
#[derive(Debug, Deserialize, Validate, Clone)]
#[derive(Debug, Deserialize, Validate, Clone, PartialEq, Eq)]
pub(crate) struct UserConfig {
#[validate(custom = "validate_username")]
#[serde(alias = "username")]
@@ -187,23 +208,8 @@ pub(crate) struct UserConfig {
pub(crate) pass: String,
}
#[derive(Debug, Deserialize, Clone, Validate)]
#[validate(schema(function = "validate_mqtt_config", skip_on_field_errors = true))]
#[derive(Debug, Deserialize, Clone, Validate, PartialEq, Eq)]
pub(crate) struct MqttConfig {
#[serde(alias = "server")]
pub(crate) broker_addr: String,
pub(crate) port: u16,
#[serde(default)]
pub(crate) credentials: Option<(String, String)>,
#[serde(default)]
pub(crate) ca: Option<std::path::PathBuf>,
#[serde(default)]
pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>,
#[serde(default = "default_true")]
pub(crate) enable_motion: bool,
#[serde(default = "default_true")]
@@ -219,14 +225,14 @@ pub(crate) struct MqttConfig {
pub(crate) discovery: Option<MqttDiscoveryConfig>,
}
#[derive(Debug, Deserialize, Clone, Validate)]
#[derive(Debug, Deserialize, Clone, Validate, PartialEq, Eq)]
pub(crate) struct MqttDiscoveryConfig {
pub(crate) topic: String,
pub(crate) features: HashSet<Discoveries>,
}
fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
fn validate_mqtt_server(config: &MqttServerConfig) -> Result<(), ValidationError> {
if config.ca.is_some() && config.client_auth.is_some() {
Err(ValidationError::new(
"Cannot have both ca and client_auth set",
+1 -1
View File
@@ -116,7 +116,7 @@ async fn main() -> Result<()> {
talk::main(opts, config).await?;
}
Some(Command::Mqtt(opts)) => {
mqtt::main(opts, config).await?;
mqtt::main(opts, neo_reactor.clone()).await?;
}
Some(Command::Image(opts)) => {
image::main(opts, neo_reactor.clone()).await?;
+134 -149
View File
@@ -5,10 +5,9 @@
use anyhow::{Context, Result};
use heck::ToTitleCase;
use log::*;
use std::sync::Arc;
use super::mqttc::MqttSender;
use crate::config::{CameraConfig, MqttDiscoveryConfig};
use super::mqttc::MqttInstance;
use crate::{common::NeoInstance, config::MqttDiscoveryConfig};
use serde::{Deserialize, Serialize, Serializer};
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Copy, Hash)]
@@ -200,9 +199,10 @@ struct DiscoverySensor {
/// Enables MQTT discovery for a camera. See docs at https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
pub(crate) async fn enable_discovery(
discovery_config: &MqttDiscoveryConfig,
mqtt_sender: &MqttSender,
cam_config: &Arc<CameraConfig>,
mqtt: &MqttInstance,
camera: &NeoInstance,
) -> Result<()> {
let cam_config = camera.config().await?.borrow().clone();
debug!("Enabling MQTT discovery for {}", cam_config.name);
let mut connections = vec![];
@@ -269,25 +269,23 @@ pub(crate) async fn enable_discovery(
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/light/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery light config into json"
})?,
true,
mqtt.send_message_with_root_topic(
&format!(
"{}/light/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data)
.with_context(|| "Cound not serialise discovery light config into json")?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish floodlight auto-discover data on over MQTT for {}",
cam_config.name
)
.await
.with_context(|| {
format!(
"Failed to publish floodlight auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
})?;
}
Discoveries::Camera => {
let config_data = DiscoveryCamera {
@@ -306,25 +304,23 @@ pub(crate) async fn enable_discovery(
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/camera/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery camera config into json"
})?,
true,
mqtt.send_message_with_root_topic(
&format!(
"{}/camera/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data)
.with_context(|| "Cound not serialise discovery camera config into json")?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish camera auto-discover data on over MQTT for {}",
cam_config.name
)
.await
.with_context(|| {
format!(
"Failed to publish camera auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
})?;
}
Discoveries::Led => {
let config_data = DiscoverySwitch {
@@ -347,25 +343,23 @@ pub(crate) async fn enable_discovery(
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/switch/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery led config into json"
})?,
true,
mqtt.send_message_with_root_topic(
&format!(
"{}/switch/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data)
.with_context(|| "Cound not serialise discovery led config into json")?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish led auto-discover data on over MQTT for {}",
cam_config.name
)
.await
.with_context(|| {
format!(
"Failed to publish led auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
})?;
}
Discoveries::Ir => {
let config_data = DiscoverySelect {
@@ -385,25 +379,23 @@ pub(crate) async fn enable_discovery(
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/select/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery led config into json"
})?,
true,
mqtt.send_message_with_root_topic(
&format!(
"{}/select/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data)
.with_context(|| "Cound not serialise discovery led config into json")?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish led auto-discover data on over MQTT for {}",
cam_config.name
)
.await
.with_context(|| {
format!(
"Failed to publish led auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
})?;
}
Discoveries::Motion => {
let config_data = DiscoveryBinarySensor {
@@ -423,25 +415,23 @@ pub(crate) async fn enable_discovery(
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/binary_sensor/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery motion config into json"
})?,
true,
mqtt.send_message_with_root_topic(
&format!(
"{}/binary_sensor/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data)
.with_context(|| "Cound not serialise discovery motion config into json")?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish motion auto-discover data on over MQTT for {}",
cam_config.name
)
.await
.with_context(|| {
format!(
"Failed to publish motion auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
})?;
}
Discoveries::Reboot => {
let config_data = DiscoveryButton {
@@ -460,25 +450,23 @@ pub(crate) async fn enable_discovery(
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/button/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery reboot config into json"
})?,
true,
mqtt.send_message_with_root_topic(
&format!(
"{}/button/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data)
.with_context(|| "Cound not serialise discovery reboot config into json")?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish reboot auto-discover data on over MQTT for {}",
cam_config.name
)
.await
.with_context(|| {
format!(
"Failed to publish reboot auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
})?;
}
Discoveries::Pt => {
for dir in ["left", "right", "up", "down"] {
@@ -498,25 +486,23 @@ pub(crate) async fn enable_discovery(
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/button/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery pt config into json"
})?,
true,
mqtt.send_message_with_root_topic(
&format!(
"{}/button/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data)
.with_context(|| "Cound not serialise discovery pt config into json")?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish pt auto-discover data on over MQTT for {}",
cam_config.name
)
.await
.with_context(|| {
format!(
"Failed to publish pt auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
})?;
}
}
Discoveries::Battery => {
@@ -537,25 +523,24 @@ pub(crate) async fn enable_discovery(
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/sensor/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery battery config into json"
})?,
true,
mqtt.send_message_with_root_topic(
&format!(
"{}/sensor/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery battery config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish battery auto-discover data on over MQTT for {}",
cam_config.name
)
.await
.with_context(|| {
format!(
"Failed to publish battery auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
})?;
}
}
}
-711
View File
@@ -1,711 +0,0 @@
use crate::config::CameraConfig;
use crate::utils::{timeout, AddressOrUid};
use anyhow::{anyhow, Context, Result};
use futures::stream::StreamExt;
use log::*;
use neolink_core::bc_protocol::{
BcCamera, Direction as BcDirection, Error as BcError, LightState, MaxEncryption, MotionStatus,
};
use std::sync::Arc;
use tokio::{
sync::mpsc::{channel, Receiver, Sender},
task::JoinSet,
time::{interval, sleep, Duration},
};
#[derive(Debug, Clone)]
pub(crate) enum Messages {
Login,
MotionStop,
MotionStart,
Reboot,
FloodlightOn,
FloodlightOff,
StatusLedOn,
StatusLedOff,
IRLedOn,
IRLedOff,
IRLedAuto,
Battery,
PIROn,
PIROff,
PIRQuery,
Ptz(Direction),
Snap(Vec<u8>),
BatteryLevel(u32),
Preset(u8),
PresetAssign(u8, String),
PresetQuery,
}
#[derive(Debug, Copy, Clone)]
pub(crate) enum Direction {
Up(f32, f32),
Down(f32, f32),
Left(f32, f32),
Right(f32, f32),
In(f32, f32),
Out(f32, f32),
}
#[derive(Debug)]
enum ToCamera {
Send(Messages),
SendAndReply {
message: Messages,
reply: Sender<String>,
},
}
#[derive(Clone)]
pub(crate) struct EventCamSender {
channel_in: Sender<ToCamera>,
}
impl EventCamSender {
#[allow(dead_code)]
pub(crate) async fn send_message(&self, msg: Messages) -> Result<()> {
self.channel_in
.send(ToCamera::Send(msg))
.await
.context("Failed to send message from camera")
}
pub(crate) async fn send_message_with_reply(&self, msg: Messages) -> Result<String> {
let (tx, mut rx) = channel(1);
self.channel_in
.send(ToCamera::SendAndReply {
message: msg,
reply: tx,
})
.await
.context("Failed to send message from camera")?;
tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv())
.await
.context("Failed to recieve reply Timeout")?
.ok_or_else(|| anyhow!("Failed to recieve reply"))
}
}
pub(crate) struct EventCam {
sender: EventCamSender,
channel_out: Receiver<Messages>,
set: JoinSet<Result<()>>,
}
impl EventCam {
pub(crate) async fn new(config: Arc<CameraConfig>) -> Self {
// Channels from the camera
let (tx, rx) = channel(40);
// Channels to the camera
let (stx, srx) = channel(40);
let mut set = JoinSet::<Result<()>>::new();
let thread_config = config;
let mut eventcam_thread = EventCamThread { rx: srx, tx };
set.spawn(async move {
let mut wait_for = tokio::time::Duration::from_micros(125);
loop {
// Ignore errors and just loop
tokio::task::yield_now().await;
if let Err(e) = eventcam_thread.cam_run(&thread_config).await {
warn!("Camera thread error: {:?}. Restarting...", e);
tokio::time::sleep(wait_for).await;
wait_for *= 2;
}
}
});
Self {
sender: EventCamSender { channel_in: stx },
channel_out: rx,
set,
}
}
/// This will also error is the join set errors
pub(crate) async fn poll(&mut self) -> Result<Messages> {
let (incoming, set) = (&mut self.channel_out, &mut self.set);
tokio::select! {
v = incoming.recv() => v.with_context(|| "Camera Polling error"),
v = async {
while let Some(res) = set.join_next().await {
match res {
Err(e) => {
set.abort_all();
return Err(e.into());
}
Ok(Err(e)) => {
set.abort_all();
return Err(e);
}
Ok(Ok(())) => {}
}
}
Err(anyhow!("Camera background thread dropped without error"))
} => v.with_context(|| "Camera Threads aborted"),
}
}
pub(crate) fn get_sender(&self) -> EventCamSender {
self.sender.clone()
}
}
impl Drop for EventCam {
fn drop(&mut self) {
self.set.abort_all();
}
}
struct EventCamThread {
rx: Receiver<ToCamera>,
tx: Sender<Messages>,
}
impl EventCamThread {
async fn cam_run(&mut self, camera_config: &CameraConfig) -> Result<()> {
let camera_addr = AddressOrUid::new(
&camera_config.camera_addr,
&camera_config.camera_uid,
&camera_config.discovery,
)
.unwrap();
info!(
"{}: Connecting to camera at {}",
camera_config.name, camera_addr
);
let camera = camera_addr
.connect_camera(camera_config)
.await
.with_context(|| {
format!(
"Failed to connect to camera {} at {} on channel {}",
camera_config.name, camera_addr, camera_config.channel_id
)
})?;
info!("{}: Logging in", camera_config.name);
let max_encryption = match camera_config.max_encryption.to_lowercase().as_str() {
"none" => MaxEncryption::None,
"bcencrypt" => MaxEncryption::BcEncrypt,
"aes" => MaxEncryption::Aes,
_ => MaxEncryption::Aes,
};
timeout(camera.login_with_maxenc(max_encryption))
.await
.context("Failed to login to the camera")??;
info!("{}: Connected and logged in", camera_config.name);
if let Err(e) = camera.monitor_battery(camera_config.print_format).await {
warn!("Could not monitor battery: {:?}", e);
}
self.tx.send(Messages::Login).await?;
// Shararble cameras
let arc_cam = Arc::new(camera);
let mut motion_thread = MotionThread {
tx: self.tx.clone(),
camera: arc_cam.clone(),
};
let mut flight_thread = FloodlightThread {
tx: self.tx.clone(),
camera: arc_cam.clone(),
};
let mut snap_thread = SnapThread {
tx: self.tx.clone(),
camera: arc_cam.clone(),
};
let mut battery_thread = BatteryLevelThread {
tx: self.tx.clone(),
camera: arc_cam.clone(),
};
let mut keepalive_thread = KeepaliveThread {
camera: arc_cam.clone(),
};
let mut message_handler = MessageHandler {
rx: &mut self.rx,
camera: arc_cam,
};
tokio::select! {
val = async {
info!("{}: Listening to Camera Motion", camera_config.name);
motion_thread.run().await
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_motion => {
if let Err(e) = val {
error!("Motion thread aborted: {:?}", e);
Err(e)
} else {
debug!("Normal finish on motion thread");
Ok(())
}
},
val = async {
debug!("{}: Starting Pings", camera_config.name);
keepalive_thread.run().await
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_pings => {
if let Err(e) = val {
debug!("Ping thread aborted: {:?}", e);
Err(e)
} else {
debug!("Normal finish on Ping thread");
Ok(())
}
},
val = async {
info!("{}: Listening to FloodLight Status", camera_config.name);
flight_thread.run().await
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_light => {
if let Err(e) = val {
error!("FloodLight thread aborted: {:?}", e);
Err(e)
} else {
debug!("Normal finish on FloodLight thread");
Ok(())
}
},
val = async {
info!("{}: Updating Preview", camera_config.name);
snap_thread.run().await
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_preview => {
if let Err(e) = val {
error!("Snap thread aborted: {:?}", e);
Err(e)
} else {
debug!("Normal finish on Snap thread");
Ok(())
}
},
val = async {
info!("{}: Updating Battery Level", camera_config.name);
battery_thread.run().await
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_battery => {
if let Err(e) = val {
error!("Battery thread aborted: {:?}", e);
Err(e)
} else {
debug!("Normal finish on Battery thread");
Ok(())
}
},
val = async {
info!("{}: Setting up camera actions", camera_config.name);
message_handler.listen().await
} => {
if let Err(e) = val {
error!("Camera message handler aborted: {:?}", e);
Err(e)
} else {
debug!("Normal finish on camera message thread");
Ok(())
}
},
}?;
Ok(())
}
}
struct MotionThread {
tx: Sender<Messages>,
camera: Arc<BcCamera>,
}
impl MotionThread {
async fn run(&mut self) -> Result<()> {
let mut motion_data = self.camera.listen_on_motion().await?;
let mut queued_motion = motion_data.consume_motion_events()?;
loop {
tokio::task::yield_now().await;
for motion_status in queued_motion.drain(..) {
match motion_status {
MotionStatus::Start(_) => {
self.tx
.send(Messages::MotionStart)
.await
.map_err(|_| BcError::Other("Failed to send Message"))?;
}
MotionStatus::Stop(_) => {
self.tx
.send(Messages::MotionStop)
.await
.map_err(|_| BcError::Other("Failed to send Message"))?;
}
_ => {}
}
}
queued_motion.push(motion_data.next_motion().await?);
}
}
}
struct FloodlightThread {
tx: Sender<Messages>,
camera: Arc<BcCamera>,
}
impl FloodlightThread {
async fn run(&mut self) -> Result<()> {
let mut reciever =
tokio_stream::wrappers::ReceiverStream::new(self.camera.listen_on_flightlight().await?);
while let Some(flights) = reciever.next().await {
for flight in flights.floodlight_status_list.iter() {
if flight.status == 0 {
self.tx.send(Messages::FloodlightOff).await?;
} else {
self.tx.send(Messages::FloodlightOn).await?;
}
}
}
Ok(())
}
}
struct SnapThread {
tx: Sender<Messages>,
camera: Arc<BcCamera>,
}
impl SnapThread {
async fn run(&mut self) -> Result<()> {
let mut tries = 0;
let base_duration = Duration::from_millis(500);
loop {
tokio::time::sleep(base_duration.saturating_mul(tries)).await;
let snapshot = match self.camera.get_snapshot().await {
Ok(info) => {
tries = 1;
info
}
Err(neolink_core::Error::UnintelligibleReply { reply, why }) => {
log::debug!("Reply: {:?}, why: {:?}", reply, why);
// Try again later
tries += 1;
continue;
}
Err(neolink_core::Error::CameraServiceUnavaliable) => {
log::debug!("Snap not supported");
futures::future::pending().await
}
Err(e) => return Err(e.into()),
};
self.tx.send(Messages::Snap(snapshot)).await?;
}
}
}
struct BatteryLevelThread {
tx: Sender<Messages>,
camera: Arc<BcCamera>,
}
impl BatteryLevelThread {
async fn run(&mut self) -> Result<()> {
let mut tries = 0;
let base_duration = Duration::from_secs(15);
loop {
tokio::time::sleep(base_duration.saturating_mul(tries)).await;
let battery = match self.camera.battery_info().await {
Ok(info) => {
tries = 1;
info
}
Err(neolink_core::Error::UnintelligibleReply { .. }) => {
// Try again later
tries += 1;
continue;
}
Err(neolink_core::Error::CameraServiceUnavaliable) => {
log::debug!("Battery not supported");
futures::future::pending().await
}
Err(e) => return Err(e.into()),
};
self.tx
.send(Messages::BatteryLevel(battery.battery_percent))
.await?;
}
}
}
struct KeepaliveThread {
camera: Arc<BcCamera>,
}
impl KeepaliveThread {
async fn run(&mut self) -> Result<()> {
let mut interval =
tokio_stream::wrappers::IntervalStream::new(interval(Duration::from_secs(5)));
while let Some(_update) = interval.next().await {
if self.camera.ping().await.is_err() {
break;
}
}
futures::pending!(); // Never actually finish, has to be aborted
Ok(())
}
}
struct MessageHandler<'a> {
rx: &'a mut Receiver<ToCamera>,
camera: Arc<BcCamera>,
}
impl<'a> MessageHandler<'a> {
async fn listen(&mut self) -> Result<()> {
loop {
tokio::task::yield_now().await;
match self.rx.recv().await {
Some(to_camera) => {
let (replier, message) = match to_camera {
ToCamera::Send(message) => (None, message),
ToCamera::SendAndReply { message, reply } => (Some(reply), message),
};
let mut error = None;
let reply = match message {
Messages::Reboot => {
if let Err(e) = self.camera.reboot().await {
error = Some(format!("Failed to reboot the camera: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::FloodlightOn => {
let res = self.camera.set_floodlight_manual(true, 180).await;
if res.is_err() {
error = Some(format!(
"Failed to turn on the floodlight light: {:?}",
res.err()
));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::FloodlightOff => {
let res = self.camera.set_floodlight_manual(false, 180).await;
if res.is_err() {
error = Some(format!(
"Failed to turn off the floodlight light: {:?}",
res.err()
));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::StatusLedOn => {
if let Err(e) = self.camera.led_light_set(true).await {
error =
Some(format!("Failed to turn on the status light: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::StatusLedOff => {
if let Err(e) = self.camera.led_light_set(false).await {
error =
Some(format!("Failed to turn off the status light: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::IRLedOn => {
if let Err(e) = self.camera.irled_light_set(LightState::On).await {
error =
Some(format!("Failed to turn on the status light: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::IRLedOff => {
if let Err(e) = self.camera.irled_light_set(LightState::Off).await {
error =
Some(format!("Failed to turn on the status light: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::IRLedAuto => {
if let Err(e) = self.camera.irled_light_set(LightState::Auto).await {
error =
Some(format!("Failed to turn on the status light: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::Battery => match self.camera.battery_info().await {
Err(e) => {
error!("Failed to get battery status: {:?}", e);
"FAIL".to_string()
}
Ok(battery_info) => {
let bytes_res = yaserde::ser::serialize_with_writer(
&battery_info,
vec![],
&Default::default(),
);
match bytes_res {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(str) => str,
Err(_) => {
error!("Failed to encode battery status");
"FAIL".to_string()
}
},
Err(_) => {
error!("Failed to serialise battery status");
"FAIL".to_string()
}
}
}
},
Messages::PIRQuery => match self.camera.get_pirstate().await {
Err(e) => {
error!("Failed to get pir status: {:?}", e);
"FAIL".to_string()
}
Ok(pir_info) => {
let bytes_res = yaserde::ser::serialize_with_writer(
&pir_info,
vec![],
&Default::default(),
);
match bytes_res {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(str) => str,
Err(_) => {
error!("Failed to encode pir status");
"FAIL".to_string()
}
},
Err(_) => {
error!("Failed to serialise pir status");
"FAIL".to_string()
}
}
}
},
Messages::PIROn => {
if let Err(e) = self.camera.pir_set(true).await {
error = Some(format!("Failed to turn on the pir: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::PIROff => {
if let Err(e) = self.camera.pir_set(false).await {
error = Some(format!("Failed to turn on the pir: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::Ptz(direction) => {
let (bc_direction, speed, seconds) = match direction {
Direction::Up(speed, seconds) => (BcDirection::Up, speed, seconds),
Direction::Down(speed, seconds) => {
(BcDirection::Down, speed, seconds)
}
Direction::Left(speed, seconds) => {
(BcDirection::Left, speed, seconds)
}
Direction::Right(speed, seconds) => {
(BcDirection::Right, speed, seconds)
}
Direction::In(speed, seconds) => (BcDirection::In, speed, seconds),
Direction::Out(speed, seconds) => {
(BcDirection::Out, speed, seconds)
}
};
if let Err(e) = self.camera.send_ptz(bc_direction, speed).await {
error = Some(format!("Failed to send PTZ: {:?}", e));
"FAIL".to_string()
} else {
// sleep for the designated seconds
sleep(Duration::from_secs_f32(seconds)).await;
// note that amount is not used in the stop command
if let Err(e) = self.camera.send_ptz(BcDirection::Stop, 0.0).await {
error = Some(format!("Failed to send PTZ: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
}
Messages::Preset(id) => {
if let Err(e) = self.camera.moveto_ptz_preset(id).await {
error = Some(format!("Failed to send PTZ preset: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::PresetAssign(id, name) => {
if let Err(e) = self.camera.set_ptz_preset(id, name).await {
error = Some(format!("Failed to send PTZ preset: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::PresetQuery => match self.camera.get_ptz_preset().await {
Err(e) => {
error!("Failed to get PTZ preset status: {:?}", e);
"FAIL".to_string()
}
Ok(ptz_info) => {
let bytes_res = yaserde::ser::serialize_with_writer(
&ptz_info,
vec![],
&Default::default(),
);
match bytes_res {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(str) => str,
Err(_) => {
error!("Failed to encode PTZ preset status");
"FAIL".to_string()
}
},
Err(_) => {
error!("Failed to serialise PTZ preset status");
"FAIL".to_string()
}
}
}
},
_ => "UNKNOWN COMMAND".to_string(),
};
if let Some(replier) = replier {
let _ = replier.send(reply).await;
}
if let Some(error) = error {
return Err(anyhow!("{}", error));
}
}
None => {
return Err(anyhow!("Message handller channel dropped"));
}
}
}
}
}
+768 -349
View File
File diff suppressed because it is too large. Load diff
+348 -264
View File
@@ -1,23 +1,357 @@
use crate::config::MqttConfig;
use crate::{
config::{Config, MqttServerConfig},
AnyResult,
};
use anyhow::{anyhow, Context, Result};
use futures::future::FutureExt;
use log::*;
use rumqttc::{
AsyncClient, ClientError, ConnectReturnCode, Event, EventLoop, Incoming, Key, LastWill,
MqttOptions, Publish, QoS, TlsConfiguration, Transport,
AsyncClient, ConnectReturnCode, Event, Incoming, Key, LastWill, MqttOptions, QoS,
TlsConfiguration, Transport,
};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio::task::JoinSet;
use tokio::{
sync::{
broadcast::{channel as broadcast, Sender as BroadcastSender},
mpsc::{channel as mpsc, Receiver as MpscReceiver, Sender as MpscSender},
oneshot::{channel as oneshot, Sender as OneshotSender},
watch::Receiver as WatchReceiver,
},
time::{sleep, Duration},
};
use tokio_stream::{wrappers::BroadcastStream, StreamExt};
use tokio_util::sync::CancellationToken;
pub(crate) struct Mqtt {
client: Arc<AsyncClient>,
name: String,
incoming: Receiver<MqttReply>,
cancel: CancellationToken,
outgoing_tx: MpscSender<MqttRequest>,
set: JoinSet<Result<()>>,
drop_message: Option<MqttReply>,
}
impl Mqtt {
pub(crate) async fn new(config: WatchReceiver<Config>) -> Self {
let (incoming_tx, _) = broadcast::<MqttReply>(100);
let (outgoing_tx, mut outgoing_rx) = mpsc::<MqttRequest>(100);
let cancel = CancellationToken::new();
let mut set = JoinSet::<AnyResult<()>>::new();
// Thread that handles the mqttc side
// including restarting it if the config changes
let thread_cancel = cancel.clone();
let mut thread_config = config;
let thread_incoming_tx = incoming_tx;
let thread_outgoing_tx = outgoing_tx.clone();
set.spawn(async move {
let mut mqtt_config = thread_config.borrow().mqtt.clone();
loop {
break tokio::select! {
_ = thread_cancel.cancelled() => AnyResult::Ok(()),
v = thread_config.wait_for(|config| config.mqtt != mqtt_config).map(|res| res.map(|r| r.clone())) =>
{
mqtt_config = v?.mqtt.clone();
continue;
}
v = async {
run_mqtt_server(thread_incoming_tx.clone(), &mut outgoing_rx, thread_outgoing_tx.clone(), mqtt_config.as_ref().unwrap()).await
}, if mqtt_config.is_some() => {
if let Err(e) = &v {
log::error!("MQTT Client Connection Failed: {:?}", e);
sleep(Duration::from_secs(2)).await;
continue;
}
v
},
};
}
});
Self {
cancel,
outgoing_tx,
set,
// Send the drop message on clean disconnect
}
}
pub async fn subscribe<T: Into<String>>(&self, name: T) -> AnyResult<MqttInstance> {
let (tx, rx) = oneshot();
self.outgoing_tx
.send(MqttRequest::Subscribe(name.into(), tx))
.await?;
rx.await?
}
}
async fn run_mqtt_server(
incomming_tx: BroadcastSender<MqttReply>,
outgoing_rx: &mut MpscReceiver<MqttRequest>,
outgoing_tx: MpscSender<MqttRequest>,
config: &MqttServerConfig,
) -> AnyResult<()> {
let mut mqttoptions = MqttOptions::new("Neolink".to_string(), &config.broker_addr, config.port);
let max_size = 100 * (1024 * 1024);
mqttoptions.set_max_packet_size(max_size, max_size);
// Use TLS if ca path is set
if let Some(ca_path) = &config.ca {
if let Ok(ca) = std::fs::read(ca_path) {
// Use client_auth if they have cert and key
let client_auth = if let Some((cert_path, key_path)) = &config.client_auth {
if let (Ok(cert_buf), Ok(key_buf)) =
(std::fs::read(cert_path), std::fs::read(key_path))
{
Some((cert_buf, Key::RSA(key_buf)))
} else {
error!("Failed to set client tls");
None
}
} else {
None
};
let transport = Transport::Tls(TlsConfiguration::Simple {
ca,
alpn: None,
client_auth,
});
mqttoptions.set_transport(transport);
} else {
error!("Failed to set CA");
}
};
if let Some((username, password)) = &config.credentials {
mqttoptions.set_credentials(username, password);
}
mqttoptions.set_keep_alive(Duration::from_secs(5));
// On unclean disconnect send this
mqttoptions.set_last_will(LastWill::new(
"neolink/status".to_string(),
"offline",
QoS::AtLeastOnce,
true,
));
let (client, mut connection) = AsyncClient::new(mqttoptions, 10);
let client = Arc::new(client);
let send_client = client.clone();
send_client
.publish(
"neolink/status".to_string(),
QoS::AtLeastOnce,
true,
"connected".to_string(),
)
.await?;
loop {
let r = tokio::select! {
v = async {
let msg = outgoing_rx.recv().await.ok_or(anyhow!("All outgoing MQTT channels closed"))?;
match msg {
MqttRequest::Send(msg) => {
send_client.publish(
msg.topic,
QoS::AtLeastOnce,
false,
msg.message,
).await?;
}
MqttRequest::SendRetained(msg) => {
send_client.publish(
msg.topic,
QoS::AtLeastOnce,
true,
msg.message,
).await?;
}
MqttRequest::HangUp(reply) => {
send_client.publish(
"neolink/status".to_string(),
QoS::AtLeastOnce,
true,
"disconnected".to_string(),
).await?;
let _ = reply.send(());
}
MqttRequest::Subscribe(name, reply) => {
let instance = MqttInstance {
name,
incomming_rx: BroadcastStream::new(incomming_tx.subscribe()),
outgoing_tx: outgoing_tx.clone(),
};
let _ = reply.send(Ok(instance));
}
}
AnyResult::Ok(())
} => {
v
},
v = async {
let notification = connection
.poll()
.await
.with_context(|| "MQTT connection dropped")?;
match notification {
Event::Incoming(Incoming::ConnAck(connected)) => {
if ConnectReturnCode::Success == connected.code {
// Publish disconnected at first then wait for connect from the camera insances
client
.publish(
"neolink/status".to_string(),
QoS::AtLeastOnce,
true,
"disconnected",
)
.await?;
// We succesfully logged in. Now ask for the cameras subscription.
client
.subscribe("neolink/".to_string(), QoS::AtMostOnce)
.await?;
}
}
Event::Incoming(Incoming::Publish(published_message)) => {
if let Some(sub_topic) = published_message
.topic
.strip_prefix("neolink/")
{
let _ = incomming_tx
.send(MqttReply {
topic: sub_topic.to_string(),
message: String::from_utf8_lossy(published_message.payload.as_ref())
.into_owned(),
});
}
}
_ => {}
}
AnyResult::Ok(())
} => {
v
},
};
if r.is_ok() {
continue;
}
break r;
}?;
Ok(())
}
impl Drop for Mqtt {
fn drop(&mut self) {
tokio::task::block_in_place(move || {
let _ = tokio::runtime::Handle::current().block_on(async move {
let (tx, rx) = oneshot();
let _ = self.outgoing_tx.send(MqttRequest::HangUp(tx)).await;
let _ = rx.await;
self.cancel.cancel();
while self.set.join_next().await.is_some() {}
AnyResult::Ok(())
});
});
}
}
pub(crate) struct MqttInstance {
outgoing_tx: MpscSender<MqttRequest>,
incomming_rx: BroadcastStream<MqttReply>,
name: String,
}
impl MqttInstance {
pub async fn subscribe<T: Into<String>>(&self, name: T) -> AnyResult<Self> {
let (tx, rx) = oneshot();
self.outgoing_tx
.send(MqttRequest::Subscribe(name.into(), tx))
.await?;
rx.await?
}
pub async fn resubscribe(&self) -> AnyResult<Self> {
let (tx, rx) = oneshot();
self.outgoing_tx
.send(MqttRequest::Subscribe(self.name.clone(), tx))
.await?;
rx.await?
}
pub async fn send_message_with_root_topic(
&self,
root_topic: &str,
sub_topic: &str,
message: &str,
retain: bool,
) -> AnyResult<()> {
let topics = vec![
root_topic.to_string(),
self.name.clone(),
sub_topic.to_string(),
]
.iter()
.filter(|s| !s.is_empty())
.cloned()
.collect::<Vec<_>>();
if retain {
self.outgoing_tx
.send(MqttRequest::SendRetained(MqttReply {
topic: topics.join("/"),
message: message.to_string(),
}))
.await?;
} else {
self.outgoing_tx
.send(MqttRequest::Send(MqttReply {
topic: topics.join("/"),
message: message.to_string(),
}))
.await?;
}
Ok(())
}
pub async fn send_message(
&self,
sub_topic: &str,
message: &str,
retain: bool,
) -> AnyResult<()> {
self.send_message_with_root_topic("neolink", sub_topic, message, retain)
.await?;
Ok(())
}
pub(crate) async fn recv(&mut self) -> AnyResult<MqttReply> {
Ok(loop {
let msg = self
.incomming_rx
.next()
.await
.ok_or(anyhow!("End or client data"))?
.with_context(|| "Clinet stream is too far behind")?;
if self.name.is_empty() {
break msg;
} else {
let topics = msg.topic.split('/').collect::<Vec<_>>();
if topics
.get(2)
.map(|subtopic| *subtopic == self.name)
.unwrap_or(false)
{
break msg;
}
}
})
}
}
#[derive(Clone)]
pub(crate) struct MqttReply {
pub(crate) topic: String,
pub(crate) message: String,
@@ -37,259 +371,9 @@ pub(crate) struct MqttReplyRef<'a> {
pub(crate) message: &'a str,
}
struct MqttReciever {
client: MqttSender,
incoming_tx: Sender<MqttReply>,
name: String,
}
#[derive(Clone)]
pub(crate) struct MqttSender {
client: Arc<AsyncClient>,
name: String,
}
impl MqttSender {
pub async fn send_message_with_root_topic(
&self,
root_topic: &str,
sub_topic: &str,
message: &str,
retain: bool,
) -> Result<(), ClientError> {
self.client
.publish(
format!("{}/{}/{}", root_topic, self.name, sub_topic),
QoS::AtLeastOnce,
retain,
message,
)
.await?;
Ok(())
}
pub async fn send_message(
&self,
sub_topic: &str,
message: &str,
retain: bool,
) -> Result<(), ClientError> {
self.send_message_with_root_topic("neolink", sub_topic, message, retain)
.await?;
Ok(())
}
async fn subscribe(&self) -> Result<(), ClientError> {
self.client
.subscribe(format!("neolink/{}/#", self.name), QoS::AtMostOnce)
.await?;
Ok(())
}
async fn update_status(&self) -> Result<()> {
self.send_message("status", "disconnected", true).await?;
Ok(())
}
pub fn try_send_message(&self, sub_topic: &str, message: &str, retain: bool) -> Result<()> {
self.client
.try_publish(
format!("neolink/{}/{}", self.name, sub_topic),
QoS::AtLeastOnce,
retain,
message,
)
.map_err(|e| e.into())
}
}
impl MqttReciever {
async fn run(&mut self, connection: &mut EventLoop) -> Result<()> {
// This acts as an event loop
let name = self.name.clone();
info!("Starting MQTT Client for {}", name);
loop {
let notification = connection
.poll()
.await
.with_context(|| "MQTT connection dropped")?;
match notification {
Event::Incoming(Incoming::ConnAck(connected)) => {
if ConnectReturnCode::Success == connected.code {
self.client
.update_status()
.await
.context("Failed to update status")?;
// We succesfully logged in. Now ask for the cameras subscription.
self.client
.subscribe()
.await
.context("Failed to subscribe")?;
}
}
Event::Incoming(Incoming::Publish(published_message)) => {
if self.handle_message(published_message).await.is_err() {
error!("Failed to forward messages in mqtt");
}
}
_ => {}
}
}
}
async fn handle_message(&mut self, published_message: Publish) -> Result<()> {
if let Some(sub_topic) = published_message
.topic
.strip_prefix(&format!("neolink/{}/", &self.name))
{
if self
.incoming_tx
.send(MqttReply {
topic: sub_topic.to_string(),
message: String::from_utf8_lossy(published_message.payload.as_ref())
.into_owned(),
})
.await
.is_err()
{
error!("Failed to send messages up the mqtt msg channel");
}
}
Ok(())
}
}
impl Mqtt {
pub(crate) async fn new(config: &MqttConfig, name: &str) -> Self {
let (incoming_tx, incoming) = channel::<MqttReply>(100);
let mut mqttoptions = MqttOptions::new(
format!("Neolink-{}", name),
&config.broker_addr,
config.port,
);
let max_size = 100 * (1024 * 1024);
mqttoptions.set_max_packet_size(max_size, max_size);
// Use TLS if ca path is set
if let Some(ca_path) = &config.ca {
if let Ok(ca) = std::fs::read(ca_path) {
// Use client_auth if they have cert and key
let client_auth = if let Some((cert_path, key_path)) = &config.client_auth {
if let (Ok(cert_buf), Ok(key_buf)) =
(std::fs::read(cert_path), std::fs::read(key_path))
{
Some((cert_buf, Key::RSA(key_buf)))
} else {
error!("Failed to set client tls");
None
}
} else {
None
};
let transport = Transport::Tls(TlsConfiguration::Simple {
ca,
alpn: None,
client_auth,
});
mqttoptions.set_transport(transport);
} else {
error!("Failed to set CA");
}
};
if let Some((username, password)) = &config.credentials {
mqttoptions.set_credentials(username, password);
}
mqttoptions.set_keep_alive(Duration::from_secs(5));
// On unclean disconnect send this
mqttoptions.set_last_will(LastWill::new(
format!("neolink/{}/status", name),
"offline",
QoS::AtLeastOnce,
true,
));
let (client, mut connection) = AsyncClient::new(mqttoptions, 10);
let client = Arc::new(client);
// Start the mqtt server
let mut set = JoinSet::<Result<()>>::new();
let mut reciever = MqttReciever {
incoming_tx,
name: name.to_string(),
client: MqttSender {
client: client.clone(),
name: name.to_string(),
},
};
set.spawn(async move { reciever.run(&mut connection).await });
Self {
client,
name: name.to_string(),
incoming,
set,
// Send the drop message on clean disconnect
drop_message: Some(MqttReply {
topic: "status".to_string(),
message: "offline".to_string(),
}),
}
}
pub fn get_sender(&self) -> MqttSender {
MqttSender {
client: self.client.clone(),
name: self.name.to_string(),
}
}
/// This will also error is the join set errors
pub(crate) async fn poll(&mut self) -> Result<MqttReply> {
let (incoming, set) = (&mut self.incoming, &mut self.set);
tokio::select! {
v = incoming.recv() => v.with_context(|| "Mqtt Polling error"),
v = async {
while let Some(res) = set.join_next().await {
match res {
Err(e) => {
set.abort_all();
return Err(e.into());
}
Ok(Err(e)) => {
set.abort_all();
return Err(e);
}
Ok(Ok(())) => {}
}
}
Err(anyhow!("MQTT background thread dropped without error"))
} => v.with_context(|| "MQTT Threads aborted"),
}
}
}
impl Drop for Mqtt {
fn drop(&mut self) {
if let Some(drop_message) = self.drop_message.as_ref() {
let res = self.get_sender().try_send_message(
&drop_message.topic,
&drop_message.message,
true,
);
if res.is_err() {
error!(
"Failed to send offline message to mqtt: {:?}. Is the MQTT topic name valid?",
res.err().unwrap()
);
}
}
self.set.abort_all();
}
enum MqttRequest {
Send(MqttReply),
SendRetained(MqttReply),
HangUp(OneshotSender<()>),
Subscribe(String, OneshotSender<Result<MqttInstance>>),
}
-1
View File
@@ -2,7 +2,6 @@
//! data using an ordinary std::io::Write interface.
mod factory;
mod sender;
mod server;
mod shared;
-1
View File
@@ -1 +0,0 @@