//******************************************************************************* // Event Functions //******************************************************************************* private void onConnectEvent(ref ReceivedData data) { for(int i = 0; i < connectionIdBehaviours.Count; ++i){ if(connectionIdBehaviours[i].connectionId == data.connectionId){ connectionIdBehaviours[i].callBack(); } } }
private ConnectionInfo getConnectionInfo(ref ReceivedData data) { string address; int port; NetworkID networkId; NodeID nodeId; byte error; NetworkTransport.GetConnectionInfo(data.hostId, data.connectionId, out address, out port, out networkId, out nodeId, out error); ConnectionInfo info = new ConnectionInfo(address, port); return info; }
private void onDataEvent(ref ReceivedData data) { if(!(mHostId == data.hostId)){ return; }else{ string message = SCNetworkUtil.getStringFromBuffer(data.buffer); string command = SCNetworkUtil.getCommand(message); SCMessageInfo info = SCNetworkUtil.decodeMessage(message); info.fromConnectionId = data.connectionId; Debug.Log("SCCommunicator| Received: \"" + message + "\" from connection Id: " + data.connectionId); brain.processMessage(command, info); } }
private void onDataEvent(ref ReceivedData data) { bool functionCalled = false; string message = SCNetworkUtil.getStringFromBuffer(data.buffer); string command = SCNetworkUtil.getCommand(message); for(int i = 0; i < commandBehaviours.Count; ++i){ if(command == commandBehaviours[i].command){ data.message = message; data.command = command; commandBehaviours[i].callBack(data); functionCalled = true; } } if(!functionCalled){ Debug.Log("Received: " + message); } }
protected void VerifyReceivedDataSharedConstraints(SampleAppUrlPathData sampleAppUrlPathData, ReceivedData receivedData) { FullFwAssertValid(receivedData); receivedData.Transactions.Count.Should().Be(sampleAppUrlPathData.TransactionsCount); receivedData.Spans.Count.Should().Be(sampleAppUrlPathData.SpansCount); receivedData.Errors.Count.Should().Be(sampleAppUrlPathData.ErrorsCount); // ReSharper disable once InvertIf if (receivedData.Transactions.Count == 1) { var transaction = receivedData.Transactions.First(); if (transaction.Context != null) { transaction.Context.Request.Url.Full.Should().Be(Consts.SampleApp.RootUrl + "/" + sampleAppUrlPathData.RelativeUrlPath); var questionMarkIndex = sampleAppUrlPathData.RelativeUrlPath.IndexOf('?'); if (questionMarkIndex == -1) { transaction.Context.Request.Url.PathName.Should() .Be(Consts.SampleApp.RootUrlPath + "/" + sampleAppUrlPathData.RelativeUrlPath); transaction.Context.Request.Url.Search.Should().BeNull(); } else { transaction.Context.Request.Url.PathName.Should() .Be(Consts.SampleApp.RootUrlPath + "/" + sampleAppUrlPathData.RelativeUrlPath.Substring(0, questionMarkIndex)); transaction.Context.Request.Url.Search.Should().Be(sampleAppUrlPathData.RelativeUrlPath.Substring(questionMarkIndex + 1)); } transaction.Context.Response.StatusCode.Should().Be(sampleAppUrlPathData.StatusCode); transaction.Outcome.Should().Be(sampleAppUrlPathData.Outcome); } var httpStatusFirstDigit = sampleAppUrlPathData.StatusCode / 100; transaction.Result.Should().Be($"HTTP {httpStatusFirstDigit}xx"); transaction.SpanCount.Started.Should().Be(sampleAppUrlPathData.SpansCount); } }
// This function receives the messages that are sent after the time stamp mentioned private void ReceiveMessagesWithTimestampFilter(string partitionId, long timestamp, ReceivedData callback) { ReceiveMessages("receive from timestamp checkpoint", 2, "amqp.annotation.x-opt-enqueuedtimeutc > " + timestamp, partitionId, callback); }
private void ProcessBuffer(byte[] compressedBuffer, int bufferSize, ulong sender) { uint uncompressedSize; var result = m_VoIP.DecompressVoice(compressedBuffer, (uint)bufferSize, m_uncompressedVoiceBuffer, out uncompressedSize); Debug.Assert(result == VoiceResult.OK, result.ToString()); if (result == VoiceResult.OK) { ReceivedData senderData; if (!m_receivedVoiceData.TryGetValue(sender, out senderData)) { senderData = new ReceivedData() { UncompressedBuffer = new List<byte>(), Timestamp = MyTimeSpan.Zero, }; } if (senderData.Timestamp == MyTimeSpan.Zero) senderData.Timestamp = MySandboxGame.Static.UpdateTime; senderData.SpeakerTimestamp = MySandboxGame.Static.UpdateTime; senderData.UncompressedBuffer.AddArray(m_uncompressedVoiceBuffer, (int)uncompressedSize); m_receivedVoiceData[sender] = senderData; } }
private void DoReceivedData(byte[] data) { ReceivedData?.Invoke(this, new BluetoothDataReceivedEventArgs(data)); }
// This function is the core receive function void ReceiveMessages(string scenario, int count, string filter, string partition, ReceivedData callback) { Trace.WriteLine(Amqp.TraceLevel.Information, "Running scenario '{0}', filter '{1}'...", scenario, filter); Trace.WriteLine(Amqp.TraceLevel.Information, "Establishing a connection..."); Address address = new Address(sbNamespace, PORT, keyName, keyValue); Connection connection = new Connection(address); Trace.WriteLine(Amqp.TraceLevel.Information, "Creating a session..."); Session session = new Session(connection); Trace.WriteLine(Amqp.TraceLevel.Information, "Creating a receiver link on partition {0}...", partition); string partitionAddress = entity + "/ConsumerGroups/$default/Partitions/" + partition; // Form the filter for receiving message based on the time stamp Map filters = new Map(); if (filter != null) { filters.Add(new Amqp.Types.Symbol("apache.org:selector-filter:string"), new DescribedValue(new Amqp.Types.Symbol("apache.org:selector-filter:string"), filter)); } string lastOffset = "-1"; long lastSeqNumber = -1; DateTime lastEnqueueTime = DateTime.MinValue; ReceiverLink receiver = new ReceiverLink( session, "receiver-" + partition, new Source() { Address = partitionAddress, FilterSet = filters }, null); // loop runs until clean up is called for (; g_bThreadActive;) { Message message = receiver.Receive(5000); if (message == null) { continue; } receiver.Accept(message); Data data = (Data)message.BodySection; // Get the data such as offset, Seq number and Devicename from the response header lastOffset = (string)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-offset")]; lastSeqNumber = (long)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-sequence-number")]; lastEnqueueTime = (DateTime)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-enqueued-time")]; var DeviceName = (string)message.MessageAnnotations[new Amqp.Types.Symbol("iothub-connection-device-id")]; callback(data.Binary, DeviceName); } receiver.Close(); session.Close(); connection.Close(); }
public void AskForReceive(ReceivedData rd) { ReceiveRequests.Add(rd); }
//HELPERS void onAllChunksReceived(ReceivedData receivedData) { ++receivedCompleteDataPortions; dataPortionDelay.Add(Timer.CurrentTime - receivedData.Data.CreationTime); }
public void ReceiveMessagesFromDevice(string partitionId, DateTime StartingTime, ReceivedData callback) { ReceiveMessagesWithTimestampFilter(partitionId, DateTimeToTimestamp(StartingTime), callback); }
public static ReceivedData ParseData(string data) { ReceivedData result = new ReceivedData(); if (data.Length < 9) { return(null); } if (data[0] == 't') { result.IsExtId = false; } else if (data[0] == 'T') { result.IsExtId = true; } else { return(null); } if (result.IsExtId) { var match = Regex.Match(data, @"T([0-9a-fA-F]{8})(\d{1})(\w*)\r"); if (!match.Success) { return(null); } int dlc = Convert.ToInt32(match.Groups[2].Value); if (dlc < 0 || dlc > 8) { return(null); } match = Regex.Match(data, @"T([0-9a-fA-F]{8})+(\d{1})+([0-9a-fA-F]{" + (dlc * 2) + "})+([0-9a-fA-F]{4})+\r"); if (!match.Success) { return(null); } result.CanId = Convert.ToInt32(match.Groups[1].Value, 16); result.DLC = Convert.ToInt32(match.Groups[2].Value, 16); result.Time = Convert.ToInt32(match.Groups[4].Value, 16) / 1000.0; result.Payload = new byte[result.DLC]; for (int i = 0; i < result.DLC; i++) { result.Payload[i] = byte.Parse(match.Groups[3].Value.Substring(2 * i, 2), System.Globalization.NumberStyles.HexNumber); } } else { var match = Regex.Match(data, @"t([0-9a-fA-F]{3})(\d{1})(\w*)\r"); if (!match.Success) { return(null); } int dlc = Convert.ToInt32(match.Groups[2].Value); if (dlc < 0 || dlc > 8) { return(null); } match = Regex.Match(data, @"t([0-9a-fA-F]{3})+(\d{1})+([0-9a-fA-F]{" + (dlc * 2) + "})+([0-9a-fA-F]{4})+\r"); if (!match.Success) { return(null); } result.CanId = Convert.ToInt32(match.Groups[1].Value, 16); result.DLC = Convert.ToInt32(match.Groups[2].Value, 16); result.Time = Convert.ToInt32(match.Groups[4].Value, 16) / 1000.0; result.Payload = new byte[result.DLC]; for (int i = 0; i < result.DLC; i++) { result.Payload[i] = byte.Parse(match.Groups[3].Value.Substring(2 * i, 2), System.Globalization.NumberStyles.HexNumber); } } if (!Validator.TryValidateObject(result, new ValidationContext(result), null, true)) { return(null); } return(result); }
public async Task <bool> ProcessMessageAsync(ReceivedData data) { await Console.Out.WriteLineAsync(Encoding.UTF8.GetString(data.Data)); return(data.AckMessage()); }
protected void VerifyReceivedDataSharedConstraints(SampleAppUrlPathData sampleAppUrlPathData, ReceivedData receivedData) { FullFwAssertValid(receivedData); receivedData.Transactions.Count.Should().Be(sampleAppUrlPathData.TransactionsCount); receivedData.Spans.Count.Should().Be(sampleAppUrlPathData.SpansCount); receivedData.Errors.Count.Should().Be(sampleAppUrlPathData.ErrorsCount); if (receivedData.Transactions.Count != 1) { return; } var transaction = receivedData.Transactions.First(); if (transaction.Context != null) { transaction.Context.Request.Url.Full.Should().Be(sampleAppUrlPathData.Uri.AbsoluteUri); transaction.Context.Request.Url.PathName.Should().Be(sampleAppUrlPathData.Uri.AbsolutePath); if (string.IsNullOrEmpty(sampleAppUrlPathData.Uri.Query)) { transaction.Context.Request.Url.Search.Should().BeNull(); } else { // Uri.Query always unescapes the querystring so don't use it, and instead get the escaped querystring. var queryString = sampleAppUrlPathData.Uri.GetComponents(UriComponents.Query, UriFormat.UriEscaped); transaction.Context.Request.Url.Search.Should().Be(queryString); } transaction.Context.Response.StatusCode.Should().Be(sampleAppUrlPathData.StatusCode); transaction.Outcome.Should().Be(sampleAppUrlPathData.Outcome); } var httpStatusFirstDigit = sampleAppUrlPathData.StatusCode / 100; transaction.Result.Should().Be($"HTTP {httpStatusFirstDigit}xx"); transaction.SpanCount.Started.Should().Be(sampleAppUrlPathData.SpansCount); }
protected override void Run() { Log.Debug("Started receiver"); // Only request all packets five times while (true) { if (Token.IsCancellationRequested) { Log.Debug("Received request to stop"); break; } foreach (var data in NeededData) { var chunkReq = new ChunkRequest(Guid.NewGuid(), ConversationId, MessageCount, data, FileInfo.ContentHash, ChunkSize); RaiseSendMessageEvent(chunkReq); MessageCount++; } Thread.Sleep(250); while (IncomingMessages.Count > 0) { Message mesg; if (IncomingMessages.TryDequeue(out mesg)) { if (mesg.MessageId == MessageType.CHUNK_REPLY) { var chunkReply = (ChunkReply)mesg; if (NeededData.Contains(chunkReply.Index)) { var provider = new RSACryptoServiceProvider(); provider.ImportCspBlob(FileInfo.PublicKeyInfo); if (MessageVerifier.CheckSignature(chunkReply.ChunkData, chunkReply.Signature, provider.ExportParameters(false))) { DataStore[chunkReply.Index] = chunkReply.ChunkData; NeededData.Remove(chunkReply.Index); ReceivedData.Add(chunkReply.Index); if (NeededData.Count == 0) { Log.Info(string.Format("Conversation complete; Downloaded {0} packets", DataStore.Count)); var ack = new Acknowledge(Guid.NewGuid(), ConversationId, mesg.MessageCount + 1, "Download complete"); CancelSource.Cancel(); RaiseSendMessageEvent(ack); break; } } else { Log.Warn("Message signature is NOT verfied"); } } } } } Thread.Sleep(250); } RaiseEndConversationEvent(); }
void Update() { int hostId; int connectionId; int channelId; byte[] buffer = new byte[1024]; int bufferSize = 1024; int recBufferSize; byte error; NetworkEventType rec = NetworkTransport.Receive(out hostId, out connectionId, out channelId, buffer, bufferSize, out recBufferSize, out error); ReceivedData data = new ReceivedData(); data.hostId = hostId; data.connectionId = connectionId; data.channelId = channelId; data.buffer = buffer; data.bufferSize = recBufferSize; data.error = error; data.message = null; data.command = null; switch(rec){ case NetworkEventType.Nothing: break; case NetworkEventType.ConnectEvent: onConnectEvent(ref data); break; case NetworkEventType.DataEvent: onDataEvent(ref data); break; case NetworkEventType.DisconnectEvent: onDisconnectEvent(ref data); break; } }
private void onNewGameResponse(ReceivedData data) { Debug.Log("New game created."); }
private void ProcessBuffer(Client C) { lock (m_LockingObj) //The following code won't execute unless it's able to acquire a lock. { while (m_CurrentlyReceived >= m_PacketSize) { byte[] PacketBuf = new byte[m_PacketSize]; if (!m_PartialPacketReceived) { Array.Copy(C.Buffer, PacketBuf, m_PacketSize); } else //The slushbuffer wasn't empty, so combine the two buffers into a packet buffer. { Array.ConstrainedCopy(C.SlushBuffer, 0, PacketBuf, 0, m_SizeOfSlush); Array.ConstrainedCopy(C.Buffer, 0, PacketBuf, m_SizeOfSlush, m_CurrentlyReceived); C.CreateSlushBuffer(0); m_SizeOfSlush = 0; m_PartialPacketReceived = false; } if (m_PacketType != 0) { lock (C.ReceivedPackets) C.ReceivedPackets.Enqueue(new AriesPacket(PacketBuf, true)); m_CurrentlyReceived -= (int)m_PacketSize; ReceivedData?.Invoke(this, C); } else { VoltronHeader Header = ReadVoltronHeader(PacketBuf, 12); if (Header.PacketSize < ((PacketBuf.Length - 1) - 12)) { ProcessVoltronPackets(C, PacketBuf); } else { lock (C.ReceivedPackets) C.ReceivedPackets.Enqueue(new VoltronPacket(PacketBuf, true)); ReceivedData?.Invoke(this, C); } m_CurrentlyReceived -= (int)m_PacketSize; } if (m_CurrentlyReceived > 0) { byte[] Remainder = new byte[m_CurrentlyReceived]; Array.ConstrainedCopy(C.Buffer, (C.Buffer.Length - m_CurrentlyReceived) + 1, Remainder, 0, m_CurrentlyReceived); m_SizeOfSlush = m_CurrentlyReceived; C.CreateBuffer(BUFFER_SIZE); C.CreateSlushBuffer(m_SizeOfSlush); Array.Copy(Remainder, C.SlushBuffer, m_CurrentlyReceived); Remainder = null; m_PartialPacketReceived = true; } else { C.CreateBuffer(BUFFER_SIZE); } } } }
protected void OnBytesReceived(IAsyncResult result) { int nBytesRec; try { nBytesRec = this.sock.EndReceive(result); } catch { try { this.sock.Close(); } catch { } if (Disconnected != null) { Disconnected(null, new ConnectionEventArgs() { }); } return; } if (nBytesRec <= 0) { try { this.sock.Close(); } catch { } if (Disconnected != null) { Disconnected(null, new ConnectionEventArgs() { }); } return; } byte[] receivedBytes = new byte[nBytesRec]; for (int i = 0; i < nBytesRec; i++) { receivedBytes[i] = dataRcvBuf[i]; } if (nBytesRec > 0) { ReceivedData.Invoke(this, new MessageEventArgs() { data = receivedBytes }); } st.Reset(); st.Start(); this.sock.BeginReceive( this.dataRcvBuf, 0, this.dataRcvBuf.Length, SocketFlags.None, new AsyncCallback(this.OnBytesReceived), this); }
/// <summary> /// Override in specific connection to handle higher level data /// </summary> /// <param name="data">The received data</param> protected virtual void HigherLevelDataReceived(ReceivedData data) { }
private void onDisconnectEvent(ref ReceivedData data) { }
/// <summary> /// Wymiana danych (klient - serwer). Podstawowa funkcja /// w ktorej obslugujemy danego klienta /// </summary> private void UpdateData() { while (true) { try { BinaryReader odbr = new BinaryReader(_clientSocket.GetStream()); int howMuchreceive = odbr.ReadInt32(); String ReceivedData; Byte[] data = new Byte[howMuchreceive]; Int32 sData; sData = _clientSocket.GetStream().Read(data, 0, data.Length); ReceivedData = Encoding.ASCII.GetString(data, 0, sData); if (ReceivedData[0] == '?') // Obaj przegrali { Console.WriteLine("Client {0} disconnected", lastId.ToString()); if ((lastId == _clientSockets[0].Id && _clientSockets[0].Id < _clientSockets[1].Id) || (lastId == _clientSockets[1].Id && _clientSockets[0].Id > _clientSockets[1].Id)) { ZeroArray(tabA, tabPos); } if ((lastId == _clientSockets[1].Id && _clientSockets[0].Id < _clientSockets[1].Id) || (lastId == _clientSockets[0].Id && _clientSockets[0].Id > _clientSockets[1].Id)) { ZeroArray(tabB, tabPos); } tabPos.Clear(); _clientSocket.GetStream().Close(); _clientSocket.Close(); _clientSockets.RemoveAt(GetIndex(_clientSockets, lastId)); _clientSocket.Dispose(); break; } if (ReceivedData[0] == '!') // Ktorys przegral badz sie rozlaczyl { if (_clientSockets.Count > 1) { for (int i = 0; i < _clientSockets.Count; i++) { if (_clientSockets[i].Socket != _clientSocket) { SendDataToClient("K" + "&", _clientSockets[i].Socket); } } } if (_clientSockets.Count > 1) { if ((lastId == _clientSockets[0].Id && _clientSockets[0].Id < _clientSockets[1].Id) || (lastId == _clientSockets[1].Id && _clientSockets[0].Id > _clientSockets[1].Id)) { ZeroArray(tabA, tabPos); } if ((lastId == _clientSockets[1].Id && _clientSockets[0].Id < _clientSockets[1].Id) || (lastId == _clientSockets[0].Id && _clientSockets[0].Id > _clientSockets[1].Id)) { ZeroArray(tabB, tabPos); } } else { if (lastId == 1) { ZeroArray(tabA, tabPos); } else { ZeroArray(tabB, tabPos); } } tabPos.Clear(); Console.WriteLine("Client {0} disconnected", lastId.ToString()); _clientSocket.GetStream().Close(); _clientSocket.Close(); _clientSockets.RemoveAt(GetIndex(_clientSockets, lastId)); //_clientSocket.Dispose(); break; } if (ReceivedData[0] == 'F') // Pozycje jedzenia { RandInfoAboutFood(); for (int i = 0; i < _clientSockets.Count; i++) { string dataAboutFood = "F#" + _typeOfFood.ToString() + "@" + _foodX.ToString() + "," + _foodY.ToString() + "&"; SendDataToClient(dataAboutFood, _clientSockets[i].Socket); } } if (ReceivedData[0] == 'S') // Wspolrzedne weza { if (_clientSockets.Count > 1) { for (int i = 0; i < _clientSockets.Count; i++) { if (_clientSockets[i].Socket != _clientSocket) { string toSend = "S#" + lastId.ToString() + "*" + ReceivedData.Remove(0, 2); SendDataToClient(toSend, _clientSockets[i].Socket); } } if ((lastId == _clientSockets[0].Id && _clientSockets[0].Id < _clientSockets[1].Id) || (lastId == _clientSockets[1].Id && _clientSockets[0].Id > _clientSockets[1].Id)) { ZeroArray(tabA, tabPos); } if ((lastId == _clientSockets[1].Id && _clientSockets[0].Id < _clientSockets[1].Id) || (lastId == _clientSockets[0].Id && _clientSockets[0].Id > _clientSockets[1].Id)) { ZeroArray(tabB, tabPos); } tabPos.Clear(); string[] split1 = ReceivedData.Split('&'); string[] split2 = split1[0].Split('$'); string[] positions = split2[1].Split(';'); foreach (var el in positions) { string[] tmp = el.Split(','); if (tmp.Length > 1) { tabPos.Add(Int32.Parse(tmp[0]) / 10); tabPos.Add(Int32.Parse(tmp[1]) / 10); } } if ((lastId == _clientSockets[0].Id && _clientSockets[0].Id < _clientSockets[1].Id) || (lastId == _clientSockets[1].Id && _clientSockets[0].Id > _clientSockets[1].Id)) { UpdateArray(tabA, tabPos); } if ((lastId == _clientSockets[1].Id && _clientSockets[0].Id < _clientSockets[1].Id) || (lastId == _clientSockets[0].Id && _clientSockets[0].Id > _clientSockets[1].Id)) { UpdateArray(tabB, tabPos); } //if (lastId == _clientSockets[0].Id) //{ // UpdateArray(tabA, tabPos); //} //else UpdateArray(tabB, tabPos); if (CheckCollsion(tabA, tabB) == true) { for (int k = 0; k < _clientSockets.Count; k++) { if (_clientSockets[k].Socket != _clientSocket) { SendDataToClient("C&", _clientSockets[k].Socket); } } } } } if (ReceivedData[0] == 'P') //Wyslanie punktow { if (_clientSockets.Count > 1) { for (int i = 0; i < _clientSockets.Count; i++) { if (_clientSockets[i].Socket != _clientSocket) { string toSend2 = ReceivedData + "&"; SendDataToClient(toSend2, _clientSockets[i].Socket); } } } } if (_clientSockets.Count == 1) { string toSendIfOne = lastId.ToString() + "*" + "0"; SendDataToClient(toSendIfOne, _clientSocket); } } catch (Exception ex) { Console.WriteLine(" >> " + ex.ToString()); } } }
protected virtual void ReceiveCallback(IAsyncResult ar) { try { int bytesRead; lock (Client) { bytesRead = Client.Socket.EndReceive(ar); } if (bytesRead > 0) { // reset the idle timer m_idleTimer.Change(MAX_IDLE_TIME_MS, MAX_IDLE_TIME_MS); var command = Encoding.ASCII.GetString(m_readBuffer, 0, bytesRead); var data = new ReceivedData(GetRemoteClientAddress(), command, DateTime.Now); try { if (m_protocol != null) { m_protocol.Receive(data); } else { Console.WriteLine("NULL PROTOCOL"); } } catch (Exception ex) { Debug.WriteLine($"Protocol Exception: {ex}"); SendData("INTERNAL SERVER ERROR\r\n"); if (m_closeAfterProtocolResponse) { Close(); } } finally { lock (Client) { Client.Socket?.BeginReceive( m_readBuffer, 0, READ_BUFFER_SIZE, SocketFlags.None, ReceiveCallback, null); } } } } catch (SocketException) { //Ignored - the stream throws an exception when it's closed. } catch (Exception) { //Ignored - the stream throws an exception when it's closed. } }
public Task <bool> ProcessMessageAsync(ReceivedData data) { messageCount++; return(Task.FromResult(data.AckMessage())); }
private void ReaderRun(TcpClient client) { NetworkStream stream = null; EndPoint endPoint = client.Client.RemoteEndPoint; LogInfo($"Client {endPoint} connected"); byte[] data = new byte[MaxLength]; stream = client.GetStream(); IFormatter formatter = new BinaryFormatter(); while (true) { LogInfo($"Reading input from {endPoint}..."); int len = 0; try { len = stream.Read(data, 0, sizeof(int)); } catch { } if (len == 0) { break; } int dataSize = BitConverter.ToInt32(data, 0); len = 0; int curLen = 0; while (len < dataSize) { try { curLen = stream.Read(data, len, dataSize - len); len += curLen; } catch { } if (curLen == 0) { break; } } if (curLen == 0) { break; } System.Diagnostics.Debug.Assert(len == dataSize && dataSize < MaxLength); string func; object[] ps; using (var serStream = new MemoryStream(data)) { func = (string)formatter.Deserialize(serStream); ps = (object[])formatter.Deserialize(serStream); } LogInfo($"Reading input from {endPoint} finished. Firing event..."); OnReceivedData(endPoint, func, ps); ReceivedData?.Invoke( this, new EventArgs <EndPoint, Invocation>( endPoint, new Invocation { FuncName = func, Parameters = ps } ) ); //LogInfo($"Reading input from {endPoint} finished. Firing event finished."); } LogInfo($"Client {endPoint} disconnected"); remoteClients.TryRemove(endPoint, out var _); ClientDisconnected?.Invoke(this, new EventArg <EndPoint>(endPoint)); }
private string[] Desinflate() { return(ReceivedData.Split(',')); }
private UInt16 CalcRxCRC(ReceivedData RData) { const UInt16 polinom = 0xa001; UInt16 code = 0xffff; byte ml; byte tmp; //amount of byte in ReceivedData structure. //After size of ReceivedData reached 70, Marshal.SizeOf() return 72, //so,just work around is change 2 to 4. int length = Marshal.SizeOf(RData) -2;// 2 is sizeof CRC in ReceivedData for (int i = 0; i < length; i++) { //For each byte from array /* Put LSB of 16 bit code(in the future a СRС16) to ml. */ ml = (byte)(code); /* Do m1 XOR msg[i] and put result to m1. */ tmp = Marshal.ReadByte(RData, i); ml ^= tmp; /* Set LSB of code to zero. */ code &= 0xff00; code += ml; for (int j = 0; j < 8; j++) { /* Check LSB bit of code. */ if ((code & 0x0001) == 1) { /* LSB bit is 1. */ code >>= 1; /* Do code XOR polinom and put result to code. */ code ^= polinom; } else { /* LSB bit is 0*/ code >>= 1; } } } return code; }
private void OnReceiveData(object obj, ReceivedData cmd) { SafeInvoke(cmdHandlers, h => h((byte)cmd.Command, cmd.Channel, cmd.DataFormat, cmd.Data1, cmd.Data2, cmd.Data3, cmd.Data4), true); }
public int ComPort( string PortName, System.IO.Ports.StopBits Stop_Bit, byte DataBits, int BaudRate, System.IO.Ports.Parity Parity ) { //Create new serial communication port component. serialComPort = new System.IO.Ports.SerialPort(); // create a Receiver structure. currentReceivedData = new ReceivedData(); SendData = new TxData(); // Create round Rx buffer. round_rx_buf = new byte[ROUND_BUFFER_SIZE]; //Set init value of round buffer server variables. round_rx_buf_head = 0; round_rx_buf_tail = 0; round_rx_buf_size = 0; //open com port and connect try { if (PortName == "") { // "PortName" error. return 1; } // Setup port parameters. serialComPort.StopBits = Stop_Bit; serialComPort.DataBits = DataBits; serialComPort.BaudRate = BaudRate; serialComPort.PortName = PortName; serialComPort.Parity = Parity.None; //Set DataReceived event function. serialComPort.DataReceived += new SerialDataReceivedEventHandler(PortDataReceived); // Opening port. serialComPort.Open(); if (serialComPort.IsOpen) { // Port opened OK. return 0; } } catch (Exception e1) { MessageBox.Show(e1.Message); // Some error happend. return 2; } // Just return :) . return 3; }
private void ReceiveCallback(UdpClient client) { IPEndPoint e = null; float lastSpeedInMS = 0; DateTime lastSpeedTime = DateTime.MinValue; double distanceSM = 0, lastDistanceSM = 0; byte distanceByte = 0; while (true) { byte[] receivedBytes = client.Receive(ref e); //get speed float speedInMS = System.BitConverter.ToSingle(receivedBytes, 28); float speed = speedInMS * 3.6f; //convert speed to renault's dashbord int dashbordSpeed = (int)speed < 5 ? 0 : 0x190 + 0x62 * ((int)speed - 5); if (lastSpeedInMS > 0.5 && lastSpeedTime != null) { TimeSpan deltaTime = DateTime.Now - lastSpeedTime; if (deltaTime.TotalMilliseconds < 500) { distanceSM += lastSpeedInMS * 100 * (deltaTime.TotalMilliseconds / 1000.0); byte increment = (byte)((distanceSM - lastDistanceSM) / 9.4921875); lastDistanceSM += increment * 9.4921875; distanceByte += increment; } } lastSpeedTime = DateTime.Now; lastSpeedInMS = speedInMS; //create data for physical dashbord byte[] convertedData = BitConverter.GetBytes(dashbordSpeed); ReceivedData ABSData = new ReceivedData() { CanId = 0x354, DLC = 8, Time = DateTime.Now.Second + DateTime.Now.Millisecond / 1000, IsExtId = false, Payload = new byte[] { convertedData[1], convertedData[0], 0, distanceByte, 0, 0, 0, 0 } }; RaiseReceivedData(ABSData); //get engine rmp and maximum rpm int rpm = (int)(System.BitConverter.ToSingle(receivedBytes, 148) * 10); int maxrpm = (int)(System.BitConverter.ToSingle(receivedBytes, 252) * 10); //convert rpm to renault's dashbord int dashbordRPM = 0x10FF + (int)(((double)rpm / maxrpm) * (0xE0FF - 0x10FF)); dashbordRPM = dashbordRPM > 0xE0FF ? 0xE0FF : dashbordRPM; convertedData = BitConverter.GetBytes(dashbordRPM); //create data for physical panel ReceivedData EngineData = new ReceivedData() { CanId = 0x181, DLC = 8, Time = 0, IsExtId = false, Payload = new byte[] { convertedData[1], convertedData[0], 0, 0, 0, 0, 0, 0 } }; RaiseReceivedData(EngineData); } }
void Update() { processInput(); processUpdater(); int hostId; int connectionId; int channelId; byte[] buffer = new byte[1024]; int bufferSize = 1024; int recBufferSize; byte error; NetworkEventType rec = NetworkTransport.Receive(out hostId, out connectionId, out channelId, buffer, bufferSize, out recBufferSize, out error); ReceivedData data = new ReceivedData(hostId, connectionId, channelId, buffer, recBufferSize, error, null, null); switch(rec){ case NetworkEventType.Nothing: break; case NetworkEventType.ConnectEvent: onConnectEvent(ref data); break; case NetworkEventType.DataEvent: onDataEvent(ref data); break; case NetworkEventType.DisconnectEvent: onDisconnectEvent(ref data); break; } }
private void onConnectEvent(ref ReceivedData data) { Debug.Log("SCCommunicator| Incoming connection with Id: " + data.connectionId); sendMessageTo(data.connectionId, "waiting"); }
public Task WriteAsync(byte[] data) { Console.WriteLine(BitConverter.ToString(data)); return(Task.Run(() => { ReceivedData.Add(data); })); }
private void onDisconnectEvent(ref ReceivedData data) { Debug.Log("SCCommunicator| Disconnected from connection Id: " + data.connectionId); brain.processDisconnection(data.connectionId); }
private static void AdapterOnReceiveData(object obj, ReceivedData result) { //var msg = string.Join("=", bytes.Select(b => b.ToString())); Console.WriteLine(result); }
private void AskHeat_Click(object sender, EventArgs e) { SerialPort serialPort = null; // Create a new SerialPort object with default settings. serialPort = new SerialPort(); // Allow the user to set the appropriate properties. serialPort.PortName = COM.Text; serialPort.DataBits = 8; serialPort.Parity = Parity.None; serialPort.StopBits = StopBits.One; serialPort.BaudRate = 9600; // Set the read/write timeouts serialPort.ReadTimeout = 500; serialPort.WriteTimeout = 500; try { serialPort.Open(); serialPort.DiscardOutBuffer(); serialPort.DiscardInBuffer(); String ReceivedData; //RecievedData = serialPort.ReadLine(); //serialPort.DataReceived += new SerialDataReceivedEventHandler(responseHandler); serialPort.Write("i" + "\r\n"); Boolean conti = true; do { ReceivedData = serialPort.ReadLine(); if (ReceivedData.Contains('$')) { conti = false; } } while (conti); ReceivedData = ReceivedData.Replace("$", ""); ReceivedData = ReceivedData.Replace("\r", ""); ReceivedData = ReceivedData.Replace("\n", ""); AppendHeatLabel("Temperature U:" + ReceivedData.Split(',')[4] + "," + "Temperature M:" + ReceivedData.Split(',')[5]); serialPort.Close(); } catch (Exception exc) { MessageBox.Show("Serial could not be opened, please check that the device is correct one"); serialPort.Close(); } }
private async void RunAsync() { if (_Udp == null) { int tryTimes = 0; while (tryTimes < 100) { try { _Udp = new UdpClient(NetworkPortManager.Port); break; } catch (Exception) { tryTimes++; } } } _Udp.Client.ReceiveBufferSize = 1024 * 1024; _Udp.Client.SendBufferSize = 1024 * 1024; // 处理异常 // System.Net.Sockets.SocketException:远程主机强迫关闭了一个现有的连接。 uint IOC_IN = 0x80000000; uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; _Udp.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); while (IsAlive) { try { var udpReceiveResult = await _Udp.ReceiveAsync(); if (udpReceiveResult != null && udpReceiveResult.Buffer != null) { if (_StreamBuffer.Length == _StreamBuffer.Capacity) { _StreamBuffer.Reset(); } _StreamBuffer.Write(udpReceiveResult.Buffer, 0, udpReceiveResult.Buffer.Length); } if (ReceivedData != null) { ReceivedData.Invoke(udpReceiveResult.Buffer, udpReceiveResult.RemoteEndPoint); } await Task.Delay(100); } catch (Exception) { if (!IsAlive || _Udp == null) { break; } } } }
private void doAssay() { Boolean cont = true; int loop = 0; do { DateTime current = DateTime.Now; int endCycle = current.Hour * 60 * 60 + current.Minute * 60 + current.Second; if (duration < endCycle) { cont = false; } SerialPort serialPort = null; // Create a new SerialPort object with default settings. serialPort = new SerialPort(); // Allow the user to set the appropriate properties. serialPort.PortName = port; serialPort.DataBits = 8; serialPort.Parity = Parity.None; serialPort.StopBits = StopBits.One; serialPort.BaudRate = 9600; // Set the read/write timeouts serialPort.ReadTimeout = 10000; serialPort.WriteTimeout = 500; try { serialPort.Open(); serialPort.DiscardOutBuffer(); serialPort.DiscardInBuffer(); String ReceivedData; //RecievedData = serialPort.ReadLine(); //serialPort.DataReceived += new SerialDataReceivedEventHandler(responseHandler); serialPort.Write("R" + "\r\n"); Boolean conti = true; do { ReceivedData = serialPort.ReadLine(); if (ReceivedData.Contains('$')) { conti = false; } } while (conti); conti = true; serialPort.Write("i" + "\r\n"); String ReceivedData1; do { ReceivedData1 = serialPort.ReadLine(); if (ReceivedData1.Contains('$')) { conti = false; } } while (conti); conti = true; Thread.Sleep(2000); ReceivedData = ReceivedData.Replace("$", ""); ReceivedData1 = ReceivedData1.Replace("$", ""); ReceivedData = ReceivedData.Replace("\r", ""); ReceivedData1 = ReceivedData1.Replace("\r", ""); ReceivedData = ReceivedData.Replace("\n", ""); ReceivedData1 = ReceivedData1.Replace("\n", ""); AppendHeatLabel("Temperature U:" + ReceivedData1.Split(',')[4] + "," + "Temperature M:" + ReceivedData1.Split(',')[5]); AppendData(loop.ToString() + "," + ReceivedData1.Split(',')[4] + "," + ReceivedData1.Split(',')[5] + "," + ReceivedData); string resToAppend = loop.ToString() + ",U,M,"; AppendResult(loop.ToString() + "," + ReceivedData1.Split(',')[4] + "," + ReceivedData1.Split(',')[5] + "," + ReceivedData); Thread.Sleep(2000); serialPort.Close(); } catch (Exception exc) { MessageBox.Show("Serial could not be opened, please check that the device is correct one"); serialPort.Close(); } Boolean timeRunning = true; do { DateTime wait = DateTime.Now; if (endCycle + 120 < wait.Hour * 60 * 60 + wait.Minute * 60 + wait.Second) { timeRunning = false; } Thread.Sleep(100); } while (timeRunning); loop += 1; } while (cont); // Cancel the heat SerialPort serialPortCancel = null; try { // Create a new SerialPort object with default settings. serialPortCancel = new SerialPort(); // Allow the user to set the appropriate properties. serialPortCancel.PortName = port; serialPortCancel.DataBits = 8; serialPortCancel.Parity = Parity.None; serialPortCancel.StopBits = StopBits.One; serialPortCancel.BaudRate = 9600; // Set the read/write timeouts serialPortCancel.ReadTimeout = 500; serialPortCancel.WriteTimeout = 500; serialPortCancel.Open(); serialPortCancel.DiscardOutBuffer(); serialPortCancel.DiscardInBuffer(); String ReceivedData; //RecievedData = serialPort.ReadLine(); //serialPort.DataReceived += new SerialDataReceivedEventHandler(responseHandler); serialPortCancel.Write("C" + "\r\n"); Boolean conti = true; do { ReceivedData = serialPortCancel.ReadLine(); if (ReceivedData.Contains('$')) { conti = false; } } while (conti); ReceivedData = ReceivedData.Replace("$", ""); ReceivedData = ReceivedData.Replace("\r", ""); ReceivedData = ReceivedData.Replace("\n", ""); serialPortCancel.Close(); } catch (Exception exc) { MessageBox.Show("Serial could not be opened, please check that the device is correct one"); serialPortCancel.Close(); } MessageBox.Show("Assay ready"); }
/** * @brief ProcessData Функция обработки набора данных * @param buf Указатель на массив данных * @param size Размер данных */ protected void ProcessData(ref List <byte> buf, int size) { //Debug.WriteLine("ProcessData: {0}", buf.Count); GARANT_EEG_DATA frameData = new GARANT_EEG_DATA(); if (m_Rate == 250) { frameData.DataRecordsCount = 25; } else if (m_Rate == 500) { frameData.DataRecordsCount = 50; } else if (m_Rate == 1000) { frameData.DataRecordsCount = 100; } if (m_Recording && !m_RecordPaused && m_File != null) { if (m_FileWriteBuffer.Count > WRITE_FILE_BUFFER_SIZE) { m_File.Write(m_FileWriteBuffer.ToArray(), 0, m_FileWriteBuffer.Count); } m_FileWriteBuffer.AddRange(buf.Take(size)); m_WrittenDataCount++; } for (int i = 0; i < 22; i++) { if (i < 8) //main channels { int ptr = (i * frameData.DataRecordsCount * 3); for (int j = 0; j < frameData.DataRecordsCount; j++, ptr += 3) { //frameData.ChannelsData[j].Value[i] = (int)(unpack24BitValue(ptr) * 0.000447) / 10.0; // из кода matlab double v = (Unpack24BitValue(ref buf, ptr) * 0.000447) / 10.0 / 1000.0; frameData.RawChannelsData[j].Value[i] = v; frameData.FilteredChannelsData[j].Value[i] = v; // /1000.0 для перевода в микровольты (из милливольт) } } else if (i < 11) //accelerometr { //uchar *ptr = buf + ((8 * frameData.Channels.size() * 3) + (i - 8) * frameData.Accelerometr.size() * 3); } else if (i < 21) //rx { int ptr = ((8 * frameData.DataRecordsCount * 3 + 3 * 5 * 3) + (i - 11) * 1 * 3); for (int j = 0; j < 1; j++, ptr += 3) { double val = (Unpack24BitValue(ref buf, ptr) * 0.0677) / 10.0; int pos = i - 11; if (pos < 8) { frameData.ResistanceData.Value[pos] = val; } else if (pos == 8) { frameData.ResistanceData.Ref = val; } else { frameData.ResistanceData.Ground = val; } } } else { //annotations //uchar *ptr = buf + ((8 * frameData.Channels.size() * 3 + 3 * frameData.Accelerometr.size() * 3) + 10 * frameData.RX.size() * 3); } } buf.RemoveRange(0, size - 90); string jsonData = System.Text.Encoding.ASCII.GetString(buf.ToArray()); //Debug.WriteLine("data.ToString() => {0} {1}", buf.Count, jsonData); Dictionary <string, object> data = jsonData.Decode <Dictionary <string, object> >(); if (data != null) { if (data.ContainsKey("FW Version")) { m_FirmwareVersion = data["FW Version"].ToString(); //Debug.WriteLine("FW Version: {0}", m_FirmwareVersion); } if (data.ContainsKey("Battery %")) { m_BatteryStatus = int.Parse(data["Battery %"].ToString()); //Debug.WriteLine("Battery %: {0}", m_BatteryStatus); } if (data.ContainsKey("Block's Time")) { frameData.Time = double.Parse(data["Block's Time"].ToString()); //Debug.WriteLine("Block's Time: {0}", frameData.Time); } } if (m_Filters.Count > 0) { foreach (var filter in m_Filters) { if (filter == null) { continue; } float[][] channels = new float[8][]; for (int i = 0; i < 8; i++) { channels[i] = new float[frameData.DataRecordsCount]; } float multiply = 1.0f; /*int index = ui->comboBoxVoltage->currentIndex(); * if(0 == index) * { * multiply = 1000000.0; * } * else if(1 == index) * { * multiply = 1000.0; * }*/ for (int i = 0; i < 8; i++) { for (int j = 0; j < frameData.DataRecordsCount; j++) { float value = (float)frameData.RawChannelsData[j].Value[i]; if (Math.Abs(value * 1000000) >= 374000) { value = 0.0f; } else { value *= multiply; } channels[i][j] = value; } filter.Process(channels[i]); } for (int i = 0; i < 8; i++) { for (int j = 0; j < frameData.DataRecordsCount; j++) { frameData.FilteredChannelsData[j].Value[i] = (double)channels[i][j]; } } } } ReceivedData.Invoke(this, frameData); }
private static Task <bool> ProcessMessageAsync(ReceivedData data) { Interlocked.Increment(ref messageCount); return(Task.FromResult(data.AckMessage())); }
// This function is the core receive function void ReceiveMessages(string scenario, int count, string filter, string partition,ReceivedData callback) { Trace.WriteLine(Amqp.TraceLevel.Information, "Running scenario '{0}', filter '{1}'...", scenario, filter); Trace.WriteLine(Amqp.TraceLevel.Information, "Establishing a connection..."); Address address = new Address(sbNamespace, PORT, keyName, keyValue); Connection connection = new Connection(address); Trace.WriteLine(Amqp.TraceLevel.Information, "Creating a session..."); Session session = new Session(connection); Trace.WriteLine(Amqp.TraceLevel.Information, "Creating a receiver link on partition {0}...", partition); string partitionAddress = entity + "/ConsumerGroups/$default/Partitions/" + partition; // Form the filter for receiving message based on the time stamp Map filters = new Map(); if (filter != null) { filters.Add(new Amqp.Types.Symbol("apache.org:selector-filter:string"), new DescribedValue(new Amqp.Types.Symbol("apache.org:selector-filter:string"), filter)); } string lastOffset = "-1"; long lastSeqNumber = -1; DateTime lastEnqueueTime = DateTime.MinValue; ReceiverLink receiver = new ReceiverLink( session, "receiver-" + partition, new Source() { Address = partitionAddress, FilterSet = filters }, null); // loop runs until clean up is called for (; g_bThreadActive; ) { Message message = receiver.Receive(5000); if (message == null) { continue; } receiver.Accept(message); Data data = (Data)message.BodySection; // Get the data such as offset, Seq number and Devicename from the response header lastOffset = (string)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-offset")]; lastSeqNumber = (long)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-sequence-number")]; lastEnqueueTime = (DateTime)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-enqueued-time")]; var DeviceName = (string)message.MessageAnnotations[new Amqp.Types.Symbol("iothub-connection-device-id")]; callback(data.Binary, DeviceName); } receiver.Close(); session.Close(); connection.Close(); }
private void OnReceivedData(ReceivedData data) { _receivedData.Raise(this, new ChannelDataReceivedEventArgs(data)); }
private void OnDataReceived(object sender, System.EventArgs e) { ReceivedData?.Invoke(DataBaseWorker.GetDataByNumber(ObjectId, Count)); Count++; }