예제 #1
0
        private void hidDeviceOnReceiveBytes(byte[] bytes)
        {
            bool isAuthenticated;
            var  data = CommunicationProtocol.GetData(bytes, out isAuthenticated);

            if (data == null)
            {
                return;
            }

            var text   = BytesConverter.GetString(data);
            var status = isAuthenticated ? ReceiveDataAuthenticatedStatus.Authenticated : ReceiveDataAuthenticatedStatus.NotAuthenticated;

            ReceiveText?.Invoke(text, status);
        }
예제 #2
0
        private static async Task WriteExamples(IExamples examples)
        {
            var targetPath = examples.Path;

            if (!Directory.Exists(targetPath))
            {
                Console.WriteLine($"Createing directory {targetPath}");
                Directory.CreateDirectory(targetPath);
            }

            var messages = examples.Build();

            var markdownPath = Path.Combine(targetPath, "Examples.md");

            using (var fs = File.Open(markdownPath, FileMode.Create, FileAccess.Write)) {
                using (var sw = new StreamWriter(fs, Encoding.UTF8)) {
                    await sw.WriteLineAsync("| File | Json | Binary |");

                    await sw.WriteLineAsync("|------|------|--------|");

                    foreach (var kvp in messages)
                    {
                        var jsonPath = Path.Combine(targetPath, $"{kvp.Key}.json");
                        kvp.Value.WriteJson(jsonPath, true).Wait();

                        long jsonSize;
                        using (var ms = new MemoryStream()) {
                            kvp.Value.WriteJson(ms, false).Wait();
                            jsonSize = ms.Length;
                        }
                        Console.WriteLine($"Wrote {jsonPath}");

                        var binPath = Path.Combine(targetPath, $"{kvp.Key}.bin");
                        kvp.Value.WriteBinary(binPath);
                        var binSize = new FileInfo(binPath).Length;
                        Console.WriteLine($"Wrote {binPath}");

                        await sw.WriteLineAsync($"| {kvp.Key} | [{BytesConverter.ToReadableString(jsonSize)}]({jsonPath.Substring(DocsPath.Length + 1).Replace("\\", "/")} ':ignore') | [{BytesConverter.ToReadableString(binSize)}]({binPath.Substring(DocsPath.Length + 1).Replace("\\", "/")} ':ignore') |");
                    }
                }
            }

            Console.WriteLine($"Wrote {markdownPath}");
        }
예제 #3
0
        /// <summary>
        /// Creates a new entry for the <see cref="ZipWriteOnlyStorer"></see>.
        /// </summary>
        /// <param name="path"> Path to the data. </param>
        /// <param name="size"> Size of the data. </param>
        /// <param name="compressionMethod"> Compression method for the data. </param>
        /// <param name="compressedSize"> Size of the compressed data. </param>
        /// <param name="headerOffset"> Offset of header information. </param>
        /// <param name="crc32"> 32-bit checksum of the data. </param>
        /// <param name="modifyTime"> Modification time of the data. </param>
        /// <param name="comment"> User comment for the data. </param>
        public ZipWriteOnlyStorerEntry(string path, uint size, CompressionMethod compressionMethod, uint compressedSize, uint headerOffset, uint crc32, DateTime modifyTime, string comment) : base(path, compressionMethod, compressedSize, headerOffset, crc32, modifyTime, comment)
        {
            this.PathAsBytes       = utf8Encoding.GetBytes(path);
            this.PathLengthAsBytes = BytesConverter.GetBytes((ushort)this.PathAsBytes.Length);

            this.CommentAsBytes       = utf8Encoding.GetBytes(comment);
            this.CommentLengthAsBytes = BytesConverter.GetBytes((ushort)this.CommentAsBytes.Length);

            this.CompressionMethodAsBytes = BytesConverter.GetBytes((ushort)compressionMethod);
            this.ModifyTimeAsBytes        = BytesConverter.GetBytes(ZipStorerUtils.DateTimeToDosTime(modifyTime));
            this.CRC32AsBytes             = BytesConverter.GetBytes(crc32);

            this.CompressedSizeAsBytes = BytesConverter.GetBytes(compressedSize >= 0xFFFFFFFF ? 0xFFFFFFFF : compressedSize);
            this.SizeAsBytes           = BytesConverter.GetBytes(size >= 0xFFFFFFFF ? 0xFFFFFFFF : size);
            this.HeaderOffsetAsBytes   = BytesConverter.GetBytes(headerOffset >= 0xFFFFFFFF ? 0xFFFFFFFF : (uint)headerOffset);

            this.CompressedSizeZip64AsBytes = BytesConverter.GetBytes(compressedSize);
            this.SizeZip64AsBytes           = BytesConverter.GetBytes(size);
            this.HeaderOffsetZip64AsBytes   = BytesConverter.GetBytes(headerOffset);
        }
예제 #4
0
        public bool UpdateGambleStoneRoundInfo(GambleStoneRoundInfo round, CustomerMySqlTransaction myTrans)
        {
            MySqlCommand mycmd = null;

            try
            {
                mycmd = myTrans.CreateCommand();
                string sqlText = "update gamblestoneroundinfo set `StartTime`=@StartTime,`FinishedInningCount`=@FinishedInningCount,`EndTime`=@EndTime,`CurrentWinRedCount`=@CurrentWinRedCount," +
                                 "`CurrentWinGreenCount`=@CurrentWinGreenCount,`CurrentWinBlueCount`=@CurrentWinBlueCount,`CurrentWinPurpleCount`=@CurrentWinPurpleCount,`LastWinRedCount`=@LastWinRedCount," +
                                 "`LastWinGreenCount`=@LastWinGreenCount,`LastWinBlueCount`=@LastWinBlueCount,`LastWinPurpleCount`=@LastWinPurpleCount,`AllBetInStone`=@AllBetInStone," +
                                 "`AllWinnedOutStone`=@AllWinnedOutStone,`WinColorItems`=@WinColorItems,`TableName`=@TableName " +
                                 " where `id`=@id ";
                mycmd.CommandText = sqlText;
                mycmd.Parameters.AddWithValue("@StartTime", round.StartTime.ToDateTime());
                mycmd.Parameters.AddWithValue("@FinishedInningCount", round.FinishedInningCount);
                mycmd.Parameters.AddWithValue("@EndTime", round.EndTime == null ? DBNull.Value : (object)round.EndTime.ToDateTime());
                mycmd.Parameters.AddWithValue("@CurrentWinRedCount", round.CurrentWinRedCount);
                mycmd.Parameters.AddWithValue("@CurrentWinGreenCount", round.CurrentWinGreenCount);
                mycmd.Parameters.AddWithValue("@CurrentWinBlueCount", round.CurrentWinBlueCount);
                mycmd.Parameters.AddWithValue("@CurrentWinPurpleCount", round.CurrentWinPurpleCount);
                mycmd.Parameters.AddWithValue("@LastWinRedCount", round.LastWinRedCount);
                mycmd.Parameters.AddWithValue("@LastWinGreenCount", round.LastWinGreenCount);
                mycmd.Parameters.AddWithValue("@LastWinBlueCount", round.LastWinBlueCount);
                mycmd.Parameters.AddWithValue("@LastWinPurpleCount", round.LastWinPurpleCount);
                mycmd.Parameters.AddWithValue("@AllBetInStone", round.AllBetInStone);
                mycmd.Parameters.AddWithValue("@AllWinnedOutStone", round.AllWinnedOutStone);
                mycmd.Parameters.AddWithValue("@WinColorItems", BytesConverter.ConvertByteArrayToBytes(round.WinColorItems));
                mycmd.Parameters.AddWithValue("@TableName", round.TableName);
                mycmd.Parameters.AddWithValue("@id", round.ID);

                mycmd.ExecuteNonQuery();
                return(true);
            }
            finally
            {
                if (mycmd != null)
                {
                    mycmd.Dispose();
                }
            }
        }
예제 #5
0
        public EnrollmentJob()
        {
            ComputerInfo computerInfo = new ComputerInfo();
            string       systemName   = Environment.MachineName;
            string       osName       = computerInfo.OSFullName;
            string       version      = computerInfo.OSVersion;

            string macAddr = (
                from nic in NetworkInterface.GetAllNetworkInterfaces()
                where nic.OperationalStatus == OperationalStatus.Up
                select nic.GetPhysicalAddress().ToString()
                ).FirstOrDefault();
            string processor = "";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor");

            foreach (ManagementObject mo in searcher.Get())
            {
                processor = mo["Name"].ToString();
            }
            string motherboard = "";

            searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BaseBoard");
            foreach (ManagementObject mo in searcher.Get())
            {
                motherboard = mo["Manufacturer"].ToString();
            }
            string ram = BytesConverter.ConvertToSize(computerInfo.TotalPhysicalMemory, BytesConverter.SizeUnits.GB);

            _registerModel = new EnrollmentModel
            {
                SystemName  = systemName,
                OsName      = osName,
                Version     = version,
                MAC         = macAddr,
                Processor   = processor,
                MotherBoard = motherboard,
                RAM         = ram
            };
        }
예제 #6
0
        public IEnumerable <IFrameable> Create(string fileName)
        {
            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                using (var br = new BinaryReader(fs))
                {
                    var frames = new List <IldFrame>();
                    while (true)
                    {
                        var header = new IldHeader(BytesConverter.ByteToType <IldHeaderRaw>(br));

                        if (header.FormatCode != 0)
                        {
                            return(frames);
                        }

                        if (header.TotalPoints == 0 || header.FrameNumber == header.TotalFrames)
                        {
                            return(frames);
                        }

                        var records = new List <IldRecord>();
                        while (true)
                        {
                            var record = new IldRecord(BytesConverter.ByteToType <IldRecordRaw>(br));
                            if (record.IsLast)
                            {
                                break;
                            }
                            records.Add(record);
                        }

                        var frame = new IldFrame(header, records, Transformation);
                        frames.Add(frame);
                    }
                }
            }
        }
예제 #7
0
        /// <summary>
        /// 解构808消息
        /// </summary>
        private void SplitMessage()
        {
            //定义消息各部分的长度
            uint msgStartTagLength = 1, msgHeadLength = 12, msgBodyLength, msgCheckCodeLength = 1, msgEndTagLength = 1;

            try
            {
                BytesConverter iBytesConverter = new BytesConverter();

                //获取起始标识位msgStartTag
                MsgStartTag = new byte[msgStartTagLength];
                Array.Copy(msgHex, 0, MsgStartTag, 0, msgStartTagLength);

                //获取消息头msgHead
                MsgHead = new byte[msgHeadLength];
                Array.Copy(msgHex, msgStartTagLength, MsgHead, 0, msgHeadLength);

                //获取消息体的长度msgBodyLength,单位bytes
                msgBodyLength = iBytesConverter.ToUShort(MsgHead, 2);
                msgBodyLength = msgBodyLength & 0x03FF;

                //获取消息体msgBody
                MsgBody = new byte[msgBodyLength];
                Array.Copy(msgHex, msgStartTagLength + msgHeadLength, MsgBody, 0, msgBodyLength);

                //获取校验码msgCheckCode
                MsgCheckCodeag = new byte[msgCheckCodeLength];
                Array.Copy(msgHex, msgStartTagLength + msgHeadLength + msgBodyLength, MsgCheckCodeag, 0, msgCheckCodeLength);

                //获取结束标识位msgEndTag
                MsgEndTag = new byte[msgEndTagLength];
                Array.Copy(msgHex, msgStartTagLength + msgHeadLength + msgBodyLength + msgCheckCodeLength, MsgEndTag, 0, msgEndTagLength);
            }
            catch (Exception e)
            {
                throw new Exception($"SplitMessage函数异常-> {e.Message}");
            }
        }
예제 #8
0
        private byte[] msgHex; //十六进制格式
        #endregion

        /// <summary>
        /// PreProcess
        /// </summary>
        /// <param name="input"></param>
        public PreProcess(string input)
        {
            try
            {
                msg = input;
                BytesConverter  iBytesConverter  = new BytesConverter();
                StringConverter iStringConverter = new StringConverter();

                //检验整条消息的合法性:
                VerifyEntireMessage();

                //将消息转换为字节数组
                msgHex = iStringConverter.ToByteArray(msg, 16);

                //还原转义
                RestoreMessage();

                //解构消息
                SplitMessage();

                //提取消息ID
                MsgId = iBytesConverter.ToUShort(MsgHead, 0);

                //打印结果
                Console.WriteLine("\n---消息解构------------------");
                Console.WriteLine("{0}:{1}", nameof(MsgStartTag), BitConverter.ToString(MsgStartTag).Replace("-", string.Empty));
                Console.WriteLine("{0}:{1}", nameof(MsgHead), BitConverter.ToString(MsgHead).Replace("-", string.Empty));
                Console.WriteLine("{0}:{1}", nameof(MsgBody), BitConverter.ToString(MsgBody).Replace("-", string.Empty));
                Console.WriteLine("{0}:{1}", nameof(MsgCheckCodeag), BitConverter.ToString(MsgCheckCodeag).Replace("-", string.Empty));
                Console.WriteLine("{0}:{1}", nameof(MsgEndTag), BitConverter.ToString(MsgEndTag).Replace("-", string.Empty));
            }
            catch (Exception e)
            {
                throw new Exception($"异常类:{this.GetType().FullName}\n消息内容:{input}\n失败原因:{e.Message}");
            }
        }
예제 #9
0
 public void ToUInt32WithOffset_4Bytes_MaxUInt32()
 {
     byte[] data = new byte[] { 0, 0, 0, 255, 255, 255, 255 };
     Assert.AreEqual(uint.MaxValue, BytesConverter.ToUInt32(data, 3));
 }
 public ConverterFactory(ImageConverter imageConverter, BytesConverter bytesConverter)
 {
     _imageConverter = imageConverter;
     _bytesConverter = bytesConverter;
 }
예제 #11
0
 public void ToInt32BigEndianWithOffset_4Bytes_MaxInt32()
 {
     byte[] data = new byte[] { 0, 0, 0, 127, 255, 255, 255 };
     Assert.AreEqual(int.MaxValue, BytesConverter.ToInt32BigEndian(data, 3));
 }
예제 #12
0
        public void InitializeByteViewerContextMenu()
        {
            Func <byte[]> GetSelectedBytes = () =>
            {
                byte[] buffer = new byte[ByteViewer.SelectionLength];
                for (long i = ByteViewer.SelectionStart, j = 0; i < ByteViewer.SelectionStart + ByteViewer.SelectionLength; i++, j++)
                {
                    buffer[j] = ByteViewer.ByteProvider.ReadByte(i);
                }

                return(buffer);
            };

            Func <string, RoutedEventHandler, MenuItem> NewMenuItem = (menuItemHeader, clickEvent) =>
            {
                MenuItem menuItem = new MenuItem {
                    Header = menuItemHeader
                };
                menuItem.Click += clickEvent;
                return(menuItem);
            };

            if (ByteViewerContextMenu == null)
            {
                ByteViewerContextMenu = new ContextMenu();

                /* COPY SUBMENU BEGIN */

                MenuItem copyMenuItem = new MenuItem {
                    Header = "Copy"
                };

                copyMenuItem.Items.Add(NewMenuItem("Decimal Bytes", (sender, e) =>
                {
                    byte[] buffer = GetSelectedBytes();
                    if (buffer.Length > 0)
                    {
                        Clipboard.SetText(new BytesConverter(buffer).ToDecimalString());
                    }
                }));

                copyMenuItem.Items.Add(new Separator());

                copyMenuItem.Items.Add(NewMenuItem("Hexadecimal Bytes", (sender, e) =>
                {
                    //ok
                    byte[] buffer = GetSelectedBytes();
                    if (buffer.Length > 0)
                    {
                        Clipboard.SetText(new BytesConverter(buffer).ToHexadecimalString(String.Empty));
                    }
                }));

                copyMenuItem.Items.Add(NewMenuItem("Hexadecimal Bytes (\\x00)", (sender, e) =>
                {
                    //ok
                    byte[] buffer = GetSelectedBytes();
                    if (buffer.Length > 0)
                    {
                        Clipboard.SetText(new BytesConverter(buffer).ToHexadecimalString("\\x"));
                    }
                }));

                copyMenuItem.Items.Add(NewMenuItem("Hexadecimal Bytes (0x00)", (sender, e) =>
                {
                    //ok
                    byte[] buffer = GetSelectedBytes();
                    if (buffer.Length > 0)
                    {
                        Clipboard.SetText(new BytesConverter(buffer).ToHexadecimalString("0x"));
                    }
                }));

                copyMenuItem.Items.Add(NewMenuItem("Hexadecimal Bytes (Formatted)", (sender, e) =>
                {
                    ByteViewer.CopyHex();
                }));

                copyMenuItem.Items.Add(new Separator());

                copyMenuItem.Items.Add(NewMenuItem("Hexadecimal Words (2 Bytes)", (sender, e) =>
                {
                    byte[] buffer = GetSelectedBytes();
                    if (buffer.Length > 0 && buffer.Length % 2 == 0)
                    {
                        Clipboard.SetText(new BytesConverter(buffer).ToHexadecimalString(2));
                    }
                }));

                copyMenuItem.Items.Add(NewMenuItem("Hexadecimal Dwords (4 Bytes)", (sender, e) =>
                {
                    //ok
                    byte[] buffer = GetSelectedBytes();
                    if (buffer.Length > 0 && buffer.Length % 4 == 0)
                    {
                        Clipboard.SetText(new BytesConverter(buffer).ToHexadecimalString(4));
                    }
                }));

                copyMenuItem.Items.Add(NewMenuItem("Hexadecimal Qwords (8 Bytes)", (sender, e) =>
                {
                    //ok
                    byte[] buffer = GetSelectedBytes();
                    if (buffer.Length > 0 && buffer.Length % 8 == 0)
                    {
                        Clipboard.SetText(new BytesConverter(buffer).ToHexadecimalString(8));
                    }
                }));

                copyMenuItem.Items.Add(new Separator());

                copyMenuItem.Items.Add(NewMenuItem("String (Ascii)", (sender, e) =>
                {
                    //ok
                    byte[] buffer = GetSelectedBytes();
                    if (buffer.Length > 0)
                    {
                        Clipboard.SetText(Encoding.ASCII.GetString(buffer));
                    }
                }));

                copyMenuItem.Items.Add(NewMenuItem("String (Utf-8)", (sender, e) =>
                {
                    //ok
                    byte[] buffer = GetSelectedBytes();
                    if (buffer.Length > 0)
                    {
                        Clipboard.SetText(Encoding.UTF8.GetString(buffer));
                    }
                }));

                copyMenuItem.Items.Add(new Separator());

                copyMenuItem.Items.Add(NewMenuItem("Address", (sender, e) =>
                {
                    string address = ByteViewer.SelectionStart.ToString("X8");
                    if (ByteViewer.SelectionLength > 1)
                    {
                        address += "-" + (ByteViewer.SelectionStart + ByteViewer.SelectionLength).ToString("X8");
                    }

                    Clipboard.SetText(address);
                }));


                /* COPY SUBMENU END */

                ByteViewerContextMenu.Items.Add(copyMenuItem);

                ByteViewerContextMenu.Items.Add(NewMenuItem("Paste", (sender, e) =>
                {
                    ByteViewer.PasteHex();
                }));

                ByteViewerContextMenu.Items.Add(new Separator());

                ByteViewerContextMenu.Items.Add(NewMenuItem("Insert Hexadecimal Bytes...", (sender, e) =>
                {
                    long index = ByteViewer.SelectionStart;
                    if (index >= 0)
                    {
                        string bytes = InputWindow.InputBox("Hexadecimal Bytes: ", "Binary Engine: Insert Hexadecimal Bytes");
                        if (bytes.Length > 0 && !String.IsNullOrEmpty(bytes))
                        {
                            ByteViewer.ByteProvider.InsertBytes(index, BytesConverter.StringToBytes(bytes));
                            ByteViewer.Refresh();
                        }
                    }
                }));

                ByteViewerContextMenu.Items.Add(NewMenuItem("Insert String...", (sender, e) =>
                {
                    long index = ByteViewer.SelectionStart;
                    if (index >= 0)
                    {
                        string data = InputWindow.InputBox("String: ", "Binary Engine: Insert String");
                        if (data.Length > 0 && !String.IsNullOrEmpty(data))
                        {
                            ByteViewer.ByteProvider.InsertBytes(index, Encoding.ASCII.GetBytes(data));
                            ByteViewer.Refresh();
                        }
                    }
                }));

                ByteViewerContextMenu.Items.Add(new Separator());

                ByteViewerContextMenu.Items.Add(NewMenuItem("Separator Group Size", (sender, e) =>
                {
                    string m = InputWindow.InputBox("Size: ", "Binary Engine: Separator Group Size", ByteViewer.GroupSize.ToString());
                    if (int.TryParse(m, out int n))
                    {
                        if (n % 2 == 0)
                        {
                            ByteViewer.GroupSize = n;
                        }
                    }
                }));

                ByteViewerContextMenu.Items.Add(new Separator());

                ByteViewerContextMenu.Items.Add(NewMenuItem("Select All", (sender, e) => { ByteViewer.SelectAll(); }));
            }
        }
예제 #13
0
 public IldHeader(IldHeaderRaw raw)
 {
     Raw        = raw;
     _converter = new BytesConverter(raw.Data);
 }
예제 #14
0
 public void ToUInt16WithOffset_2Bytes_HalfMaxUInt16()
 {
     byte[] data = new byte[] { 0, 0, 255, 127 };
     Assert.AreEqual(ushort.MaxValue / 2, BytesConverter.ToUInt16(data, 2));
 }
예제 #15
0
        /// <inheritdoc/>
        public byte[] Close()
        {
            // Writes the central directory header
            ulong centralOffset = (ulong)this.zipFileWriter.Position;
            ulong centralSize   = 0;

            long position = 0;

            for (var node = this.entries.First; node != null; node = node.Next)
            {
                position = this.zipFileWriter.Position;
                this.WriteFileHeader(this.zipFileWriter, node.Value, true);
                centralSize += (ulong)(this.zipFileWriter.Position - position);
            }

            ulong dirOffset = (ulong)this.zipFileWriter.Position;

            byte[] encodedComment = utf8Encoding.GetBytes(this.comment);

            if (this.isZip64)
            {
                // Writes a ZIP64 end of central directory record (56 bytes)

                byte[] countBytes = BytesConverter.GetBytes((ulong)this.entries.Count);

                this.zipFileWriter.WriteBytes(zip64EndOfCentralDirRecordSignatureBytes); // 4 bytes, ZIP64 end of central dir signature
                this.zipFileWriter.WriteBytes(fourtyFour8Bytes);                         // 8 bytes, size of ZIP64 end of central directory record. Size = SizeOfFixedFields + SizeOfVariableData - 12.
                this.zipFileWriter.WriteBytes(fourtyFive2Bytes);                         // 2 bytes, version made by
                this.zipFileWriter.WriteBytes(fourtyFive2Bytes);                         // 2 bytes, version needed to extract
                this.zipFileWriter.WriteBytes(zero4Bytes);                               // 4 bytes, number of this disk
                this.zipFileWriter.WriteBytes(zero4Bytes);                               // 4 bytes, number of the disk with the start of the central directory
                this.zipFileWriter.WriteBytes(countBytes);                               // 8 bytes, total number of entries in the central directory on this disk
                this.zipFileWriter.WriteBytes(countBytes);                               // 8 bytes, total number of entries in the central directory
                this.zipFileWriter.WriteBytes(BytesConverter.GetBytes(centralSize));     // 8 bytes, size of the central directory
                this.zipFileWriter.WriteBytes(BytesConverter.GetBytes(centralOffset));   // 8 bytes, offset of start of central directory with respect to the starting disk number

                // Writes the ZIP64 end of central directory locator (20 bytes)
                this.zipFileWriter.WriteBytes(zip64EndOfCentralDirLocatorSignatureBytes); // 4 bytes, ZIP64 end of central dir locator signature
                this.zipFileWriter.WriteBytes(zero4Bytes);                                // 4 bytes, number of the disk with the start of the zip64 end of central directory
                this.zipFileWriter.WriteBytes(BytesConverter.GetBytes(dirOffset));        // 8 bytes, relative offset of the zip64 end of central directory record
                this.zipFileWriter.WriteBytes(one4Bytes);                                 // 4 bytes, total number of disks
            }

            // Writes the end of central directory record (22 bytes)
            this.zipFileWriter.WriteBytes(endOfCentralDirRecordSignatureBytes); // 4 bytes, end of central dir signature
            this.zipFileWriter.WriteBytes(zero2Bytes);                          // 2 bytes, number of this disk
            this.zipFileWriter.WriteBytes(zero2Bytes);                          // 2 bytes, number of the disk with the start of the central directory

            if (isZip64)
            {
                this.zipFileWriter.WriteBytes(zip64EndOfCentralDirectoryDataPart); // 2 + 2 + 4 + 4 = 12 bytes, total number of entries in the central directory on this disk (2),total number of entries in the central directory (2), size of the central directory (4), offset of start of central directory with respect to the starting disk number (4)
            }
            else
            {
                byte[] countBytes = BytesConverter.GetBytes((ushort)this.entries.Count);

                this.zipFileWriter.WriteBytes(countBytes);                                   // 2 bytes, total number of entries in the central directory on this disk
                this.zipFileWriter.WriteBytes(countBytes);                                   // 2 bytes, total number of entries in the central directory
                this.zipFileWriter.WriteBytes(BytesConverter.GetBytes((uint)centralSize));   // 4 bytes, size of the central directory
                this.zipFileWriter.WriteBytes(BytesConverter.GetBytes((uint)centralOffset)); // 4 bytes, offset of start of central directory with respect to the starting disk number
            }

            this.zipFileWriter.WriteBytes(BytesConverter.GetBytes((ushort)encodedComment.Length)); // 2 bytes, .ZIP file comment length
            this.zipFileWriter.WriteBytes(encodedComment);                                         // variable size, .ZIP file comment

            return(this.zipFileWriter.GetBytes());
        }
예제 #16
0
 public void ToUInt32WithoutOffset_4Bytes_HalfMaxUInt32()
 {
     byte[] data = new byte[] { 255, 255, 255, 127 };
     Assert.AreEqual(uint.MaxValue / 2, BytesConverter.ToUInt32(data, 0));
 }
예제 #17
0
 public void ToUInt32WithoutOffset_4ZeroBytes_ZeroUInt32()
 {
     byte[] data = new byte[] { 0, 0, 0, 0 };
     Assert.AreEqual(0, BytesConverter.ToUInt32(data, 0));
 }
예제 #18
0
 public void ToUInt16WithOffset_2Bytes_MaxUInt16()
 {
     byte[] data = new byte[] { 0, 0, 0, 255, 255 };
     Assert.AreEqual(ushort.MaxValue, BytesConverter.ToUInt16(data, 3));
 }
예제 #19
0
        public bool exe(int type, float xPos, float yPos, float zPos, float rPos, float tPos, SolderDef solderDef, int Rinse)
        {
            switch (StartStep)
            {
            case 0:
                List <byte> temp = new List <byte>();
                temp.AddRange(Functions.NetworkBytes(1));
                temp.AddRange(Functions.NetworkBytes(type));
                temp.AddRange(Functions.NetworkBytes(1));

                temp.AddRange(Functions.NetworkBytes(xPos));
                temp.AddRange(Functions.NetworkBytes(yPos));
                temp.AddRange(Functions.NetworkBytes(zPos));
                temp.AddRange(Functions.NetworkBytes(rPos));
                temp.AddRange(Functions.NetworkBytes(tPos));

                byte[] aaa        = BytesConverter.ObjToBytes(solderDef);
                byte[] tempdata   = temp.ToArray();
                byte[] _rinsedata = BitConverter.GetBytes(Rinse);

                for (int i = 0; i < _rinsedata.Length; i++)
                {
                    if (i % 2 == 0)
                    {
                        byte rdata = _rinsedata[i];
                        _rinsedata[i]     = _rinsedata[i + 1];
                        _rinsedata[i + 1] = rdata;
                    }
                }



                byte[] ndata = new byte[tempdata.Length + aaa.Length + _rinsedata.Length];

                tempdata.CopyTo(ndata, 0);
                aaa.CopyTo(ndata, tempdata.Length);
                _rinsedata.CopyTo(ndata, tempdata.Length + aaa.Length);


                CommData = new BaseData(Addr, ndata);
                movedriverZm.WriteRegister(CommData);
                StartOT.Restart();
                StartStep = 1;
                return(false);

            case 1:
                if (CommData.Succeed == true)
                {
                    StartStep        = 0;
                    CommData.Succeed = false;
                    if (Addr == 4400)
                    {
                        FormMain.RunProcess.LogicData.RunData.leftSoldertintimes++;
                    }
                    else
                    {
                        FormMain.RunProcess.LogicData.RunData.rightSoldertintimes++;
                    }
                    return(true);
                }
                if (StartOT.ElapsedMilliseconds > 10000)
                {
                    StartStep = 0;
                }
                return(false);

            default:
                StartStep        = 0;
                CommData.Succeed = false;
                return(false);
            }
        }
예제 #20
0
 public void ToUInt64WithoutOffset_8Bytes_HalfMaxUInt64()
 {
     byte[] data = new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 };
     Assert.AreEqual(ulong.MaxValue / 2, BytesConverter.ToUInt64(data, 0));
 }
예제 #21
0
        private void OnUpdatePosition()
        {
            string content = $"Ln {ByteViewer.CurrentLine}\tCol {ByteViewer.CurrentPositionInLine}";

            if (ByteViewer.ByteProvider != null && ByteViewer.ByteProvider.Length > ByteViewer.SelectionStart)
            {
                content += $"\tAddress: {ByteViewer.SelectionStart.ToString("X8")}";
                byte current = ByteViewer.ByteProvider.ReadByte(ByteViewer.SelectionStart);
                content += $"\tBits of Byte {ByteViewer.SelectionStart} ({current.ToString()} || {"0x" + current.ToString("X2")}): {BytesConverter.ToBits(current)}";
            }

            content += $"\t{GetDisplayBytes(ByteViewer.ByteProvider.Length)}";

            ByteSizeStatusBarItem.Content = content;
        }
예제 #22
0
 public void ToUInt64WithOffset_8Bytes_ZeroUInt64()
 {
     byte[] data = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
     Assert.AreEqual(0, BytesConverter.ToUInt64(data, 1));
 }
예제 #23
0
        private void FindAllButton_Click(object sender, RoutedEventArgs e)
        {
            FindAllReferencesGroupBox.Visibility = Visibility.Visible;
            ByteViewerHost.Margin = new Thickness(0, 20, 250, 105);

            FindAllListBox.Items.Clear();

            if (String.IsNullOrEmpty(SearchTextBox.Text) || ByteViewer.ByteProvider == null)
            {
                return;
            }

            if (SearchBytesRadioButton.IsChecked == true && SearchOptionCheckBox.IsChecked == true)
            {
                SignatureSearchResult = 1;
                SignatureScan scan = new SignatureScan(SearchTextBox.Text, ByteViewer.ByteProvider, SignatureSearchResult);
                for (long address = scan.Address(); address >= 0; scan.Result++, address = scan.Address())
                {
                    byte[] data = new byte[scan.PatternSize];
                    for (int i = 0; i < scan.PatternSize; ++i)
                    {
                        data[i] = ByteViewer.ByteProvider.ReadByte(address + i);
                    }

                    string content = $"{address.ToString("X8")} ({scan.PatternSize}): {new BytesConverter(data).ToHexadecimalString()} [\"{Encoding.ASCII.GetString(data)}\"]";
                    FindAllListBox.Items.Add(new ListBoxItem()
                    {
                        Content = content,
                        Tag     = new KeyValuePair <long, long>(address, scan.PatternSize),
                        ToolTip = new ToolTip()
                        {
                            Content = content
                        }
                    });
                }

                return;
            }
            else
            {
                try
                {
                    ByteViewer.SelectionStart     = 0;
                    ByteViewFindOptions.MatchCase = (bool)SearchOptionCheckBox.IsChecked;
                    ByteViewFindOptions.Type      = (bool)SearchBytesRadioButton.IsChecked ? FindType.Hex : FindType.Text;

                    if (ByteViewFindOptions.Type == FindType.Hex)
                    {
                        ByteViewFindOptions.Hex = BytesConverter.StringToBytes(SearchTextBox.Text);
                    }
                    else
                    {
                        ByteViewFindOptions.Text = SearchTextBox.Text;
                    }

                    ByteViewFindOptions.IsValid = true;


                    const long NO_MATCH = -1;

                    while (ByteViewer.Find(ByteViewFindOptions) != NO_MATCH)
                    {
                        byte[] data = new byte[ByteViewer.SelectionLength];
                        for (int i = 0; i < ByteViewer.SelectionLength; ++i)
                        {
                            data[i] = ByteViewer.ByteProvider.ReadByte(ByteViewer.SelectionStart + i);
                        }

                        string content = $"{ByteViewer.SelectionStart.ToString("X8")} ({ByteViewer.SelectionLength}): {new BytesConverter(data).ToHexadecimalString()} [\"{Encoding.ASCII.GetString(data)}\"]";
                        FindAllListBox.Items.Add(new ListBoxItem()
                        {
                            Content = content,
                            Tag     = new KeyValuePair <long, long>(ByteViewer.SelectionStart, ByteViewer.SelectionLength),
                            ToolTip = new ToolTip()
                            {
                                Content = content
                            }
                        });
                    }
                }
                catch
                {
                }
            }
        }
예제 #24
0
 public void ToUInt64WithOffset_8Bytes_MaxUInt64()
 {
     byte[] data = new byte[] { 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255 };
     Assert.AreEqual(ulong.MaxValue, BytesConverter.ToUInt64(data, 3));
 }
예제 #25
0
        /// <summary>
        /// Creates a new read-only zip storer from the data.
        /// </summary>
        /// <param name="data"> The data. </param>
        /// <returns> New read-only zip storer. </returns>
        /// <exception cref="Localization.ValueNullException">
        /// The exception that is thrown when data is null.
        /// </exception>
        /// <exception cref="InvalidDataException">
        /// The exception that is thrown when data is invalid.
        /// </exception>
        public static IReadOnlyDataStorer FromData(params byte[] data)
        {
            Validation.NotNull("Data", data);

            const int cfhSize   = 46; // fixed size of the central file header
            const int lfhSize   = 30; // fixed size of the local file header
            const int lfnOffset = 26; // relative offset to the size of the file name (local header)
            const int lefOffset = 28; // relative offset to the size of the extra field (local header)

            int length = data.Length;

            if (length < 22)
            {
                // Min length of the zip data is more than or equals to 22 bytes
                throw new InvalidDataException();
            }

            int lastIndex         = length - 1;
            int max               = length - 5;
            int signaturePosition = -1;

            for (int i = max; i >= 0; i--)
            {
                signaturePosition = lastIndex - i - 4;

                if (BytesConverter.ToUInt32(data, signaturePosition) == endOfCentralDirRecordSignature)
                {
                    bool isZip64           = false;
                    long centralDirEntries = BytesConverter.ToUInt16(data, signaturePosition + 10);
                    long centralDirSize    = BytesConverter.ToUInt32(data, signaturePosition + 12);
                    long centralDirOffset  = BytesConverter.ToUInt32(data, signaturePosition + 16);

                    if (centralDirOffset == zip64CentralDirSignature) // It is a Zip64 file
                    {
                        isZip64 = true;

                        int zip64CentralDirLocatorOffset = signaturePosition - 20;
                        if (BytesConverter.ToUInt32(data, zip64CentralDirLocatorOffset) != zip64EndOfCentralDirLocatorSignature)
                        {
                            // Not a ZIP64 central dir locator
                            throw new InvalidDataException();
                        }

                        int zip64CentralDirRecordOffset = (int)BytesConverter.ToUInt32(data, zip64CentralDirLocatorOffset + 8);
                        if (BytesConverter.ToUInt32(data, zip64CentralDirRecordOffset) != zip64EndOfCentralDirRecordSignature)
                        {
                            // Not a ZIP64 central dir record
                            throw new InvalidDataException();
                        }

                        centralDirEntries = (long)BytesConverter.ToUInt64(data, zip64CentralDirRecordOffset + 32);
                        centralDirSize    = (long)BytesConverter.ToUInt64(data, zip64CentralDirRecordOffset + 40);
                        centralDirOffset  = (long)BytesConverter.ToUInt64(data, zip64CentralDirRecordOffset + 48);
                    }

                    int centralDirStartIndex = (int)centralDirOffset;
                    int centralDirEndIndex   = centralDirStartIndex + (int)centralDirSize;

                    IDataStorerEntry[] fileEntries = new IDataStorerEntry[centralDirEntries];
                    int index = 0;

                    for (int pointer = centralDirStartIndex; pointer < centralDirEndIndex;)
                    {
                        if (BytesConverter.ToUInt32(data, pointer) != centralDirectoryFileHeaderSignature)
                        {
                            // Not a ZIP64 central dir file header
                            throw new InvalidDataException();
                        }

                        // 4 bytes, central directory file header signature
                        // 2 bytes, version made by
                        // 2 bytes, version needed to extract (minimum)
                        // 2 bytes, general purpose bit flag
                        ushort method         = BytesConverter.ToUInt16(data, pointer + 10); // 2 bytes, compression method
                        uint   modifyTime     = BytesConverter.ToUInt32(data, pointer + 12); // 2+2 bytes, file last modification time and date
                        uint   crc32          = BytesConverter.ToUInt32(data, pointer + 16); // 4 bytes, CRC-32
                        uint   compressedSize = BytesConverter.ToUInt32(data, pointer + 20); // 4 bytes, compressed size
                        uint   fileSize       = BytesConverter.ToUInt32(data, pointer + 24); // 4 bytes, uncompressed size
                        ushort fileNameSize   = BytesConverter.ToUInt16(data, pointer + 28); // 2 bytes, file name length
                        ushort extraFieldSize = BytesConverter.ToUInt16(data, pointer + 30); // 2 bytes, extra field length
                        ushort commentSize    = BytesConverter.ToUInt16(data, pointer + 32); // 2 bytes, file comment length
                                                                                             // 2+2=4 bytes, disk number where file starts (disk=0), internal file attributes
                                                                                             // 4 bytes, External file attributes
                        uint headerOffset = BytesConverter.ToUInt32(data, pointer + 42);     // 4 bytes, relative offset of header

                        uint headerSize             = (uint)(cfhSize + fileNameSize + extraFieldSize + commentSize);
                        int  commentsPointer        = (int)(pointer + headerSize - commentSize);
                        int  extraFieldBlockPointer = commentsPointer - extraFieldSize;

                        while (true)
                        {
                            if (extraFieldBlockPointer >= commentsPointer)
                            {
                                break;
                            }

                            if (BytesConverter.ToUInt16(data, extraFieldBlockPointer) == zip64ExtraBlockTagSignature)
                            {
                                if (fileSize == zip64CentralDirSignature)
                                {
                                    fileSize = BytesConverter.ToUInt32(data, extraFieldBlockPointer + 12);
                                }

                                if (compressedSize == zip64CentralDirSignature)
                                {
                                    compressedSize = BytesConverter.ToUInt32(data, extraFieldBlockPointer + 20);
                                }

                                if (headerOffset == zip64CentralDirSignature)
                                {
                                    headerOffset = BytesConverter.ToUInt32(data, extraFieldBlockPointer + 28);
                                }

                                break;
                            }
                            else
                            {
                                extraFieldBlockPointer += BytesConverter.ToUInt16(data, extraFieldBlockPointer + 2);
                            }
                        }

                        if (BytesConverter.ToUInt32(data, (int)headerOffset) != localFileHeaderSignature)
                        {
                            throw new InvalidDataException();
                        }

                        uint lfeSize = (uint)(BytesConverter.ToUInt16(data, (int)headerOffset + lfnOffset) + BytesConverter.ToUInt16(data, (int)headerOffset + lefOffset));

                        ZipReadOnlyStorerEntry fileEntry = new ZipReadOnlyStorerEntry(
                            utf8Encoding.GetString(data, cfhSize + pointer, fileNameSize),
                            fileSize,
                            (CompressionMethod)method,
                            compressedSize,
                            headerOffset,
                            (uint)(lfhSize + lfeSize + headerOffset),
                            crc32,
                            ZipStorerUtils.DosTimeToDateTime(modifyTime),
                            (commentSize > 0) ? utf8Encoding.GetString(data, (int)(pointer + headerSize - commentSize), commentSize) : ""
                            );

                        fileEntries[index++] = fileEntry;
                        pointer += (int)headerSize;
                    }

                    return(new ZipReadOnlyStorer(isZip64, data, fileEntries));
                }
            }

            throw new InvalidDataException();
        }
        public void Main(byte[] input)
        {
            try
            {
                //协议相关变量
                ushort replySeq;        //应答流水号,详见JTT808-2013第8.1章节
                ushort replyId;         //应答ID,详见JTT808-2013第8.1章节
                byte   result;          //结果,详见JTT808-2013第8.1章节
                string resultExplain;   //结果的描述

                //临时变量
                BytesConverter iBytesConverter = new BytesConverter();
                int            startIndex      = 0;
                int            length;

                //解析"应答流水号"
                replySeq   = iBytesConverter.ToUShort(input, startIndex);
                length     = iBytesConverter.returnLength;
                startIndex = startIndex + length;

                //解析"应答ID"
                replyId    = iBytesConverter.ToUShort(input, startIndex);
                length     = iBytesConverter.returnLength;
                startIndex = startIndex + length;

                //解析"结果"
                result        = iBytesConverter.ToByte(input, startIndex);
                resultExplain = result.ToString("D");
                length        = iBytesConverter.returnLength;
                startIndex    = startIndex + length;
                switch (result)
                {
                case 0:
                    resultExplain = resultExplain + " 成功/确认";
                    break;

                case 1:
                    resultExplain = resultExplain + " 失败";
                    break;

                case 2:
                    resultExplain = resultExplain + " 消息有误";
                    break;

                case 3:
                    resultExplain = resultExplain + " 不支持";
                    break;

                case 4:
                    resultExplain = resultExplain + " 报警处理确认";
                    break;

                default:
                    resultExplain = "!!!>>>数值错误<<<!!!";
                    break;
                }

                //打印
                ConsoleColorPrint iPrint = new ConsoleColorPrint();
                iPrint.TripleInOneLine("---消息体名称:", ConsoleColor.Gray, "平台通用应答", ConsoleColor.Green, "---", ConsoleColor.Gray);
                iPrint.DoubleInOneLine("应答流水号:", ConsoleColor.Green, replySeq.ToString("D"), ConsoleColor.White);
                iPrint.DoubleInOneLine("应答ID:", ConsoleColor.Green, replyId.ToString("D"), ConsoleColor.White);
                iPrint.DoubleInOneLine("结果:", ConsoleColor.Green, resultExplain, ConsoleColor.White);
            }
            catch (Exception e)
            {
                throw new Exception($"{this.GetType().FullName}.{MethodBase.GetCurrentMethod().Name}异常:{e.Message}");
            }
        }
        public void Main(byte[] input)
        {
            //协议相关变量
            ushort provinceId;          //省域ID,详见JTT808-2013第8.5章节
            ushort cityId;              //市县域ID,详见JTT808-2013第8.5章节
            string manufId;             //制造商ID,详见JTT808-2013第8.5章节
            string terminalModel;       //终端型号,详见JTT808-2013第8.5章节
            string terminalId;          //终端ID,详见JTT808-2013第8.5章节
            byte   carPlateColor;       //车牌颜色,详见JTT808-2013第8.5章节
            string carId;               //车辆标识,详见JTT808-2013第8.5章节
            string carPlateNumber = ""; //车辆牌照,详见JTT808-2013第8.5章节
            string carVin         = ""; //车辆VIN,详见JTT808-2013第8.5章节

            //临时变量
            BytesConverter iBytesConverter = new BytesConverter();
            int            startIndex      = 0;
            int            length;

            //所有字符串都使用GBK编码规则
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Encoding gbk = Encoding.GetEncoding("GBK");

            try
            {
                //提取"省域ID"
                length     = 2;
                provinceId = iBytesConverter.ToUShort(input, startIndex);
                length     = iBytesConverter.returnLength;
                startIndex = startIndex + length;

                //提取"市县域ID"
                cityId     = iBytesConverter.ToUShort(input, startIndex);
                length     = iBytesConverter.returnLength;
                startIndex = startIndex + length;

                //提取"制造商ID"
                length     = 5;
                manufId    = gbk.GetString(input, startIndex, length);
                startIndex = startIndex + length;

                //提取"终端型号"
                length        = 20;
                terminalModel = gbk.GetString(iBytesConverter.TrimEndZero(input, startIndex, length));
                startIndex    = startIndex + length;

                //提取"终端ID"
                length     = 7;
                terminalId = gbk.GetString(iBytesConverter.TrimEndZero(input, startIndex, length));
                startIndex = startIndex + length;

                //提取"车牌颜色"
                carPlateColor = iBytesConverter.ToByte(input, startIndex);
                length        = iBytesConverter.returnLength;
                startIndex    = startIndex + length;

                //提取"车辆标识"
                //车牌颜色为0时,车辆标识表示车辆VIN
                //车牌颜色不为0时,车辆标识表示公安交通管理部门颁发的机动车号牌
                length = input.Length - startIndex;
                if (carPlateColor == 0)
                {
                    carVin = gbk.GetString(input, startIndex, length);
                }
                else
                {
                    carPlateNumber = gbk.GetString(input, startIndex, length);
                }

                #region 打印
                ConsoleColorPrint iPrint = new ConsoleColorPrint();
                iPrint.TripleInOneLine("---消息体名称:", ConsoleColor.Gray, "终端注册", ConsoleColor.Green, "---", ConsoleColor.Gray);
                //省域ID
                iPrint.DoubleInOneLine("省域ID:", ConsoleColor.Green, provinceId.ToString("D"), ConsoleColor.White);
                //市县域ID
                iPrint.DoubleInOneLine("市县域ID:", ConsoleColor.Green, cityId.ToString("D4"), ConsoleColor.White);
                //制造商ID
                iPrint.DoubleInOneLine("制造商ID:", ConsoleColor.Green, manufId, ConsoleColor.White);
                //终端型号
                iPrint.DoubleInOneLine("终端型号:", ConsoleColor.Green, terminalModel, ConsoleColor.White);
                //终端ID
                iPrint.DoubleInOneLine("终端ID:", ConsoleColor.Green, terminalId, ConsoleColor.White);
                //车牌颜色
                iPrint.DoubleInOneLine("车牌颜色:", ConsoleColor.Green, carPlateColor.ToString(), ConsoleColor.White);
                //车辆标识
                if (carPlateColor == 0)
                {
                    iPrint.DoubleInOneLine("车辆VIN:", ConsoleColor.Green, carVin, ConsoleColor.White);
                }
                else
                {
                    iPrint.DoubleInOneLine("机动车号牌:", ConsoleColor.Green, carPlateNumber, ConsoleColor.White);
                }
                #endregion
            }
            catch (Exception e)
            {
                throw new Exception($"{this.GetType().FullName}.{MethodBase.GetCurrentMethod().Name}异常:{e.Message}");
            }
        }
예제 #28
0
        private ushort msgBodyProperty;                        //消息体属性,详见JTT808-2013第4.4.3章节
        #endregion


        /// <summary>
        /// MessageHead
        /// </summary>
        /// <param name="msgHead"></param>
        public MessageHead(byte[] msgHead)
        {
            BytesConverter iBytesConverter = new BytesConverter();
            int            startIndex      = 0;
            int            length;

            try
            {
                //提取"消息ID"
                MsgId      = iBytesConverter.ToUShort(msgHead, startIndex);
                length     = iBytesConverter.returnLength;
                startIndex = startIndex + length;

                //提取"消息体属性"
                msgBodyProperty = iBytesConverter.ToUShort(msgHead, startIndex);
                length          = iBytesConverter.returnLength;
                startIndex      = startIndex + length;

                //提取"消息体属性"中的:消息体长度
                MsgLength = Convert.ToUInt16(msgBodyProperty & 0x03FF);

                //提取"消息体属性"中的:数据加密方式,并计算分析加密方式
                encryption10 = Convert.ToBoolean(msgBodyProperty & 0x0400);
                encryption11 = Convert.ToBoolean(msgBodyProperty & 0x0800);
                encryption12 = Convert.ToBoolean(msgBodyProperty & 0x1000);
                if (encryption10)
                {
                    EncryptionType = "RSA";
                }
                else
                {
                    EncryptionType = "unencrypted";
                }

                //提取"消息体属性"中的:分包
                IsSubpackage = Convert.ToBoolean(msgBodyProperty & 0x2000);

                //提取"消息体属性"中的:保留
                Reserved = Convert.ToByte(msgBodyProperty & 0xC000);

                //提取"终端手机号"
                length      = 6;
                PhoneNumber = iBytesConverter.ToStringInBase(msgHead, startIndex, length, 16);
                startIndex  = startIndex + length;

                //提取"消息流水号"
                MsgSequence = iBytesConverter.ToUShort(msgHead, startIndex);

                #region  打印结果
                ConsoleColorPrint iPrint = new ConsoleColorPrint();
                string[]          iPrintStrings;
                ConsoleColor[]    iPrintConsoleColor;

                //标题
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine("\n---消息头------------------");
                //消息ID
                iPrintStrings = new string[3] {
                    "消息ID:", "0x", MsgId.ToString("X4")
                };
                iPrintConsoleColor = new ConsoleColor[3] {
                    ConsoleColor.Magenta, ConsoleColor.White, ConsoleColor.White
                };
                iPrint.MultipleInOneLine(iPrintStrings, iPrintConsoleColor);
                //消息体长度
                iPrintStrings = new string[3] {
                    "消息体长度:", MsgLength.ToString(), "Bytes"
                };
                iPrintConsoleColor = new ConsoleColor[3] {
                    ConsoleColor.Magenta, ConsoleColor.White, ConsoleColor.White
                };
                iPrint.MultipleInOneLine(iPrintStrings, iPrintConsoleColor);
                //数据加密方式
                iPrint.DoubleInOneLine("数据加密方式:", ConsoleColor.Magenta, EncryptionType, ConsoleColor.White);
                //分包
                iPrint.DoubleInOneLine("分包:", ConsoleColor.Magenta, IsSubpackage.ToString(), ConsoleColor.White);
                //保留
                iPrint.DoubleInOneLine("保留:", ConsoleColor.Magenta, Reserved.ToString(), ConsoleColor.White);
                //终端手机号
                iPrint.DoubleInOneLine("终端手机号:", ConsoleColor.Magenta, PhoneNumber, ConsoleColor.White);
                //消息流水号
                iPrint.DoubleInOneLine("消息流水号:", ConsoleColor.Magenta, MsgSequence.ToString(), ConsoleColor.White);
                #endregion
            }
            catch (Exception e)
            {
                throw new Exception($"{this.GetType().FullName}.{MethodBase.GetCurrentMethod().Name}异常:{e.Message}");
            }
        }
        public void Main(byte[] input)
        {
            try
            {
                //协议相关变量
                ushort replySeq;        //应答流水号,详见JTT808-2013第8.6章节
                byte   result;          //结果,详见JTT808-2013第8.6章节
                string resultExplain;   //结果的描述
                string authKey;         //鉴权码,详见JTT808-2013第8.6章节

                //临时变量
                BytesConverter iBytesConverter = new BytesConverter();
                int            startIndex      = 0;
                int            length;

                //所有字符串都使用GBK编码规则
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Encoding gbk = Encoding.GetEncoding("GBK");

                //解析"应答流水号"
                replySeq   = iBytesConverter.ToUShort(input, startIndex);
                length     = iBytesConverter.returnLength;
                startIndex = startIndex + length;

                //解析"结果"
                result        = iBytesConverter.ToByte(input, startIndex);
                resultExplain = result.ToString("D");
                length        = iBytesConverter.returnLength;
                startIndex    = startIndex + length;
                switch (result)
                {
                case 0:
                    resultExplain = resultExplain + " 成功";
                    break;

                case 1:
                    resultExplain = resultExplain + " 车辆已被注册";
                    break;

                case 2:
                    resultExplain = resultExplain + " 数据库中无该车辆";
                    break;

                case 3:
                    resultExplain = resultExplain + " 终端已被注册";
                    break;

                case 4:
                    resultExplain = resultExplain + " 数据库中无该终端";
                    break;

                default:
                    resultExplain = "!!!>>>数值错误<<<!!!";
                    break;
                }

                //解析"鉴权码"
                length  = input.Length - startIndex;
                authKey = gbk.GetString(input, startIndex, length);

                //打印
                ConsoleColorPrint iPrint = new ConsoleColorPrint();
                iPrint.TripleInOneLine("---消息体名称:", ConsoleColor.Gray, "终端注册应答", ConsoleColor.Green, "---", ConsoleColor.Gray);
                iPrint.DoubleInOneLine("应答流水号:", ConsoleColor.Green, replySeq.ToString("D"), ConsoleColor.White);
                iPrint.DoubleInOneLine("结果:", ConsoleColor.Green, resultExplain, ConsoleColor.White);
                iPrint.DoubleInOneLine("鉴权码:", ConsoleColor.Green, authKey, ConsoleColor.White);
            }
            catch (Exception e)
            {
                throw new Exception($"{this.GetType().FullName}.{MethodBase.GetCurrentMethod().Name}异常:{e.Message}");
            }
        }
예제 #30
0
 public IldRecord(IldRecordRaw raw)
 {
     Raw = raw;
     _converter = new BytesConverter(raw.Data);
 }
예제 #31
0
 public IldHeader(IldHeaderRaw raw)
 {
     Raw = raw;
     _converter= new BytesConverter(raw.Data);
 }
예제 #32
0
        public void Test()
        {
            var result = DirectoryEx.CalcSize(@"C:\Amat");

            Console.WriteLine(BytesConverter.GBytes(result));
        }