public static Boolean Receive(ref ICommunicationInterface ci, out PacketSpinel97 rxPacket, int timeout = 500) { rxPacket = null; byte[] buffer = new byte[1024]; // přijímací buffer int index = 0; int i; int bytesToRead = 0; DateTime dt = DateTime.Now.AddMilliseconds(timeout); // maximální timeout pro příjem zprávy while (DateTime.Now < dt) { System.Threading.Thread.Sleep(1); bytesToRead = (int)ci.BytesToRead(); if (bytesToRead > 0) { Debug.Print(bytesToRead.ToString()); } if ((bytesToRead > 0) && (index + bytesToRead < 1024)) { index += ci.Read(ref buffer, index, bytesToRead); //Debug.Print(Papouch.Utils.PapUtils.ConvertBinToHex(buffer)); i = GetSpinelPacket(ref buffer, index, out rxPacket); // testujme zda je již přijat kompletní paket if ((rxPacket != null) && (i > 0)) { //Debug.Print("packet"); return(true); } } } //if (bytesToRead!=0) //Debug.Print("timeout"); return(false); }
protected void CheckCommunicationInterface(ICommunicationInterface communicationInterface) { if (communicationInterface != null && !communicationInterface.IsUsable) { throw new InvalidOperationException("Cannot listen on an unusable communication interface."); } }
public Task JoinMulticastGroupAsync( string multicastAddress, int port, ICommunicationInterface communicationInterface, bool allowMultipleBindToSamePort = false) { throw new NotImplementedException(BaitNoSwitch); }
//public IObservable<IUdpMessage> ObservableMulticastListener( // string multicastAddress, // int port, // ICommunicationInterface communicationInterface, // bool allowMultipleBindToSamePort = false) //{ // throw new SocketException(new NotImplementedException("For UWP please use ObservableMulticastListenerAsync")); //} public async Task <IObservable <IUdpMessage> > ObservableMulticastListener( string multicastAddress, int port, ICommunicationInterface communicationInterface, bool allowMultipleBindToSamePort = false) { //Throws and exception if the communication interface is not ready og valid. CheckCommunicationInterface(communicationInterface); var serviceName = port.ToString(); await BindeUdpServiceNameAsync(communicationInterface, serviceName, allowMultipleBindToSamePort) .ConfigureAwait(false); DatagramSocket.Control.OutboundUnicastHopLimit = (byte)TTL; _isMulticastInitialized = true; MulticastAddMembership(null, multicastAddress); IpAddress = multicastAddress; Port = port; var messageCancellationTokenSource = new CancellationTokenSource(); return(CreateObservableMessageStream(messageCancellationTokenSource)); }
public async Task JoinMulticastGroupAsync( string multicastAddress, int port, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = false) { CheckCommunicationInterface(communicationInterface); var ipAddress = (communicationInterface as CommunicationInterface)?.NativeIpAddress ?? IPAddress.Any; var ipEndPoint = new IPEndPoint(ipAddress, port); InitializeUdpClient(ipEndPoint, allowMultipleBindToSamePort); MessageConcellationTokenSource = new CancellationTokenSource(); var multicastIp = IPAddress.Parse(multicastAddress); try { BackingUdpClient.JoinMulticastGroup(multicastIp, TTL); } catch (Exception ex) { throw (NativeSocketExceptions.Contains(ex.GetType())) ? new PclSocketException(ex) : ex; } _multicastAddress = multicastAddress; _multicastPort = port; await Task.Run(() => RunMessageReceiver(MessageConcellationTokenSource.Token)).ConfigureAwait(false); }
public async Task StartUdpListener( int port, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = true) { await _udpListener.StartListeningAsync(port, communicationInterface, allowMultipleBindToSamePort); }
public async Task StartListeningAsync( int port, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = false) { //Throws and exception if the communication interface is not ready og valid. CheckCommunicationInterface(communicationInterface); _streamSocketListener = new StreamSocketListener(); var localServiceName = port == 0 ? "" : port.ToString(); var adapter = (communicationInterface as CommunicationsInterface)?.NativeNetworkAdapter; if (adapter != null) { await _streamSocketListener.BindServiceNameAsync( localServiceName, SocketProtectionLevel.PlainSocket, adapter); } else { await _streamSocketListener.BindServiceNameAsync(localServiceName); } _subscription = ObservableTcpSocketConnectionsFromEvents.Subscribe( client => { _subjectTcpSocket.OnNext(client); }, ex => { _subjectTcpSocket.OnError(ex); }); }
/// <summary> /// Deattach communication interface from communication viewer /// </summary> /// <param name="CommunicationInterface">Communication interface</param> public static void DeattachInterface(ICommunicationInterface CommunicationInterface) { if (CommunicationInterface != null) { GetViewer().DeattachInterface(CommunicationInterface); } }
public async Task StartListeningAsync( int port, ICommunicationInterface listenOn = null, bool allowMultipleBindToSamePort = false) { CheckCommunicationInterface(listenOn); var ipAddress = listenOn != null ? ((CommunicationInterface)listenOn).NativeIpAddress : IPAddress.Any; _tcpListener = new TcpListener(ipAddress, port) { ExclusiveAddressUse = !allowMultipleBindToSamePort }; try { _tcpListener.Start(); } catch (PlatformSocketException ex) { throw new PclSocketException(ex); } _tcpClientSubscribe = ObservableTcpSocketFromAsync.Subscribe( client => { _subjectTcpSocket.OnNext(client); }, ex => { _subjectTcpSocket.OnError(ex); }); }
public Task StartListeningAsync( int port, ICommunicationInterface communicationInterface, bool allowMultipleBindToSamePort = false) { throw new NotImplementedException(BaitNoSwitch); }
protected IPEndPoint UdpClientInitialize( ICommunicationInterface communicationInterface, int port, bool allowMultipleBindToSamePort = false, bool isUdpMultiCast = false, IPAddress mcastAddress = null) { var ipLanAddress = (communicationInterface as CommunicationsInterface)?.NativeIpAddress ?? IPAddress.Any; var ipEndPoint = new IPEndPoint(ipLanAddress, port); #if (NETSTANDARD1_5 || NETSTANDARD1_3) if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) #else var p = Environment.OSVersion.Platform; if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) #endif { UdpWindowsClient(ipLanAddress, ipEndPoint, mcastAddress, allowMultipleBindToSamePort, isUdpMultiCast); } else { if (allowMultipleBindToSamePort) { throw new ArgumentException("The paramenter allowMultipleBindToSamePort is only available on Windows"); } UdpLinuxOrMacClient(ipLanAddress, ipEndPoint, mcastAddress, allowMultipleBindToSamePort, isUdpMultiCast); } return(ipEndPoint); }
public static Boolean SendAndReceive(ref ICommunicationInterface ci, ref PacketSpinel97 txPacket, out PacketSpinel97 rxPacket, int timeout = 500) { rxPacket = null; byte[] txData = txPacket.GetBin(); ci.Write(txData, 0, txData.Length); // ci.Write(txData); return(Receive(ref ci, out txPacket, timeout)); /* byte[] buffer = new byte[1024]; // přijímací buffer * int index = 0; * int i; * * int bytesToRead = 0; * DateTime dt = DateTime.Now.AddMilliseconds(timeout); // maximální timeout pro příjem zprávy * while (DateTime.Now < dt) * { * System.Threading.Thread.Sleep(1); * bytesToRead = (int)ci.BytesToRead(); * if ((bytesToRead > 0) && (index + bytesToRead < 1024)) * { * index += ci.Read(ref buffer, index, bytesToRead); * i = GetSpinelPacket(ref buffer, index, out rxPacket); // testujme zda je již přijat kompletní paket * if ((rxPacket != null) && (i > 0)) * { * return true; * } * } * } * return false; */ }
public void SetUp() { _communicationInterface = Substitute.For<ICommunicationInterface>(); _databaseHandler = Substitute.For<IDatabaseHandler>(); _configProvider = Substitute.For<IConfigprovider>(); _main = new DbWriterMain(_communicationInterface, _databaseHandler, _configProvider); }
public Task <IObservable <IUdpMessage> > ObservableMulticastListenerAsync( string multicastAddress, int port, ICommunicationInterface communicationInterface, bool allowMultipleBindToSamePort = false) { throw new NotImplementedException(); }
private void CommInterface_OnBufferUpdatedHandler(ICommunicationInterface CommunicationInterface, string Buffer) { lock (displayBufferLocker) { displayBufferWriter.Write(Buffer); displayBufferWriter.Flush(); latestActiveInterface = CommunicationInterface; } }
public DeviceEmulator(string deviceId, IDataSource[] dataSources, ICommunicationInterface communicationInterface) { IncludeTimeStamp = true; _communicationInterface = communicationInterface; _deviceId = deviceId; _communicationInterface.NewDataFromServerEvent += _communicationInterface_NewDataFromServerEvent; _dataSources.AddRange(dataSources); SendDataIntervalMs = 1000; }
private async Task <IObservable <IHttpRequestReponse> > GetTcpRequestResponseObservable( int port, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = false) { var tcpListener = new TcpSocketListener(); var observeTcpRequest = await tcpListener.CreateObservableListener( port, communicationInterface, allowMultipleBindToSamePort); var observable = Observable.Create <IHttpRequestReponse>( obs => { var disp = observeTcpRequest.Subscribe( tcpSocket => { var stream = tcpSocket.ReadStream; var requestHandler = new HttpParserDelegate { HttpRequestReponse = { RemoteAddress = tcpSocket.RemoteAddress, RemotePort = tcpSocket.RemotePort, TcpSocketClient = tcpSocket, RequestType = RequestType.TCP } }; var result = _httpStreamParser.Parse(requestHandler, stream, Timeout); obs.OnNext(result); }, ex => { Cleanup(); obs.OnError(ex); }, () => { Cleanup(); obs.OnCompleted(); }); return(disp); void Cleanup() { _tcpListenerPortToObservable.Remove(port); tcpListener.Dispose(); } }); return(observable); }
public void DeattachInterface(ICommunicationInterface CommunicationInterface) { string ChannelName = CommunicationInterface.FriendlyName; if (channels.ContainsKey(ChannelName)) { CommunicationChannel channel = channels[ChannelName]; channel.DeattachInterface(CommunicationInterface); } }
public async Task <IObservable <ITcpSocketClient> > CreateObservableListener( int port, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = false) { CheckCommunicationInterface(communicationInterface); _streamSocketListener = new StreamSocketListener(); var observable = Observable.Create <ITcpSocketClient>( obs => { var observeEvents = Observable.FromEventPattern < TypedEventHandler <StreamSocketListener, StreamSocketListenerConnectionReceivedEventArgs>, StreamSocketListenerConnectionReceivedEventArgs>( ev => _streamSocketListener.ConnectionReceived += ev, ev => _streamSocketListener.ConnectionReceived -= ev) .Select(handler => new TcpSocketClient(handler.EventArgs.Socket, BufferSize)); var disp = observeEvents.Subscribe( tcpClient => { obs.OnNext(tcpClient); }, ex => { Cleanup(); obs.OnError(ex); }, () => { Cleanup(); obs.OnCompleted(); }); return(disp); }); var localServiceName = port == 0 ? "" : port.ToString(); var adapter = (communicationInterface as CommunicationsInterface)?.NativeNetworkAdapter; if (adapter != null) { await _streamSocketListener.BindServiceNameAsync( localServiceName, SocketProtectionLevel.PlainSocket, adapter); } else { await _streamSocketListener.BindServiceNameAsync(localServiceName); } return(observable); }
public static async Task <IHttpListener> GetHttpListener( ICommunicationInterface communicationInterface, TimeSpan timeout = default(TimeSpan)) { if (timeout == default(TimeSpan)) { timeout = TimeSpan.FromSeconds(30); } return(new HttpListener(communicationInterface, timeout)); }
public ICommunicationInterface Instance(string ConfigString, string FriendlyName) { ICommunicationInterface Instance = null; if (Type != null) { Instance = (ICommunicationInterface)Activator.CreateInstance(Type, ConfigString, FriendlyName); } return(Instance); }
private async Task <IObservable <IHttpRequestReponse> > GetUdpRequestResponseObservable( int port, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = false) { IUdpSocketReceiver udpListener = new UdpSocketReceiver(); var observeUdpRequest = await udpListener.ObservableUnicastListener( port, communicationInterface, allowMultipleBindToSamePort); var observable = Observable.Create <IHttpRequestReponse>( obs => { var disp = observeUdpRequest.Subscribe( udpSocket => { var stream = new MemoryStream(udpSocket.ByteData); var requestHandler = new HttpParserDelegate { HttpRequestReponse = { RemoteAddress = udpSocket.RemoteAddress, RemotePort = int.Parse(udpSocket.RemotePort), RequestType = RequestType.UDP } }; var result = _httpStreamParser.Parse(requestHandler, stream, Timeout); obs.OnNext(result); }, ex => { Cleanup(); obs.OnError(ex); }, () => { Cleanup(); obs.OnCompleted(); }); return(disp); void Cleanup() { _udpReceiverPortToObservable.Remove(port); udpListener.Dispose(); } }); return(observable); }
private void CommInterface_WriteEventHandler(ICommunicationInterface CommunicationInterface, string Buffer) { if (CommunicationInterface.WriteEcho) { lock (displayBufferLocker) { displayBufferWriter.Write(Buffer); } } latestActiveInterface = CommunicationInterface; }
public async Task StartListeningAsync( int port = 0, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = false) { CheckCommunicationInterface(communicationInterface); var serviceName = port == 0 ? "" : port.ToString(); await BindeUdpServiceNameAsync(communicationInterface, serviceName, allowMultipleBindToSamePort) .ConfigureAwait(false); }
public async Task JoinMulticastGroupAsync( string multicastAddress, int port, ICommunicationInterface communicationInterface, bool allowMultipleBindToSamePort = false) { await JoinMulticastGroupAsync( multicastAddress, port, communicationInterface, null, allowMultipleBindToSamePort); }
public void AttachInterface(ICommunicationInterface CommunicationInterface, bool ClearPrevious = true) { this.latestActiveInterface = CommunicationInterface; CommunicationInterface.BufferUpdatedHandler += new OnBufferUpdatedEvent(CommInterface_OnBufferUpdatedHandler); CommunicationInterface.WriteEventHandler += new OnWriteEvent(CommInterface_WriteEventHandler); UpdateConnString(this.latestActiveInterface); if (ClearPrevious) { Clear(); } }
public async Task StartUdpMulticastListener( string ipAddr, int port, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = true) { await StartUdpMulticastListener( ipAddr, port, null, communicationInterface, allowMultipleBindToSamePort); }
public void UpdateConnString(ICommunicationInterface CommunicationInterface) { this.SafeInvoke(() => { if (CommunicationInterface != null) { this.ConnectionString.Text = CommunicationInterface.ConfigString; } else { this.ConnectionString.Text = ""; } }); }
public async Task StartUdpMulticastListener( string ipAddr, int port, IEnumerable <string> mcastIpv6AddressList, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = true) { await _udpMultiCastListener.JoinMulticastGroupAsync( ipAddr, port, communicationInterface, allowMultipleBindToSamePort); }
private void buttonCiDestroy_Click(object sender, EventArgs e) { if (ci != null) { ci.Close(); ci = null; LogMsg("DESTROY - ok"); } else { LogMsg("DESTROY - err: ci is NULL"); } checkFormControls(); }
public async Task StartListeningAsync( int port = 0, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = false) { CheckCommunicationInterface(communicationInterface); _ipEndPoint = UdpClientInitialize(communicationInterface, port, allowMultipleBindToSamePort); _cancellationTokenSource = new CancellationTokenSource(); await Task.Run(() => RunMessageReceiver(_cancellationTokenSource.Token)) .ConfigureAwait(false); }
public DbWriterMain(ICommunicationInterface communitaionInterface, IDatabaseHandler databaseHandler, IConfigprovider configprovider) { _communicationInterface = communitaionInterface; _dbHandler = databaseHandler; _configProvider = configprovider; }
/// <summary> /// Initialize a new instance of the class. /// </summary> /// <param name="watchControl">The watch control derived user control that called this form.</param> /// <exception cref="Exception">Thrown if the old Identifier associated with the control that called this form is not defined in the current data dictionary.</exception> public FormChangeWatch(WatchControl watchControl) { InitializeComponent(); m_WatchControl = watchControl; // Use the communication interface associated with the client form. m_ICommunicationInterface = m_WatchControl.ClientForm as ICommunicationInterface<ICommunicationWatch>; Debug.Assert(m_ICommunicationInterface != null); // Register the event handler for the data update event. m_IDataUpdate = m_WatchControl.ClientForm as IDataUpdate; if (m_IDataUpdate != null) { m_IDataUpdate.DataUpdate += new EventHandler(DataUpdate); } m_IPollTarget = m_WatchControl.ClientForm as IPollTarget; Debug.Assert(m_IPollTarget != null); m_OldIdentifier = (short)m_WatchControl.Identifier; try { m_WatchVariable = Lookup.WatchVariableTableByOldIdentifier.Items[m_OldIdentifier]; if (m_WatchVariable == null) { throw new ArgumentException(Resources.MBTWatchVariableNotDefined); } } catch (Exception) { throw new ArgumentException(Resources.MBTWatchVariableNotDefined); } m_WatchVariableName = m_WatchControl.VariableNameFieldText; Text = m_WatchVariableName; #region - [Units] - string units = m_WatchVariable.Units; m_LabelCurrentValueUnits.Text = units; m_LabelAllowableRangeUnits.Text = units; m_LabelNewValueUnits.Text = units; #endregion - [Units] - // Update the display by calling the DataUpdate event handler. DataUpdate(this, new EventArgs()); }
/// <summary> /// Initialize a new instance of the class. /// </summary> /// <param name="bitmaskControl">The <c>WatchControl</c> derived user control that called this form.</param> public FormChangeBitmask(WatchBitmaskControl bitmaskControl) { InitializeComponent(); m_WatchControl = bitmaskControl; // Use the communication interface associated with the client form. m_ICommunicationInterface = m_WatchControl.ClientForm as ICommunicationInterface<ICommunicationWatch>; Debug.Assert(m_ICommunicationInterface != null); // Register the event handler for the data update event. m_IDataUpdate = m_WatchControl.ClientForm as IDataUpdate; if (m_IDataUpdate != null) { m_IDataUpdate.DataUpdate += new EventHandler(DataUpdate); } m_IPollTarget = m_WatchControl.ClientForm as IPollTarget; Debug.Assert(m_IPollTarget != null); m_OldIdentifier = (short)m_WatchControl.Identifier; try { m_WatchVariable = Lookup.WatchVariableTableByOldIdentifier.Items[m_OldIdentifier]; if (m_WatchVariable == null) { throw new ArgumentException(Resources.MBTWatchVariableNotDefined); } } catch(Exception) { throw new ArgumentException(Resources.MBTWatchVariableNotDefined); } Debug.Assert(m_WatchVariable.VariableType == VariableType.Bitmask, "FormChangeBitmask.Ctor() - [m_WatchVariable.VariableType == VariableType.Bitmask]"); Text = m_WatchVariable.Name; #region - [Units] - string units = m_WatchVariable.Units; m_LabelCurrentValueUnits.Text = units; m_LabelNewValueUnits.Text = units; #endregion - [Units] - #region - [NumericUpDown] - m_NumericUpDownNewValue.Hexadecimal = m_RadioButtonHex.Checked; m_NumericUpDownNewValue.DecimalPlaces = 0; m_NumericUpDownNewValue.Increment = 1; m_NumericUpDownNewValue.Maximum = (decimal)m_WatchVariable.MaxModifyValue; m_NumericUpDownNewValue.Minimum = (decimal)m_WatchVariable.MinModifyValue; // Initialize the NumericUpDown control Value property. try { m_NumericUpDownNewValue.Value = (decimal)m_WatchControl.Value; } catch (Exception) { // The specified initial value is outside of the limits, set to the minimum value. m_NumericUpDownNewValue.Value = m_NumericUpDownNewValue.Minimum; } #endregion - [NumericUpDown] - #region - [ICheckBoxUInt32] - m_ICheckBoxUInt32 = new CheckBoxUInt32(); CheckBox[] checkBoxes; ConfigureCheckBoxes(out checkBoxes); m_ICheckBoxUInt32.CheckBoxes = checkBoxes; m_ICheckBoxUInt32.SetText(m_OldIdentifier); m_ICheckBoxUInt32.SetChecked((uint)m_WatchControl.Value); #endregion - [ICheckBoxUInt32] - // Update the display by calling the DataUpdate event handler. DataUpdate(this, new EventArgs()); // Now that the display has been initialized, disable the apply button. This will only be re-enabled when the user has specified a new watch value. m_ButtonApply.Enabled = false; }