Example #1
0
        /// <summary>
        /// Parses the binary header image.
        /// </summary>
        /// <param name="buffer">Binary image to parse.</param>
        /// <param name="startIndex">Start index into <paramref name="buffer"/> to begin parsing.</param>
        /// <param name="length">Length of valid data within <paramref name="buffer"/>.</param>
        /// <returns>The length of the data that was parsed.</returns>
        protected override int ParseHeaderImage(byte[] buffer, int startIndex, int length)
        {
            IConfigurationCellParsingState state = State;
            int index = startIndex;

            // Parse out station name
            index += base.ParseHeaderImage(buffer, startIndex, length);

            IDCode        = BigEndian.ToUInt16(buffer, index);
            m_formatFlags = (FormatFlags)BigEndian.ToUInt16(buffer, index + 2);

            // Parse out total phasors, analogs and digitals defined for this device
            state.PhasorCount  = BigEndian.ToUInt16(buffer, index + 4);
            state.AnalogCount  = BigEndian.ToUInt16(buffer, index + 6);
            state.DigitalCount = BigEndian.ToUInt16(buffer, index + 8);
            index += 10;

            return(index - startIndex);
        }
Example #2
0
        /// <summary>
        /// Creates a new <see cref="CommonFrameHeader"/> from given <paramref name="buffer"/>.
        /// </summary>
        /// <param name="configurationFrame">IEEE C37.118 <see cref="ConfigurationFrame1"/> if already parsed.</param>
        /// <param name="buffer">Buffer that contains data to parse.</param>
        /// <param name="startIndex">Start index into buffer where valid data begins.</param>
        public CommonFrameHeader(ConfigurationFrame1 configurationFrame, byte[] buffer, int startIndex)
        {
            const byte VersionNumberMask = (byte)IEEEC37_118.FrameType.VersionNumberMask;

            if (buffer[startIndex] != PhasorProtocols.Common.SyncByte)
            {
                throw new InvalidOperationException("Bad data stream, expected sync byte 0xAA as first byte in IEEE C37.118 frame, got 0x" + buffer[startIndex].ToString("X").PadLeft(2, '0'));
            }

            // Strip out frame type and version information...
            m_frameType = (FrameType)(buffer[startIndex + 1] & ~VersionNumberMask);
            m_version   = (byte)(buffer[startIndex + 1] & VersionNumberMask);

            m_frameLength = BigEndian.ToUInt16(buffer, startIndex + 2);
            m_idCode      = BigEndian.ToUInt16(buffer, startIndex + 4);

            uint secondOfCentury  = BigEndian.ToUInt32(buffer, startIndex + 6);
            uint fractionOfSecond = BigEndian.ToUInt32(buffer, startIndex + 10);

            // Without timebase, the best timestamp you can get is down to the whole second
            m_timestamp = (new UnixTimeTag((decimal)secondOfCentury)).ToDateTime().Ticks;

            if ((object)configurationFrame != null)
            {
                long ticksBeyondSecond;

                // If config frame is available, frames have enough information for sub-second time resolution
                m_timebase = configurationFrame.Timebase;

                // "Actual fractional seconds" are obtained by taking fractionOfSecond and dividing by timebase.
                // Since we are converting to ticks, we need to multiply by Ticks.PerSecond.
                // We do the multiplication first so that the whole operation can be done using integer arithmetic.
                // m_timebase / 2L is added before dividing by timebase in order to round the result.
                ticksBeyondSecond = (fractionOfSecond & ~Common.TimeQualityFlagsMask) * Ticks.PerSecond;
                m_timestamp      += (ticksBeyondSecond + m_timebase / 2L) / m_timebase;

                // Hang on to configured frame rate and ticks per frame
                m_framesPerSecond = configurationFrame.FrameRate;
                m_ticksPerFrame   = Ticks.PerSecond / (double)m_framesPerSecond;
            }

            m_timeQualityFlags = fractionOfSecond & Common.TimeQualityFlagsMask;
        }
Example #3
0
        private void EDExtractValuesBtn_Click(object sender, EventArgs e)
        {
            EDExtracterLstvw.Items.Clear();
            byte[] encodedBlocks = HMessage.ToBytes(EDEncodedBlocksTxt.Text);
            if (encodedBlocks.Length % 4 == 0)
            {
                int    value        = 0;
                string encoded      = string.Empty;
                byte[] encodedBlock = new byte[4];
                for (int i = 0; i < encodedBlocks.Length; i += 4)
                {
                    Buffer.BlockCopy(encodedBlocks, i, encodedBlock, 0, 4);
                    value   = BigEndian.DecypherInt(encodedBlock);
                    encoded = HMessage.ToString(encodedBlock);

                    EDExtracterLstvw.FocusAdd(value.ToString(), encoded, i.ToString());
                }
            }
        }
Example #4
0
            public void Write(Stream file)
            {
                var encoder = new PngBitmapEncoder();

                encoder.Frames.Add(BitmapFrame.Create(m_bitmap));
                using (var png = new MemoryStream())
                    using (var cwp = new BinaryWriter(file, System.Text.Encoding.ASCII, true))
                    {
                        encoder.Save(png);
                        var header = new byte[0x11];
                        png.Position = 0x10;
                        png.Read(header, 0, header.Length);
                        cwp.Write(0x50445743u); // 'CWDP'
                        cwp.Write(header, 0, header.Length);
                        long idat;
                        using (var bin = new BinMemoryStream(png, ""))
                            idat = PngFormat.FindChunk(bin, "IDAT");
                        if (-1 == idat)
                        {
                            throw new InvalidFormatException("CWP conversion failed");
                        }
                        png.Position = idat;
                        png.Read(header, 0, 8);
                        int chunk_size = BigEndian.ToInt32(header, 0) + 4;
                        cwp.Write(header, 0, 4);
                        for (;;)
                        {
                            CopyChunk(png, file, chunk_size);
                            if (8 != png.Read(header, 0, 8))
                            {
                                throw new InvalidFormatException("CWP conversion failed");
                            }
                            if (Binary.AsciiEqual(header, 4, "IEND"))
                            {
                                cwp.Write((byte)0);
                                break;
                            }
                            chunk_size = BigEndian.ToInt32(header, 0) + 4;
                            cwp.Write(header, 0, 8);
                        }
                    }
            }
Example #5
0
        /// <summary>
        /// Parses the binary header image.
        /// </summary>
        /// <param name="buffer">Binary image to parse.</param>
        /// <param name="startIndex">Start index into <paramref name="buffer"/> to begin parsing.</param>
        /// <param name="length">Length of valid data within <paramref name="buffer"/>.</param>
        /// <returns>The length of the data that was parsed.</returns>
        protected override int ParseHeaderImage(byte[] buffer, int startIndex, int length)
        {
            IConfigurationCellParsingState state = State;
            int index = startIndex;

            m_statusFlags = BigEndian.ToUInt16(buffer, index);
            index        += 2;

            // Parse out station name
            index += base.ParseHeaderImage(buffer, index, length);

            IDCode = BigEndian.ToUInt64(buffer, index);

            // Parse out total phasors and digitals defined for this device
            state.PhasorCount  = BigEndian.ToUInt16(buffer, index + 8);
            state.DigitalCount = BigEndian.ToUInt16(buffer, index + 10);
            index += 12;

            return(index - startIndex);
        }
Example #6
0
        public override ImageMetaData ReadMetaData(IBinaryStream file)
        {
            var header = file.ReadHeader(13);

            if (!header.AsciiEqual(4, "TPGF"))
            {
                return(null);
            }
            int bpp = header[12];

            if (bpp != 8 && bpp != 24)
            {
                return(null);
            }
            return(new ImageMetaData {
                Width = BigEndian.ToUInt16(header, 8),
                Height = BigEndian.ToUInt16(header, 10),
                BPP = bpp,
            });
        }
Example #7
0
        public void EncryptXD(byte[] data, ushort[] encryptionKeys, uint end = 0x27FD8)
        {
            ushort tmp = 0;

            ushort[] keys = new ushort[4];
            for (int i = 0; i < 4; i++)
            {
                keys[i] = encryptionKeys[i];
            }
            for (int i = 16; i < end; i += 8)
            {
                for (int j = 0; j < 4; j++)
                {
                    tmp  = BigEndian.ToUInt16(data, i + j * 2);
                    tmp += keys[j];
                    BigEndian.WriteUInt16(tmp, data, i + j * 2);
                }
                AdvanceKeys(keys);
            }
        }
Example #8
0
        public override ImageMetaData ReadMetaData(IBinaryStream stream)
        {
            var header = stream.ReadHeader(12);

            if (header.Length != 12)
            {
                return(null);
            }
            if (!header.AsciiEqual(4, "GWD"))
            {
                return(null);
            }
            return(new GwdMetaData
            {
                Width = BigEndian.ToUInt16(header, 7),
                Height = BigEndian.ToUInt16(header, 9),
                BPP = header[11],
                DataSize = LittleEndian.ToUInt32(header, 0),
            });
        }
Example #9
0
        private void SavePocket(ItemTypes pocketType, int index)
        {
            ItemPocket pocket     = parent.Inventory.Items[pocketType];
            uint       pocketSize = pocket.TotalSlots;

            for (int i = 0; i < (int)pocketSize; i++)
            {
                if (i < (int)pocket.SlotsUsed)
                {
                    ushort id = pocket[i].ID;
                    if (gameSave.GameType == GameTypes.XD)
                    {
                        // Share Colognes and cologne case between games so make sure we use one of the game's ID's, We're using Colosseum's IDs
                        if (id >= 542 && id <= 545)
                        {
                            id += 970;
                        }
                        // Two Key items that are shared between Colosseum and XD
                        if (id == 501)
                        {
                            id += 1000;
                        }
                        if (id == 530)
                        {
                            id += 975;
                        }
                        // Because XD and Colosseum share the same item IDs with different items, XD items are 1000 higher. (I chose 1000 for easy reading)
                        if (id >= 1500)
                        {
                            id -= 1000;
                        }
                    }
                    BigEndian.WriteUInt16(id, raw, index + i * 4);
                    BigEndian.WriteUInt16((ushort)pocket[i].Count, raw, index + i * 4 + 2);
                }
                else
                {
                    BigEndian.WriteUInt32(0, raw, index + i * 4);
                }
            }
        }
Example #10
0
        public PokemonBoxGameSave(string filePath, bool japanese = false)
        {
            byte[] data = File.ReadAllBytes(filePath);
            this.loaded     = false;
            this.hasGCIData = false;
            this.japanese   = japanese;

            if (data.Length == 483328 || data.Length == 483392)
            {
                if (data.Length == 483392)
                {
                    this.hasGCIData = true;
                }
            }
            else
            {
                throw new Exception("Pokemon Box saves must be either 483,328 or 483,392 bytes in length");
            }

            int start = 0x2000 + (hasGCIData ? 64 : 0);

            this.saveData = new PokemonBoxSaveData[2];
            List <PokemonBoxBlockData> blocks = new List <PokemonBoxBlockData>();

            for (int i = 0; start + 0x2000 * (i + 1) <= data.Length; i++)
            {
                //blocks.Add(new PokemonBoxBlockData(ByteHelper.SubByteArray(start + 0x2000 * i, data, 0x2E000)));
            }
            if (BigEndian.ToSInt32(data, start + 0x8) != 0)
            {
                this.saveData[0] = new PokemonBoxSaveData(this, ByteHelper.SubByteArray(start, data, 0x2E000));
            }
            if (BigEndian.ToSInt32(data, start + 0x2E000 + 0x8) != 0)
            {
                this.saveData[1] = new PokemonBoxSaveData(this, ByteHelper.SubByteArray(start + 0x2E000, data, 0x2E000));
            }
            PokePC.ApplyGameType(GameTypes.PokemonBox);

            this.raw    = data;
            this.loaded = true;
        }
Example #11
0
        /// <summary>
        /// Validates and parses 4-byte length sample value tag.
        /// </summary>
        /// <param name="buffer">Buffer containing sampled value.</param>
        /// <param name="tag">Sampled value tag to parse.</param>
        /// <param name="index">Start index of buffer where tag length begins - will be auto-incremented.</param>
        public static uint ParseUInt32Tag(this byte[] buffer, SampledValueTag tag, ref int index)
        {
            if ((SampledValueTag)buffer[index] != tag)
            {
                throw new InvalidOperationException("Encountered out-of-sequence or unknown sampled value tag: 0x" + buffer[index].ToString("X").PadLeft(2, '0'));
            }

            index++;
            int tagLength = buffer.ParseTagLength(ref index);

            if (tagLength < 4)
            {
                throw new InvalidOperationException(string.Format("Unexpected length for \"{0}\" tag: {1}", tag, tagLength));
            }

            uint result = BigEndian.ToUInt32(buffer, index);

            index += tagLength;

            return(result);
        }
Example #12
0
        public override ImageMetaData ReadMetaData(IBinaryStream file)
        {
            var header = file.ReadHeader(0x20);
            int bpp    = header[10] & 0x1F;

            if (!(bpp == 24 || bpp == 16 || bpp == 8))
            {
                return(null);
            }
            return(new LagMetaData
            {
                Width = BigEndian.ToUInt16(header, 4),
                Height = BigEndian.ToUInt16(header, 6),
                BPP = bpp,
                ScanLineSize = BigEndian.ToUInt16(header, 8),
                HasPalette = (header[10] & 0x80) != 0,
                HasAlpha = (header[10] & 0x20) != 0,
                LastChunkSize = BigEndian.ToInt32(header, 0x14),
                ChunkCount = BigEndian.ToUInt16(header, 0x18),
            });
        }
Example #13
0
        /// <summary>
        /// Validates and parses 8-byte length sample value tag.
        /// </summary>
        /// <param name="buffer">Buffer containing sampled value.</param>
        /// <param name="tag">Sampled value tag to parse.</param>
        /// <param name="index">Start index of buffer where tag length begins - will be auto-incremented.</param>
        public static ulong ParseUInt64Tag(this byte[] buffer, SampledValueTag tag, ref int index)
        {
            if ((SampledValueTag)buffer[index] != tag)
            {
                throw new InvalidOperationException($"Encountered out-of-sequence or unknown sampled value tag: 0x{buffer[index].ToString("X").PadLeft(2, '0')}");
            }

            index++;
            int tagLength = buffer.ParseTagLength(ref index);

            if (tagLength < 8)
            {
                throw new InvalidOperationException($"Unexpected length for \"{tag}\" tag: {tagLength}");
            }

            ulong result = BigEndian.ToUInt64(buffer, index);

            index += tagLength;

            return(result);
        }
Example #14
0
        public void TestDateTime()
        {
            byte[] min = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] max = new byte[] { 0, 255, 255, 255, 0, 0, 0, 0 };

            for (int x = 0; x < 128; x++)
            {
                min[0] = (byte)x;
                max[0] = (byte)x;

                long mind = BigEndian.ToInt64(min, 0);
                long maxd = BigEndian.ToInt64(max, 0);

                if (maxd > CtpTime.MaxValue.Ticks)
                {
                    continue;
                }

                Console.WriteLine($"{x}\t{new CtpTime(mind)}\t{new CtpTime(maxd)}");
            }
        }
Example #15
0
        public override void Replace <T>(int index, object chunk)
        {
            switch (Type.GetTypeCode(typeof(T)))
            {
            case TypeCode.Int32: _body.RemoveRange(index, 4); break;

            case TypeCode.UInt16: _body.RemoveRange(index, 2); break;

            case TypeCode.Boolean: _body.RemoveAt(index); break;

            case TypeCode.String:
            {
                int stringLength = BigEndian.DecypherShort(Body, index);
                _body.RemoveRange(index, 2 + stringLength);
                break;
            }
            }

            _body.InsertRange(index, Encode(chunk));
            Reconstruct();
        }
Example #16
0
        public override ImageMetaData ReadMetaData(IBinaryStream file)
        {
            var           header      = file.ReadHeader(14);
            int           header_size = BigEndian.ToUInt16(header, 0);
            CandyMetaData info;

            if (14 == header_size)
            {
                info = new CandyMetaData {
                    OffsetX    = BigEndian.ToInt16(header, 2),
                    OffsetY    = BigEndian.ToInt16(header, 4),
                    Width      = BigEndian.ToUInt16(header, 6),
                    Height     = BigEndian.ToUInt16(header, 8),
                    BPP        = header[0xA],
                    Colors     = BigEndian.ToUInt16(header, 0xC),
                    Version    = header[0xB],
                    HeaderSize = header_size,
                };
            }
            else if (10 == header_size)
            {
                info = new CandyMetaData {
                    Width      = BigEndian.ToUInt16(header, 2),
                    Height     = BigEndian.ToUInt16(header, 4),
                    BPP        = header[6],
                    Colors     = BigEndian.ToUInt16(header, 8),
                    Version    = header[7],
                    HeaderSize = header_size,
                };
            }
            else
            {
                return(null);
            }
            if (info.Version != 1 && info.Version != 2 || info.BPP < 8 || info.BPP > 32)
            {
                return(null);
            }
            return(info);
        }
Example #17
0
        /// <summary>
        /// Generates binary image of the <see cref="CompactMeasurement"/> and copies it into the given buffer, for <see cref="ISupportBinaryImage.BinaryLength"/> bytes.
        /// </summary>
        /// <param name="buffer">Buffer used to hold generated binary image of the source object.</param>
        /// <param name="startIndex">0-based starting index in the <paramref name="buffer"/> to start writing.</param>
        /// <returns>The number of bytes written to the <paramref name="buffer"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="startIndex"/> or <see cref="ISupportBinaryImage.BinaryLength"/> is less than 0 -or-
        /// <paramref name="startIndex"/> and <see cref="ISupportBinaryImage.BinaryLength"/> will exceed <paramref name="buffer"/> length.
        /// </exception>
        /// <remarks>
        /// <para>
        /// Field:     Bytes: <br/>
        /// --------   -------<br/>
        ///  Flags        1   <br/>
        ///   ID          2   <br/>
        ///  Value        4   <br/>
        ///  [Time]       2?  <br/>
        /// </para>
        /// <para>
        /// Constant Length = 7<br/>
        /// Variable Length = 0, 2, 4 or 8 (i.e., total size is 7, 9, 11 or 15)
        /// </para>
        /// </remarks>
        public int GenerateBinaryImage(byte[] buffer, int startIndex)
        {
            // Call to binary length property caches result of m_usingBaseTimeOffset
            int length = BinaryLength;

            buffer.ValidateParameters(startIndex, length);

            // Added encoded compact state flags to beginning of buffer
            buffer[startIndex++] = CompactStateFlags;

            // Encode runtime ID
            startIndex += BigEndian.CopyBytes(RuntimeID, buffer, startIndex);

            // Encode adjusted value (accounts for adder and multiplier)
            startIndex += BigEndian.CopyBytes((float)AdjustedValue, buffer, startIndex);

            if (m_includeTime)
            {
                if (m_usingBaseTimeOffset)
                {
                    if (m_useMillisecondResolution)
                    {
                        // Encode 2-byte millisecond offset timestamp
                        BigEndian.CopyBytes(TimestampC2, buffer, startIndex);
                    }
                    else
                    {
                        // Encode 4-byte ticks offset timestamp
                        BigEndian.CopyBytes(TimestampC4, buffer, startIndex);
                    }
                }
                else
                {
                    // Encode 8-byte full fidelity timestamp
                    BigEndian.CopyBytes((long)Timestamp, buffer, startIndex);
                }
            }

            return(length);
        }
Example #18
0
        /// <summary>
        /// Idmの読み出し
        /// </summary>
        /// <param name="sysCode">システムコード</param>
        /// <param name="idm">Idm(idm)</param>
        /// <returns>成功?</returns>
        public static bool ReadIdm(ushort sysCode, byte[] idm)
        {
            HandleContainer hc = new HandleContainer();

            try
            {
                //取得対象
                byte[] sysCodeBuffer = new byte[2];
                BigEndian.SetUIntToBytes(sysCode, sysCodeBuffer, 0);

                StructurePolling polling = new StructurePolling();
                polling.TimeSlot   = 0x00;//同時に検出できる枚数=1
                polling.SystemCode = hc.AddPinnedObject(sysCodeBuffer).AddrOfPinnedObject();

                //出力バッファ
                byte[] idmBuffer = new byte[8];
                byte[] pmmBuffer = new byte[8];
                StructureCardInformation card = new StructureCardInformation();
                card.CardIdm = hc.AddPinnedObject(idmBuffer).AddrOfPinnedObject();
                card.CardPmm = hc.AddPinnedObject(pmmBuffer).AddrOfPinnedObject();

                //メモリ固定
                byte cards = new Byte();
                hc.AddPinnedObject(cards);

                bool res = felica_dll.PollingAndGetCardInformation(ref polling, ref cards, ref card);
                if (res && cards > 0)
                {
                    //取得したIdmを返す
                    idmBuffer.CopyTo(idm, 0);
                    return(true);
                }
                return(false);
            }
            finally
            {
                //GC除外メモリの解放
                hc.FreeHandle();
            }
        }
Example #19
0
        private void RealignBtn_Click(object sender, EventArgs e)
        {
            if (InputBox == null)
            {
                return;
            }

            int packetHeaderEnd = 0;

            if (!InputBox.Text.StartsWith("{l}{u:"))
            {
                ushort packetHeader = 0;
                byte[] packetData   = HMessage.ToBytes(InputBox.Text);
                if (packetData.Length >= 6)
                {
                    int packetLength = BigEndian.ToInt32(packetData, 0);
                    packetHeader = BigEndian.ToUInt16(packetData, 4);

                    byte[] headerData = new byte[6];
                    Buffer.BlockCopy(packetData, 0, headerData, 0, 6);

                    if (packetLength == (packetData.Length - 4))
                    {
                        string formattedHeader = HMessage.ToString(headerData);
                        InputBox.Text = InputBox.Text.Remove(0, formattedHeader.Length);
                    }
                }
                InputBox.Text   = InputBox.Text.Insert(0, $"{{l}}{{u:{packetHeader}}}");
                packetHeaderEnd = packetHeader.ToString().Length;
            }
            else
            {
                string formattedHeader = InputBox.Text
                                         .GetChild("{l}{u:").GetParent("}");

                packetHeaderEnd = formattedHeader.Length;
            }
            InputBox.Select(6, packetHeaderEnd);
            InputBox.ScrollToCaret();
        }
Example #20
0
        private void XmlSerialize(XmlWriter xw)
        {
            xw.WriteStartDocument();
            xw.WriteStartElement(nameof(PARAMDEF));
            xw.WriteAttributeString("XmlVersion", XML_VERSION.ToString());
            xw.WriteElementString(nameof(ParamType), ParamType);
            xw.WriteElementString(nameof(Unk06), Unk06.ToString());
            xw.WriteElementString(nameof(BigEndian), BigEndian.ToString());
            xw.WriteElementString(nameof(Unicode), Unicode.ToString());
            xw.WriteElementString(nameof(Version), Version.ToString());

            xw.WriteStartElement(nameof(Fields));
            foreach (Field field in Fields)
            {
                xw.WriteStartElement(nameof(Field));
                field.XmlSerialize(xw);
                xw.WriteEndElement();
            }
            xw.WriteEndElement();

            xw.WriteEndElement();
        }
Example #21
0
        /// <summary>
        /// Encodes primitive type sampled value tag.
        /// </summary>
        /// <param name="value">Value to encode.</param>
        /// <param name="tag">Sampled value tag to encode.</param>
        /// <param name="buffer">Buffer to hold encoded sampled value.</param>
        /// <param name="index">Start index of buffer where tag will begin - will be auto-incremented.</param>
        public static void EncodeTagValue <T>(this T value, SampledValueTag tag, byte[] buffer, ref int index) where T : struct, IConvertible
        {
            if (!typeof(T).IsPrimitive)
            {
                throw new ArgumentException("Value type is not primitive", nameof(value));
            }

            // Not sure if booleans would be encoded correctly here (due to Marshal sizeof) - also not sure
            // how IEC 61850 deals with booleans - as a result, booleans should likely be avoided.
            // I wonder if compiler is smart enough to exclude this expression in implementations since this
            // is always false for non boolean types - where is my WHERE expression like "~bool"...
            if (typeof(T) == typeof(bool))
            {
                throw new ArgumentOutOfRangeException(nameof(value), "Boolean encoding is currently not supported");
            }

            ushort length = (ushort)Marshal.SizeOf(typeof(T));

            buffer[index++] = (byte)tag;
            length.EncodeTagLength(buffer, ref index);
            index += BigEndian.CopyBytes(value, buffer, index);
        }
Example #22
0
        public async Task <HMessage> ReceiveAsync(SocketFlags flags)
        {
            byte[] lengthData = await ReceiveAsync(flags, 4, true)
                                .ConfigureAwait(false);

            if (lengthData == null)
            {
                return(null);
            }
            PacketsReceived++;

            int length = BigEndian.ToInt32(lengthData, 0);

            byte[] data = await ReceiveAsync(flags, length, true).ConfigureAwait(false);

            var messageData = new byte[4 + length];

            Buffer.BlockCopy(lengthData, 0, messageData, 0, lengthData.Length);
            Buffer.BlockCopy(data, 0, messageData, lengthData.Length, data.Length);

            return(new HMessage(messageData));
        }
Example #23
0
        protected virtual void UpdateValue(ListViewItem item, object value)
        {
            lock (_values)
            {
                byte[] data = null;
                switch (item.SubItems[0].Text)
                {
                case "String": data = BigEndian.GetBytes((string)value); break;

                case "Integer": data = BigEndian.GetBytes((int)value); break;

                case "Boolean": data = BigEndian.GetBytes((bool)value); break;
                }

                string encoded = HMessage.ToString(data);
                item.SubItems[1].Text = value.ToString();
                item.SubItems[2].Text = encoded;

                _values[item.Index] = value;
                _cachedPacket       = null;
            }
        }
Example #24
0
        private void EDTDecodeValuesBtn_Click(object sender, EventArgs e)
        {
            MainUI.EDTDecodedVw.Items.Clear();
            string encodedBlocks = MainUI.EDTEncodedValuesTxt.Text;

            byte[] data = HMessage.ToBytes(encodedBlocks);

            if (data.Length % 4 != 0)
            {
                return;
            }
            for (int i = 0; i < data.Length; i += 4)
            {
                var block = new byte[4];
                Buffer.BlockCopy(data, i, block, 0, 4);

                int    value   = BigEndian.ToSI32(block);
                string encoded = HMessage.ToString(block);

                MainUI.EDTDecodedVw.FocusAdd(value, encoded, i);
            }
        }
Example #25
0
        private void OnReceiving(IAsyncResult ar)
        {
            try
            {
                SocketError errorCode;
                int         length = _client.EndReceive(ar, out errorCode);
                if (errorCode != SocketError.Success)
                {
                    Disconnect();
                }
                else if (ShouldReceive)
                {
                    var data = new byte[length];
                    Buffer.BlockCopy(_inBuffer, 0, data, 0, length);

                    if (IncomingDecrypt != null)
                    {
                        IncomingDecrypt.Parse(data);
                    }

                    if (_inStep == 2)
                    {
                        length = (data.Length >= 6 ? BigEndian.DecypherInt(data) : 0);
                        IsIncomingEncrypted = (length != data.Length - 4);
                    }

                    foreach (byte[] packet in ByteUtils.Split(ref _inCache, data, true))
                    {
                    }

                    if (ShouldReceive) // 'ShouldReceive' could have been changed while processing the current data.
                    {
                        _client.BeginReceive(_inBuffer, 0, _inBuffer.Length, SocketFlags.None, OnReceiving, null);
                    }
                }
            }
            catch (ObjectDisposedException) { }
            catch { Disconnect(); }
        }
Example #26
0
        public override ImageMetaData ReadMetaData(IBinaryStream input)
        {
            var  header = input.ReadHeader(0x11);
            uint width  = BigEndian.ToUInt32(header, 4);
            uint height = BigEndian.ToUInt32(header, 8);

            if (0 == width || 0 == height)
            {
                return(null);
            }
            int bpp = header[0xC];

            if (bpp != 1 && bpp != 2 && bpp != 4 && bpp != 8 && bpp != 16)
            {
                return(null);
            }
            int color_type = header[0xD];

            switch (color_type)
            {
            case 2: bpp *= 3; break;

            case 4: bpp *= 2; break;

            case 6: bpp *= 4; break;

            case 3:
            case 0: break;

            default: return(null);
            }
            return(new ImageMetaData
            {
                Width = width,
                Height = height,
                BPP = 32, // always converted to 32bpp
            });
        }
Example #27
0
        private void HandleSendMeasurementsCommand(ClientConnection connection, byte[] buffer, int startIndex, int length)
        {
            int index = startIndex;

            if (length - index < 4)
            {
                throw new Exception("Not enough bytes in buffer to parse measurement count");
            }

            int count = BigEndian.ToInt32(buffer, index);

            index += sizeof(int);

            if (length - index < count * 36)
            {
                throw new Exception("Not enough bytes in buffer to parse all measurements");
            }

            List <IMeasurement> measurements = new List <IMeasurement>(count);

            for (int i = 0; i < count; i++)
            {
                Guid     signalID  = buffer.ToRfcGuid(index); index += 16;
                DateTime timestamp = new DateTime(BigEndian.ToInt64(buffer, index)); index += sizeof(long);
                double   value     = BigEndian.ToDouble(buffer, index); index += sizeof(double);
                MeasurementStateFlags stateFlags = (MeasurementStateFlags)BigEndian.ToInt32(buffer, index); index += sizeof(int);

                measurements.Add(new Measurement()
                {
                    Metadata   = MeasurementKey.LookUpBySignalID(signalID).Metadata,
                    Timestamp  = timestamp,
                    Value      = value,
                    StateFlags = stateFlags
                });
            }

            OnNewMeasurements(measurements);
        }
Example #28
0
        }                                                                 // '8BPS'

        public override ImageMetaData ReadMetaData(Stream stream)
        {
            var header = new byte[26];

            if (header.Length != stream.Read(header, 0, header.Length))
            {
                return(null);
            }
            int version = BigEndian.ToInt16(header, 4);

            if (1 != version)
            {
                return(null);
            }
            int channels = BigEndian.ToInt16(header, 0x0C);

            if (channels < 1 || channels > 56)
            {
                return(null);
            }
            uint height = BigEndian.ToUInt32(header, 0x0E);
            uint width  = BigEndian.ToUInt32(header, 0x12);

            if (width < 1 || width > 30000 || height < 1 || height > 30000)
            {
                return(null);
            }
            int bpc = BigEndian.ToInt16(header, 0x16);

            return(new PsdMetaData
            {
                Width = width,
                Height = height,
                Channels = channels,
                BPP = channels * bpc,
                Mode = BigEndian.ToInt16(header, 0x18),
            });
        }
Example #29
0
        public bool IsInjectionAuthorized(HMessage packet)
        {
            if (!IsInjectionAuthorized())
            {
                return(false);
            }
            if (!packet.IsCorrupted)
            {
                return(true);
            }
            else
            {
                byte[] data     = packet.ToBytes();
                string alertMsg = PACKET_LENGTH_INVALID;

                if (data.Length < 6)
                {
                    alertMsg +=
                        $"\r\n\r\nYou're missing {6 - data.Length:#,##0} byte(s).";
                }
                else
                {
                    int length = (data.Length > 0 ?
                                  BigEndian.ToInt32(data, 0) : 0);

                    int  realLength = (data.Length - 4);
                    bool tooShort   = (length > realLength);
                    int  difference = Math.Abs(realLength - length);

                    alertMsg +=
                        $"\r\n\r\nYou're {difference:#,##0} byte(s) too {(tooShort ? "short" : "big")}.";
                }
                MessageBox.Show(alertMsg, "Tanji ~ Alert!",
                                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                return(false);
            }
        }
Example #30
0
        private void AddPocket(ItemTypes pocketType, int index, uint pocketSize, uint maxStackSize, bool allowDuplicateStacks, bool ordered)
        {
            parent.Inventory.Items.AddPocket(pocketType, pocketSize, maxStackSize, allowDuplicateStacks, ordered);
            ItemPocket pocket = parent.Inventory.Items[pocketType];

            for (int i = 0; i < (int)pocketSize; i++)
            {
                ushort id = BigEndian.ToUInt16(raw, index + i * 4);
                if (gameSave.GameType == GameTypes.XD)
                {
                    // Because XD and Colosseum share the same item IDs with different items, XD items are 1000 higher. (I chose 1000 for easy reading)
                    // When we save the items we'll decrement their id again.
                    if (id >= 500)
                    {
                        id += 1000;
                    }
                    // Share Colognes amd cologne case between games so make sure we use one of the game's ID's, We're using Colosseum's IDs
                    if (id >= 1512 && id <= 1515)
                    {
                        id -= 970;
                    }
                    // Two Key items that are shared between Colosseum and XD
                    if (id == 1501)
                    {
                        id -= 1000;
                    }
                    if (id == 1505)
                    {
                        id -= 975;
                    }
                }
                ushort count = BigEndian.ToUInt16(raw, index + i * 4 + 2);
                if (id != 0)
                {
                    pocket.AddItem(id, count);
                }
            }
        }