• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 //! base
16 #![allow(missing_docs)]
17 
18 use ylong_runtime::sync::mpsc::BoundedSender;
19 
20 use crate::config::TaskMessage;
21 use crate::config::*;
22 use crate::serializer;
23 use crate::utils;
24 #[allow(unused)]
25 use crate::utils::hdc_log::*;
26 
27 use std::io::{self, Error, ErrorKind};
28 use std::sync::Arc;
29 use ylong_runtime::sync::Mutex;
30 
31 type BOOL_ = Arc<Mutex<bool>>;
32 
33 pub struct CheckCompressVersion {}
34 impl CheckCompressVersion {
get_instance() -> BOOL_35     pub fn get_instance() -> BOOL_ {
36         static mut CAN_COMPRESS: Option<BOOL_> = Option::None;
37         unsafe {
38             CAN_COMPRESS
39                 .get_or_insert_with(|| Arc::new(Mutex::new(true)))
40                 .clone()
41         }
42     }
43 
set(check_version: bool)44     pub async fn set(check_version: bool) {
45         let arc = Self::get_instance();
46         let mut mutex = arc.lock().await;
47         *mutex = check_version;
48     }
49 
get() -> bool50     pub async fn get() -> bool {
51         let arc = Self::get_instance();
52         let mutex = arc.lock().await;
53         *mutex
54     }
55 }
56 
57 pub trait Writer {
write_all(&self, data: Vec<u8>) -> io::Result<()>58     fn write_all(&self, data: Vec<u8>) -> io::Result<()>;
59 }
60 
61 pub trait Reader: Send + Sync + 'static {
read_frame(&self, expected_size: usize) -> io::Result<Vec<u8>>62     fn read_frame(&self, expected_size: usize) -> io::Result<Vec<u8>>;
check_protocol_head(&mut self) -> io::Result<(u32, u32)>63     fn check_protocol_head(&mut self) -> io::Result<(u32, u32)> {
64         Err(utils::error_other("not implemeted".to_string()))
65     }
process_head(&self)66     fn process_head(&self) {}
67 }
68 
unpack_task_message_lock( rd: &mut dyn Reader, pack_size: u32, tx: BoundedSender<TaskMessage>, ) -> io::Result<()>69 pub async fn unpack_task_message_lock(
70     rd: &mut dyn Reader,
71     pack_size: u32,
72     tx: BoundedSender<TaskMessage>,
73 ) -> io::Result<()> {
74     let data = rd.read_frame(pack_size as usize)?;
75     let (head, body) = data.split_at(serializer::HEAD_SIZE);
76     let payload_head = serializer::unpack_payload_head(head.to_vec());
77     match payload_head {
78         Ok(payload_head) => {
79             let expected_head_size = u16::from_be(payload_head.head_size) as usize;
80             let expected_data_size = u32::from_be(payload_head.data_size) as usize;
81 
82             if serializer::HEAD_SIZE + expected_head_size + expected_data_size != pack_size as usize
83             {
84                 crate::warn!(
85             "protocol size diff: {pack_size} != {} + {expected_head_size} + {expected_data_size}",
86             serializer::HEAD_SIZE
87         );
88             }
89 
90             if expected_head_size + expected_data_size == 0
91                 || expected_head_size + expected_data_size > HDC_BUF_MAX_SIZE
92             {
93                 return Err(Error::new(ErrorKind::Other, "Packet size incorrect"));
94             }
95 
96             let (protect, payload) = body.split_at(expected_head_size);
97 
98             let payload_protect = serializer::unpack_payload_protect(protect.to_vec())?;
99             let channel_id = payload_protect.channel_id;
100 
101             let command = match HdcCommand::try_from(payload_protect.command_flag) {
102                 Ok(command) => command,
103                 Err(_) => {
104                     return Err(Error::new(ErrorKind::Other, "unknown command"));
105                 }
106             };
107             let mut remaining = (expected_data_size - payload.len()) as i32;
108             if remaining == 0 {
109                 let _ = tx
110                     .send(TaskMessage {
111                         channel_id,
112                         command,
113                         payload: payload.to_vec(),
114                     })
115                     .await;
116             }
117             let mut total_payload = payload.to_vec();
118             while remaining > 0 {
119                 let head_result = rd.check_protocol_head();
120                 match head_result {
121                     Ok((packet_size, _pkg_index)) => {
122                         rd.process_head();
123                         if packet_size == 0 {
124                             continue;
125                         }
126                         let mut payload1 = rd.read_frame(packet_size as usize).unwrap();
127                         total_payload.append(&mut payload1);
128                         remaining -= packet_size as i32;
129                         println!("remaining:{}, packet_size:{}", remaining, packet_size);
130                         if remaining == 0 {
131                             let _ = tx
132                                 .send(TaskMessage {
133                                     channel_id,
134                                     command,
135                                     payload: total_payload,
136                                 })
137                                 .await;
138                             break;
139                         }
140                     }
141                     Err(e) => {
142                         println!("check head error: {:#?}", e);
143                         return Err(e);
144                     }
145                 }
146             }
147 
148             let _ = tx
149                 .send(TaskMessage {
150                     channel_id,
151                     command: HdcCommand::UartFinish,
152                     payload: vec![],
153                 })
154                 .await;
155             Ok(())
156         }
157         Err(e) => {
158             println!("uart unpack_task_message_lock, err:{:#?}", e);
159             Err(e)
160         }
161     }
162 }
163 
unpack_task_message( rd: &mut dyn Reader, tx: BoundedSender<(TaskMessage, u32)>, ) -> io::Result<()>164 pub fn unpack_task_message(
165     rd: &mut dyn Reader,
166     tx: BoundedSender<(TaskMessage, u32)>,
167 ) -> io::Result<()> {
168     let (pack_size, package_index) = rd.check_protocol_head()?;
169     if pack_size == 0 {
170         println!("dummy package.");
171         return Ok(());
172     }
173 
174     let data = rd.read_frame(pack_size as usize)?;
175     ylong_runtime::spawn(async move {
176         let (head, body) = data.split_at(serializer::HEAD_SIZE);
177         let payload_head = serializer::unpack_payload_head(head.to_vec())?;
178         let expected_head_size = u16::from_be(payload_head.head_size) as usize;
179         let expected_data_size = u32::from_be(payload_head.data_size) as usize;
180 
181         if serializer::HEAD_SIZE + expected_head_size + expected_data_size != pack_size as usize {
182             crate::warn!(
183                 "protocol size diff: {pack_size} != {} + {expected_head_size} + {expected_data_size}",
184                 serializer::HEAD_SIZE
185             );
186         }
187 
188         if expected_head_size + expected_data_size == 0
189             || expected_head_size + expected_data_size > HDC_BUF_MAX_SIZE
190         {
191             return Err(Error::new(ErrorKind::Other, "Packet size incorrect"));
192         }
193 
194         let (protect, payload) = body.split_at(expected_head_size);
195 
196         let payload_protect = serializer::unpack_payload_protect(protect.to_vec())?;
197         let channel_id = payload_protect.channel_id;
198 
199         let command = match HdcCommand::try_from(payload_protect.command_flag) {
200             Ok(command) => command,
201             Err(_) => {
202                 return Err(Error::new(ErrorKind::Other, "unknown command"));
203             }
204         };
205 
206         let _ = tx
207             .send((
208                 TaskMessage {
209                     channel_id,
210                     command,
211                     payload: payload.to_vec(),
212                 },
213                 package_index,
214             ))
215             .await;
216         Ok(())
217     });
218 
219     Ok(())
220 }
221