st3215/
group_sync_write.rs1use crate::protocol_packet_handler::ProtocolPacketHandler;
2use crate::values::*;
3use std::collections::HashMap;
4
5pub struct GroupSyncWrite {
6 start_address: u8,
7 data_length: usize,
8 is_param_changed: bool,
9 param: Vec<u8>,
10 data_dict: HashMap<u8, Vec<u8>>,
11}
12
13impl GroupSyncWrite {
14 pub fn new(start_address: u8, data_length: usize) -> Self {
15 Self {
16 start_address,
17 data_length,
18 is_param_changed: false,
19 param: Vec::new(),
20 data_dict: HashMap::new(),
21 }
22 }
23
24 fn make_param(&mut self) {
25 if self.data_dict.is_empty() {
26 return;
27 }
28
29 self.param.clear();
30
31 for (sts_id, data) in &self.data_dict {
32 if data.is_empty() {
33 return;
34 }
35 self.param.push(*sts_id);
36 self.param.extend(data);
37 }
38 }
39
40 pub fn add_param(&mut self, sts_id: u8, data: Vec<u8>) -> bool {
41 if self.data_dict.contains_key(&sts_id) {
42 return false;
43 }
44
45 if data.len() > self.data_length {
46 return false;
47 }
48
49 self.data_dict.insert(sts_id, data);
50 self.is_param_changed = true;
51 true
52 }
53
54 pub fn remove_param(&mut self, sts_id: u8) {
55 if self.data_dict.remove(&sts_id).is_some() {
56 self.is_param_changed = true;
57 }
58 }
59
60 pub fn change_param(&mut self, sts_id: u8, data: Vec<u8>) -> bool {
61 if !self.data_dict.contains_key(&sts_id) {
62 return false;
63 }
64
65 if data.len() > self.data_length {
66 return false;
67 }
68
69 self.data_dict.insert(sts_id, data);
70 self.is_param_changed = true;
71 true
72 }
73
74 pub fn clear_param(&mut self) {
75 self.data_dict.clear();
76 }
77
78 pub fn tx_packet(&mut self, ph: &mut ProtocolPacketHandler) -> CommResult {
79 if self.data_dict.is_empty() {
80 return CommResult::NotAvailable;
81 }
82
83 if self.is_param_changed || self.param.is_empty() {
84 self.make_param();
85 }
86
87 ph.sync_write_tx_only(self.start_address, self.data_length as u8, &self.param)
88 }
89}