public void TestClearChunk()
        {
            ByteArrayBuilder builder     = new ByteArrayBuilder();
            string           firstChunk  = "123";
            string           secondChunk = "ab";

            byte[] firstChunkBytes  = GetBytesFromString(firstChunk);
            byte[] secondChunkBytes = GetBytesFromString(secondChunk);


            builder.AddChunkReference(firstChunkBytes, 3);
            builder.AddChunkReference(secondChunkBytes, 2);


            byte[] returnedBytes       = builder.ToArray();
            string returnedBytesString = Encoding.UTF8.GetString(returnedBytes);

            Assert.AreEqual("123ab", returnedBytesString);

            //now clear
            builder.ClearChunks();

            Assert.AreEqual("", Encoding.UTF8.GetString(builder.ToArray()));

            //check that the index gets reset after clear
            builder.AddChunkReference(firstChunkBytes, 3);

            returnedBytes       = builder.ReadChunk();
            returnedBytesString = Encoding.UTF8.GetString(returnedBytes);

            Assert.AreEqual(firstChunk, returnedBytesString);
        }
예제 #2
0
        private async Task <(bool same, byte[] hash)> WorkWithHashAsync(ByteArrayBuilder byteArrayBuilder, CancellationToken cancellationToken)
        {
            byte[] hash = null;
            try
            {
                var bytes = byteArrayBuilder.ToArray();
                hash = HashHelpers.GenerateSha256Hash(bytes);
                if (File.Exists(DigestFilePath))
                {
                    var digest = await File.ReadAllBytesAsync(DigestFilePath, cancellationToken).ConfigureAwait(false);

                    if (ByteHelpers.CompareFastUnsafe(hash, digest))
                    {
                        if (File.Exists(NewFilePath))
                        {
                            File.Delete(NewFilePath);
                        }
                        return(true, hash);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarning("Failed to read digest.");
                Logger.LogInfo(ex);
            }

            return(false, hash);
        }
예제 #3
0
        private void HanlderModbusBaseRead(MasterReadDataBase masterReadData)
        {
            byte _readOrderCmd = 0x00;

            if (masterReadData is ReadCoilsData)
            {
                _readOrderCmd = (byte)ModbusBaseOrderCmd.ReadCoilStatus;
            }
            else if (masterReadData is ReadDiscreteInputData)
            {
                _readOrderCmd = (byte)ModbusBaseOrderCmd.ReadInputStatus;
            }
            else if (masterReadData is ReadHoldingRegistersData)
            {
                _readOrderCmd = (byte)ModbusBaseOrderCmd.ReadHoldingRegister;
            }
            else if (masterReadData is ReadInputRegisters)
            {
                _readOrderCmd = (byte)ModbusBaseOrderCmd.ReadInputRegister;
            }
            if (_readOrderCmd != 0x00)
            {
                using (ByteArrayBuilder builder = new ByteArrayBuilder())
                {
                    builder.Append(masterReadData.SlaveID);                            //高位在前
                    builder.Append(_readOrderCmd);                                     //功能码
                    builder.Append(ByteHelper.ToBytes(masterReadData.Address, true));  //高位在前
                    builder.Append(ByteHelper.ToBytes(masterReadData.Quantity, true)); //数量
                    ModBusAppData = builder.ToArray();
                }
            }
        }
예제 #4
0
 /// <summary>
 /// 处理多个线圈写入
 /// </summary>
 /// <param name="masterWriteData">Modubs Master 写入数据</param>
 private void HanlderWriteMultipleCoilsData(MasterWriteDataBase masterWriteData)
 {
     if (masterWriteData is WriteMultipleCoilsData)
     {
         //02 0F 00 01 00 0A 02 FF 03 F1 E8
         //02--从机地址
         //0F--功能码
         //00 01--寄存器地址
         //00 0A--寄存器数量
         //02--数据长度
         //FF 03--数据
         //F1 E8--CRC
         WriteMultipleCoilsData _data = (WriteMultipleCoilsData)masterWriteData;
         using (ByteArrayBuilder builder = new ByteArrayBuilder())
         {
             builder.Append(_data.SlaveID);                               //高位在前
             builder.Append((byte)ModbusBaseOrderCmd.WriteMultipleCoils); //功能码
             builder.Append(ByteHelper.ToBytes(_data.Address, true));     //高位在前
             builder.Append(ByteHelper.ToBytes(_data.Quantity, true));    //数量
             byte[] _coilsValue = _data.ColisStatus.ToBytes();
             byte   _coilsCount = (byte)_coilsValue.Length;
             builder.Append(_coilsCount);
             builder.Append(_coilsValue);
             ModBusAppData = builder.ToArray();
         }
     }
 }
예제 #5
0
        public byte[] RawBytesToSend()
        {
            return(Match(i =>
            {
                switch (i)
                {
                case RequestInterruption.Abort:
                    return new[] { Bytes.CAN };

                default:
                    return Array.Empty <byte>();
                }
            }, data =>
            {
                var crc = Crc16.Compute(data.Concat(new[] { Bytes.ETB }));
                var crcByte1 = (byte)(crc / 256);
                var crcByte2 = (byte)(crc % 256);
                var bytes = new ByteArrayBuilder()
                            .Add(Bytes.SYN)
                            .Add(data)
                            .Add(Bytes.ETB)
                            .Add(crcByte1, crcByte2);
                return bytes.ToArray();
            }));
        }
예제 #6
0
        private void RunResponseBodyTest(string contentType, byte[] expectedBody, Encoding expectedEncoding)
        {
            ByteArrayBuilder builder = new ByteArrayBuilder();


            byte[] responseHead = Constants.DefaultEncoding.GetBytes(String.Format("HTTP/1.1 200 OK\r\nContent-Type: {0}\r\nContent-Length: {1}\r\n\r\n", contentType, expectedBody.Length));

            builder.AddChunkReference(responseHead, responseHead.Length);
            builder.AddChunkReference(expectedBody, expectedBody.Length);
            byte[]           expectedResponseBytes = builder.ToArray();
            HttpRequestInfo  expectedRequest       = new HttpRequestInfo("GET / HTTP/1.1\r\n\r\n");
            HttpResponseInfo expectedResponse      = new HttpResponseInfo(expectedResponseBytes);



            HttpRequestInfo  receivedReqInfo;
            HttpResponseInfo receivedRespInfo;

            SendTestRequestToMockProxy(expectedRequest, expectedResponse,
                                       out receivedReqInfo,
                                       out receivedRespInfo);


            string receivedResponseBody = receivedRespInfo.ResponseBody.ToString(receivedRespInfo.Headers["Content-Type"]);

            Assert.AreEqual(expectedEncoding.GetString(expectedBody), receivedResponseBody);
        }
        public void Test_HttpClient_RequestBody_POST_Binary()
        {
            ByteArrayBuilder builder = new ByteArrayBuilder();

            byte [] requestHead = Encoding.UTF8.GetBytes("POST / HTTP/1.1\r\nContent-Type: application/octet-stream\r\nContent-Length:4\r\n\r\n");
            builder.AddChunkReference(requestHead, requestHead.Length);
            builder.AddChunkReference(new byte[4] {
                0, 1, 0, 1
            }, 4);
            HttpRequestInfo reqInfo = new HttpRequestInfo(builder.ToArray());

            HttpRequestInfo  receivedRequestInfo;
            HttpResponseInfo receivedResponseInfo;

            SendTestRequestToMockProxy(reqInfo, new HttpResponseInfo("HTTP/1.1 200 OK\r\n\r\n"), out receivedRequestInfo, out receivedResponseInfo);


            byte [] respBody = receivedRequestInfo.ContentData.ToArray();

            Assert.AreEqual(4, respBody.Length);
            Assert.AreEqual(0, respBody[0]);
            Assert.AreEqual(1, respBody[1]);
            Assert.AreEqual(0, respBody[2]);
            Assert.AreEqual(1, respBody[3]);
        }
예제 #8
0
        private void HanlderWriteMultipleRegisterData(MasterWriteDataBase masterWriteData)
        {
            if (masterWriteData is WriteMultipleRegisterData)
            {
                //02 10 00 01 00 01 02 FF 01 33 41
                //02--从机地址
                //10--功能码
                //00 01--寄存器地址
                //00 01--寄存器数量
                //02--数据长度
                //FF 01--数据 -255
                //33 41--CRC
                WriteMultipleRegisterData _data = (WriteMultipleRegisterData)masterWriteData;
                using (ByteArrayBuilder builder = new ByteArrayBuilder())
                {
                    builder.Append(_data.SlaveID);                                  //高位在前
                    builder.Append((byte)ModbusBaseOrderCmd.WriteMultipleRegister); //功能码
                    builder.Append(ByteHelper.ToBytes(_data.Address, true));        //高位在前
                    builder.Append(ByteHelper.ToBytes(_data.Quantity, true));       //数量

                    byte _coilsCount = (byte)(_data.Value.Length * 2);
                    builder.Append(_coilsCount);
                    foreach (short item in _data.Value)
                    {
                        byte[] _registerValue = item.ToBytes(true);
                        builder.Append(_registerValue);
                    }

                    ModBusAppData = builder.ToArray();
                }
            }
        }
예제 #9
0
        /// <summary>
        /// Adds a request to the current Traffic Viewer File
        /// </summary>
        /// <param name="request"></param>
        /// <param name="description"></param>
        private void AddAppScanRequest(XmlNode request, string description)
        {
            TVRequestInfo reqInfo = new TVRequestInfo();

            reqInfo.Description = description;
            reqInfo.IsHttps     = request.Attributes["scheme"] != null && request.Attributes["scheme"].Equals("https");
            reqInfo.ThreadId    = Properties.Resources.Settings;

            XmlNode rawRequestNode = request.SelectSingleNode("raw");

            byte[] rawRequestBytes = new byte[0];
            if (rawRequestNode.Attributes["encoding"] != null && rawRequestNode.Attributes["encoding"].Value.Equals("none"))
            {
                string rawRequest = String.Empty;
                rawRequest      = rawRequestNode.InnerText;
                rawRequestBytes = Constants.DefaultEncoding.GetBytes(rawRequest);
            }
            reqInfo.RequestLine = HttpRequestInfo.GetRequestLine(rawRequestBytes);
            reqInfo.Id          = _tvFile.AddRequestInfo(reqInfo);
            _tvFile.SaveRequest(reqInfo.Id, rawRequestBytes);

            XmlNode response = request.SelectSingleNode("response");

            //put together the response

            if (response != null)
            {
                ByteArrayBuilder builder     = new ByteArrayBuilder();
                XmlNode          headersNode = response.SelectSingleNode("headers");
                if (headersNode != null && headersNode.Attributes["value"] != null)
                {
                    builder.AddChunkReference(Constants.DefaultEncoding.GetBytes(headersNode.Attributes["value"].Value));
                }

                XmlNode bodyNode = response.SelectSingleNode("body");
                if (bodyNode != null)
                {
                    bool isCompressed = bodyNode.Attributes["compressedBinaryValue"] != null && bodyNode.Attributes["compressedBinaryValue"].Value == "true";


                    string body      = bodyNode.Attributes["value"].Value;
                    byte[] bodyBytes = new byte[0];
                    if (isCompressed)
                    {
                        bodyBytes = Utils.DecompressBytesFromBase64String(body);
                    }
                    else
                    {
                        body      = Utils.Base64Decode(body);
                        bodyBytes = Constants.DefaultEncoding.GetBytes(body);
                    }
                    builder.AddChunkReference(bodyBytes);
                }
                _tvFile.SaveResponse(reqInfo.Id, builder.ToArray());
            }
        }
예제 #10
0
        public static byte[] Combine(params byte[][] byteArrays)
        {
            ByteArrayBuilder builder = new ByteArrayBuilder();

            foreach (var byteArray in byteArrays)
            {
                builder.Append(byteArray);
            }
            return(builder.ToArray());
        }
예제 #11
0
        /* Image Commands */
        public byte[] SetImageDensity(bool isHiDPI)
        {
            ByteArrayBuilder builder    = new ByteArrayBuilder();
            byte             dpiSetting = isHiDPI ? (byte)0x33 : (byte)0x32; // TODO: is this right??

            byte[] baseCommand = new byte[] { 0x30, 0x31, dpiSetting, dpiSetting };
            builder.Append(GetImageHeader(baseCommand.Length));
            builder.Append(baseCommand);
            return(builder.ToArray());
        }
예제 #12
0
 public byte[] ToArray()
 {
     using (ByteArrayBuilder builder = new ByteArrayBuilder())
     {
         builder.Append(CRCCaluData);
         byte[] _crcValue = ByteHelper.ToBytes(CRCBuilder.Calu16MODBUS(CRCCaluData), false);
         builder.Append(_crcValue);
         return(builder.ToArray());
     }
 }
예제 #13
0
        public byte[] WriteImageFromBuffer()
        {
            // Print image that's already buffered.
            ByteArrayBuilder response = new ByteArrayBuilder();

            byte[] printCommandBytes = new byte[] { 0x30, 0x32 };
            response.Append(GetImageHeader(printCommandBytes.Length));
            response.Append(printCommandBytes);
            return(response.ToArray());
        }
예제 #14
0
 public byte[] ToArray()
 {
     using (ByteArrayBuilder builder = new ByteArrayBuilder())
     {
         builder.Append(ModbusHeader.TransactionIdentifier);
         builder.Append(ModbusHeader.ProtocolIdentifier);
         builder.Append(ByteHelper.ToBytes((ushort)ModBusAppData.Length));
         builder.Append(ModBusAppData);
         ModbusHeader.IncreaseTranIdentifier();
         return(builder.ToArray());
     }
 }
예제 #15
0
        /// <summary>
        /// Called to read the response asyncroneusly
        /// </summary>
        /// <param name="ar"></param>
        private void ReadResponse(IAsyncResult ar)
        {
            Stream           stream    = null;
            int              bytesRead = 0;
            HttpClientResult result    = HttpClientResult.Error;

            try
            {
                lock (_lock)
                {
                    stream    = (Stream)ar.AsyncState;
                    bytesRead = stream.EndRead(ar);

                    if (bytesRead > 0)
                    {
                        //add to the exiting data
                        _dataBuilder.AddChunkReference(_buffer, bytesRead);
                        //make a new chunk
                        _buffer = new byte[MAX_BUFFER_SIZE];
                        //continue reading
                        stream.BeginRead(_buffer, 0, MAX_BUFFER_SIZE, new AsyncCallback(ReadResponse), stream);
                    }
                    else
                    {
                        //construct the full response
                        _response = _dataBuilder.ToArray();
                        result    = HttpClientResult.Success;
                    }
                }
            }
            catch
            {
                //we don't care that much for the errors that occur here
            }
            finally
            {
                if (bytesRead == 0)
                {
                    //if the caller was waiting on the request complete event allow continuation
                    _requestCompleteEvent.Set();

                    //we're done reading close the connection and trigger the event with the collected response
                    //the result will be success
                    if (RequestComplete != null)
                    {
                        RequestComplete.Invoke
                            (new HttpClientRequestCompleteEventArgs(new HttpResponseInfo(_response)));
                    }
                    _connection.Close();
                }
            }
        }
예제 #16
0
        /// <summary>
        /// Gets the bytes of the request
        /// </summary>
        /// <param name="isProxyHttp">Whether this is a request to a proxy</param>
        /// <returns></returns>
        public byte[] ToArray(bool isProxyHttp = false)
        {
            string           requestHead  = GetRequestHead(isProxyHttp);
            ByteArrayBuilder arrayBuilder = new ByteArrayBuilder();

            byte[] requestHeadBytes = Constants.DefaultEncoding.GetBytes(requestHead);
            arrayBuilder.AddChunkReference(requestHeadBytes, requestHeadBytes.Length);
            if (ContentData != null)
            {
                arrayBuilder.AddChunkReference(ContentData, ContentData.Length);
            }
            return(arrayBuilder.ToArray());
        }
        /// <summary>
        /// Override to change the OnRead behavior
        /// </summary>
        /// <param name="ar"></param>
        protected virtual void OnRead(IAsyncResult ar)
        {
            try
            {
                if (_stop || Closed)
                {
                    return;
                }

                _isBusy = true;
                HttpProxyClientStreamWrapper wrapper = (HttpProxyClientStreamWrapper)ar.AsyncState;
                int bytesRead = 0;

                bytesRead = wrapper.EndRead(ar);

                //we are still connected and we read more bytes

                if (bytesRead > 0)
                {
                    // Append data to the request
                    _requestBuilder.AddChunkReference(Buffer, bytesRead);

                    _requestInfo = new HttpRequestInfo(_requestBuilder.ToArray(), false);

                    if (!_requestInfo.IsFullRequest)
                    {
                        // not finished keep on reading!
                        wrapper.BeginRead(Buffer, 0, Buffer.Length, new AsyncCallback(OnRead), wrapper);
                    }
                    else
                    {
                        lock (_proxyLock)
                        {
                            // Done reading, process the request
                            ProcessRequest();
                        }
                    }
                }
                else
                {
                    //we read 0 bytes
                    _isBusy = _requestBuilder.Length > 0;
                }
            }
            catch (Exception ex)
            {
                ClientStreamWrapper.Close();
                HttpServerConsole.Instance.WriteLine(ex);
            }
        }
예제 #18
0
 public static byte[] GenerateRequestMessage(string deviceAddr = "")
 {
     _buffer.Clear();
     _buffer.Append(Constants.StartMessage);
     _buffer.Append(Constants.Request);
     if (!String.IsNullOrEmpty(deviceAddr))
     {
         _buffer.Append(deviceAddr);
     }
     _buffer.Append(Constants.EndMessage);
     _buffer.Append(Constants.CR);
     _buffer.Append(Constants.LF);
     return(_buffer.ToArray());
 }
예제 #19
0
        public static byte[] Combine(params byte[][] byteArrays)
        {
            ByteArrayBuilder builder = new ByteArrayBuilder();

            foreach (var byteArray in byteArrays)
            {
                // For easier usage, ignore null byte arrays
                if (byteArray != null)
                {
                    builder.Append(byteArray);
                }
            }
            return(builder.ToArray());
        }
        private static async Task <HttpContent> GetContentTillEndAsync(Stream stream, CancellationToken ctsToken)
        {
            var bab = new ByteArrayBuilder();

            while (true)
            {
                var read = await stream.ReadByteAsync(ctsToken);

                if (read == -1)
                {
                    return(new ByteArrayContent(bab.ToArray()));
                }
            }
        }
예제 #21
0
        /// <summary>
        /// Called to read the response asyncroneusly
        /// </summary>
        /// <param name="ar"></param>
        private void ReadResponse(IAsyncResult ar)
        {
            lock (_proxyLock)
            {
                Stream stream    = null;
                int    bytesRead = 0;
                _isReading = true;

                try
                {
                    stream     = (Stream)ar.AsyncState;
                    bytesRead  = stream.EndRead(ar);
                    _isReading = false;

                    if (bytesRead > 0 && !ClientStreamWrapper.Closed)
                    {
                        //add to the exiting data
                        _responseBuilder.AddChunkReference(_responseBuffer, bytesRead);
                        byte[] chunk = new byte[bytesRead];
                        Array.Copy(_responseBuffer, chunk, bytesRead);

                        //save the response send the response down the pipe


                        HttpServerConsole.Instance.WriteLine(LogMessageType.Information,
                                                             "Sending upstream binary response downstream");
                        _dataStore.SaveResponse(_messageReqInfo.Id, _responseBuilder.ToArray());
                        ClientStreamWrapper.Stream.Write(chunk, 0, chunk.Length);

                        if (stream.CanRead && !_isReading)
                        {
                            _isReading = true;
                            //continue reading
                            stream.BeginRead(_responseBuffer, 0, MAX_BUFFER_SIZE, new AsyncCallback(ReadResponse), stream);
                        }
                    }
                    else
                    {
                        Close();
                    }
                }
                catch
                {
                    Close();
                }
                finally
                {
                }
            }
        }
예제 #22
0
        public static async Task <byte[]> ReadStartStopAsync(this SerialPort port, byte startbyte, byte stopbyte, CancellationToken token = default, int timeoutms = 0)
        {
            CancellationTokenSource linkedCTS  = null;
            CancellationTokenSource timeoutCTS = null;

            try
            {
                CancellationToken internalToken = token;
                timeoutCTS = new CancellationTokenSource(timeoutms);
                if (timeoutms > 0)
                {
                    linkedCTS     = CancellationTokenSource.CreateLinkedTokenSource(timeoutCTS.Token, token);
                    internalToken = linkedCTS.Token;
                }
                //number of total received data bytes
                int    received       = 0;
                var    buffer         = new ByteArrayBuilder();
                bool   startByteFound = false;
                byte[] tempBuffer     = new byte[1];
                while (!token.IsCancellationRequested)
                {
                    received = await port.BaseStream.ReadAsync(tempBuffer, 0, 1, internalToken);

                    if (!startByteFound)
                    {
                        if (tempBuffer[0] == startbyte)
                        {
                            startByteFound = true;
                            buffer.Append(startbyte);
                        }
                        continue;
                    }
                    else
                    {
                        buffer.Append(tempBuffer[0]);
                        if (tempBuffer[0] == stopbyte)
                        {
                            break;
                        }
                    }
                }
                return(buffer.ToArray());
            }
            finally
            {
                linkedCTS?.Dispose();
                timeoutCTS?.Dispose();
            }
        }
예제 #23
0
        void AppendString(FormatOptions options, bool allowAtom, ByteArrayBuilder builder, string value)
        {
            byte[] buf;

            switch (GetStringType(Engine, value, allowAtom))
            {
            case ImapStringType.Literal:
                var literal = Encoding.UTF8.GetBytes(value);
                var plus    = CanUseNonSynchronizedLiteral(Engine, literal.Length);
                var length  = literal.Length.ToString(CultureInfo.InvariantCulture);
                buf = Encoding.ASCII.GetBytes(length);

                builder.Append((byte)'{');
                builder.Append(buf, 0, buf.Length);
                if (plus)
                {
                    builder.Append((byte)'+');
                }
                builder.Append((byte)'}');
                builder.Append((byte)'\r');
                builder.Append((byte)'\n');

                if (plus)
                {
                    builder.Append(literal, 0, literal.Length);
                }
                else
                {
                    parts.Add(new ImapCommandPart(builder.ToArray(), new ImapLiteral(options, literal)));
                    builder.Clear();
                }
                break;

            case ImapStringType.QString:
                buf = Encoding.UTF8.GetBytes(MimeUtils.Quote(value));
                builder.Append(buf, 0, buf.Length);
                break;

            case ImapStringType.Atom:
                buf = Encoding.UTF8.GetBytes(value);
                builder.Append(buf, 0, buf.Length);
                break;

            case ImapStringType.Nil:
                builder.Append(Nil, 0, Nil.Length);
                break;
            }
        }
예제 #24
0
		private static async Task<byte[]> GetBytesTillEndAsync(Stream stream, CancellationToken ctsToken)
		{
			var bab = new ByteArrayBuilder();
			while (true)
			{
				int read = await stream.ReadByteAsync(ctsToken);
				if (read == -1)
				{
					return bab.ToArray();
				}
				else
				{
					bab.Append((byte)read);
				}
			}
		}
        private void RunTest(string firstChunk, int firstChunkSize, string secondChunk, int secondChunkSize, string expectedResult, int maxSize)
        {
            ByteArrayBuilder builder = new ByteArrayBuilder(maxSize);

            builder.AddChunkReference(GetBytesFromString(firstChunk), firstChunkSize);
            builder.AddChunkReference(GetBytesFromString(secondChunk), secondChunkSize);

            string result = Encoding.UTF8.GetString(builder.ToArray());

            Assert.AreEqual(expectedResult, result);

            if (firstChunkSize + secondChunkSize > maxSize)
            {
                Assert.IsTrue(builder.IsTruncated);
            }
        }
예제 #26
0
 public void ToArrayTest()
 {
     using (ByteArrayBuilder builder = new ByteArrayBuilder())
     {
         builder.Append((byte)0x68);
         builder.Append((byte)0x01);
         builder.Append((byte)0x01);
         builder.Append((byte)0x02);
         builder.Append(new byte[2] {
             0x03, 0x04
         });
         byte[] _data     = builder.ToArray();
         byte[] _expected = new byte[6] {
             0x68, 0x01, 0x01, 0x02, 0x03, 0x04
         };
         CollectionAssert.AreEqual(_expected, _data);
     }
 }
        public void Test_HttpRequestInfo_BinaryContent()
        {
            byte[] expectedPostData = new byte[4] {
                1, 0, 0, 5
            };
            string           request      = "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\n";
            ByteArrayBuilder arrayBuilder = new ByteArrayBuilder();

            byte[] requestBytes = Encoding.UTF8.GetBytes(request);
            arrayBuilder.AddChunkReference(requestBytes, requestBytes.Length);
            arrayBuilder.AddChunkReference(expectedPostData, expectedPostData.Length);
            HttpRequestInfo reqInfo = new HttpRequestInfo(arrayBuilder.ToArray());

            Assert.AreEqual(4, reqInfo.ContentData.Length);
            Assert.AreEqual(reqInfo.ContentData[0], 1);
            Assert.AreEqual(reqInfo.ContentData[1], 0);
            Assert.AreEqual(reqInfo.ContentData[2], 0);
            Assert.AreEqual(reqInfo.ContentData[3], 5);
        }
예제 #28
0
        /// <summary>
        /// 通过构造函数初始化参数,来将对象转换为BYTE数组
        /// </summary>
        /// <returns>
        /// BYTE数组
        /// </returns>
        /// 时间:2016/8/30 17:21
        /// 备注:
        public override byte[] ToBytes()
        {
            byte[] _cmdLengthDataPart = null;
            using (ByteArrayBuilder builder = new ByteArrayBuilder())
            {
                builder.Append(CmdWordArray);

                if (CmdParmArray != null)
                {
                    builder.Append(CmdParmArray);
                }

                _cmdLengthDataPart = builder.ToArray();
            }
            byte[] _packetLength   = ByteHelper.ToBytes((ushort)_cmdLengthDataPart.Length, false).Resize <byte>(2);//Length占位
            byte[] _cmdCRCDataPart = null;
            using (ByteArrayBuilder builder = new ByteArrayBuilder())
            {
                builder.Append(_packetLength); //长度
                builder.Append(TerminalId);    //CTM 终端ID
                builder.Append(SynWord1);
                builder.Append(CmdWordArray);

                if (CmdParmArray != null)
                {
                    builder.Append(CmdParmArray);//用户数据
                }
                _cmdCRCDataPart = builder.ToArray();
            }
            byte[] _cmdAll = null;
            using (ByteArrayBuilder builder = new ByteArrayBuilder())
            {
                builder.Append(SynWord1);
                builder.Append(_cmdCRCDataPart);
                builder.Append(ByteHelper.ToBytes(GetCrc16(_cmdCRCDataPart), false)[0]);
                builder.Append(SyncWord2);
                _cmdAll = builder.ToArray();
            }
            return(_cmdAll);
        }
예제 #29
0
        /// <summary>
        /// 处理单个寄存器写入
        /// </summary>
        /// <param name="masterWriteData">Modubs Master 写入数据</param>
        private void HanlderWriteSingleRegisterData(MasterWriteDataBase masterWriteData)
        {
            if (masterWriteData is WriteSingleRegisterData)
            {
                //02 06 00 01 00 03 98 38
                //02 --从设备地址
                //06 --功能码
                //00 01 --寄存器起始地址
                //03 --寄存器写入值
                //98 38 --CRC
                WriteSingleRegisterData _data = (WriteSingleRegisterData)masterWriteData;

                using (ByteArrayBuilder builder = new ByteArrayBuilder())
                {
                    builder.Append(_data.SlaveID);                                //高位在前
                    builder.Append((byte)ModbusBaseOrderCmd.WriteSingleRegister); //功能码
                    builder.Append(ByteHelper.ToBytes(_data.Address, true));      //高位在前
                    builder.Append(ByteHelper.ToBytes(_data.Value, true));
                    ModBusAppData = builder.ToArray();
                }
            }
        }
예제 #30
0
        private static byte[] FormatMessage(ref LowLevelRequestMessage message)
        {
            var bytes = new ByteArrayBuilder()
                        .Add(Bytes.SYN)
                        .Add(message.Command.acronym);

            if (!message.Parameters.Any())
            {
                message = message.With(parameters: new[] { string.Empty });
            }
            foreach (var parameter in message.Parameters)
            {
                bytes
                .Add(parameter.Length.ToString("000"))
                .Add(parameter);
            }
            bytes.Add(Bytes.ETB);
            var crc = Crc16.Compute(bytes.Skip(1));

            bytes.Add((byte)(crc / 256), (byte)(crc % 256));
            return(bytes.ToArray());
        }