コード例 #1
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var discoverer = new Discoverer();

            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    var agents = new List <string>();

                    void OnAgentFound(object sender, AgentFoundEventArgs args)
                    {
                        agents.Add(args.Agent.Address.ToString());
                    };

                    discoverer.AgentFound += OnAgentFound;
                    discoverer.AgentFound += OnAgentFound;
                    await discoverer.DiscoverAsync(VersionCode.V3, new IPEndPoint(IPAddress.Broadcast, 161), new OctetString("public"), 5000);

                    var discoveredAgents = agents.Select(x =>
                                                         new AgentDeviceInfo(x, VersionCode.V3.ToString())).ToArray();

                    var currentAgents  = _activeAgentsCache.GetActiveDevices();
                    var newAgents      = discoveredAgents.Except(currentAgents);
                    var inactiveAgents = currentAgents.Except(discoveredAgents);

                    foreach (var newAgent in newAgents)
                    {
                        await _agentsHubContext.Clients.All.SendAsync("NEW-AGENT-DISCOVERED", newAgent, cancellationToken);

                        _activeAgentsCache.AddOrUpdateDevice(newAgent);
                        Console.WriteLine($"New agent discovered: {newAgent}");
                    }

                    foreach (var inactiveAgent in inactiveAgents)
                    {
                        await _agentsHubContext.Clients.All.SendAsync("AGENT-DISCONNECTED", inactiveAgent, cancellationToken);

                        _activeAgentsCache.DeleteDevice(inactiveAgent);
                        Console.WriteLine($"Agent ({inactiveAgent}) became inactive");
                    }

                    await Task.Delay(5000, cancellationToken);
                }
            }
            catch (TaskCanceledException)
            {
            }
            finally
            {
                _activeAgentsCache.Clear();
            }
        }
コード例 #2
0
        public IActionResult Get()
        {
            var devices = _activeAgentsCache.GetActiveDevices();

            return(Ok(devices));
        }