示例#1
0
        public void WriterThread(object stateInfo)
        {
            while (dataToSend.Count > 0 && !disposed)
            {
                byte[] data = null;
                lock (dataToSend)
                {
                    data = dataToSend[0];
                    dataToSend.RemoveAt(0);
                }

                while (!view.ReadBoolean(WritePosition + READ_CONFIRM_OFFSET))
                {
                    Thread.Sleep(500);
                }

                // Sets length and write data.
                view.Write(writePosition + DATA_LENGTH_OFFSET, data.Length);
                view.WriteArray <byte>(writePosition + DATA_OFFSET, data, 0, data.Length);

                // Resets the flag used to signal that data has been read.
                view.Write(writePosition + READ_CONFIRM_OFFSET, false);
                // Sets the flag used to signal that there are data avaibla.
                view.Write(writePosition + DATA_AVAILABLE_OFFSET, true);
            }

            writerThreadRunning = false;
        }
示例#2
0
 public ItemData <bool> ReadBit(DeviceAddress address)
 {
     try
     {
         return(new ItemData <bool>(accessor.ReadBoolean(FindPosition(address)), 0, QUALITIES.QUALITY_GOOD));
     }
     catch { return(new ItemData <bool>(false, 0, QUALITIES.QUALITY_BAD)); }
 }
        public void Write(float x, float y)
        {
            byte[] byteArray = new byte[sizeof(int) + 2 * sizeof(float) + 1];
            Buffer.BlockCopy(BitConverter.GetBytes(++messageIndex), 0, byteArray, 0, sizeof(int));
            Buffer.BlockCopy(BitConverter.GetBytes(x), 0, byteArray, 4, sizeof(float));
            Buffer.BlockCopy(BitConverter.GetBytes(y), 0, byteArray, 8, sizeof(float));
            Buffer.BlockCopy(BitConverter.GetBytes(false), 0, byteArray, 12, sizeof(bool));

            Mutex.WaitOne();
            writer.Write(byteArray);
            writer.Flush();
            Mutex.ReleaseMutex();

            writer.Seek(0, SeekOrigin.Begin);

            while (true)
            {
                Thread.Sleep(1);
                Mutex.WaitOne();
                byte[] array = new byte[byteArray.Length];
                accessor.ReadArray <byte>(0, array, 0, array.Length);
                var isProcessed = accessor.ReadBoolean(byteArray.Length - 1);
                if (isProcessed)
                {
                    Mutex.ReleaseMutex();
                    return;
                }

                Mutex.ReleaseMutex();
            }
        }
        private void ReaderThread(object stateInfo)
        {
            while (started)
            {
                // Checks if there is something to read.
                var dataAvailable = view.ReadBoolean(ReadPosition + DATA_AVAILABLE_OFFSET);
                if (dataAvailable)
                {
                    // Checks how many bytes to read.
                    int availableBytes = view.ReadInt32(ReadPosition + DATA_LENGTH_OFFSET);
                    var bytes          = new byte[availableBytes];
                    // Reads the byte array.
                    int read = view.ReadArray <byte>(ReadPosition + DATA_OFFSET, bytes, 0, availableBytes);

                    // Sets the flag used to signal that there aren't available data anymore.
                    view.Write(ReadPosition + DATA_AVAILABLE_OFFSET, false);
                    // Sets the flag used to signal that data has been read.
                    view.Write(ReadPosition + READ_CONFIRM_OFFSET, true);

                    DataReceivedEventArgs args = new DataReceivedEventArgs(bytes, read);
                    operation.Post(callback, args);
                }

                Thread.Sleep(500);
            }
        }
示例#5
0
        public void Write(Layer[] layers, Gis3DObject[] gis3DObjects)
        {
            var byteArray = GetByteArray(MapToProxy(layers), MapToProxy(gis3DObjects));

            Mutex.WaitOne();
            writer.Write(byteArray);
            writer.Flush();
            Mutex.ReleaseMutex();

            while (true)
            {
                Thread.Sleep(1);
                Mutex.WaitOne();
                byte[] array = new byte[byteArray.Length];
                accessor.ReadArray <byte>(0, array, 0, array.Length);
                var isProcessed = accessor.ReadBoolean(byteArray.Length - 1);
                if (isProcessed)
                {
                    Mutex.ReleaseMutex();
                    return;
                }

                Mutex.ReleaseMutex();
            }
        }
示例#6
0
        /// <summary>
        /// 从内存获取文本
        /// </summary>
        /// <param name="Name">名字 确认内存的位置</param>
        /// <returns>获取的文本</returns>
        public static string GETStringFromMemory(string Name)
        {
            //创建异步阻塞
            MemoryMappedFile         lockmmf  = MemoryMappedFile.CreateOrOpen("lpsdb" + Name + "lock", 1, MemoryMappedFileAccess.ReadWrite);
            MemoryMappedViewAccessor lockmmva = lockmmf.CreateViewAccessor();

            while (lockmmva.ReadBoolean(0))
            {
                Thread.Sleep(10);
            }
            lockmmva.Write(0, true);
            //正常操作
            MemoryMappedFile         mmf  = MemoryMappedFile.OpenExisting(Name);
            MemoryMappedViewAccessor mmva = mmf.CreateViewAccessor();
            int len = mmva.ReadInt32(0);

            char[] buff = new char[len];
            mmva.ReadArray <char>(4, buff, 0, len);
            mmva.Dispose();
            mmf.Dispose();
            lockmmva.Write(0, false);
            lockmmva.Dispose();
            lockmmf.Dispose();
            return(new string(buff));
        }
示例#7
0
        /// <summary>
        /// 判断内存是否被锁定
        /// </summary>
        /// <param name="Name">名字 确认内存的位置</param>
        /// <returns>退回锁定状态</returns>
        public static bool IsLock(string Name)
        {
            MemoryMappedFile         lockmmf  = MemoryMappedFile.CreateOrOpen("lpsdb" + Name + "lock", 1, MemoryMappedFileAccess.ReadWrite);
            MemoryMappedViewAccessor lockmmva = lockmmf.CreateViewAccessor();
            bool bl = lockmmva.ReadBoolean(0);

            lockmmva.Dispose();
            lockmmf.Dispose();
            return(bl);
        }
        async void ReadCore()
        {
            while (r_IsStarted)
            {
                var rAvailable = r_ViewAccessor.ReadBoolean(ReadPosition + DATA_AVAILABLE_OFFSET);
                if (rAvailable)
                {
                    var rLength    = r_ViewAccessor.ReadInt32(ReadPosition + DATA_LENGTH_OFFSET);
                    var rData      = new byte[rLength];
                    var rBytesRead = r_ViewAccessor.ReadArray <byte>(ReadPosition + DATA_OFFSET, rData, 0, rLength);

                    r_ViewAccessor.Write(ReadPosition + DATA_AVAILABLE_OFFSET, false);
                    r_ViewAccessor.Write(ReadPosition + READ_CONFIRM_OFFSET, true);

                    DataReceived.OnNext(rData);
                }

                await Task.Delay(500);
            }
        }
    private static void StartReading()
    {
        bool currVal = false;

        for (int i = 0; i < 100; i++)
        {
            currVal = currVal != true;
            Console.WriteLine(_view.ReadBoolean(0));
            Thread.Sleep(221);
        }
    }
示例#10
0
        public bool ReadBoolean()
        {
            long position = _position + _origin;

            if (position + 1 > _length)
            {
                throw new IOException(SR.BlobReadOutOfBound);
            }

            var value = _accessor.ReadBoolean(position);

            _position++;

            return(value);
        }
示例#11
0
        static Telemetry ReadAllValues(MemoryMappedViewAccessor accessor, int buffOffset, VarHeader[] varHeaders)
        {
            var result = new Telemetry();

            var maps = new Dictionary <VarType, Func <int, object> >()
            {
                { VarType.irInt, (offset) => accessor.ReadInt32(offset) },
                { VarType.irBitField, (offset) => accessor.ReadInt32(offset) },
                { VarType.irDouble, (offset) => accessor.ReadDouble(offset) },
                { VarType.irBool, (offset) => accessor.ReadBoolean(offset) },
                { VarType.irFloat, (offset) => accessor.ReadSingle(offset) }
            };

            var arryMaps = new Dictionary <VarType, Func <int, int, object> >()
            {
                { VarType.irInt, (size, offset) => GetArrayData <int>(accessor, size, offset) },
                { VarType.irBitField, (size, offset) => GetArrayData <int>(accessor, size, offset) },
                { VarType.irDouble, (size, offset) => GetArrayData <double>(accessor, size, offset) },
                { VarType.irFloat, (size, offset) => GetArrayData <float>(accessor, size, offset) },
                { VarType.irBool, (size, offset) => GetArrayData <bool>(accessor, size, offset) }
            };

            for (var i = 0; i < varHeaders.Length; i++)
            {
                var varHeader = varHeaders[i];
                var offset    = buffOffset + varHeader.offset;

                if (varHeader.type == VarType.irChar)
                {
                    throw new NotSupportedException();
                }

                object value;
                if (varHeader.count != 1)
                {
                    value = arryMaps[varHeader.type](varHeader.count, offset);
                }
                else
                {
                    value = maps[varHeader.type](offset);
                }

                result.Add(varHeader.name, value);
            }

            return(result);
        }
示例#12
0
 public override byte[] Get(byte[] key)
 {
     lock (index) {
         long OO = index [key];
         //TODO: FIX THE UPPERBOUND
         MemoryMappedViewAccessor accessor = mmfBlock.CreateViewAccessor(reservedBytes + OO, capacity - (reservedBytes + OO), MemoryMappedFileAccess.Read);
         if (accessor.ReadBoolean(0))
         {
             throw new InvalidDataException();
         }
         const int ObjectHeaderSize = 40;
         byte[]    outArr           = new byte[accessor.ReadInt32(4)];
         accessor.ReadArray <byte> (ObjectHeaderSize, outArr, 0, outArr.Length);
         accessor.Dispose();
         return(outArr);
     }
 }
示例#13
0
        public object GetData(string name)
        {
            if (!IsStarted || Header == null)
            {
                return(null);
            }
            if (!VarHeaders.TryGetValue(name, out var requestedHeader))
            {
                return(null);
            }

            int varOffset = requestedHeader.Offset;
            int count     = requestedHeader.Count;

            switch (requestedHeader.Type)
            {
            case VarType.irChar:
            {
                byte[] data = new byte[count];
                FileMapView.ReadArray(Header.Offset + varOffset, data, 0, count);
                return(_encoding.GetString(data).TrimEnd(trimChars));
            }

            case VarType.irBool:
            {
                if (count > 1)
                {
                    bool[] data = new bool[count];
                    FileMapView.ReadArray(Header.Offset + varOffset, data, 0, count);
                    return(data);
                }
                else
                {
                    return(FileMapView.ReadBoolean(Header.Offset + varOffset));
                }
            }

            case VarType.irInt:
            case VarType.irBitField:
            {
                if (count > 1)
                {
                    int[] data = new int[count];
                    FileMapView.ReadArray(Header.Offset + varOffset, data, 0, count);
                    return(data);
                }
                else
                {
                    return(FileMapView.ReadInt32(Header.Offset + varOffset));
                }
            }

            case VarType.irFloat:
            {
                if (count > 1)
                {
                    float[] data = new float[count];
                    FileMapView.ReadArray(Header.Offset + varOffset, data, 0, count);
                    return(data);
                }
                else
                {
                    return(FileMapView.ReadSingle(Header.Offset + varOffset));
                }
            }

            case VarType.irDouble:
            {
                if (count > 1)
                {
                    double[] data = new double[count];
                    FileMapView.ReadArray(Header.Offset + varOffset, data, 0, count);
                    return(data);
                }
                else
                {
                    return(FileMapView.ReadDouble(Header.Offset + varOffset));
                }
            }

            default: return(null);
            }
        }
        /// <summary>Performs many reads and writes of various data types against the accessor.</summary>
        private static void AssertWritesReads(MemoryMappedViewAccessor acc)
        {
            // Successful reads and writes at the beginning for each data type
            AssertWriteRead <bool>(false, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
            AssertWriteRead <bool>(true, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
            AssertWriteRead <byte>(42, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos));
            AssertWriteRead <char>('c', 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos));
            AssertWriteRead <decimal>(9, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos));
            AssertWriteRead <double>(10, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos));
            AssertWriteRead <short>(11, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos));
            AssertWriteRead <int>(12, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos));
            AssertWriteRead <long>(13, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos));
            AssertWriteRead <sbyte>(14, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos));
            AssertWriteRead <float>(15, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos));
            AssertWriteRead <ushort>(16, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos));
            AssertWriteRead <uint>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos));
            AssertWriteRead <ulong>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos));

            // Successful reads and writes at the end for each data type
            long end = acc.Capacity;

            AssertWriteRead <bool>(false, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
            AssertWriteRead <bool>(true, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
            AssertWriteRead <byte>(42, end - sizeof(byte), (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos));
            AssertWriteRead <char>('c', end - sizeof(char), (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos));
            AssertWriteRead <decimal>(9, end - sizeof(decimal), (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos));
            AssertWriteRead <double>(10, end - sizeof(double), (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos));
            AssertWriteRead <short>(11, end - sizeof(short), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos));
            AssertWriteRead <int>(12, end - sizeof(int), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos));
            AssertWriteRead <long>(13, end - sizeof(long), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos));
            AssertWriteRead <sbyte>(14, end - sizeof(sbyte), (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos));
            AssertWriteRead <float>(15, end - sizeof(float), (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos));
            AssertWriteRead <ushort>(16, end - sizeof(ushort), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos));
            AssertWriteRead <uint>(17, end - sizeof(uint), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos));
            AssertWriteRead <ulong>(17, end - sizeof(ulong), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos));

            // Failed reads and writes just at the border of the end. This triggers different exception types
            // for some types than when we're completely beyond the end.
            long beyondEnd = acc.Capacity + 1;

            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte)));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadChar(beyondEnd - sizeof(char)));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal)));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double)));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short)));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int)));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long)));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float)));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort)));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint)));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong)));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c'));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0));
            AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0));

            // Failed reads and writes well past the end
            beyondEnd = acc.Capacity + 20;
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadChar(beyondEnd - sizeof(char)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint)));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong)));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c'));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0));
        }
        public object GetData(string name)
        {
            if (!IsInitialized || Header == null)
            {
                return(null);
            }

            if (!VarHeaders.ContainsKey(name))
            {
                return(null);
            }

            var varOffset = VarHeaders[name].Offset;
            var count     = VarHeaders[name].Count;

            switch (VarHeaders[name].Type)
            {
            case CVarHeader.VarType.IrChar:
                var bytes = new byte[count];
                _fileMapView.ReadArray(Header.Buffer + varOffset, bytes, 0, count);
                return(Encoding.Default.GetString(bytes).TrimEnd('\0'));

            case CVarHeader.VarType.IrBool:
                if (count > 1)
                {
                    var data = new bool[count];
                    _fileMapView.ReadArray(Header.Buffer + varOffset, data, 0, count);
                    return(data);
                }

                return(_fileMapView.ReadBoolean(Header.Buffer + varOffset));

            case CVarHeader.VarType.IrInt:
            case CVarHeader.VarType.IrBitField:
                if (count > 1)
                {
                    var data = new int[count];
                    _fileMapView.ReadArray(Header.Buffer + varOffset, data, 0, count);
                    return(data);
                }

                return(_fileMapView.ReadInt32(Header.Buffer + varOffset));

            case CVarHeader.VarType.IrFloat:
                if (count > 1)
                {
                    var data = new float[count];
                    _fileMapView.ReadArray(Header.Buffer + varOffset, data, 0, count);
                    return(data);
                }

                return(_fileMapView.ReadSingle(Header.Buffer + varOffset));

            case CVarHeader.VarType.IrDouble:
                if (count > 1)
                {
                    var data = new double[count];
                    _fileMapView.ReadArray(Header.Buffer + varOffset, data, 0, count);
                    return(data);
                }

                return(_fileMapView.ReadDouble(Header.Buffer + varOffset));

            default:
                return(null);
            }
        }
示例#16
0
 public object GetData(string name)
 {
     if (IsInitialized && Header != null)
     {
         CVarHeader header = null;
         if (VarHeaders.TryGetValue(name, out header))
         {
             int varOffset = header.Offset;
             int count     = header.Count;
             if (header.Type == CVarHeader.VarType.irChar)
             {
                 byte[] data = new byte[count];
                 FileMapView.ReadArray <byte>(Header.Buffer + varOffset, data, 0, count);
                 return(System.Text.Encoding.Default.GetString(data).TrimEnd(new char[] { '\0' }));
             }
             else if (header.Type == CVarHeader.VarType.irBool)
             {
                 if (count > 1)
                 {
                     bool[] data = new bool[count];
                     FileMapView.ReadArray <bool>(Header.Buffer + varOffset, data, 0, count);
                     return(data);
                 }
                 else
                 {
                     return(FileMapView.ReadBoolean(Header.Buffer + varOffset));
                 }
             }
             else if (header.Type == CVarHeader.VarType.irInt || header.Type == CVarHeader.VarType.irBitField)
             {
                 if (count > 1)
                 {
                     int[] data = new int[count];
                     FileMapView.ReadArray <int>(Header.Buffer + varOffset, data, 0, count);
                     return(data);
                 }
                 else
                 {
                     return(FileMapView.ReadInt32(Header.Buffer + varOffset));
                 }
             }
             else if (header.Type == CVarHeader.VarType.irFloat)
             {
                 if (count > 1)
                 {
                     float[] data = new float[count];
                     FileMapView.ReadArray <float>(Header.Buffer + varOffset, data, 0, count);
                     return(data);
                 }
                 else
                 {
                     return(FileMapView.ReadSingle(Header.Buffer + varOffset));
                 }
             }
             else if (header.Type == CVarHeader.VarType.irDouble)
             {
                 if (count > 1)
                 {
                     double[] data = new double[count];
                     FileMapView.ReadArray <double>(Header.Buffer + varOffset, data, 0, count);
                     return(data);
                 }
                 else
                 {
                     return(FileMapView.ReadDouble(Header.Buffer + varOffset));
                 }
             }
         }
     }
     return(null);
 }
示例#17
0
 public bool GetValueBool(long offset)
 {
     return(_viewAccessor.ReadBoolean(offset));
 }
示例#18
0
 public object GetData(string name)
 {
     if (IsInitialized && Header != null)
     {
         if (VarHeaders.ContainsKey(name))
         {
             int varOffset = VarHeaders[name].Offset;
             int count     = VarHeaders[name].Count;
             if (VarHeaders[name].Type == CVarHeader.VarType.irChar)
             {
                 byte[] data = new byte[count];
                 FileMapView.ReadArray(Header.Buffer + varOffset, data, 0, count);
                 return(encoding.GetString(data).TrimEnd(new char[] { '\0' }));
             }
             else if (VarHeaders[name].Type == CVarHeader.VarType.irBool)
             {
                 if (count > 1)
                 {
                     bool[] data = new bool[count];
                     FileMapView.ReadArray(Header.Buffer + varOffset, data, 0, count);
                     return(data);
                 }
                 else
                 {
                     return(FileMapView.ReadBoolean(Header.Buffer + varOffset));
                 }
             }
             else if (VarHeaders[name].Type == CVarHeader.VarType.irInt || VarHeaders[name].Type == CVarHeader.VarType.irBitField)
             {
                 if (count > 1)
                 {
                     int[] data = new int[count];
                     FileMapView.ReadArray(Header.Buffer + varOffset, data, 0, count);
                     return(data);
                 }
                 else
                 {
                     return(FileMapView.ReadInt32(Header.Buffer + varOffset));
                 }
             }
             else if (VarHeaders[name].Type == CVarHeader.VarType.irFloat)
             {
                 if (count > 1)
                 {
                     float[] data = new float[count];
                     FileMapView.ReadArray(Header.Buffer + varOffset, data, 0, count);
                     return(data);
                 }
                 else
                 {
                     return(FileMapView.ReadSingle(Header.Buffer + varOffset));
                 }
             }
             else if (VarHeaders[name].Type == CVarHeader.VarType.irDouble)
             {
                 if (count > 1)
                 {
                     double[] data = new double[count];
                     FileMapView.ReadArray(Header.Buffer + varOffset, data, 0, count);
                     return(data);
                 }
                 else
                 {
                     return(FileMapView.ReadDouble(Header.Buffer + varOffset));
                 }
             }
         }
     }
     return(null);
 }
示例#19
0
        public static IEnumerable <HistoryData> LoadFromFile(DateTime start, DateTime end, short ID, bool sdt = false)
        {
            string path = string.Concat(m_Path, "\\", start.Year.ToString(), "-", start.Month.ToString(), sdt ? ".sdt" : ".bin");//bin-sdt

            if (!File.Exists(path))
            {
                yield break;
            }
            int day1       = start.Day;
            int startTicks = new SqlDateTime(start).TimeTicks; //开始日期部分的4位数据
            int endTicks   = new SqlDateTime(end).TimeTicks;
            int ln         = end.Day - day1 + 1;               //日期天数

            using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                long         filelen   = stream.Length;        //文件长度
                BinaryReader reader    = new BinaryReader(stream);
                long[]       positions = new long[ln];         //每日数据指针(指向第一条数据,包括当日数据索引区)
                stream.Seek((day1 - 1) * 8, SeekOrigin.Begin); ///找到对应的开始日期索引位置

                for (int i = 0; i < ln; i++)
                {
                    positions[i] = reader.ReadInt64();//读入时间段内每日数据长度值
                }
                long[] sizes = new long[ln];
                for (int i = 0; i < ln; i++)
                {
                    if (positions[i] >= filelen)
                    {
                        break;                                       //如果读入长度超过文件大小则退出
                    }
                    stream.Seek(positions[i] + 8, SeekOrigin.Begin); //定位文件指针到当日数据开头
                    sizes[i] = reader.ReadInt32();                   //sizes为当日该标签数
                }
                //reader.Close();
                HistoryData data = HistoryData.Empty;
                //stream.Read(new byte[]
                using (MemoryMappedFile mapp = MemoryMappedFile.CreateFromFile(stream, Guid.NewGuid().ToString(), filelen, MemoryMappedFileAccess.Read,
                                                                               HandleInheritability.Inheritable, false))
                {
                    for (int k = 0; k < ln; k++)//先读入当日索引区
                    {
                        if (positions[k] < 0x100 || sizes[k] <= 0 || positions[k] + sizes[k] > filelen)
                        {
                            continue;
                        }
                        //if (sizes[k] == 0) continue;
                        long     pos   = 0;
                        int      count = 0;
                        int      day   = 0;
                        int      len   = 0;
                        DataType type  = DataType.NONE;
                        using (MemoryMappedViewAccessor acc1 = mapp.CreateViewAccessor(positions[k], 12 + sizes[k] * 11, MemoryMappedFileAccess.Read)) //12是头的长度,11是一个格式字段的长度
                        {
                            day = acc1.ReadInt32(0);                                                                                                   //当日日期部分
                            int index = BinarySearch(acc1, (int)sizes[k], ID);                                                                         //找到当天 指定标签的记录索引
                            if (index >= 0)
                            {
                                index = index * 11 + 12;//如找到,则定位到当日数据的元数据(相对位移)
                            }
                            //sw.Stop();
                            else
                            {
                                continue;
                            }
                            byte tp = acc1.ReadByte(index + 2);                                                                        //读入数据类型
                            type  = (DataType)tp;
                            len   = dataLen[tp];                                                                                       //4,6,8分别为存储的标签长度,其中4字节是时间戳
                            count = acc1.ReadInt32(index + 3);                                                                         //读入数量
                            pos   = positions[k] + 12 + sizes[k] * 11 + acc1.ReadInt32(index + 7);                                     //指针指向当日当前标签第一条记录
                        }
                        using (MemoryMappedViewAccessor acc2 = mapp.CreateViewAccessor(pos, count * len, MemoryMappedFileAccess.Read)) //重新从头定位文件指针到数据区
                        {
                            pos = 0;
                            int j = 0;
                            if (k == 0)                                                      //判断是否为起始日期或结束日期
                            {
                                int ind = BinarySearchTime(acc2, 0, count, len, startTicks); //根据时间排序方式二分法查找当日当前时间节点的数据,如为第一日
                                if (ind < 0)
                                {
                                    ind = ~ind;
                                }
                                j   += ind;
                                pos += ind * len;
                            }
                            if (k == ln - 1)
                            {
                                int ind = BinarySearchTime(acc2, 0, count, len, endTicks);//如果为最后一日的数据,则按结束时间定位
                                count = ind >= 0 ? ind : ~ind;
                            }
                            while (j++ < count)
                            {
                                data.ID        = ID;
                                data.TimeStamp = new SqlDateTime(day, acc2.ReadInt32(pos)).Value; //日期在前(4位)
                                pos           += 4;                                               //数据区也是4位
                                switch (type)
                                {
                                case DataType.BOOL:
                                    data.Value.Boolean = acc2.ReadBoolean(pos);
                                    pos++;
                                    break;

                                case DataType.BYTE:
                                    data.Value.Byte = acc2.ReadByte(pos);
                                    pos++;
                                    break;

                                case DataType.WORD:
                                case DataType.SHORT:
                                    data.Value.Int16 = acc2.ReadInt16(pos);
                                    pos += 2;
                                    break;

                                case DataType.INT:
                                    data.Value.Int32 = acc2.ReadInt32(pos);
                                    pos += 4;
                                    break;

                                case DataType.FLOAT:
                                    data.Value.Single = acc2.ReadSingle(pos);
                                    pos += 4;
                                    break;
                                }
                                yield return(data);
                            }
                        }
                    }
                }
                reader.Close();
            }
            yield break;
        }
示例#20
0
        public static IEnumerable <HistoryData> LoadFromFile(DateTime start, DateTime end, bool sdt = false)
        {
            //Stopwatch sw = Stopwatch.StartNew();
            //文件的组织格式:头文件:31,ln为间隔日期,position为指向日期段的指针,sizes为日期段的长度。
            //每日的抬头:按ID次序,包含每个TAG的数量,arr为每个日期所有的标签、每标签数量、数据类型、位置指针。
            //按时间排序,每个标签的值、时间戳。
            string path = string.Concat(m_Path, "\\", start.Year.ToString(), "-", start.Month.ToString(), sdt ? ".sdt" : ".bin");

            if (!File.Exists(path))
            {
                yield break;
            }
            int day1       = start.Day;
            int startTicks = new SqlDateTime(start).TimeTicks;
            int endTicks   = new SqlDateTime(end).TimeTicks;
            int ln         = end.Day - day1 + 1;

            using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                BinaryReader reader    = new BinaryReader(stream);
                long[]       positions = new long[ln + 1];
                long[]       sizes     = new long[ln];
                stream.Seek((day1 - 1) * 8, SeekOrigin.Begin);
                positions[0] = reader.ReadInt64();
                for (int i = 0; i < ln; i++)
                {
                    positions[i + 1] = reader.ReadInt64();
                    sizes[i]         = positions[i + 1] - positions[i];//每一天数据的长度
                }
                //reader.Close();
                HistoryData data = HistoryData.Empty;
                using (MemoryMappedFile mapp = MemoryMappedFile.CreateFromFile(stream, Guid.NewGuid().ToString(), 0, MemoryMappedFileAccess.Read,
                                                                               HandleInheritability.Inheritable, false))
                {
                    for (int k = 0; k < ln; k++)
                    {
                        if (positions[k] < 0x100 || sizes[k] <= 0 || positions[k] + sizes[k] > stream.Length)
                        {
                            continue;
                        }
                        using (MemoryMappedViewAccessor acc = mapp.CreateViewAccessor(positions[k], sizes[k], MemoryMappedFileAccess.Read))
                        {
                            long pos = 0;
                            int  day = acc.ReadInt32(pos);
                            pos += 8;
                            int count = acc.ReadInt32(pos);
                            pos += 4;
                            HDataFormat[] arr = new HDataFormat[count];
                            for (int i = 0; i < count; i++)
                            {
                                arr[i].ID   = acc.ReadInt16(pos);
                                pos        += 2;
                                arr[i].Type = (DataType)acc.ReadByte(pos);
                                pos++;
                                arr[i].Count = acc.ReadInt32(pos);//4个字节是预留
                                pos         += 8;
                            }
                            long tempos = pos;
                            for (int i = 0; i < count; i++)
                            {
                                int con = arr[i].Count;
                                int j   = 0;
                                pos = tempos + acc.ReadInt32(i * 11 + 19);
                                long     pf   = pos;
                                DataType type = arr[i].Type;
                                int      len  = dataLen[(int)type];
                                if (k == 0)        //判断是否为起始日期或结束日期
                                {
                                    int ind = BinarySearchTime(acc, pf, con, len, startTicks);
                                    if (ind < 0)
                                    {
                                        ind = ~ind;
                                    }
                                    j   += ind;
                                    pos += ind * len;
                                }
                                if (k == ln - 1)
                                {
                                    int index = BinarySearchTime(acc, pf, con, len, endTicks);
                                    con = index >= 0 ? index : ~index;
                                }
                                while (j++ < con)
                                {
                                    data.ID        = arr[i].ID;
                                    data.TimeStamp = new SqlDateTime(day, acc.ReadInt32(pos)).Value;
                                    pos           += 4;
                                    switch (type)
                                    {
                                    case DataType.BOOL:
                                        data.Value.Boolean = acc.ReadBoolean(pos);
                                        pos++;
                                        break;

                                    case DataType.BYTE:
                                        data.Value.Byte = acc.ReadByte(pos);
                                        pos++;
                                        break;

                                    case DataType.WORD:
                                    case DataType.SHORT:
                                        data.Value.Int16 = acc.ReadInt16(pos);
                                        pos += 2;
                                        break;

                                    case DataType.INT:
                                        data.Value.Int32 = acc.ReadInt32(pos);
                                        pos += 4;
                                        break;

                                    case DataType.FLOAT:
                                        data.Value.Single = acc.ReadSingle(pos);
                                        pos += 4;
                                        break;
                                    }
                                    yield return(data);
                                }
                            }
                        }
                    }
                }
            }
            yield break;
        }
            public override int Read(byte[] buffer, int offset, int count)
            {
                if (buffer == null)
                {
                    throw new ArgumentNullException("buffer", "Buffer cannot be null.");
                }
                if (offset < 0)
                {
                    throw new ArgumentOutOfRangeException("offset", "Non-negative number required.");
                }
                if (count < 0)
                {
                    throw new ArgumentOutOfRangeException("count", "Non-negative number required.");
                }
                if (buffer.Length - offset < count)
                {
                    throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.");
                }

                if (_messageCompleted && _bytesRemainingToBeRead == 0)
                {
                    return(0);
                }

                if (_shouldWait)
                {
                    var index = WaitHandle.WaitAny(new[] { _bytesWrittenEvent, _messageCancelledEvent, _cancellationToken.WaitHandle });

                    if (index == 1 || index == 2)
                    {
                        _receiver.LastMessageWasCancelled = true;

                        return(0);
                    }

                    _stream.Seek(0, SeekOrigin.Begin);
                    _bytesRemainingToBeRead = _bytesWrittenAccessor.ReadInt32(0);
                    _offset           = 0;
                    _shouldWait       = false;
                    _messageCompleted = _messageCompletedAccessor.ReadBoolean(0);
                }

                var numberOfBytesToRead = count >= _bytesRemainingToBeRead ? _bytesRemainingToBeRead : count;

                if (_offset == 0)
                {
                    _stream.Read(buffer, offset, numberOfBytesToRead);
                }
                else
                {
                    var readBuffer = new byte[_offset + numberOfBytesToRead];
                    _stream.Read(readBuffer, _offset, numberOfBytesToRead);
                    Buffer.BlockCopy(readBuffer, _offset, buffer, offset, numberOfBytesToRead);
                }

                _offset += numberOfBytesToRead;
                _bytesRemainingToBeRead -= numberOfBytesToRead;

                if (_bytesRemainingToBeRead == 0)
                {
                    _shouldWait = true;
                    _bytesReadEvent.Set();
                }

                return(numberOfBytesToRead);
            }