Example #1
0
        private bool ReportToBuffer(Joycon hidReport, byte[] outputData, ref int outIdx) {
            var ds4 = Joycon.MapToDualShock4Input(hidReport);

            outputData[outIdx] = 0;

            if (ds4.dPad == Controller.DpadDirection.West || ds4.dPad == Controller.DpadDirection.Northwest || ds4.dPad == Controller.DpadDirection.Southwest) outputData[outIdx] |= 0x80;
            if (ds4.dPad == Controller.DpadDirection.South || ds4.dPad == Controller.DpadDirection.Southwest || ds4.dPad == Controller.DpadDirection.Southeast) outputData[outIdx] |= 0x40;
            if (ds4.dPad == Controller.DpadDirection.East || ds4.dPad == Controller.DpadDirection.Northeast || ds4.dPad == Controller.DpadDirection.Southeast) outputData[outIdx] |= 0x20;
            if (ds4.dPad == Controller.DpadDirection.North || ds4.dPad == Controller.DpadDirection.Northwest || ds4.dPad == Controller.DpadDirection.Northeast) outputData[outIdx] |= 0x10;

            if (ds4.options) outputData[outIdx] |= 0x08;
            if (ds4.thumb_right) outputData[outIdx] |= 0x04;
            if (ds4.thumb_left) outputData[outIdx] |= 0x02;
            if (ds4.share) outputData[outIdx] |= 0x01;

            outputData[++outIdx] = 0;

            if (ds4.square) outputData[outIdx] |= 0x80;
            if (ds4.cross) outputData[outIdx] |= 0x40;
            if (ds4.circle) outputData[outIdx] |= 0x20;
            if (ds4.triangle) outputData[outIdx] |= 0x10;

            if (ds4.shoulder_right) outputData[outIdx] |= 0x08;
            if (ds4.shoulder_left) outputData[outIdx] |= 0x04;
            if (ds4.trigger_right_value == Byte.MaxValue) outputData[outIdx] |= 0x02;
            if (ds4.trigger_left_value == Byte.MaxValue) outputData[outIdx] |= 0x01;

            outputData[++outIdx] = ds4.ps ? (byte)1 : (byte)0;
            outputData[++outIdx] = ds4.touchpad ? (byte)1 : (byte)0;

            outputData[++outIdx] = ds4.thumb_left_x;
            outputData[++outIdx] = ds4.thumb_left_y;
            outputData[++outIdx] = ds4.thumb_right_x;
            outputData[++outIdx] = ds4.thumb_right_y;

            //we don't have analog buttons so just use the Button enums (which give either 0 or 0xFF)
            outputData[++outIdx] = (ds4.dPad == Controller.DpadDirection.West || ds4.dPad == Controller.DpadDirection.Northwest || ds4.dPad == Controller.DpadDirection.Southwest) ? (byte)0xFF : (byte)0;
            outputData[++outIdx] = (ds4.dPad == Controller.DpadDirection.South || ds4.dPad == Controller.DpadDirection.Southwest || ds4.dPad == Controller.DpadDirection.Southeast) ? (byte)0xFF : (byte)0;
            outputData[++outIdx] = (ds4.dPad == Controller.DpadDirection.East || ds4.dPad == Controller.DpadDirection.Northeast || ds4.dPad == Controller.DpadDirection.Southeast) ? (byte)0xFF : (byte)0;
            outputData[++outIdx] = (ds4.dPad == Controller.DpadDirection.North || ds4.dPad == Controller.DpadDirection.Northwest || ds4.dPad == Controller.DpadDirection.Northeast) ? (byte)0xFF : (byte)0; ;

            outputData[++outIdx] = ds4.square ? (byte)0xFF : (byte)0;
            outputData[++outIdx] = ds4.cross ? (byte)0xFF : (byte)0;
            outputData[++outIdx] = ds4.circle ? (byte)0xFF : (byte)0;
            outputData[++outIdx] = ds4.triangle ? (byte)0xFF : (byte)0;

            outputData[++outIdx] = ds4.shoulder_right ? (byte)0xFF : (byte)0;
            outputData[++outIdx] = ds4.shoulder_left ? (byte)0xFF : (byte)0;

            outputData[++outIdx] = ds4.trigger_right_value;
            outputData[++outIdx] = ds4.trigger_left_value;

            outIdx++;

            //DS4 only: touchpad points
            for (int i = 0; i < 2; i++) {
                outIdx += 6;
            }

            //motion timestamp
            Array.Copy(BitConverter.GetBytes(hidReport.Timestamp), 0, outputData, outIdx, 8);
            outIdx += 8;

            //accelerometer
            {
                var accel = hidReport.GetAccel();
                if (accel != Vector3.Zero) {
                    Array.Copy(BitConverter.GetBytes(accel.Y), 0, outputData, outIdx, 4);
                    outIdx += 4;
                    Array.Copy(BitConverter.GetBytes(-accel.Z), 0, outputData, outIdx, 4);
                    outIdx += 4;
                    Array.Copy(BitConverter.GetBytes(accel.X), 0, outputData, outIdx, 4);
                    outIdx += 4;
                } else {
                    outIdx += 12;
                    Console.WriteLine("No accelerometer reported.");
                }
            }

            //gyroscope
            {
                var gyro = hidReport.GetGyro();
                if (gyro != Vector3.Zero) {
                    Array.Copy(BitConverter.GetBytes(gyro.Y), 0, outputData, outIdx, 4);
                    outIdx += 4;
                    Array.Copy(BitConverter.GetBytes(gyro.Z), 0, outputData, outIdx, 4);
                    outIdx += 4;
                    Array.Copy(BitConverter.GetBytes(gyro.X), 0, outputData, outIdx, 4);
                    outIdx += 4;
                } else {
                    outIdx += 12;
                    Console.WriteLine("No gyroscope reported.");
                }
            }

            return true;
        }
Example #2
0
 public void WriteDouble(Span <byte> span, double value, int offset, SerializationContext context)
 {
     this.WriteLong(span, BitConverter.DoubleToInt64Bits(value), offset, context);
 }
Example #3
0
 void write(byte[] buf, int offset, ulong val)
 {
     byte[] val_b = BitConverter.GetBytes(val);
     for (int i = 0; i < val_b.Length; i++)
         buf[offset + i] = val_b[i];
 }
    public void TestToInt32() {
      Int32 expected = BitConverter.ToInt32(_bytes, 0);
      Int32 actual = BitConverterNonAlloc.ToInt32(_bytes, 0);

      Assert.That(actual, Is.EqualTo(expected));
    }
Example #5
0
        private SerializedType ReadSerializedType(bool isRefType)
        {
            var type = new SerializedType();

            // type.classID = reader.ReadInt32();
            // see ASB_DecodeClassID
            var buf = reader.ReadBytes(4);
            Array.Reverse(buf);
            type.classID = (BitConverter.ToInt32(buf, 0) ^ 0x23746FBE) - 3;

            if (header.m_Version >= SerializedFileFormatVersion.kRefactoredClassId)
            {
                type.m_IsStrippedType = reader.ReadBoolean();
            }

            if (header.m_Version >= SerializedFileFormatVersion.kRefactorTypeData)
            {
                type.m_ScriptTypeIndex = reader.ReadInt16();
            }

            if (header.m_Version >= SerializedFileFormatVersion.kHasTypeTreeHashes)
            {
                if (isRefType && type.m_ScriptTypeIndex >= 0)
                {
                    type.m_ScriptID = reader.ReadBytes(16);
                }
                else if ((header.m_Version < SerializedFileFormatVersion.kRefactoredClassId && type.classID < 0) || (header.m_Version >= SerializedFileFormatVersion.kRefactoredClassId && type.classID == 114))
                {
                    type.m_ScriptID = reader.ReadBytes(16);
                }
                type.m_OldTypeHash = reader.ReadBytes(16);
            }

            if (m_EnableTypeTree)
            {
                type.m_Type = new TypeTree();
                type.m_Type.m_Nodes = new List<TypeTreeNode>();
                if (header.m_Version >= SerializedFileFormatVersion.kUnknown_12 || header.m_Version == SerializedFileFormatVersion.kUnknown_10)
                {
                    TypeTreeBlobRead(type.m_Type);
                }
                else
                {
                    ReadTypeTree(type.m_Type);
                }
                if (header.m_Version >= SerializedFileFormatVersion.kStoresTypeDependencies)
                {
                    if (isRefType)
                    {
                        type.m_KlassName = reader.ReadStringToNull();
                        type.m_NameSpace = reader.ReadStringToNull();
                        type.m_AsmName = reader.ReadStringToNull();
                    }
                    else
                    {
                        type.m_TypeDependencies = reader.ReadInt32Array();
                    }
                }
            }

            return type;
        }
 public bool ReadBoolean()
 {
     byte[] buffer = new byte[1];
     Read(buffer, 0, 1);
     return(BitConverter.ToBoolean(buffer, 0));
 }
    public void TestToDouble() {
      Double expected = BitConverter.ToDouble(_bytes, 0);
      Double actual = BitConverterNonAlloc.ToDouble(_bytes, 0);

      Assert.That(actual, Is.EqualTo(expected));
    }
Example #8
0
 public float GetFloat(int field) => BitConverter.ToSingle(parent.bytes, offset + field * 4);
 public void CheckDataStream()
 {
   if ((DateTime.Now - this._lastContact).TotalMinutes >= 30.0)
   {
     this.DestroyClient();
   }
   else
   {
     this._baseStream.ReadTimeout = 1000;
     if (this.Destroyed || !this.ClientReady || !this._baseStream.DataAvailable)
       return;
     byte[] buf = new byte[4];
     this._protectedStream.ReadStrictBytes(buf, 4);
     int int32 = BitConverter.ToInt32(buf, 0);
     if (int32 > 32000)
     {
       this.DestroyClient();
     }
     else
     {
       byte[] numArray = new byte[int32];
       this._protectedStream.ReadStrictBytes(numArray, int32);
       Message e = Message.Deserialize(numArray);
       if (e == null || string.IsNullOrEmpty(e.Payload) || (string.IsNullOrEmpty(e.Sender) || string.IsNullOrEmpty(e.TimeStamp)))
         return;
       this._lastContact = DateTime.Now;
       Channel channel = Channel.GetChannel(e.DestinationChannel);
       if (e.Payload[0] == '!')
       {
         string payload = e.Payload;
         if (!(payload == "!HELO"))
         {
           if (!(payload == "!GBYE"))
           {
             if (!(payload == "!FRWL"))
             {
               if (!(payload == "!CONT"))
                 return;
               this.SendMessage(new Message("INFO_CLIENT_COUNT", "SERVER", channel.ClientCount.ToString()));
             }
             else
               this.DestroyClient();
           }
           else
             this.UnsubscribeToChannel(channel);
         }
         else
           this.SubscribeToChannel(channel);
       }
       else
       {
         this.SubscribeToChannel(channel);
         // ISSUE: reference to a compiler-generated field
         EventHandler<Message> messageReceived = this.MessageReceived;
         if (messageReceived == null)
           return;
         messageReceived((object) this, e);
       }
     }
   }
 }
Example #10
0
 /// <summary>
 /// 序列化
 /// </summary>
 /// <param name="value">值</param>
 /// <param name="type">返回序列化类型</param>
 /// <param name="compressionThreshold">指定超过长度时启用压缩功能</param>
 /// <returns></returns>
 public static byte[] Serialize(object value, out SerializedType type, uint compressionThreshold)
 {
     byte[] bytes;
     if (value is byte[])
     {
         bytes = (byte[])value;
         type  = SerializedType.ByteArray;
         if (bytes.Length > compressionThreshold)
         {
             bytes = compress(bytes);
             type  = SerializedType.CompressedByteArray;
         }
     }
     else if (value is string)
     {
         bytes = Encoding.UTF8.GetBytes((string)value);
         type  = SerializedType.String;
         if (bytes.Length > compressionThreshold)
         {
             bytes = compress(bytes);
             type  = SerializedType.CompressedString;
         }
     }
     else if (value is DateTime)
     {
         bytes = BitConverter.GetBytes(((DateTime)value).Ticks);
         type  = SerializedType.Datetime;
     }
     else if (value is bool)
     {
         bytes = new byte[] { (byte)((bool)value ? 1 : 0) };
         type  = SerializedType.Bool;
     }
     else if (value is byte)
     {
         bytes = new byte[] { (byte)value };
         type  = SerializedType.Byte;
     }
     else if (value is short)
     {
         bytes = BitConverter.GetBytes((short)value);
         type  = SerializedType.Short;
     }
     else if (value is ushort)
     {
         bytes = BitConverter.GetBytes((ushort)value);
         type  = SerializedType.UShort;
     }
     else if (value is int)
     {
         bytes = BitConverter.GetBytes((int)value);
         type  = SerializedType.Int;
     }
     else if (value is uint)
     {
         bytes = BitConverter.GetBytes((uint)value);
         type  = SerializedType.UInt;
     }
     else if (value is long)
     {
         bytes = BitConverter.GetBytes((long)value);
         type  = SerializedType.Long;
     }
     else if (value is ulong)
     {
         bytes = BitConverter.GetBytes((ulong)value);
         type  = SerializedType.ULong;
     }
     else if (value is float)
     {
         bytes = BitConverter.GetBytes((float)value);
         type  = SerializedType.Float;
     }
     else if (value is double)
     {
         bytes = BitConverter.GetBytes((double)value);
         type  = SerializedType.Double;
     }
     else
     {
         type = SerializedType.ObjectJson;
         Type t = value.GetType();
         switch (StaticTool.GetSystemType(ref t))
         {
         case SysType.Base:
         case SysType.Enum:
         case SysType.Custom:
             if (t.GetCustomAttributes(typeof(SerializableAttribute), false).Length > 0)
             {
                 type = SerializedType.Object;
             }
             break;
         }
         if (type == SerializedType.Object)
         {
             //可序列化 List<object> 如果 object 不支持序列化,会挂。
             using (MemoryStream ms = new MemoryStream())
             {
                 new BinaryFormatter().Serialize(ms, value);
                 bytes = ms.ToArray();
                 if (bytes.Length > compressionThreshold)
                 {
                     bytes = compress(bytes);
                     type  = SerializedType.CompressedObject;
                 }
             }
         }
         else
         {
             string json = JsonHelper.ToJson(value);
             bytes = Encoding.UTF8.GetBytes(json);
             if (bytes.Length > compressionThreshold)
             {
                 bytes = compress(bytes);
                 type  = SerializedType.CompressedObjectJson;
             }
         }
     }
     return(bytes);
 }
Example #11
0
 public uint GetUInt(int field) => BitConverter.ToUInt32(parent.bytes, offset + field * 4);
Example #12
0
        public static object DeSerialize(byte[] bytes, SerializedType type)
        {
            switch (type)
            {
            case SerializedType.String:
                return(Encoding.UTF8.GetString(bytes));

            case SerializedType.Datetime:
                return(new DateTime(BitConverter.ToInt64(bytes, 0)));

            case SerializedType.Bool:
                return(bytes[0] == 1);

            case SerializedType.Byte:
                return(bytes[0]);

            case SerializedType.Short:
                return(BitConverter.ToInt16(bytes, 0));

            case SerializedType.UShort:
                return(BitConverter.ToUInt16(bytes, 0));

            case SerializedType.Int:
                return(BitConverter.ToInt32(bytes, 0));

            case SerializedType.UInt:
                return(BitConverter.ToUInt32(bytes, 0));

            case SerializedType.Long:
                return(BitConverter.ToInt64(bytes, 0));

            case SerializedType.ULong:
                return(BitConverter.ToUInt64(bytes, 0));

            case SerializedType.Float:
                return(BitConverter.ToSingle(bytes, 0));

            case SerializedType.Double:
                return(BitConverter.ToDouble(bytes, 0));

            case SerializedType.Object:
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    return(new BinaryFormatter().Deserialize(ms));
                }

            case SerializedType.ObjectJson:
                return(Encoding.UTF8.GetString(bytes));

            case SerializedType.CompressedByteArray:
                return(DeSerialize(decompress(bytes), SerializedType.ByteArray));

            case SerializedType.CompressedString:
                return(DeSerialize(decompress(bytes), SerializedType.String));

            case SerializedType.CompressedObject:
                return(DeSerialize(decompress(bytes), SerializedType.Object));

            case SerializedType.CompressedObjectJson:
                return(DeSerialize(decompress(bytes), SerializedType.ObjectJson));

            case SerializedType.ByteArray:
            default:
                return(bytes);
            }
        }
Example #13
0
        private void FinishPacket(byte[] packetBuf) {
            Array.Clear(packetBuf, 8, 4);

            uint crcCalc = Crc32Algorithm.Compute(packetBuf);
            Array.Copy(BitConverter.GetBytes((uint)crcCalc), 0, packetBuf, 8, 4);
        }
Example #14
0
        public void NewReportIncoming(Joycon hidReport) {
            if (!running)
                return;

            var clientsList = new List<IPEndPoint>();
            var now = DateTime.UtcNow;
            lock (clients) {
                var clientsToDelete = new List<IPEndPoint>();

                foreach (var cl in clients) {
                    const double TimeoutLimit = 5;

                    if ((now - cl.Value.AllPadsTime).TotalSeconds < TimeoutLimit)
                        clientsList.Add(cl.Key);
                    else if ((hidReport.PadId >= 0 && hidReport.PadId <= 3) &&
                             (now - cl.Value.PadIdsTime[(byte)hidReport.PadId]).TotalSeconds < TimeoutLimit)
                        clientsList.Add(cl.Key);
                    else if (cl.Value.PadMacsTime.ContainsKey(hidReport.PadMacAddress) &&
                             (now - cl.Value.PadMacsTime[hidReport.PadMacAddress]).TotalSeconds < TimeoutLimit)
                        clientsList.Add(cl.Key);
                    else //check if this client is totally dead, and remove it if so
                    {
                        bool clientOk = false;
                        for (int i = 0; i < cl.Value.PadIdsTime.Length; i++) {
                            var dur = (now - cl.Value.PadIdsTime[i]).TotalSeconds;
                            if (dur < TimeoutLimit) {
                                clientOk = true;
                                break;
                            }
                        }
                        if (!clientOk) {
                            foreach (var dict in cl.Value.PadMacsTime) {
                                var dur = (now - dict.Value).TotalSeconds;
                                if (dur < TimeoutLimit) {
                                    clientOk = true;
                                    break;
                                }
                            }

                            if (!clientOk)
                                clientsToDelete.Add(cl.Key);
                        }
                    }
                }

                foreach (var delCl in clientsToDelete) {
                    clients.Remove(delCl);
                }
                clientsToDelete.Clear();
                clientsToDelete = null;
            }

            if (clientsList.Count <= 0)
                return;

            byte[] outputData = new byte[100];
            int outIdx = BeginPacket(outputData, 1001);
            Array.Copy(BitConverter.GetBytes((uint)MessageType.DSUS_PadDataRsp), 0, outputData, outIdx, 4);
            outIdx += 4;

            outputData[outIdx++] = (byte)hidReport.PadId;
            outputData[outIdx++] = (byte)hidReport.constate;
            outputData[outIdx++] = (byte)hidReport.model;
            outputData[outIdx++] = (byte)hidReport.connection;
            {
                byte[] padMac = hidReport.PadMacAddress.GetAddressBytes();
                outputData[outIdx++] = padMac[0];
                outputData[outIdx++] = padMac[1];
                outputData[outIdx++] = padMac[2];
                outputData[outIdx++] = padMac[3];
                outputData[outIdx++] = padMac[4];
                outputData[outIdx++] = padMac[5];
            }

            outputData[outIdx++] = (byte)hidReport.battery;
            outputData[outIdx++] = 1;

            Array.Copy(BitConverter.GetBytes(hidReport.packetCounter), 0, outputData, outIdx, 4);
            outIdx += 4;

            if (!ReportToBuffer(hidReport, outputData, ref outIdx))
                return;
            else
                FinishPacket(outputData);

            foreach (var cl in clientsList) {
                try { udpSock.SendTo(outputData, cl); } catch (SocketException /*e*/) { }
            }
            clientsList.Clear();
            clientsList = null;
        }
Example #15
0
 public char ReadChar()
 {
     byte[] buffer = new byte[2];
     Read(buffer, 0, 2);
     return(BitConverter.ToChar(buffer, 0));
 }
Example #16
0
 /// <summary>
 /// Writes a double field value, without a tag, to the stream.
 /// </summary>
 public static void WriteDouble(ref Span <byte> buffer, ref WriterInternalState state, double value)
 {
     WriteRawLittleEndian64(ref buffer, ref state, (ulong)BitConverter.DoubleToInt64Bits(value));
 }
Example #17
0
 public void WriteBoolean(bool data)
 {
     byte[] buffer = BitConverter.GetBytes(data);
     Write(buffer, 0, buffer.Length);
 }
Example #18
0
 protected TrainerFashion6(byte[] data, int offset)
 {
     data0 = BitConverter.ToUInt32(data, 0 + offset);
     data1 = BitConverter.ToUInt32(data, 4 + offset);
     data2 = BitConverter.ToUInt32(data, 8 + offset);
 }
Example #19
0
        public void readIn(BinaryReader b)
        {
            objPlace = b.BaseStream.Position;
            IndexedInfo idex = new IndexedInfo(b);


          

            //Console.WriteLine("Prado you "+ idex.objectMarker + ":" + idex.lengthOfBody);

          //  foreach (Byte key in idex.recordStore.Keys)
          //  {
            //    Console.WriteLine(key + " KEY");
           // }


           // for (byte i = 0; i < 30; i++)
            //{
             //   Console.WriteLine(i + ": " + idex.getValueAsHexStr(i));
           //     Console.WriteLine(i + ": " + idex.getValueAsString(i));
           // }

            senderMailAddress = idex.getValueAsString(14);
            recvAddress = idex.getValueAsString(19);
            subjectLine = idex.getValueAsString(8);
            dtf = DateTime.FromFileTimeUtc(BitConverter.ToInt64(idex.getValueAsArray(2), 0));


          //  Console.WriteLine();

            try
            {
                if (idex.recordStore.ContainsKey(132))
                    msgPointer = BitConverter.ToInt32(idex.getValueAsArray(132).Reverse().ToArray(), 0);
                else
                {
                    msgPointer = BitConverter.ToInt32(idex.getValueAsArray(4), 0);
                //    Console.WriteLine("URGENT " + BitConverter.ToString(idex.getValueAsArray(4)) + "-" + BitConverter.ToInt32(idex.getValueAsArray(4),0).ToString());
                }
            }
            catch (Exception eeeee)
            { }

          
         //   Console.WriteLine("OBJPOINT " + objPlace);
         //   Console.WriteLine("FROM " + idex.getValueAsString(14));
         //   Console.WriteLine("TO " + idex.getValueAsString(19));
         //   Console.WriteLine("SUBJECT " + idex.getValueAsString(8));




                //  Console.WriteLine("POINTER " + msgPointer.ToString());

               // mainVein = new MessageNode();

            /*
               
            */


               // Console.WriteLine(mainVein.runningText);




            



           /* try
            //{
                
                    
                    //      BitConverter.ToString(idex.getValueAsArray(132)));
                byte[] brah = { 0, 1, 0x5c, 0x44};
                brah = brah.Reverse().ToArray();
                Console.WriteLine(BitConverter.ToInt32(brah,0).ToString());
           }
            catch (Exception eeee)
            {
            }
            idex.findKey(0);
            */

            Program.messages.Add(this);
            Program.mCount++;

        }
Example #20
0
 public void Write(byte[] data, int offset)
 {
     BitConverter.GetBytes(data0).CopyTo(data, 0 + offset);
     BitConverter.GetBytes(data1).CopyTo(data, 4 + offset);
     BitConverter.GetBytes(data2).CopyTo(data, 8 + offset);
 }
    public void TestToUInt16() {
      UInt16 expected = BitConverter.ToUInt16(_bytes, 0);
      UInt16 actual = BitConverterNonAlloc.ToUInt16(_bytes, 0);

      Assert.That(actual, Is.EqualTo(expected));
    }
Example #22
0
 public int ReadInt()
 {
     byte[] buffer = new byte[4];
     Read(buffer, 0, 4);
     return(BitConverter.ToInt32(buffer, 0));
 }
Example #23
0
 private static Int64 GetRandomLong()
 {
     byte[] buffer = new byte[sizeof(Int64)];
     rand.NextBytes(buffer);
     return(Math.Abs(BitConverter.ToInt64(buffer, 0)));
 }
Example #24
0
 public void WriteFloat(float data)
 {
     byte[] buffer = BitConverter.GetBytes(data);
     Write(buffer, 0, buffer.Length);
 }
 public static long GetAddress(this IPAddress thisObj)
 {
     byte[] addressBytes = thisObj.GetAddressBytes();
     Debug.Assert(addressBytes.Length == 4);
     return((long)BitConverter.ToInt32(addressBytes, 0));
 }
Example #26
0
 public float ReadFloat()
 {
     byte[] buffer = new byte[4];
     Read(buffer, 0, 4);
     return(BitConverter.ToSingle(buffer, 0));
 }
Example #27
0
 public PathNode(PCCObject Pcc, int Index)
 {
     pcc = Pcc;
     MyIndex = Index;
     if (pcc.isExport(Index))
         data = pcc.Exports[Index].Data;
     Props = PropertyReader.getPropList(pcc, data);
     BitConverter.IsLittleEndian = true;
     foreach (PropertyReader.Property p in Props)
         switch (pcc.getNameEntry(p.Name))
         {
             #region
             case "bHasCrossLevelPaths":
                 if (p.raw[p.raw.Length - 1] == 1)
                     bHasCrossLevelPaths = true;
                 break;
             case "bPathsChanged":
                 if (p.raw[p.raw.Length - 1] == 1)
                     bPathsChanged = true;
                 break;
             case "bOneWayPath":
                 if (p.raw[p.raw.Length - 1] == 1)
                     bOneWayPath = true;
                 break;
             case "Tag":
                 Tag = p.Value.IntValue;
                 break;
             case "Group":
                 Group = p.Value.IntValue;
                 break;
             case "nextNavigationPoint":
                 nextNavigationPoint = p.Value.IntValue;
                 break;
             case "CylinderComponent":
                 CylinderComponent = p.Value.IntValue;
                 break;
             case "Base":
                 Base = p.Value.IntValue;
                 break;
             case "CollisionComponent":
                 CollisionComponent = p.Value.IntValue;
                 break;
             case "DrawScale":
                 DrawScale = BitConverter.ToSingle(p.raw, p.raw.Length - 4);
                 break;
             case "visitedWeight":
                 visitedWeight = p.Value.IntValue;
                 break;
             case "bestPathWeight":
                 bestPathWeight = p.Value.IntValue;
                 break;
             case "NetworkID":
                 NetworkID = p.Value.IntValue;
                 break;
             case "ApproximateLineOfFire":
                 ApproximateLineOfFire = p.Value.IntValue;
                 break;
             case "Cost":
                 Cost = p.Value.IntValue;
                 break;
             case "ExtraCost":
                 ExtraCost = p.Value.IntValue;
                 break;
             case "location":
                 location = new Vector3(BitConverter.ToSingle(p.raw, p.raw.Length - 12),
                                       BitConverter.ToSingle(p.raw, p.raw.Length - 8),
                                       BitConverter.ToSingle(p.raw, p.raw.Length - 4));
                 break;
             #endregion
         }
     MyMatrix = Matrix.Translation(location);
     GenerateMesh();
 }
Example #28
0
 public void WriteChar(char data)
 {
     byte[] buffer = BitConverter.GetBytes(data);
     Write(buffer, 0, buffer.Length);
 }
Example #29
0
        // Function that returns a boolean value depending on whether or not the user's details match the details in tblUsers
        private bool getIsAuthenticated(SqlConnection connection, string username, string password)
        {
            // Opens a new connection if there isn't already a connection open (this just makes sure an error relating to no connection being open won't occur)
            if (connection.State != ConnectionState.Open) connection.Open();

            // Creates a new object called command that can allow SQL code to be run
            using (SqlCommand command = new SqlCommand())
            {
                // Initialises the connection
                command.Connection = connection;

                // A SQL query that authenticates the user and decides whether or not the user is an admin
                command.CommandText = @"
SELECT *
FROM tblUsers
WHERE username = @username;
";
                command.Parameters.AddWithValue("@username", username_textbox.Text);

                // Runs the SQL code and stores the generated table in the reader
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    // Creates a new boolean variable called match, which is initialised to false
                    bool match = false;
                    
                    // Tries to find a match for username and password in tblUsers and returns true if found and false if not found
                    while (reader.Read())
                    {
                        // TEST FOR AN OLD VERSION OF THE CODE THAT DIDN'T WORK
                        // MessageBox.Show(reader.GetString(2));
                        // MessageBox.Show(getSaltedHash(password, Encoding.UTF8.GetBytes(reader.GetString(2))));
                        // MessageBox.Show(getSaltedHash(password, salt));

                        // Initialises two new byte arrays that will store the values of hPassword and salt from tblUsers
                        byte[] hPassword = new byte[UserLogin.hPasswordLength];
                        byte[] salt = new byte[UserLogin.saltLength];
                        reader.GetBytes(2, 0, hPassword, 0, UserLogin.hPasswordLength);
                        reader.GetBytes(3, 0, salt, 0, UserLogin.saltLength);

                        // Compares the the username entered with the one in the database and compares the hex value of the hashed password entered with the hex value of the hashed password stored in the database
                        if (reader.GetString(1) == username && BitConverter.ToString(hPassword) == BitConverter.ToString(getSaltedHash(password, salt)))
                        {
                            match = true;

                            // Sets the global variable userID to be the userID of the user
                            Program.userID = reader.GetString(0);

                            // Sets the boolean variable admin to true if the user is an admin
                            if (reader.GetBoolean(4) == true) admin = true;
                        }
                    }

                    // Clears the parameters
                    command.Parameters.Clear();

                    // Returns a boolean value
                    return match;
                }
            }
        }
Example #30
0
        private void ProcessIncoming(byte[] localMsg, IPEndPoint clientEP) {
            try {
                int currIdx = 0;
                if (localMsg[0] != 'D' || localMsg[1] != 'S' || localMsg[2] != 'U' || localMsg[3] != 'C')
                    return;
                else
                    currIdx += 4;

                uint protocolVer = BitConverter.ToUInt16(localMsg, currIdx);
                currIdx += 2;

                if (protocolVer > MaxProtocolVersion)
                    return;

                uint packetSize = BitConverter.ToUInt16(localMsg, currIdx);
                currIdx += 2;

                if (packetSize < 0)
                    return;

                packetSize += 16; //size of header
                if (packetSize > localMsg.Length)
                    return;
                else if (packetSize < localMsg.Length) {
                    byte[] newMsg = new byte[packetSize];
                    Array.Copy(localMsg, newMsg, packetSize);
                    localMsg = newMsg;
                }

                uint crcValue = BitConverter.ToUInt32(localMsg, currIdx);
                //zero out the crc32 in the packet once we got it since that's whats needed for calculation
                localMsg[currIdx++] = 0;
                localMsg[currIdx++] = 0;
                localMsg[currIdx++] = 0;
                localMsg[currIdx++] = 0;

                uint crcCalc = Crc32Algorithm.Compute(localMsg);
                if (crcValue != crcCalc)
                    return;

                uint clientId = BitConverter.ToUInt32(localMsg, currIdx);
                currIdx += 4;

                uint messageType = BitConverter.ToUInt32(localMsg, currIdx);
                currIdx += 4;

                if (messageType == (uint)MessageType.DSUC_VersionReq) {
                    byte[] outputData = new byte[8];
                    int outIdx = 0;
                    Array.Copy(BitConverter.GetBytes((uint)MessageType.DSUS_VersionRsp), 0, outputData, outIdx, 4);
                    outIdx += 4;
                    Array.Copy(BitConverter.GetBytes((ushort)MaxProtocolVersion), 0, outputData, outIdx, 2);
                    outIdx += 2;
                    outputData[outIdx++] = 0;
                    outputData[outIdx++] = 0;

                    SendPacket(clientEP, outputData, 1001);
                } else if (messageType == (uint)MessageType.DSUC_ListPorts) {
                    // Requested information on gamepads - return MAC address
                    int numPadRequests = BitConverter.ToInt32(localMsg, currIdx);
                    currIdx += 4;
                    if (numPadRequests < 0 || numPadRequests > 4)
                        return;

                    int requestsIdx = currIdx;
                    for (int i = 0; i < numPadRequests; i++) {
                        byte currRequest = localMsg[requestsIdx + i];
                        if (currRequest < 0 || currRequest > 4)
                            return;
                    }

                    byte[] outputData = new byte[16];
                    for (byte i = 0; i < numPadRequests; i++) {
                        byte currRequest = localMsg[requestsIdx + i];
                        var padData = controllers[i];//controllers[currRequest];

                        int outIdx = 0;
                        Array.Copy(BitConverter.GetBytes((uint)MessageType.DSUS_PortInfo), 0, outputData, outIdx, 4);
                        outIdx += 4;

                        outputData[outIdx++] = (byte)padData.PadId;
                        outputData[outIdx++] = (byte)padData.constate;
                        outputData[outIdx++] = (byte)padData.model;
                        outputData[outIdx++] = (byte)padData.connection;

                        var addressBytes = padData.PadMacAddress.GetAddressBytes();
                        if (addressBytes.Length == 6) {
                            outputData[outIdx++] = addressBytes[0];
                            outputData[outIdx++] = addressBytes[1];
                            outputData[outIdx++] = addressBytes[2];
                            outputData[outIdx++] = addressBytes[3];
                            outputData[outIdx++] = addressBytes[4];
                            outputData[outIdx++] = addressBytes[5];
                        } else {
                            outputData[outIdx++] = 0;
                            outputData[outIdx++] = 0;
                            outputData[outIdx++] = 0;
                            outputData[outIdx++] = 0;
                            outputData[outIdx++] = 0;
                            outputData[outIdx++] = 0;
                        }

                        outputData[outIdx++] = (byte)padData.battery;//(byte)padData.BatteryStatus;
                        outputData[outIdx++] = 0;

                        SendPacket(clientEP, outputData, 1001);
                    }
                } else if (messageType == (uint)MessageType.DSUC_PadDataReq) {
                    byte regFlags = localMsg[currIdx++];
                    byte idToReg = localMsg[currIdx++];
                    PhysicalAddress macToReg = null;
                    {
                        byte[] macBytes = new byte[6];
                        Array.Copy(localMsg, currIdx, macBytes, 0, macBytes.Length);
                        currIdx += macBytes.Length;
                        macToReg = new PhysicalAddress(macBytes);
                    }

                    lock (clients) {
                        if (clients.ContainsKey(clientEP))
                            clients[clientEP].RequestPadInfo(regFlags, idToReg, macToReg);
                        else {
                            var clientTimes = new ClientRequestTimes();
                            clientTimes.RequestPadInfo(regFlags, idToReg, macToReg);
                            clients[clientEP] = clientTimes;
                        }
                    }
                }
            } catch (Exception /*e*/) { }
        }