Exemplo n.º 1
0
        private void Initialize(string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            IntPtr hModule = IntPtr.Zero;

            try
            {
                hModule = NativeMethods.LoadLibraryEx(fileName, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE);
                if (hModule == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                FileName = GetFileName(hModule);

                // Enumerate the icon resource and build .ico files in memory.

                var tmpData = new List <byte[]>();

                bool callback(IntPtr h, IntPtr t, IntPtr name, IntPtr l)
                {
                    // Refer to the following URL for the data structures used here:
                    // http://msdn.microsoft.com/en-us/library/ms997538.aspx

                    // RT_GROUP_ICON resource consists of a GRPICONDIR and GRPICONDIRENTRY's.

                    var dir = GetDataFromResource(hModule, RT_GROUP_ICON, name);

                    // Calculate the size of an entire .icon file.

                    int count = BitConverter.ToUInt16(dir, 4);  // GRPICONDIR.idCount
                    int len   = 6 + 16 * count;                 // sizeof(ICONDIR) + sizeof(ICONDIRENTRY) * count

                    for (int i = 0; i < count; ++i)
                    {
                        len += BitConverter.ToInt32(dir, 6 + 14 * i + 8);   // GRPICONDIRENTRY.dwBytesInRes
                    }
                    using (var dst = new BinaryWriter(new MemoryStream(len)))
                    {
                        // Copy GRPICONDIR to ICONDIR.

                        dst.Write(dir, 0, 6);

                        int picOffset = 6 + 16 * count; // sizeof(ICONDIR) + sizeof(ICONDIRENTRY) * count

                        for (int i = 0; i < count; ++i)
                        {
                            // Load the picture.

                            ushort id  = BitConverter.ToUInt16(dir, 6 + 14 * i + 12);   // GRPICONDIRENTRY.nID
                            var    pic = GetDataFromResource(hModule, RT_ICON, (IntPtr)id);

                            // Copy GRPICONDIRENTRY to ICONDIRENTRY.

                            dst.Seek(6 + 16 * i, SeekOrigin.Begin);

                            dst.Write(dir, 6 + 14 * i, 8);  // First 8bytes are identical.
                            dst.Write(pic.Length);          // ICONDIRENTRY.dwBytesInRes
                            dst.Write(picOffset);           // ICONDIRENTRY.dwImageOffset

                            // Copy a picture.

                            dst.Seek(picOffset, SeekOrigin.Begin);
                            dst.Write(pic, 0, pic.Length);

                            picOffset += pic.Length;
                        }

                        tmpData.Add(((MemoryStream)dst.BaseStream).ToArray());
                    }

                    return(true);
                }
                NativeMethods.EnumResourceNames(hModule, RT_GROUP_ICON, callback, IntPtr.Zero);

                iconData = tmpData.ToArray();
            }
            finally
            {
                if (hModule != IntPtr.Zero)
                {
                    NativeMethods.FreeLibrary(hModule);
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 对接收到的下位机传来的数据包进行解包
        /// </summary>
        /// <param name="Buffer">数据包</param>
        /// <param name="MyRov">ROV数据结构体</param>
        public static void DataRX_Handler(List <byte> Buffer, ref ROVDatabase MyRov)
        {
            byte[] RxBuffer = Buffer.ToArray(); //数据包数组
            switch (RxBuffer[0])
            {
            case (RX_StartBit_JY901):      //表示待解析的是JY901姿态传感器的数据包
            {
                MyRov.JY901Data.AccelerationX = BitConverter.ToSingle(RxBuffer, 1);
                MyRov.JY901Data.AccelerationY = BitConverter.ToSingle(RxBuffer, 5);
                MyRov.JY901Data.AccelerationZ = BitConverter.ToSingle(RxBuffer, 9);
                MyRov.JY901Data.PitchAngle    = BitConverter.ToSingle(RxBuffer, 13);
                MyRov.JY901Data.YawAngle      = BitConverter.ToSingle(RxBuffer, 17);
                MyRov.JY901Data.RollAngle     = BitConverter.ToSingle(RxBuffer, 21);
                MyRov.JY901Data.AngleSpeedX   = BitConverter.ToSingle(RxBuffer, 25);
                MyRov.JY901Data.AngleSpeedY   = BitConverter.ToSingle(RxBuffer, 29);
                MyRov.JY901Data.AngleSpeedZ   = BitConverter.ToSingle(RxBuffer, 33);
                break;
            }

            case (RX_StartBit_MS5837):      //表示待解析的是MS5837深度传感器的数据包
            {
                MyRov.MS5837Data.Pressure    = BitConverter.ToSingle(RxBuffer, 1);
                MyRov.MS5837Data.Depth       = BitConverter.ToSingle(RxBuffer, 5);
                MyRov.MS5837Data.Temperature = BitConverter.ToSingle(RxBuffer, 9);
                MyRov.MS5837Data.Offset      = BitConverter.ToSingle(RxBuffer, 13);
                break;
            }

            case (RX_StartBit_SERVO):                                                                //表示待解析的是舵机的数据包
            {
                MyRov.ServoData.FinTail_Front_StartingPosition = BitConverter.ToUInt16(RxBuffer, 1); //尾部推进舵机 起始位置
                MyRov.ServoData.FinTail_Front_EndingPosition   = BitConverter.ToUInt16(RxBuffer, 3); //尾部推进舵机 终止位置
                MyRov.ServoData.FinTail_Front_EachCCR          = BitConverter.ToUInt16(RxBuffer, 5); //尾部推进舵机 每次改变的占空比
                MyRov.ServoData.FinTail_Front_DelayTime        = BitConverter.ToUInt16(RxBuffer, 7); //尾部推进舵机 延时长度

                MyRov.ServoData.FinTail_Rear_StartingPosition = BitConverter.ToUInt16(RxBuffer, 9);  //尾部推进舵机 起始位置
                MyRov.ServoData.FinTail_Rear_EndingPosition   = BitConverter.ToUInt16(RxBuffer, 11); //尾部推进舵机 终止位置
                MyRov.ServoData.FinTail_Rear_EachCCR          = BitConverter.ToUInt16(RxBuffer, 13); //尾部推进舵机 每次改变的占空比
                MyRov.ServoData.FinTail_Rear_DelayTime        = BitConverter.ToUInt16(RxBuffer, 15); //尾部推进舵机 延时长度

                MyRov.ServoData.Camera_Position = BitConverter.ToUInt16(RxBuffer, 17);               //摄像机云台舵机 位置
                MyRov.ServoData.Pulse_Num       = BitConverter.ToUInt16(RxBuffer, 19);               //脉冲数
                break;
            }

            case (RX_StartBit_PID):      //表示待解析的是PID系数的数据包
            {
                MyRov.pidData_Depth.Kp     = BitConverter.ToSingle(RxBuffer, 1);
                MyRov.pidData_Depth.Ki     = BitConverter.ToSingle(RxBuffer, 5);
                MyRov.pidData_Depth.Kd     = BitConverter.ToSingle(RxBuffer, 9);
                MyRov.pidData_Depth.Target = BitConverter.ToSingle(RxBuffer, 13);

                MyRov.pidData_Pitch.Kp     = BitConverter.ToSingle(RxBuffer, 17);
                MyRov.pidData_Pitch.Ki     = BitConverter.ToSingle(RxBuffer, 21);
                MyRov.pidData_Pitch.Kd     = BitConverter.ToSingle(RxBuffer, 25);
                MyRov.pidData_Pitch.Target = BitConverter.ToSingle(RxBuffer, 29);

                MyRov.pidData_Yaw.Kp     = BitConverter.ToSingle(RxBuffer, 33);
                MyRov.pidData_Yaw.Ki     = BitConverter.ToSingle(RxBuffer, 37);
                MyRov.pidData_Yaw.Kd     = BitConverter.ToSingle(RxBuffer, 41);
                MyRov.pidData_Yaw.Target = BitConverter.ToSingle(RxBuffer, 45);

                MyRov.pidData_AccelerationY.Kp     = BitConverter.ToSingle(RxBuffer, 49);
                MyRov.pidData_AccelerationY.Ki     = BitConverter.ToSingle(RxBuffer, 53);
                MyRov.pidData_AccelerationY.Kd     = BitConverter.ToSingle(RxBuffer, 57);
                MyRov.pidData_AccelerationY.Target = BitConverter.ToSingle(RxBuffer, 61);

                break;
            }
            }
        }
Exemplo n.º 3
0
        byte ProcessSocksHeaders(List <byte> buffer)
        {
            if (9 > buffer.Count || 265 < buffer.Count)
            {
                ServerComms.LogError($"Socks server: buffer size {buffer.Count} is not valid, must be between 9 & 256");
                return(Socks4ClientHeader.Socks4ClientHeaderStatus.REQUEST_REJECTED_OR_FAILED);
            }
            byte version = buffer[0];

            if (version == 0x4)
            {
                byte commandCode = buffer.Skip(1).Take(1).First();
                BitConverter.ToUInt16(buffer.Skip(2).Take(2).ToArray(), 0);
                BitConverter.ToUInt16(buffer.Skip(2).Take(2).Reverse().ToArray(), 0);
                _targetPort = BitConverter.ToUInt16(buffer.Skip(2).Take(2).Reverse().ToArray(), 0);
                var dstIp = buffer.Skip(4).Take(4).ToArray();

                var tailBuffer = buffer.Skip(8);
                var endUserIdx = tailBuffer.ToList().IndexOf(0x0) + 1;
                if (-1 == endUserIdx)
                {
                    ServerComms.LogError($"User id is invalid rejecting connection request");
                    return(Socks4ClientHeader.Socks4ClientHeaderStatus.REQUEST_REJECTED_OR_FAILED);
                }
                var userId = UTF8Encoding.UTF8.GetString(tailBuffer.Take(endUserIdx).ToArray());

                //Check if SOCKS 4a and domain name specified
                //If the domain name is to follow the IP will be in the format 0.0.0.x
                if (0 == dstIp[0] && 0 == dstIp[1] && 0 == dstIp[2] && 0 != dstIp[3])
                {
                    var endHostIdx = tailBuffer.Skip(endUserIdx).ToList().IndexOf(0x0);
                    var arrayHost  = tailBuffer.Skip(endUserIdx).Take(endHostIdx).ToArray();
                    if (arrayHost.Length == 0)
                    {
                        ServerComms.LogError($"Host name is empty rejecting connection request");
                        return(Socks4ClientHeader.Socks4ClientHeaderStatus.REQUEST_REJECTED_OR_FAILED);
                    }
                    var dnsHost = UTF8Encoding.UTF8.GetString(arrayHost);
                    if (UriHostNameType.Unknown == Uri.CheckHostName(dnsHost))
                    {
                        ServerComms.LogError($"Host name {dnsHost} is invalid rejecting connection request");
                        return(Socks4ClientHeader.Socks4ClientHeaderStatus.REQUEST_REJECTED_OR_FAILED);
                    }
                    _targetHost = dnsHost;
                }
                else
                {
                    _targetHost = new IPAddress(BitConverter.ToUInt32(dstIp, 0)).ToString();
                }

                ServerComms.LogMessage($"SOCKS Request to open {_targetHost}:{_targetPort}");
                status         = "opening";
                LastUpdateTime = DateTime.Now;

                _targetId = SocketComms.CreateNewConnectionTarget(_targetHost, _targetPort);
                var thisptr = this;
                if (null == thisptr)
                {
                    ServerComms.LogError("This pointer is NULL something wrong here");
                }

                mapTargetIdToSocksInstance.Add(_targetId, thisptr);

                if (_waitOnConnect)
                {
                    SocksTimeout.WaitOne(SOCKSCONNECTIONTOOPENTIMEOUT);
                    if (!_open)
                    {
                        return(Socks4ClientHeader.Socks4ClientHeaderStatus.REQUEST_REJECTED_OR_FAILED);
                    }
                }
            }
            else
            {
                return(Socks4ClientHeader.Socks4ClientHeaderStatus.REQUEST_REJECTED_OR_FAILED);
            }

            ServerComms.LogMessage($"Opened SOCKS port {_targetHost}:{_targetPort} targetid {_targetId}");
            return(Socks4ClientHeader.Socks4ClientHeaderStatus.REQUEST_GRANTED);
        }
 private UInt16 ReadUInt16()
 {
     m_position += 2;
     return BitConverter.ToUInt16(m_byteArray, m_position - 2);
 }
Exemplo n.º 5
0
 /// <summary>
 /// Takes the first 2 bytes of a commit ID (i.e. first 4 characters of its hex-encoded SHA)
 /// and returns them as an 16-bit unsigned integer.
 /// </summary>
 /// <param name="commit">The commit to identify with an integer.</param>
 /// <returns>The unsigned integer which identifies a commit.</returns>
 public static ushort GetTruncatedCommitIdAsUInt16(this Commit commit)
 {
     Requires.NotNull(commit, nameof(commit));
     return(BitConverter.ToUInt16(commit.Id.RawId, 0));
 }
Exemplo n.º 6
0
 public ushort ReadUShort()
 {
     this.CheckCompressedRead();
     byte[] value = this.ReverseOrder(this.ReadBytes(2));
     return(BitConverter.ToUInt16(value, 0));
 }
Exemplo n.º 7
0
 public UInt16 ReadUInt16()
 {
     _pos += 2;
     return(BitConverter.ToUInt16(_buffer, _pos - 2));
 }
Exemplo n.º 8
0
        public void DecodeFromStream(Stream ms)
        {            
            byte lvByte  = (byte)ms.ReadByte();
            byte[] rawByte = null;
            MsgPack msgPack = null;
            int len = 0;
            int i = 0;
            
            if (lvByte <= 0x7F)
            {   //positive fixint	0xxxxxxx	0x00 - 0x7f
                SetAsInteger(lvByte);
            }else if ((lvByte >= 0x80) && (lvByte <= 0x8F))
            {
                //fixmap	1000xxxx	0x80 - 0x8f
                this.Clear();
                this.valueType = MsgPackType.Map;
                len = lvByte - 0x80;
                for (i=0; i<len;i++)
                {
                    msgPack = InnerAdd();
                    msgPack.SetName(ReadTools.ReadString(ms));                    
                    msgPack.DecodeFromStream(ms);
                }
            }
            else if ((lvByte >= 0x90) && (lvByte <= 0x9F))  //fixarray	1001xxxx	0x90 - 0x9f
            {
                //fixmap	1000xxxx	0x80 - 0x8f
                this.Clear();
                this.valueType = MsgPackType.Array;
                len = lvByte - 0x90;
                for (i = 0; i < len; i++)
                {
                    msgPack = InnerAdd();
                    msgPack.DecodeFromStream(ms);
                }
            }
            else if ((lvByte >= 0xA0) && (lvByte <= 0xBF))  // fixstr	101xxxxx	0xa0 - 0xbf
            {
                len = lvByte - 0xA0;
                SetAsString(ReadTools.ReadString(ms, len));
            }
            else if ((lvByte >= 0xE0) && (lvByte <= 0xFF))
            {   /// -1..-32
                //  negative fixnum stores 5-bit negative integer
                //  +--------+
                //  |111YYYYY|
                //  +--------+                
                SetAsInteger((sbyte)lvByte);
            }
            else if (lvByte == 0xC0)
            {
                SetAsNull();
            }
            else if (lvByte == 0xC1)
            {
                throw new Exception("(never used) type $c1");
            }
            else if (lvByte == 0xC2)
            {
                SetAsBoolean(false);
            }
            else if (lvByte == 0xC3)
            {
                SetAsBoolean(true);
            }
            else if (lvByte == 0xC4)
            {  // max 255
                len = ms.ReadByte();
                rawByte = new byte[len];
                ms.Read(rawByte, 0, len);
                SetAsBytes(rawByte);
            }
            else if (lvByte == 0xC5)
            {  // max 65535                
                rawByte = new byte[2];
                ms.Read(rawByte, 0, 2);
                rawByte = BytesTools.SwapBytes(rawByte);
                len = BitConverter.ToInt16(rawByte, 0);

                // read binary
                rawByte = new byte[len];
                ms.Read(rawByte, 0, len);
                SetAsBytes(rawByte);
            }
            else if (lvByte == 0xC6)
            {  // binary max: 2^32-1                
                rawByte = new byte[4];
                ms.Read(rawByte, 0, 4);
                rawByte = BytesTools.SwapBytes(rawByte);
                len = BitConverter.ToInt32(rawByte, 0);

                // read binary
                rawByte = new byte[len];
                ms.Read(rawByte, 0, len);
                SetAsBytes(rawByte);
            }
            else if ((lvByte == 0xC7) || (lvByte == 0xC8) || (lvByte == 0xC9))
            {
                throw new Exception("(ext8,ext16,ex32) type $c7,$c8,$c9");
            }
            else if (lvByte == 0xCA)
            {  // float 32              
                rawByte = new byte[4];
                ms.Read(rawByte, 0, 4);
                rawByte = BytesTools.SwapBytes(rawByte);
                
                SetAsSingle(BitConverter.ToSingle(rawByte, 0));
            }
            else if (lvByte == 0xCB)
            {  // float 64              
                rawByte = new byte[8];
                ms.Read(rawByte, 0, 8);
                rawByte = BytesTools.SwapBytes(rawByte);
                SetAsFloat(BitConverter.ToDouble(rawByte, 0));
            }
            else if (lvByte == 0xCC)
            {  // uint8   
                //      uint 8 stores a 8-bit unsigned integer
                //      +--------+--------+
                //      |  0xcc  |ZZZZZZZZ|
                //      +--------+--------+
                lvByte =(byte)ms.ReadByte();
                SetAsInteger(lvByte);
            }
            else if (lvByte == 0xCD)
            {  // uint16      
                //    uint 16 stores a 16-bit big-endian unsigned integer
                //    +--------+--------+--------+
                //    |  0xcd  |ZZZZZZZZ|ZZZZZZZZ|
                //    +--------+--------+--------+
                rawByte = new byte[2];
                ms.Read(rawByte, 0, 2);
                rawByte = BytesTools.SwapBytes(rawByte);
                SetAsInteger(BitConverter.ToUInt16(rawByte, 0));
            }
            else if (lvByte == 0xCE)
            {      
                //  uint 32 stores a 32-bit big-endian unsigned integer
                //  +--------+--------+--------+--------+--------+
                //  |  0xce  |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ
                //  +--------+--------+--------+--------+--------+
                rawByte = new byte[4];
                ms.Read(rawByte, 0, 4);
                rawByte = BytesTools.SwapBytes(rawByte);
                SetAsInteger(BitConverter.ToUInt32(rawByte, 0));
            }
            else if (lvByte == 0xCF)
            {
                //  uint 64 stores a 64-bit big-endian unsigned integer
                //  +--------+--------+--------+--------+--------+--------+--------+--------+--------+
                //  |  0xcf  |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|
                //  +--------+--------+--------+--------+--------+--------+--------+--------+--------+
                rawByte = new byte[8];
                ms.Read(rawByte, 0, 8);
                rawByte = BytesTools.SwapBytes(rawByte);
                SetAsUInt64(BitConverter.ToUInt64(rawByte, 0));
            }
            else if (lvByte == 0xDC)
            {
                //      +--------+--------+--------+~~~~~~~~~~~~~~~~~+
                //      |  0xdc  |YYYYYYYY|YYYYYYYY|    N objects    |
                //      +--------+--------+--------+~~~~~~~~~~~~~~~~~+
                rawByte = new byte[2];
                ms.Read(rawByte, 0, 2);
                rawByte = BytesTools.SwapBytes(rawByte);
                len = BitConverter.ToInt16(rawByte, 0);

                this.Clear();
                this.valueType = MsgPackType.Array;
                for (i = 0; i < len; i++)
                {
                    msgPack = InnerAdd();
                    msgPack.DecodeFromStream(ms);
                }
            }
            else if (lvByte == 0xDD)
            {
                //  +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
                //  |  0xdd  |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|    N objects    |
                //  +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
                rawByte = new byte[4];
                ms.Read(rawByte, 0, 4);
                rawByte = BytesTools.SwapBytes(rawByte);
                len = BitConverter.ToInt16(rawByte, 0);

                this.Clear();
                this.valueType = MsgPackType.Array;
                for (i = 0; i < len; i++)
                {
                    msgPack = InnerAdd();
                    msgPack.DecodeFromStream(ms);
                }
            }
            else if (lvByte == 0xD9)
            {
                //  str 8 stores a byte array whose length is upto (2^8)-1 bytes:
                //  +--------+--------+========+
                //  |  0xd9  |YYYYYYYY|  data  |
                //  +--------+--------+========+
                SetAsString(ReadTools.ReadString(lvByte, ms));
            }
            else if (lvByte == 0xDE)
            {
                //    +--------+--------+--------+~~~~~~~~~~~~~~~~~+
                //    |  0xde  |YYYYYYYY|YYYYYYYY|   N*2 objects   |
                //    +--------+--------+--------+~~~~~~~~~~~~~~~~~+
                rawByte = new byte[2];
                ms.Read(rawByte, 0, 2);
                rawByte = BytesTools.SwapBytes(rawByte);
                len = BitConverter.ToUInt16(rawByte, 0);

                this.Clear();
                this.valueType = MsgPackType.Map;
                for (i = 0; i < len; i++)
                {
                    msgPack = InnerAdd();
                    msgPack.SetName(ReadTools.ReadString(ms));
                    msgPack.DecodeFromStream(ms);
                }
            }
            else if (lvByte == 0xDE)
            {
                //    +--------+--------+--------+~~~~~~~~~~~~~~~~~+
                //    |  0xde  |YYYYYYYY|YYYYYYYY|   N*2 objects   |
                //    +--------+--------+--------+~~~~~~~~~~~~~~~~~+
                rawByte = new byte[2];
                ms.Read(rawByte, 0, 2);
                rawByte = BytesTools.SwapBytes(rawByte);
                len = BitConverter.ToInt16(rawByte, 0);

                this.Clear();
                this.valueType = MsgPackType.Map;
                for (i = 0; i < len; i++)
                {
                    msgPack = InnerAdd();
                    msgPack.SetName(ReadTools.ReadString(ms));
                    msgPack.DecodeFromStream(ms);
                }
            }
            else if (lvByte == 0xDF)
            {
                //    +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
                //    |  0xdf  |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|   N*2 objects   |
                //    +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
                rawByte = new byte[4];
                ms.Read(rawByte, 0, 4);
                rawByte = BytesTools.SwapBytes(rawByte);
                len = BitConverter.ToInt32(rawByte, 0);

                this.Clear();
                this.valueType = MsgPackType.Map;
                for (i = 0; i < len; i++)
                {
                    msgPack = InnerAdd();
                    msgPack.SetName(ReadTools.ReadString(ms));
                    msgPack.DecodeFromStream(ms);
                }
            }
            else if (lvByte == 0xDA)
            {
                //      str 16 stores a byte array whose length is upto (2^16)-1 bytes:
                //      +--------+--------+--------+========+
                //      |  0xda  |ZZZZZZZZ|ZZZZZZZZ|  data  |
                //      +--------+--------+--------+========+
                SetAsString(ReadTools.ReadString(lvByte, ms));
            }
            else if (lvByte == 0xDB)
            {
                //  str 32 stores a byte array whose length is upto (2^32)-1 bytes:
                //  +--------+--------+--------+--------+--------+========+
                //  |  0xdb  |AAAAAAAA|AAAAAAAA|AAAAAAAA|AAAAAAAA|  data  |
                //  +--------+--------+--------+--------+--------+========+
                SetAsString(ReadTools.ReadString(lvByte, ms));
            }
            else if (lvByte == 0xD0)
            {
                //      int 8 stores a 8-bit signed integer
                //      +--------+--------+
                //      |  0xd0  |ZZZZZZZZ|
                //      +--------+--------+
                SetAsInteger((sbyte)ms.ReadByte());
            }
            else if (lvByte == 0xD1)
            {
                //    int 16 stores a 16-bit big-endian signed integer
                //    +--------+--------+--------+
                //    |  0xd1  |ZZZZZZZZ|ZZZZZZZZ|
                //    +--------+--------+--------+
                rawByte = new byte[2];
                ms.Read(rawByte, 0, 2);
                rawByte = BytesTools.SwapBytes(rawByte);
                SetAsInteger(BitConverter.ToInt16(rawByte, 0));
            }
            else if (lvByte == 0xD2)
            {
                //  int 32 stores a 32-bit big-endian signed integer
                //  +--------+--------+--------+--------+--------+
                //  |  0xd2  |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|
                //  +--------+--------+--------+--------+--------+
                rawByte = new byte[4];
                ms.Read(rawByte, 0, 4);
                rawByte = BytesTools.SwapBytes(rawByte);
                SetAsInteger(BitConverter.ToInt32(rawByte, 0));
            }
            else if (lvByte == 0xD3)
            {
                //  int 64 stores a 64-bit big-endian signed integer
                //  +--------+--------+--------+--------+--------+--------+--------+--------+--------+
                //  |  0xd3  |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|
                //  +--------+--------+--------+--------+--------+--------+--------+--------+--------+
                rawByte = new byte[8];
                ms.Read(rawByte, 0, 8);
                rawByte = BytesTools.SwapBytes(rawByte);
                SetAsInteger(BitConverter.ToInt64(rawByte, 0));
            }    
        }
Exemplo n.º 9
0
        /// <summary>Reads a <see cref="ushort"/> from the address in the remote process.</summary>
        /// <param name="address">The address to read from.</param>
        /// <returns>The data read as <see cref="ushort"/> or 0 if the read fails.</returns>
        public ushort ReadRemoteUInt16(IntPtr address)
        {
            var data = ReadRemoteMemory(address, sizeof(ushort));

            return(BitConverter.ToUInt16(data, 0));
        }
Exemplo n.º 10
0
        private Image getWCPreviewImage(byte[] data)
        {
            Image img;
            WC6   wc = new WC6(data);

            if (wc.IsPokémon)
            {
                img = PKX.getSprite(wc.Species, wc.Form, wc.Gender, wc.HeldItem, wc.IsEgg, wc.PIDType == 2);
            }
            else if (wc.IsItem)
            {
                img = (Image)(Properties.Resources.ResourceManager.GetObject("item_" + BitConverter.ToUInt16(data, 0x68)) ?? Properties.Resources.unknown);
            }
            else
            {
                img = Properties.Resources.unknown;
            }

            if (wc.GiftUsed)
            {
                img = Util.LayerImage(new Bitmap(img.Width, img.Height), img, 0, 0, 0.3);
            }
            return(img);
        }
    public void TestToUInt16() {
      UInt16 expected = BitConverter.ToUInt16(_bytes, 0);
      UInt16 actual = BitConverterNonAlloc.ToUInt16(_bytes, 0);

      Assert.That(actual, Is.EqualTo(expected));
    }
Exemplo n.º 12
0
        private void tabMain_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            // Check for multiple wondercards
            int ctr = currentSlot;

            if (Directory.Exists(files[0]))
            {
                files = Directory.GetFiles(files[0], "*", SearchOption.AllDirectories);
            }
            if (files.Length == 1 && !Directory.Exists(files[0]))
            {
                string path = files[0]; // open first D&D
                long   len  = new FileInfo(path).Length;
                if (len != WC6.Size && len != WC6.SizeFull)
                {
                    Util.Error("File is not a Wonder Card:", path);
                    return;
                }
                byte[] newwc6 = File.ReadAllBytes(path);
                if (newwc6.Length == WC6.SizeFull)
                {
                    newwc6 = newwc6.Skip(WC6.SizeFull - WC6.Size).ToArray();
                }
                Array.Copy(newwc6, wondercard_data, newwc6.Length);
                loadwcdata();
                return;
            }

            if (DialogResult.Yes != Util.Prompt(MessageBoxButtons.YesNo, $"Try to load {files.Length} Wonder Cards starting at Card {ctr + 1}?"))
            {
                return;
            }

            foreach (string file in files)
            {
                long len = new FileInfo(file).Length;
                if (len != WC6.Size && len != WC6.SizeFull)
                {
                    Util.Error("File is not a Wonder Card:", file); continue;
                }

                // Load in WC
                byte[] newwc6 = File.ReadAllBytes(file);

                if (newwc6.Length == WC6.SizeFull)
                {
                    newwc6 = newwc6.Skip(WC6.SizeFull - WC6.Size).ToArray();
                }
                if (checkSpecialWonderCard(newwc6))
                {
                    newwc6.CopyTo(sav, Main.SAV.WondercardData + WC6.Size * ctr++);
                    setCardID(BitConverter.ToUInt16(newwc6, 0));
                }
                if (ctr >= 24)
                {
                    break;
                }
            }
            populateWClist();
        }
 public static ushort GetWord(byte[] data, ref int pos)
 {
     pos += 2;
     return(BitConverter.ToUInt16(data, pos - 2));
 }
Exemplo n.º 14
0
        /// <summary>
        /// This will get the value for a basic data type in this data
        /// </summary>
        /// <param name="type">The type to convert the bytes for</typeparam>
        /// <param name="start">The byte start index to read from</param>
        /// <returns>The value of the object</returns>
        public object GetBasicType(Type type, int start, bool moveIndex = false)
        {
            if (type == typeof(sbyte))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(sbyte));
                }

                return(byteArr[start]);
            }
            else if (type == typeof(byte))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(byte));
                }

                return(byteArr[start]);
            }
            else if (type == typeof(char))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(char));
                }

                return(byteArr[start]);
            }
            else if (type == typeof(short))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(short));
                }

                return(BitConverter.ToInt16(byteArr, start));
            }
            else if (type == typeof(ushort))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(ushort));
                }

                return(BitConverter.ToUInt16(byteArr, start));
            }
            else if (type == typeof(bool))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(bool));
                }

                return(BitConverter.ToBoolean(byteArr, start));
            }
            else if (type == typeof(int))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(int));
                }

                return(BitConverter.ToInt32(byteArr, start));
            }
            else if (type == typeof(uint))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(uint));
                }

                return(BitConverter.ToUInt32(byteArr, start));
            }
            else if (type == typeof(float))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(float));
                }

                return(BitConverter.ToSingle(byteArr, start));
            }
            else if (type == typeof(long))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(long));
                }

                return(BitConverter.ToInt64(byteArr, start));
            }
            else if (type == typeof(ulong))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(ulong));
                }

                return(BitConverter.ToUInt64(byteArr, start));
            }
            else if (type == typeof(double))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(double));
                }

                return(BitConverter.ToDouble(byteArr, start));
            }
            else if (type == typeof(string))
            {
                return(GetString(start, moveIndex));
            }
            else if (type == typeof(Vector))
            {
                return(GetVector(start, moveIndex));
            }
            else if (type.IsArray)
            {
                int  rank       = type.GetArrayRank();
                Type targetType = type.GetElementType();

                //int startingIndex = StartIndex();
                MoveStartIndex(sizeof(int));

                if (rank > 4)
                {
                    throw new Exception("Currently the system only supports up to 4 dimensions in an array");
                }

                int i, j, k, l, x, y, z, w;
                switch (rank)
                {
                case 1:
                    x = GetBasicType <int>(StartIndex(), true);
                    object[] one = new object[x];
                    for (i = 0; i < x; i++)
                    {
                        one[i] = GetBasicType(targetType, StartIndex(), true);
                    }
                    return(one);

                case 2:
                    x             = GetBasicType <int>(StartIndex(), true);
                    y             = GetBasicType <int>(StartIndex(), true);
                    object[,] two = new object[x, y];
                    for (i = 0; i < x; i++)
                    {
                        for (j = 0; j < y; j++)
                        {
                            two[i, j] = GetBasicType(targetType, StartIndex(), true);
                        }
                    }
                    return(two);

                case 3:
                    x = GetBasicType <int>(StartIndex(), true);
                    y = GetBasicType <int>(StartIndex(), true);
                    z = GetBasicType <int>(StartIndex(), true);
                    object[,,] three = new object[x, y, z];
                    for (i = 0; i < x; i++)
                    {
                        for (j = 0; j < y; j++)
                        {
                            for (k = 0; k < z; k++)
                            {
                                three[i, j, k] = GetBasicType(targetType, StartIndex(), true);
                            }
                        }
                    }
                    return(three);

                case 4:
                    x = GetBasicType <int>(StartIndex(), true);
                    y = GetBasicType <int>(StartIndex(), true);
                    z = GetBasicType <int>(StartIndex(), true);
                    w = GetBasicType <int>(StartIndex(), true);
                    object[,,,] four = new object[x, y, z, w];
                    for (i = 0; i < x; i++)
                    {
                        for (j = 0; j < y; j++)
                        {
                            for (k = 0; k < z; k++)
                            {
                                for (l = 0; l < w; l++)
                                {
                                    four[i, j, k, l] = GetBasicType(targetType, StartIndex(), true);
                                }
                            }
                        }
                    }
                    return(four);
                }

                throw new Exception("Deserialize case not found for this array");
            }
#if WINDOWS_UWP
            else if (type == typeof(Enum))
#else
            else if (type.IsEnum)
#endif
            { return(GetBasicType(Enum.GetUnderlyingType(type), start, moveIndex)); }
            else
            {
                throw new Exception("The type " + type.ToString() + " is gettable from basic type, maybe try one of the other getters?");
            }
        }
Exemplo n.º 15
0
 public static UInt16 ReadU16BE(this Stream stream)
 {
     byte[] data = new byte[2];
     stream.Read(data, 0, 2);
     return(BitConverter.ToUInt16(data, 0).Swap());
 }
Exemplo n.º 16
0
 public ushort Opcode()
 {
     return(BitConverter.ToUInt16(this.Bytes, OpcodeIndex));
 }
Exemplo n.º 17
0
        public static ushort UInt16Converter(byte[] hash)
        {
            CorrectEndianness(hash, sizeof(ushort));

            return(BitConverter.ToUInt16(hash, 0));
        }
Exemplo n.º 18
0
        private void OnNetworkMessage(IntPtr dataPtr, ushort opCode, uint sourceActorId, uint targetActorId, NetworkMessageDirection direction)
        {
            if (direction != NetworkMessageDirection.ZoneDown)
            {
                return;
            }

            if (!this.dalamud.Data.IsDataReady)
            {
                return;
            }

            if (opCode == this.dalamud.Data.ServerOpCodes["CfNotifyPop"])
            {
                var data = new byte[64];
                Marshal.Copy(dataPtr, data, 0, 64);

                var notifyType = data[0];
                var contentFinderConditionId = BitConverter.ToUInt16(data, 0x14);

                if (notifyType != 3)
                {
                    return;
                }

                var contentFinderCondition = this.dalamud.Data.GetExcelSheet <ContentFinderCondition>().GetRow(contentFinderConditionId);

                if (contentFinderCondition == null)
                {
                    Log.Error("CFC key {0} not in lumina data.", contentFinderConditionId);
                    return;
                }

                var cfcName = contentFinderCondition.Name.ToString();
                if (string.IsNullOrEmpty(contentFinderCondition.Name))
                {
                    cfcName = "Duty Roulette";
                    contentFinderCondition.Image = 112324;
                }

                if (this.dalamud.Configuration.DutyFinderTaskbarFlash && !NativeFunctions.ApplicationIsActivated())
                {
                    var flashInfo = new NativeFunctions.FLASHWINFO
                    {
                        cbSize    = (uint)Marshal.SizeOf <NativeFunctions.FLASHWINFO>(),
                        uCount    = uint.MaxValue,
                        dwTimeout = 0,
                        dwFlags   = NativeFunctions.FlashWindow.FLASHW_ALL |
                                    NativeFunctions.FlashWindow.FLASHW_TIMERNOFG,
                        hwnd = Process.GetCurrentProcess().MainWindowHandle
                    };
                    NativeFunctions.FlashWindowEx(ref flashInfo);
                }

                Task.Run(() => {
                    if (this.dalamud.Configuration.DutyFinderChatMessage)
                    {
                        this.dalamud.Framework.Gui.Chat.Print("Duty pop: " + cfcName);
                    }

                    CfPop?.Invoke(this, contentFinderCondition);
                });

                return;
            }

            if (!this.optOutMbUploads)
            {
                if (opCode == this.dalamud.Data.ServerOpCodes["MarketBoardItemRequestStart"])
                {
                    var catalogId = (uint)Marshal.ReadInt32(dataPtr);
                    var amount    = Marshal.ReadByte(dataPtr + 0xB);

                    this.marketBoardRequests.Add(new MarketBoardItemRequest {
                        CatalogId      = catalogId,
                        AmountToArrive = amount,
                        Listings       = new List <MarketBoardCurrentOfferings.MarketBoardItemListing>(),
                        History        = new List <MarketBoardHistory.MarketBoardHistoryListing>()
                    });

                    Log.Verbose($"NEW MB REQUEST START: item#{catalogId} amount#{amount}");
                    return;
                }

                if (opCode == this.dalamud.Data.ServerOpCodes["MarketBoardOfferings"])
                {
                    var listing = MarketBoardCurrentOfferings.Read(dataPtr);

                    var request =
                        this.marketBoardRequests.LastOrDefault(
                            r => r.CatalogId == listing.ItemListings[0].CatalogId && !r.IsDone);

                    if (request == null)
                    {
                        Log.Error(
                            $"Market Board data arrived without a corresponding request: item#{listing.ItemListings[0].CatalogId}");
                        return;
                    }

                    if (request.Listings.Count + listing.ItemListings.Count > request.AmountToArrive)
                    {
                        Log.Error(
                            $"Too many Market Board listings received for request: {request.Listings.Count + listing.ItemListings.Count} > {request.AmountToArrive} item#{listing.ItemListings[0].CatalogId}");
                        return;
                    }

                    if (request.ListingsRequestId != -1 && request.ListingsRequestId != listing.RequestId)
                    {
                        Log.Error(
                            $"Non-matching RequestIds for Market Board data request: {request.ListingsRequestId}, {listing.RequestId}");
                        return;
                    }

                    if (request.ListingsRequestId == -1 && request.Listings.Count > 0)
                    {
                        Log.Error(
                            $"Market Board data request sequence break: {request.ListingsRequestId}, {request.Listings.Count}");
                        return;
                    }

                    if (request.ListingsRequestId == -1)
                    {
                        request.ListingsRequestId = listing.RequestId;
                        Log.Verbose($"First Market Board packet in sequence: {listing.RequestId}");
                    }

                    request.Listings.AddRange(listing.ItemListings);

                    Log.Verbose("Added {0} ItemListings to request#{1}, now {2}/{3}, item#{4}",
                                listing.ItemListings.Count, request.ListingsRequestId, request.Listings.Count,
                                request.AmountToArrive, request.CatalogId);

                    if (request.IsDone)
                    {
                        Log.Verbose("Market Board request finished, starting upload: request#{0} item#{1} amount#{2}",
                                    request.ListingsRequestId, request.CatalogId, request.AmountToArrive);
                        try {
                            Task.Run(() => this.uploader.Upload(request));
                        } catch (Exception ex) {
                            Log.Error(ex, "Market Board data upload failed.");
                        }
                    }

                    return;
                }

                if (opCode == this.dalamud.Data.ServerOpCodes["MarketBoardHistory"])
                {
                    var listing = MarketBoardHistory.Read(dataPtr);

                    var request = this.marketBoardRequests.LastOrDefault(r => r.CatalogId == listing.CatalogId);

                    if (request == null)
                    {
                        Log.Error(
                            $"Market Board data arrived without a corresponding request: item#{listing.CatalogId}");
                        return;
                    }

                    if (request.ListingsRequestId != -1)
                    {
                        Log.Error(
                            $"Market Board data history sequence break: {request.ListingsRequestId}, {request.Listings.Count}");
                        return;
                    }

                    request.History.AddRange(listing.HistoryListings);

                    Log.Verbose("Added history for item#{0}", listing.CatalogId);

                    if (request.AmountToArrive == 0)
                    {
                        Log.Verbose("Request had 0 amount, uploading now");

                        try
                        {
                            Task.Run(() => this.uploader.Upload(request));
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex, "Market Board data upload failed.");
                        }
                    }
                }

                if (opCode == this.dalamud.Data.ServerOpCodes["MarketTaxRates"])
                {
                    var taxes = MarketTaxRates.Read(dataPtr);

                    Log.Verbose("MarketTaxRates: limsa#{0} grid#{1} uldah#{2} ish#{3} kugane#{4} cr#{5}",
                                taxes.LimsaLominsaTax, taxes.GridaniaTax, taxes.UldahTax, taxes.IshgardTax, taxes.KuganeTax, taxes.CrystariumTax);
                    try
                    {
                        Task.Run(() => this.uploader.UploadTax(taxes));
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Market Board data upload failed.");
                    }
                }
            }
        }
Exemplo n.º 19
0
        public void WaitForCommands()
        {
            string input = null;

            this.Start();
            LoadScripts();
            InitGameData();
            while (!IsConsoleShuttingDown)
            {
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.Write("\n[{Realm World Server}] ");
                Console.ResetColor();
                input = Console.ReadLine();
                string[] args = input.Split(' ');



                switch (args[0].ToLower())
                {
                case "sam":
                {
                    int    Index     = 0;
                    byte[] Data      = new byte[] { 0x01, 0x02 };
                    UInt16 PacketLen = (UInt16)(Data[Index + 1] << 8 | Data[Index + 0]);

                    Console.WriteLine(PacketLen.ToString());
                }
                break;

                case "r":
                {
                    string file = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "npcappear.txt");
                    string data = File.ReadAllText(file);
                    data = RemoveWhitespace(data);
                    Console.WriteLine(data);
                }
                break;

                case "1":
                {
                    GameMobile m = new GameMobile();

                    m.GraphicID     = 2204;
                    m.GameID        = ServerGlobals.GetNextAvailableID();
                    m.Width         = 100;
                    m.Height        = 100;
                    m.CurrentHealth = 12345;
                    m.MaximumHealth = 12399;

                    m.Location = new GameLocation(4056,

                                                  110, 110,
                                                  0);

                    PacketWriter add = new PacketWriter(0x2A);
                    add.WriteUInt32(2041);
                    add.WriteUInt32(0);
                    add.WriteInt32(-1);
                    add.WriteUInt32(4056);

                    add.WriteByte(0x40);



                    PacketWriter wrap = new PacketWriter();
                    wrap.WriteShort((short)m.ToByteArray().Length);
                    wrap.WriteUInt32(m.GameID);
                    wrap.WriteBytes(m.ToByteArray());

                    add.WriteBytes(wrap.GetRawPacket());

                    byte[] packet = add.ToArray();
                    //Player.Socket.Send(ref packet);

                    string fileLocation1 = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "bptest.txt");
                    File.WriteAllText(fileLocation1, BitConverter.ToString(packet));
                    Console.WriteLine("Sent Data");
                }
                break;

                case "pass":
                {
                    // we gonna hash passwords here man !!
                    string password = string.Empty;

                    if (args.Length >= 2)
                    {
                        // get the pass
                        password = args[1];
                        string hash = RealmOffline.Accounts.PasswordHash.CreateHash(password);
                        bool   back = RealmOffline.Accounts.PasswordHash.ValidatePassword(password, hash);
                        Console.WriteLine("We got password ({0}) and hash ({1}), they {2} match.", password, hash,
                                          back ? "do":" do not");
                    }
                }
                break;

                case "/mob":
                {
                    if (args.Length >= 2)
                    {
                        short id = 0;
                        if (short.TryParse(args[1], out id))
                        {
                            MobileType type = MobileType.None;
                            string     name = BaseMobile.MobNameFromID(id, out type);
                            Console.WriteLine("We found {0} for MobID {1}, its type is {2}",
                                              name, id, type);
                        }
                    }
                }
                break;

                case "/sm":
                {
                    if (args.Length >= 3)
                    {
                        //1 = topic 2 on = message
                        string topic = input.Split('|').First();
                        string msg   = input.Split('|').Last();
                        Console.WriteLine("Topic ({0}) Message ({1})", topic, msg);
                    }
                }
                break;

                case "terd":
                {
                    BaseMobile.Init();
                    string[] m = BaseMobile.NonHumanoid.Select(x => x.Value).ToArray();
                    foreach (string c in m)
                    {
                        Console.WriteLine(c);
                    }
                }
                break;

                case "fight":
                {
                    // We want stats 2 stats 2 skills for attack
                    //1 = str 2 = dex 3 = CS 4 = wepskill
                    if (args.Length >= 5)
                    {
                        int str = 0;
                        int dex = 0;
                        int cs  = 0;
                        int wep = 0;
                        if (int.TryParse(args[1], out str) &&
                            int.TryParse(args[2], out dex) &&
                            int.TryParse(args[3], out cs) &&
                            int.TryParse(args[4], out wep))
                        {
                            Console.WriteLine("We got STR:({0}) DEX:({1}) CS:({2}) Wep:({3})",
                                              str, dex, cs, wep);

                            // Lets formulate a chance
                            int[] attacker = { str, dex, cs, wep };
                            int[] oppn     = { 12, 12, 5, 5 };

                            // int hitpoints = 3000; // both have 3k hp
                            int aper = attacker.Sum();
                            int oper = oppn.Sum();

                            Console.WriteLine("We start with {0}% for Attacker and {1}% for opponent.", aper, oper);
                        }
                    }
                }
                break;

                case "id":
                {
                    if (args.Length == 2)
                    {
                        short id = 0;
                        if (short.TryParse(args[1], out id))
                        {
                            bool vali = Mob.IsValidID(id);
                            Console.WriteLine("{0} {1} a valid id.", id, vali ? "is" : "is not");
                        }
                    }
                }
                break;

                case "ts":
                {
                    byte[] t = new byte[] { 0x21, 0xFF, 0x00, 0x9C };
                    Array.Reverse(t);
                    double   d  = (double)BitConverter.ToInt32(t, 0);
                    DateTime dt = MagicMail.UnixTimeStampToDateTime(d);
                    Console.WriteLine(dt);
                }
                break;

                    #region Account Creation and Deletion
                case "account":
                {
                    string useage = "[Create an Account]\naccount create username password emailaddress secretword 3 \n" +
                                    "Last value is User Priv's\n" +
                                    "5 = Player, 4 = EventHost 3 = Guide 2 = Moderator 1 = Admin 0 = Owner \n" +
                                    "\n" +
                                    "[Delete an Account]\n" +
                                    "account delete username";
                    string createUseage = "[Create an Account]\naccount create username password emailaddress secretword 3 \n" +
                                          "Last value is User Priv's\n" +
                                          "5 = Player, 4 = EventHost 3 = Guide 2 = Moderator 1 = Admin 0 = Owner \n";
                    string deleteUsage = "[Delete an Account]\n" +
                                         "account delete username";

                    // create or delete
                    if (args.Length > 2)
                    {
                        if (args[1].ToLower() == "create")
                        {
                            if (args[2].ToLower() == "help" || args[2] == string.Empty)
                            {
                                Console.WriteLine(createUseage);
                            }
                            else
                            {
                                string error = string.Empty;
                                if (!MySqlManager.ValidateAccount(args, out error))
                                {
                                    if (error.Trim() != string.Empty)
                                    {
                                        Console.ForegroundColor = ConsoleColor.Red;
                                        Console.WriteLine(error);
                                        Console.ResetColor();
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("Account {0} Created.", args[2]);
                                }
                            }
                        }
                        else if (args[1].ToLower() == "delete")
                        {
                            if (args.Length != 3)
                            {
                                Console.WriteLine(deleteUsage);
                            }
                            else
                            {
                                bool delete = MySqlManager.DeleteUserAccount(args[2].ToLower());
                                if (delete)
                                {
                                    Console.WriteLine("Removed Account {0}.", args[2].ToLower());
                                }
                                else
                                {
                                    Console.WriteLine("Account {0} not found.", args[2].ToLower());
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("create or delete are the only valid options.");
                        }
                    }
                    else
                    {
                        Console.WriteLine(useage);
                    }
                    // Ok this will be the command to create a new account

                    /*
                     * We need
                     * 2: Username
                     * 3: Password
                     * 4: email address
                     * 5: secret word
                     * 6: Priv Level
                     * string string string string int
                     */
                }
                    #endregion
                    break;

                case "spell":
                {
                    List <Account> accts = ServerGlobals.GetAccountsInRoom(1310);
                    Console.WriteLine("Total in room 1310 {0}", accts.Count);
                }
                break;

                case "online":
                {
                    int online = 0;
                    if (ServerGlobals.LoggedInAccounts != null)
                    {
                        online = ServerGlobals.LoggedInAccounts.Count;
                    }
                    Console.WriteLine("Currently {0} accounts online.", online);
                }
                break;

                case "clear":
                    Console.Clear();
                    break;

                case "mem":
                {
                    // Returns the current memory usage
                    Console.WriteLine(MemoryUseDisplay);
                }
                break;

                case "q":
                {
                    TestObject t       = new TestObject();
                    string     fileloc = Path.Combine(ServerGlobals.BaseDirectory, "TestSerialize.xml");

                    SerializedObject.Serialize(t, fileloc);

                    TestObject t1 = SerializedObject.Deserialize <TestObject>(fileloc);
                    Console.WriteLine(t1.ID);
                }
                break;

                case "touint16":
                {
                    if (args.Length == 2)
                    {
                        // should be 4 letters / numbers
                        string toParse = args[1].Trim();
                        // split string in half
                        if (toParse.Length == 4)
                        {
                            string      b1    = toParse.Substring(0, 2);
                            string      b2    = toParse.Substring(2);
                            List <byte> blist = new List <byte>();

                            try
                            {
                                byte a;
                                byte b;
                                a = Byte.Parse(b1, NumberStyles.HexNumber);
                                b = Byte.Parse(b2, NumberStyles.HexNumber);
                                blist.Add(a);
                                blist.Add(b);
                                byte[] f1     = blist.ToArray();
                                ushort result = BitConverter.ToUInt16(f1, 0);
                                Console.WriteLine("UInt16 result of bytes [{0}] [{1}] = {2}",
                                                  BitConverter.ToString(new byte[] { a }), BitConverter.ToString(new byte[] { b }), result);
                            }
                            catch { Console.WriteLine("Bad Parse"); }
                        }
                    }
                }
                break;

                case "toint32":
                {
                    if (args.Length == 2)
                    {
                        // should be 8 letters / numbers
                        string toParse = args[1].Trim();
                        // split string in half
                        if (toParse.Length == 8)
                        {
                            string      b1    = toParse.Substring(0, 2);
                            string      b2    = toParse.Substring(2, 2);
                            string      b3    = toParse.Substring(4, 2);
                            string      b4    = toParse.Substring(6);
                            List <byte> blist = new List <byte>();

                            try
                            {
                                byte a;
                                byte b;
                                byte c;
                                byte d;
                                a = Byte.Parse(b1, NumberStyles.HexNumber);
                                b = Byte.Parse(b2, NumberStyles.HexNumber);
                                c = Byte.Parse(b3, NumberStyles.HexNumber);
                                d = Byte.Parse(b4, NumberStyles.HexNumber);
                                blist.Add(a);
                                blist.Add(b);
                                blist.Add(c);
                                blist.Add(d);
                                byte[] f1 = blist.ToArray();
                                f1.Reverse();
                                Int32 result = BitConverter.ToInt32(f1, 0);
                                Console.WriteLine("Int32 result of bytes [{0}] [{1}] [{2}] [{3}]= {4}",
                                                  BitConverter.ToString(new byte[] { a }), BitConverter.ToString(new byte[] { b }),
                                                  BitConverter.ToString(new byte[] { c }), BitConverter.ToString(new byte[] { d }),
                                                  result);
                            }
                            catch { Console.WriteLine("Bad Parse"); }
                        }
                    }
                }
                break;

                case "touint32":
                {
                    if (args.Length == 2)
                    {
                        // should be 8 letters / numbers
                        string toParse = args[1].Trim();
                        // split string in half
                        if (toParse.Length == 8)
                        {
                            string      b1    = toParse.Substring(0, 2);
                            string      b2    = toParse.Substring(2, 2);
                            string      b3    = toParse.Substring(4, 2);
                            string      b4    = toParse.Substring(6);
                            List <byte> blist = new List <byte>();

                            try
                            {
                                byte a;
                                byte b;
                                byte c;
                                byte d;
                                a = Byte.Parse(b1, NumberStyles.HexNumber);
                                b = Byte.Parse(b2, NumberStyles.HexNumber);
                                c = Byte.Parse(b3, NumberStyles.HexNumber);
                                d = Byte.Parse(b4, NumberStyles.HexNumber);
                                blist.Add(a);
                                blist.Add(b);
                                blist.Add(c);
                                blist.Add(d);
                                byte[] f1 = blist.ToArray();
                                f1.Reverse();
                                UInt32 result = BitConverter.ToUInt32(f1, 0);
                                Console.WriteLine("Int32 result of bytes [{0}] [{1}] [{2}] [{3}]= {4}",
                                                  BitConverter.ToString(new byte[] { a }), BitConverter.ToString(new byte[] { b }),
                                                  BitConverter.ToString(new byte[] { c }), BitConverter.ToString(new byte[] { d }),
                                                  result);
                            }
                            catch { Console.WriteLine("Bad Parse"); }
                        }
                    }
                }
                break;

                case "tobytes32":
                {
                    // the next value is a number
                    if (args.Length == 2)
                    {
                        int value = 0;
                        if (int.TryParse(args[1], out value))
                        {
                            byte[] conv = BitConverter.GetBytes(value);
                            Console.WriteLine(BitConverter.ToString(conv));
                        }
                    }
                }
                break;

                case "m2ushort":
                {
                    // we have 2 bytes space 2 bytes 0 1 2 args or 3 total

                    if (args.Length == 3)
                    {
                        try
                        {
                            string firstushort  = args[1].Trim();
                            string secondushort = args[2].Trim();

                            string      b1    = firstushort.Substring(0, 2);
                            string      b2    = firstushort.Substring(2, 2);
                            string      b3    = secondushort.Substring(0, 2);
                            string      b4    = secondushort.Substring(2, 2);
                            List <byte> blist = new List <byte>();


                            byte a;
                            byte b;
                            byte c;
                            byte d;
                            a = Byte.Parse(b1, NumberStyles.HexNumber);
                            b = Byte.Parse(b2, NumberStyles.HexNumber);
                            c = Byte.Parse(b3, NumberStyles.HexNumber);
                            d = Byte.Parse(b4, NumberStyles.HexNumber);
                            byte[] fArg = { a, b };
                            byte[] sArg = { c, d };
                            ushort vone = BitConverter.ToUInt16(fArg, 0);
                            ushort vtwo = BitConverter.ToUInt16(sArg, 0);
                            Console.WriteLine("We got {0} and {1} for a difference of {2} or {3}",
                                              vone, vtwo, vone - vtwo, vtwo - vone);
                        }
                        catch { Console.WriteLine("Bad Parse"); }
                    }
                }
                break;

                case "bc":
                {
                    if (args.Length > 2)
                    {
                        // get the rest of this string
                        StringBuilder build = new StringBuilder();
                        foreach (string s in args)
                        {
                            build.Append(s + " ");
                        }
                        string   first  = build.ToString().Remove(0, 3);
                        string[] parse2 = first.Split(' ');
                        // whats the color ?
                        int color = -1;
                        if (int.TryParse(parse2[0], out color))
                        {
                            // Fix the last string again then
                            build.Clear();
                            foreach (string s in parse2)
                            {
                                build.Append(s + " ");
                            }
                            string message       = build.ToString().Remove(0, parse2[0].Length + 1);
                            byte[] messagePacket = RealmPacketIO.BuildGossipPacket(color, message, "SERVER");
                            ServerGlobals.SendToAllClients(messagePacket);
                            byte[] messagePacket2 = Packet.ChatPacket(color, 1, message, "SERVER");
                            ServerGlobals.SendToAllClients(messagePacket2);
                            //Console.WriteLine(message);
                        }
                        else
                        {
                            Console.WriteLine("Bad color argument of {0}", parse2[0]);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Usage: bc 10 I want to say hi !!");
                    }
                }
                break;

                case "sta":
                {
                    //string fileLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ServerPacket24Message.txt");
                    byte[] fake0 = RealmPacketIO.ServerMessageType1(
                        "A Topic Test", "A Very Nice Message, we couldnt have much nicer, so dont be a dick!");        //RealmPacketIO.GetByteArrayFromFile(fileLocation);

                    if (args.Length == 2)
                    {
                        if (args[1].ToLower() == "len")
                        {
                            Console.WriteLine("Message Packet Length {0}",
                                              BitConverter.ToString(BitConverter.GetBytes(fake0.Length - 8)));
                        }
                    }
                    else
                    {
                        //ServerPacket24Message.txt

                        ServerGlobals.SendToAllClients(fake0);
                    }
                }
                break;

                case "sta2":
                {
                    // ServerMessagePacket81.txt
                    string fileLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ServerMessagePacket81.txt");
                    byte[] fake0        = RealmPacketIO.ServerMessageType2(
                        "F**k you and da horse you roded in on foo!");        //RealmPacketIO.GetByteArrayFromFile(fileLocation);
                    if (args.Length == 2)
                    {
                        if (args[1].ToLower() == "len")
                        {
                            Console.WriteLine("Message Packet Length {0}",
                                              BitConverter.ToString(BitConverter.GetBytes(fake0.Length - 8)));
                        }
                    }
                    else
                    {
                        // ServerMessagePacket81.txt

                        ServerGlobals.SendToAllClients(fake0);
                    }
                }
                break;

                case "switch":
                {
                    if (ServerGlobals.LoadFromSql)
                    {
                        ServerGlobals.LoadFromSql = false; Console.WriteLine("Loading from CharData.txt File.");
                    }
                    else
                    {
                        ServerGlobals.LoadFromSql = true; Console.WriteLine("Loading from MySql.");
                    }
                }
                break;

                case "croom":
                {
                    // Sends a packet derived from a filename in our debug dir
                    // args[1] is the filename
                    string fileLocation = string.Empty;
                    if (args.Length != 2)
                    {
                        Console.WriteLine("Please supply a filename with extention.");
                    }
                    else
                    {
                        if (args[1].Trim() == "off")
                        {
                            RealmPacketIO.CustomRoomLoad = false;
                            RealmPacketIO.CustomRoomFile = string.Empty;
                        }
                        else
                        {
                            fileLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), args[1].Trim());
                            if (!File.Exists(fileLocation))
                            {
                                Console.WriteLine("Unable to find file {0}", fileLocation);
                            }
                            else
                            {
                                RealmPacketIO.CustomRoomLoad = true;
                                RealmPacketIO.CustomRoomFile = args[1].Trim();
                                Console.WriteLine("CustomFile Atrrib = {0} for file {1}",
                                                  RealmPacketIO.CustomRoomLoad, RealmPacketIO.CustomRoomFile);
                            }
                        }
                    }
                }
                break;

                case "to":
                {
                }
                break;

                case "itempacket":
                {
                    for (int f = 0; f < 2001; f++)
                    {
                        Item i = new Item();
                        i.GraphicID = 1444;
                        i.Color     = 0x69;
                        //uint id = 0;
                        // byte[] r = i.Ser();
                        //byte[] item = i.Serialize(out id);
                        Console.Write("\rItem:{0}.          ", f);
                    }
                }
                break;

                case "send":
                {
                    // Sends a packet derived from a filename in our debug dir
                    // args[1] is the filename
                    string fileLocation = string.Empty;
                    if (args.Length != 2)
                    {
                        Console.WriteLine("Please supply a filename with extention.");
                    }
                    else
                    {
                        fileLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), args[1].Trim());
                        if (!File.Exists(fileLocation))
                        {
                            Console.WriteLine("Unable to find file {0}", fileLocation);
                        }
                        else
                        {
                            byte[] fileToArray = null;
                            try { fileToArray = RealmPacketIO.GetByteArrayFromFile(fileLocation); }
                            catch (Exception ex) { Console.WriteLine(ex.Message); }

                            if (fileToArray != null)
                            {
                                ServerGlobals.SendToAllClients(fileToArray);
                                Console.WriteLine("Sent {0}", fileLocation);
                            }
                        }
                    }
                }
                break;

                case "a":
                {
                }
                break;

                case "x":
                {
                    //byte[] p = RealmPacketIO.Test;
                    // ServerGlobals.SendToAllClients(p);
                }
                break;

                case "w":
                {
                    /*
                     * string fileLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Lookat.txt");
                     * byte[] fake0 = RealmPacketIO.GetByteArrayFromFile(fileLocation);
                     * byte[] len = BitConverter.GetBytes(fake0.Length);
                     * Console.WriteLine(BitConverter.ToString(len));
                     */
                }
                break;

                case "t":
                {
                    // try to get this room
                    Room found = null;
                    if (ScriptResolver.ImportedRooms.TryGetRoom(213, out found))
                    {
                        Console.WriteLine("Found room {0}", 213);
                        Console.WriteLine(BitConverter.ToString(found.GetRoomPacket(3)));
                    }
                }
                break;

                case "tt":
                {
                    // messin wit commands
                    if (ScriptResolver.ImportedCommands.Count == 0)
                    {
                        Console.WriteLine("WTF ?");
                    }
                    else
                    {
                        Console.WriteLine("{0} commands found.", ScriptResolver.ImportedCommands.Count);
                        foreach (Command cmd in ScriptResolver.ImportedCommands)
                        {
                            Console.WriteLine("Command Name {0}", cmd.CommandName);

                            Command[] cmds = ScriptResolver.ImportedCommands.CommandsByPrefix('/');
                            Console.WriteLine("Commands by Prefix returned {0}", cmds.Length);
                        }
                    }
                }
                break;

                case "lmob":
                {
                    string fileLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "mobtest.txt");
                    byte[] fake0        = RealmPacketIO.GetByteArrayFromFile(fileLocation);
                    byte[] len          = BitConverter.GetBytes(fake0.Length);
                    Console.WriteLine(BitConverter.ToString(len));
                }
                break;

                case "mob":
                {
                    string fileLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "mobtest.txt");
                    byte[] fake0        = RealmPacketIO.GetByteArrayFromFile(fileLocation);
                    Console.WriteLine("We have a packet {0} in length.", fake0.Length);
                    ServerGlobals.SendToAllClients(fake0);
                }
                break;

                case "s":
                {
                    string        fileLocation = Path.Combine(ServerGlobals.BaseDirectory, "Test.log");
                    RLog          log          = new RLog(fileLocation);
                    StringBuilder b            = new StringBuilder();
                    for (int i = 2000; i != 0; i--)
                    {
                        b.AppendLine(i.ToString());
                    }
                    log.LogMessage(b.ToString(), MessageType.Warning);
                }
                break;

                case "start":
                {
                    this.Start();
                }
                break;

                case "stop":
                    ThreadMgr.Stop();
                    srv.Stop();
                    break;

                case "exit":
                    this.Stop();
                    break;

                default:
                    Console.WriteLine("No Such Command: " + input + "\r\n");
                    break;
                }
            }
        }
Exemplo n.º 20
0
 /// <inheritdoc />
 public ushort ToUInt16(ReadOnlySpan <byte> value)
 {
     return(BitConverter.ToUInt16(value));
 }
Exemplo n.º 21
0
        /// <summary>
        /// DeSerialization method
        /// </summary>
        /// <param name="data"></param>
        public override void Read(byte[] data)
        {
            /*
             *  The .TAP files contain blocks of tape-saved data. All blocks start with two bytes specifying how many bytes will follow (not counting the two length bytes). Then raw tape data follows, including the flag and checksum bytes. The checksum is the bitwise XOR of all bytes including the flag byte. For example, when you execute the line SAVE "ROM" CODE 0,2 this will result:
             *
             |------ Spectrum-generated data -------|       |---------|
             *
             * 13 00 00 03 52 4f 4d 7x20 02 00 00 00 00 80 f1 04 00 ff f3 af a3
             *
             * ^^^^^...... first block is 19 bytes (17 bytes+flag+checksum)
             *       ^^... flag byte (A reg, 00 for headers, ff for data blocks)
             *          ^^ first byte of header, indicating a code block
             *
             * file name ..^^^^^^^^^^^^^
             * header info ..............^^^^^^^^^^^^^^^^^
             * checksum of header .........................^^
             * length of second block ........................^^^^^
             * flag byte ............................................^^
             * first two bytes of rom .................................^^^^^
             * checksum (checkbittoggle would be a better name!).............^^
             */

            // clear existing tape blocks
            _datacorder.DataBlocks.Clear();

            // convert bytearray to memory stream
            MemoryStream stream = new MemoryStream(data);

            // the first 2 bytes of the TAP file designate the length of the first data block
            // this (I think) should always be 17 bytes (as this is the tape header)
            byte[] blockLengthData = new byte[2];

            // we are now going to stream through the entire file processing a block at a time
            while (stream.Position < stream.Length)
            {
                // read and calculate the length of the block
                stream.Read(blockLengthData, 0, 2);
                int blockSize = BitConverter.ToUInt16(blockLengthData, 0);
                if (blockSize == 0)
                {
                    // block size is 0 - this is probably invalid (but I guess could be EoF in some situations)
                    break;
                }

                // copy the entire block into a new bytearray
                byte[] blockdata = new byte[blockSize];
                stream.Read(blockdata, 0, blockSize);

                // create and populate a new tapedatablock object
                TapeDataBlock tdb = new TapeDataBlock();

                // ascertain the block description
                string description = string.Empty;
                byte   crc         = 0;
                byte   crcValue    = 0;
                byte   crcFile     = 0;
                byte[] programData = new byte[10];

                // calculate block checksum value
                for (int i = 0; i < blockSize; i++)
                {
                    crc ^= blockdata[i];
                    if (i < blockSize - 1)
                    {
                        crcValue = crc;
                    }
                    else
                    {
                        crcFile = blockdata[i];
                    }
                }

                // process the type byte

                /*  (The type is 0,1,2 or 3 for a Program, Number array, Character array or Code file.
                 *  A SCREEN$ file is regarded as a Code file with start address 16384 and length 6912 decimal.
                 *  If the file is a Program file, parameter 1 holds the autostart line number (or a number >=32768 if no LINE parameter was given)
                 *  and parameter 2 holds the start of the variable area relative to the start of the program. If it's a Code file, parameter 1 holds
                 *  the start of the code block when saved, and parameter 2 holds 32768. For data files finally, the byte at position 14 decimal holds the variable name.)
                 */

                tdb.MetaData = new Dictionary <BlockDescriptorTitle, string>();

                if (blockdata[0] == 0x00 && blockSize == 19)
                {
                    string        fileName = Encoding.ASCII.GetString(blockdata.Skip(2).Take(10).ToArray()).Trim();
                    string        type     = "Unknown Type";
                    StringBuilder sb       = new StringBuilder();

                    var param1 = GetWordValue(blockdata, 12);
                    var param2 = GetWordValue(blockdata, 14);

                    // header block - examine first byte of header
                    if (blockdata[1] == 0)
                    {
                        type = "Program";
                        sb.Append(type + ": ");
                        sb.Append(fileName + " ");
                    }
                    else if (blockdata[1] == 1)
                    {
                        type = "NumArray";
                        sb.Append(type + ": ");
                        sb.Append(fileName + " ");
                    }
                    else if (blockdata[1] == 2)
                    {
                        type = "CharArray";
                        sb.Append(type + ": ");
                        sb.Append(fileName + " ");
                    }
                    else if (blockdata[1] == 3)
                    {
                        type = "Code";
                        sb.Append(type + ": ");
                        sb.Append(fileName + " ");
                    }
                }
                else if (blockdata[0] == 0xff)
                {
                    // data block
                    description = "Data Block " + (blockSize - 2) + "bytes";
                    tdb.AddMetaData(BlockDescriptorTitle.Data_Bytes, (blockSize - 2).ToString() + " Bytes");
                }
                else
                {
                    // some other type (turbo data etc..)
                    description = string.Format("#{0} block, {1} bytes", blockdata[0].ToString("X2"), blockSize);
                    //description += string.Format(", crc {0}", ((crc != 0) ? string.Format("bad (#{0:X2}!=#{1:X2})", crcFile, crcValue) : "ok"));
                    tdb.AddMetaData(BlockDescriptorTitle.Undefined, description);
                }

                /*
                 * if (blockdata[0] == 0x00 && blockSize == 19 && (blockdata[1] == 0x00) || blockdata[1] == 3)
                 * {
                 *  // This is the PROGRAM header
                 *  // take the 10 filename bytes (that start at offset 2)
                 *  programData = blockdata.Skip(2).Take(10).ToArray();
                 *
                 *  // get the filename as a string (with padding removed)
                 *  string fileName = Encoding.ASCII.GetString(programData).Trim();
                 *
                 *  // get the type
                 *  string type = "";
                 *  if (blockdata[0] == 0x00)
                 *  {
                 *      type = "Program";
                 *  }
                 *  else
                 *  {
                 *      type = "Bytes";
                 *  }
                 *
                 *  // now build the description string
                 *  StringBuilder sb = new StringBuilder();
                 *  sb.Append(type + ": ");
                 *  sb.Append(fileName + " ");
                 *  sb.Append(GetWordValue(blockdata, 14));
                 *  sb.Append(":");
                 *  sb.Append(GetWordValue(blockdata, 12));
                 *  description = sb.ToString();
                 * }
                 * else if (blockdata[0] == 0xFF)
                 * {
                 *  // this is a data block
                 *  description = "Data Block " + (blockSize - 2) + "bytes";
                 * }
                 * else
                 * {
                 *  // other type
                 *  description = string.Format("#{0} block, {1} bytes", blockdata[0].ToString("X2"), blockSize - 2);
                 *  description += string.Format(", crc {0}", ((crc != 0) ? string.Format("bad (#{0:X2}!=#{1:X2})", crcFile, crcValue) : "ok"));
                 * }
                 */

                tdb.BlockDescription = BlockType.Standard_Speed_Data_Block;

                // calculate the data periods for this block
                int pilotLength = 0;

                // work out pilot length
                if (blockdata[0] < 4)
                {
                    pilotLength = 8064;
                }
                else
                {
                    pilotLength = 3220;
                }

                // create a list to hold the data periods
                List <int> dataPeriods = new List <int>();

                // generate pilot pulses
                for (int i = 0; i < pilotLength; i++)
                {
                    dataPeriods.Add(PILOT_PL);
                }

                // add syncro pulses
                dataPeriods.Add(SYNC_1_PL);
                dataPeriods.Add(SYNC_2_PL);

                int pos = 0;

                // add bit0 and bit1 periods
                for (int i = 0; i < blockSize - 1; i++, pos++)
                {
                    for (byte b = 0x80; b != 0; b >>= 1)
                    {
                        if ((blockdata[i] & b) != 0)
                        {
                            dataPeriods.Add(BIT_1_PL);
                        }
                        else
                        {
                            dataPeriods.Add(BIT_0_PL);
                        }
                        if ((blockdata[i] & b) != 0)
                        {
                            dataPeriods.Add(BIT_1_PL);
                        }
                        else
                        {
                            dataPeriods.Add(BIT_0_PL);
                        }
                    }
                }

                // add the last byte
                for (byte c = 0x80; c != (byte)(0x80 >> BIT_COUNT_IN_LAST); c >>= 1)
                {
                    if ((blockdata[pos] & c) != 0)
                    {
                        dataPeriods.Add(BIT_1_PL);
                    }
                    else
                    {
                        dataPeriods.Add(BIT_0_PL);
                    }
                    if ((blockdata[pos] & c) != 0)
                    {
                        dataPeriods.Add(BIT_1_PL);
                    }
                    else
                    {
                        dataPeriods.Add(BIT_0_PL);
                    }
                }

                // add block pause
                //int actualPause = PAUSE_MS * 1000;
                //dataPeriods.Add(actualPause);

                // default pause for tap files
                tdb.PauseInMS = 1000;

                // add to the tapedatablock object
                tdb.DataPeriods = dataPeriods;

                // add the raw data
                tdb.BlockData = blockdata;

                // generate separate PAUS block
                TapeDataBlock tdbPause = new TapeDataBlock();
                tdbPause.DataPeriods      = new List <int>();
                tdbPause.BlockDescription = BlockType.PAUSE_BLOCK;
                tdbPause.PauseInMS        = 0;
                var pauseInTStates = TranslatePause(tdb.PauseInMS);
                //if (pauseInTStates > 0)
                //tdbPause.DataPeriods.Add(pauseInTStates);
                tdb.PauseInMS = 0;

                // add block to the tape
                _datacorder.DataBlocks.Add(tdb);

                // PAUS block if neccessary
                if (pauseInTStates > 0)
                {
                    tdbPause.AddMetaData(BlockDescriptorTitle.Block_ID, pauseInTStates.ToString() + " cycles");

                    int by1000  = pauseInTStates / 70000;
                    int rem1000 = pauseInTStates % 70000;

                    if (by1000 > 1)
                    {
                        tdbPause.DataPeriods.Add(35000);
                        tdbPause.DataPeriods.Add(pauseInTStates - 35000);
                    }
                    else
                    {
                        tdbPause.DataPeriods.Add(pauseInTStates);
                        tdbPause.DataPeriods.Add(0);
                    }

                    _datacorder.DataBlocks.Add(tdbPause);
                }
            }
        }
Exemplo n.º 22
0
 /// <inheritdoc />
 public ushort ToUInt16(byte[] value, int startIndex)
 {
     return(BitConverter.ToUInt16(value, startIndex));
 }
Exemplo n.º 23
0
        private void Encompress(BinaryWriter writer, bool low, byte[] data)
        {
            int pixels = data.Length;
            int shift  = low ? 2 : 0;

            List <ushort> palette = new List <ushort>();
            var           LUT     = new Dictionary <ushort, long>();

            using (var memory = new MemoryStream())
                using (var memoryWriter = new BitWriter(memory))
                {
                    int paletteSize = 0x1000;

                    var bitSize       = paletteSize < 0x1000 ? 3 : 4;
                    var loopThreshold = (1 << bitSize) - 2;

                    for (int px = shift; px < pixels; px += 4)
                    {
                        // Invert for correct endianness
                        if (low)
                        {
                            data[px + 1] ^= 0xFF; // Flip
                        }
                        var color = BitConverter.ToUInt16(new byte[] { data[px], data[px + 1] }, 0);

                        long paletteOffset;
                        if (LUT.ContainsKey(color))
                        {
                            paletteOffset = LUT[color];
                        }
                        else
                        {
                            paletteOffset = palette.Count;
                            palette.Add(color);
                            LUT[color] = paletteOffset;
                        }

                        byte paletteOffsetSize = (byte)(paletteOffset == 0
                        ? 1
                        : (Math.Floor(Math.Log(paletteOffset, 2)) + 1));

                        //byte paletteOffsetSize = 6;
                        memoryWriter.WriteWithBits((byte)(Math.Min(loopThreshold + 1, (int)paletteOffsetSize)), bitSize);

                        //memoryWriter.WriteBits(byte.MinValue, BitNum.MinValue); // Break
                        if (paletteOffsetSize > 1)
                        {
                            // Ignore first bit
                            //0b10 -> 0b00 or 0b11 -> 0b01
                            paletteOffsetSize--;

                            if (paletteOffsetSize > loopThreshold - 1)
                            {
                                if (paletteOffsetSize > loopThreshold)
                                {
                                    memoryWriter.WriteWithBits(uint.MaxValue, paletteOffsetSize - loopThreshold);
                                }
                                //memoryWriter.WriteBits(byte.MaxValue, (BitNum)(paletteOffsetSize - loopThreshold - 1));
                                memoryWriter.WriteBits(byte.MinValue, BitNum.MinValue); // Break
                            }

                            paletteOffset &= (int)((int)(1 << paletteOffsetSize) ^ uint.MaxValue);
                        }

                        memoryWriter.WriteWithBits((uint)paletteOffset, paletteOffsetSize);
                    }

                    memoryWriter.Flush();
                    var memoryArray = memory.ToArray();

                    while (palette.Count <= paletteSize)
                    {
                        // Add dummies
                        palette.Add(0x00);
                    }

                    //for (int i = 0; i < 32; i++) palette.Insert(0, 0); // Add dummy values

                    // Write RLE header
                    writer.Write((uint)(data.Length / 2));    // full size
                    writer.Write((uint)(memoryArray.Length)); // data size
                    writer.Write((ushort)(palette.Count));    // palette size

                    writer.Write((ushort)0);

                    // Write palette
                    foreach (var col in palette)
                    {
                        writer.Write(col);
                    }

                    // Write actual data
                    writer.Write(memoryArray);
                }
        }
Exemplo n.º 24
0
        public CapturePacket(Raw raw)
        {
            //RawCapture = raw;
            Date           = raw.TimeStamp;
            _linkLayerType = raw.LinkLayer;

            try
            {
                Packet = Packet.ParsePacket((LinkLayers)raw.LinkLayer, raw.RawData);
            }
            catch (Exception e)
            {
                Error = e.Message;
            }


            if (Packet == null)
            {
                return;
            }

            // protect against corrupted data with a try read
            try
            {
                var throwaway = Packet.Bytes.Length + Packet.HeaderData.Length;
            }
            catch (Exception e)
            {
                _protocolinfo = "Malformed Packet or Header";
                this.Error    = "Malformed Packet or Header";
                return;
            }

            if (Packet.PayloadPacket is IPv4Packet)
            {
                var ipv4 = (IPv4Packet)Packet.PayloadPacket;

                switch (ipv4.Protocol)
                {
                case PacketDotNet.ProtocolType.Tcp:
                    var tcpPacket = (TcpPacket)ipv4.PayloadPacket;
                    Protocol = ProtocolType.TCP;

                    // catch a semi-rare error in PacketDotNet that cannot be checked against
                    try
                    {
                        if (tcpPacket.PayloadData.Length == 0)
                        {
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        Error = e.Message;
                        break;
                    }

                    if ((tcpPacket.DestinationPort == 50039 || tcpPacket.DestinationPort == 50040) &&
                        tcpPacket.PayloadData.Length > 0)
                    {
                        Protocol = ProtocolType.JRU;


                        try
                        {
                            var ss27 = ExtractSS27Packet(tcpPacket);

                            DisplayFields.Add(new Tuple <string, object>("time", ss27.DateTime));
                            if (ss27.Events.Count == 0)
                            {
                                // if there is no event, chuck some other data in there, maybe
                                // ParsedData = new ParsedDataSet() { ParsedFields = new List<ParsedField>(ss27.Header) };
                            }
                            else
                            {
                                // TODO FIX THIS SO IT WORKS
                                ss27.Events.ForEach(e => DisplayFields.Add(new Tuple <string, object>(e.EventType.ToString(), e.Description)));
                            }

                            this.SS27Packet = ss27;
                        }
                        catch (Exception e)
                        {
                            Error = e.Message;
                        }
                    }

                    if (tcpPacket.SourcePort == 50041 && tcpPacket.PayloadData.Length > 0)
                    {
                        Protocol = ProtocolType.JRU;
                        var jruload = tcpPacket.PayloadData;
                        try
                        {
                            ushort jrulen = BitConverter.ToUInt16(new byte[] { jruload[1], jruload[0] }, 0);
                            var    buffer = new byte[jrulen];
                            Array.Copy(jruload, 2, buffer, 0, jrulen);
                            ParsedData = VSIS210.JRU_STATUS.Parse(buffer);
                        }
                        catch (Exception e)
                        {
                            Error = e.Message;
                        }
                    }

                    break;

                case PacketDotNet.ProtocolType.Udp:

                    Protocol = ProtocolType.UDP;
                    var udp = (UdpPacket)ipv4.PayloadPacket;

                    if (udp == null)
                    {
                        _protocolinfo = "Malformed UDP";
                        this.Error    = "Malformed UDP";
                        return;
                    }

                    // protect against corrupted data with a try read
                    try
                    {
                        var throwaway = udp.DestinationPort + udp.SourcePort + udp.Length + udp.Checksum;
                    }
                    catch (Exception e)
                    {
                        _protocolinfo = "Malformed UDP";
                        this.Error    = "Malformed UDP";
                        return;
                    }


                    if (udp.SourcePort == 123 && udp.DestinationPort == 123)
                    {
                        Protocol = ProtocolType.NTP;
                    }
                    else if (Equals(ipv4.SourceAddress, VapAddress))
                    {
                        if (udp.DestinationPort == 50023)
                        {
                            _protocolinfo = "VAP->ETC (TR)";
                        }
                        else if (udp.DestinationPort == 50030)
                        {
                            _protocolinfo = "VAP->ETC (DMI1 to ETC)";
                        }
                        else if (udp.DestinationPort == 50031)
                        {
                            _protocolinfo = "VAP->ETC (DMI2 to ETC)";
                        }
                        else if (udp.DestinationPort == 50032)
                        {
                            _protocolinfo = "VAP->ETC (DMI1 to iSTM)";
                        }
                        else if (udp.DestinationPort == 50033)
                        {
                            _protocolinfo = "VAP->ETC (DMI2 to iSTM)";
                        }
                        else if (udp.DestinationPort == 50051)
                        {
                            _protocolinfo = "VAP->ETC (DMI1 to gSTM)";
                        }
                        else if (udp.DestinationPort == 50052)
                        {
                            _protocolinfo = "VAP->ETC (DMI2 to gSTM)";
                        }
                        else if (udp.DestinationPort == 50024)
                        {
                            _protocolinfo = "VAP->ETC (DMI1 EVC-102)";
                        }
                        else if (udp.DestinationPort == 50025)
                        {
                            _protocolinfo = "VAP->ETC (DMI2 EVC-102)";
                        }
                        else if (udp.DestinationPort == 50039)
                        {
                            _protocolinfo = "VAP->ETC (STM to JRU)";
                        }
                        else if (udp.DestinationPort == 50041)
                        {
                            _protocolinfo = "VAP->ETC (JRU Status)";
                        }
                        else if (udp.DestinationPort == 50050)
                        {
                            _protocolinfo = "VAP->ETC (VAP Status)";
                        }
                        else if (udp.DestinationPort == 50015)
                        {
                            Protocol      = ProtocolType.UDP_SPL;
                            _protocolinfo = "VAP->OPC (DMI to STM)";
                        }
                        else if (udp.DestinationPort == 5514)
                        {
                            _protocolinfo = "VAP->BDS (VAP Diag)";
                        }
                    }
                    else if (Equals(ipv4.DestinationAddress, VapAddress))
                    {
                        if (udp.DestinationPort == 50022)
                        {
                            _protocolinfo = "ETC->VAP (OBU)";
                        }
                        else if (udp.DestinationPort == 50026)
                        {
                            _protocolinfo = "ETC->VAP (ETC to DMI1)";
                        }
                        else if (udp.DestinationPort == 50027)
                        {
                            _protocolinfo = "ETC->VAP (ETC to DMI2)";
                        }
                        else if (udp.DestinationPort == 50037)
                        {
                            _protocolinfo = "ETC->VAP (EVC-1&7)";
                        }
                        else if (udp.DestinationPort == 50035)
                        {
                            _protocolinfo = "ETC->VAP (EVC-1&7)";
                        }
                        else if (udp.DestinationPort == 50028)
                        {
                            _protocolinfo = "ETC->VAP (iSTM to DMI1)";
                        }
                        else if (udp.DestinationPort == 50029)
                        {
                            _protocolinfo = "ETC->VAP (iSTM to DMI2)";
                        }
                        else if (udp.DestinationPort == 50055)
                        {
                            _protocolinfo = "ETC->VAP (gSTM to DMI1)";
                        }
                        else if (udp.DestinationPort == 50056)
                        {
                            _protocolinfo = "ETC->VAP (gSTM to DMI2)";
                        }
                        else if (udp.DestinationPort == 50034)
                        {
                            _protocolinfo = "ETC->VAP (to JRU)";
                        }
                        else if (udp.DestinationPort == 50057)
                        {
                            _protocolinfo = "ETC->VAP (VAP Config)";
                        }
                        else if (udp.DestinationPort == 50014)
                        {
                            Protocol      = ProtocolType.UDP_SPL;
                            _protocolinfo = "OPC->VAP";

                            var payload = udp.PayloadData;
                            var spl     = VAP.UDP_SPL.Parse(payload);
                            this.DisplayFields =
                                spl.ParsedFields.Select(f => new Tuple <string, object>(f.Name, f.Value)).ToList();

                            if (spl.ParsedFields.Last().Value.Equals("C9"))
                            {
                                var nextBytes = Functions.SubArrayGetter(payload, 81);
                                var stm       = VAP.STM_Packet.Parse(nextBytes);
                                DisplayFields.AddRange(stm.ParsedFields.Select(f => new Tuple <string, object>(f.Name, f.Value)).ToList());
                            }
                        }
                        else if (udp.DestinationPort == 50036)
                        {
                            _protocolinfo = "BDS->VAP (Diag)";
                        }
                        else if (udp.DestinationPort == 50070)
                        {
                            _protocolinfo = "ETC->VAP (ATO)";
                        }
                        else if (udp.DestinationPort == 50068)
                        {
                            _protocolinfo = "ETC->VAP (ATO)";
                        }
                        else if (udp.DestinationPort == 50072)
                        {
                            _protocolinfo = "ETC->VAP (ATO)";
                        }
                    }


                    try
                    {
                        IPTWPPacket = IPTWPPacket.Extract(udp);
                    }
                    catch (Exception e)
                    {
                        Error = e.Message;
                    }

                    if (IPTWPPacket != null)
                    {
                        Protocol = ProtocolType.IPTWP;
                    }
                    break;

                case PacketDotNet.ProtocolType.Icmp:
                    Protocol = ProtocolType.ICMP;
                    // dunno
                    break;

                case PacketDotNet.ProtocolType.Igmp:
                    Protocol = ProtocolType.IGMP;
                    // dunno
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            else if (Packet.PayloadPacket is ArpPacket arpPacket)
            {
                Protocol = ProtocolType.ARP;
            }
            else if (Packet.PayloadPacket is IPv6Packet)
            {
                Protocol = ProtocolType.IPv6;
                // ignore, for now
            }
            else if (raw.LinkLayer == LinkLayerType.Ethernet && Packet.HeaderData[12] == 0x88 &&
                     Packet.HeaderData[13] == 0xe1)
            {
                Protocol = ProtocolType.HomeplugAV;
                // ignore
            }
            else if (raw.LinkLayer == LinkLayerType.Ethernet && Packet.HeaderData[12] == 0x89 &&
                     Packet.HeaderData[13] == 0x12)
            {
                Protocol = ProtocolType.Mediaxtream;
                // ignore
            }
            else if (raw.LinkLayer == LinkLayerType.Ethernet && Packet.HeaderData[12] == 0x88 &&
                     Packet.HeaderData[13] == 0xcc)
            {
                Protocol = ProtocolType.LLDP;
                // ignore
            }
            else
            {
                Protocol = ProtocolType.UNKNOWN;
#if DEBUG
                // if we are in debug, we might want to know what is in the unknown
                //                throw new NotImplementedException("Surprise data! " + BitConverter.ToString(packet.Bytes));
#endif
            }

            var extractParsedData = ExtractParsedData(this, out var displayfields);
            this.DisplayFields.AddRange(displayfields);
            this.ParsedData = extractParsedData;
        }
Exemplo n.º 25
0
        /// <summary>
        /// Tests whether an object's ID starts with the specified 16-bits, or a subset of them.
        /// </summary>
        /// <param name="object">The object whose ID is to be tested.</param>
        /// <param name="leadingBytes">The leading 16-bits to be tested.</param>
        /// <param name="bitMask">The mask that indicates which bits should be compared.</param>
        /// <returns><c>True</c> if the object's ID starts with <paramref name="leadingBytes"/> after applying the <paramref name="bitMask"/>.</returns>
        private static bool StartsWith(this ObjectId @object, ushort leadingBytes, ushort bitMask = 0xffff)
        {
            ushort truncatedObjectId = BitConverter.ToUInt16(@object.RawId, 0);

            return((truncatedObjectId & bitMask) == leadingBytes);
        }
Exemplo n.º 26
0
        public static void Read()
        {
            Value = Spc.Ram[Position++];

            if (Value == RomSongs.EndTrack)
            {
                EventType = EventTypes.Stop;
            }
            else if (Value < RomSongs.FirstNote)
            {
                Length = Value;

                if ((Spc.Ram[Position] & 0x80) != 0x00)
                {
                    EventType = EventTypes.Length;
                }
                else
                {
                    EventType = EventTypes.LengthDurationVelocity;

                    Duration = Spc.Ram[Position] >> 4;
                    Velocity = Spc.Ram[Position] & 0x0f;

                    Position++;
                }
            }
            else if (Value < RomSongs.Tie)
            {
                EventType = EventTypes.Note;
                Note      = Value - RomSongs.FirstNote;

                if (Spc.Ram[Position] != 0xf9)
                {
                    Delay      = 0;
                    Duration   = 0;
                    PitchSlide = 0;
                }
                else
                {
                    Position++;

                    Delay      = Spc.Ram[Position++];
                    Duration   = Spc.Ram[Position++];
                    PitchSlide = Spc.Ram[Position++] - RomSongs.FirstNote;
                }
            }
            else if (Value == RomSongs.Tie)
            {
                EventType = EventTypes.Tie;
            }
            else if (Value == RomSongs.Rest)
            {
                EventType = EventTypes.Rest;
            }
            else if (Value < RomSongs.FirstEvent)
            {
                EventType = EventTypes.Percussion;
                Note      = Value - RomSongs.FirstPercussion;
            }
            else if (Value == 0xE0)
            {
                EventType  = EventTypes.Instrument;
                Instrument = Spc.Ram[Position++];
            }
            else if (Value == 0xE1)
            {
                EventType = EventTypes.Pan;
                Pan       = Spc.Ram[Position] & 0x2F;
                Phase     = Spc.Ram[Position++] >> 6;
            }
            else if (Value == 0xE2)
            {
                EventType = EventTypes.PanFade;
                Fade      = Spc.Ram[Position++];
                Pan       = Spc.Ram[Position++] & 0x2F;
            }
            else if (Value == 0xE5)
            {
                EventType = EventTypes.MasterVolume;
                Volume    = Spc.Ram[Position++];
            }
            else if (Value == 0xE6)
            {
                EventType = EventTypes.MasterVolumeFade;
                Fade      = Spc.Ram[Position++];
                Volume    = Spc.Ram[Position++];
            }
            else if (Value == 0xE7)
            {
                EventType = EventTypes.Tempo;
                Tempo     = Spc.Ram[Position++];
            }
            else if (Value == 0xE8)
            {
                EventType = EventTypes.TempoFade;
                Fade      = Spc.Ram[Position++];
                Tempo     = Spc.Ram[Position++];
            }
            else if (Value == 0xEA)
            {
                EventType = EventTypes.Transpose;
                Transpose = (sbyte)Spc.Ram[Position++];
            }
            else if (Value == 0xED)
            {
                EventType = EventTypes.Volume;
                Volume    = Spc.Ram[Position++];
            }
            else if (Value == 0xEE)
            {
                EventType = EventTypes.VolumeFade;
                Fade      = Spc.Ram[Position++];
                Volume    = Spc.Ram[Position++];
            }
            else if (Value == 0xEF)
            {
                EventType = EventTypes.Call;
                Call      = BitConverter.ToUInt16(Spc.Ram, Position);
                Repeat    = Spc.Ram[Position + 2];

                Position += 3;
            }
            else if (Value == 0xF4)
            {
                EventType = EventTypes.Tuning;
                Tuning    = Spc.Ram[Position++];
            }
            else if (Value == 0xF9)
            {
                EventType  = EventTypes.PitchSlide;
                Delay      = Spc.Ram[Position++];
                Duration   = Spc.Ram[Position++];
                PitchSlide = Spc.Ram[Position++];
            }
            else if (Value == 0xFA)
            {
                EventType = EventTypes.PercussionInstrumentOffset;
                PercussionInstrumentOffset = Spc.Ram[Position++];
            }
            else
            {
                EventType = EventTypes.Other;

                Position += RomSongs.EventTypes[Value - RomSongs.FirstEvent].Length;

                System.Diagnostics.Debug.WriteLine("Unknown Event: " + Value.ToString("X2"));
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// 根据类型地址以及需要写入的数据来生成报文
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="value">写入数据的实际值</param>
        /// <param name="networkNumber">网络号</param>
        /// <param name="networkStationNumber">网络站号</param>
        /// <returns>带有成功标志的指令数据</returns>
        public static OperateResult <byte[]> BuildWriteCommand(string address, byte[] value, byte networkNumber = 0, byte networkStationNumber = 0)
        {
            OperateResult <MelsecMcDataType, ushort> analysis = MelsecHelper.McAnalysisAddress(address);

            if (!analysis.IsSuccess)
            {
                return(OperateResult.CreateFailedResult <byte[]>(analysis));
            }


            // 预处理指令
            if (analysis.Content1.DataType == 0x01)
            {
                // 位写入
                value = value.Select(m => m == 0x00 ? (byte)0x30 : (byte)0x31).ToArray( );
            }
            else
            {
                // 字写入
                byte[] buffer = new byte[value.Length * 2];
                for (int i = 0; i < value.Length / 2; i++)
                {
                    MelsecHelper.BuildBytesFromData(BitConverter.ToUInt16(value, i * 2)).CopyTo(buffer, 4 * i);
                }
                value = buffer;
            }


            // 默认信息----注意:高低字节交错

            byte[] _PLCCommand = new byte[42 + value.Length];

            _PLCCommand[0]  = 0x35;                                                                              // 副标题
            _PLCCommand[1]  = 0x30;
            _PLCCommand[2]  = 0x30;
            _PLCCommand[3]  = 0x30;
            _PLCCommand[4]  = MelsecHelper.BuildBytesFromData(networkNumber)[0];                                 // 网络号
            _PLCCommand[5]  = MelsecHelper.BuildBytesFromData(networkNumber)[1];
            _PLCCommand[6]  = 0x46;                                                                              // PLC编号
            _PLCCommand[7]  = 0x46;
            _PLCCommand[8]  = 0x30;                                                                              // 目标模块IO编号
            _PLCCommand[9]  = 0x33;
            _PLCCommand[10] = 0x46;
            _PLCCommand[11] = 0x46;
            _PLCCommand[12] = MelsecHelper.BuildBytesFromData(networkStationNumber)[0];                          // 目标模块站号
            _PLCCommand[13] = MelsecHelper.BuildBytesFromData(networkStationNumber)[1];
            _PLCCommand[14] = MelsecHelper.BuildBytesFromData((ushort)(_PLCCommand.Length - 18))[0];             // 请求数据长度
            _PLCCommand[15] = MelsecHelper.BuildBytesFromData((ushort)(_PLCCommand.Length - 18))[1];
            _PLCCommand[16] = MelsecHelper.BuildBytesFromData((ushort)(_PLCCommand.Length - 18))[2];
            _PLCCommand[17] = MelsecHelper.BuildBytesFromData((ushort)(_PLCCommand.Length - 18))[3];
            _PLCCommand[18] = 0x30;                                                                              // CPU监视定时器
            _PLCCommand[19] = 0x30;
            _PLCCommand[20] = 0x31;
            _PLCCommand[21] = 0x30;
            _PLCCommand[22] = 0x31;                                                                              // 批量写入的命令
            _PLCCommand[23] = 0x34;
            _PLCCommand[24] = 0x30;
            _PLCCommand[25] = 0x31;
            _PLCCommand[26] = 0x30;                                                                              // 子命令
            _PLCCommand[27] = 0x30;
            _PLCCommand[28] = 0x30;
            _PLCCommand[29] = analysis.Content1.DataType == 0 ? (byte)0x30 : (byte)0x31;
            _PLCCommand[30] = Encoding.ASCII.GetBytes(analysis.Content1.AsciiCode)[0];                           // 软元件类型
            _PLCCommand[31] = Encoding.ASCII.GetBytes(analysis.Content1.AsciiCode)[1];
            _PLCCommand[32] = MelsecHelper.BuildBytesFromAddress(analysis.Content2, analysis.Content1)[0];       // 起始地址的地位
            _PLCCommand[33] = MelsecHelper.BuildBytesFromAddress(analysis.Content2, analysis.Content1)[1];
            _PLCCommand[34] = MelsecHelper.BuildBytesFromAddress(analysis.Content2, analysis.Content1)[2];
            _PLCCommand[35] = MelsecHelper.BuildBytesFromAddress(analysis.Content2, analysis.Content1)[3];
            _PLCCommand[36] = MelsecHelper.BuildBytesFromAddress(analysis.Content2, analysis.Content1)[4];
            _PLCCommand[37] = MelsecHelper.BuildBytesFromAddress(analysis.Content2, analysis.Content1)[5];

            // 判断是否进行位操作
            if (analysis.Content1.DataType == 1)
            {
                _PLCCommand[38] = MelsecHelper.BuildBytesFromData((ushort)value.Length)[0];                      // 软元件点数
                _PLCCommand[39] = MelsecHelper.BuildBytesFromData((ushort)value.Length)[1];
                _PLCCommand[40] = MelsecHelper.BuildBytesFromData((ushort)value.Length)[2];
                _PLCCommand[41] = MelsecHelper.BuildBytesFromData((ushort)value.Length)[3];
            }
            else
            {
                _PLCCommand[38] = MelsecHelper.BuildBytesFromData((ushort)(value.Length / 4))[0];                // 软元件点数
                _PLCCommand[39] = MelsecHelper.BuildBytesFromData((ushort)(value.Length / 4))[1];
                _PLCCommand[40] = MelsecHelper.BuildBytesFromData((ushort)(value.Length / 4))[2];
                _PLCCommand[41] = MelsecHelper.BuildBytesFromData((ushort)(value.Length / 4))[3];
            }
            Array.Copy(value, 0, _PLCCommand, 42, value.Length);

            return(OperateResult.CreateSuccessResult(_PLCCommand));
        }
Exemplo n.º 28
0
        /// <summary>
        ///     Loads this class with data from a stream.
        /// </summary>
        /// <param name="graphicsDevice">The graphicsDevice device.</param>
        /// <param name="stream">The stream that contains the model data.</param>
        public void Load(GraphicsDevice graphicsDevice, Stream stream)
        {
            this.graphics = graphicsDevice;

            using (var reader = new BinaryReader(stream))
            {
                this.BoundingBox.Min = reader.ReadVector3();
                this.BoundingBox.Max = reader.ReadVector3();

                int numBones = reader.ReadInt32();
                for (int i = 0; i < numBones; i++)
                {
                    byte[] dataBones   = reader.ReadBytes(8);
                    int    boneIndex   = BitConverter.ToInt32(dataBones, 0);
                    int    parentIndex = BitConverter.ToInt32(dataBones, 4);

                    string boneName = reader.ReadString();

                    Matrix matrix;
                    reader.ReadMatrix(out matrix);

                    this.Bones.Add(new Bone(boneIndex, parentIndex, boneName, matrix));
                }

                int numMeshes = reader.ReadInt32();

                for (int i = 0; i < numMeshes; i++)
                {
                    string meshName = reader.ReadString();

                    byte[] dataHeader = reader.ReadBytes(8);

                    int parentBone = BitConverter.ToInt32(dataHeader, 0);
                    int meshParts  = BitConverter.ToInt32(dataHeader, 4);

                    for (int j = 0; j < meshParts; j++)
                    {
                        byte[] dataPart = reader.ReadBytes(24);

                        int vertexOffset      = BitConverter.ToInt32(dataPart, 0);
                        int numVertices       = BitConverter.ToInt32(dataPart, 4);
                        int startIndex        = BitConverter.ToInt32(dataPart, 8);
                        int primitiveCount    = BitConverter.ToInt32(dataPart, 12);
                        int numVertexElements = BitConverter.ToInt32(dataPart, 20);

                        var properties = new VertexElementProperties[numVertexElements];

                        byte[] data = reader.ReadBytes(numVertexElements * 16);
                        for (int k = 0; k < numVertexElements; k++)
                        {
                            VertexElementProperties item = properties[k];

                            item.Offset     = BitConverter.ToInt32(data, 0 + (k * 16));
                            item.Format     = (VertexElementFormat)BitConverter.ToInt32(data, 4 + (k * 16));
                            item.Usage      = (VertexElementUsage)BitConverter.ToInt32(data, 8 + (k * 16));
                            item.UsageIndex = BitConverter.ToInt32(data, 12 + (k * 16));

                            properties[k] = item;
                        }

                        // Skip collision data (read from file for retrocompatibility)
                        bool hasCollision = reader.ReadBoolean();
                        if (hasCollision)
                        {
                            int collisionVerticesCount = reader.ReadInt32();
                            reader.ReadBytes(collisionVerticesCount * 12);

                            int collisionIndicesCount = reader.ReadInt32();
                            reader.ReadBytes(collisionVerticesCount * 2);
                        }

                        int    bufferSize = reader.ReadInt32();
                        byte[] bufferData = reader.ReadBytes(bufferSize);

                        int    indexSize   = reader.ReadInt32();
                        byte[] dataIndices = reader.ReadBytes(indexSize * 2);

                        indexSize = (indexSize / 3) * 3;
                        var indices = new ushort[indexSize];

                        for (int k = 0; k < indexSize; k++)
                        {
                            indices[k] = BitConverter.ToUInt16(dataIndices, k * 2);
                        }

                        var vertexBuffer = new VertexBuffer(new VertexBufferFormat(properties));
                        vertexBuffer.SetData(bufferData, numVertices);
                        var indexBuffer = new IndexBuffer(indices);
                        var mesh        = new Mesh(vertexOffset, numVertices, startIndex, primitiveCount, vertexBuffer, indexBuffer, PrimitiveType.TriangleList);
                        mesh.Name = meshName;

                        this.Meshes.Add(mesh);
                        this.MeshBonePairs.Add(this.Meshes.Count - 1, parentBone);
                    }
                }
            }

            for (int i = 0; i < this.Bones.Count; i++)
            {
                Bone bone = this.Bones[i];
                if (bone.ParentIndex == -1)
                {
                    this.Bones[i].AbsoluteTransform = bone.LocalTransform;
                }
                else
                {
                    this.Bones[i].AbsoluteTransform = bone.LocalTransform
                                                      * this.Bones[bone.ParentIndex].AbsoluteTransform;
                }
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// 从流中读取一个ushort数据
 /// </summary>
 /// <returns></returns>
 public ushort ReadUShort()
 {
     byte[] arr = new byte[2];
     base.Read(arr, 0, 2);
     return(BitConverter.ToUInt16(arr, 0));
 }
        internal void Read(Stream stream)
        {
            // For the complete documentation for this section see:
            // http://tools.ietf.org/html/rfc6455#section-5.2

            this.Header = ReadByte(stream);

            // The first byte is the Final Bit and the type of the frame
            IsFinal = (this.Header & 0x80) != 0;
            Type    = (WebSocketFrameTypes)(this.Header & 0xF);

            byte maskAndLength = ReadByte(stream);

            // The secound byte is the Mask Bit and the length of the payload data
            HasMask = (maskAndLength & 0x80) != 0;

            // if 0-125, that is the payload length.
            Length = (UInt64)(maskAndLength & 127);

            // If 126, the following 2 bytes interpreted as a 16-bit unsigned integer are the payload length.
            if (Length == 126)
            {
                byte[] rawLen = new byte[2];
                stream.ReadBuffer(rawLen);

                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(rawLen, 0, rawLen.Length);
                }

                Length = (UInt64)BitConverter.ToUInt16(rawLen, 0);
            }
            else if (Length == 127)
            {
                // If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the
                // most significant bit MUST be 0) are the payload length.

                byte[] rawLen = new byte[8];
                stream.ReadBuffer(rawLen);

                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(rawLen, 0, rawLen.Length);
                }

                Length = (UInt64)BitConverter.ToUInt64(rawLen, 0);
            }

            // Read the Mask, if has any
            if (HasMask)
            {
                Mask = new byte[4];
                if (stream.Read(Mask, 0, 4) < Mask.Length)
                {
                    throw ExceptionHelper.ServerClosedTCPStream();
                }
            }

            Data = new byte[Length];

            if (Length == 0L)
            {
                return;
            }

            int readLength = 0;

            do
            {
                int read = stream.Read(Data, readLength, Data.Length - readLength);

                if (read <= 0)
                {
                    throw ExceptionHelper.ServerClosedTCPStream();
                }

                readLength += read;
            } while (readLength < Data.Length);

            // It would be great to speed this up with SSE
            if (HasMask)
            {
                for (int i = 0; i < Data.Length; ++i)
                {
                    Data[i] = (byte)(Data[i] ^ Mask[i % 4]);
                }
            }
        }