NtripClient.java

  1. /* Copyright 2002-2024 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.gnss.metric.ntrip;

  18. import java.io.BufferedReader;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.InputStreamReader;
  22. import java.net.Authenticator;
  23. import java.net.HttpURLConnection;
  24. import java.net.InetAddress;
  25. import java.net.InetSocketAddress;
  26. import java.net.Proxy;
  27. import java.net.Proxy.Type;
  28. import java.net.SocketAddress;
  29. import java.net.URI;
  30. import java.net.URISyntaxException;
  31. import java.net.URL;
  32. import java.net.URLConnection;
  33. import java.net.UnknownHostException;
  34. import java.nio.charset.StandardCharsets;
  35. import java.util.ArrayList;
  36. import java.util.Formatter;
  37. import java.util.HashMap;
  38. import java.util.List;
  39. import java.util.Locale;
  40. import java.util.Map;
  41. import java.util.concurrent.ExecutorService;
  42. import java.util.concurrent.Executors;
  43. import java.util.concurrent.TimeUnit;
  44. import java.util.concurrent.atomic.AtomicReference;

  45. import org.hipparchus.util.FastMath;
  46. import org.orekit.errors.OrekitException;
  47. import org.orekit.errors.OrekitMessages;
  48. import org.orekit.gnss.metric.messages.ParsedMessage;

  49. /** Source table for ntrip streams retrieval.
  50.  * <p>
  51.  * Note that all authentication is performed automatically by just
  52.  * calling the standard {@link Authenticator#setDefault(Authenticator)}
  53.  * method to set up an authenticator.
  54.  * </p>
  55.  * @author Luc Maisonobe
  56.  * @since 11.0
  57.  */
  58. public class NtripClient {

  59.     /** Default timeout for connections and reads (ms). */
  60.     public static final int DEFAULT_TIMEOUT = 10000;

  61.     /** Default port for ntrip communication. */
  62.     public static final int DEFAULT_PORT = 2101;

  63.     /** Default delay before we reconnect after connection close (s). */
  64.     public static final double DEFAULT_RECONNECT_DELAY = 1.0;

  65.     /** Default factor by which reconnection delay is multiplied after each attempt. */
  66.     public static final double DEFAULT_RECONNECT_DELAY_FACTOR = 1.5;

  67.     /** Default maximum number of reconnect a attempts without readin any data. */
  68.     public static final int DEFAULT_MAX_RECONNECT = 20;

  69.     /** Host header. */
  70.     private static final String HOST_HEADER_KEY = "Host";

  71.     /** User-agent header key. */
  72.     private static final String USER_AGENT_HEADER_KEY = "User-Agent";

  73.     /** User-agent header value. */
  74.     private static final String USER_AGENT_HEADER_VALUE = "NTRIP orekit/11.0";

  75.     /** Version header key. */
  76.     private static final String VERSION_HEADER_KEY = "Ntrip-Version";

  77.     /** Version header value. */
  78.     private static final String VERSION_HEADER_VALUE = "Ntrip/2.0";

  79.     /** Connection header key. */
  80.     private static final String CONNECTION_HEADER_KEY = "Connection";

  81.     /** Connection header value. */
  82.     private static final String CONNECTION_HEADER_VALUE = "close";

  83.     /** Flags header key. */
  84.     private static final String FLAGS_HEADER_KEY = "Ntrip-Flags";

  85.     /** Content type for source table. */
  86.     private static final String SOURCETABLE_CONTENT_TYPE = "gnss/sourcetable";

  87.     /** Degrees to arc minutes conversion factor. */
  88.     private static final double DEG_TO_MINUTES = 60.0;

  89.     /** Caster host. */
  90.     private final String host;

  91.     /** Caster port. */
  92.     private final int port;

  93.     /** Delay before we reconnect after connection close. */
  94.     private double reconnectDelay;

  95.     /** Multiplication factor for reconnection delay. */
  96.     private double reconnectDelayFactor;

  97.     /** Max number of reconnections. */
  98.     private int maxRetries;

  99.     /** Timeout for connections and reads. */
  100.     private int timeout;

  101.     /** Proxy to use. */
  102.     private Proxy proxy;

  103.     /** NMEA GGA sentence (may be null). */
  104.     private AtomicReference<String> gga;

  105.     /** Observers for encoded messages. */
  106.     private final List<ObserverHolder> observers;

  107.     /** Monitors for data streams. */
  108.     private final Map<String, StreamMonitor> monitors;

  109.     /** Source table. */
  110.     private SourceTable sourceTable;

  111.     /** Executor for stream monitoring tasks. */
  112.     private ExecutorService executorService;

  113.     /** Build a client for NTRIP.
  114.      * <p>
  115.      * The default configuration uses default timeout, default reconnection
  116.      * parameters, no GPS fix and no proxy.
  117.      * </p>
  118.      * @param host caster host providing the source table
  119.      * @param port port to use for connection
  120.      * see {@link #DEFAULT_PORT}
  121.      */
  122.     public NtripClient(final String host, final int port) {
  123.         this.host         = host;
  124.         this.port         = port;
  125.         this.observers    = new ArrayList<>();
  126.         this.monitors     = new HashMap<>();
  127.         setTimeout(DEFAULT_TIMEOUT);
  128.         setReconnectParameters(DEFAULT_RECONNECT_DELAY,
  129.                                DEFAULT_RECONNECT_DELAY_FACTOR,
  130.                                DEFAULT_MAX_RECONNECT);
  131.         setProxy(Type.DIRECT, null, -1);
  132.         this.gga             = new AtomicReference<String>(null);
  133.         this.sourceTable     = null;
  134.         this.executorService = null;
  135.     }

  136.     /** Get the caster host.
  137.      * @return caster host
  138.      */
  139.     public String getHost() {
  140.         return host;
  141.     }

  142.     /** Get the port to use for connection.
  143.      * @return port to use for connection
  144.      */
  145.     public int getPort() {
  146.         return port;
  147.     }

  148.     /** Set timeout for connections and reads.
  149.      * @param timeout timeout for connections and reads (ms)
  150.      */
  151.     public void setTimeout(final int timeout) {
  152.         this.timeout = timeout;
  153.     }

  154.     /** Set Reconnect parameters.
  155.      * @param delay delay before we reconnect after connection close
  156.      * @param delayFactor factor by which reconnection delay is multiplied after each attempt
  157.      * @param max max number of reconnect a attempts without reading any data
  158.      */
  159.     public void setReconnectParameters(final double delay,
  160.                                        final double delayFactor,
  161.                                        final int max) {
  162.         this.reconnectDelay       = delay;
  163.         this.reconnectDelayFactor = delayFactor;
  164.         this.maxRetries           = max;
  165.     }

  166.     /** Set proxy parameters.
  167.      * @param type proxy type
  168.      * @param proxyHost host name of the proxy (ignored if {@code type} is {@code Proxy.Type.DIRECT})
  169.      * @param proxyPort port number of the proxy (ignored if {@code type} is {@code Proxy.Type.DIRECT})
  170.      */
  171.     public void setProxy(final Proxy.Type type, final String proxyHost, final int proxyPort) {
  172.         try {
  173.             if (type == Proxy.Type.DIRECT) {
  174.                 // disable proxy
  175.                 proxy = Proxy.NO_PROXY;
  176.             } else {
  177.                 // enable proxy
  178.                 final InetAddress   hostAddress  = InetAddress.getByName(proxyHost);
  179.                 final SocketAddress proxyAddress = new InetSocketAddress(hostAddress, proxyPort);
  180.                 proxy = new Proxy(type, proxyAddress);
  181.             }
  182.         } catch (UnknownHostException uhe) {
  183.             throw new OrekitException(uhe, OrekitMessages.UNKNOWN_HOST, proxyHost);
  184.         }
  185.     }

  186.     /** Get proxy.
  187.      * @return proxy to use
  188.      */
  189.     public Proxy getProxy() {
  190.         return proxy;
  191.     }

  192.     /** Set GPS fix data to send as NMEA sentence to Ntrip caster if required.
  193.      * @param hour hour of the fix (UTC time)
  194.      * @param minute minute of the fix (UTC time)
  195.      * @param second second of the fix (UTC time)
  196.      * @param latitude latitude (radians)
  197.      * @param longitude longitude (radians)
  198.      * @param ellAltitude altitude above ellipsoid (m)
  199.      * @param undulation height of the geoid above ellipsoid (m)
  200.      */
  201.     public void setFix(final int hour, final int minute, final double second,
  202.                        final double latitude, final double longitude, final double ellAltitude,
  203.                        final double undulation) {

  204.         // convert latitude
  205.         final double latDeg = FastMath.abs(FastMath.toDegrees(latitude));
  206.         final int    dLat   = (int) FastMath.floor(latDeg);
  207.         final double mLat   = DEG_TO_MINUTES * (latDeg - dLat);
  208.         final char   cLat   = latitude >= 0.0 ? 'N' : 'S';

  209.         // convert longitude
  210.         final double lonDeg = FastMath.abs(FastMath.toDegrees(longitude));
  211.         final int    dLon   = (int) FastMath.floor(lonDeg);
  212.         final double mLon   = DEG_TO_MINUTES * (lonDeg - dLon);
  213.         final char   cLon   = longitude >= 0.0 ? 'E' : 'W';

  214.         // build NMEA GGA sentence
  215.         final StringBuilder builder = new StringBuilder(82);
  216.         try (Formatter formatter = new Formatter(builder, Locale.US)) {

  217.             // dummy values
  218.             final int    fixQuality = 1;
  219.             final int    nbSat      = 4;
  220.             final double hdop       = 1.0;

  221.             // sentence body
  222.             formatter.format("$GPGGA,%02d%02d%06.3f,%02d%07.4f,%c,%02d%07.4f,%c,%1d,%02d,%3.1f,%.1f,M,%.1f,M,,",
  223.                              hour, minute, second,
  224.                              dLat, mLat, cLat, dLon, mLon, cLon,
  225.                              fixQuality, nbSat, hdop,
  226.                              ellAltitude, undulation);

  227.             // checksum
  228.             byte sum = 0;
  229.             for (int i = 1; i < builder.length(); ++i) {
  230.                 sum ^= builder.charAt(i);
  231.             }
  232.             formatter.format("*%02X", sum);

  233.         }
  234.         gga.set(builder.toString());

  235.     }

  236.     /** Get NMEA GGA sentence.
  237.      * @return NMEA GGA sentence (may be null)
  238.      */
  239.     String getGGA() {
  240.         return gga.get();
  241.     }

  242.     /** Add an observer for an encoded messages.
  243.      * <p>
  244.      * If messages of the specified type have already been retrieved from
  245.      * a stream, the observer will be immediately notified with the last
  246.      * message from each mount point (in unspecified order) as a side effect
  247.      * of being added.
  248.      * </p>
  249.      * @param typeCode code for the message type (if set to 0, notification
  250.      * will be triggered regardless of message type)
  251.      * @param mountPoint mountPoint from which data must come (if null, notification
  252.      * will be triggered regardless of mount point)
  253.      * @param observer observer for this message type
  254.      */
  255.     public void addObserver(final int typeCode, final String mountPoint,
  256.                             final MessageObserver observer) {

  257.         // store the observer for future monitored mount points
  258.         observers.add(new ObserverHolder(typeCode, mountPoint, observer));

  259.         // check if we should also add it to already monitored mount points
  260.         for (Map.Entry<String, StreamMonitor> entry : monitors.entrySet()) {
  261.             if (mountPoint == null || mountPoint.equals(entry.getKey())) {
  262.                 entry.getValue().addObserver(typeCode, observer);
  263.             }
  264.         }

  265.     }

  266.     /** Get a sourcetable.
  267.      * @return source table from the caster
  268.      */
  269.     public SourceTable getSourceTable() {
  270.         if (sourceTable == null) {
  271.             try {

  272.                 // perform request
  273.                 final HttpURLConnection connection = connect("");

  274.                 final int responseCode = connection.getResponseCode();
  275.                 if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
  276.                     throw new OrekitException(OrekitMessages.FAILED_AUTHENTICATION, "caster");
  277.                 } else if (responseCode != HttpURLConnection.HTTP_OK) {
  278.                     throw new OrekitException(OrekitMessages.CONNECTION_ERROR, host, connection.getResponseMessage());
  279.                 }

  280.                 // for this request, we MUST get a source table
  281.                 if (!SOURCETABLE_CONTENT_TYPE.equals(connection.getContentType())) {
  282.                     throw new OrekitException(OrekitMessages.UNEXPECTED_CONTENT_TYPE, connection.getContentType());
  283.                 }

  284.                 final SourceTable table = new SourceTable(getHeaderValue(connection, FLAGS_HEADER_KEY));

  285.                 // parse source table records
  286.                 try (InputStream is = connection.getInputStream();
  287.                      InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
  288.                      BufferedReader br = new BufferedReader(isr)) {
  289.                     int lineNumber = 0;
  290.                     for (String line = br.readLine(); line != null; line = br.readLine()) {

  291.                         ++lineNumber;
  292.                         line = line.trim();
  293.                         if (line.length() == 0) {
  294.                             continue;
  295.                         }

  296.                         if (line.startsWith(RecordType.CAS.toString())) {
  297.                             table.addCasterRecord(new CasterRecord(line));
  298.                         } else if (line.startsWith(RecordType.NET.toString())) {
  299.                             table.addNetworkRecord(new NetworkRecord(line));
  300.                         } else if (line.startsWith(RecordType.STR.toString())) {
  301.                             table.addDataStreamRecord(new DataStreamRecord(line));
  302.                         } else if (line.startsWith("ENDSOURCETABLE")) {
  303.                             // we have reached end of table
  304.                             break;
  305.                         } else {
  306.                             throw new OrekitException(OrekitMessages.SOURCETABLE_PARSE_ERROR,
  307.                                                       connection.getURL().getHost(), lineNumber, line);
  308.                         }

  309.                     }
  310.                 }

  311.                 sourceTable = table;
  312.                 return table;

  313.             } catch (IOException | URISyntaxException e) {
  314.                 throw new OrekitException(e, OrekitMessages.CANNOT_PARSE_SOURCETABLE, host);
  315.             }
  316.         }

  317.         return sourceTable;

  318.     }

  319.     /** Connect to a mount point and start streaming data from it.
  320.      * <p>
  321.      * This method sets up an internal dedicated thread for continuously
  322.      * monitoring data incoming from a mount point. When new complete
  323.      * {@link ParsedMessage parsed messages} becomes available, the
  324.      * {@link MessageObserver observers} that have been registered
  325.      * using {@link #addObserver(int, String, MessageObserver) addObserver()}
  326.      * method will be notified about the message.
  327.      * </p>
  328.      * <p>
  329.      * This method must be called once for each stream to monitor.
  330.      * </p>
  331.      * @param mountPoint mount point providing the stream
  332.      * @param type messages type of the mount point
  333.      * @param requiresNMEA if true, the mount point requires a NMEA GGA sentence in the request
  334.      * @param ignoreUnknownMessageTypes if true, unknown messages types are silently ignored
  335.      */
  336.     public void startStreaming(final String mountPoint, final org.orekit.gnss.metric.ntrip.Type type,
  337.                                final boolean requiresNMEA, final boolean ignoreUnknownMessageTypes) {

  338.         if (executorService == null) {
  339.             // lazy creation of executor service, with one thread for each possible data stream
  340.             executorService = Executors.newFixedThreadPool(getSourceTable().getDataStreams().size());
  341.         }

  342.         // safety check
  343.         if (monitors.containsKey(mountPoint)) {
  344.             throw new OrekitException(OrekitMessages.MOUNPOINT_ALREADY_CONNECTED, mountPoint);
  345.         }

  346.         // create the monitor
  347.         final StreamMonitor monitor = new StreamMonitor(this, mountPoint, type, requiresNMEA, ignoreUnknownMessageTypes,
  348.                                                         reconnectDelay, reconnectDelayFactor, maxRetries);
  349.         monitors.put(mountPoint, monitor);

  350.         // set up the already known observers
  351.         for (final ObserverHolder observerHolder : observers) {
  352.             if (observerHolder.mountPoint == null ||
  353.                 observerHolder.mountPoint.equals(mountPoint)) {
  354.                 monitor.addObserver(observerHolder.typeCode, observerHolder.observer);
  355.             }
  356.         }

  357.         // start streaming data
  358.         executorService.execute(monitor);

  359.     }

  360.     /** Check if any of the streaming thread has thrown an exception.
  361.      * <p>
  362.      * If a streaming thread has thrown an exception, it will be rethrown here
  363.      * </p>
  364.      */
  365.     public void checkException() {
  366.         // check if any of the stream got an exception
  367.         for (final  Map.Entry<String, StreamMonitor> entry : monitors.entrySet()) {
  368.             final OrekitException exception = entry.getValue().getException();
  369.             if (exception != null) {
  370.                 throw exception;
  371.             }
  372.         }
  373.     }

  374.     /** Stop streaming data from all connected mount points.
  375.      * <p>
  376.      * If an exception was encountered during data streaming, it will be rethrown here
  377.      * </p>
  378.      * @param time timeout for waiting underlying threads termination (ms)
  379.      */
  380.     public void stopStreaming(final int time) {

  381.         // ask all monitors to stop retrieving data
  382.         for (final  Map.Entry<String, StreamMonitor> entry : monitors.entrySet()) {
  383.             entry.getValue().stopMonitoring();
  384.         }

  385.         try {
  386.             // wait for proper ending
  387.             executorService.shutdown();
  388.             executorService.awaitTermination(time, TimeUnit.MILLISECONDS);
  389.         } catch (InterruptedException ie) {
  390.             // Restore interrupted state...
  391.             Thread.currentThread().interrupt();
  392.         }

  393.         checkException();

  394.     }

  395.     /** Connect to caster.
  396.      * @param mountPoint mount point (empty for getting sourcetable)
  397.      * @return performed connection
  398.      * @throws IOException if an I/O exception occurs during connection
  399.      * @throws URISyntaxException if the built URI is invalid
  400.      */
  401.     HttpURLConnection connect(final String mountPoint)
  402.         throws IOException, URISyntaxException {

  403.         // set up connection
  404.         final String scheme = "http";
  405.         final URL casterURL = new URI(scheme, null, host, port, "/" + mountPoint, null, null).toURL();
  406.         final HttpURLConnection connection = (HttpURLConnection) casterURL.openConnection(proxy);
  407.         connection.setConnectTimeout(timeout);
  408.         connection.setReadTimeout(timeout);

  409.         // common headers
  410.         connection.setRequestProperty(HOST_HEADER_KEY,       host);
  411.         connection.setRequestProperty(VERSION_HEADER_KEY,    VERSION_HEADER_VALUE);
  412.         connection.setRequestProperty(USER_AGENT_HEADER_KEY, USER_AGENT_HEADER_VALUE);
  413.         connection.setRequestProperty(CONNECTION_HEADER_KEY, CONNECTION_HEADER_VALUE);

  414.         return connection;

  415.     }

  416.     /** Get an header from a response.
  417.      * @param connection connection to analyze
  418.      * @param key header key
  419.      * @return header value
  420.      */
  421.     private String getHeaderValue(final URLConnection connection, final String key) {
  422.         final String value = connection.getHeaderField(key);
  423.         if (value == null) {
  424.             throw new OrekitException(OrekitMessages.MISSING_HEADER,
  425.                                       connection.getURL().getHost(), key);
  426.         }
  427.         return value;
  428.     }

  429.     /** Local holder for observers. */
  430.     private static class ObserverHolder {

  431.         /** Code for the message type. */
  432.         private final int typeCode;

  433.         /** Mount point. */
  434.         private final String mountPoint;

  435.         /** Observer to notify. */
  436.         private final MessageObserver observer;

  437.         /** Simple constructor.
  438.          * @param typeCode code for the message type
  439.          * @param mountPoint mountPoint from which data must come (if null, notification
  440.          * will be triggered regardless of mount point)
  441.          * @param observer observer for this message type
  442.          */
  443.         ObserverHolder(final int typeCode, final String mountPoint,
  444.                             final MessageObserver observer) {
  445.             this.typeCode   = typeCode;
  446.             this.mountPoint = mountPoint;
  447.             this.observer   = observer;
  448.         }

  449.     }

  450. }