private void ReadWrite_ValueUpdated(object sender, CharacteristicUpdatedEventArgs e) { var value = e.Characteristic.Value; _logger.Debug($"BLE receive: {ByteArrayToString(value)}"); BytesReceived?.Invoke(this, value); }
private void EndRead(IAsyncResult result) { try { if (TcpStream == null) { ClientDisconnected?.Invoke(this, null); return; } int byteRead = TcpStream.EndRead(result); if (byteRead == 0) { Close(); ClientDisconnected?.Invoke(this, null); return; } else { //Debug.WriteLine("Received " + byteRead + " bytes."); BytesReceived?.Invoke(this, new TcpServerDataEventArgs(this, buffer, byteRead)); //Build string until delimeter character is detected. EventHandler <MessageReceivedEventArgs> OnMessageReceived = MessageReceived; for (int x = 0; x < byteRead; x++) { byte b = buffer[x]; if (b != MessageDelimiter) { MessageBuffer.Add(b); } else { byte[] messageBytes = MessageBuffer.ToArray(); Message = Encoding.ASCII.GetString(messageBytes); MessageBuffer.Clear(); OnMessageReceived?.Invoke(this, new MessageReceivedEventArgs() { Client = this, ReceivedMessage = Message, ReceivedBytes = messageBytes }); ProcessReceivedMessageCallback?.Invoke(this, Message, messageBytes); } } BeginRead(); } } catch (ObjectDisposedException) { ClientDisconnected?.Invoke(this, null); return; } catch (Exception ex) { Trace.WriteLine("Exception raised from TcpServerConnection: " + ex.Message); Trace.WriteLine("Client disconnected from server."); ClientDisconnected?.Invoke(this, null); return; } }
public override int GetHashCode() { var hashCode = 637993755; hashCode = hashCode * -1521134295 + BytesReceived.GetHashCode(); hashCode = hashCode * -1521134295 + TotalBytes.GetHashCode(); return(hashCode); }
private void Receive() { while (IsRunning) { byte[] bytes = m_client.Receive(ref m_receiveEndPoint); BytesReceived?.Invoke(this, bytes); m_buffer.AddRange(bytes); ProcessBuffer(); } }
public void Connect(string portName) { Disconnect(); Arduino = new ArduinoSerial(portName); Arduino.BytesSent += (port, bytes) => BytesSent?.Invoke(port, bytes); Arduino.BytesReceived += (port, bytes) => BytesReceived?.Invoke(port, bytes); Arduino.Connect(false); _thread = new Thread(Loop); _thread.IsBackground = true; _thread.Start(); }
public ConnectResult TryConnect(string portName, bool sayhello) { if (portName == "") { return(ConnectResult.InvalidArgument); } Disconnect(); EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset); ConnectResult result = ConnectResult.None; Arduino = new ArduinoSerial(portName); Arduino.BytesSent += (port, bytes) => BytesSent?.Invoke(port, bytes); Arduino.BytesReceived += (port, bytes) => BytesReceived?.Invoke(port, bytes); ArduinoSerial.StatusChangedHandler statuschanged = status => { lock (ewh) { if (result != ConnectResult.None) { return; } if (status == ArduinoSerial.Status.Connected || status == ArduinoSerial.Status.ConnectedUnsafe) { result = ConnectResult.Success; ewh.Set(); } if (status == ArduinoSerial.Status.Error) { result = ConnectResult.Error; ewh.Set(); } } }; Arduino.StatusChanged += statuschanged; Arduino.Connect(sayhello); if (!ewh.WaitOne(300) && sayhello) { Arduino.Disconnect(); Arduino = null; return(ConnectResult.Timeout); } if (result != ConnectResult.Success) { Arduino.Disconnect(); Arduino = null; return(result); } Arduino.StatusChanged -= statuschanged; _thread = new Thread(Loop); _thread.IsBackground = true; _thread.Start(); return(ConnectResult.Success); }
private async Task OnDataReceivedAsync(byte[] messageData) { if (messageData.Length < 4) { LogDebug("Packet ended prematurely on receive"); TransmitError(ETftpErrorType.IllegalOperation, "Packet ended prematurely"); Parent.UnregisterSession(this); return; } var blockNumber = messageData.Get16BE(2); if (blockNumber != ((CurrentBlock + 1) & 0xFFFF)) { LogDebug("Block received out of sequence"); TransmitError(ETftpErrorType.IllegalOperation, "Block received out of sequence"); Parent.UnregisterSession(this); } BytesReceived += messageData.Length - 4; CurrentBlock++; TransmitAck(blockNumber); if (TransferStream == null) { if (CurrentBlock != 1) { LogDebug("ReceiveStream not created yet but not on first packet. Ending transfer"); TransmitError(ETftpErrorType.NotDefined, "Server error"); Parent.UnregisterSession(this); } TransferStream = new MemoryStream(); } TransferStream.Write(messageData, 4, messageData.Length - 4); if (messageData.Length != 516) { LogDebug("Last block received, transfer complete"); await Parent.TransferCompleteAsync(this); } else { if (IdleSince.Subtract(LastMessageTime) > TimeSpan.FromSeconds(1)) { LogDebug("Received " + BytesReceived.ToString() + " bytes so far"); LastMessageTime = IdleSince; } } }
private Task OnBytesReceived(int count) { if (count > 0) { if (BytesReceived != null) { return(BytesReceived.InvokeAllAsync(this, new BytesReceivedEventArgs(count))); } } return(Task.CompletedTask); // return a fake completed task to continue on awaiting }
public FakeTransport() { Task.Run(async() => { return; while (true) { await Task.Delay(1000); BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(GetFakeMessage()))); } }); }
public static void AddBytesReceived(int increment) { if (initializationSuccesfull) { if (BytesReceived != null) { BytesReceived.IncrementBy(increment); } if (GlobalBytesReceived != null) { GlobalBytesReceived.IncrementBy(increment); } GlobalLog.Print("NetworkingPerfCounters::AddBytesReceived(" + increment.ToString() + ")"); } }
void Do() { try { _port.Open(); byte[] inBuffer = new byte[255]; List <byte> outBuffer = new List <byte>(); while (true) { // read if (_port.BytesToRead > 0) { int count = _port.Read(inBuffer, 0, inBuffer.Length); if (DEBUG_MESSAGE) { Debug.WriteLine($"[{_name}] " + string.Join(" ", inBuffer.Take(count).Select(b => b.ToString("X2")))); } lock (_inBuffer) _inBuffer.AddRange(inBuffer.Take(count)); BytesReceived?.Invoke(_inBuffer.ToArray()); if (DEBUG_MESSAGE && _time != DateTime.MinValue) { Debug.WriteLine("Delay: " + (DateTime.Now - _time).TotalMilliseconds); } } // write lock (_outBuffer) { outBuffer.Clear(); _outBuffer.ForEach(item => outBuffer.AddRange(item)); _outBuffer.Clear(); } if (outBuffer.Count > 0) { _port.Write(outBuffer.ToArray(), 0, outBuffer.Count); lock (_inBuffer) _inBuffer.Clear(); } } } finally { _port.Close(); } }
internal virtual void OnBytesReceived(INetworkNode From, int NumberOfBytes) { if ((BytesReceived == null) || (From == null) || (NumberOfBytes <= 0)) { return; } Task.Run(() => { BytesReceived?.Invoke(this, new InternetBytesTransferredEventArgs { Remote = From, Local = this, Direction = CommunicationDirection.Inbound, NumBytes = NumberOfBytes }); }); }
/// <summary> /// Format the data section of a FTP termination record. /// </summary> /// <returns>String representation of a FTP termination record.</returns> public override string ToString() { return(StartTime.ToString().PadRight(22, ' ') + " " + EndTime.ToString().PadRight(22, ' ') + " " + VseTaskId.ToString().PadRight(2 + 5, ' ') + " " + FtpNodeName.PadRight(16, ' ') + " " + FtpUserId.PadRight(8, ' ') + " " + VseIp.PadRight(15, ' ') + " " + VsePort.ToString().PadRight(8, ' ') + " " + ClientPort.ToString().PadRight(11, ' ') + " " + ClientIp.PadRight(15, ' ') + " " + ForeignDataIp.PadRight(15, ' ') + " " + FilesSent.ToString().PadRight(10, ' ') + " " + FilesReceived.ToString().PadRight(10, ' ') + " " + BytesSentAcked.ToString().PadRight(20, ' ') + " " + BytesReceived.ToString().PadRight(20, ' ') + " " + GeneralFlagFormatter(GeneralFlag).PadRight(8, ' ') + " " + SslFlagFormatter(SslFlag).ToString().PadRight(5, ' ')); }
public void RegisterMetrics(MetricFactory metrics) { if (!_socketCounters.Enabled) { return; } OutgoingConnectionEstablished = metrics.CreateCounter("dotnet_sockets_connections_established_outgoing_total", "The total number of outgoing established TCP connections"); var lastEstablishedOutgoing = 0.0; _socketCounters.Events.OutgoingConnectionsEstablished += e => { OutgoingConnectionEstablished.Inc(e.Mean - lastEstablishedOutgoing); lastEstablishedOutgoing = e.Mean; }; IncomingConnectionEstablished = metrics.CreateCounter("dotnet_sockets_connections_established_incoming_total", "The total number of incoming established TCP connections"); var lastEstablishedIncoming = 0.0; _socketCounters.Events.IncomingConnectionsEstablished += e => { IncomingConnectionEstablished.Inc(e.Mean - lastEstablishedIncoming); lastEstablishedIncoming = e.Mean; }; BytesReceived = metrics.CreateCounter("dotnet_sockets_bytes_received_total", "The total number of bytes received over the network"); var lastReceived = 0.0; _socketCounters.Events.BytesReceived += e => { BytesReceived.Inc(e.Mean - lastReceived); lastReceived = e.Mean; }; var lastSent = 0.0; BytesSent = metrics.CreateCounter("dotnet_sockets_bytes_sent_total", "The total number of bytes sent over the network"); _socketCounters.Events.BytesSent += e => { BytesSent.Inc(e.Mean - lastSent); lastSent = e.Mean; }; }
public async Task SendBytes(byte[] bytes) { var _ = Task.Run(async() => { var msg = Encoding.ASCII.GetString(bytes); var cmsg = CbusMessage.FromTransportString(msg); switch (cmsg.OpCode) { case CbusOpCodes.QNN: BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(":SB060NB60102A5080D;"))); BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(":SB020NB60100A5050F;"))); BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(":SB040NB60101A5050F;"))); BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(":SB080NB60103A5200F;"))); break; case CbusOpCodes.RQNPN: var m = cmsg as ReadNodeParameterByIndexMessage; BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(new ReadNodeParameterByIndexResponseMessage { NodeNumber = m.NodeNumber, ParameterIndex = 1, ParameterValue = 165 }.TransportString))); BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(new ReadNodeParameterByIndexResponseMessage { NodeNumber = m.NodeNumber, ParameterIndex = 3, ParameterValue = (byte)((m.NodeNumber == 256 || m.NodeNumber == 257) ? 8 : (m.NodeNumber == 258 ? 5 : 32)) }.TransportString))); BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(new ReadNodeParameterByIndexResponseMessage { NodeNumber = m.NodeNumber, ParameterIndex = 6, ParameterValue = (byte)((m.NodeNumber == 259) ? 127 : 10) }.TransportString))); break; } }); }
public async Task Open() { _cts = new CancellationTokenSource(); _port = new SerialPort(_portName); try { _port.Open(); } catch (Exception e) { } var buffer = new byte[30]; while (!_cts.IsCancellationRequested) { try { var read = await _port.BaseStream.ReadAsync(buffer, 0, buffer.Length, _cts.Token); BytesReceived?.Invoke(this, new BytesReceivedEventArgs(buffer.Take(read).ToArray())); } catch (TaskCanceledException) { //ok } catch (Exception e) { } } }
protected void RaiseBytesReceived(byte[] message) { BytesReceived?.Invoke(this, message); }
public override int GetHashCode() { return(this.GetType().FullName.GetHashCode() ^ Address.GetHashCode() ^ vectors.GetHashCode() ^ NumVectors.GetHashCode() ^ BytesReceived.GetHashCode() ^ Flags.GetHashCode() ^ ControlMessages.GetHashCode() ^ _num_control_messages.GetHashCode()); }
public void Dispose() { CurrentBandwidth.Dispose(); BytesSent.Dispose(); BytesReceived.Dispose(); }
protected virtual void OnBytesReceived(BytesReceivedEventArgs e) => BytesReceived?.Invoke(this, e);
public bool Equals(InputMessage other) { return(true && Address.Equals(other.Address) && vectors.Equals(other.vectors) && NumVectors.Equals(other.NumVectors) && BytesReceived.Equals(other.BytesReceived) && Flags.Equals(other.Flags) && ControlMessages.Equals(other.ControlMessages) && _num_control_messages.Equals(other._num_control_messages)); }
private void OnBytesReceived(UDPPacketReceivedEventArgs e) { BytesReceived?.Invoke(this, e); }
protected virtual void OnBytesReceived(byte[] e) { BytesReceived?.Invoke(this, e); }
protected void OnBytesReceived(byte[] data) { recQueue.EnqueueRange(data, 0, data.Length); BytesReceived?.BeginInvoke(data, null, null); }
public static void ChangeTrafic(TraficType type, int xbytes) { float bytes = xbytes / 1024f; try { switch (type) { case TraficType.Received: ReceivedPackets++; Winda.Other.Settings.Mainform.listStats.Items[4].SubItems[1].Text = ReceivedPackets.ToString(); BytesReceived = BytesReceived + bytes; Winda.Other.Settings.Mainform.listStats.Items[0].SubItems[1].Text = BytesReceived.ToString(); Winda.Other.Settings.Mainform.listStats.Items[1].SubItems[1].Text = bytes.ToString(); DrawRe((int)xbytes); break; case TraficType.Sent: SentPackets++; BytesSent = BytesSent + bytes; Winda.Other.Settings.Mainform.listStats.Items[2].SubItems[1].Text = BytesSent.ToString(); Winda.Other.Settings.Mainform.listStats.Items[3].SubItems[1].Text = bytes.ToString(); Winda.Other.Settings.Mainform.listStats.Items[5].SubItems[1].Text = SentPackets.ToString(); DrawSe((int)xbytes); break; } } catch { } }
protected internal override void RaiseBytesReceived(IClientInfo client, byte[] data) { BytesReceived?.Invoke(client, data); }