-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathonewire.rs
2103 lines (1973 loc) · 86.3 KB
/
onewire.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::database::{CommandCode, DbTask};
use crate::ethlcd::{BeepMethod, EthLcd};
use crate::lcdproc::{LcdTask, LcdTaskCommand};
use crate::rfid::RfidTag;
use humantime::format_duration;
use ini::Ini;
use serde::ser::SerializeSeq;
use serde::{Deserialize, Serialize, Serializer};
use simplelog::*;
use std::collections::HashMap;
use std::fmt;
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use std::io::BufReader;
use std::io::{Read, Seek, SeekFrom, Write};
use std::net::TcpStream;
use std::ops::Add;
use std::path::Path;
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Receiver;
use std::sync::mpsc::Sender;
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
//family codes for devices
pub const FAMILY_CODE_DS2413: u8 = 0x3a;
pub const FAMILY_CODE_DS2408: u8 = 0x29;
pub const FAMILY_CODE_DS18S20: u8 = 0x10;
pub const FAMILY_CODE_DS18B20: u8 = 0x28;
pub const FAMILY_CODE_DS2438: u8 = 0x26;
pub const DS2408_INITIAL_STATE: u8 = 0xff;
//timing constants
pub const DEFAULT_PIR_HOLD_SECS: f32 = 120.0; //2min for PIR sensors
pub const DEFAULT_SWITCH_HOLD_SECS: f32 = 3600.0; //1hour for wall-switches
pub const DEFAULT_PIR_PROLONG_SECS: f32 = 900.0; //15min prolonging in override_mode
pub const MIN_TOGGLE_DELAY_SECS: f32 = 1.0; //1sec flip-flop protection: minimum delay between toggles
pub const ENTRY_LIGHT_PROLONG_SECS: f32 = 600.0; //10min prolonging for entry lights
pub static W1_ROOT_PATH: &str = "/sys/bus/w1/devices";
//yeelight consts
pub const YEELIGHT_TCP_PORT: u16 = 55443;
static YEELIGHT_METHOD_SET_POWER: &str = "set_power"; //method value name for powering on/off
static YEELIGHT_EFFECT: &str = "smooth"; //default effect for turning on/off
pub const YEELIGHT_DURATION_MS: u32 = 500; //duration of above effect
pub const DAYLIGHT_SUN_DEGREE: f64 = 3.0; //sun elevation for day/night switching
pub const SUN_POS_CHECK_INTERVAL_SECS: f32 = 60.0; //secs between calculating sun position
#[derive(Debug, PartialEq)]
pub enum ProlongKind {
PIR,
Remote,
Switch,
AutoOff,
DayNight,
}
pub enum Operation {
On,
Off,
Toggle,
}
#[derive(Clone, Debug)]
pub enum TaskCommand {
TurnOnProlong,
TurnOnProlongNight,
TurnOff,
}
#[derive(Clone)]
pub struct OneWireTask {
pub command: TaskCommand,
pub id_relay: Option<i32>,
pub tag_group: Option<String>,
pub id_yeelight: Option<i32>,
pub duration: Option<Duration>,
}
pub fn get_w1_device_name(family_code: u8, address: u64) -> String {
format!("{:02x}-{:012x}", family_code, address)
}
pub struct Sensor {
pub id_sensor: i32,
pub id_kind: i32,
pub name: String,
pub tags: Vec<String>,
pub associated_relays: Vec<i32>,
pub associated_yeelights: Vec<i32>,
}
pub struct SensorBoard {
pub pio_a: Option<Sensor>,
pub pio_b: Option<Sensor>,
pub ow_family: u8,
pub ow_address: u64,
pub last_value: Option<u8>,
pub file: Option<File>,
}
impl SensorBoard {
fn open(&mut self) {
let path = format!(
"{}/{}/state",
W1_ROOT_PATH,
get_w1_device_name(self.ow_family, self.ow_address)
);
let data_path = Path::new(&path);
info!(
"{}: opening sensor file: {}",
get_w1_device_name(self.ow_family, self.ow_address),
data_path.display()
);
self.file = File::open(data_path).ok();
}
fn read_state(&mut self) -> Option<u8> {
if self.file.is_none() {
self.open();
}
match &mut self.file {
Some(file) => {
let mut new_value = [0u8; 1];
match file.seek(SeekFrom::Start(0)) {
Err(e) => {
error!(
"{}: file seek error: {:?}",
get_w1_device_name(self.ow_family, self.ow_address),
e,
);
}
_ => {}
}
let result = file.read_exact(&mut new_value);
match result {
Ok(_) => {
debug!(
"{}: read byte: {:#04x}",
get_w1_device_name(self.ow_family, self.ow_address),
new_value[0]
);
//in this application only the following values are valid
if new_value[0] == 0x5a
|| new_value[0] == 0x4b
|| new_value[0] == 0x1e
|| new_value[0] == 0x0f
{
return Some(new_value[0]);
} else {
error!(
"{}: reading state file gives invalid byte value: {:#04x}, ignoring",
get_w1_device_name(self.ow_family, self.ow_address),
new_value[0]
);
}
}
Err(e) => {
error!(
"{}: error reading: {:?}",
get_w1_device_name(self.ow_family, self.ow_address),
e,
);
}
}
}
None => (),
}
return None;
}
}
pub struct Device {
pub id: i32,
pub name: String,
pub tags: Vec<String>,
pub pir_exclude: bool,
pub pir_hold_secs: f32,
pub switch_hold_secs: f32,
pub pir_all_day: bool,
pub override_mode: bool,
pub last_toggled: Option<Instant>,
pub stop_after: Option<Duration>,
}
impl Device {
fn turn_on_prolong(
&mut self,
kind: ProlongKind,
night: bool,
dest_name: String,
on: bool,
currently_off: bool,
duration: Option<Duration>,
) -> bool {
if (kind == ProlongKind::PIR
&& !(self.override_mode && on
|| (!self.pir_exclude && on && (night || self.pir_all_day))))
|| ((kind == ProlongKind::Remote
|| (kind == ProlongKind::AutoOff && !self.override_mode))
&& !on
&& currently_off)
{
return false;
}
let d = match duration {
Some(d) => {
//if we have a duration pass it directly
d
}
None => {
//otherwise take a switch_hold_secs or pir_hold_secs
let mut prolong_secs = match kind {
ProlongKind::Switch => self.switch_hold_secs,
_ => self.pir_hold_secs,
};
if kind != ProlongKind::Switch {
if !self.override_mode && currently_off {
if kind == ProlongKind::Remote
&& self.switch_hold_secs != DEFAULT_SWITCH_HOLD_SECS
{
prolong_secs = self.switch_hold_secs
}
} else if self.override_mode {
if DEFAULT_PIR_PROLONG_SECS > prolong_secs {
prolong_secs = DEFAULT_PIR_PROLONG_SECS;
};
}
}
Duration::from_secs_f32(prolong_secs)
}
};
//visual
let mode = match kind {
ProlongKind::Switch => format!("🔲 Switch toggle {}", {
if currently_off {
"💡"
} else {
"◼️"
}
}),
ProlongKind::Remote => format!("🧩 Remote turn-{}", {
if on {
"on"
} else {
"off"
}
}),
ProlongKind::PIR => "💡 PIR turn-on".to_string(),
ProlongKind::AutoOff => "⌛ Auto turn-off".to_string(),
ProlongKind::DayNight => format!("🌄 Day/night auto turn-{}", {
if on {
"on"
} else {
"off"
}
}),
};
//checking if device is currently OFF
if kind == ProlongKind::Switch
|| ((kind == ProlongKind::Remote || kind == ProlongKind::AutoOff) && !on)
|| (!self.override_mode && currently_off)
|| kind == ProlongKind::DayNight
{
//flip-flop protection for too fast state changes
let mut flipflop_block = false;
match self.last_toggled {
Some(toggled) => {
if toggled.elapsed() < Duration::from_secs_f32(MIN_TOGGLE_DELAY_SECS) {
flipflop_block = true;
}
}
_ => {}
}
if flipflop_block {
warn!(
"<d>- - -</> 🚫 flip-flop protection: <b>{}</> <cyan>(</><magenta>{}</><cyan>)</>, {} request ignored",
self.name,
dest_name,
mode,
);
} else {
let mut duration;
if (kind == ProlongKind::Remote && !on)
|| kind == ProlongKind::AutoOff
|| kind == ProlongKind::DayNight
{
duration = "".to_string();
self.stop_after = None;
if kind == ProlongKind::AutoOff && currently_off && self.override_mode {
info!(
"<d>- - -</> 🔓 End of override mode: <b>{}</> <cyan>(</><magenta>{}</><cyan>)</>{}",
self.name, dest_name, duration,
);
self.last_toggled = None;
self.override_mode = false;
return false;
}
//mark that we was in override
if self.override_mode {
duration.push_str(" 🔓");
}
self.override_mode = false;
} else {
duration = format!(", duration: <yellow>{}</>", format_duration(d));
if kind == ProlongKind::Switch {
self.override_mode = true;
duration.push_str(" 🔒");
}
self.stop_after = Some(d);
}
info!(
"<d>- - -</> {}: <b>{}</> <cyan>(</><magenta>{}</><cyan>)</>{}",
mode, self.name, dest_name, duration,
);
self.last_toggled = Some(Instant::now());
return true;
}
} else {
let toggled_elapsed = self.last_toggled.unwrap_or(Instant::now()).elapsed();
let mut duration = format!(", duration added: <yellow>{}</>", format_duration(d));
if self.override_mode {
if self.switch_hold_secs > d.as_secs_f32()
&& toggled_elapsed
> Duration::from_secs_f32(self.switch_hold_secs - d.as_secs_f32())
{
self.stop_after = Some(toggled_elapsed.add(d));
} else {
duration = "".into();
}
//mark that we are in override mode
duration.push_str(" 🔒");
} else {
self.stop_after = Some(toggled_elapsed.add(d));
}
info!(
"<d>- - -</> ♾️ {:?} prolonged{}: <b>{}</> <cyan>(</><magenta>{}</><cyan>)</>{}",
kind,
{
if !self.override_mode {
""
} else if !currently_off {
" 💡"
} else {
" ◼️"
}
},
self.name,
dest_name,
duration,
);
}
false
}
}
trait OnOff {
fn currently_off(&self, index: Option<usize>) -> bool;
fn get_dest_name(&self, index: Option<usize>) -> String;
fn set_new_value(
&mut self,
op: Operation,
index: Option<usize>,
onewire: Option<&OneWire>,
dev: &mut Device,
);
fn sensor_trigger(
&mut self,
device: &mut Device,
index: Option<usize>,
state_machine: &mut StateMachine,
onewire: Option<&OneWire>,
associated_devices: &Vec<i32>,
kind_code: &str,
on: bool,
night: bool,
) {
let currently_off = self.currently_off(index);
let dest_name = self.get_dest_name(index);
if associated_devices.contains(&device.id) {
//check hook function result and stop processing when needed
let stop_processing =
!state_machine.device_hook(&kind_code, on, &device.tags, night, device.id);
if stop_processing {
debug!("{}: {}: stopped processing", dest_name, device.name);
return;
}
match kind_code.as_ref() {
"PIR_Trigger" => {
if device.turn_on_prolong(
ProlongKind::PIR,
night,
dest_name,
on,
currently_off,
None,
) {
self.set_new_value(Operation::On, index, onewire, device);
}
}
"Switch" => {
if device.turn_on_prolong(
ProlongKind::Switch,
night,
dest_name,
on,
currently_off,
None,
) {
self.set_new_value(Operation::Toggle, index, onewire, device);
}
}
_ => (),
}
}
}
}
pub struct RelayBoard {
pub relay: [Option<i32>; 8],
pub ow_family: u8,
pub ow_address: u64,
pub new_value: Option<u8>,
pub last_value: Option<u8>,
pub file: Option<File>,
}
impl RelayBoard {
fn open(&mut self) {
let path = format!(
"{}/{}/output",
W1_ROOT_PATH,
get_w1_device_name(self.ow_family, self.ow_address)
);
let data_path = Path::new(&path);
info!(
"{}: opening relay file: {}",
get_w1_device_name(self.ow_family, self.ow_address),
data_path.display()
);
let file = OpenOptions::new().write(true).open(data_path);
match file {
Ok(file) => {
self.file = Some(file);
}
Err(e) => {
error!(
"{}: error opening file {:?}: {:?}",
get_w1_device_name(self.ow_family, self.ow_address),
data_path.display(),
e,
);
}
}
}
fn save_state(&mut self) {
if self.file.is_none() {
self.open();
}
match &mut self.file {
Some(file) => match self.new_value {
Some(val) => {
info!(
"{}: 💾 saving output byte: {:#04x}",
get_w1_device_name(self.ow_family, self.ow_address),
val
);
match file.seek(SeekFrom::Start(0)) {
Err(e) => {
error!(
"{}: file seek error: {:?}",
get_w1_device_name(self.ow_family, self.ow_address),
e,
);
}
_ => {}
}
let new_value = [val; 1];
match file.write_all(&new_value) {
Ok(_) => {
self.last_value = Some(val);
self.new_value = None;
}
Err(e) => {
error!(
"{}: error writing output byte: {:?}",
get_w1_device_name(self.ow_family, self.ow_address),
e,
);
}
}
}
_ => {}
},
None => (),
}
}
fn get_actual_state(&self) -> u8 {
//we will be computing new output byte for a relay board
//so first of all get the base/previous value
self.new_value
.unwrap_or(self.last_value.unwrap_or(DS2408_INITIAL_STATE))
}
}
impl OnOff for RelayBoard {
fn currently_off(&self, index: Option<usize>) -> bool {
//check if bit is set (relay is off)
self.get_actual_state() & (1 << index.unwrap() as u8) != 0
}
fn get_dest_name(&self, index: Option<usize>) -> String {
format!(
"relay:{}|bit:{}",
get_w1_device_name(self.ow_family, self.ow_address),
index.unwrap()
)
}
fn set_new_value(
&mut self,
op: Operation,
index: Option<usize>,
_onewire: Option<&OneWire>,
_dev: &mut Device,
) {
let mut new_state: u8 = self.get_actual_state();
match op {
Operation::On => new_state = new_state & !(1 << index.unwrap() as u8),
Operation::Toggle => {
//switching is toggling current state to the opposite:
new_state = new_state ^ (1 << index.unwrap() as u8);
}
_ => (),
}
self.new_value = Some(new_state);
}
}
pub struct Yeelight {
pub id: i32,
pub ip_address: String,
pub powered_on: bool,
}
#[derive(Serialize)]
struct YeelightCommand {
id: u32,
method: String,
#[serde(serialize_with = "Yeelight::params_serialize")]
params: Vec<String>,
}
#[derive(Deserialize)]
struct YeelightResult {
id: u32,
result: Vec<String>,
}
impl Yeelight {
fn params_serialize<S>(params: &Vec<String>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(params.len()))?;
for (pos, elem) in params.iter().enumerate() {
if pos == 2 {
//converting last parameter (duration of effect) to integer
let duration: u32 = elem.parse().unwrap_or_default();
seq.serialize_element(&duration)?;
} else {
//leaving as String
seq.serialize_element(&elem)?;
}
}
seq.end()
}
fn yeelight_tcp_command(yeelight_name: String, ip_addr: String, turn_on: bool) {
let on_off = if turn_on { "on" } else { "off" };
let id = 1;
let cmd = YeelightCommand {
id: id,
method: YEELIGHT_METHOD_SET_POWER.to_owned(),
params: vec![
on_off.to_owned(),
YEELIGHT_EFFECT.to_owned(),
YEELIGHT_DURATION_MS.to_string(),
],
};
// serialize command to a JSON string
let mut json_cmd = serde_json::to_string(&cmd).unwrap();
debug!(
"Yeelight: {}: generated JSON command={:?}",
yeelight_name, json_cmd
);
for _ in 1..=3 {
debug!("Yeelight: {}: connecting...", yeelight_name);
match TcpStream::connect(format!("{}:{}", ip_addr, YEELIGHT_TCP_PORT)) {
Err(e) => {
error!("Yeelight: {}: connection error: {:?}", yeelight_name, e);
}
Ok(mut stream) => {
debug!("Yeelight: {}: connected, sending command", yeelight_name);
json_cmd.push_str("\r\n"); //specs requirement
match stream.write_all(json_cmd.as_bytes()) {
Ok(_) => {
let _ = stream.set_read_timeout(Some(Duration::from_secs_f32(1.5)));
let mut reader = BufReader::new(stream.try_clone().unwrap());
//read a line with json result from yeelight
let mut raw_result = String::new();
let _ = reader.read_line(&mut raw_result);
//try to parse json
match serde_json::from_str::<YeelightResult>(&raw_result) {
Ok(json_res) => {
//check for correct command result
if json_res.id == id && json_res.result == vec!["ok"] {
break;
}
}
Err(e) => {
error!(
"Yeelight: {}: error parsing result JSON: {:?}\nraw input data: {:?}",
yeelight_name, e, raw_result
);
}
}
}
Err(e) => {
error!(
"Yeelight: {}: cannot write to socket: {:?}",
yeelight_name, e
);
}
}
}
}
}
}
fn tasmota_command(yeelight_name: String, ip_addr: String, turn_on: bool) -> bool {
let cmd = if turn_on { "Power On" } else { "Power off" };
let url =
reqwest::Url::parse_with_params(&format!("http://{}/cm", ip_addr), &[("cmnd", cmd)])
.unwrap();
debug!("URL = {:?}", url.as_str());
for _ in 1..=3 {
debug!(
"Tasmota: {}: sending <blue>{}</> command...",
yeelight_name, cmd
);
let resp = reqwest::blocking::get(url.clone()).unwrap();
if resp.status() == reqwest::StatusCode::OK {
return true;
} else {
thread::sleep(Duration::from_secs(1));
}
}
false
}
fn turn_on_off(&mut self, turn_on: bool, dev: &Device) {
let yeelight_name = dev.name.clone();
let ip_address = self.ip_address.clone();
if yeelight_name.starts_with("Nous") {
thread::spawn(move || Yeelight::tasmota_command(yeelight_name, ip_address, turn_on));
} else {
thread::spawn(move || {
Yeelight::yeelight_tcp_command(yeelight_name, ip_address, turn_on)
});
}
self.powered_on = turn_on;
}
}
impl OnOff for Yeelight {
fn currently_off(&self, _index: Option<usize>) -> bool {
!self.powered_on
}
fn get_dest_name(&self, _index: Option<usize>) -> String {
format!("yeelight:{}", self.ip_address)
}
fn set_new_value(
&mut self,
op: Operation,
_index: Option<usize>,
onewire: Option<&OneWire>,
dev: &mut Device,
) {
let new_state = match op {
Operation::On => true,
Operation::Off => false,
Operation::Toggle => !self.powered_on,
};
self.turn_on_off(new_state, dev);
dev.last_toggled = Some(Instant::now());
onewire.unwrap().increment_yeelight_counter(self.id);
}
}
pub struct SensorDevices {
pub kinds: HashMap<i32, String>,
pub sensor_boards: Vec<SensorBoard>,
pub max_cesspool_level: usize,
}
pub struct RelayDevices {
pub relay_boards: Vec<RelayBoard>,
pub yeelight: Vec<Yeelight>,
}
pub struct Relays {
pub relay: Vec<Device>,
}
impl SensorDevices {
pub fn add_sensor(
&mut self,
id_sensor: i32,
id_kind: i32,
name: String,
family_code: Option<i16>,
address: u64,
bit: u8,
associated_relays: Vec<i32>,
associated_yeelights: Vec<i32>,
tags: Vec<String>,
) {
//find or create a sensor board
let sens_board = match self
.sensor_boards
.iter_mut()
.find(|b| b.ow_address == address)
{
Some(b) => b,
None => {
let mut sens_board = SensorBoard {
pio_a: None,
pio_b: None,
ow_family: match family_code {
Some(family) => family as u8,
None => FAMILY_CODE_DS2413,
},
ow_address: address,
last_value: None,
file: None,
};
sens_board.open();
self.sensor_boards.push(sens_board);
self.sensor_boards.last_mut().unwrap()
}
};
//find a max index for cesspool level
for tag in tags
.iter()
.filter(|&s| s.starts_with("cesspool"))
.into_iter()
{
let v: Vec<&str> = tag.split(":").collect();
match v.get(1) {
Some(&index_string) => match index_string.parse::<usize>() {
Ok(index) => {
if self.max_cesspool_level < index {
self.max_cesspool_level = index
}
}
Err(_) => (),
},
None => (),
}
}
//create and attach a sensor
let sensor = Sensor {
id_sensor,
id_kind,
name,
tags,
associated_relays,
associated_yeelights,
};
match bit {
0 => {
sens_board.pio_a = Some(sensor);
}
2 => {
sens_board.pio_b = Some(sensor);
}
_ => {}
}
}
}
impl RelayDevices {
pub fn add_relay(
&mut self,
relays: &mut Vec<Device>,
id_relay: i32,
name: String,
family_code: Option<i16>,
address: u64,
bit: u8,
pir_exclude: bool,
pir_hold_secs: Option<f32>,
switch_hold_secs: Option<f32>,
initial_state: bool,
pir_all_day: bool,
tags: Vec<String>,
) {
//find or create a relay board
let relay_board = match self
.relay_boards
.iter_mut()
.find(|b| b.ow_address == address)
{
Some(b) => b,
None => {
let mut relay_board = RelayBoard {
relay: Default::default(),
ow_family: match family_code {
Some(family) => family as u8,
None => FAMILY_CODE_DS2408,
},
ow_address: address,
new_value: None,
last_value: None,
file: None,
};
//we probably can read the current state of relays but due to safety reasons
//assume that all relays are turned off by default
relay_board.last_value = Some(DS2408_INITIAL_STATE);
relay_board.open();
self.relay_boards.push(relay_board);
self.relay_boards.last_mut().unwrap()
}
};
//if the initial_state is true, then we are turning on this relay
if initial_state {
let mut new_state = relay_board.last_value.unwrap_or(DS2408_INITIAL_STATE);
new_state = new_state & !(1 << bit as u8);
warn!(
"{}: Initial state is active for: {}: bit={} new state: {:#04x}",
get_w1_device_name(relay_board.ow_family, relay_board.ow_address),
name.clone(),
bit,
new_state,
);
relay_board.new_value = Some(new_state);
}
let old_relay = relays.iter().find(|r| r.id == id_relay);
//create and attach a relay
let relay = Device {
id: id_relay,
name: name.clone(),
tags,
pir_exclude,
pir_hold_secs: pir_hold_secs.unwrap_or(DEFAULT_PIR_HOLD_SECS),
switch_hold_secs: switch_hold_secs.unwrap_or(DEFAULT_SWITCH_HOLD_SECS),
pir_all_day,
override_mode: {
if let Some(old_relay) = old_relay {
if old_relay.id == id_relay {
if old_relay.override_mode {
info!(
"{}: {}: 📌 override_mode preserved",
name,
get_w1_device_name(relay_board.ow_family, relay_board.ow_address),
);
};
old_relay.override_mode
} else {
initial_state
}
} else {
initial_state
}
},
last_toggled: {
if let Some(old_relay) = old_relay {
if old_relay.id == id_relay {
if old_relay.last_toggled.is_some() {
info!(
"{}: {}: 📌 last_toggled preserved ({})",
get_w1_device_name(relay_board.ow_family, relay_board.ow_address),
name,
format_duration(old_relay.last_toggled.unwrap().elapsed()),
);
};
old_relay.last_toggled
} else {
None
}
} else {
None
}
},
stop_after: {
if let Some(old_relay) = old_relay {
if old_relay.id == id_relay {
if old_relay.stop_after.is_some() {
info!(
"{}: {}: 📌 stop_after preserved ({})",
get_w1_device_name(relay_board.ow_family, relay_board.ow_address),
name,
format_duration(old_relay.stop_after.unwrap()),
);
};
old_relay.stop_after
} else {
None
}
} else {
None
}
},
};
relay_board.relay[bit as usize] = Some(id_relay);
relays.retain(|r| r.id != id_relay);
relays.push(relay);
}
pub fn add_yeelight(
&mut self,
relays: &mut Vec<Device>,
id_yeelight: i32,
name: String,
ip_address: String,
pir_exclude: bool,
pir_hold_secs: Option<f32>,
switch_hold_secs: Option<f32>,
pir_all_day: bool,
tags: Vec<String>,
) {
//create and add a yeelight
let dev = Device {
id: id_yeelight,
name,
tags,
pir_exclude,
pir_hold_secs: pir_hold_secs.unwrap_or(DEFAULT_PIR_HOLD_SECS),
switch_hold_secs: switch_hold_secs.unwrap_or(DEFAULT_SWITCH_HOLD_SECS),
pir_all_day,
override_mode: false,
last_toggled: None,
stop_after: None,
};
let light = Yeelight {
id: id_yeelight,
ip_address,
powered_on: false,
};
self.yeelight.push(light);
relays.retain(|r| r.id != id_yeelight);
relays.push(dev);
}
pub fn relay_sensor_trigger(
&mut self,
relays: &mut Vec<Device>,
state_machine: &mut StateMachine,
associated_relays: &Vec<i32>,
kind_code: &str,
on: bool,
night: bool,
) {
for rb in &mut self.relay_boards {
for i in 0..=7 {
match rb.relay[i] {
Some(id) => {
let r = relays.iter_mut().find(|r| r.id == id);
match r {
Some(relay) => {
rb.sensor_trigger(
relay,
Some(i),
state_machine,