1use super::{PROFILE, std, tcp::Timed};
8#[cfg(feature = "loopback-client")]
9use sml_kit::CloseRequest;
10use sml_kit::{Body, Decoder, Error, SmlFile, Time, encode_frame};
11use std::io::{self, Read, Write};
12
13pub const SERVER_ID: &[u8] = b"\x0a\x01IMS\x00\x00\x00\x00\x01";
15pub(super) const MAX_FRAME: usize = 1024;
17pub(super) const PROFILE_PATH: [&[u8]; 1] = [&PROFILE.0];
18
19fn invalid(error: Error) -> io::Error {
20 io::Error::new(io::ErrorKind::InvalidData, error)
21}
22
23pub(super) fn send(stream: &mut Timed, file_id: &[u8], bodies: &[Body<'_>]) -> io::Result<()> {
25 let mut payload = [0; MAX_FRAME];
26 let n = SmlFile {
27 file_id,
28 messages: bodies,
29 }
30 .write(&mut payload)
31 .map_err(invalid)?;
32 let mut frame = [0; 2 * MAX_FRAME + 16];
34 let m = encode_frame(&payload[..n], &mut frame).map_err(invalid)?;
35 stream.write_all(&frame[..m])?;
36 stream.flush()
37}
38
39pub(super) fn receive(stream: &mut Timed, out: &mut [u8; MAX_FRAME]) -> io::Result<usize> {
42 let mut decoder = Decoder::new([0u8; MAX_FRAME]);
43 let mut chunk = [0; 256];
44 loop {
45 let n = stream.read(&mut chunk)?;
46 if n == 0 {
47 return Err(io::ErrorKind::UnexpectedEof.into());
48 }
49 for (i, &byte) in chunk[..n].iter().enumerate() {
50 if let Some(payload) = decoder.push(byte).map_err(invalid)? {
51 if i + 1 != n {
52 return Err(io::Error::new(
53 io::ErrorKind::InvalidData,
54 "bytes after the SML frame",
55 ));
56 }
57 out[..payload.len()].copy_from_slice(payload);
58 return Ok(payload.len());
59 }
60 }
61 }
62}
63
64#[cfg(feature = "loopback-client")]
65pub(super) const CLOSE_REQUEST: Body<'static> = Body::CloseRequest(CloseRequest {
66 global_signature: None,
67});
68
69pub(super) fn timestamp(utc: i64) -> io::Result<Time> {
70 u32::try_from(utc).map(Time::Timestamp).map_err(|_| {
71 io::Error::new(
72 io::ErrorKind::InvalidInput,
73 "SML timestamps cover 1970 to 2106",
74 )
75 })
76}
77
78#[cfg(feature = "loopback-meter")]
79pub(super) mod meter {
80 use super::*;
81 use crate::simulator::{ENERGY, VirtualMeter};
82 use sml_kit::{
83 Attention, CloseResponse, GetProfilePackResponse, GetProfileRequest, NameList, Obis,
84 OpenResponse, ProfileColumn, ProfileColumns, ProfilePeriod, ProfilePeriods, ProfileValue,
85 ProfileValues, ServerId, SmlValue, Unit, messages,
86 };
87 use std::vec::Vec;
88
89 pub(in crate::simulator) const UNKNOWN_OBJECT: [u8; 6] = [0x81, 0x81, 0xC7, 0xC7, 0xFE, 0x03];
91 const REGISTER: Obis = Obis(*ENERGY.as_bytes());
92 const CLOSE_RESPONSE: Body<'static> = Body::CloseResponse(CloseResponse {
93 global_signature: None,
94 });
95
96 const COLUMNS: [ProfileColumn; 1] = [ProfileColumn {
97 obis: REGISTER,
98 unit: Unit::WH,
99 scaler: -1,
100 }];
101
102 fn selection(request: &GetProfileRequest<'_>) -> Option<(i64, i64)> {
104 let server = request.server_id.map(|id| id.as_bytes());
105 let mut path = request.tree_path.iter();
106 let profile = matches!((path.next(), path.next()), (Some(Ok(p)), None) if p == PROFILE.0);
107 let (Some(Time::Timestamp(begin)), Some(Time::Timestamp(end))) =
108 (request.begin_time, request.end_time)
109 else {
110 return None;
111 };
112 (server == Some(SERVER_ID) && profile && request.objects.is_none() && begin <= end)
113 .then_some((i64::from(begin), i64::from(end)))
114 }
115
116 pub(in crate::simulator) fn serve(
119 stream: &mut Timed,
120 history: &VirtualMeter,
121 on_profile_read: impl FnOnce(),
122 ) -> io::Result<()> {
123 let mut request = [0; MAX_FRAME];
124 let n = receive(stream, &mut request)?;
125 let mut file_id: &[u8] = b"";
126 let mut range = None;
127 for message in messages(&request[..n]) {
128 match message.map_err(invalid)?.body {
129 Body::OpenRequest(open) => file_id = open.req_file_id,
130 Body::GetProfilePackRequest(get) => range = selection(&get),
131 _ => {}
132 }
133 }
134 let server_id = ServerId::new(SERVER_ID);
135 let open = Body::OpenResponse(OpenResponse {
136 codepage: None,
137 client_id: None,
138 req_file_id: file_id,
139 server_id,
140 ref_time: None,
141 sml_version: None,
142 });
143 let Some((begin, end)) = range else {
144 let refusal = Body::Attention(Attention {
145 server_id,
146 number: &UNKNOWN_OBJECT,
147 message: None,
148 details: None,
149 });
150 return send(stream, file_id, &[open, refusal, CLOSE_RESPONSE]);
151 };
152 on_profile_read();
153 let readings: Vec<_> = history
154 .readings()
155 .filter(|r| (begin..=end).contains(&r.utc))
156 .collect();
157 let values: Vec<_> = readings
158 .iter()
159 .map(|r| [ProfileValue::new(SmlValue::Uint(u64::from(r.import_dwh)))])
160 .collect();
161 let mut periods = Vec::with_capacity(readings.len());
162 for (reading, value) in readings.iter().zip(&values) {
163 periods.push(ProfilePeriod {
164 val_time: timestamp(reading.utc)?,
165 status: 1,
166 values: ProfileValues::from_slice(value),
167 period_signature: None,
168 });
169 }
170 let profile = Body::GetProfilePackResponse(GetProfilePackResponse {
171 server_id,
172 act_time: timestamp(history.current().utc)?,
173 reg_period: 900,
174 tree_path: NameList::from_slice(&PROFILE_PATH),
175 columns: ProfileColumns::from_slice(&COLUMNS),
176 periods: ProfilePeriods::from_slice(&periods),
177 rawdata: None,
178 profile_signature: None,
179 });
180 send(stream, file_id, &[open, profile, CLOSE_RESPONSE])
181 }
182}
183
184#[cfg(feature = "loopback-client")]
185pub(super) mod gateway {
186 use super::*;
187 use crate::{
188 Counts,
189 simulator::SOURCE,
190 sml::{
191 Source,
192 protocol::{GetProfileRequest, NameList, OpenRequest, ServerId, messages},
193 read_profile_pack,
194 },
195 };
196 use smgw_core::taf15::Profile;
197
198 pub const SML_SOURCE: Source<'static> = Source {
200 channel: SOURCE.channel,
201 server_id: SERVER_ID,
202 profile: sml_kit::Obis(PROFILE.0),
203 };
204
205 pub(in crate::simulator) fn read<const N: usize>(
207 stream: &mut Timed,
208 destination: &mut Profile<'static, N>,
209 ) -> io::Result<Counts> {
210 let window = destination.window();
211 let server_id = Some(ServerId::new(SERVER_ID));
212 let file_id = b"gw";
213 let request = [
214 Body::OpenRequest(OpenRequest {
215 codepage: None,
216 client_id: b"smgw-sim",
217 req_file_id: file_id,
218 server_id,
219 username: None,
220 password: None,
221 sml_version: None,
222 }),
223 Body::GetProfilePackRequest(GetProfileRequest {
224 server_id,
225 username: None,
226 password: None,
227 with_rawdata: None,
228 begin_time: Some(timestamp(*window.start())?),
229 end_time: Some(timestamp(*window.end())?),
230 tree_path: NameList::from_slice(&PROFILE_PATH),
231 objects: None,
232 details: None,
233 }),
234 CLOSE_REQUEST,
235 ];
236 send(stream, file_id, &request)?;
237 let mut answer = [0; MAX_FRAME];
238 let n = receive(stream, &mut answer)?;
239 stream.shutdown()?;
240 let mut profile = None;
241 for message in messages(&answer[..n]) {
242 match message.map_err(invalid)?.body {
243 Body::GetProfilePackResponse(r) if profile.is_none() => profile = Some(r),
244 Body::GetProfilePackResponse(_) => {
245 return Err(io::Error::new(
246 io::ErrorKind::InvalidData,
247 "the meter sent two profiles",
248 ));
249 }
250 Body::Attention(_) => {
251 return Err(io::Error::new(
252 io::ErrorKind::PermissionDenied,
253 "the meter refused the profile request",
254 ));
255 }
256 _ => {}
257 }
258 }
259 let profile = profile
260 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "no profile in answer"))?;
261 read_profile_pack(&profile, &SML_SOURCE, window, destination).map_err(io::Error::other)
262 }
263}