2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.network.internal.utils;
15 import java.util.Optional;
16 import java.util.regex.Matcher;
17 import java.util.regex.Pattern;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * Examines output lines of the ping command and tries to extract the contained latency value.
25 * @author Andreas Hirsch - Initial contribution
27 public class LatencyParser {
29 private final Logger logger = LoggerFactory.getLogger(LatencyParser.class);
31 // This is how the input looks like on Mac and Linux:
32 // ping -c 1 192.168.1.1
33 // PING 192.168.1.1 (192.168.1.1): 56 data bytes
34 // 64 bytes from 192.168.1.1: icmp_seq=0 ttl=64 time=1.225 ms
36 // --- 192.168.1.1 ping statistics ---
37 // 1 packets transmitted, 1 packets received, 0.0% packet loss
38 // round-trip min/avg/max/stddev = 1.225/1.225/1.225/0.000 ms
41 * Examine a single ping command output line and try to extract the latency value if it is contained.
43 * @param inputLine Single output line of the ping command.
44 * @return Latency value provided by the ping command. Optional is empty if the provided line did not contain a
45 * latency value which matches the known patterns.
47 public Optional<Double> parseLatency(String inputLine) {
48 logger.debug("Parsing latency from input {}", inputLine);
50 String pattern = ".*time=(.*) ms";
51 Matcher m = Pattern.compile(pattern).matcher(inputLine);
52 if (m.find() && m.groupCount() == 1) {
53 return Optional.of(Double.parseDouble(m.group(1)));
56 logger.debug("Did not find a latency value");
57 return Optional.empty();