1use serde::Serialize;
10
11use crate::generic::Error;
12use crate::interfaces::grown;
13use crate::read::{Reader, Values};
14
15pub const LOW_NOISE_MARGIN: f64 = 6.0;
17
18pub const CABLE_FAULT: &str = "DONE_CABLE_NOK";
20
21const INTERFACE: &str = "WANDSLInterfaceConfig1";
22const LINK: &str = "WANDSLLinkConfig1";
23
24#[derive(Debug, Clone, Default, PartialEq, Serialize)]
26pub struct Report {
27 pub access_type: Option<String>,
29 #[serde(skip_serializing_if = "Option::is_none")]
31 pub note: Option<String>,
32 #[serde(flatten)]
33 pub details: Option<Details>,
34}
35
36#[derive(Debug, Clone, Default, PartialEq, Serialize)]
38pub struct Details {
39 pub line: Line,
40 pub errors_since_sync: Option<Errors>,
43 pub errors_total: Errors,
45 pub link: Option<Link>,
47 pub diagnosis: Option<Diagnosis>,
49 pub hints: Vec<String>,
51}
52
53#[derive(Debug, Clone, Default, PartialEq, Serialize)]
55pub struct Line {
56 pub status: Option<String>,
58 pub enabled: Option<bool>,
59 pub sync: Option<bool>,
61 pub standard: Option<String>,
63 pub profile: Option<String>,
65 pub data_path: Option<String>,
67 pub downstream_rate: Option<u64>,
69 pub upstream_rate: Option<u64>,
70 pub downstream_max: Option<u64>,
71 pub upstream_max: Option<u64>,
72 pub downstream_noise_margin: Option<f64>,
74 pub upstream_noise_margin: Option<f64>,
75 pub downstream_attenuation: Option<f64>,
76 pub upstream_attenuation: Option<f64>,
77 pub downstream_power: Option<i64>,
80 pub upstream_power: Option<i64>,
81}
82
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
86pub struct Errors {
87 pub crc: Option<u64>,
89 pub remote_crc: Option<u64>,
90 pub fec: Option<u64>,
92 pub remote_fec: Option<u64>,
93 pub hec: Option<u64>,
95 pub remote_hec: Option<u64>,
96 pub errored_seconds: Option<u64>,
98 pub severely_errored_seconds: Option<u64>,
100 pub loss_of_framing: Option<u64>,
101 pub resyncs: Option<u64>,
103 pub init_errors: Option<u64>,
104 pub init_timeouts: Option<u64>,
105 pub cell_delineation: Option<u64>,
106 pub receive_blocks: Option<u64>,
107 pub transmit_blocks: Option<u64>,
108}
109
110impl Errors {
111 fn from_values(answers: &[&Values]) -> Self {
114 let find = |name: &str| answers.iter().find_map(|values| values.number(name));
115 Self {
116 crc: find("NewCRCErrors"),
117 remote_crc: find("NewATUCCRCErrors"),
118 fec: find("NewFECErrors"),
119 remote_fec: find("NewATUCFECErrors"),
120 hec: find("NewHECErrors"),
121 remote_hec: find("NewATUCHECErrors"),
122 errored_seconds: find("NewErroredSecs"),
123 severely_errored_seconds: find("NewSeverelyErroredSecs"),
124 loss_of_framing: find("NewLossOfFraming"),
125 resyncs: find("NewLinkRetrain"),
126 init_errors: find("NewInitErrors"),
127 init_timeouts: find("NewInitTimeouts"),
128 cell_delineation: find("NewCellDelin"),
129 receive_blocks: find("NewReceiveBlocks"),
130 transmit_blocks: find("NewTransmitBlocks"),
131 }
132 }
133
134 #[must_use]
136 pub fn since(&self, earlier: &Self) -> Self {
137 let grown = |now: Option<u64>, then: Option<u64>| grown(then?, now?);
138 Self {
139 crc: grown(self.crc, earlier.crc),
140 remote_crc: grown(self.remote_crc, earlier.remote_crc),
141 fec: grown(self.fec, earlier.fec),
142 remote_fec: grown(self.remote_fec, earlier.remote_fec),
143 hec: grown(self.hec, earlier.hec),
144 remote_hec: grown(self.remote_hec, earlier.remote_hec),
145 errored_seconds: grown(self.errored_seconds, earlier.errored_seconds),
146 severely_errored_seconds: grown(
147 self.severely_errored_seconds,
148 earlier.severely_errored_seconds,
149 ),
150 loss_of_framing: grown(self.loss_of_framing, earlier.loss_of_framing),
151 resyncs: grown(self.resyncs, earlier.resyncs),
152 init_errors: grown(self.init_errors, earlier.init_errors),
153 init_timeouts: grown(self.init_timeouts, earlier.init_timeouts),
154 cell_delineation: grown(self.cell_delineation, earlier.cell_delineation),
155 receive_blocks: grown(self.receive_blocks, earlier.receive_blocks),
156 transmit_blocks: grown(self.transmit_blocks, earlier.transmit_blocks),
157 }
158 }
159}
160
161#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
163pub struct Link {
164 pub link_type: Option<String>,
166 pub link_status: Option<String>,
168 pub atm_crc_errors: Option<u64>,
169 pub aal5_crc_errors: Option<u64>,
170}
171
172#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
176pub struct Diagnosis {
177 pub state: Option<String>,
180 pub last_run_seconds: Option<u64>,
183 pub signal_lost_seconds: Option<u64>,
186 pub cable_fault_distance: Option<u64>,
189 pub dsl_active: Option<bool>,
190 pub dsl_sync: Option<bool>,
191}
192
193#[derive(Debug, Clone, Default, PartialEq, Serialize)]
195pub struct Sample {
196 pub seconds: f64,
198 pub status: Option<String>,
200 pub changes: Option<Errors>,
203 pub hints: Vec<String>,
204}
205
206impl Report {
207 #[must_use]
209 pub fn since(&self, earlier: &Self, seconds: f64) -> Sample {
210 let (Some(now), Some(then)) = (&self.details, &earlier.details) else {
211 return Sample {
212 seconds,
213 hints: self.note.iter().cloned().collect(),
214 ..Sample::default()
215 };
216 };
217 let changes = now.errors_total.since(&then.errors_total);
218 let mut hints = Vec::new();
219 if let Some(crc) = changes.crc.filter(|c| *c > 0) {
220 hints.push(format!(
221 "CRC errors rose by {crc} in {seconds:.0} s: data was lost on the line"
222 ));
223 }
224 if changes.resyncs.is_some_and(|r| r > 0) {
225 hints.push("the line resynchronized".to_owned());
226 }
227 hints.extend(noise_hints(&now.line));
228 Sample {
229 seconds,
230 status: now.line.status.clone(),
231 changes: Some(changes),
232 hints,
233 }
234 }
235}
236
237pub async fn report(reader: &mut Reader) -> Result<Report, Error> {
245 let access_type = reader
246 .try_read("WANCommonInterfaceConfig1", "GetCommonLinkProperties", &[])
247 .await?
248 .and_then(|c| c.text("NewWANAccessType"));
249 if let Some(other) = access_type.as_deref().filter(|a| *a != "DSL") {
250 return Ok(Report {
251 note: Some(format!("the connection is not DSL but {other}")),
252 access_type,
253 details: None,
254 });
255 }
256 let info = reader.try_read(INTERFACE, "GetInfo", &[]).await?;
257 let extra = reader
258 .try_read(INTERFACE, "X_AVM-DE_GetDSLInfo", &[])
259 .await?;
260 if info.is_none() && extra.is_none() {
261 return Ok(Report {
262 note: Some("the device has no DSL interface".to_owned()),
263 access_type,
264 details: None,
265 });
266 }
267 let total = reader
268 .try_read(INTERFACE, "GetStatisticsTotal", &[])
269 .await?;
270 let showtime = reader
271 .try_read(INTERFACE, "GetStatisticsShowtime", &[])
272 .await?;
273 let diagnosis = reader
274 .try_read(INTERFACE, "X_AVM-DE_GetDSLDiagnoseInfo", &[])
275 .await?;
276 let link_info = reader.try_read(LINK, "GetDSLLinkInfo", &[]).await?;
277 let link_statistics = reader.try_read(LINK, "GetStatistics", &[]).await?;
278 let (info, extra) = (info.unwrap_or_default(), extra.unwrap_or_default());
279 let diagnosis = diagnosis.as_ref().map(diagnosis_of);
280 let values = line(&info, &extra, diagnosis.as_ref());
281 let errors_total = Errors::from_values(&total.iter().chain([&extra]).collect::<Vec<_>>());
284 let link = (link_info.is_some() || link_statistics.is_some()).then(|| {
285 let (info, statistics) = (
286 link_info.unwrap_or_default(),
287 link_statistics.unwrap_or_default(),
288 );
289 Link {
290 link_type: info.text("NewLinkType"),
291 link_status: info.text("NewLinkStatus"),
292 atm_crc_errors: statistics.number("NewATMCRCErrors"),
293 aal5_crc_errors: statistics.number("NewAAL5CRCErrors"),
294 }
295 });
296 let mut details = Details {
297 line: values,
298 errors_since_sync: showtime.as_ref().map(|s| Errors::from_values(&[s])),
299 errors_total,
300 link,
301 diagnosis,
302 hints: Vec::new(),
303 };
304 details.hints = hints(&details);
305 Ok(Report {
306 access_type,
307 note: None,
308 details: Some(details),
309 })
310}
311
312fn line(info: &Values, extra: &Values, diagnosis: Option<&Diagnosis>) -> Line {
315 let text = |name| info.text(name).or_else(|| extra.text(name));
316 let rate = |name| info.number::<u64>(name).or_else(|| extra.number(name));
317 let signed = |name| info.number::<i64>(name).or_else(|| extra.number(name));
318 let decibels = |name| signed(name).map(crate::status::tenths);
319 let power = |name| signed(name).filter(|p| *p != 0);
321 Line {
322 status: text("NewStatus").or_else(|| extra.text("NewLinkStatus")),
323 enabled: info.flag("NewEnable"),
324 sync: diagnosis.and_then(|d| d.dsl_sync),
325 standard: extra.text("NewModulationType"),
326 profile: extra.text("NewCurrentProfile"),
327 data_path: info.text("NewDataPath"),
328 downstream_rate: rate("NewDownstreamCurrRate"),
329 upstream_rate: rate("NewUpstreamCurrRate"),
330 downstream_max: rate("NewDownstreamMaxRate"),
331 upstream_max: rate("NewUpstreamMaxRate"),
332 downstream_noise_margin: decibels("NewDownstreamNoiseMargin"),
333 upstream_noise_margin: decibels("NewUpstreamNoiseMargin"),
334 downstream_attenuation: decibels("NewDownstreamAttenuation"),
335 upstream_attenuation: decibels("NewUpstreamAttenuation"),
336 downstream_power: power("NewDownstreamPower"),
337 upstream_power: power("NewUpstreamPower"),
338 }
339}
340
341fn diagnosis_of(values: &Values) -> Diagnosis {
342 let seconds = |name| values.number::<u64>(name).filter(|t| *t > 0);
343 let state = values
344 .text("NewX_AVM-DE_DSLDiagnoseState")
345 .or_else(|| values.text("NewX_AVM-DE_DSLDigagnoseState"));
347 let fault = state.as_deref() == Some(CABLE_FAULT);
349 Diagnosis {
350 last_run_seconds: seconds("NewX_AVM-DE_DSLLastDiagnoseTime"),
351 signal_lost_seconds: seconds("NewX_AVM-DE_DSLSignalLossTime"),
352 cable_fault_distance: values
353 .number::<u64>("NewX_AVM-DE_CableNokDistance")
354 .filter(|_| fault),
355 state,
356 dsl_active: values.flag("NewX_AVM-DE_DSLActive"),
357 dsl_sync: values.flag("NewX_AVM-DE_DSLSync"),
358 }
359}
360
361fn noise_hints(line: &Line) -> Vec<String> {
363 [
364 ("downstream", line.downstream_noise_margin),
365 ("upstream", line.upstream_noise_margin),
366 ]
367 .into_iter()
368 .filter_map(|(direction, margin)| {
369 margin.filter(|m| *m < LOW_NOISE_MARGIN).map(|m| {
370 format!(
371 "the {direction} noise margin of {m:.1} dB is below {LOW_NOISE_MARGIN:.0} dB: \
372 the line may lose its sync"
373 )
374 })
375 })
376 .collect()
377}
378
379fn hints(details: &Details) -> Vec<String> {
381 let mut hints = Vec::new();
382 if details.line.sync == Some(false) {
383 hints.push("the line is not synchronized".to_owned());
384 }
385 hints.extend(noise_hints(&details.line));
386 let errors = details.errors_since_sync.unwrap_or(details.errors_total);
387 if let Some(seconds) = errors.severely_errored_seconds.filter(|s| *s > 0) {
388 hints.push(format!(
389 "{seconds} severely errored seconds: the line had phases of many errors"
390 ));
391 }
392 if let Some(resyncs) = details.errors_total.resyncs.filter(|r| *r > 1) {
393 hints.push(format!("the line resynchronized {resyncs} times"));
394 }
395 if let Some(diagnosis) = &details.diagnosis {
396 if let Some(seconds) = diagnosis.signal_lost_seconds {
397 hints.push(format!("the line lost its signal {seconds} s ago"));
398 }
399 match diagnosis.cable_fault_distance {
400 Some(distance) => hints.push(format!(
401 "the line diagnosis found a cable fault about {distance} m away"
402 )),
403 None if diagnosis.state.as_deref() == Some(CABLE_FAULT) => hints
404 .push("the line diagnosis found a cable fault, but not how far away".to_owned()),
405 None => {}
406 }
407 }
408 hints
409}
410
411#[cfg(test)]
412mod tests {
413 use super::*;
414 use crate::read::values;
415
416 #[test]
417 fn reads_the_line_from_both_answers() {
418 let info = values(&[("NewStatus", "Up"), ("NewDownstreamNoiseMargin", "55")]);
419 let extra = values(&[
420 ("NewLinkStatus", "Down"),
421 ("NewModulationType", "VDSL"),
422 ("NewDownstreamNoiseMargin", "70"),
423 ("NewUpstreamNoiseMargin", "80"),
424 ("NewDownstreamPower", "-12"),
425 ("NewUpstreamPower", "0"),
426 ]);
427 let line = line(&info, &extra, None);
428 assert_eq!(line.status.as_deref(), Some("Up"));
429 assert_eq!(line.standard.as_deref(), Some("VDSL"));
430 assert_eq!(line.downstream_noise_margin, Some(5.5));
431 assert_eq!(line.upstream_noise_margin, Some(8.0));
432 assert_eq!(line.downstream_power, Some(-12));
433 assert_eq!(line.upstream_power, None);
434 assert_eq!(line.sync, None);
435 let line = super::line(&Values::default(), &extra, None);
436 assert_eq!(line.status.as_deref(), Some("Down"));
437 }
438
439 #[test]
440 fn reads_the_diagnosis() {
441 let diagnosis = diagnosis_of(&values(&[
442 ("NewX_AVM-DE_DSLDiagnoseState", "DONE_CABLE_NOK"),
443 ("NewX_AVM-DE_DSLLastDiagnoseTime", "320"),
444 ("NewX_AVM-DE_DSLSignalLossTime", "0"),
445 ("NewX_AVM-DE_CableNokDistance", "350"),
446 ("NewX_AVM-DE_DSLSync", "0"),
447 ]));
448 assert_eq!(diagnosis.state.as_deref(), Some(CABLE_FAULT));
449 assert_eq!(diagnosis.last_run_seconds, Some(320));
450 assert_eq!(diagnosis.signal_lost_seconds, None);
451 assert_eq!(diagnosis.cable_fault_distance, Some(350));
452 assert_eq!(diagnosis.dsl_sync, Some(false));
453 let unknown = diagnosis_of(&values(&[
454 ("NewX_AVM-DE_DSLDiagnoseState", CABLE_FAULT),
455 ("NewX_AVM-DE_CableNokDistance", "-1"),
456 ]));
457 assert_eq!(unknown.cable_fault_distance, None);
458 let none = diagnosis_of(&values(&[
460 ("NewX_AVM-DE_DSLDiagnoseState", "NONE"),
461 ("NewX_AVM-DE_CableNokDistance", "0"),
462 ("NewX_AVM-DE_DSLSignalLossTime", "42"),
463 ]));
464 assert_eq!(none.cable_fault_distance, None);
465 assert_eq!(none.signal_lost_seconds, Some(42));
466 let documented = diagnosis_of(&values(&[("NewX_AVM-DE_DSLDigagnoseState", "RUNNING")]));
467 assert_eq!(documented.state.as_deref(), Some("RUNNING"));
468 }
469
470 #[test]
471 fn gives_hints() {
472 let details = Details {
473 line: Line {
474 sync: Some(false),
475 downstream_noise_margin: Some(4.5),
476 upstream_noise_margin: Some(9.0),
477 ..Line::default()
478 },
479 errors_since_sync: Some(Errors {
480 severely_errored_seconds: Some(3),
481 ..Errors::default()
482 }),
483 errors_total: Errors {
484 resyncs: Some(4),
485 ..Errors::default()
486 },
487 diagnosis: Some(Diagnosis {
488 signal_lost_seconds: Some(30),
489 cable_fault_distance: Some(120),
490 ..Diagnosis::default()
491 }),
492 ..Details::default()
493 };
494 assert_eq!(
495 hints(&details),
496 [
497 "the line is not synchronized",
498 "the downstream noise margin of 4.5 dB is below 6 dB: the line may lose its sync",
499 "3 severely errored seconds: the line had phases of many errors",
500 "the line resynchronized 4 times",
501 "the line lost its signal 30 s ago",
502 "the line diagnosis found a cable fault about 120 m away",
503 ]
504 );
505 let unknown = Details {
506 diagnosis: Some(Diagnosis {
507 state: Some(CABLE_FAULT.to_owned()),
508 ..Diagnosis::default()
509 }),
510 ..Details::default()
511 };
512 assert_eq!(
513 hints(&unknown),
514 ["the line diagnosis found a cable fault, but not how far away"]
515 );
516 assert_eq!(hints(&Details::default()), Vec::<String>::new());
517 }
518
519 #[test]
520 fn computes_changes_between_reads() {
521 let earlier = Report {
522 details: Some(Details {
523 errors_total: Errors {
524 crc: Some(10),
525 fec: Some(u64::from(u32::MAX)),
526 resyncs: Some(1),
527 ..Errors::default()
528 },
529 ..Details::default()
530 }),
531 ..Report::default()
532 };
533 let mut now = earlier.clone();
534 let details = now.details.as_mut().unwrap();
535 details.line.status = Some("Up".to_owned());
536 details.errors_total.crc = Some(13);
537 details.errors_total.fec = Some(4);
538 details.errors_total.resyncs = Some(2);
539 let sample = now.since(&earlier, 5.0);
540 assert_eq!(sample.status.as_deref(), Some("Up"));
541 let changes = sample.changes.unwrap();
542 assert_eq!(changes.crc, Some(3));
543 assert_eq!(changes.fec, Some(5));
544 assert_eq!(changes.hec, None);
545 assert_eq!(
546 sample.hints,
547 [
548 "CRC errors rose by 3 in 5 s: data was lost on the line",
549 "the line resynchronized",
550 ]
551 );
552 let steady = earlier.since(&earlier, 5.0);
553 assert_eq!(steady.hints, Vec::<String>::new());
554
555 let gone = Report {
556 note: Some("the connection is not DSL but Ethernet".to_owned()),
557 ..Report::default()
558 };
559 let sample = gone.since(&earlier, 5.0);
560 assert_eq!(sample.changes, None);
561 assert_eq!(sample.hints, ["the connection is not DSL but Ethernet"]);
562 }
563}