StreamMonitor.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.IOException;
  19. import java.io.InputStream;
  20. import java.net.HttpURLConnection;
  21. import java.net.SocketTimeoutException;
  22. import java.net.URISyntaxException;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.HashMap;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.concurrent.atomic.AtomicBoolean;
  29. import java.util.concurrent.atomic.AtomicReference;

  30. import org.hipparchus.util.FastMath;
  31. import org.orekit.errors.OrekitException;
  32. import org.orekit.errors.OrekitInternalError;
  33. import org.orekit.errors.OrekitMessages;
  34. import org.orekit.gnss.metric.messages.ParsedMessage;
  35. import org.orekit.gnss.metric.parser.AbstractEncodedMessage;
  36. import org.orekit.gnss.metric.parser.MessagesParser;

  37. /** Monitor for retrieving streamed data from one mount point.
  38.  * @author Luc Maisonobe
  39.  * @since 11.0
  40.  */
  41. public class StreamMonitor extends AbstractEncodedMessage implements Runnable {

  42.     /** GGA header key. */
  43.     private static final String GGA_HEADER_KEY = "Ntrip-GGA";

  44.     /** Content type for GNSS data. */
  45.     private static final String GNSS_DATA_CONTENT_TYPE = "gnss/data";

  46.     /** Size of buffer for retrieving data. */
  47.     private static final int BUFFER_SIZE = 0x4000;

  48.     /** Frame preamble. */
  49.     private static final int PREAMBLE = 0xD3;

  50.     /** Frame preamble size. */
  51.     private static final int PREAMBLE_SIZE = 3;

  52.     /** Frame CRC size. */
  53.     private static final int CRC_SIZE = 3;

  54.     /** Generator polynomial for CRC. */
  55.     private static final int GENERATOR = 0x1864CFB;

  56.     /** High bit of the generator polynomial. */
  57.     private static final int HIGH = 0x1000000;

  58.     /** CRC 24Q lookup table. */
  59.     private static final int[] CRC_LOOKUP = new int[256];

  60.     static {

  61.         // set up lookup table
  62.         CRC_LOOKUP[0] = 0;
  63.         CRC_LOOKUP[1] = GENERATOR;

  64.         int h = GENERATOR;
  65.         for (int i = 2; i < 256; i <<= 1) {
  66.             h <<= 1;
  67.             if ((h & HIGH) != 0) {
  68.                 h ^= GENERATOR;
  69.             }
  70.             for (int j = 0; j < i; ++j) {
  71.                 CRC_LOOKUP[i + j] = CRC_LOOKUP[j] ^ h;
  72.             }
  73.         }

  74.     }

  75.     /** Associated NTRIP client. */
  76.     private final NtripClient client;

  77.     /** Mount point providing the stream. */
  78.     private final String mountPoint;

  79.     /** Messages type of the mount point. */
  80.     private final Type type;

  81.     /** Indicator for required NMEA. */
  82.     private final boolean nmeaRequired;

  83.     /** Indicator for ignoring unknown messages. */
  84.     private final boolean ignoreUnknownMessageTypes;

  85.     /** Delay before we reconnect after connection close. */
  86.     private final double reconnectDelay;

  87.     /** Multiplication factor for reconnection delay. */
  88.     private final double reconnectDelayFactor;

  89.     /** Max number of reconnections. */
  90.     private final int maxRetries;

  91.     /** Stop flag. */
  92.     private AtomicBoolean stop;

  93.     /** Circular buffer. */
  94.     private byte[] buffer;

  95.     /** Read index. */
  96.     private int readIndex;

  97.     /** Message end index. */
  98.     private int messageEndIndex;

  99.     /** Write index. */
  100.     private int writeIndex;

  101.     /** Observers for encoded messages. */
  102.     private final Map<Integer, List<MessageObserver>> observers;

  103.     /** Last available message for each type. */
  104.     private final Map<Integer, ParsedMessage> lastMessages;

  105.     /** Exception caught during monitoring. */
  106.     private final AtomicReference<OrekitException> exception;

  107.     /** Build a monitor for streaming data from a mount point.
  108.      * @param client associated NTRIP client
  109.      * @param mountPoint mount point providing the stream
  110.      * @param type messages type of the mount point
  111.      * @param requiresNMEA if true, the mount point requires a NMEA GGA sentence in the request
  112.      * @param ignoreUnknownMessageTypes if true, unknown messages types are silently ignored
  113.      * @param reconnectDelay delay before we reconnect after connection close
  114.      * @param reconnectDelayFactor factor by which reconnection delay is multiplied after each attempt
  115.      * @param maxRetries max number of reconnect a attempts without reading any data
  116.      */
  117.     public StreamMonitor(final NtripClient client,
  118.                          final String mountPoint, final Type type,
  119.                          final boolean requiresNMEA, final boolean ignoreUnknownMessageTypes,
  120.                          final double reconnectDelay, final double reconnectDelayFactor,
  121.                          final int maxRetries) {
  122.         this.client                    = client;
  123.         this.mountPoint                = mountPoint;
  124.         this.type                      = type;
  125.         this.nmeaRequired              = requiresNMEA;
  126.         this.ignoreUnknownMessageTypes = ignoreUnknownMessageTypes;
  127.         this.reconnectDelay            = reconnectDelay;
  128.         this.reconnectDelayFactor      = reconnectDelayFactor;
  129.         this.maxRetries                = maxRetries;
  130.         this.stop                      = new AtomicBoolean(false);
  131.         this.observers                 = new HashMap<>();
  132.         this.lastMessages              = new HashMap<>();
  133.         this.exception                 = new AtomicReference<OrekitException>(null);
  134.     }

  135.     /** Add an observer for encoded messages.
  136.      * <p>
  137.      * If messages of the specified type have already been retrieved from
  138.      * a stream, the observer will be immediately notified with the last
  139.      * message as a side effect of being added.
  140.      * </p>
  141.      * @param typeCode code for the message type (if set to 0, notification
  142.      * will be triggered regardless of message type)
  143.      * @param observer observer for this message type
  144.      */
  145.     public void addObserver(final int typeCode, final MessageObserver observer) {
  146.         synchronized (observers) {

  147.             // register the observer
  148.             observers.computeIfAbsent(typeCode, tc -> new ArrayList<>()).add(observer);

  149.             // if we already have a message of the proper type
  150.             // immediately notify the new observer about it
  151.             final ParsedMessage last = lastMessages.get(typeCode);
  152.             if (last != null) {
  153.                 observer.messageAvailable(mountPoint, last);
  154.             }

  155.         }
  156.     }

  157.     /** Stop monitoring. */
  158.     public void stopMonitoring() {
  159.         stop.set(true);
  160.     }

  161.     /** Retrieve exception caught during monitoring.
  162.      * @return exception caught
  163.      */
  164.     public OrekitException getException() {
  165.         return exception.get();
  166.     }

  167.     /** {@inheritDoc} */
  168.     @Override
  169.     public void run() {

  170.         try {

  171.             final MessagesParser parser = type.getParser(extractUsedMessages());
  172.             int nbAttempts = 0;
  173.             double delay = reconnectDelay;
  174.             while (nbAttempts < maxRetries) {

  175.                 try {
  176.                     // prepare request
  177.                     final HttpURLConnection connection = client.connect(mountPoint);
  178.                     if (nmeaRequired) {
  179.                         if (client.getGGA() == null) {
  180.                             throw new OrekitException(OrekitMessages.STREAM_REQUIRES_NMEA_FIX, mountPoint);
  181.                         } else {
  182.                             // update NMEA GGA sentence in the extra headers for this mount point
  183.                             connection.setRequestProperty(GGA_HEADER_KEY, client.getGGA());
  184.                         }
  185.                     }

  186.                     // perform request
  187.                     final int responseCode = connection.getResponseCode();
  188.                     if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
  189.                         throw new OrekitException(OrekitMessages.FAILED_AUTHENTICATION, mountPoint);
  190.                     } else if (responseCode != HttpURLConnection.HTTP_OK) {
  191.                         throw new OrekitException(OrekitMessages.CONNECTION_ERROR,
  192.                                                   connection.getURL().getHost(),
  193.                                                   connection.getResponseMessage());
  194.                     }

  195.                     // for this request, we MUST get GNSS data
  196.                     if (!GNSS_DATA_CONTENT_TYPE.equals(connection.getContentType())) {
  197.                         throw new OrekitException(OrekitMessages.UNEXPECTED_CONTENT_TYPE, connection.getContentType());
  198.                     }

  199.                     // data extraction loop
  200.                     resetCircularBuffer();
  201.                     try (InputStream is = connection.getInputStream()) {

  202.                         for (int r = fillUp(is); r >= 0; r = fillUp(is)) {

  203.                             // we have read something, reset reconnection attempts counters
  204.                             nbAttempts = 0;
  205.                             delay      = reconnectDelay;

  206.                             if (stop.get()) {
  207.                                 // stop monitoring immediately
  208.                                 // (returning closes the input stream automatically)
  209.                                 return;
  210.                             }

  211.                             while (bufferSize() >= 3) {
  212.                                 if (peekByte(0) != PREAMBLE) {
  213.                                     // we are out of synch with respect to frame structure
  214.                                     // drop the unknown byte
  215.                                     moveRead(1);
  216.                                 } else {
  217.                                     final int size = (peekByte(1) & 0x03) << 8 | peekByte(2);
  218.                                     if (bufferSize() >= PREAMBLE_SIZE + size + CRC_SIZE) {
  219.                                         // check CRC
  220.                                         final int crc = (peekByte(PREAMBLE_SIZE + size)     << 16) |
  221.                                                         (peekByte(PREAMBLE_SIZE + size + 1) <<  8) |
  222.                                                          peekByte(PREAMBLE_SIZE + size + 2);
  223.                                         if (crc == computeCRC(PREAMBLE_SIZE + size)) {
  224.                                             // we have a complete and consistent frame
  225.                                             // we can extract the message it contains
  226.                                             messageEndIndex = (readIndex + PREAMBLE_SIZE + size) % BUFFER_SIZE;
  227.                                             moveRead(PREAMBLE_SIZE);
  228.                                             start();
  229.                                             final ParsedMessage message = parser.parse(this, ignoreUnknownMessageTypes);
  230.                                             if (message != null) {
  231.                                                 storeAndNotify(message);
  232.                                             }
  233.                                             // jump to expected message end, in case the message was corrupted
  234.                                             // and parsing did not reach message end
  235.                                             readIndex = (messageEndIndex + CRC_SIZE) % BUFFER_SIZE;
  236.                                         } else {
  237.                                             // CRC is not consistent, we are probably not really synched
  238.                                             // and the preamble byte was just a random byte
  239.                                             // we drop this single byte and continue looking for sync
  240.                                             moveRead(1);
  241.                                         }
  242.                                     } else {
  243.                                         // the frame is not complete, we need more data
  244.                                         break;
  245.                                     }
  246.                                 }
  247.                             }

  248.                         }

  249.                     }
  250.                 } catch (SocketTimeoutException ste) {
  251.                     // ignore exception, it will be handled by reconnection attempt below
  252.                 } catch (IOException | URISyntaxException e) {
  253.                     throw new OrekitException(e, OrekitMessages.CANNOT_PARSE_GNSS_DATA, client.getHost());
  254.                 }

  255.                 // manage reconnection
  256.                 try {
  257.                     Thread.sleep((int) FastMath.rint(delay * 1000));
  258.                 } catch (InterruptedException ie) {
  259.                     // Restore interrupted state...
  260.                     Thread.currentThread().interrupt();
  261.                 }
  262.                 ++nbAttempts;
  263.                 delay *= reconnectDelayFactor;

  264.             }

  265.         } catch (OrekitException oe) {
  266.             // store the exception so it can be retrieved by Ntrip client
  267.             exception.set(oe);
  268.         }

  269.     }

  270.     /** Store a parsed encoded message and notify observers.
  271.      * @param message parsed message
  272.      */
  273.     private void storeAndNotify(final ParsedMessage message) {
  274.         synchronized (observers) {

  275.             for (int typeCode : Arrays.asList(0, message.getTypeCode())) {

  276.                 // store message
  277.                 lastMessages.put(typeCode, message);

  278.                 // notify observers
  279.                 final List<MessageObserver> list = observers.get(typeCode);
  280.                 if (list != null) {
  281.                     for (final MessageObserver observer : list) {
  282.                         // notify observer
  283.                         observer.messageAvailable(mountPoint, message);
  284.                     }
  285.                 }

  286.             }

  287.         }
  288.     }

  289.     /** Reset the circular buffer.
  290.      */
  291.     private void resetCircularBuffer() {
  292.         buffer     = new byte[BUFFER_SIZE];
  293.         readIndex  = 0;
  294.         writeIndex = 0;
  295.     }

  296.     /** Extract data from input stream.
  297.      * @param is input stream to extract data from
  298.      * @return number of byes read or -1
  299.      * @throws IOException if data cannot be extracted properly
  300.      */
  301.     private int fillUp(final InputStream is) throws IOException {
  302.         final int max = bufferMaxWrite();
  303.         if (max == 0) {
  304.             // this should never happen
  305.             // the buffer is large enough for almost 16 encoded messages, including wrapping frame
  306.             throw new OrekitInternalError(null);
  307.         }
  308.         final int r = is.read(buffer, writeIndex, max);
  309.         if (r >= 0) {
  310.             writeIndex = (writeIndex + r) % BUFFER_SIZE;
  311.         }
  312.         return r;
  313.     }

  314.     /** {@inheritDoc} */
  315.     @Override
  316.     protected int fetchByte() {
  317.         if (readIndex == messageEndIndex || readIndex == writeIndex) {
  318.             return -1;
  319.         }

  320.         final int ret = buffer[readIndex] & 0xFF;
  321.         moveRead(1);
  322.         return ret;
  323.     }

  324.     /** Get the number of bytes currently in the buffer.
  325.      * @return number of bytes currently in the buffer
  326.      */
  327.     private int bufferSize() {
  328.         final int n = writeIndex - readIndex;
  329.         return n >= 0 ? n : BUFFER_SIZE + n;
  330.     }

  331.     /** Peek a buffer byte without moving read pointer.
  332.      * @param offset offset counted from read pointer
  333.      * @return value of the byte at given offset
  334.      */
  335.     private int peekByte(final int offset) {
  336.         return buffer[(readIndex + offset) % BUFFER_SIZE] & 0xFF;
  337.     }

  338.     /** Move read pointer.
  339.      * @param n number of bytes to move read pointer
  340.      */
  341.     private void moveRead(final int n) {
  342.         readIndex = (readIndex + n) % BUFFER_SIZE;
  343.     }

  344.     /** Get the number of bytes that can be added to the buffer without wrapping around.
  345.      * @return number of bytes that can be added
  346.      */
  347.     private int bufferMaxWrite() {
  348.         if (writeIndex >= readIndex) {
  349.             return (readIndex == 0 ? BUFFER_SIZE - 1 : BUFFER_SIZE) - writeIndex;
  350.         } else {
  351.             return readIndex - writeIndex - 1;
  352.         }
  353.     }

  354.     /** Compute QualCom CRC.
  355.      * @param length length of the byte stream
  356.      * @return QualCom CRC
  357.      */
  358.     private int computeCRC(final int length) {
  359.         int crc = 0;
  360.         for (int i = 0; i < length; ++i) {
  361.             crc = ((crc << 8) ^ CRC_LOOKUP[peekByte(i) ^ (crc >>> 16)]) & (HIGH - 1);
  362.         }
  363.         return crc;
  364.     }

  365.     /** Extract the used messages.
  366.      * @return the extracted messages
  367.      */
  368.     private List<Integer> extractUsedMessages() {
  369.         synchronized (observers) {

  370.             // List of needed messages
  371.             final List<Integer> messages = new ArrayList<>();

  372.             // Loop on observers entries
  373.             for (Map.Entry<Integer, List<MessageObserver>> entry : observers.entrySet()) {
  374.                 // Extract message type code
  375.                 final int typeCode = entry.getKey();
  376.                 // Add to the list
  377.                 messages.add(typeCode);
  378.             }

  379.             return messages;
  380.         }
  381.     }

  382. }