/// <summary> /// Initializes a new instance of the <see cref="ForwarderDevice"/> class. /// </summary> /// <param name="context">The <see cref="NetMQContext"/> to use when creating the sockets.</param> /// <param name="poller">The <see cref="Poller"/> to use.</param> /// <param name="frontendBindAddress">The endpoint used to bind the frontend socket.</param> /// <param name="backendBindAddress">The endpoint used to bind the backend socket.</param> /// <param name="mode">The <see cref="DeviceMode"/> for the device.</param> public ForwarderDevice(NetMQContext context, Poller poller, string frontendBindAddress, string backendBindAddress, DeviceMode mode = DeviceMode.Threaded) : base(poller, context.CreateSubscriberSocket(), context.CreatePublisherSocket(), mode) { FrontendSetup.Bind(frontendBindAddress); BackendSetup.Bind(backendBindAddress); }
/// <summary> /// Initializes a new instance of the <see cref="DeviceBase"/> class. /// </summary> /// <param name="frontendSocket"> /// A <see cref="NetMQSocket"/> that will pass incoming messages to <paramref name="backendSocket"/>. /// </param> /// <param name="backendSocket"> /// A <see cref="NetMQSocket"/> that will receive messages from (and optionally send replies to) <paramref name="frontendSocket"/>. /// </param> /// <param name="mode">The <see cref="DeviceMode"/> for the current device.</param> /// <param name="poller">The <see cref="Poller"/> to use.</param> protected DeviceBase(Poller poller, NetMQSocket frontendSocket, NetMQSocket backendSocket, DeviceMode mode) { if (frontendSocket == null) { throw new ArgumentNullException("frontendSocket"); } if (backendSocket == null) { throw new ArgumentNullException("backendSocket"); } FrontendSocket = frontendSocket; BackendSocket = backendSocket; FrontendSetup = new DeviceSocketSetup(FrontendSocket); BackendSetup = new DeviceSocketSetup(BackendSocket); m_poller = poller; FrontendSocket.ReceiveReady += FrontendHandler; BackendSocket.ReceiveReady += BackendHandler; m_poller.AddSocket(FrontendSocket); m_poller.AddSocket(BackendSocket); m_runner = mode == DeviceMode.Blocking ? new DeviceRunner(this) : new ThreadedDeviceRunner(this); }
/// <summary> /// Start polling for messages. /// </summary> private void StartPolling() { Task.Run(() => { using (var subSocket = context.CreateSubscriberSocket()) { byte[] buffer = null; subSocket.Options.ReceiveHighWatermark = 1000; subSocket.Connect(SubscriberAddress); subSocket.Subscribe(String.Empty); subSocket.ReceiveReady += (s, a) => { buffer = subSocket.Receive(); if (MessageRecieved != null) { MessageRecieved.Report(buffer.ToObject <Taurus.FeedMux>()); } }; // Poll. poller = new Poller(); poller.AddSocket(subSocket); poller.PollTillCancelled(); token.ThrowIfCancellationRequested(); } }, token).ContinueWith(ant => { pollerCancelled.Set(); }, TaskContinuationOptions.OnlyOnCanceled); }
public void ExternalPoller() { bool triggered = false; using (NetMQContext context = NetMQContext.Create()) { Poller poller = new Poller(); using (NetMQScheduler scheduler = new NetMQScheduler(context, poller)) { poller.PollTillCancelledNonBlocking(); Task task = new Task(() => { triggered = true; }); task.Start(scheduler); task.Wait(); Assert.IsTrue(triggered); } poller.CancelAndJoin(); } }
/// <summary> /// Create a new instance of the <see cref="DeviceBase"/> class. /// </summary> /// <param name="poller">the <see cref="Poller"/> to use for detecting when messages are available</param> /// <param name="frontendSocket"> /// A <see cref="NetMQSocket"/> that will pass incoming messages to <paramref name="backendSocket"/>. /// </param> /// <param name="backendSocket"> /// A <see cref="NetMQSocket"/> that will receive messages from (and optionally send replies to) <paramref name="frontendSocket"/>. /// </param> /// <param name="mode">the <see cref="DeviceMode"/> (either Blocking or Threaded) for this device</param> protected DeviceBase(Poller poller, [NotNull] NetMQSocket frontendSocket, [NotNull] NetMQSocket backendSocket, DeviceMode mode) { if (frontendSocket == null) throw new ArgumentNullException("frontendSocket"); if (backendSocket == null) throw new ArgumentNullException("backendSocket"); FrontendSocket = frontendSocket; BackendSocket = backendSocket; FrontendSetup = new DeviceSocketSetup(FrontendSocket); BackendSetup = new DeviceSocketSetup(BackendSocket); m_poller = poller; FrontendSocket.ReceiveReady += FrontendHandler; BackendSocket.ReceiveReady += BackendHandler; m_poller.AddSocket(FrontendSocket); m_poller.AddSocket(BackendSocket); m_runner = mode == DeviceMode.Blocking ? new DeviceRunner(this) : new ThreadedDeviceRunner(this); }
public void PollOnce() { int count = 0; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(50)); timer.Elapsed += (a, s) => { count++; if (count == 3) { timer.Enable = false; } }; // NOTE if the PollTimeout here is less than the timer period, it won't fire during PollOnce -- is this by design? using (var poller = new Poller(timer) { PollTimeout = 1000 }) { Stopwatch stopwatch = Stopwatch.StartNew(); poller.PollOnce(); var pollOnceElapsedTime = stopwatch.ElapsedMilliseconds; Assert.AreEqual(1, count, "the timer should have fired just once during the call to PollOnce()"); Assert.Less(pollOnceElapsedTime, 90, "pollonce should return soon after the first timer firing."); } }
public void RunMultipleTimes() { using (NetMQContext contex = NetMQContext.Create()) using (Poller poller = new Poller()) { int count = 0; NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(50)); timer.Elapsed += (a, s) => { count++; if (count == 3) { timer.Enable = false; } }; poller.AddTimer(timer); Task.Factory.StartNew(poller.Start); Thread.Sleep(300); poller.Stop(); Assert.AreEqual(3, count); } }
public void TwoTimers() { using (NetMQContext contex = NetMQContext.Create()) using (Poller poller = new Poller()) { NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(52)); NetMQTimer timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(40)); int count = 0; timer.Elapsed += (a, s) => { count++; timer.Enable = false; timer2.Enable = false; }; poller.AddTimer(timer); int count2 = 0; timer2.Elapsed += (s, a) => { count2++; }; poller.AddTimer(timer2); poller.PollTillCancelledNonBlocking(); Thread.Sleep(300); poller.CancelAndJoin(); Assert.AreEqual(1, count); Assert.AreEqual(1, count2); } }
public void RunMultipleTimes() { using (NetMQContext contex = NetMQContext.Create()) using (Poller poller = new Poller()) { int count = 0; NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(50)); timer.Elapsed += (a, s) => { count++; if (count == 3) { timer.Enable = false; } }; poller.AddTimer(timer); poller.PollTillCancelledNonBlocking(); Thread.Sleep(300); poller.CancelAndJoin(); Assert.AreEqual(3, count); } }
public void ExternalPoller() { bool triggered = false; using (NetMQContext context = NetMQContext.Create()) { Poller poller = new Poller(); using (NetMQScheduler scheduler = new NetMQScheduler(context, poller)) { Task.Factory.StartNew(poller.Start); Task task = new Task(() => { triggered = true; }); task.Start(scheduler); task.Wait(); Assert.IsTrue(triggered); } poller.Stop(); } }
public void ReceiveImplicitConnect_ValidScenario_ShouldReturnRequest() { const string hostAddress = "tcp://localhost:5557"; var loggingMessages = new List <string> (); // setup the counter socket for communication using (var context = NetMQContext.Create()) using (var broker = context.CreateRouterSocket()) using (var poller = new Poller()) using (var session = new MDPWorker(hostAddress, "test", new[] { (byte)'1' })) { broker.Bind(hostAddress); // we need to pick up any message in order to avoid errors broker.ReceiveReady += (s, e) => { var msg = e.Socket.ReceiveMultipartMessage(); // we expect to receive a 5 Frame message // [WORKER ADR][EMPTY]["MDPW01"]["READY"]["test"] if (msg.FrameCount != 5) { Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount); } // make sure the frames are as expected Assert.That(msg[1], Is.EqualTo(NetMQFrame.Empty)); Assert.That(msg[2].ConvertToString(), Is.EqualTo("MDPW01")); Assert.That(msg[3].BufferSize, Is.EqualTo(1)); Assert.That(msg[3].Buffer[0], Is.EqualTo((byte)MDPCommand.Ready)); Assert.That(msg[4].ConvertToString(), Is.EqualTo("test")); // tell worker to stop gracefully var reply = new NetMQMessage(); reply.Push(new[] { (byte)MDPCommand.Kill }); // push MDP Version reply.Push(msg[2]); // push separator reply.Push(NetMQFrame.Empty); // push worker address reply.Push(msg[0]); // send reply which is a request for the worker e.Socket.SendMessage(reply); }; poller.AddSocket(broker); Task.Factory.StartNew(poller.PollTillCancelled); // set the event handler to receive the logging messages session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info); // initialise the worker - broker protocol session.Receive(null); poller.CancelAndJoin(); poller.RemoveSocket(broker); Assert.That(loggingMessages.Count, Is.EqualTo(5)); Assert.That(loggingMessages[0], Is.EqualTo("[WORKER] connected to broker at tcp://localhost:5557")); Assert.That(loggingMessages[1].Contains("[WORKER] sending"), Is.True); Assert.That(loggingMessages[2].Contains("[WORKER] received")); Assert.That(loggingMessages[4].Contains("abandoning")); } }
public void Can_handle_rolling_log() { var file = Path.Combine(".", "testfile4.xml"); if (File.Exists(file)) { File.Delete(file); } File.WriteAllText(file, _buffer); var outofbounds = new ConcurrentStack <OutOfBoundsEvent>(); var exceptionWhileReading = new ConcurrentStack <Exception>(); var files = new ConcurrentQueue <LogEntry>(); using (var watcher = new Poller <LogEntry>(new FileWithPosition(file), 30, new LogEntryParser()).Tap(w => { w.LogEntry += l => { files.Enqueue(l); }; w.OutOfBounds += () => { outofbounds.Push(new OutOfBoundsEvent()); }; w.ExceptionOccurred += e => { exceptionWhileReading.Push(e); }; })) { watcher.Init(); File.WriteAllText(file, ""); Thread.Sleep(100 /*750*3*/); Assert.True(outofbounds.ToArray().Length >= 1, "outofbounds>=1"); } }
/// <summary> /// Initializes a new instance of the <see cref="StreamerDevice"/> class. /// </summary> /// <param name="context">The <see cref="NetMQContext"/> to use when creating the sockets.</param> /// <param name="poller">The <see cref="Poller"/> to use.</param> /// <param name="frontendBindAddress">The endpoint used to bind the frontend socket.</param> /// <param name="backendBindAddress">The endpoint used to bind the backend socket.</param> /// <param name="mode">The <see cref="DeviceMode"/> for the device.</param> public StreamerDevice(NetMQContext context, Poller poller, string frontendBindAddress, string backendBindAddress, DeviceMode mode = DeviceMode.Threaded) : base(poller, context.CreatePullSocket(), context.CreatePushSocket(), mode) { FrontendSetup.Bind(frontendBindAddress); BackendSetup.Bind(backendBindAddress); }
void t_Elapsed() { NetMQContext ctx = NetMQContext.Create(); NetMQSocket socket = ctx.CreateSubscriberSocket(); // TODO: change socket connection ip, port socket.Connect("tcp://172.16.12.188:5555"); socket.Subscribe(_tagID.ToString("000")); socket.ReceiveReady += (s, a) => { string topic = socket.ReceiveString(); string message = socket.ReceiveString(); msg m = JsonConvert.DeserializeObject <msg>(message); WriteText(m); //Application.DoEvents(); }; Poller poller = new Poller(); poller.AddSocket(socket); poller.Start(); }
public void Can_detect_changes_to_file() { var file = Path.Combine(".", "testfile3.xml"); if (File.Exists(file)) { File.Delete(file); } File.WriteAllText(file, _buffer); var outofbounds = new ConcurrentStack <OutOfBoundsEvent>(); var exceptionWhileReading = new ConcurrentStack <Exception>(); var files = new ConcurrentQueue <LogEntry>(); using (var watcher = new Poller <LogEntry>(new FileWithPosition(file), 30, new LogEntryParser()).Tap(w => { w.LogEntry += l => { files.Enqueue(l); }; w.OutOfBounds += () => { outofbounds.Push(new OutOfBoundsEvent()); }; w.ExceptionOccurred += e => { exceptionWhileReading.Push(e); }; })) { watcher.Init(); Assert.Equal(1, files.Count); File.AppendAllText(file, _buffer); Thread.Sleep(100 /*750*3*/); Assert.Equal(2, files.Count); } }
public static void Main(string[] args) { using (var context = ZmqContext.Create()) { // Connect to task ventilator and weather server using (ZmqSocket receiver = context.CreateSocket(SocketType.PULL), subscriber = context.CreateSocket(SocketType.SUB)) { receiver.Connect("tcp://localhost:5557"); subscriber.Connect("tcp://localhost:5556"); subscriber.Subscribe(Encoding.Unicode.GetBytes("10001 ")); receiver.ReceiveReady += ReceiverPollInHandler; subscriber.ReceiveReady += SubscriberPollInHandler; var poller = new Poller(new List <ZmqSocket> { }); // Process messages from both sockets while (true) { poller.Poll(); } } } }
public void Run() { _logger.LogInformation($"This is a console application for {_config.Value.Pids}"); _connection = new ObdSerialPortConnection(_logger, _settings); _connection.Open(); //Getting available-supported pids var supportedPidsCommand = new SupportedPidsCommand(); supportedPidsCommand.Execute(_connection); var supportedPids = supportedPidsCommand.SupportedPids; //converting Car List to PidObject List with percents var configPids = _config.Value.Pids; var pidObjs = configPids.Select(pid => new PidObj(pid.Name, pid.Code, pid.Priority)).ToList(); //start algorithm, get output queue var poller = new Poller(pidObjs, supportedPids); _pidObjectsList = poller._queue; foreach (var code in _pidObjectsList) { _commands.Add(Factory.GetCommand(code.Code)); } Execute(); }
/// <summary> /// Initializes a new instance of the <see cref="QueueDevice"/> class. /// </summary> /// <param name="context">The <see cref="NetMQContext"/> to use when creating the sockets.</param> /// <param name="poller">The <see cref="Poller"/> to use.</param> /// <param name="frontendBindAddress">The endpoint used to bind the frontend socket.</param> /// <param name="backendBindAddress">The endpoint used to bind the backend socket.</param> /// <param name="mode">The <see cref="DeviceMode"/> for the device.</param> public QueueDevice(NetMQContext context, Poller poller, string frontendBindAddress, string backendBindAddress, DeviceMode mode = DeviceMode.Threaded) : base(poller, context.CreateRouterSocket(), context.CreateDealerSocket(), mode) { FrontendSetup.Bind(frontendBindAddress); BackendSetup.Bind(backendBindAddress); }
public void ResponsePoll() { using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) using (var poller = new Poller(rep) { PollTimeout = TestPollTimeoutMillis }) { int port = rep.BindRandomPort("tcp://127.0.0.1"); req.Connect("tcp://127.0.0.1:" + port); rep.ReceiveReady += (s, e) => { bool more; Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more)); Assert.False(more); e.Socket.SendFrame("World"); }; poller.PollTillCancelledNonBlocking(); req.SendFrame("Hello"); bool more2; Assert.AreEqual("World", req.ReceiveFrameString(out more2)); Assert.IsFalse(more2); poller.CancelAndJoin(); } }
public void Dispose() { if (_poller != null) { _poller.RemoveSocket(_worker); _poller.RemoveTimer(_heartbeatTimer); _poller = null; } if (_heartbeatTimer != null) { _heartbeatTimer.Elapsed -= heartbeatTimer_Elapsed; _heartbeatTimer = null; } if (_scheduler != null) { //_scheduler.Dispose(); } if (_worker != null) { _worker.ReceiveReady -= _worker_ReceiveReady; _worker.Disconnect("tcp://localhost:5556"); } }
public static async Task <T> GetEventually <T>(IProbe <T> probe, int timeout) where T : class { var poller = new Poller(timeout); return(await poller.GetAsync(probe)); }
public void ResponsePoll() { using (var context = NetMQContext.Create()) using (var rep = context.CreateResponseSocket()) using (var req = context.CreateRequestSocket()) using (var poller = new Poller(rep) { PollTimeout = TestPollTimeoutMillis }) { int port = rep.BindRandomPort("tcp://127.0.0.1"); req.Connect("tcp://127.0.0.1:" + port); rep.ReceiveReady += (s, e) => { bool more; Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more)); Assert.False(more); e.Socket.Send("World"); }; poller.PollTillCancelledNonBlocking(); req.Send("Hello"); bool more2; Assert.AreEqual("World", req.ReceiveFrameString(out more2)); Assert.IsFalse(more2); poller.CancelAndJoin(); } }
public async Task <IEventStore> GetEventStore(string schema) { var eventStore = new MsSqlEventStore(ConnectionString, Poller.CreateEventStoreNotifier(), schema); await eventStore.InitializeStore(); return(eventStore); }
public void Receive_BrokerDisconnectedWithLogging_ShouldReturnRequest() { const string hostAddress = "tcp://localhost:5555"; var loggingMessages = new List <string> (); // setup the counter socket for communication using (var context = NetMQContext.Create()) using (var broker = context.CreateRouterSocket()) using (var poller = new Poller()) using (var session = new MDPWorker(hostAddress, "test")) { broker.Bind(hostAddress); // we need to pick up any message in order to avoid errors but don't answer broker.ReceiveReady += (s, e) => e.Socket.ReceiveMultipartMessage(); poller.AddSocket(broker); Task.Factory.StartNew(poller.PollTillCancelled); // speed up the test session.HeartbeatDelay = TimeSpan.FromMilliseconds(250); session.ReconnectDelay = TimeSpan.FromMilliseconds(250); // set the event handler to receive the logging messages session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info); // initialise the worker - broker protocol session.Receive(null); poller.CancelAndJoin(); poller.RemoveSocket(broker); Assert.That(loggingMessages.Count(m => m.Contains("retrying")), Is.EqualTo(3)); // 3 times retrying and 1 time initial connecting Assert.That(loggingMessages.Count(m => m.Contains("localhost")), Is.EqualTo(4)); Assert.That(loggingMessages.Last().Contains("abandoning")); } }
public void RunMultipleTimes() { int count = 0; const int timerIntervalMillis = 20; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); timer.Elapsed += (a, s) => { count++; if (count == 3) { timer.Enable = false; } }; using (var poller = new Poller(timer) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Thread.Sleep(timerIntervalMillis * 6); poller.CancelAndJoin(); Assert.AreEqual(3, count); } }
public void StartUpdateChecking() { if (Poller != null) { Poller.Start(); } }
//************************************************************** // RestartApp() // - Shuts down the app, returns the AppStart restart return code // - May not work for all apps. Application.Exit() is a soft shutdown // - if your app has threads hanging around, the shutdown won't work // - Use the ApplicationExit() event //************************************************************** public void RestartApp() { Environment.ExitCode = RestartAppReturnValue; Application.Exit(); Poller.Stop(); Downloader.Stop(); }
static void Main(string[] args) { using (NetMQContext context = NetMQContext.Create()) { using (WSRouter router = context.CreateWSRouter()) using (WSPublisher publisher = context.CreateWSPublisher()) { router.Bind("ws://localhost:80"); publisher.Bind("ws://localhost:81"); router.ReceiveReady += (sender, eventArgs) => { string identity = router.ReceiveString(); string message = router.ReceiveString(); router.SendMore(identity).Send("OK"); publisher.SendMore("chat").Send(message); }; Poller poller = new Poller(); poller.AddSocket(router); // we must add the publisher to the poller although we are not registering to any event. // The internal stream socket handle connections and subscriptions and use the events internally poller.AddSocket(publisher); poller.Start(); } } }
private void Run(PairSocket shim) { m_shim = shim; shim.ReceiveReady += OnShimMessage; m_timeoutTimer = new NetMQTimer(TimeOut); m_timeoutTimer.Elapsed += OnTimeoutTimer; m_reconnectTimer = new NetMQTimer(ReconnectTimer); m_reconnectTimer.Elapsed += OnReconnectTimer; m_poller = new Poller(shim); m_poller.AddTimer(m_timeoutTimer); m_poller.AddTimer(m_reconnectTimer); shim.SignalOK(); Connect(); m_poller.PollTillCancelled(); if (m_subscriber != null) { m_subscriber.Dispose(); } }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { //Load Config DAQConfiguration _daqConfig = (DAQConfiguration)ConfigHandler.LoadConfig(ConfigType.DAQConfig, "DAQConfig.json"); TransmitterArrayConfiguration _transmitterArrayConfig = (TransmitterArrayConfiguration)ConfigHandler.LoadConfig(ConfigType.TransmitterConfig, "TransmitterConfig.json"); //DAQ IDaq _daq = new CommonDAQ(_daqConfig); //transmitter array TransmitterArray _transmitterArray = new TransmitterArray(_transmitterArrayConfig, _daq); //or poller Poller _poller = new Poller(_transmitterArray); _poller.SetSamplingRate(1000); _poller.Start(); _poller.OnDataUpdated += _poller_OnDataUpdated1; while (true) { //Tuple<DateTime, List<TransmitterData>> dataPacket = _transmitterArray.PollAll(); //Console.WriteLine( "Data: " + dataPacket.Item1.ToString( "yyyy-mm-dd HH:mm:ffff" ) ); //foreach( TransmitterData a in dataPacket.Item2 ) //{ // Console.WriteLine( a.ID + " " + a.Value ); //} Console.ReadLine(); } }
/// <summary> /// Dispose managed resources. /// </summary> /// <param name="disposing">Is desposing.</param> protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { CancelPolling(); if (pubSocket != null) { pubSocket.Disconnect(PublisherAddress); pubSocket.Dispose(); pubSocket = null; } if (poller != null) { poller.Dispose(); poller = null; } if (context != null) { context.Terminate(); context.Dispose(); context = null; } if (source != null) { source.Dispose(); source = null; } } // Shared cleanup logic. disposed = true; } }
public void PollOnce() { using (NetMQContext contex = NetMQContext.Create()) using (Poller poller = new Poller()) { int count = 0; NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(50)); timer.Elapsed += (a, s) => { count++; if (count == 3) { timer.Enable = false; } }; poller.AddTimer(timer); Stopwatch stopwatch = Stopwatch.StartNew(); poller.PollOnce(); var pollOnceElapsedTime = stopwatch.ElapsedMilliseconds; Assert.AreEqual(1, count, "the timer should have fired just once during the call to PollOnce()"); Assert.Less(pollOnceElapsedTime, 90, "pollonce should return soon after the first timer firing."); } }
/// <summary> /// Create a new instance of a Proxy (NetMQ.Proxy) /// with the given sockets to serve as a front-end, a back-end, and a control socket. /// </summary> /// <param name="frontend">the socket that messages will be forwarded from</param> /// <param name="backend">the socket that messages will be forwarded to</param> /// <param name="control">this socket will have messages also sent to it - you can set this to null if not needed</param> /// <param name="poller">an optional external poller to use within this proxy</param> public Proxy([NotNull] NetMQSocket frontend, [NotNull] NetMQSocket backend, [CanBeNull] NetMQSocket control = null, Poller poller = null) { m_frontend = frontend; m_backend = backend; m_control = control; m_externalPoller = poller != null; m_poller = poller; }
public void ReturnTimedOutGivenPollingFunctionReturnsFalse() { this.functionRunLimit = 3; var poller = new Poller(); poller.Start(() => false); Assert.That(poller.State == Poller.PollerState.TimedOut); }
public void ReturnFinishedGivenPollingFunctionReturnsTrueAfterMultipleAttempts() { this.functionRunLimit = 3; var poller = new Poller(); poller.Start(this.PollingFunction); Assert.That(poller.State == Poller.PollerState.Finished); }
public void ReturnFinishedGivenPollingFunctionReturnsTrue() { this.functionRunLimit = 3; var poller = new Poller(); poller.Start(() => true); Assert.That(poller.State == Poller.PollerState.Finished); }
public ComplementaryFilter(IAccelerometer accelerometer, IGyroscope gyroscope, int samplePeriodMs = 10, bool usePerformanceTimer = false) { this.accel = accelerometer; this.gyro = gyroscope; accelPoller = new Poller<IAccelerometer>(accelerometer, samplePeriodMs, usePerformanceTimer); accelPoller.OnSensorValueChanged += PollerEvent; if (accelerometer != gyroscope) // if we have two different sensors { gyroPoller = new Poller<IAccelerometer>(accelerometer, samplePeriodMs, usePerformanceTimer); gyroPoller.OnSensorValueChanged += PollerEvent; } }
public void CanDisposeSchedulerWhenPollerExternalAndCancelled() { using (var poller = new Poller()) using (var scheduler = new NetMQScheduler(poller)) { poller.PollTillCancelledNonBlocking(); var startedEvent = new ManualResetEvent(false); Task.Factory.StartNew(() => { startedEvent.Set(); }, CancellationToken.None, TaskCreationOptions.None, scheduler); startedEvent.WaitOne(); poller.CancelAndJoin(); } }
public void ExternalPoller() { var triggered = false; using (var poller = new Poller()) using (var scheduler = new NetMQScheduler(poller)) { poller.PollTillCancelledNonBlocking(); var task = new Task(() => { triggered = true; }); task.Start(scheduler); task.Wait(); Assert.IsTrue(triggered); } }
public SimpleAutoPulser(TimeSpan interval, params string[] eventTypes) { if(eventTypes.Length==0) throw new ArgumentOutOfRangeException("eventTypes", "At least one event type needs to be passed in."); _poller = new Poller(new FixedInterval(interval), () => { if (PulseGenerated != null) { PulseGenerated(this, eventTypes.Select(x => new Event(string.Empty) { EventType = QueueName.FromTopicName(x).ToString(), QueueName = QueueName.FromTopicName(x).ToString() }).ToArray()); } return false; }); }
public void TwoMessagesFromRouterToDealer() { using (var context = NetMQContext.Create()) using (var poller = new Poller()) using (var server = context.CreateRouterSocket()) using (var client = context.CreateDealerSocket()) { var port = server.BindRandomPort("tcp://*"); client.Connect("tcp://127.0.0.1:" + port); poller.AddSocket(client); var cnt = 0; client.ReceiveReady += (object sender, NetMQSocketEventArgs e) => { var strs = e.Socket.ReceiveMultipartStrings(); foreach (var str in strs) { Console.WriteLine(str); } cnt++; if (cnt == 2) { poller.Cancel(); } }; byte[] clientId = Encoding.Unicode.GetBytes("ClientId"); client.Options.Identity = clientId; const string request = "GET /\r\n"; const string response = "HTTP/1.0 200 OK\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "Hello, World!"; client.SendFrame(request); byte[] serverId = server.ReceiveFrameBytes(); Assert.AreEqual(request, server.ReceiveFrameString()); // two messages in a row, not frames server.SendMoreFrame(serverId).SendFrame(response); server.SendMoreFrame(serverId).SendFrame(response); poller.PollTimeout = 1000; poller.PollTillCancelled(); } }
public void Monitoring() { var listeningEvent = new ManualResetEvent(false); var acceptedEvent = new ManualResetEvent(false); var connectedEvent = new ManualResetEvent(false); using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) using (var poller = new Poller { PollTimeout = TestPollTimeoutMillis }) using (var repMonitor = new NetMQMonitor(rep, "inproc://rep.inproc", SocketEvents.Accepted | SocketEvents.Listening)) using (var reqMonitor = new NetMQMonitor(req, "inproc://req.inproc", SocketEvents.Connected)) { repMonitor.Accepted += (s, e) => acceptedEvent.Set(); repMonitor.Listening += (s, e) => listeningEvent.Set(); repMonitor.AttachToPoller(poller); int port = rep.BindRandomPort("tcp://127.0.0.1"); reqMonitor.Connected += (s, e) => connectedEvent.Set(); reqMonitor.AttachToPoller(poller); poller.PollTillCancelledNonBlocking(); req.Connect("tcp://127.0.0.1:" + port); req.SendFrame("a"); rep.SkipFrame(); rep.SendFrame("b"); req.SkipFrame(); Assert.IsTrue(listeningEvent.WaitOne(300)); Assert.IsTrue(connectedEvent.WaitOne(300)); Assert.IsTrue(acceptedEvent.WaitOne(300)); poller.CancelAndJoin(); } }
/// <summary> /// Initializes a new instance of the <see cref="Device"/> class. /// </summary> /// <param name="frontendSocket"> /// A <see cref="ZmqSocket"/> that will pass incoming messages to <paramref name="backendSocket"/>. /// </param> /// <param name="backendSocket"> /// A <see cref="ZmqSocket"/> that will receive messages from (and optionally send replies to) <paramref name="frontendSocket"/>. /// </param> /// <param name="mode">The <see cref="DeviceMode"/> for the current device.</param> protected Device(ZmqSocket frontendSocket, ZmqSocket backendSocket, DeviceMode mode) { if (frontendSocket == null) { throw new ArgumentNullException("frontendSocket"); } if (backendSocket == null) { throw new ArgumentNullException("backendSocket"); } FrontendSocket = frontendSocket; BackendSocket = backendSocket; FrontendSetup = new DeviceSocketSetup(FrontendSocket); BackendSetup = new DeviceSocketSetup(BackendSocket); DoneEvent = new ManualResetEvent(false); _poller = new Poller(); _runner = mode == DeviceMode.Blocking ? new DeviceRunner(this) : new ThreadedDeviceRunner(this); }
/// <summary> /// Create a new NetMQScheduler object within the given context, and optionally using the given poller. /// </summary> /// <param name="context">the NetMQContext to create this NetMQScheduler within</param> /// <param name="poller">(optional)the Poller for this Net to use</param> public NetMQScheduler([NotNull] NetMQContext context, [CanBeNull] Poller poller = null) { if (poller == null) { m_ownPoller = true; m_poller = new Poller(); } else { m_ownPoller = false; m_poller = poller; } m_tasksQueue = new ConcurrentQueue<Task>(); m_syncObject = new object(); var schedulerId = Interlocked.Increment(ref s_schedulerCounter); var address = string.Format("{0}://scheduler-{1}", Address.InProcProtocol, schedulerId); m_serverSocket = context.CreatePullSocket(); m_serverSocket.Options.Linger = TimeSpan.Zero; m_serverSocket.Bind(address); m_currentMessageHandler = OnMessageFirstTime; m_serverSocket.ReceiveReady += m_currentMessageHandler; m_poller.AddSocket(m_serverSocket); m_clientSocket = context.CreatePushSocket(); m_clientSocket.Connect(address); m_schedulerThread = new ThreadLocal<bool>(() => false); if (m_ownPoller) { m_poller.PollTillCancelledNonBlocking(); } }
public void Can_detect_changes_to_file() { var file = Path.Combine(".", "testfile3.xml"); if (File.Exists(file)) { File.Delete(file); } File.WriteAllText(file, _buffer); var outofbounds = new ConcurrentStack<OutOfBoundsEvent>(); var exceptionWhileReading = new ConcurrentStack<Exception>(); var files = new ConcurrentQueue<LogEntry>(); using (var watcher = new Poller<LogEntry>(new FileWithPosition(file), 30, new LogEntryParser()).Tap(w=> { w.LogEntry += l => { files.Enqueue(l); }; w.OutOfBounds += () => { outofbounds.Push(new OutOfBoundsEvent()); }; w.ExceptionOccurred += e => { exceptionWhileReading.Push(e); }; })) { watcher.Init(); Assert.Equal(1, files.Count); File.AppendAllText(file, _buffer); Thread.Sleep(100/*750*3*/); Assert.Equal(2, files.Count); } }
public void Can_handle_rolling_log() { var file = Path.Combine(".", "testfile4.xml"); if (File.Exists(file)) { File.Delete(file); } File.WriteAllText(file, _buffer); var outofbounds = new ConcurrentStack<OutOfBoundsEvent>(); var exceptionWhileReading = new ConcurrentStack<Exception>(); var files = new ConcurrentQueue<LogEntry>(); using (var watcher = new Poller<LogEntry>(new FileWithPosition(file), 30, new LogEntryParser()).Tap(w=> { w.LogEntry += l => { files.Enqueue(l); }; w.OutOfBounds += () => { outofbounds.Push(new OutOfBoundsEvent()); }; w.ExceptionOccurred += e => { exceptionWhileReading.Push(e); }; })) { watcher.Init(); File.WriteAllText(file, ""); Thread.Sleep(100/*750*3*/); Assert.True(outofbounds.ToArray().Length >= 1, "outofbounds>=1"); } }
public void WithPoller() { using (NetMQContext context = NetMQContext.Create()) using (NetMQQueue<int> queue = new NetMQQueue<int>(context)) { Poller poller = new Poller(); poller.AddSocket(queue); ManualResetEvent manualResetEvent = new ManualResetEvent(false); queue.ReceiveReady += (sender, args) => { manualResetEvent.Set(); }; poller.PollTillCancelledNonBlocking(); Assert.IsFalse(manualResetEvent.WaitOne(100)); queue.Enqueue(1); Assert.IsTrue(manualResetEvent.WaitOne(100)); poller.CancelAndJoin(); } }
public void ResponsePoll() { using (Context contex = Context.Create()) { using (ResponseSocket rep = contex.CreateResponseSocket()) { rep.Bind("tcp://127.0.0.1:5002"); using (RequestSocket req = contex.CreateRequestSocket()) { req.Connect("tcp://127.0.0.1:5002"); Poller poller = new Poller(contex); poller.AddSocket(rep, r => { bool more; string m = r.ReceiveString(out more); Assert.False(more); Assert.AreEqual("Hello", m); r.Send("World"); }); Task pollerTask = Task.Factory.StartNew(poller.Start); req.Send("Hello"); bool more2; string m1 = req.ReceiveString(out more2); Assert.IsFalse(more2); Assert.AreEqual("World", m1); poller.Stop(); Thread.Sleep(100); Assert.IsTrue(pollerTask.IsCompleted); } } } }
public void Polling() { using (var context = NetMQContext.Create()) using (var speaker = new NetMQBeacon(context)) using (var listener = new NetMQBeacon(context)) { speaker.Configure(9999); Console.WriteLine(speaker.Hostname); speaker.Publish("Hello", s_publishInterval); var manualResetEvent = new ManualResetEvent(false); listener.Configure(9999); listener.Subscribe("H"); string peerName = ""; string message = ""; listener.ReceiveReady += (sender, args) => { message = listener.ReceiveString(out peerName); manualResetEvent.Set(); }; using (var poller = new Poller(listener) { PollTimeout = 10}) { poller.PollTillCancelledNonBlocking(); manualResetEvent.WaitOne(); Console.WriteLine(peerName); Assert.AreEqual("Hello", message); poller.CancelAndJoin(); } } }
public void TestProxySendAndReceiveWithExternalPoller() { using (var context = NetMQContext.Create()) using (var front = context.CreateRouterSocket()) using (var back = context.CreateDealerSocket()) using (var poller = new Poller(front, back)) { front.Bind("inproc://frontend"); back.Bind("inproc://backend"); var proxy = new Proxy(front, back, null, poller); poller.PollTillCancelledNonBlocking(); proxy.Start(); using (var client = context.CreateRequestSocket()) using (var server = context.CreateResponseSocket()) { client.Connect("inproc://frontend"); server.Connect("inproc://backend"); client.SendFrame("hello"); Assert.AreEqual("hello", server.ReceiveFrameString()); server.SendFrame("reply"); Assert.AreEqual("reply", client.ReceiveFrameString()); // Now stop the external poller poller.CancelAndJoin(); client.SendFrame("anyone there?"); // Should no longer receive any messages Assert.IsFalse(server.TrySkipFrame(TimeSpan.FromMilliseconds(50))); } } }
public void StoppingProxyDisengagesFunctionality() { using (var context = NetMQContext.Create()) using (var front = context.CreateRouterSocket()) using (var back = context.CreateDealerSocket()) { front.Bind("inproc://frontend"); back.Bind("inproc://backend"); var proxy = new Proxy(front, back); Task.Factory.StartNew(proxy.Start); // Send a message through to ensure the proxy has started using (var client = context.CreateRequestSocket()) using (var server = context.CreateResponseSocket()) { client.Connect("inproc://frontend"); server.Connect("inproc://backend"); client.SendFrame("hello"); Assert.AreEqual("hello", server.ReceiveFrameString()); server.SendFrame("reply"); Assert.AreEqual("reply", client.ReceiveFrameString()); proxy.Stop(); // blocks until stopped using (var poller = new Poller(front, back)) { poller.PollTillCancelledNonBlocking(); client.SendFrame("anyone there?"); // Should no longer receive any messages Assert.IsFalse(server.TrySkipFrame(TimeSpan.FromMilliseconds(50))); poller.CancelAndJoin(); } } } }
public void AddSocketDuringWork() { using (Context contex = Context.Create()) { // we are using three responses to make sure we actually move the correct socket and other sockets still work using (RouterSocket router = contex.CreateRouterSocket()) using (RouterSocket router2 = contex.CreateRouterSocket()) { router.Bind("tcp://127.0.0.1:5002"); router2.Bind("tcp://127.0.0.1:5003"); using (DealerSocket dealer = contex.CreateDealerSocket()) using (DealerSocket dealer2 = contex.CreateDealerSocket()) { dealer.Connect("tcp://127.0.0.1:5002"); dealer2.Connect("tcp://127.0.0.1:5003"); bool router1arrived = false; bool router2arrived = false; Poller poller = new Poller(contex); bool more; poller.AddSocket(router, (r) => { router1arrived = true; router.Receive(out more); router.Receive(out more); poller.AddSocket(router2, (r2) => { router2.Receive(out more); router2.Receive(out more); router2arrived = true; }); }); Task task = Task.Factory.StartNew(poller.Start); dealer.Send("1"); Thread.Sleep(100); dealer2.Send("2"); Thread.Sleep(100); poller.Stop(true); task.Wait(); Assert.IsTrue(router1arrived); Assert.IsTrue(router2arrived); } } } }
/// <summary> /// Stops the proxy, blocking until the underlying <see cref="Poller"/> has completed. /// </summary> /// <exception cref="InvalidOperationException">The proxy has not been started.</exception> public void Stop() { if (Interlocked.CompareExchange(ref m_state, StateStopping, StateStarted) != StateStarted) { throw new InvalidOperationException("Proxy has not been started"); } if (!m_externalPoller) { m_poller.CancelAndJoin(); m_poller = null; } m_frontend.ReceiveReady -= OnFrontendReady; m_backend.ReceiveReady -= OnBackendReady; m_state = StateStopped; }
/// <summary> /// Start proxying messages between the front and back ends. Blocks, unless using an external <see cref="Poller"/>. /// </summary> /// <exception cref="InvalidOperationException">The proxy has already been started.</exception> public void Start() { if (Interlocked.CompareExchange(ref m_state, StateStarting, StateStopped) != StateStopped) { throw new InvalidOperationException("Proxy has already been started"); } m_frontend.ReceiveReady += OnFrontendReady; m_backend.ReceiveReady += OnBackendReady; if (m_externalPoller) { m_state = StateStarted; } else { m_poller = new Poller(m_frontend, m_backend); m_state = StateStarted; m_poller.PollTillCancelled(); } }
public void TwoTimers() { using (Context contex = Context.Create()) { // we are using three responses to make sure we actually move the correct socket and other sockets still work using (RouterSocket router = contex.CreateRouterSocket()) { router.Bind("tcp://127.0.0.1:5002"); using (DealerSocket dealer = contex.CreateDealerSocket()) { dealer.Connect("tcp://127.0.0.1:5002"); Poller poller = new Poller(contex); bool messageArrived = false; poller.AddSocket(router, s => { bool isMore; router.Receive(out isMore); router.Receive(out isMore); messageArrived = true; }); bool timerTriggered = false; // the timer will jump after 100ms poller.AddTimer(20, 1, id => { // the timer should jump before the message Assert.IsFalse(messageArrived); timerTriggered = true; }); bool timerTriggered2 = false; poller.AddTimer(80, 2, id => { // the timer should jump before the message Assert.IsTrue(messageArrived); timerTriggered2 = true; }); Task.Factory.StartNew(poller.Start); Thread.Sleep(50); dealer.Send("hello"); Thread.Sleep(50); poller.Stop(); Assert.IsTrue(messageArrived); Assert.IsTrue(timerTriggered); Assert.IsTrue(timerTriggered2); } } } }
public void InprocRouterDealerTest() { // The main thread simply starts several clients and a server, and then // waits for the server to finish. List<Thread> workers = new List<Thread>(); byte[] s_ReadyMsg = Encoding.UTF8.GetBytes("RDY"); Queue<byte[]> s_FreeWorkers = new Queue<byte[]>(); using (var context = NetMQContext.Create()) { using (var backendsRouter = context.CreateRouterSocket()) { backendsRouter.Options.Identity = Guid.NewGuid().ToByteArray(); backendsRouter.Bind("inproc://backend"); backendsRouter.ReceiveReady += (o, e)=> { // Handle worker activity on backend while (e.Socket.HasIn) { var msg = e.Socket.ReceiveMultipartMessage(); var idRouter = msg.Pop(); // forget the empty frame if (msg.First.IsEmpty) msg.Pop(); var id = msg.Pop(); if (msg.First.IsEmpty) msg.Pop(); if (msg.FrameCount == 1) { // worker send RDY message queue his Identity to the free workers queue if (s_ReadyMsg[0] ==msg[0].Buffer[0] && s_ReadyMsg[1] ==msg[0].Buffer[1] && s_ReadyMsg[2] ==msg[0].Buffer[2]) { lock (s_FreeWorkers) { s_FreeWorkers.Enqueue(id.Buffer); } } } } }; Poller poller = new Poller(); poller.AddSocket(backendsRouter); for (int i = 0; i < 2; i++) { var workerThread = new Thread((state) => { byte[] routerId = (byte[])state; byte[] workerId = Guid.NewGuid().ToByteArray(); using (var workerSocket = context.CreateDealerSocket()) { workerSocket.Options.Identity = workerId; workerSocket.Connect("inproc://backend"); var workerReadyMsg = new NetMQMessage(); workerReadyMsg.Append(workerId); workerReadyMsg.AppendEmptyFrame(); workerReadyMsg.Append(s_ReadyMsg); workerSocket.SendMultipartMessage(workerReadyMsg); Thread.Sleep(1000); } }); workerThread.IsBackground = true; workerThread.Name = "worker" + i; workerThread.Start(backendsRouter.Options.Identity); workers.Add(workerThread); } poller.PollTillCancelledNonBlocking(); Thread.Sleep(1000); poller.CancelAndJoin(); Assert.AreEqual(2, s_FreeWorkers.Count); } } }