public void Write(Location location)
        {
            string[] lineTokens = new string[]
            {
                location.IsLocationServiceEnabled.ToString(),
                     location.IsLocationServiceInitializing.ToString(),
                     location.IsLocationUpdated.ToString(),
                     location.IsUserHeadingUpdated.ToString(),
                     location.Provider,
                     LocationProviderFactory.Instance.DefaultLocationProvider.GetType().Name,
                     DateTime.UtcNow.ToString("yyyyMMdd-HHmmss.fff"),
                UnixTimestampUtils.From(location.Timestamp).ToString("yyyyMMdd-HHmmss.fff"),
                string.Format(_invariantCulture, "{0:0.00000000}", location.LatitudeLongitude.x),
                string.Format(_invariantCulture, "{0:0.00000000}", location.LatitudeLongitude.y),
                string.Format(_invariantCulture, "{0:0.0}", location.Accuracy),
                string.Format(_invariantCulture, "{0:0.0}", location.UserHeading),
                string.Format(_invariantCulture, "{0:0.0}", location.DeviceOrientation),
                nullableAsStr <float>(location.SpeedKmPerHour, "{0:0.0}"),
                nullableAsStr <bool>(location.HasGpsFix, "{0}"),
                nullableAsStr <int>(location.SatellitesUsed, "{0}"),
                nullableAsStr <int>(location.SatellitesInView, "{0}")
            };

            _lineCount++;
            string logMsg = string.Join(Delimiter, lineTokens);

            Debug.Log(logMsg);
            _textWriter.WriteLine(logMsg);
            _textWriter.Flush();
        }
        //void UnityARSessionNativeInterface_ARSessionTrackingChanged(UnityEngine.XR.iOS.UnityARCamera camera)
        //{
        //	Unity.Utilities.Console.Instance.Log(string.Format("AR Tracking State Changed: {0}: {1}", camera.trackingState, camera.trackingReason), "silver");
        //}

        void LocationProvider_OnLocationUpdated(Location location)
        {
            if (location.IsLocationUpdated || location.IsUserHeadingUpdated)
            {
                // With this line, we can control accuracy of Gps updates.
                // Be aware that we only get location information if it previously met
                // the conditions of DeviceLocationProvider:
                // * desired accuarracy in meters
                // * and update distance in meters
                if (location.Accuracy > _minimumDesiredAccuracy)
                {
                    Unity.Utilities.Console.Instance.Log(
                        string.Format(
                            "Gps update ignored due to bad accuracy: {0:0.0} > {1:0.0}"
                            , location.Accuracy
                            , _minimumDesiredAccuracy
                            )
                        , "red"
                        );
                }
                else
                {
                    //_kalman.Process(
                    //	location.LatitudeLongitude.x
                    //	, location.LatitudeLongitude.y
                    //	, location.Accuracy
                    //	, (long)location.Timestamp
                    //);
                    //location.LatitudeLongitude.x = _kalman.Lat;
                    //location.LatitudeLongitude.y = _kalman.Lng;
                    //location.Accuracy = (int)_kalman.Accuracy;

                    var latitudeLongitude = location.LatitudeLongitude;
                    Unity.Utilities.Console.Instance.Log(
                        string.Format(
                            "Location[{0:yyyyMMdd-HHmmss}]: {1},{2}\tAccuracy: {3}\tHeading: {4}"
                            , UnixTimestampUtils.From(location.Timestamp)
                            , latitudeLongitude.x
                            , latitudeLongitude.y
                            , location.Accuracy
                            , location.UserHeading
                            )
                        , "lightblue"
                        );

                    var position = _map.GeoToWorldPosition(latitudeLongitude, false);
                    position.y = _map.Root.position.y;
                    _synchronizationContext.AddSynchronizationNodes(location, position, _arPositionReference.localPosition);
                }
            }
        }
        /// <summary>
        /// Returns the tile data, otherwise null
        /// </summary>
        /// <param name="tileId">Canonical tile id to identify the tile</param>
        /// <returns>tile data as byte[], if tile is not cached returns null</returns>
        public CacheItem Get(string tilesetName, CanonicalTileId tileId)
        {
#if MAPBOX_DEBUG_CACHE
            string methodName = _className + "." + new System.Diagnostics.StackFrame().GetMethod().Name;
            Debug.LogFormat("{0} {1} {2}", methodName, _tileset, tileId);
#endif
            tiles tile = null;

            try
            {
                int?tilesetId = getTilesetId(tilesetName);
                if (!tilesetId.HasValue)
                {
                    return(null);
                }

                tile = _sqlite
                       .Table <tiles>()
                       .Where(t =>
                              t.tile_set == tilesetId.Value &&
                              t.zoom_level == tileId.Z &&
                              t.tile_column == tileId.X &&
                              t.tile_row == tileId.Y
                              )
                       .FirstOrDefault();
            }
            catch (Exception ex)
            {
                Debug.LogErrorFormat("error getting tile {1} {2} from cache{0}{3}", Environment.NewLine, tilesetName, tileId, ex);
                return(null);
            }
            if (null == tile)
            {
                return(null);
            }

            DateTime?lastModified = null;
            if (tile.lastmodified.HasValue)
            {
                lastModified = UnixTimestampUtils.From((double)tile.lastmodified.Value);
            }

            return(new CacheItem()
            {
                Data = tile.tile_data,
                AddedToCacheTicksUtc = tile.timestamp,
                ETag = tile.etag,
                LastModified = lastModified
            });
        }
Exemple #4
0
        public static Response FromWebResponse(IAsyncRequest request, UnityWebRequest apiResponse, Exception apiEx)
        {
            Response response = new Response();

            response.Request = request;

            if (null != apiEx)
            {
                response.AddException(apiEx);
            }

            if (apiResponse.isNetworkError)
            {
                response.AddException(new Exception(apiResponse.error));
            }

            if (null == apiResponse.downloadHandler.data)
            {
                response.AddException(new Exception("Response has no data."));
            }

#if NETFX_CORE
            StringComparison stringComp = StringComparison.OrdinalIgnoreCase;
#elif WINDOWS_UWP
            StringComparison stringComp = StringComparison.OrdinalIgnoreCase;
#else
            StringComparison stringComp = StringComparison.InvariantCultureIgnoreCase;
#endif

            Dictionary <string, string> apiHeaders = apiResponse.GetResponseHeaders();
            if (null != apiHeaders)
            {
                response.Headers = new Dictionary <string, string>();
                foreach (var apiHdr in apiHeaders)
                {
                    string key = apiHdr.Key;
                    string val = apiHdr.Value;
                    response.Headers.Add(key, val);
                    if (key.Equals("X-Rate-Limit-Interval", stringComp))
                    {
                        int limitInterval;
                        if (int.TryParse(val, out limitInterval))
                        {
                            response.XRateLimitInterval = limitInterval;
                        }
                    }
                    else if (key.Equals("X-Rate-Limit-Limit", stringComp))
                    {
                        long limitLimit;
                        if (long.TryParse(val, out limitLimit))
                        {
                            response.XRateLimitLimit = limitLimit;
                        }
                    }
                    else if (key.Equals("X-Rate-Limit-Reset", stringComp))
                    {
                        double unixTimestamp;
                        if (double.TryParse(val, out unixTimestamp))
                        {
                            response.XRateLimitReset = UnixTimestampUtils.From(unixTimestamp);
                        }
                    }
                    else if (key.Equals("Content-Type", stringComp))
                    {
                        response.ContentType = val;
                    }
                }
            }

            int statusCode = (int)apiResponse.responseCode;
            response.StatusCode = statusCode;

            if (statusCode != 200)
            {
                response.AddException(new Exception(string.Format("Status Code {0}", apiResponse.responseCode)));
            }
            if (429 == statusCode)
            {
                response.AddException(new Exception("Rate limit hit"));
            }

            response.Data = apiResponse.downloadHandler.data;

            return(response);
        }
Exemple #5
0
        public static Response FromWebResponse(IAsyncRequest request, HttpWebResponse apiResponse, Exception apiEx)
        {
            Response response = new Response();

            response.Request = request;

            if (null != apiEx)
            {
                response.AddException(apiEx);
            }

            // timeout: API response is null
            if (null == apiResponse)
            {
                response.AddException(new Exception("No Reponse."));
            }
            else
            {
                // https://www.mapbox.com/api-documentation/#rate-limits
                if (null != apiResponse.Headers)
                {
                    response.Headers = new Dictionary <string, string>();
                    for (int i = 0; i < apiResponse.Headers.Count; i++)
                    {
                        // TODO: implement .Net Core / UWP implementation
                        string key = apiResponse.Headers.Keys[i];
                        string val = apiResponse.Headers[i];
                        response.Headers.Add(key, val);
                        if (key.Equals("X-Rate-Limit-Interval", StringComparison.InvariantCultureIgnoreCase))
                        {
                            int limitInterval;
                            if (int.TryParse(val, out limitInterval))
                            {
                                response.XRateLimitInterval = limitInterval;
                            }
                        }
                        else if (key.Equals("X-Rate-Limit-Limit", StringComparison.InvariantCultureIgnoreCase))
                        {
                            long limitLimit;
                            if (long.TryParse(val, out limitLimit))
                            {
                                response.XRateLimitLimit = limitLimit;
                            }
                        }
                        else if (key.Equals("X-Rate-Limit-Reset", StringComparison.InvariantCultureIgnoreCase))
                        {
                            double unixTimestamp;
                            if (double.TryParse(val, out unixTimestamp))
                            {
                                response.XRateLimitReset = UnixTimestampUtils.From(unixTimestamp);
                            }
                        }
                        else if (key.Equals("Content-Type", StringComparison.InvariantCultureIgnoreCase))
                        {
                            response.ContentType = val;
                        }
                    }
                }

                if (apiResponse.StatusCode != HttpStatusCode.OK)
                {
                    response.AddException(new Exception(string.Format("{0}: {1}", apiResponse.StatusCode, apiResponse.StatusDescription)));
                }
                int statusCode = (int)apiResponse.StatusCode;
                response.StatusCode = statusCode;
                if (429 == statusCode)
                {
                    response.AddException(new Exception("Rate limit hit"));
                }

                if (null != apiResponse)
                {
                    using (Stream responseStream = apiResponse.GetResponseStream()) {
                        byte[] buffer = new byte[0x1000];
                        int    bytesRead;
                        using (MemoryStream ms = new MemoryStream()) {
                            while (0 != (bytesRead = responseStream.Read(buffer, 0, buffer.Length)))
                            {
                                ms.Write(buffer, 0, bytesRead);
                            }
                            response.Data = ms.ToArray();
                        }
                    }
                    apiResponse.Close();
                }
            }

            return(response);
        }
Exemple #6
0
        private void LocationProvider_OnLocationUpdated(Location location)
        {
            /////////////// GUI logging //////////////////////
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(string.Format("IsLocationServiceEnabled: {0}", location.IsLocationServiceEnabled));
            sb.AppendLine(string.Format("IsLocationServiceInitializing: {0}", location.IsLocationServiceInitializing));
            sb.AppendLine(string.Format("IsLocationUpdated: {0}", location.IsLocationUpdated));
            sb.AppendLine(string.Format("IsHeadingUpdated: {0}", location.IsUserHeadingUpdated));
            string locationProviderClass = LocationProviderFactory.Instance.DefaultLocationProvider.GetType().Name;

            sb.AppendLine(string.Format("location provider: {0} ({1})", location.Provider, locationProviderClass));
            sb.AppendLine(string.Format("UTC time:{0}  - device:  {1}{0}  - location:{2}", Environment.NewLine, DateTime.UtcNow.ToString("yyyyMMdd HHmmss"), UnixTimestampUtils.From(location.Timestamp).ToString("yyyyMMdd HHmmss")));
            sb.AppendLine(string.Format(_invariantCulture, "position: {0:0.00000000} / {1:0.00000000}", location.LatitudeLongitude.x, location.LatitudeLongitude.y));
            sb.AppendLine(string.Format(_invariantCulture, "accuracy: {0:0.0}m", location.Accuracy));
            sb.AppendLine(string.Format(_invariantCulture, "user heading: {0:0.0}°", location.UserHeading));
            sb.AppendLine(string.Format(_invariantCulture, "device orientation: {0:0.0}°", location.DeviceOrientation));
            sb.AppendLine(nullableAsStr <float>(location.SpeedKmPerHour, "speed: {0:0.0}km/h"));
            sb.AppendLine(nullableAsStr <bool>(location.HasGpsFix, "HasGpsFix: {0}"));
            sb.AppendLine(nullableAsStr <int>(location.SatellitesUsed, "SatellitesUsed:{0} "));
            sb.AppendLine(nullableAsStr <int>(location.SatellitesInView, "SatellitesInView:{0}"));

            if (null != _logText)
            {
                _logText.text = sb.ToString();
            }

            /////////////// file logging //////////////////////

            // start logging to file
            if (_logToFile && null == _logWriter)
            {
                Debug.Log("--- about to start logging to file ---");
                _logWriter = new LocationLogWriter();
                _logToggle.GetComponentInChildren <Text>().text = "stop logging";
            }

            // stop logging to file
            if (!_logToFile && null != _logWriter)
            {
                Debug.Log("--- about to stop logging to file ---");
                _logToggle.GetComponentInChildren <Text>().text = "start logging";
                closeLogWriter();
            }

            // write line to log file
            if (_logToFile && null != _logWriter)
            {
                _logWriter.Write(location);
            }
        }
        void LocationProvider_OnLocationUpdated(Location location)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(string.Format("IsLocationServiceEnabled: {0}", location.IsLocationServiceEnabled));
            sb.AppendLine(string.Format("IsLocationServiceInitializing: {0}", location.IsLocationServiceInitializing));
            sb.AppendLine(string.Format("IsLocationUpdated: {0}", location.IsLocationUpdated));
            sb.AppendLine(string.Format("IsHeadingUpdated: {0}", location.IsUserHeadingUpdated));
            string locationProviderClass = LocationProviderFactory.Instance.DefaultLocationProvider.GetType().Name;

            sb.AppendLine(string.Format("location provider: {0} ({1})", location.Provider, locationProviderClass));
            sb.AppendLine(string.Format("UTC time:{0}  - device:  {1}{0}  - location:{2}", Environment.NewLine, DateTime.UtcNow.ToString("yyyyMMdd HHmmss"), UnixTimestampUtils.From(location.Timestamp).ToString("yyyyMMdd HHmmss")));
            sb.AppendLine(string.Format(_invariantCulture, "position: {0:0.00000000} / {1:0.00000000}", location.LatitudeLongitude.x, location.LatitudeLongitude.y));
            sb.AppendLine(string.Format(_invariantCulture, "accuracy: {0:0.0}m", location.Accuracy));
            sb.AppendLine(string.Format(_invariantCulture, "user heading: {0:0.0}°", location.UserHeading));
            sb.AppendLine(string.Format(_invariantCulture, "device orientation: {0:0.0}°", location.DeviceOrientation));
            sb.AppendLine(nullableAsStr <float>(location.SpeedKmPerHour, "speed: {0:0.0}km/h"));
            sb.AppendLine(nullableAsStr <bool>(location.HasGpsFix, "HasGpsFix: {0}"));
            sb.AppendLine(nullableAsStr <int>(location.SatellitesUsed, "SatellitesUsed:{0} ") + nullableAsStr <int>(location.SatellitesInView, "SatellitesInView:{0}"));

            _logText.text = sb.ToString();
        }