pub fn spawn_detection_threads(
sensors: Arc<Vec<Mutex<MotionSensor>>>,
stop_command: Arc<CancellationToken>,
)Examples found in repository?
examples/multiple-sensors/main.rs (line 83)
13async fn main() {
14 // channel for sensor data
15 #[allow(clippy::type_complexity)]
16 let (detections_channel_sender, mut detections_channel_receiver): (
17 Sender<(String, SystemTime)>,
18 Receiver<(String, SystemTime)>,
19 ) = mpsc::channel(10);
20
21 //
22 // sensors initialization - check README for more details about sensor parameters
23 // in this example we initialize 4 motion sensors
24 //
25 let sensors_list = vec![
26 // Bedroom
27 MotionSensor::new(
28 String::from("SensorBedroom"), // name
29 6, // gpio PIN number
30 100, // sensor refresh rate in miliseconds
31 500, // sensor motion time period in miliseconds
32 5, // sensor minimal triggering number
33 detections_channel_sender.clone(), // channel where sensor thread will be sending detections
34 None, // None for real GPIO usage, Some(Vec<u64>) for unit tests, please check tests/* */
35 ),
36 // Main door
37 MotionSensor::new(
38 String::from("MainDoorSlow"),
39 25,
40 100,
41 1000,
42 4,
43 detections_channel_sender.clone(),
44 None,
45 ),
46 // Kitchen
47 MotionSensor::new(
48 String::from("KitchenFast"),
49 20,
50 20,
51 1000,
52 4,
53 detections_channel_sender.clone(),
54 None,
55 ),
56 // Garage
57 MotionSensor::new(
58 String::from("Garage"),
59 16,
60 100,
61 500,
62 5,
63 detections_channel_sender,
64 None,
65 ),
66 ];
67
68 // starting detector in the background
69 let mut sensors = Vec::new();
70
71 // bulding list of sensors to use it later
72 sensors_list.into_iter().for_each(|sensor| {
73 sensors.push(Mutex::new(sensor));
74 });
75
76 let sensors = Arc::new(sensors);
77
78 // cancellation token which can be later used to stop sensors threads
79 let token = Arc::new(CancellationToken::new());
80
81 // helper function to run important threads (via tokio::spawn)
82 // you don't have deal this is you don't want to - just leave it as it is
83 spawn_detection_threads(sensors, token.clone());
84
85 //
86 // main loop: here we put logic to handle valid detections, place your code here
87 //
88 loop {
89 if let Ok(detection_message) = detections_channel_receiver.try_recv() {
90 // valid detection received
91 // each "valid" detection contains the sensor name and time of detection as SystemTime
92 let (detection_name, detection_time) = detection_message;
93
94 println!("detection happened, sensor: {detection_name}, time: {detection_time:?} ");
95 //
96 // put your action here like alarm or turn on/off light
97 // to interact with rest GPIOs you can check rppal lib examples here: https://github.com/golemparts/rppal/tree/master/examples
98 //
99 }
100 sleep(Duration::from_millis(1)).await;
101 }
102}