Exemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GribFile" /> class. File read rights are shared between processes.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <exception cref="System.IO.IOException">Could not open file. See inner exception for more detail.</exception>
        /// <exception cref="System.IO.FileLoadException">The file is empty.</exception>
        public GribFile(string fileName)
        {
            FileInfo fi = new FileInfo(fileName);

            // need a better check
            if (fi.Length < 4)
            {
                throw new FileLoadException("This file is empty or invalid.");
            }

            _pFileHandleProxy = GribApiNative.CreateFileHandleProxy(fileName);

            if (_pFileHandleProxy == IntPtr.Zero)
            {
                throw new IOException("Could not open file. See inner exception for more detail.", new Win32Exception(Marshal.GetLastWin32Error()));
            }

            _fileHandleProxy = (FileHandleProxy)Marshal.PtrToStructure(_pFileHandleProxy, typeof(FileHandleProxy));

            FileName  = fileName;
            Reference = new HandleRef(this, _fileHandleProxy.File);
            Context   = GribApiProxy.GribContextGetDefault();

            // set the message count here; the result seems to be connected to the message iterator so
            // that after you begin iterating messages, the count decreases until it reaches 1.
            int count = 0;

            GribApiProxy.GribCountInFile(Context, this, out count);
            MessageCount = count;
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bits"></param>
        /// <param name="index"></param>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public static GribMessage Create(byte[] bits, int index, GribContext ctx)
        {
            var buff = Marshal.AllocHGlobal(bits.Length);

            Marshal.Copy(bits, 0, buff, bits.Length);
            int   err = 0;
            SizeT sz  = (SizeT)bits.Length;

            GribMessage msg    = null;
            GribHandle  handle = null;

            lock (_fileLock)
            {
                // grib_api moves to the next message in a stream for each new handle
                handle = GribApiProxy.GribHandleNewFromMultiMessage(ctx, out buff, ref sz, out err);
            }

            if (err != 0)
            {
                Marshal.AllocHGlobal(buff);
                throw GribApiException.Create(err);
            }

            if (handle != null)
            {
                msg = new GribMessage(handle, ctx, buff, index);
            }

            return(msg);
        }
Exemplo n.º 3
0
 /// <summary>
 /// Called when [dispose].
 /// </summary>
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 protected override void OnDispose(bool disposing)
 {
     if (this.pReference != IntPtr.Zero)
     {
         this.Rewind();
         GribApiProxy.GribKeysIteratorDelete(this);
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Gets an enum describing a key's representation within the message.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        private GribValueType NativeTypeForKey(string key)
        {
            int type = 0;

            GribApiProxy.GribGetNativeType(_handle, key, out type);

            return((GribValueType)type);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Sets the key's value in bytes.
        /// </summary>
        /// <param name="newBytes">The new bytes.</param>
        public void AsBytes(byte[] newBytes)
        {
            AssertTypeSafe(GribValueType.Bytes);

            SizeT sz = (SizeT)newBytes.Length;

            GribApiProxy.GribSetBytes(_handle, Key, newBytes, ref sz);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Sets the key's value.
        /// </summary>
        /// <param name="newValue">The new value.</param>
        public virtual void AsString(string newValue)
        {
            AssertTypeSafe(GribValueType.String);

            SizeT len = (SizeT)newValue.Length;

            GribApiProxy.GribSetString(_handle, Key, newValue, ref len);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Sets the key's value.
        /// </summary>
        /// <param name="newValue">The new value.</param>
        public virtual void AsDouble(double newValue)
        {
            string valueKey = BuildTokenForDouble();

            AssertTypeSafe(valueKey, NativeTypeForKey(valueKey), GribValueType.Double);

            GribApiProxy.GribSetDouble(_handle, valueKey, newValue);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Retrieves the GRIB key's type name.
        /// </summary>
        /// <param name="vt">The vt.</param>
        /// <returns></returns>
        public static string AsString(this GribValueType vt)
        {
            if ((int)vt >= (int)GribValueType.IntArray)
            {
                return(vt.ToString());
            }

            return(GribApiProxy.GribGetTypeName((int)vt));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Gets the next value in a series.
        /// </summary>
        /// <param name="isMissingFlag">The is missing flag.</param>
        /// <param name="gsVal">The gs value.</param>
        /// <returns>False if there are no more values.</returns>
        public bool Next(double isMissingFlag, out GridCoordinateValue gsVal)
        {
            double lat, lon, val;
            bool   success = GribApiProxy.GribIteratorNext(this, out lat, out lon, out val) != 0;

            gsVal = new GridCoordinateValue(lat, lon, val, val == isMissingFlag);

            return(success);
        }
Exemplo n.º 10
0
 protected override void OnDispose(bool disposing)
 {
     if (this.pReference != IntPtr.Zero)
     {
         GribApiProxy.GribNearestDelete(Nearest);
         this.Nearest = null;
         this.Handle  = null;
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Gets the key's value.
        /// </summary>
        /// <returns></returns>
        public virtual int AsInt()
        {
            AssertTypeSafe(GribValueType.Int);

            int val;

            GribApiProxy.GribGetLong(_handle, Key, out val);

            return(val);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets the key's value.
        /// </summary>
        /// <returns></returns>
        public virtual double AsDouble()
        {
            string valueKey = BuildTokenForDouble();

            AssertTypeSafe(valueKey, NativeTypeForKey(valueKey), GribValueType.Double);

            double val;

            GribApiProxy.GribGetDouble(_handle, valueKey, out val);

            return(val);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Creates an instance of GribValuesIterator.
        /// </summary>
        /// <param name="h">The handle of the message to iterate.</param>
        /// <param name="filters">The filters.</param>
        /// <returns></returns>
        public static GribCoordinateValuesIterator Create(GribHandle h, uint filters)
        {
            int err = 0;

            GribCoordinateValuesIterator iter = GribApiProxy.GribIteratorNew(h, filters, out err);

            if (err != 0)
            {
                throw GribApiException.Create(err);
            }

            return(iter);
        }
Exemplo n.º 14
0
        ///// <summary>
        ///// Find the nearest point of a set of points whose latitudes and longitudes.
        ///// </summary>
        ///// <param name="coordinates">The reference coordinates.</param>
        ///// <param name="useLandSeaMask">If true, the nearest land point is returned and the grib passed as the handle is considered a land sea mask.
        ///// land nearest point is the nearest point with land sea mask value>=0.5. If no nearest land points are found the nearest value is returned.
        ///// If the flag false, the nearest points, along with values, distances, and indexes are returned.
        ///// </param>
        ///// <returns></returns>
        //public GribNearestCoordinate[] FindNearestCoordinates(IGeoCoordinate[] coordinates, bool useLandSeaMask = false)
        //{
        //	var len = coordinates.Length;
        //	var latitudes = new double[len];
        //	var longitudes = new double[len];
        //	var outLatitudes = new double[len];
        //	var outLongitudes = new double[len];
        //	var distances = new double[len];
        //	var values = new double[len];
        //	var indexes = new int[len];

        //	for (var i = 0; i < len; i++)
        //	{
        //		latitudes[i] = coordinates[i].Latitude;
        //		longitudes[i] = coordinates[i].Longitude;
        //	}

        //	Interop.SizeT sz = (SizeT)len;
        //	Interop.SWIG.GribApiProxy.GribNearestFindMultiple(this.Handle, useLandSeaMask ? 1 : 0, latitudes, longitudes, len,
        //											          outLatitudes, outLongitudes, values, distances, indexes);

        //	var vals = new GribNearestCoordinate[len];

        //	for (var i = 0; i < len; i++)
        //	{
        //		vals[i] = new GribNearestCoordinate(latitudes[i], longitudes[i], values[i], distances[i], indexes[i]);
        //	}

        //	Array.Sort(vals, (v1, v2) => v1.Distance.CompareTo(v2.Distance));

        //	return vals;
        //}

        public static GribNearest Create(GribHandle handle)
        {
            int err = 0;

            var nearest = GribApiProxy.GribNearestNew(handle, out err);

            if (err != 0)
            {
                throw GribApiException.Create(err);
            }

            return(new GribNearest(nearest, handle));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Sets the key's value.
        /// </summary>
        /// <param name="newValues">The new values.</param>
        /// <param name="force">if set to <c>true</c> [force].</param>
        public virtual void AsDoubleArray(double[] newValues, bool force = false)
        {
            if (force)
            {
                GribApiProxy.GribSetForceDoubleArray(_handle, Key, newValues, (SizeT)newValues.Length);
            }
            else
            {
                AssertTypeSafe(GribValueType.DoubleArray);

                GribApiProxy.GribSetDoubleArray(_handle, Key, newValues, (SizeT)newValues.Length);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Gets the key's value in bytes.
        /// </summary>
        /// <returns></returns>
        public byte[] AsBytes()
        {
            AssertTypeSafe(GribValueType.Bytes);

            SizeT sz = 0;

            GribApiProxy.GribGetSize(_handle, Key, ref sz);
            byte[] bytes = new byte[sz];

            GribApiProxy.GribGetBytes(_handle, Key, bytes, ref sz);

            return(bytes);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Gets a copy of the key's array value. Changing the values of this array does not affect the owning message.
        /// Call ::AsXArray(alteredArray) to set new values.
        /// </summary>
        /// <returns>Returns a *copy* of the key's array.</returns>
        public virtual int[] AsIntArray()
        {
            AssertTypeSafe(GribValueType.IntArray);

            SizeT sz = 0;

            GribApiProxy.GribGetSize(_handle, Key, ref sz);

            int[] values = new int[sz];
            GribApiProxy.GribGetLongArray(_handle, Key, values, ref sz);

            return(values);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Gets a copy of the key's array value. Changing the values of this array does not affect the owning message.
        /// Call ::AsXArray(alteredArray) to set new values.
        /// </summary>
        /// <returns>Returns a *copy* of the key's array.</returns>
        public virtual double[] AsDoubleArray()
        {
            AssertTypeSafe(GribValueType.DoubleArray);

            SizeT sz = 0;

            GribApiProxy.GribGetSize(_handle, Key, ref sz);

            double[] values = new double[sz];
            GribApiProxy.GribGetDoubleArray(_handle, Key, values, ref sz);

            return(values);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Gets the key's value.
        /// </summary>
        /// <param name="inDegrees">if set to <c>true</c>, GribApi.NET will return the value [in degrees] when possible.</param>
        /// <returns></returns>
        public virtual double AsDouble(bool inDegrees = true)
        {
            string valueKey = BuildTokenForDouble(inDegrees);

            AssertTypeSafe(valueKey, NativeTypeForKey(valueKey), GribValueType.Double);

            if (!IsDefined)
            {
                return(Double.NaN);
            }

            double val;

            GribApiProxy.GribGetDouble(_handle, valueKey, out val);

            return(val);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Creates a GribMessage instance from a <seealso cref="Grib.Api.GribFile"/>.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="index">The index.</param>
        /// <returns></returns>
        public static GribMessage Create(GribFile file, int index)
        {
            GribMessage msg = null;
            int         err = 0;
            // grib_api moves to the next message in a stream for each new handle
            GribHandle handle = GribApiProxy.GribHandleNewFromFile(file.Context, file, out err);

            if (err != 0)
            {
                throw GribApiException.Create(err);
            }

            if (handle != null)
            {
                msg = new GribMessage(handle, file.Context, index);
            }

            return(msg);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GribBox"/> class.
        /// </summary>
        /// <param name="msgHandle">The MSG handle.</param>
        /// <param name="nw">The nw.</param>
        /// <param name="se">The se.</param>
        public GribBox(GribHandle msgHandle, GeoCoordinate nw, GeoCoordinate se)
        {
            int err;
            var box = GribApiProxy.GribBoxNew(msgHandle, out err);

            if (err != 0)
            {
                throw GribApiException.Create(err);
            }

            var pts = GribApiProxy.GribBoxGetPoints(box, nw.Latitude, nw.Longitude, se.Latitude, se.Longitude, out err);

            if (err != 0)
            {
                throw GribApiException.Create(err);
            }

            _points = new GribPoints(SWIGTYPE_p_grib_points.getCPtr(pts).Handle, false);
        }
Exemplo n.º 22
0
        public bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                disposedValue = true;

                if (this._nearest != null)
                {
                    this._nearest.Dispose();
                }

                if (this.BufferHandle.IsAllocated)
                {
                    SWIGTYPE_p_grib_multi_handle mh = new SWIGTYPE_p_grib_multi_handle(this.Handle.Reference.Handle, false);
                    GribApiProxy.GribMultiHandleDelete(mh);
                    this.BufferHandle.Free();
                }
            }
        }
Exemplo n.º 23
0
        public bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                disposedValue = true;

                if (this._nearest != null)
                {
                    this._nearest.Dispose();
                }

                if (this.OwnsMemory)
                {
                    SWIGTYPE_p_grib_multi_handle mh = new SWIGTYPE_p_grib_multi_handle(this.Handle.Reference.Handle, false);
                    GribApiProxy.GribMultiHandleDelete(mh);
                    // Marshal.FreeHGlobal(this.NativeBuffer);
                    this.NativeBuffer = IntPtr.Zero;
                }
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Gets the key's value.
        /// </summary>
        /// <returns></returns>
        public virtual string AsString()
        {
            if (!IsDefined || _asStringBlacklist.Contains(NativeType))
            {
                return(String.Empty);
            }

            SizeT  ptLen    = 0;
            string valueKey = Key;

            if (CanConvertToDegrees)
            {
                valueKey = BuildTokenForDouble();
            }

            // not sure it's worth checking the length here--could just use MAX_VAL_LEN
            GribApiProxy.GribGetLength(_handle, valueKey, ref ptLen);
            StringBuilder msg = new StringBuilder((int)ptLen);

            GribApiProxy.GribGetString(_handle, valueKey, msg, ref ptLen);

            return(msg.ToString().Trim());
        }
Exemplo n.º 25
0
        /// <summary>
        /// Creates a GribMessage instance from a buffer.
        /// </summary>
        /// <param name="bits"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static GribMessage Create(byte[] bits, int index = 0)
        {
            GCHandle h       = GCHandle.Alloc(bits, GCHandleType.Pinned);
            IntPtr   pHandle = h.AddrOfPinnedObject();

            int        err    = 0;
            SizeT      sz     = (SizeT)bits.Length;
            GribHandle handle = GribApiProxy.GribHandleNewFromMultiMessage(GribContext.Default, out pHandle, ref sz, out err);

            if (err != 0)
            {
                h.Free();
                throw GribApiException.Create(err);
            }

            GribMessage msg = null;

            if (handle != null)
            {
                msg = new GribMessage(handle, GribContext.Default, h, index);
            }

            return(msg);
        }
Exemplo n.º 26
0
 /// <summary>
 /// Creates an instance of GribKeysIterator.
 /// </summary>
 /// <param name="handle">The handle of the message to iterate.</param>
 /// <param name="filters">The key filters.</param>
 /// <param name="nspace">The namespace of the keys to iterate.</param>
 /// <returns></returns>
 public static GribKeysIterator Create(GribHandle handle, uint filters, string nspace)
 {
     return(GribApiProxy.GribKeysIteratorNew(handle, filters, nspace));
 }
Exemplo n.º 27
0
 /// <summary>
 /// Rewinds this instance.
 /// </summary>
 public void Rewind()
 {
     GribApiProxy.GribKeysIteratorRewind(this);
 }
Exemplo n.º 28
0
 /// <summary>
 /// Return true if the key name exists (is defined) in the grib message.
 /// </summary>
 /// <param name="handle"></param>
 /// <param name="keyName"></param>
 /// <returns></returns>
 public static bool IsKeyDefined(GribHandle handle, string keyName)
 {
     return(GribApiProxy.GribIsDefined(handle, keyName));
 }
Exemplo n.º 29
0
        /// <summary>
        /// Sets the key's value.
        /// </summary>
        /// <param name="newValue">The new value.</param>
        public virtual void AsInt(int newValue)
        {
            AssertTypeSafe(GribValueType.Int);

            GribApiProxy.GribSetLong(_handle, Key, newValue);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Sets the key's value.
        /// </summary>
        /// <param name="newValues">The new values.</param>
        public virtual void AsIntArray(int[] newValues)
        {
            AssertTypeSafe(GribValueType.IntArray);

            GribApiProxy.GribSetLongArray(_handle, Key, newValues, (SizeT)newValues.Length);
        }