public short rdShort(string Module, int pOffset)
 {
     return(BitConverter.ToInt16(this.rdMem(this.DllImageAddress(Module) + pOffset, 2), 0));
 }
Пример #2
0
        protected virtual void OnReceivedInternal(byte[] data, int offset, int count)
        {
            if (data != null && count >= ReceiveBufferLength)
            {
                double[] result = new double[4];

                result[0] = BitConverter.ToInt16(data, offset + 2);
                result[1] = BitConverter.ToInt16(data, offset + 4);
                result[2] = BitConverter.ToInt16(data, offset + 6);
                result[3] = BitConverter.ToInt16(data, offset + 8);

                switch (data[1])
                {
                case 0x50:
                    //ChipTime
                    break;

                case 0x51:
                    //Gravity
                    this.GravityDataReceivedEvent(
                        new Vector3D(
                            result[0] / 32768.0 * 16.0,
                            result[1] / 32768.0 * 16.0,
                            result[2] / 32768.0 * 16.0
                            )
                        );
                    break;

                case 0x52:
                    //AngleSpeed
                    this.AngleSpeedDataReceivedEvent(
                        new Vector3D(
                            result[0] / 32768.0 * 2000.0,
                            result[1] / 32768.0 * 2000.0,
                            result[2] / 32768.0 * 2000.0
                            )
                        );
                    break;

                case 0x53:
                    //AngleValue
                    this.AngleValueDataReceivedEvent(
                        new Vector3D(
                            result[0] / 32768.0 * 180.0,
                            result[1] / 32768.0 * 180.0,
                            result[2] / 32768.0 * 180.0
                            )
                        );
                    break;

                case 0x54:
                    //Magnet
                    this.MagnetDataReceivedEvent(
                        new Vector3D(
                            result[0] / 32768.0 * 1200.0 * 2.0,
                            result[1] / 32768.0 * 1200.0 * 2.0,
                            result[2] / 32768.0 * 1200.0 * 2.0
                            )
                        );
                    break;

                case 0x55:
                    //PortVoltage
                    //PortVoltage[0] = Data[0];
                    //PortVoltage[1] = Data[1];
                    //PortVoltage[2] = Data[2];
                    //PortVoltage[3] = Data[3];
                    break;

                case 0x56:
                    //Pressure = BitConverter.ToInt32(byteTemp, 2);
                    //Altitude = (double)BitConverter.ToInt32(byteTemp, 6) / 100.0;
                    break;

                case 0x57:
                    //Longitude = BitConverter.ToInt32(byteTemp, 2);
                    //Latitude = BitConverter.ToInt32(byteTemp, 6);
                    break;

                case 0x58:
                    //GPSHeight = (double)BitConverter.ToInt16(byteTemp, 2) / 10.0;
                    //GPSYaw = (double)BitConverter.ToInt16(byteTemp, 4) / 10.0;
                    //GroundVelocity = BitConverter.ToInt16(byteTemp, 6) / 1e3;
                    break;

                default:
                    break;
                }
            }
        }
Пример #3
0
        /// <summary>
        ///     Swaps endian of structure members that correspond to numerical types.
        ///     Does not traverse nested structures.
        /// </summary>
        /// <returns>The structure with its members endian swapped.</returns>
        /// <param name="str">The structure.</param>
        public static object SwapStructureMembersEndian(object str)
        {
            Type t = str.GetType();

            FieldInfo[] fieldInfo = t.GetFields();
            foreach (FieldInfo fi in fieldInfo)
            {
                if (fi.FieldType == typeof(short))
                {
                    short  int16   = (short)fi.GetValue(str);
                    byte[] int16_b = BitConverter.GetBytes(int16);
                    byte[] int16_r = int16_b.Reverse().ToArray();
                    fi.SetValue(str, BitConverter.ToInt16(int16_r, 0));
                }
                else if (fi.FieldType == typeof(int))
                {
                    int    int32   = (int)fi.GetValue(str);
                    byte[] int32_b = BitConverter.GetBytes(int32);
                    byte[] int32_r = int32_b.Reverse().ToArray();
                    fi.SetValue(str, BitConverter.ToInt32(int32_r, 0));
                }
                else if (fi.FieldType == typeof(long))
                {
                    long   int64   = (long)fi.GetValue(str);
                    byte[] int64_b = BitConverter.GetBytes(int64);
                    byte[] int64_r = int64_b.Reverse().ToArray();
                    fi.SetValue(str, BitConverter.ToInt64(int64_r, 0));
                }
                else if (fi.FieldType == typeof(ushort))
                {
                    ushort uint16   = (ushort)fi.GetValue(str);
                    byte[] uint16_b = BitConverter.GetBytes(uint16);
                    byte[] uint16_r = uint16_b.Reverse().ToArray();
                    fi.SetValue(str, BitConverter.ToUInt16(uint16_r, 0));
                }
                else if (fi.FieldType == typeof(uint))
                {
                    uint   uint32   = (uint)fi.GetValue(str);
                    byte[] uint32_b = BitConverter.GetBytes(uint32);
                    byte[] uint32_r = uint32_b.Reverse().ToArray();
                    fi.SetValue(str, BitConverter.ToUInt32(uint32_r, 0));
                }
                else if (fi.FieldType == typeof(ulong))
                {
                    ulong  uint64   = (ulong)fi.GetValue(str);
                    byte[] uint64_b = BitConverter.GetBytes(uint64);
                    byte[] uint64_r = uint64_b.Reverse().ToArray();
                    fi.SetValue(str, BitConverter.ToUInt64(uint64_r, 0));
                }
                else if (fi.FieldType == typeof(float))
                {
                    float  flt   = (float)fi.GetValue(str);
                    byte[] flt_b = BitConverter.GetBytes(flt);
                    byte[] flt_r = flt_b.Reverse().ToArray();
                    fi.SetValue(str, BitConverter.ToSingle(flt_r, 0));
                }
                else if (fi.FieldType == typeof(double))
                {
                    double dbl   = (double)fi.GetValue(str);
                    byte[] dbl_b = BitConverter.GetBytes(dbl);
                    byte[] dbl_r = dbl_b.Reverse().ToArray();
                    fi.SetValue(str, BitConverter.ToDouble(dbl_r, 0));
                }
                else if (fi.FieldType == typeof(byte) || fi.FieldType == typeof(sbyte))
                {
                    // Do nothing, can't byteswap them!
                }
                else if (fi.FieldType == typeof(Guid))
                {
                    // TODO: Swap GUID
                }
                // TODO: Swap arrays and enums
                else if (fi.FieldType.IsValueType && !fi.FieldType.IsEnum && !fi.FieldType.IsArray)
                {
                    object obj  = fi.GetValue(str);
                    Type   ty   = obj.GetType();
                    object strc = SwapStructureMembersEndian(obj);
                    fi.SetValue(str, strc);
                }
            }

            return(str);
        }
Пример #4
0
        /// <summary>
        ///     This register contains the roll of the device.
        ///     The sensor data is represented as a signed 16-bit integer.
        ///     1degree = 16 int.
        /// </summary>
        /// <returns>Euler angles roll</returns>
        public int EulRoll(int remoteId = 0)
        {
            byte[] data = ReadRegister(0x68, 2, null, remoteId);

            return(BitConverter.ToInt16(data, 0));
        }
Пример #5
0
 /// <summary>
 ///   Read a Short from the Buffer
 /// </summary>
 /// <returns></returns>
 public short ReadShort()
 {
     return(BitConverter.ToInt16(ReadBigEndianBytes(2), 0));
 }
Пример #6
0
 int readShort(BinaryReader reader)
 {
     byte[] charData = reader.ReadBytes(2);
     Array.Reverse(charData);
     return(BitConverter.ToInt16(charData, 0));
 }
Пример #7
0
 public short ToInt16(uint offset = 0)
 {
     return(BitConverter.ToInt16(Bytes, (int)offset));
 }
Пример #8
0
 public short ReadInt16(int offset)
 {
     return(BitConverter.ToInt16(m_bytes, m_readoffset + offset));
 }
Пример #9
0
 public static void dtSwapEndian(ref short v)
 {
     byte[] bytes = BitConverter.GetBytes(v);
     System.Array.Reverse(bytes);
     v = BitConverter.ToInt16(bytes, 0);
 }
Пример #10
0
        public Save(string folder, bool skipVersionCheck = false)
        {
            this.SaveFolder = folder;

            if (!File.Exists(Path.Combine(this.SaveFolder, "option.sav")))
            {
                throw new ArgumentException("The selected folder is not a valid Breath of the Wild save folder. " +
                                            "Please select a folder containing valid save data, including option.sav " +
                                            "in the root of the folder.");
            }

            using (FileStream fs = new FileStream(Path.Combine(this.SaveFolder, "option.sav"), FileMode.Open))
                using (BinaryReader br = new BinaryReader(fs))
                {
                    byte[] check = br.ReadBytes(1);
                    this.SaveConsoleType = ByteArrayToString(check) == "00" ? SaveType.WiiU : SaveType.Switch;
                }

            foreach (string file in Directory.EnumerateFiles(this.SaveFolder, "game_data.sav", SearchOption.AllDirectories))
            {
                using (FileStream fs = new FileStream(file, FileMode.Open))
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        // Not a reliable way to determine game version
                        //this.GameVersion = versionList[filesizes.IndexOf((int)f.Length)];

                        if (this.SaveConsoleType == SaveType.WiiU)
                        {
                            while (ByteArrayToString(br.ReadBytes(1)) == "00")
                            {
                            }

                            br.BaseStream.Position -= 1;

                            byte[] backwardsHeader = br.ReadBytes(2);

                            try
                            {
                                this.SaveVersionList.Add(versionList[headers.IndexOf(BitConverter.ToInt16(backwardsHeader.Reverse().ToArray(), 0))]);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                                if (!skipVersionCheck)
                                {
                                    throw new UnsupportedSaveException(
                                              "The version of a numbered save folder you selected cannot be retrieved.");
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                if (BitConverter.ToInt16(br.ReadBytes(2), 0) == 0x2a46)
                                {
                                    this.SaveVersionList.Add(versionList[headers.IndexOf(0x29c0)]); //v1.3.0 switch?
                                    return;
                                }

                                br.BaseStream.Position = 0;

                                if (BitConverter.ToInt16(br.ReadBytes(2), 0) == 0x3ef9)
                                {
                                    this.SaveVersionList.Add(versionList[headers.IndexOf(0x3ef8)]); //v1.3.3 switch?
                                    return;
                                }

                                br.BaseStream.Position = 0;

                                this.SaveVersionList.Add(versionList[headers.IndexOf(BitConverter.ToInt16(br.ReadBytes(2), 0))]);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                                if (!skipVersionCheck)
                                {
                                    throw new UnsupportedSaveException("The version of a numbered save folder you selected cannot be retrieved.")
                                          {
                                              IsSwitch = true
                                          };
                                }
                            }
                        }
                    }
            }
        }
Пример #11
0
        public T Read <T>(IntPtr address) where T : struct
        {
            object ret    = default(T);
            var    buffer = new byte[0];

            if (typeof(T) == typeof(string))
            {
                return((T)(object)ReadCString(address));
            }
            buffer = ReadBytes(address, (uint)Marshal.SizeOf(typeof(T)));

            switch (Type.GetTypeCode(typeof(T)))
            {
            case TypeCode.Object:
                GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                Marshal.PtrToStructure(handle.AddrOfPinnedObject(), ret);
                handle.Free();
                break;

            case TypeCode.Boolean:
                ret = BitConverter.ToBoolean(buffer, 0);
                break;

            case TypeCode.Char:
                ret = BitConverter.ToChar(buffer, 0);
                break;

            case TypeCode.Byte:
                ret = buffer[0];
                break;

            case TypeCode.Int16:
                ret = BitConverter.ToInt16(buffer, 0);
                break;

            case TypeCode.UInt16:
                ret = BitConverter.ToUInt16(buffer, 0);
                break;

            case TypeCode.Int32:
                ret = BitConverter.ToInt32(buffer, 0);
                break;

            case TypeCode.UInt32:
                ret = BitConverter.ToUInt32(buffer, 0);
                break;

            case TypeCode.Int64:
                ret = BitConverter.ToInt64(buffer, 0);
                break;

            case TypeCode.UInt64:
                ret = BitConverter.ToUInt64(buffer, 0);
                break;

            case TypeCode.Single:
                ret = BitConverter.ToSingle(buffer, 0);
                break;

            case TypeCode.Double:
                ret = BitConverter.ToDouble(buffer, 0);
                break;

            default:
                throw new NotSupportedException($"Unknown type {typeof(T).Name}.");
            }

            return((T)ret);
        }
 internal static short DeserializeInt16(Stream stream)
 {
     byte[] buffer = new byte[2];
     stream.Read(buffer, 0, 2);
     return(BitConverter.ToInt16(buffer, 0));
 }
Пример #13
0
        public Version30(byte[] rawBytes, string sourceFilename)
        {
            SourceFilename = sourceFilename;

            RawBytes = rawBytes;

            try
            {
                var headerBytes = new byte[84];
                Buffer.BlockCopy(rawBytes, 0, headerBytes, 0, 84);

                Header = new Header(headerBytes);

                var fi = new FileInfo(sourceFilename);
                SourceCreatedOn  = new DateTimeOffset(fi.CreationTimeUtc);
                SourceModifiedOn = new DateTimeOffset(fi.LastWriteTimeUtc);
                SourceAccessedOn = new DateTimeOffset(fi.LastAccessTimeUtc);

                //TODO factor out creation of File info blocks
                var fileInfoBytes = new byte[224];
                Buffer.BlockCopy(rawBytes, 84, fileInfoBytes, 0, 224);

                FileMetricsOffset = BitConverter.ToInt32(fileInfoBytes, 0);
                FileMetricsCount  = BitConverter.ToInt32(fileInfoBytes, 4);

                TraceChainsOffset = BitConverter.ToInt32(fileInfoBytes, 8);
                TraceChainsCount  = BitConverter.ToInt32(fileInfoBytes, 12);

                FilenameStringsOffset = BitConverter.ToInt32(fileInfoBytes, 16);
                FilenameStringsSize   = BitConverter.ToInt32(fileInfoBytes, 20);

                VolumesInfoOffset = BitConverter.ToInt32(fileInfoBytes, 24);
                VolumeCount       = BitConverter.ToInt32(fileInfoBytes, 28);

                VolumesInfoSize = BitConverter.ToInt32(fileInfoBytes, 32);

                //at offset 36 there are 8 unknown values, seemingly empty
                TotalDirectoryCount = BitConverter.ToInt32(fileInfoBytes, 36);

                var runtimeBytes = new byte[64];
                Buffer.BlockCopy(fileInfoBytes, 44, runtimeBytes, 0, 64);
                //var runtimeBytes = fileInfoBytes.Skip(44).Take(64).ToArray();

                LastRunTimes = new List <DateTimeOffset>();

                for (var i = 0; i < 8; i++)
                {
                    var rawTime = BitConverter.ToInt64(runtimeBytes, i * 8);

                    if (rawTime > 0)
                    {
                        LastRunTimes.Add(DateTimeOffset.FromFileTime(rawTime).ToUniversalTime());
                    }
                }

                //at offset 108 there are 16 bytes of unknown, possibly previous data from runtimes

                RunCount = BitConverter.ToInt32(fileInfoBytes, 124);

                var unknown0 = BitConverter.ToInt32(fileInfoBytes, 128);
                var unknown1 = BitConverter.ToInt32(fileInfoBytes, 132);
                //at offset 136 there is 88 bytes of unknown, empty values
                var unknown2 = BitConverter.ToInt32(fileInfoBytes, 128);

                var fileMetricsBytes = new byte[FileMetricsCount * 32];
                Buffer.BlockCopy(rawBytes, FileMetricsOffset, fileMetricsBytes, 0, FileMetricsCount * 32);
                var tempIndex = 0;

                FileMetrics = new List <FileMetric>();

                var fileMetricsTempBuffer = new byte[32];
                while (tempIndex < fileMetricsBytes.Length)
                {
                    Buffer.BlockCopy(fileMetricsBytes, tempIndex, fileMetricsTempBuffer, 0, 32);
                    FileMetrics.Add(new FileMetric(fileMetricsBytes, false));
                    tempIndex += 32;
                }

                TraceChains = new List <TraceChain>();

                var traceChainBytes = new byte[8 * TraceChainsCount];
                Buffer.BlockCopy(rawBytes, TraceChainsOffset, traceChainBytes, 0, 8 * TraceChainsCount);
                var traceIndex           = 0;
                var traceChainTempBuffer = new byte[8];
                while (traceIndex < traceChainBytes.Length)
                {
                    Buffer.BlockCopy(traceChainBytes, traceIndex, traceChainTempBuffer, 0, 8);
                    TraceChains.Add(new TraceChain(traceChainTempBuffer, true));
                    traceIndex += 8;
                }


                var filenameStringsBytes = new byte[FilenameStringsSize];
                Buffer.BlockCopy(rawBytes, FilenameStringsOffset, filenameStringsBytes, 0, FilenameStringsSize);

                var filenamesRaw = Encoding.Unicode.GetString(filenameStringsBytes);
                var fileNames    = filenamesRaw.Split(new[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);

                Filenames = new List <string>();

                Filenames.AddRange(fileNames);

                var volumeInfoBytes = new byte[VolumesInfoSize];
                Buffer.BlockCopy(rawBytes, VolumesInfoOffset, volumeInfoBytes, 0, VolumesInfoSize);

                VolumeInformation = new List <VolumeInfo>();

                //TODO factor this out as they are all the same?
                //TODO better yet, add in all the unique stuff so it can be researched

                var volBytes = new byte[96];
                for (var j = 0; j < VolumeCount; j++)
                {
                    var skipSize = j * 96;
                    Buffer.BlockCopy(volumeInfoBytes, skipSize, volBytes, 0, 96);

                    var volDevOffset  = BitConverter.ToInt32(volBytes, 0);
                    var volDevNumChar = BitConverter.ToInt32(volBytes, 4);

                    var ct = BitConverter.ToInt64(volBytes, 8);

                    var devNameBytes = new byte[volDevNumChar * 2];
                    Buffer.BlockCopy(rawBytes, VolumesInfoOffset + volDevOffset, devNameBytes, 0, volDevNumChar * 2);
                    var devName = Encoding.Unicode.GetString(devNameBytes);

                    var sn = BitConverter.ToInt32(volBytes, 16).ToString("X");

                    VolumeInformation.Add(new VolumeInfo(volDevOffset, DateTimeOffset.FromFileTime(ct).ToUniversalTime(), sn, devName));

                    var fileRefOffset = BitConverter.ToInt32(volBytes, 20);
                    var fileRefSize   = BitConverter.ToInt32(volBytes, 24);

                    var dirStringsOffset    = BitConverter.ToInt32(volBytes, 28);
                    var numDirectoryStrings = BitConverter.ToInt32(volBytes, 32);

                    //filerefs are at VolumesInfoOffset + fileRefOffset
                    var fileRefsIndex = VolumesInfoOffset + fileRefOffset;
                    var fileRefBytes  = new byte[fileRefSize];
                    Buffer.BlockCopy(rawBytes, fileRefsIndex, fileRefBytes, 0, fileRefSize);

                    var fileRefVer  = BitConverter.ToInt32(fileRefBytes, 0);
                    var numFileRefs = BitConverter.ToInt32(fileRefBytes, 4);

                    tempIndex = 8;

                    var tempFileRefBytes = new byte[8];
                    while (tempIndex < fileRefBytes.Length && VolumeInformation.Last().FileReferences.Count < numFileRefs)
                    {
                        Buffer.BlockCopy(fileRefBytes, tempIndex, tempFileRefBytes, 0, 8);
                        VolumeInformation.Last()
                        .FileReferences.Add(new MFTInformation(tempFileRefBytes));
                        tempIndex += 8;
                    }

                    var dirStringsIndex = VolumesInfoOffset + dirStringsOffset;
                    var dirStringsBytes = new byte[rawBytes.Length - dirStringsIndex];
                    Buffer.BlockCopy(rawBytes, dirStringsIndex, dirStringsBytes, 0, rawBytes.Length - dirStringsIndex);

                    tempIndex = 0;
                    for (var k = 0; k < numDirectoryStrings; k++)
                    {
                        var dirCharCount = BitConverter.ToInt16(dirStringsBytes, tempIndex) * 2 + 2;
                        // double the count since its Unicode and add 2 extra for null char
                        tempIndex += 2;
                        var dirName = Encoding.Unicode.GetString(dirStringsBytes, tempIndex, dirCharCount).Trim('\0');
                        VolumeInformation.Last().DirectoryNames.Add(dirName);

                        tempIndex += dirCharCount;
                    }
                }
            }
            catch (Exception)
            {
                ParsingError = true;
            }
        }
Пример #14
0
        public static object GetValue(ElementType etype, byte[] data)
        {
            switch (etype)
            {
            case ElementType.Boolean:
                if (data == null || data.Length < 1)
                {
                    return(false);
                }
                return(BitConverter.ToBoolean(data, 0));

            case ElementType.Char:
                if (data == null || data.Length < 2)
                {
                    return((char)0);
                }
                return(BitConverter.ToChar(data, 0));

            case ElementType.I1:
                if (data == null || data.Length < 1)
                {
                    return((sbyte)0);
                }
                return((sbyte)data[0]);

            case ElementType.U1:
                if (data == null || data.Length < 1)
                {
                    return((byte)0);
                }
                return(data[0]);

            case ElementType.I2:
                if (data == null || data.Length < 2)
                {
                    return((short)0);
                }
                return(BitConverter.ToInt16(data, 0));

            case ElementType.U2:
                if (data == null || data.Length < 2)
                {
                    return((ushort)0);
                }
                return(BitConverter.ToUInt16(data, 0));

            case ElementType.I4:
                if (data == null || data.Length < 4)
                {
                    return((int)0);
                }
                return(BitConverter.ToInt32(data, 0));

            case ElementType.U4:
                if (data == null || data.Length < 4)
                {
                    return((uint)0);
                }
                return(BitConverter.ToUInt32(data, 0));

            case ElementType.I8:
                if (data == null || data.Length < 8)
                {
                    return((long)0);
                }
                return(BitConverter.ToInt64(data, 0));

            case ElementType.U8:
                if (data == null || data.Length < 8)
                {
                    return((ulong)0);
                }
                return(BitConverter.ToUInt64(data, 0));

            case ElementType.R4:
                if (data == null || data.Length < 4)
                {
                    return((float)0);
                }
                return(BitConverter.ToSingle(data, 0));

            case ElementType.R8:
                if (data == null || data.Length < 8)
                {
                    return((double)0);
                }
                return(BitConverter.ToDouble(data, 0));

            case ElementType.String:
                if (data == null)
                {
                    return(string.Empty);
                }
                return(Encoding.Unicode.GetString(data, 0, data.Length / 2 * 2));

            case ElementType.Class:
                return(null);

            default:
                return(null);
            }
        }
Пример #15
0
        public static void ProcessVariableData(PropertyInfo[] propertyList, object obj, byte[] sourceData, int index, bool[] IncludedFields)
        {
            if (propertyList != null && obj != null && sourceData != null && IncludedFields != null)
            {
                //@@@@
                int position = index;
                for (int i = 0; i < IncludedFields.Length; i++)
                {
                    if (position > sourceData.Length)
                    {
                        break;
                    }
                    if (IncludedFields[i])
                    {
                        try
                        {
                            PropertyInfo prop = propertyList[i];
                            if (prop.PropertyType == typeof(bool?))
                            {
                                //incoming must be byte--no way to translate other type at this point.
                                bool?boolVal = Convert.ToBoolean(sourceData[position]);
                                if (_log.IsInfoEnabled && boolVal != null)
                                {
                                    _log.InfoFormat("Property {0} set to {1}", prop.Name, boolVal.Value.ToString());
                                }
                                propertyList[i].SetValue(obj, boolVal, null);
                                position += 1;
                            }
                            if (prop.PropertyType == typeof(int?))
                            {
                                if (position + 4 < sourceData.Length)
                                {
                                    int?intVal = BitConverter.ToInt32(sourceData, position);
                                    if (_log.IsInfoEnabled && intVal != null)
                                    {
                                        _log.InfoFormat("Property {0} set to {1}", prop.Name, intVal.Value.ToString());
                                    }
                                    propertyList[i].SetValue(obj, intVal, null);
                                }
                                position += 4;
                            }
                            if (prop.PropertyType == typeof(ArtemisString))
                            {
                                ArtemisString val = new ArtemisString(sourceData, position);

                                if (_log.IsInfoEnabled && val != null)
                                {
                                    _log.InfoFormat("Property {0} set to {1}", prop.Name, val.Value);
                                }


                                propertyList[i].SetValue(obj, val, null);
                                position += val.Length * 2 + 4;
                            }
                            if (prop.PropertyType == typeof(float?))
                            {
                                if (position + 4 < sourceData.Length)
                                {
                                    float?floatVal = BitConverter.ToSingle(sourceData, position);
                                    propertyList[i].SetValue(obj, floatVal, null);
                                    if (_log.IsInfoEnabled && floatVal != null)
                                    {
                                        _log.InfoFormat("Property {0} set to {1}", prop.Name, floatVal.Value.ToString());
                                    }
                                }
                                position += 4;
                            }
                            if (prop.PropertyType == typeof(byte?))
                            {
                                if (_log.IsInfoEnabled)
                                {
                                    _log.InfoFormat("Property {0} set to {1}", prop.Name, sourceData[position].ToString());
                                }
                                propertyList[i].SetValue(obj, sourceData[position], null);
                                position++;
                            }
                            if (prop.PropertyType == typeof(short?))
                            {
                                if (position + 2 < sourceData.Length)
                                {
                                    short?shortVal = BitConverter.ToInt16(sourceData, position);
                                    if (_log.IsInfoEnabled && shortVal != null)
                                    {
                                        _log.InfoFormat("Property {0} set to {1}", prop.Name, shortVal.Value.ToString());
                                    }
                                    propertyList[i].SetValue(obj, shortVal, null);
                                }
                                position += 2;
                            }
                            if (prop.PropertyType == typeof(long?))
                            {
                                if (position + 8 < sourceData.Length)
                                {
                                    long?longVal = BitConverter.ToInt64(sourceData, position);
                                    if (_log.IsInfoEnabled && longVal != null)
                                    {
                                        _log.InfoFormat("Property {0} set to {1}", prop.Name, longVal.Value.ToString());
                                    }

                                    propertyList[i].SetValue(obj, longVal, null);
                                }
                                position += 8;
                            }

                            if (prop.PropertyType == typeof(OrdinanceTypes?))
                            {
                                OrdinanceTypes?OrdVal = (OrdinanceTypes?)sourceData[position++];
                                if (_log.IsInfoEnabled && OrdVal != null)
                                {
                                    _log.InfoFormat("Property {0} set to {1}", prop.Name, OrdVal.Value.ToString());
                                }

                                propertyList[i].SetValue(obj, OrdVal, null);
                                position++;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (_log.IsWarnEnabled)
                            {
                                _log.Warn("Error getting bytes", ex);
                            }
                        }
                    }
                    else
                    {
                        if (_log.IsInfoEnabled)
                        {
                            _log.InfoFormat("Property {0} not included", propertyList[i].Name);
                        }
                    }
                }
            }
        }
Пример #16
0
        public int MakeData(DataRow workRow, byte s, int sz, byte[] info_bytes, string sn, DateTime deviceTime)
        {
            //eventlog parsing

            DateTime logtime;
            UInt16   status;

            workRow = dt.NewRow();
            switch (s)
            {
            case 0x10:    //Startup control byte
                          //info_bytes = rdr.ReadBytes(4);
                workRow[0] = sn;
                workRow[1] = "Power up";
                logtime    = deviceTime.AddSeconds(BitConverter.ToUInt32(info_bytes, 0));
                workRow[2] = logtime.ToString("yyyy/MM/dd HH:mm:ss");
                sz        -= 4;
                addNewRow(s, workRow, dt);
                break;

            case 0x11:    //Shutdown control byte
                          //info_bytes = rdr.ReadBytes(4);
                workRow[0] = sn;
                workRow[1] = "ShutDown";
                logtime    = deviceTime.AddSeconds(BitConverter.ToUInt32(info_bytes, 0));
                workRow[2] = logtime.ToString("yyyy/MM/dd HH:mm:ss");
                sz        -= 4;
                addNewRow(s, workRow, dt);
                break;

            case 0x20:     //Gas readings (full record)
                           //info_bytes = rdr.ReadBytes(22);
                workRow[0] = sn;
                workRow[1] = "Gas Reading";
                logtime    = deviceTime.AddSeconds(BitConverter.ToUInt32(info_bytes, 0));
                workRow[2] = logtime.ToString("yyyy/MM/dd HH:mm:ss");
                status     = BitConverter.ToUInt16(info_bytes, 4);
                workRow[3] = Optionparse(status, ReadingStatusList);
                if ((status & (1 << 10)) == (1 << 10))
                {
                    workRow[4] = "Yes";
                    isBump     = true;
                }
                else
                {
                    workRow[4] = "No";
                    isBump     = false;
                }
                if (H2SEnabled && isvalid(BitConverter.ToInt16(info_bytes, 6)))
                {
                    workRow[5] = (BitConverter.ToInt16(info_bytes, 6) / 10.0).ToString("0.0");
                    workRow[6] = (BitConverter.ToUInt16(info_bytes, 8) / 10.0).ToString("0.0");
                    workRow[7] = (BitConverter.ToUInt16(info_bytes, 10) / 10.0).ToString("0.0");
                }
                else
                {
                    H2SEnabled = false;
                }
                if (COEnabled && isvalid(BitConverter.ToInt16(info_bytes, 18)))
                {
                    workRow[8]  = (BitConverter.ToInt16(info_bytes, 12) / 10.0).ToString("0.0");
                    workRow[9]  = (BitConverter.ToUInt16(info_bytes, 14) / 10.0).ToString("0.0");
                    workRow[10] = (BitConverter.ToUInt16(info_bytes, 16) / 10.0).ToString("0.0");
                }
                else
                {
                    COEnabled = false;
                }
                if (O2Enabled && isvalid(BitConverter.ToInt16(info_bytes, 18)))
                {
                    workRow[11] = (BitConverter.ToInt16(info_bytes, 18) / 10.0).ToString("0.0");
                }
                else
                {
                    O2Enabled = false;
                }
                if (LELEnabled && isvalid(BitConverter.ToInt16(info_bytes, 20)))
                {
                    workRow[12] = (BitConverter.ToInt16(info_bytes, 20) / 10.0).ToString("0.0");
                }
                else
                {
                    LELEnabled = false;
                }

                sz -= 22;
                addNewRow(s, workRow, dt);
                break;

            case 0x21:    //All gas readings & STEL/TWA are zero (compressed record)
                          //info_bytes = rdr.ReadBytes(4);
                workRow[0] = sn;
                workRow[1] = "Gas Reading";
                logtime    = deviceTime.AddSeconds(BitConverter.ToUInt32(info_bytes, 0));
                workRow[2] = logtime.ToString("yyyy/MM/dd HH:mm:ss");
                if (isBump)
                {
                    workRow[4] = "Yes";
                }
                else
                {
                    workRow[4] = "No";
                }
                workRow[3]  = "";
                workRow[5]  = "0.0";
                workRow[6]  = "0.0";
                workRow[7]  = "0.0";
                workRow[8]  = "0.0";
                workRow[9]  = "0.0";
                workRow[10] = "0.0";
                workRow[11] = "20.9";
                workRow[12] = "0";

                sz -= 4;
                addNewRow(s, workRow, dt);
                break;

            case 0x30:     //Unit options
                workRow[0] = sn;
                //info_bytes = rdr.ReadBytes(6);
                UInt16 h = BitConverter.ToUInt16(info_bytes, 4);
                workRow[1]  = "Unit Option";
                workRow[2]  = dt.Rows[dt.Rows.Count - 1][2];
                workRow[18] = Optionparse(BitConverter.ToUInt32(info_bytes, 0), UnitOptionList);

                if (h == 0)
                {
                    workRow[19] = "English";
                }
                else if (h == 1)
                {
                    workRow[19] = "French";
                }
                else if (h == 2)
                {
                    workRow[19] = "German";
                }
                else if (h == 3)
                {
                    workRow[19] = "Spanish";
                }
                else if (h == 4)
                {
                    workRow[19] = "Portugese";
                }
                else
                {
                    workRow[19] = "invalid";
                }

                sz -= 6;
                addNewRow(s, workRow, dt);
                break;

            //H2S options//CO options//O2 options//LEL options

            case 0x40:
            case 0x41:
            case 0x42:
            case 0x43:
                //info_bytes = rdr.ReadBytes(28);
                workRow[0]  = sn;
                workRow[2]  = dt.Rows[dt.Rows.Count - 1][2];
                workRow[20] = Optionparse(BitConverter.ToUInt16(info_bytes, 0), GasconfigOptionList);
                workRow[21] = BitConverter.ToUInt32(info_bytes, 2) / 86400;
                workRow[22] = deviceTime.AddSeconds(BitConverter.ToUInt32(info_bytes, 6)).ToString("yyyy-MM-dd HH:mm:ss");
                workRow[23] = BitConverter.ToUInt32(info_bytes, 10) / 86400;
                workRow[24] = deviceTime.AddSeconds(BitConverter.ToUInt32(info_bytes, 14)).ToString("yyyy-MM-dd HH:mm:ss");
                workRow[25] = (BitConverter.ToUInt16(info_bytes, 18) / 10.0).ToString("0.0");
                workRow[26] = (BitConverter.ToUInt16(info_bytes, 20) / 10.0).ToString("0.0");
                if (s == 0x40 || s == 0x41)
                {
                    workRow[27] = (BitConverter.ToUInt16(info_bytes, 22) / 10.0).ToString("0.0");
                    workRow[28] = (BitConverter.ToUInt16(info_bytes, 24) / 10.0).ToString("0.0");
                    workRow[29] = BitConverter.ToUInt16(info_bytes, 26);
                }
                if (s == 0x40)
                {
                    workRow[1] = "H2S Options"; H2SEnabled = true;
                }
                else if (s == 0x41)
                {
                    workRow[1] = "CO Options"; COEnabled = true;
                }
                else if (s == 0x42)
                {
                    workRow[1] = "O2 Options"; O2Enabled = true;
                }
                else if (s == 0x43)
                {
                    workRow[1] = "LEL Options"; LELEnabled = true;
                }

                sz -= 28;
                addNewRow(s, workRow, dt);
                break;

            case 0x50:     //STATUS(i.e. self-test failure, cal failure, etc.)
                workRow[0] = sn;
                //info_bytes = rdr.ReadBytes(9);
                logtime     = deviceTime.AddSeconds(BitConverter.ToUInt32(info_bytes, 0));
                workRow[1]  = "Status";
                workRow[2]  = logtime.ToString("yyyy/MM/dd HH:mm:ss");
                workRow[13] = Optionparse(info_bytes[4], SensorStatusList);
                workRow[14] = Optionparse(info_bytes[5], SensorStatusList);
                workRow[15] = Optionparse(info_bytes[6], SensorStatusList);
                workRow[16] = Optionparse(info_bytes[7], SensorStatusList);
                workRow[17] = Optionparse(info_bytes[8], SensorStatusList);

                sz -= 9;
                addNewRow(s, workRow, dt);
                break;

            case 0x51:     //Temperature
                           //info_bytes = rdr.ReadBytes(7);
                workRow[0]  = sn;
                workRow[1]  = "Charging Alarm";
                logtime     = deviceTime.AddSeconds(BitConverter.ToUInt32(info_bytes, 0));
                workRow[2]  = logtime.ToString("yyyy/MM/dd HH:mm:ss");
                workRow[3]  = chargingAlarmParse(info_bytes[4]);
                workRow[30] = BitConverter.ToInt16(info_bytes, 5);

                sz -= 7;
                addNewRow(s, workRow, dt);
                break;
            }
            if ((s == 0x21))
            {
                inZero++;
            }
            else
            {
                inZero = 0;
            }

            return(sz);
        }
Пример #17
0
        private void MainForm_Load(object sender, EventArgs args)
        {
            var waveIn = new NAudio.Wave.WaveInEvent();

            waveIn.DeviceNumber   = 0;
            waveIn.WaveFormat     = new NAudio.Wave.WaveFormat(16000, 1);
            waveIn.DataAvailable +=
                (object waveSender, NAudio.Wave.WaveInEventArgs e) =>
            {
                //Dynamic waveform buffer offset, i want to f*****g die btw
                short[] waveValues = new short[(int)(e.BytesRecorded * .55)];
                for (int i = 0; i < e.BytesRecorded; i += 2)
                {
                    waveValues[(i / 2) + ((waveValues.Length - e.BytesRecorded / 2) / 2)] = (short)(BitConverter.ToInt16(e.Buffer, i) / 50);
                }
                try
                {
                    waveform.Invoke((MethodInvoker)(() => waveform.Series[0].Points.DataBindY(waveValues)));
                    UpdateVolumeMeter(Math.Abs(waveValues[waveValues.Length / 2]));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            };
            waveIn.StartRecording();



            new Thread((ThreadStart) delegate
            {
                while (true)
                {
                    StreamingMicRecognizeAsync(10).Wait();
                }
            }).Start();

            //Volume meter de-incrimenter
            #region
            progressReset.Interval = 50;
            progressReset.Elapsed += (o, arg) =>
            {
                if (progressBar.Value > 0)
                {
                    progressBar.Invoke((MethodInvoker)(() => progressBar.Value--));
                }
            };
            progressReset.Start();
            #endregion

            wave.ChartType = SeriesChartType.Area;
            wave.Color     = Color.Blue;
        }
 /// <summary>
 /// 从缓存中提取short结果
 /// </summary>
 /// <param name="buffer">缓存数据</param>
 /// <param name="index">索引位置</param>
 /// <returns>short对象</returns>
 public virtual short TransInt16(byte[] buffer, int index)
 {
     return(BitConverter.ToInt16(buffer, index));
 }
Пример #19
0
        /// <summary>
        /// 如果返回的是错误码、抛出异常 ;其他情况返回空。
        /// </summary>
        /// <param name="t"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public static byte[] Receive(Collector.ITaskContext t, Collector.Channel.BaseChannel channel)
        {
            sendByte = t.GetTX();

            buf.Clear();
            #region

            switch (sendByte[1])
            {
            case 0x03:
                recLength = (BitConverter.ToInt16(new byte[] { sendByte[sendByte.Length - 3], sendByte[sendByte.Length - 4] }, 0) * 2) + 5;
                break;

            case 0x06:
                recLength = sendByte.Length;
                break;

            case 0x10:
                recLength = 8;
                break;

            default:
                throw new Exception("发送指令中存在不支持的指令码:" + sendByte[1].ToString());
            }


            #endregion


            sw.Restart();
            while (sw.ElapsedMilliseconds < recLength + TimeOut)
            {
                buf.AddRange(channel.Read(recLength));

                if (buf.Count > 2) //判断返回的是否有错误
                {
                    if (buf[1] != sendByte[1])
                    {
                        buf.Clear();
                        return(buf.ToArray());
                    }
                }
                if (buf.Count >= recLength)//接收完指定长度后,判断crc是否通过
                {
                    sw.Stop();
                    if (!ModbusHelper.CheckDataCrc16(buf.ToArray()) || buf.Count != recLength)
                    {
                    }
                    break;
                }
            }
            sw.Stop();
            if (buf.Count > 0)
            {
                ErrorCount = 0;
            }
            else
            {
                ErrorCount++;
            }
            if (ErrorCount > 3)
            {
                throw new Exception("串口多次未读取到数据、请检查通讯是否有问题");
            }
            return(buf.ToArray());
        }
Пример #20
0
        void _masterClient_GotGameUpdate(object sender, GameInstance.GameUpdateEventArgs e)
        {
            GamePlayer player = (GamePlayer)sender;

            if (e.Message == GameMessage.EndGame)
            {
                Trace.WriteLine("Ending Game: " + player.Device.User);
                lock (_gameDb)
                {
                    Game.Completed = true;
                    _gameDb.SubmitChanges();
                }

                if (null != GameEnded)
                {
                    GameEnded(this, new EventArgs());
                }

                player.Close();
            }
            else if (e.Message == GameMessage.AcceptUser)
            {
                Int16  queryStringLength        = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(e.GameState, 0));
                string queryString              = System.Text.Encoding.ASCII.GetString(e.GameState, 2, queryStringLength);
                NameValueCollection queryBucket = System.Web.HttpUtility.ParseQueryString(queryString);

                string device = queryBucket["id"];

                foreach (GamePlayer slave in _slaveClients)
                {
                    if (string.Equals(slave.Device.Device, device, StringComparison.InvariantCultureIgnoreCase))
                    {
                        slave.Device.Accepted = true;
                        slave.SendUpdate(GameMessage.AcceptUserResponse, new byte[0]);

                        break;
                    }
                }

                SendGameInfo();
            }
            else if (e.Message == GameMessage.RejectUser)
            {
                Int16  queryStringLength        = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(e.GameState, 0));
                string queryString              = System.Text.Encoding.ASCII.GetString(e.GameState, 2, queryStringLength);
                NameValueCollection queryBucket = System.Web.HttpUtility.ParseQueryString(queryString);

                string device = queryBucket["id"];

                foreach (GamePlayer slave in _slaveClients)
                {
                    if (string.Equals(slave.Device.Device, device, StringComparison.InvariantCultureIgnoreCase))
                    {
                        slave.SendUpdate(GameMessage.RejectUserResponse, new byte[0]);
                        slave.Close();

                        _slaveClients.Remove(slave);

                        break;
                    }
                }

                SendGameInfo();
            }
            else if (e.Message == GameMessage.Start)
            {
                this.Game.Ready = true;
                SendGameInfo();

                Thread.Sleep(1500);
                player.SendUpdate(GameMessage.StartResponse, new byte[0]);
            }
            else if (e.Message == GameMessage.PushState)
            {
                //Int16 queryStringLength = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(e.GameState, 0));
                //string queryString = System.Text.Encoding.ASCII.GetString(e.GameState, 2, queryStringLength);
                //NameValueCollection queryBucket = System.Web.HttpUtility.ParseQueryString(queryString);

                //byte[] buffer = new byte[e.GameState.Length + 10];
                //Encoding.ASCII.GetBytes("mobilesrc").CopyTo(buffer, 0);
                //buffer[9] = 1;
                //e.GameState.CopyTo(buffer, 10);

                foreach (GamePlayer slave in _slaveClients)
                {
                    Console.WriteLine("_masterClient_GotGameUpdate: " + slave.Device.User);
                    //slave.SendUpdate(GameMessage.NOP, new byte[1500]);
                    try
                    {
                        slave.SendUpdate(GameMessage.PushStateResponse, e.GameState);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("ERROR _masterClient_GotGameUpdate");
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
            else
            {
            }
        }
Пример #21
0
 protected override void OnPaint(PaintEventArgs e)
 {
     if (this.waveStream != null)
     {
         e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
         e.Graphics.SmoothingMode      = SmoothingMode.HighQuality;
         e.Graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
         this.waveStream.Position      = 0L;
         byte[]     buffer        = new byte[this.samplesPerPixel * this.bytesPerSample];
         WaveStream waveStream    = this.waveStream;
         long       startPosition = this.startPosition;
         Rectangle  clipRectangle = e.ClipRectangle;
         long       num1          = (long)(clipRectangle.Left * this.bytesPerSample * this.samplesPerPixel);
         long       num2          = startPosition + num1;
         waveStream.Position = num2;
         clipRectangle       = e.ClipRectangle;
         float x = (float)clipRectangle.X;
         while (true)
         {
             double num3 = (double)x;
             clipRectangle = e.ClipRectangle;
             double right = (double)clipRectangle.Right;
             if (num3 < right)
             {
                 short num4 = 0;
                 short num5 = 0;
                 int   num6 = this.waveStream.Read(buffer, 0, this.samplesPerPixel * this.bytesPerSample);
                 if (num6 != 0)
                 {
                     for (int startIndex = 0; startIndex < num6; startIndex += 2)
                     {
                         short int16 = BitConverter.ToInt16(buffer, startIndex);
                         if ((int)int16 < (int)num4)
                         {
                             num4 = int16;
                         }
                         if ((int)int16 > (int)num5)
                         {
                             num5 = int16;
                         }
                     }
                     float num7  = (float)(((double)num4 - (double)short.MinValue) / (double)ushort.MaxValue);
                     float num8  = (float)(((double)num5 - (double)short.MinValue) / (double)ushort.MaxValue);
                     short num9  = 0;
                     short num10 = 0;
                     int   num11 = this.waveStream.Read(buffer, 0, this.samplesPerPixel * this.bytesPerSample);
                     this.waveStream.Position -= (long)(this.samplesPerPixel * this.bytesPerSample);
                     if (num11 != 0)
                     {
                         for (int startIndex = 0; startIndex < num11; startIndex += 2)
                         {
                             short int16 = BitConverter.ToInt16(buffer, startIndex);
                             if ((int)int16 < (int)num9)
                             {
                                 num9 = int16;
                             }
                             if ((int)int16 > (int)num10)
                             {
                                 num10 = int16;
                             }
                         }
                         float num12 = (float)(((double)num9 - (double)short.MinValue) / (double)ushort.MaxValue);
                         float num13 = (float)(((double)num10 - (double)short.MinValue) / (double)ushort.MaxValue);
                         e.Graphics.DrawLine(new Pen(this.FillColor), x, (float)this.Height * num7, x, (float)this.Height * num8);
                         e.Graphics.DrawLine(new Pen(this.LineColor, 1f), x, (float)this.Height * num7, x + 1f, (float)this.Height * num12);
                         e.Graphics.DrawLine(new Pen(this.LineColor, 1f), x, (float)this.Height * num8, x + 1f, (float)this.Height * num13);
                         ++x;
                     }
                     else
                     {
                         break;
                     }
                 }
                 else
                 {
                     break;
                 }
             }
             else
             {
                 break;
             }
         }
     }
     base.OnPaint(e);
 }
Пример #22
0
 /// <summary>
 ///     Reads and returns a double byte.
 /// </summary>
 /// <param name="position">The position.</param>
 /// <returns></returns>
 public short ReadShort(long position = -1)
 {
     Position = position;
     return(BitConverter.ToInt16(Br.ReadBytes(2), 0));
 }
Пример #23
0
        /// <summary>
        ///     This register contains the magnetic field strength along the x-axis of the Pozyx device.
        ///     The sensor data is stored as a signed 16-bit integer.
        ///     1µT = 16 int.
        /// </summary>
        /// <returns>Magnemtometer data</returns>
        public int MagnX(int remoteId = 0)
        {
            byte[] data = ReadRegister(0x5A, 2, null, remoteId);

            return(BitConverter.ToInt16(data, 0));
        }
Пример #24
0
        private dynamic ParseHour9Response(byte[] bytes)
        {
            dynamic hour = Parse70Response(bytes);

            if (!hour.success)
            {
                return(hour);
            }
            hour.records = new List <dynamic>();
            hour.channel = hour.body[0];
            var rowsCount = hour.body[2];

            hour.isEmpty = false;
            if (rowsCount == 0)
            {
                hour.success = true;
                hour.error   = "данные за запрошенную дату отсутствуют";
                hour.isEmpty = true;
                return(hour);
            }

            hour.date = new DateTime(hour.body[10 - 3] + 2000, hour.body[9 - 3], hour.body[8 - 3], hour.body[7 - 3], hour.body[6 - 3], 0);

            //время наработки
            var timeWork = new TimeSpan(BitConverter.ToUInt16(hour.body, 13 - 3), hour.body[12 - 3], hour.body[11 - 3]).TotalHours;

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Twork, hour.channel), timeWork, "ч", hour.date));

            //накопленный на конец часа|суток объем при нормальных условиях, нм3
            var volumeNormal = BitConverter.ToUInt32(hour.body, 19 - 3);

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Vn, hour.channel), volumeNormal, "м³", hour.date));

            //накопленный на конец часа|суток объем при рабочих условиях, м3
            var volumeWork = BitConverter.ToUInt32(hour.body, 23 - 3);

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Vw, hour.channel), volumeWork, "м³", hour.date));

            //среднечасовое|среднесуточное значение расхода при нормальных условиях, нм3/час| нм3/сут
            var volumeConsumptionNormal = BitConverter.ToUInt32(hour.body, 27 - 3);

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Qn, hour.channel), volumeConsumptionNormal, "м³", hour.date));

            //среднечасовое|среднесуточное значение расхода при рабочих условиях, м3/час| м3/сут
            var volumeConsumptionWork = BitConverter.ToUInt32(hour.body, 31 - 3);

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Qw, hour.channel), volumeConsumptionWork, "м³", hour.date));

            //среднечасовое|среднесуточное значение давления, кПа
            var pressure = BitConverter.ToSingle(hour.body, 35 - 3);

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.P, hour.channel), pressure, "кПа", hour.date));

            //среднечасовое|среднесуточное знчение температуры, 0C
            var temperature = BitConverter.ToSingle(hour.body, 39 - 3);

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.T, hour.channel), temperature, "°C", hour.date));

            //время при НС0
            var tns0 = BitConverter.ToInt16(hour.body, 43 - 3);

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Tns0, hour.channel), tns0, "с", hour.date));

            //время при НС1
            var tns1 = BitConverter.ToInt16(hour.body, 45 - 3);

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Tns1, hour.channel), tns1, "с", hour.date));

            //время при НС2
            var tns2 = BitConverter.ToInt16(hour.body, 47 - 3);

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Tns2, hour.channel), tns2, "с", hour.date));

            //время при НС3
            var tns3 = BitConverter.ToInt16(hour.body, 46);

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Tns3, hour.channel), tns3, "с", hour.date));

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Qns2, hour.channel), BitConverter.ToInt32(hour.body, 48), "н.м³", hour.date));

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Vns, hour.channel), BitConverter.ToInt32(hour.body, 52), "н.м³", hour.date));

            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Fl_a, hour.channel), hour.body[59 - 3], "", hour.date));
            hour.records.Add(MakeHourRecord(string.Format("{0}{1}", Glossary.Fl_b, hour.channel), BitConverter.ToInt16(hour.body, 60 - 3), "", hour.date));

            return(hour);
        }
Пример #25
0
 public short ReadShort()
 {
     return(BitConverter.ToInt16(get(2), 0));
 }
Пример #26
0
        public string GetDataAsString()
        {
            int index;

            switch (ValType)
            {
            case TagBuilder.ValueType.NullType:
                return(string.Empty);

            case TagBuilder.ValueType.StringType:
                var s = Encoding.Unicode.GetString(DataBytes).Trim('\0');
                s = Regex.Replace(s, @"\p{C}+", ", ");
                return(s);

            case TagBuilder.ValueType.AnsiStringType:
                var sa = Encoding.GetEncoding(1252).GetString(DataBytes).Trim('\0');
                sa = Regex.Replace(sa, @"\p{C}+", ", ");
                return(sa);

            case TagBuilder.ValueType.Int8Type:
                return(((sbyte)DataBytes[0]).ToString());

            case TagBuilder.ValueType.UInt8Type:
                return(DataBytes[0].ToString());

            case TagBuilder.ValueType.Int16Type:
                return(BitConverter.ToInt16(DataBytes, 0).ToString());

            case TagBuilder.ValueType.UInt16Type:
                return(BitConverter.ToUInt16(DataBytes, 0).ToString());

            case TagBuilder.ValueType.Int32Type:
                return(BitConverter.ToInt32(DataBytes, 0).ToString());

            case TagBuilder.ValueType.UInt32Type:
                return(BitConverter.ToUInt32(DataBytes, 0).ToString());

            case TagBuilder.ValueType.Int64Type:
                return(BitConverter.ToInt64(DataBytes, 0).ToString());

            case TagBuilder.ValueType.UInt64Type:
                return(BitConverter.ToUInt64(DataBytes, 0).ToString());

            case TagBuilder.ValueType.Real32Type:
                return(BitConverter.ToSingle(DataBytes, 0).ToString(CultureInfo.InvariantCulture));

            case TagBuilder.ValueType.Real64Type:
                return(BitConverter.ToDouble(DataBytes, 0).ToString(CultureInfo.InvariantCulture));

            case TagBuilder.ValueType.BoolType:
                return(BitConverter.ToBoolean(DataBytes, 0).ToString());

            case TagBuilder.ValueType.BinaryType:
                return(BitConverter.ToString(DataBytes));

            case TagBuilder.ValueType.GuidType:
                var g = new Guid(DataBytes);
                return(g.ToString());

            case TagBuilder.ValueType.SizeTType:
                return(BitConverter.ToString(DataBytes));

            case TagBuilder.ValueType.FileTimeType:
                var fts = DateTimeOffset.FromFileTime(BitConverter.ToInt64(DataBytes, 0)).ToUniversalTime();
                return(fts.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));

            case TagBuilder.ValueType.SysTimeType:

                var sts = GetSystemTime(DataBytes);

                return(sts.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));

            case TagBuilder.ValueType.SidType:
                return(ConvertHexStringToSidString(DataBytes));

            case TagBuilder.ValueType.HexInt32Type:
                return($"0x{BitConverter.ToInt32(DataBytes, 0):X}");

            case TagBuilder.ValueType.HexInt64Type:
                return($"0x{BitConverter.ToInt64(DataBytes, 0):X}");

            case TagBuilder.ValueType.EvtXml:
            case TagBuilder.ValueType.EvtHandle:
                return("UNKNOWN: Please submit to [email protected]!");

            case TagBuilder.ValueType.BinXmlType:
                return("BinaryXML");

            case TagBuilder.ValueType.ArrayUnicodeString:
                var tsu = Encoding.Unicode.GetString(DataBytes)
                          .Split(new[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
                return(string.Join(", ", tsu).Trim('\0'));

            case TagBuilder.ValueType.ArrayAsciiString:
                var tsa = Encoding.GetEncoding(1252).GetString(DataBytes)
                          .Split(new[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
                return(string.Join(", ", tsa).Trim('\0'));

            case TagBuilder.ValueType.Array64BitIntSigned:
                var a64i = new List <long>();
                index = 0;
                while (index < DataBytes.Length)
                {
                    var ul = BitConverter.ToInt64(DataBytes, index);
                    index += 8;
                    a64i.Add(ul);
                }

                return(string.Join(",", a64i));

            case TagBuilder.ValueType.Array64BitIntUnsigned:
                var a64ui = new List <ulong>();

                index = 0;
                while (index < DataBytes.Length)
                {
                    var ul = BitConverter.ToUInt64(DataBytes, index);
                    index += 8;
                    a64ui.Add(ul);
                }

                return(string.Join(",", a64ui));

            case TagBuilder.ValueType.Array16BitIntUnsigned:
                var a16ui = new List <ushort>();

                index = 0;
                while (index < DataBytes.Length)
                {
                    var ul = BitConverter.ToUInt16(DataBytes, index);
                    index += 2;
                    a16ui.Add(ul);
                }

                return(string.Join(",", a16ui));

            case TagBuilder.ValueType.Array16BitIntSigned:
                var a16i = new List <short>();
                index = 0;
                while (index < DataBytes.Length)
                {
                    var ul = BitConverter.ToInt16(DataBytes, index);
                    index += 2;
                    a16i.Add(ul);
                }

                return(string.Join(",", a16i));

            case TagBuilder.ValueType.Array32BitIntSigned:
                var a32i = new List <int>();
                index = 0;
                while (index < DataBytes.Length)
                {
                    var ul = BitConverter.ToInt32(DataBytes, index);
                    index += 4;
                    a32i.Add(ul);
                }

                return(string.Join(",", a32i));

            case TagBuilder.ValueType.Array32BitIntUnsigned:
                var a32ui = new List <uint>();
                index = 0;
                while (index < DataBytes.Length)
                {
                    var ul = BitConverter.ToUInt32(DataBytes, index);
                    index += 4;
                    a32ui.Add(ul);
                }

                return(string.Join(",", a32ui));

            case TagBuilder.ValueType.Array8BitIntSigned:
                var sb = new List <sbyte>();
                index = 0;
                while (index < DataBytes.Length)
                {
                    sb.Add((sbyte)DataBytes[index]);
                    index += 1;
                }

                return(string.Join(",", sb));

            case TagBuilder.ValueType.Array8BitIntUnsigned:
                var b = new List <byte>();
                index = 0;
                while (index < DataBytes.Length)
                {
                    b.Add(DataBytes[index]);
                    index += 1;
                }

                return(string.Join(",", b));

            case TagBuilder.ValueType.ArrayFloat32Bit:
                var sl = new List <float>();
                index = 0;
                while (index < DataBytes.Length)
                {
                    var sn = BitConverter.ToSingle(DataBytes, index);
                    index += 4;
                    sl.Add(sn);
                }

                return(string.Join(",", sl));

            case TagBuilder.ValueType.ArrayFloat64Bit:
                var dl = new List <double>();
                index = 0;
                while (index < DataBytes.Length)
                {
                    var dn = BitConverter.ToDouble(DataBytes, index);
                    index += 4;
                    dl.Add(dn);
                }

                return(string.Join(",", dl));

            case TagBuilder.ValueType.ArrayBool:
                var boo = new List <bool>();
                index = 0;
                while (index < DataBytes.Length)
                {
                    var bv = BitConverter.ToInt32(DataBytes, index) != 0;
                    boo.Add(bv);
                    index += 4;
                }

                return(string.Join(",", boo));

            case TagBuilder.ValueType.ArrayFileTime:
                var dto = new List <string>();
                index = 0;
                while (index < DataBytes.Length)
                {
                    var ts = DateTime.FromFileTime(BitConverter.ToInt64(DataBytes, index)).ToUniversalTime();
                    dto.Add(ts.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));
                    index += 8;
                }

                return(string.Join(",", dto));

            case TagBuilder.ValueType.ArraySystemTime:
                var st = new List <string>();
                index = 0;

                while (index < DataBytes.Length)
                {
                    var stb = new byte[16];
                    Buffer.BlockCopy(DataBytes, index, stb, 0, 16);
                    index += 16;

                    var nst = GetSystemTime(stb).ToUniversalTime();

                    st.Add(nst.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));
                }

                return(string.Join(",", st));

            case TagBuilder.ValueType.ArrayGuid:
                var gl = new List <string>();
                index = 0;

                while (index < DataBytes.Length)
                {
                    var gb = new byte[16];
                    Buffer.BlockCopy(DataBytes, index, gb, 0, 16);
                    index += 16;
                    var ng = new Guid(gb);
                    gl.Add(ng.ToString());
                }

                return(string.Join(",", gl));

            case TagBuilder.ValueType.ArraySizeType:

            case TagBuilder.ValueType.ArraySids:
            case TagBuilder.ValueType.Array32BitHex:
            case TagBuilder.ValueType.Array64BitHex:

            default:
                throw new ArgumentOutOfRangeException(
                          $"When converting substitution array entry to string, ran into unknown Value type: {ValType}. Please submit to [email protected]!");
            }
        }
Пример #27
0
        public async Task WriterHeaderIntroTocAsync_ValidData_Written()
        {
            var toc = new Nefs20HeaderIntroToc();

            toc.Data0x04_OffsetToPart1.Value = 111;
            toc.Data0x0c_OffsetToPart2.Value = 222;
            toc.Data0x14_OffsetToPart3.Value = 333;
            toc.Data0x18_OffsetToPart4.Value = 444;
            toc.Data0x1c_OffsetToPart5.Value = 555;
            toc.Data0x08_OffsetToPart6.Value = 666;
            toc.Data0x10_OffsetToPart7.Value = 777;
            toc.Data0x20_OffsetToPart8.Value = 888;
            toc.Data0x00_NumVolumes.Value    = 404;
            toc.Data0x02_HashBlockSize.Value = 505;

            // This chunk of data is unknown, but it must be 0x5C bytes long
            toc.Data0x24_Unknown.Value    = new byte[0x5C];
            toc.Data0x24_Unknown.Value[0] = 20;

            /*
             * Write
             */

            var writer = this.CreateWriter();

            byte[] buffer;
            var    offset = 10;

            using (var ms = new MemoryStream())
            {
                await writer.WriteHeaderIntroTocAsync(ms, (uint)offset, toc, new NefsProgress());

                buffer = ms.ToArray();
            }

            /*
             * Verify
             */

            // Num volumes
            Assert.Equal(404, BitConverter.ToInt16(buffer, offset + 0x00));

            // Hash block size
            Assert.Equal(505, BitConverter.ToInt16(buffer, offset + 0x02));

            // Offset to part 1
            Assert.Equal(111, BitConverter.ToInt32(buffer, offset + 0x04));

            // Offset to part 6
            Assert.Equal(666, BitConverter.ToInt32(buffer, offset + 0x08));

            // Offset to part 2
            Assert.Equal(222, BitConverter.ToInt32(buffer, offset + 0x0C));

            // Offset to part 7
            Assert.Equal(777, BitConverter.ToInt32(buffer, offset + 0x10));

            // Offset to part 3
            Assert.Equal(333, BitConverter.ToInt32(buffer, offset + 0x14));

            // Offset to part 4
            Assert.Equal(444, BitConverter.ToInt32(buffer, offset + 0x18));

            // Offset to part 5
            Assert.Equal(555, BitConverter.ToInt32(buffer, offset + 0x1C));

            // Offset to part 8
            Assert.Equal(888, BitConverter.ToInt32(buffer, offset + 0x20));

            // 0x24 Unknown
            Assert.Equal(20, buffer[offset + 0x24]);
        }
Пример #28
0
    public void Update()
    {
        if (socket_status == NetSocket.CLOSE)
        {
            return;
        }
        if (socket.Status == NetSocket.DISCONNECT)
        {
            event_close();
            socket_status = NetSocket.DISCONNECT;
            Debug.Log("[NetProtocol] Reconnect addr " + connect_addr + ":" + connect_port);
            socket.Connect(connect_addr, connect_port);
        }
        switch (socket_status)
        {
        case NetSocket.DISCONNECT:
            if (socket.Status == NetSocket.CONNECTED)
            {
                socket_status = NetSocket.CONNECTED;
                event_connect();
            }
            break;
        }
        if (socket.Length < 2)
        {
            return;
        }
        if (length_val == 0)
        {
            socket.Read(buffer, 2);
            length_val = BitConverter.ToInt16(buffer, 0);
            length_val = System.Net.IPAddress.NetworkToHostOrder(length_val);
        }
        if (socket.Length < length_val)
        {
            return;
        }
        if (buffer.Length < length_val)
        {
            buffer = new byte[length_val];
        }
        socket.Read(buffer, 4);
        int cmd = BitConverter.ToInt32(buffer, 0);

        Debug.Assert(length_val > 4);
        length_val -= sizeof(int);
        socket.Read(buffer, length_val);
        if (!protocol_obj.ContainsKey(cmd))
        {
            Debug.Log("[NetProtocol] can't has handler of cmd[" + cmd + "]");
            return;
        }
        wire obj = protocol_obj[cmd];
        int  err = obj._parse(buffer, length_val);

        length_val = 0;
        //Debug.Log("[NetProtocol] Process cmd[" + obj._name() + "]Err:" + err);
        if (err < 0)
        {
            return;
        }
        cb_t cb = protocol_cb[cmd];

        cb(0, obj);
        return;
    }
Пример #29
0
        static bool DecodeArrayInitializer(TypeSig elementTypeRef, byte[] initialValue, ILExpression[] output)
        {
            TypeCode elementType = TypeAnalysis.GetTypeCode(elementTypeRef);

            switch (elementType)
            {
            case TypeCode.Boolean:
            case TypeCode.Byte:
                return(DecodeArrayInitializer(initialValue, output, elementType, (d, i) => (int)d[i]));

            case TypeCode.SByte:
                return(DecodeArrayInitializer(initialValue, output, elementType, (d, i) => (int)unchecked ((sbyte)d[i])));

            case TypeCode.Int16:
                return(DecodeArrayInitializer(initialValue, output, elementType, (d, i) => (int)BitConverter.ToInt16(d, i)));

            case TypeCode.Char:
            case TypeCode.UInt16:
                return(DecodeArrayInitializer(initialValue, output, elementType, (d, i) => (int)BitConverter.ToUInt16(d, i)));

            case TypeCode.Int32:
            case TypeCode.UInt32:
                return(DecodeArrayInitializer(initialValue, output, elementType, BitConverter.ToInt32));

            case TypeCode.Int64:
            case TypeCode.UInt64:
                return(DecodeArrayInitializer(initialValue, output, elementType, BitConverter.ToInt64));

            case TypeCode.Single:
                return(DecodeArrayInitializer(initialValue, output, elementType, BitConverter.ToSingle));

            case TypeCode.Double:
                return(DecodeArrayInitializer(initialValue, output, elementType, BitConverter.ToDouble));

            case TypeCode.Object:
                var typeDef = elementTypeRef.ToTypeDefOrRef().ResolveWithinSameModule();
                if (typeDef != null && typeDef.IsEnum)
                {
                    return(DecodeArrayInitializer(typeDef.GetEnumUnderlyingType(), initialValue, output));
                }

                return(false);

            default:
                return(false);
            }
        }
 public short rdShort(bool AddToImageAddress, int pOffset)
 {
     return(BitConverter.ToInt16(this.rdMem(pOffset, 2, AddToImageAddress), 0));
 }