NtripClient.java

  1. /* Copyright 2002-2021 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.URL;
  30. import java.net.URLConnection;
  31. import java.net.UnknownHostException;
  32. import java.nio.charset.StandardCharsets;
  33. import java.util.ArrayList;
  34. import java.util.Formatter;
  35. import java.util.HashMap;
  36. import java.util.List;
  37. import java.util.Locale;
  38. import java.util.Map;
  39. import java.util.concurrent.ExecutorService;
  40. import java.util.concurrent.Executors;
  41. import java.util.concurrent.TimeUnit;
  42. import java.util.concurrent.atomic.AtomicReference;

  43. import org.orekit.errors.OrekitException;
  44. import org.orekit.errors.OrekitMessages;
  45. import org.orekit.gnss.metric.messages.ParsedMessage;

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

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

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

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

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

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

  66.     /** Host header. */
  67.     private static final String HOST_HEADER_KEY = "Host";

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

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

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

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

  76.     /** Connection header key. */
  77.     private static final String CONNECTION_HEADER_KEY = "Connection";

  78.     /** Connection header value. */
  79.     private static final String CONNECTION_HEADER_VALUE = "close";

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

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

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

  86.     /** Caster host. */
  87.     private final String host;

  88.     /** Caster port. */
  89.     private final int port;

  90.     /** Delay before we reconnect after connection close. */
  91.     private double reconnectDelay;

  92.     /** Multiplication factor for reconnection delay. */
  93.     private double reconnectDelayFactor;

  94.     /** Max number of reconnections. */
  95.     private int maxRetries;

  96.     /** Timeout for connections and reads. */
  97.     private int timeout;

  98.     /** Proxy to use. */
  99.     private Proxy proxy;

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

  102.     /** Observers for encoded messages. */
  103.     private final List<ObserverHolder> observers;

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

  106.     /** Source table. */
  107.     private SourceTable sourceTable;

  108.     /** Executor for stream monitoring tasks. */
  109.     private ExecutorService executorService;

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

  133.     /** Get the caster host.
  134.      * @return caster host
  135.      */
  136.     public String getHost() {
  137.         return host;
  138.     }

  139.     /** Get the port to use for connection.
  140.      * @return port to use for connection
  141.      */
  142.     public int getPort() {
  143.         return port;
  144.     }

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

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

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

  183.     /** Get proxy.
  184.      * @return proxy to use
  185.      */
  186.     public Proxy getProxy() {
  187.         return proxy;
  188.     }

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

  201.         // convert latitude
  202.         final double latDeg = Math.abs(Math.toDegrees(latitude));
  203.         final int    dLat   = (int) Math.floor(latDeg);
  204.         final double mLat   = DEG_TO_MINUTES * (latDeg - dLat);
  205.         final char   cLat   = latitude >= 0.0 ? 'N' : 'S';

  206.         // convert longitude
  207.         final double lonDeg = Math.abs(Math.toDegrees(longitude));
  208.         final int    dLon   = (int) Math.floor(lonDeg);
  209.         final double mLon   = DEG_TO_MINUTES * (lonDeg - dLon);
  210.         final char   cLon   = longitude >= 0.0 ? 'E' : 'W';

  211.         // build NMEA GGA sentence
  212.         final StringBuilder builder = new StringBuilder(82);
  213.         try (Formatter formatter = new Formatter(builder, Locale.US)) {

  214.             // dummy values
  215.             final int    fixQuality = 1;
  216.             final int    nbSat      = 4;
  217.             final double hdop       = 1.0;

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

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

  230.         }
  231.         gga.set(builder.toString());

  232.     }

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

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

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

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

  262.     }

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

  269.                 // perform request
  270.                 final HttpURLConnection connection = connect("");

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

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

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

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

  288.                         ++lineNumber;
  289.                         line = line.trim();
  290.                         if (line.length() == 0) {
  291.                             continue;
  292.                         }

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

  306.                     }
  307.                 }

  308.                 sourceTable = table;
  309.                 return table;

  310.             } catch (IOException ioe) {
  311.                 throw new OrekitException(ioe, OrekitMessages.CANNOT_PARSE_SOURCETABLE, host);
  312.             }
  313.         }

  314.         return sourceTable;

  315.     }

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

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

  339.         // safety check
  340.         if (monitors.containsKey(mountPoint)) {
  341.             throw new OrekitException(OrekitMessages.MOUNPOINT_ALREADY_CONNECTED, mountPoint);
  342.         }

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

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

  354.         // start streaming data
  355.         executorService.execute(monitor);

  356.     }

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

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

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

  382.         try {
  383.             // wait for proper ending
  384.             executorService.awaitTermination(time, TimeUnit.MILLISECONDS);
  385.         } catch (InterruptedException ie) {
  386.             // Restore interrupted state...
  387.             Thread.currentThread().interrupt();
  388.         }

  389.         checkException();

  390.     }

  391.     /** Connect to caster.
  392.      * @param mountPoint mount point (empty for getting sourcetable)
  393.      * @return performed connection
  394.      * @throws IOException if an I/O exception occurs during connection
  395.      */
  396.     HttpURLConnection connect(final String mountPoint)
  397.         throws IOException {

  398.         // set up connection
  399.         final String protocol = "http";
  400.         final URL casterURL = new URL(protocol, host, port, "/" + mountPoint);
  401.         final HttpURLConnection connection = (HttpURLConnection) casterURL.openConnection(proxy);
  402.         connection.setConnectTimeout(timeout);
  403.         connection.setReadTimeout(timeout);

  404.         // common headers
  405.         connection.setRequestProperty(HOST_HEADER_KEY,       host);
  406.         connection.setRequestProperty(VERSION_HEADER_KEY,    VERSION_HEADER_VALUE);
  407.         connection.setRequestProperty(USER_AGENT_HEADER_KEY, USER_AGENT_HEADER_VALUE);
  408.         connection.setRequestProperty(CONNECTION_HEADER_KEY, CONNECTION_HEADER_VALUE);

  409.         return connection;

  410.     }

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

  424.     /** Local holder for observers. */
  425.     private static class ObserverHolder {

  426.         /** Code for the message type. */
  427.         private final int typeCode;

  428.         /** Mount point. */
  429.         private final String mountPoint;

  430.         /** Observer to notify. */
  431.         private final MessageObserver observer;

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

  444.     }

  445. }