]> git.basschouten.com Git - openhab-addons.git/blob
416d455edfdb0413fc6c232088eca7906712a771
[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 static org.openhab.binding.network.internal.utils.NetworkUtils.millisToDuration;
16
17 import java.time.Duration;
18 import java.util.regex.Matcher;
19 import java.util.regex.Pattern;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 /**
27  * Examines output lines of the ping command and tries to extract the contained latency value.
28  *
29  * @author Andreas Hirsch - Initial contribution
30  */
31 @NonNullByDefault
32 public class LatencyParser {
33
34     private static final Pattern LATENCY_PATTERN = Pattern.compile(".*time=(.*) ?ms");
35     private final Logger logger = LoggerFactory.getLogger(LatencyParser.class);
36
37     // This is how the input looks like on Mac and Linux:
38     // ping -c 1 192.168.1.1
39     // PING 192.168.1.1 (192.168.1.1): 56 data bytes
40     // 64 bytes from 192.168.1.1: icmp_seq=0 ttl=64 time=1.225 ms
41     //
42     // --- 192.168.1.1 ping statistics ---
43     // 1 packets transmitted, 1 packets received, 0.0% packet loss
44     // round-trip min/avg/max/stddev = 1.225/1.225/1.225/0.000 ms
45
46     /**
47      * Examine a single ping command output line and try to extract the latency value if it is contained.
48      *
49      * @param inputLine Single output line of the ping command.
50      * @return Latency value provided by the ping command. <code>null</code> if the provided line did not contain a
51      *         latency value which matches the known patterns.
52      */
53     public @Nullable Duration parseLatency(String inputLine) {
54         logger.debug("Parsing latency from input {}", inputLine);
55
56         Matcher m = LATENCY_PATTERN.matcher(inputLine);
57         if (m.find() && m.groupCount() == 1) {
58             return millisToDuration(Double.parseDouble(m.group(1)));
59         }
60
61         logger.debug("Did not find a latency value");
62         return null;
63     }
64 }