/*----------------------------------------------------------------------------- Module: CANoeFDX Interfaces: FDXSocket ------------------------------------------------------------------------------- Windows socket wrapper for CANoe FDX protocol ------------------------------------------------------------------------------- Copyright (c) Vector Informatik GmbH. All rights reserved. -----------------------------------------------------------------------------*/ using System; namespace FDXClient { class FDXSocket { /// /// Default-constructor of a FDXSocket that set default values for destination address (127.0.0.1) /// and port (2809). /// public FDXSocket() { this._mCanoeAddr = System.Net.IPAddress.Parse("127.0.0.1"); this._mPort = 2809; } /// /// This functions open the socket for further communication /// public void Open() { this._mSocket = new System.Net.Sockets.UdpClient(this._mCanoeAddr.ToString(), this._mPort); this._mNextTransmitSequenceNumber = FDXHelperSequenceNumber.kSequenceNumberStart; } /// /// This function closes the socket /// public void Close() { this._mSocket.Close(); } /// /// This function sets the destination address and port of the socket connection. This function will not reset /// the current connection. /// /// new destination adress to the host /// new UDP-port to the host public void SetCANoeAddr(string host, ushort port) { this._mCanoeAddr = System.Net.IPAddress.Parse(host); this._mPort = port; } /// /// This function sends out a FDXDatagram /// /// the datagram that is to be send /// public int Send(ref FDXDatagram datagram) { //Set the current valid sequence number datagram.SetSequenceNumber(this._mNextTransmitSequenceNumber); // convert the datagram object to a byte array var outData = datagram.GenerateBuffer(); var res = this._mSocket.Send(outData, outData.Length); // Increment the sequence number for the next datagram this._mNextTransmitSequenceNumber = FDXDatagram.IncrementSequenceNumber(this._mNextTransmitSequenceNumber); return res; } /// /// This function receives a datagram on the socket /// /// Reference to a datagram to store the information /// size of the received datagram, -1 if no data is received public int Receive(ref FDXDatagram datagram) { // Get the IPEndpoint var ep = new System.Net.IPEndPoint(this._mCanoeAddr, this._mPort); try { if (this._mSocket.Available > 0) { datagram.Buffer = this._mSocket.Receive(ref ep); } } catch (System.Net.Sockets.SocketException) { Console.Out.WriteLine("No answer from CANoe Client"); return -1; } return datagram.Buffer.Length; } private System.Net.Sockets.UdpClient _mSocket; private System.Net.IPAddress _mCanoeAddr; private ushort _mPort; private ushort _mNextTransmitSequenceNumber; } }