Try to make all threads close on drop
This commit is contained in:
22 files changed
+270
-167
No files matched your search
@@ -57,7 +57,7 @@ impl BcConnection {
|
||||
let mut rx_thread = JoinSet::<Result<()>>::new();
|
||||
let thread_poll_commander = poll_commander.clone();
|
||||
let thread_cancel = cancel.clone();
|
||||
let handle = tokio::task::spawn_blocking(move || {
|
||||
rx_thread.spawn_blocking(move || {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
@@ -79,16 +79,6 @@ impl BcConnection {
|
||||
log::trace!("PollSender Bc {:?}", result);
|
||||
result
|
||||
});
|
||||
let thread_cancel = cancel.clone();
|
||||
rx_thread.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => Result::Ok(()),
|
||||
v = async {
|
||||
handle.await??;
|
||||
Ok(())
|
||||
} => v
|
||||
}
|
||||
});
|
||||
|
||||
let thread_cancel = cancel.clone();
|
||||
rx_thread.spawn(async move {
|
||||
@@ -207,8 +197,15 @@ impl BcConnection {
|
||||
|
||||
impl Drop for BcConnection {
|
||||
fn drop(&mut self) {
|
||||
log::debug!("BcConnection::drop Cancel");
|
||||
log::trace!("Drop BcConnection");
|
||||
self.cancel.cancel();
|
||||
tokio::task::block_in_place(move || {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async move {
|
||||
let _ = self.shutdown().await;
|
||||
Result::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped BcConnection");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1062,7 +1062,15 @@ impl Discoverer {
|
||||
|
||||
impl Drop for Discoverer {
|
||||
fn drop(&mut self) {
|
||||
log::trace!("Drop Discoverer");
|
||||
self.cancel.cancel();
|
||||
tokio::task::block_in_place(move || {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async move {
|
||||
while self.handle.get_mut().join_next().await.is_some() {}
|
||||
Result::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped Discoverer");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ use std::task::{Context, Poll};
|
||||
use tokio::sync::mpsc::channel;
|
||||
use tokio::{
|
||||
net::UdpSocket,
|
||||
task::JoinHandle,
|
||||
task::JoinSet,
|
||||
time::{interval, sleep, Duration, Instant, Interval},
|
||||
};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
@@ -264,15 +264,21 @@ impl AckLatency {
|
||||
pub(crate) struct UdpPayloadSource {
|
||||
inner_stream: ReceiverStream<IoResult<Vec<u8>>>,
|
||||
inner_sink: PollSender<Vec<u8>>,
|
||||
handle: JoinHandle<Result<()>>,
|
||||
set: JoinSet<Result<()>>,
|
||||
cancel_token: CancellationToken,
|
||||
}
|
||||
|
||||
impl Drop for UdpPayloadSource {
|
||||
fn drop(&mut self) {
|
||||
log::debug!("UdpPayloadSource::drop Cancel");
|
||||
log::trace!("Drop UdpPayloadSource");
|
||||
self.cancel_token.cancel();
|
||||
self.handle.abort();
|
||||
tokio::task::block_in_place(|| {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async {
|
||||
while self.set.join_next().await.is_some() {}
|
||||
Result::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped UdpPayloadSource");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,6 +303,7 @@ struct UdpPayloadInner {
|
||||
resend_interval: Interval,
|
||||
ack_latency: AckLatency,
|
||||
cancel: CancellationToken,
|
||||
set: JoinSet<Result<()>>,
|
||||
}
|
||||
impl UdpPayloadInner {
|
||||
fn new(
|
||||
@@ -306,6 +313,7 @@ impl UdpPayloadInner {
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
) -> Self {
|
||||
let mut set = JoinSet::new();
|
||||
let camera_addr = inner.addr;
|
||||
let cancel = CancellationToken::new();
|
||||
// Data in this needs to be passed into the socket regularly
|
||||
@@ -327,7 +335,7 @@ impl UdpPayloadInner {
|
||||
let thread_camera_id = camera_id;
|
||||
const TIME_OUT: u64 = 10;
|
||||
let mut recv_timeout = Box::pin(sleep(Duration::from_secs(TIME_OUT)));
|
||||
tokio::task::spawn_blocking(move || {
|
||||
set.spawn_blocking(move || {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
@@ -408,7 +416,7 @@ impl UdpPayloadInner {
|
||||
let (ack_tx, mut ack_rx) = channel(1000);
|
||||
let thread_camera_id = camera_id;
|
||||
let ack_socket_in_tx = socket_in_tx.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
set.spawn_blocking(move || {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
@@ -451,7 +459,7 @@ impl UdpPayloadInner {
|
||||
let thread_sender = socket_in_tx.clone();
|
||||
let mut thread_interval = interval(Duration::from_secs(1));
|
||||
let thread_cancel = cancel.clone();
|
||||
tokio::task::spawn(async move {
|
||||
set.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => Result::Ok(()),
|
||||
v = async {
|
||||
@@ -494,6 +502,7 @@ impl UdpPayloadInner {
|
||||
resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms
|
||||
ack_latency: Default::default(),
|
||||
cancel,
|
||||
set,
|
||||
}
|
||||
}
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
@@ -623,12 +632,25 @@ impl UdpPayloadInner {
|
||||
}
|
||||
self.ack_latency.feed_ack();
|
||||
}
|
||||
|
||||
async fn shutdown(&mut self) -> Result<()> {
|
||||
self.cancel.cancel();
|
||||
while self.set.join_next().await.is_some() {}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for UdpPayloadInner {
|
||||
fn drop(&mut self) {
|
||||
log::debug!("UdpPayloadInner::drop Cancel");
|
||||
log::trace!("Drop UdpPayloadInner");
|
||||
self.cancel.cancel();
|
||||
tokio::task::block_in_place(move || {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async move {
|
||||
self.shutdown().await?;
|
||||
Result::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped UdpPayloadInner");
|
||||
}
|
||||
}
|
||||
impl UdpPayloadSource {
|
||||
@@ -646,7 +668,8 @@ impl UdpPayloadSource {
|
||||
let cancel_token = tokio_util::sync::CancellationToken::new();
|
||||
|
||||
let thread_cancel_token = cancel_token.clone();
|
||||
let handle = tokio::task::spawn_blocking(move || {
|
||||
let mut set = JoinSet::new();
|
||||
set.spawn_blocking(move || {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
@@ -686,7 +709,7 @@ impl UdpPayloadSource {
|
||||
UdpPayloadSource {
|
||||
inner_stream: ReceiverStream::new(inner_stream),
|
||||
inner_sink: PollSender::new(inner_sink),
|
||||
handle,
|
||||
set,
|
||||
cancel_token,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::bc::{model::*, xml::*};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::mpsc::{channel, error::TryRecvError, Receiver};
|
||||
use tokio::task::JoinSet;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Motion Status that the callback can send
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -20,6 +21,7 @@ pub enum MotionStatus {
|
||||
/// When this object is dropped the motion events are stopped
|
||||
pub struct MotionData {
|
||||
handle: JoinSet<Result<()>>,
|
||||
cancel: CancellationToken,
|
||||
rx: Receiver<Result<MotionStatus>>,
|
||||
last_update: MotionStatus,
|
||||
}
|
||||
@@ -212,60 +214,68 @@ impl BcCamera {
|
||||
|
||||
let mut set = JoinSet::new();
|
||||
let channel_id = self.channel_id;
|
||||
let cancel = CancellationToken::new();
|
||||
let thread_cancel = cancel.clone();
|
||||
set.spawn(async move {
|
||||
let mut sub = connection.subscribe_to_id(MSG_ID_MOTION).await?;
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => Result::Ok(()),
|
||||
v = async {
|
||||
let mut sub = connection.subscribe_to_id(MSG_ID_MOTION).await?;
|
||||
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
let msg = sub.recv().await;
|
||||
let status = match msg {
|
||||
Ok(motion_msg) => {
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
alarm_event_list: Some(alarm_event_list),
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
let msg = sub.recv().await;
|
||||
let status = match msg {
|
||||
Ok(motion_msg) => {
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
alarm_event_list: Some(alarm_event_list),
|
||||
..
|
||||
})),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = motion_msg.body
|
||||
{
|
||||
let mut result = MotionStatus::NoChange(Instant::now());
|
||||
for alarm_event in &alarm_event_list.alarm_events {
|
||||
if alarm_event.channel_id == channel_id {
|
||||
if alarm_event.status != "none"
|
||||
|| alarm_event
|
||||
.ai_type
|
||||
.as_ref()
|
||||
.map(|ai_type| ai_type != "none")
|
||||
.unwrap_or(false)
|
||||
{
|
||||
result = MotionStatus::Start(Instant::now());
|
||||
break;
|
||||
} else {
|
||||
result = MotionStatus::Stop(Instant::now());
|
||||
break;
|
||||
}) = motion_msg.body
|
||||
{
|
||||
let mut result = MotionStatus::NoChange(Instant::now());
|
||||
for alarm_event in &alarm_event_list.alarm_events {
|
||||
if alarm_event.channel_id == channel_id {
|
||||
if alarm_event.status != "none"
|
||||
|| alarm_event
|
||||
.ai_type
|
||||
.as_ref()
|
||||
.map(|ai_type| ai_type != "none")
|
||||
.unwrap_or(false)
|
||||
{
|
||||
result = MotionStatus::Start(Instant::now());
|
||||
break;
|
||||
} else {
|
||||
result = MotionStatus::Stop(Instant::now());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
Ok(MotionStatus::NoChange(Instant::now()))
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
Ok(MotionStatus::NoChange(Instant::now()))
|
||||
// On connection drop we stop
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
|
||||
if tx.send(status).await.is_err() {
|
||||
// Motion reciever has been dropped
|
||||
break;
|
||||
}
|
||||
}
|
||||
// On connection drop we stop
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
|
||||
if tx.send(status).await.is_err() {
|
||||
// Motion reciever has been dropped
|
||||
break;
|
||||
}
|
||||
Ok(())
|
||||
} => v,
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
Ok(MotionData {
|
||||
handle: set,
|
||||
cancel,
|
||||
rx,
|
||||
last_update: MotionStatus::NoChange(Instant::now()),
|
||||
})
|
||||
@@ -274,6 +284,14 @@ impl BcCamera {
|
||||
|
||||
impl Drop for MotionData {
|
||||
fn drop(&mut self) {
|
||||
self.handle.abort_all();
|
||||
log::trace!("Drop MotionData");
|
||||
self.cancel.cancel();
|
||||
tokio::task::block_in_place(move || {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async move {
|
||||
while self.handle.join_next().await.is_some() {}
|
||||
Result::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped MotionData");
|
||||
}
|
||||
}
|
||||
@@ -88,11 +88,13 @@ impl StreamData {
|
||||
|
||||
impl Drop for StreamData {
|
||||
fn drop(&mut self) {
|
||||
log::trace!("Drop StreamData");
|
||||
tokio::task::block_in_place(|| {
|
||||
tokio::runtime::Handle::current().block_on(async {
|
||||
let _ = self.shutdown().await;
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped MotionData");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,5 @@ pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
.expect("Should be UTF8");
|
||||
println!("{}", ser);
|
||||
|
||||
camera.shutdown().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -52,11 +52,6 @@ impl NeoInstance {
|
||||
instance_rx.await?
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
let _ = self.camera_control.send(NeoCamCommand::HangUp).await;
|
||||
self.cancel.cancelled().await
|
||||
}
|
||||
|
||||
/// This is a helpful convience function
|
||||
///
|
||||
/// Given an async task it will:
|
||||
|
||||
@@ -93,8 +93,9 @@ impl NeoCamMdThread {
|
||||
|
||||
impl Drop for NeoCamMdThread {
|
||||
fn drop(&mut self) {
|
||||
log::debug!("NeoCamMdThread::drop Cancel");
|
||||
log::trace!("Drop NeoCamMdThread");
|
||||
self.cancel.cancel();
|
||||
log::trace!("Dropped NeoCamMdThread");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+27
-14
@@ -6,10 +6,13 @@
|
||||
//! Clonable interface to share amongst threadsanyhow::anyhow;
|
||||
use futures::stream::StreamExt;
|
||||
use std::sync::Weak;
|
||||
use tokio::sync::{
|
||||
mpsc::{channel as mpsc, Sender as MpscSender},
|
||||
oneshot::{channel as oneshot, Sender as OneshotSender},
|
||||
watch::{channel as watch, Receiver as WatchReceiver, Sender as WatchSender},
|
||||
use tokio::{
|
||||
sync::{
|
||||
mpsc::{channel as mpsc, Sender as MpscSender},
|
||||
oneshot::{channel as oneshot, Sender as OneshotSender},
|
||||
watch::{channel as watch, Receiver as WatchReceiver, Sender as WatchSender},
|
||||
},
|
||||
task::JoinSet,
|
||||
};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
@@ -38,6 +41,7 @@ pub(crate) struct NeoCam {
|
||||
config_watch: WatchSender<CameraConfig>,
|
||||
commander: MpscSender<NeoCamCommand>,
|
||||
camera_watch: WatchReceiver<Weak<BcCamera>>,
|
||||
set: JoinSet<AnyResult<()>>,
|
||||
}
|
||||
|
||||
impl NeoCam {
|
||||
@@ -48,11 +52,13 @@ impl NeoCam {
|
||||
let (stream_request_tx, stream_request_rx) = mpsc(100);
|
||||
let (md_request_tx, md_request_rx) = mpsc(100);
|
||||
|
||||
let me = Self {
|
||||
let set = JoinSet::new();
|
||||
let mut me = Self {
|
||||
cancel: CancellationToken::new(),
|
||||
config_watch: watch_config_tx,
|
||||
commander: commander_tx.clone(),
|
||||
camera_watch: camera_watch_rx.clone(),
|
||||
set,
|
||||
};
|
||||
|
||||
// This thread recieves messages from the instances
|
||||
@@ -65,7 +71,7 @@ impl NeoCam {
|
||||
let strict = config.strict;
|
||||
let thread_commander_tx = commander_tx.clone();
|
||||
let thread_watch_config_rx = watch_config_rx.clone();
|
||||
tokio::task::spawn(async move {
|
||||
me.set.spawn(async move {
|
||||
let thread_cancel = sender_cancel.clone();
|
||||
let res = tokio::select! {
|
||||
_ = sender_cancel.cancelled() => {
|
||||
@@ -151,13 +157,13 @@ impl NeoCam {
|
||||
let thread_watch_config_rx = watch_config_rx.clone();
|
||||
let mut cam_thread =
|
||||
NeoCamThread::new(thread_watch_config_rx, camera_watch_tx, me.cancel.clone()).await;
|
||||
tokio::task::spawn(async move { cam_thread.run().await });
|
||||
me.set.spawn(async move { cam_thread.run().await });
|
||||
|
||||
// This thread maintains the streams
|
||||
let stream_instance = instance.subscribe().await?;
|
||||
let stream_cancel = me.cancel.clone();
|
||||
let mut stream_thread = NeoCamStreamThread::new(stream_request_rx, stream_instance).await?;
|
||||
tokio::task::spawn(async move {
|
||||
me.set.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = stream_cancel.cancelled() => AnyResult::Ok(()),
|
||||
v = stream_thread.run() => v,
|
||||
@@ -168,7 +174,7 @@ impl NeoCam {
|
||||
let md_instance = instance.subscribe().await?;
|
||||
let md_cancel = me.cancel.clone();
|
||||
let mut md_thread = NeoCamMdThread::new(md_request_rx, md_instance).await?;
|
||||
tokio::task::spawn(async move {
|
||||
me.set.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = md_cancel.cancelled() => AnyResult::Ok(()),
|
||||
v = md_thread.run() => v,
|
||||
@@ -179,7 +185,7 @@ impl NeoCam {
|
||||
let report_instance = instance.subscribe().await?;
|
||||
let report_cancel = me.cancel.clone();
|
||||
let report_name = config.name.clone();
|
||||
tokio::task::spawn(async move {
|
||||
me.set.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = report_cancel.cancelled() => {
|
||||
AnyResult::Ok(())
|
||||
@@ -227,9 +233,10 @@ impl NeoCam {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
async fn shutdown(&mut self) -> AnyResult<()> {
|
||||
let _ = self.commander.send(NeoCamCommand::HangUp).await;
|
||||
self.cancel.cancelled().await
|
||||
self.set.shutdown().await;
|
||||
AnyResult::Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn get_config_watch(&self) -> &WatchSender<CameraConfig> {
|
||||
@@ -239,7 +246,13 @@ impl NeoCam {
|
||||
|
||||
impl Drop for NeoCam {
|
||||
fn drop(&mut self) {
|
||||
log::debug!("Cancel:: NeoCam::drop");
|
||||
self.cancel.cancel();
|
||||
log::trace!("Drop NeoCam");
|
||||
tokio::task::block_in_place(move || {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async move {
|
||||
let _ = self.shutdown().await;
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped NeoCam");
|
||||
}
|
||||
}
|
||||
+38
-33
@@ -5,15 +5,18 @@ use std::{
|
||||
collections::{hash_map::Entry, HashMap},
|
||||
sync::Arc,
|
||||
};
|
||||
use tokio::sync::{
|
||||
mpsc::{channel as mpsc, Sender as MpscSender},
|
||||
oneshot::{channel as oneshot, Sender as OneshotSender},
|
||||
watch::{channel as watch, Receiver as WatchReceiver},
|
||||
use tokio::{
|
||||
sync::{
|
||||
mpsc::{channel as mpsc, Sender as MpscSender},
|
||||
oneshot::{channel as oneshot, Sender as OneshotSender},
|
||||
watch::{channel as watch, Receiver as WatchReceiver},
|
||||
},
|
||||
task::JoinSet,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{NeoCam, NeoInstance};
|
||||
use crate::{config::Config, Result};
|
||||
use crate::{config::Config, AnyResult, Result};
|
||||
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum NeoReactorCommand {
|
||||
@@ -28,40 +31,32 @@ enum NeoReactorCommand {
|
||||
pub(crate) struct NeoReactor {
|
||||
cancel: CancellationToken,
|
||||
commander: MpscSender<NeoReactorCommand>,
|
||||
arc: Arc<()>,
|
||||
set: Option<Arc<JoinSet<AnyResult<()>>>>,
|
||||
}
|
||||
|
||||
impl NeoReactor {
|
||||
pub(crate) async fn new(config: Config) -> Self {
|
||||
let (commad_tx, mut command_rx) = mpsc(100);
|
||||
let me = Self {
|
||||
cancel: CancellationToken::new(),
|
||||
commander: commad_tx,
|
||||
arc: Arc::new(()),
|
||||
};
|
||||
|
||||
let cancel = CancellationToken::new();
|
||||
let (config_tx, _) = watch(config);
|
||||
let mut set = JoinSet::new();
|
||||
|
||||
let cancel = me.cancel.clone();
|
||||
let cancel2 = me.cancel.clone();
|
||||
let cancel1 = cancel.clone();
|
||||
let cancel2 = cancel.clone();
|
||||
let config_tx = Arc::new(config_tx);
|
||||
tokio::task::spawn(async move {
|
||||
set.spawn(async move {
|
||||
let mut instances: HashMap<String, NeoCam> = Default::default();
|
||||
|
||||
let r = tokio::select! {
|
||||
_ = cancel.cancelled() => {
|
||||
for instance in instances.values() {
|
||||
instance.shutdown().await;
|
||||
}
|
||||
_ = cancel1.cancelled() => {
|
||||
instances.clear();
|
||||
Ok(())
|
||||
},
|
||||
v = async {
|
||||
while let Some(command) = command_rx.recv().await {
|
||||
match command {
|
||||
NeoReactorCommand::HangUp => {
|
||||
for instance in instances.values() {
|
||||
instance.shutdown().await;
|
||||
}
|
||||
instances.clear();
|
||||
log::debug!("Cancel:: NeoReactorCommand::HangUp");
|
||||
cancel2.cancel();
|
||||
return Result::<(), anyhow::Error>::Ok(());
|
||||
@@ -96,13 +91,14 @@ impl NeoReactor {
|
||||
NeoReactorCommand::UpdateConfig(new_conf, reply) => {
|
||||
// Shutdown or Notify instances of a change
|
||||
let mut names = new_conf.cameras.iter().filter_map(|cam_conf| cam_conf.enabled.then(|| (cam_conf.name.clone(), cam_conf.clone()))).collect::<HashMap<_,_>>();
|
||||
// Remove those no longer in the config
|
||||
instances.retain(|name, _| names.contains_key(name));
|
||||
for (name, instance) in instances.iter() {
|
||||
if let Some(conf) = names.remove(name) {
|
||||
let _ = instance.get_config_watch().send_replace(conf);
|
||||
} else {
|
||||
instance.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
// Set the new conf
|
||||
let _ = config_tx.send_replace(new_conf);
|
||||
// Reply that we are done
|
||||
@@ -116,7 +112,11 @@ impl NeoReactor {
|
||||
r
|
||||
});
|
||||
|
||||
me
|
||||
Self {
|
||||
cancel,
|
||||
commander: commad_tx,
|
||||
set: Some(Arc::new(set)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get camera by name but do not create
|
||||
@@ -148,18 +148,23 @@ impl NeoReactor {
|
||||
|
||||
sender_rx.await?
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
let _ = self.commander.send(NeoReactorCommand::HangUp).await;
|
||||
self.cancel.cancelled().await;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NeoReactor {
|
||||
fn drop(&mut self) {
|
||||
if Arc::strong_count(&self.arc) == 1 {
|
||||
log::debug!("Cancel:: NeoReactor::drop");
|
||||
self.cancel.cancel();
|
||||
if let Some(set) = self.set.take() {
|
||||
if let Ok(mut set) = Arc::try_unwrap(set) {
|
||||
log::trace!("Drop NeoReactor");
|
||||
self.cancel.cancel();
|
||||
tokio::task::block_in_place(move || {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async move {
|
||||
let _ = self.commander.send(NeoReactorCommand::HangUp).await;
|
||||
while set.join_next().await.is_some() {}
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped NeoReactor");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ use tokio::{
|
||||
oneshot::Sender as OneshotSender,
|
||||
watch::{channel as watch, Receiver as WatchReceiver, Sender as WatchSender},
|
||||
},
|
||||
task::JoinHandle,
|
||||
task::{JoinHandle, JoinSet},
|
||||
time::{timeout, Duration},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
@@ -228,6 +228,7 @@ pub(crate) struct UseCounter {
|
||||
value: WatchReceiver<u32>,
|
||||
notifier_tx: MpscSender<bool>,
|
||||
cancel: CancellationToken,
|
||||
set: JoinSet<AnyResult<()>>,
|
||||
}
|
||||
|
||||
impl UseCounter {
|
||||
@@ -235,9 +236,10 @@ impl UseCounter {
|
||||
let (notifier_tx, mut notifier) = mpsc(100);
|
||||
let (value_tx, value) = watch(0);
|
||||
let cancel = CancellationToken::new();
|
||||
let mut set = JoinSet::new();
|
||||
|
||||
let thread_cancel = cancel.clone();
|
||||
tokio::task::spawn(async move {
|
||||
set.spawn(async move {
|
||||
let r = tokio::select! {
|
||||
_ = thread_cancel.cancelled() => {
|
||||
AnyResult::Ok(())
|
||||
@@ -264,6 +266,7 @@ impl UseCounter {
|
||||
value,
|
||||
notifier_tx,
|
||||
cancel,
|
||||
set,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,8 +283,15 @@ impl UseCounter {
|
||||
|
||||
impl Drop for UseCounter {
|
||||
fn drop(&mut self) {
|
||||
log::debug!("UseCounter::drop Cancel");
|
||||
log::trace!("Drop UseCounter");
|
||||
self.cancel.cancel();
|
||||
tokio::task::block_in_place(move || {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async move {
|
||||
while self.set.join_next().await.is_some() {}
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped UseCounter");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -698,7 +708,16 @@ impl StreamData {
|
||||
|
||||
impl Drop for StreamData {
|
||||
fn drop(&mut self) {
|
||||
log::debug!("Cancel:: StreamData::drop");
|
||||
log::trace!("Drop StreamData");
|
||||
self.cancel.cancel();
|
||||
tokio::task::block_in_place(move || {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async move {
|
||||
if let Some(h) = self.handle.take() {
|
||||
let _ = h.await;
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped StreamData");
|
||||
}
|
||||
}
|
||||
+46
-21
@@ -8,10 +8,11 @@ use tokio::{
|
||||
self,
|
||||
mpsc::{channel, Sender},
|
||||
},
|
||||
task::{self, JoinSet},
|
||||
task::JoinSet,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::common::VidFormat;
|
||||
use crate::{common::VidFormat, AnyResult};
|
||||
|
||||
#[derive(Debug)]
|
||||
enum GstControl {
|
||||
@@ -23,6 +24,7 @@ pub(super) struct GstSender {
|
||||
sender: Sender<GstControl>,
|
||||
set: JoinSet<Result<()>>,
|
||||
finished: sync::oneshot::Receiver<Result<()>>,
|
||||
cancel: CancellationToken,
|
||||
}
|
||||
|
||||
impl GstSender {
|
||||
@@ -56,6 +58,20 @@ impl GstSender {
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for GstSender {
|
||||
fn drop(&mut self) {
|
||||
log::trace!("Drop GstSender");
|
||||
self.cancel.cancel();
|
||||
tokio::task::block_in_place(move || {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async move {
|
||||
while self.set.join_next().await.is_some() {}
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped GstSender");
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn from_input<T: AsRef<Path>>(
|
||||
format: VidFormat,
|
||||
out_file: T,
|
||||
@@ -67,42 +83,51 @@ pub(super) async fn from_input<T: AsRef<Path>>(
|
||||
async fn output(pipeline: Pipeline) -> Result<GstSender> {
|
||||
let source = get_source(&pipeline)?;
|
||||
let (sender, mut reciever) = channel::<GstControl>(100);
|
||||
let mut set = JoinSet::new();
|
||||
let mut set = JoinSet::<AnyResult<()>>::new();
|
||||
let cancel = CancellationToken::new();
|
||||
let thread_cancel = cancel.clone();
|
||||
set.spawn(async move {
|
||||
while let Some(control) = reciever.recv().await {
|
||||
tokio::task::yield_now().await;
|
||||
match control {
|
||||
GstControl::Data(buf) => {
|
||||
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(&buf);
|
||||
tokio::select!{
|
||||
_ = thread_cancel.cancelled() => Result::Ok(()),
|
||||
v = async {
|
||||
while let Some(control) = reciever.recv().await {
|
||||
tokio::task::yield_now().await;
|
||||
match control {
|
||||
GstControl::Data(buf) => {
|
||||
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(&buf);
|
||||
}
|
||||
source.push_buffer(gst_buf).map_err(|e| anyhow!("Streamer Error: {e:?}"))?;
|
||||
}
|
||||
GstControl::Eos => {
|
||||
source.end_of_stream().map_err(|e| anyhow!("Streamer Error: {e:?}"))?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
source.push_buffer(gst_buf)?;
|
||||
}
|
||||
GstControl::Eos => {
|
||||
source.end_of_stream()?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
} => v,
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
let (tx, finished) = sync::oneshot::channel();
|
||||
task::spawn_blocking(move || {
|
||||
set.spawn_blocking(move || {
|
||||
let res = start_pipeline(pipeline);
|
||||
if let Err(e) = &res {
|
||||
log::error!("Failed to run pipeline: {:?}", e);
|
||||
}
|
||||
tx.send(res)
|
||||
let _ = tx.send(res);
|
||||
Ok(())
|
||||
});
|
||||
|
||||
Ok(GstSender {
|
||||
sender,
|
||||
set,
|
||||
finished,
|
||||
cancel,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,5 @@ pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
buffer.write_all(jpeg_data.as_slice()).await?;
|
||||
}
|
||||
|
||||
camera.shutdown().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -132,7 +132,5 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
neo_reactor.shutdown().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -92,6 +92,7 @@ impl Mqtt {
|
||||
|
||||
impl Drop for Mqtt {
|
||||
fn drop(&mut self) {
|
||||
log::trace!("Drop MQTT");
|
||||
tokio::task::block_in_place(move || {
|
||||
let _ = tokio::runtime::Handle::current().block_on(async move {
|
||||
let (tx, rx) = oneshot();
|
||||
@@ -104,6 +105,7 @@ impl Drop for Mqtt {
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
});
|
||||
log::trace!("Dropped MQTT");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,5 @@ pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
println!("{}", pir_ser);
|
||||
}
|
||||
|
||||
camera.shutdown().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -122,7 +122,5 @@ pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
}
|
||||
};
|
||||
|
||||
camera.shutdown().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -35,7 +35,5 @@ pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
})
|
||||
.await?;
|
||||
|
||||
camera.shutdown().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+7
-4
@@ -908,6 +908,7 @@ async fn handle_data<T: Stream<Item = Result<StreamData, E>> + Unpin, E>(
|
||||
mut data_rx: T,
|
||||
) -> Result<()> {
|
||||
if let Some(app) = app {
|
||||
let mut set = JoinSet::<AnyResult<()>>::new();
|
||||
let mut last_ft: Option<Duration> = None;
|
||||
let mut ft = Duration::ZERO;
|
||||
let mut last_rt: Option<Duration> = None;
|
||||
@@ -949,7 +950,7 @@ async fn handle_data<T: Stream<Item = Result<StreamData, E>> + Unpin, E>(
|
||||
let thread_app = app.clone();
|
||||
let thread_rt = rt;
|
||||
let thread_ft = ft;
|
||||
tokio::task::spawn(async move {
|
||||
set.spawn(async move {
|
||||
check_live(&thread_app)?; // Stop if appsrc is dropped
|
||||
if ft > (rt + Duration::from_millis(50)) {
|
||||
let delta = ft - rt;
|
||||
@@ -971,13 +972,15 @@ async fn handle_data<T: Stream<Item = Result<StreamData, E>> + Unpin, E>(
|
||||
|
||||
log::trace!("Pushing Data");
|
||||
let appsrc = thread_app.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut inner_set = JoinSet::new();
|
||||
inner_set.spawn_blocking(move || {
|
||||
appsrc
|
||||
.push_buffer(buf.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await??;
|
||||
});
|
||||
inner_set.join_next().await.unwrap()??;
|
||||
while inner_set.join_next().await.is_some() {}
|
||||
log::trace!(" Pushed Data");
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
|
||||
@@ -40,7 +40,5 @@ pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
})
|
||||
.await?;
|
||||
|
||||
camera.shutdown().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+10
-5
@@ -1,3 +1,4 @@
|
||||
use crate::AnyResult;
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use crossbeam_channel::{bounded, Receiver, Sender};
|
||||
use gstreamer::{
|
||||
@@ -5,30 +6,34 @@ use gstreamer::{
|
||||
Pipeline, ResourceError, State,
|
||||
};
|
||||
use gstreamer_app::{AppSink, AppSinkCallbacks};
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
use byte_slice_cast::*;
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub(super) fn from_input(
|
||||
input_src: &str,
|
||||
volume: f32,
|
||||
block_align: u16,
|
||||
sample_rate: u16,
|
||||
) -> Result<Receiver<Vec<u8>>> {
|
||||
) -> Result<(JoinSet<AnyResult<()>>, Receiver<Vec<u8>>)> {
|
||||
let pipeline = create_pipeline(input_src, volume, block_align, sample_rate)?;
|
||||
input(pipeline)
|
||||
}
|
||||
|
||||
fn input(pipeline: Pipeline) -> Result<Receiver<Vec<u8>>> {
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn input(pipeline: Pipeline) -> Result<(JoinSet<AnyResult<()>>, Receiver<Vec<u8>>)> {
|
||||
let appsink = get_sink(&pipeline)?;
|
||||
let (tx, rx) = bounded(30);
|
||||
|
||||
let mut set = JoinSet::<AnyResult<()>>::new();
|
||||
set_data_channel(&appsink, tx);
|
||||
|
||||
std::thread::spawn(move || {
|
||||
set.spawn_blocking(move || {
|
||||
let _ = start_pipeline(pipeline);
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
|
||||
Ok(rx)
|
||||
Ok((set, rx))
|
||||
}
|
||||
|
||||
fn start_pipeline(pipeline: Pipeline) -> Result<()> {
|
||||
|
||||
+3
-2
@@ -70,7 +70,7 @@ pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
));
|
||||
}
|
||||
|
||||
let rx = match (&opt.file_path, &opt.microphone) {
|
||||
let (mut set, rx) = match (&opt.file_path, &opt.microphone) {
|
||||
(Some(path), false) => gst::from_input(
|
||||
&format!(
|
||||
"filesrc location={}",
|
||||
@@ -98,7 +98,8 @@ pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
.await
|
||||
.context("Talk stream ended early")?;
|
||||
|
||||
camera.shutdown().await;
|
||||
drop(rx);
|
||||
while set.join_next().await.is_some() {}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user