private void BytesReceived(object sender, BytesReceivedEventArgs e) { _incomingStream += Encoding.ASCII.GetString(e.Bytes); if (!_incomingStream.StartsWith(":")) { //throw away part message var i = _incomingStream.IndexOf(":", StringComparison.InvariantCultureIgnoreCase); if (i > 0) { _incomingStream = _incomingStream.Substring(i); } } while (_incomingStream.StartsWith(":") && _incomingStream.Contains(";")) { var end = _incomingStream.IndexOf(";", StringComparison.InvariantCultureIgnoreCase); if (end > 0) { var msg = _incomingStream.Substring(0, end + 1); if (end + 1 < _incomingStream.Length) { _incomingStream = _incomingStream.Substring(end + 1); } else { _incomingStream = ""; } MessageReceived?.Invoke(this, new CbusMessageEventArgs(CbusMessage.FromTransportString(msg))); } } }
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; } }); }