StreamMonitor.java

  1. /* Copyright 2002-2022 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.util.ArrayList;
  23. import java.util.Arrays;
  24. import java.util.HashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.concurrent.atomic.AtomicBoolean;
  28. import java.util.concurrent.atomic.AtomicReference;

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

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

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

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

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

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

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

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

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

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

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

  59.     static {

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

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

  73.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  146.             // register the observer
  147.             List<MessageObserver> list = observers.get(typeCode);
  148.             if (list == null) {
  149.                 // create a new list the first time we register an observer for a message
  150.                 list =  new ArrayList<>();
  151.                 observers.put(typeCode, list);
  152.             }
  153.             list.add(observer);

  154.             // if we already have a message of the proper type
  155.             // immediately notify the new observer about it
  156.             final ParsedMessage last = lastMessages.get(typeCode);
  157.             if (last != null) {
  158.                 observer.messageAvailable(mountPoint, last);
  159.             }

  160.         }
  161.     }

  162.     /** Stop monitoring. */
  163.     public void stopMonitoring() {
  164.         stop.set(true);
  165.     }

  166.     /** Retrieve exception caught during monitoring.
  167.      * @return exception caught
  168.      */
  169.     public OrekitException getException() {
  170.         return exception.get();
  171.     }

  172.     /** {@inheritDoc} */
  173.     @Override
  174.     public void run() {

  175.         try {

  176.             final MessagesParser parser = type.getParser(extractUsedMessages());
  177.             int nbAttempts = 0;
  178.             double delay = reconnectDelay;
  179.             while (nbAttempts < maxRetries) {

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

  191.                     // perform request
  192.                     final int responseCode = connection.getResponseCode();
  193.                     if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
  194.                         throw new OrekitException(OrekitMessages.FAILED_AUTHENTICATION, mountPoint);
  195.                     } else if (responseCode != HttpURLConnection.HTTP_OK) {
  196.                         throw new OrekitException(OrekitMessages.CONNECTION_ERROR,
  197.                                                   connection.getURL().getHost(),
  198.                                                   connection.getResponseMessage());
  199.                     }

  200.                     // for this request, we MUST get GNSS data
  201.                     if (!GNSS_DATA_CONTENT_TYPE.equals(connection.getContentType())) {
  202.                         throw new OrekitException(OrekitMessages.UNEXPECTED_CONTENT_TYPE, connection.getContentType());
  203.                     }

  204.                     // data extraction loop
  205.                     resetCircularBuffer();
  206.                     try (InputStream is = connection.getInputStream()) {

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

  208.                             // we have read something, reset reconnection attempts counters
  209.                             nbAttempts = 0;
  210.                             delay      = reconnectDelay;

  211.                             if (stop.get()) {
  212.                                 // stop monitoring immediately
  213.                                 // (returning closes the input stream automatically)
  214.                                 return;
  215.                             }

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

  253.                         }

  254.                     }
  255.                 } catch (SocketTimeoutException ste) {
  256.                     // ignore exception, it will be handled by reconnection attempt below
  257.                 } catch (IOException ioe) {
  258.                     throw new OrekitException(ioe, OrekitMessages.CANNOT_PARSE_GNSS_DATA, client.getHost());
  259.                 }

  260.                 // manage reconnection
  261.                 try {
  262.                     Thread.sleep((int) FastMath.rint(delay * 1000));
  263.                 } catch (InterruptedException ie) {
  264.                     // Restore interrupted state...
  265.                     Thread.currentThread().interrupt();
  266.                 }
  267.                 ++nbAttempts;
  268.                 delay *= reconnectDelayFactor;

  269.             }

  270.         } catch (OrekitException oe) {
  271.             // store the exception so it can be retrieved by Ntrip client
  272.             exception.set(oe);
  273.         }

  274.     }

  275.     /** Store a parsed encoded message and notify observers.
  276.      * @param message parsed message
  277.      */
  278.     private void storeAndNotify(final ParsedMessage message) {
  279.         synchronized (observers) {

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

  281.                 // store message
  282.                 lastMessages.put(typeCode, message);

  283.                 // notify observers
  284.                 final List<MessageObserver> list = observers.get(typeCode);
  285.                 if (list != null) {
  286.                     for (final MessageObserver observer : list) {
  287.                         // notify observer
  288.                         observer.messageAvailable(mountPoint, message);
  289.                     }
  290.                 }

  291.             }

  292.         }
  293.     }

  294.     /** Reset the circular buffer.
  295.      */
  296.     private void resetCircularBuffer() {
  297.         buffer     = new byte[BUFFER_SIZE];
  298.         readIndex  = 0;
  299.         writeIndex = 0;
  300.     }

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

  319.     /** {@inheritDoc} */
  320.     @Override
  321.     protected int fetchByte() {
  322.         if (readIndex == messageEndIndex || readIndex == writeIndex) {
  323.             return -1;
  324.         }

  325.         final int ret = buffer[readIndex] & 0xFF;
  326.         moveRead(1);
  327.         return ret;
  328.     }

  329.     /** Get the number of bytes currently in the buffer.
  330.      * @return number of bytes currently in the buffer
  331.      */
  332.     private int bufferSize() {
  333.         final int n = writeIndex - readIndex;
  334.         return n >= 0 ? n : BUFFER_SIZE + n;
  335.     }

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

  343.     /** Move read pointer.
  344.      * @param n number of bytes to move read pointer
  345.      */
  346.     private void moveRead(final int n) {
  347.         readIndex = (readIndex + n) % BUFFER_SIZE;
  348.     }

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

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

  370.     private List<Integer> extractUsedMessages() {
  371.         synchronized (observers) {

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

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

  381.             return messages;
  382.         }
  383.     }

  384. }