コード例 #1
0
        private void StartScannerThread()
        {
            EndPoint localEp = _localEp;

            _cancellationTokenSource = new CancellationTokenSource();
            CancellationToken ct = _cancellationTokenSource.Token;

            _scannerThread = Task.Run(async() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    try
                    {
                        byte[] response = new byte[8000];
                        int no          = _socket.ReceiveFrom(response, ref localEp);
                        string str      = Encoding.UTF8.GetString(Decrypt(response.Take(no).ToArray()));

                        JObject obj = ParserHelpers.ParseGetSysInfo(str);

                        if (obj == null)
                        {
                            continue;
                        }

                        DeviceType deviceType = ParserHelpers.GetDeviceType(obj);

                        if (GetDeviceTypeFilter()?.Contains(deviceType) == false)
                        {
                            Debug.WriteLine("Excluded device");
                            continue;
                        }

                        var requestContext    = new RequestContext(obj, (localEp as IPEndPoint)?.Address);
                        DeviceStateInfo state = await _deviceManager.AddOrUpdate(requestContext).ConfigureAwait(false);

                        switch (state.State)
                        {
                        case DeviceState.Added:
                            DeviceDiscovered?.Invoke(this, new DeviceEventArgs(state.Device));
                            break;

                        case DeviceState.Updated:
                            DeviceUpdated?.Invoke(this, new DeviceEventArgs(state.Device));
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e);
                    }
                }
            }, ct);
        }