/// <summary> /// Called whenever a datagram is received /// </summary> /// <param name="ep">The IPEndPoint of the sending device</param> /// <param name="buffer">The buffer containing the datagram</param> /// <param name="length">The length of the received datagram</param> /// <returns>The inbound netgram to propagate, if any</returns> private void _onDatagramReceived(IPEndPoint ep, byte[] buffer, int length) { int offset = 0; BvlcHeader header = null; IBvlcMessage message = null; NetgramReceivedMessage netgram = null; Mac mac = IPUtils.IPEndPointToMac(ep); try { if (length < 4) throw new Exception("Received datagram under 4 bytes long"); header = new BvlcHeader(); offset = header.Deserialize(buffer, offset); if (header.Length != length) throw new Exception("Received bvlc datagram with non-matching lengths"); message = _createMessage(header.Function); offset = message.Deserialize(buffer, offset); lock (_lock) { netgram = _processMessage(mac, message, buffer, offset, length); } if (netgram != null && Session != null) Session.QueueMessage(netgram); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } }
/// <summary> /// Sends a bvlc message /// </summary> /// <param name="mac">The BACnet mac address of the destination device</param> /// <param name="message"></param> private void _sendMessage(Mac mac, IBvlcMessage message) { // TODO: constant for buffer size, or // lease buffers from the UDPAsyncServer instance IPEndPoint ep = IPUtils.MacToIPEndPoint(mac); byte[] buffer = new byte[1500]; int offset = 0; BvlcHeader header = null; header = new BvlcHeader(); header.Function = message.Function; header.Length = 0; offset = header.Serialize(buffer, offset); offset = message.Serialize(buffer, offset); // patch the length in now that it is known buffer[2] = (byte)(offset << 8); buffer[3] = (byte)(offset); _server.Send(ep, buffer, offset); }
/// <summary> /// Sends a netgram out of this port /// </summary> /// <param name="netgram">The netgram to send</param> public void SendNetgram(OutboundNetgram netgram) { IPEndPoint ep = null; byte[] buffer = new byte[1500]; int offset = 0; BvlcHeader header = new BvlcHeader(); IBvlcMessage message = null; if (netgram.Destination.IsBroadcast()) { ep = IPUtils.MacToIPEndPoint(_bbmdMac); header.Function = FunctionCode.OriginalUnicastNpdu; //header.Function = FunctionCode.OriginalBroadcastNpdu; header.Length = 0; message = new OriginalBroadcastNpduMessage(); } else { ep = IPUtils.MacToIPEndPoint(netgram.Destination); header.Function = FunctionCode.OriginalUnicastNpdu; header.Length = 0; message = new OriginalUnicastNpduMessage(); } offset = header.Serialize(buffer, offset); offset = message.Serialize(buffer, offset); offset = netgram.Content.Serialize(buffer, offset); // patch the length buffer[2] = (byte)(offset << 8); buffer[3] = (byte)(offset); lock(this._lock) { if (_server != null) { _server.Send(ep, buffer, offset); } } }