]> git.basschouten.com Git - openhab-addons.git/blob
f8222bd9a2894b33f8e8744064f9550e3c17a929
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.network.internal.utils;
14
15 import java.util.Optional;
16 import java.util.regex.Matcher;
17 import java.util.regex.Pattern;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 /**
24  * Examines output lines of the ping command and tries to extract the contained latency value.
25  *
26  * @author Andreas Hirsch - Initial contribution
27  */
28 @NonNullByDefault
29 public class LatencyParser {
30
31     private static final Pattern LATENCY_PATTERN = Pattern.compile(".*time=(.*) ?ms");
32     private final Logger logger = LoggerFactory.getLogger(LatencyParser.class);
33
34     // This is how the input looks like on Mac and Linux:
35     // ping -c 1 192.168.1.1
36     // PING 192.168.1.1 (192.168.1.1): 56 data bytes
37     // 64 bytes from 192.168.1.1: icmp_seq=0 ttl=64 time=1.225 ms
38     //
39     // --- 192.168.1.1 ping statistics ---
40     // 1 packets transmitted, 1 packets received, 0.0% packet loss
41     // round-trip min/avg/max/stddev = 1.225/1.225/1.225/0.000 ms
42
43     /**
44      * Examine a single ping command output line and try to extract the latency value if it is contained.
45      *
46      * @param inputLine Single output line of the ping command.
47      * @return Latency value provided by the ping command. Optional is empty if the provided line did not contain a
48      *         latency value which matches the known patterns.
49      */
50     public Optional<Double> parseLatency(String inputLine) {
51         logger.debug("Parsing latency from input {}", inputLine);
52
53         Matcher m = LATENCY_PATTERN.matcher(inputLine);
54         if (m.find() && m.groupCount() == 1) {
55             return Optional.of(Double.parseDouble(m.group(1)));
56         }
57
58         logger.debug("Did not find a latency value");
59         return Optional.empty();
60     }
61 }