예제 #1
0
    private void RunUdp(CancellationToken token)
    {
        using var client = new UdpClient();

        try
        {
            Logger.Info("Connecting to {0} at \"{1}\"", Identifier, $"udp://{Endpoint}");

            const int SIO_UDP_CONNRESET = -1744830452;
            client.Client.IOControl((IOControlCode)SIO_UDP_CONNRESET, new byte[] { 0, 0, 0, 0 }, null);

            client.Connect(Endpoint);
            Status = ConnectionStatus.Connected;
        }
        catch (Exception e)
        {
            Logger.Warn(e, "Error when connecting to server");
            _ = DialogHelper.ShowErrorAsync(e, $"Error when connecting to server", "RootDialog");
            return;
        }

        try
        {
            EventAggregator.Publish(new SyncRequestMessage());

            var buffer    = new byte[256];
            var stopwatch = Stopwatch.StartNew();
            while (!token.IsCancellationRequested)
            {
                stopwatch.Restart();
                Sleep(stopwatch);

                UpdateValues();

                if (client.Available > 0)
                {
                    var endpoint = new IPEndPoint(Endpoint.Address, Endpoint.Port);
                    var message  = Encoding.UTF8.GetString(client.Receive(ref endpoint));
                    Logger.Debug("Received \"{0}\" from \"{1}\"", message, $"udp://{endpoint}");
                }

                var commands = DeviceAxis.ToString(Values, 1000 * stopwatch.ElapsedTicks / (float)Stopwatch.Frequency);
                if (!string.IsNullOrWhiteSpace(commands))
                {
                    Logger.Trace("Sending \"{0}\" to \"{1}\"", commands.Trim(), $"udp://{Endpoint}");

                    var encoded = Encoding.UTF8.GetBytes(commands, buffer);
                    client.Send(buffer, encoded);
                }
            }
        }
        catch (Exception e)
        {
            Logger.Error(e, $"{Identifier} failed with exception");
            _ = DialogHelper.ShowErrorAsync(e, $"{Identifier} failed with exception", "RootDialog");
        }
    }
예제 #2
0
    private void RunTcp(CancellationToken token)
    {
        using var client = new TcpClient();

        try
        {
            Logger.Info("Connecting to {0} at \"{1}\"", Identifier, $"tcp://{Endpoint}");
            client.Connect(Endpoint);
            Status = ConnectionStatus.Connected;
        }
        catch (Exception e)
        {
            Logger.Warn(e, "Error when connecting to server");
            _ = DialogHelper.ShowErrorAsync(e, $"Error when connecting to server", "RootDialog");
            return;
        }

        try
        {
            EventAggregator.Publish(new SyncRequestMessage());

            var stopwatch = Stopwatch.StartNew();
            using var stream = new StreamWriter(client.GetStream(), Encoding.UTF8);
            while (!token.IsCancellationRequested && client.Connected)
            {
                stopwatch.Restart();
                Sleep(stopwatch);

                UpdateValues();

                if (client.Connected && client.Available > 0)
                {
                    var message = Encoding.UTF8.GetString(client.GetStream().ReadBytes(client.Available));
                    Logger.Debug("Received \"{0}\" from \"{1}\"", message, $"tcp://{Endpoint}");
                }

                var commands = DeviceAxis.ToString(Values, 1000 * stopwatch.ElapsedTicks / (float)Stopwatch.Frequency);
                if (client.Connected && !string.IsNullOrWhiteSpace(commands))
                {
                    Logger.Trace("Sending \"{0}\" to \"{1}\"", commands.Trim(), $"tcp://{Endpoint}");
                    stream.WriteLine(commands);
                }
            }
        }
        catch (Exception e)
        {
            Logger.Error(e, $"{Identifier} failed with exception");
            _ = DialogHelper.ShowErrorAsync(e, $"{Identifier} failed with exception", "RootDialog");
        }
    }
예제 #3
0
    private async Task WriteAsync(ClientWebSocket client, CancellationToken token)
    {
        try
        {
            var stopwatch = Stopwatch.StartNew();
            while (!token.IsCancellationRequested && client.State == WebSocketState.Open)
            {
                stopwatch.Restart();
                await Sleep(stopwatch, token);

                UpdateValues();

                var commands = DeviceAxis.ToString(Values, 1000 * stopwatch.ElapsedTicks / (float)Stopwatch.Frequency);
                if (client.State == WebSocketState.Open && !string.IsNullOrWhiteSpace(commands))
                {
                    Logger.Trace("Sending \"{0}\" to \"{1}\"", commands.Trim(), Uri.ToString());
                    await client.SendAsync(Encoding.UTF8.GetBytes(commands), WebSocketMessageType.Text, true, token);
                }
            }
        }
        catch (OperationCanceledException) { }
    }
    protected override void Run(CancellationToken token)
    {
        var client = default(NamedPipeClientStream);

        try
        {
            Logger.Info("Connecting to {0} at \"{1}\"", Identifier, PipeName);

            client = new NamedPipeClientStream(".", PipeName, PipeDirection.Out);
            client.Connect(2500);

            Status = ConnectionStatus.Connected;
        }
        catch (Exception e)
        {
            Logger.Warn(e, "Error when opening pipe");
            if (client?.IsConnected == true)
            {
                client.Close();
            }

            _ = DialogHelper.ShowErrorAsync(e, $"Error when opening pipe", "RootDialog");
            return;
        }

        try
        {
            EventAggregator.Publish(new SyncRequestMessage());

            var buffer    = new byte[256];
            var stopwatch = Stopwatch.StartNew();
            while (!token.IsCancellationRequested && client?.IsConnected == true)
            {
                stopwatch.Restart();
                Sleep(stopwatch);

                UpdateValues();

                var commands = DeviceAxis.ToString(Values, 1000 * stopwatch.ElapsedTicks / (float)Stopwatch.Frequency);
                if (client.IsConnected && !string.IsNullOrWhiteSpace(commands))
                {
                    Logger.Trace("Sending \"{0}\" to \"{1}\"", commands.Trim(), PipeName);
                    var encoded = Encoding.UTF8.GetBytes(commands, buffer);
                    client.Write(buffer, 0, encoded);
                }
            }
        }
        catch (Exception e)
        {
            Logger.Error(e, $"{Identifier} failed with exception");
            _ = DialogHelper.ShowErrorAsync(e, $"{Identifier} failed with exception", "RootDialog");
        }

        try
        {
            if (client?.IsConnected == true)
            {
                client.Close();
            }
        } catch { }
    }
    protected override void Run(CancellationToken token)
    {
        var serialPort = default(SerialPort);

        try
        {
            Logger.Info("Connecting to {0} at \"{1}\"", Identifier, SelectedSerialPortDeviceId);

            serialPort = new SerialPort(SelectedSerialPort.PortName, 115200)
            {
                ReadTimeout  = 1000,
                WriteTimeout = 1000,
                DtrEnable    = true,
                RtsEnable    = true
            };

            serialPort.Open();
            serialPort.ReadExisting();
            Status = ConnectionStatus.Connected;
        }
        catch (Exception e)
        {
            Logger.Warn(e, "Error when opening serial port");

            try { serialPort?.Close(); }
            catch (IOException) { }

            _ = Execute.OnUIThreadAsync(async() =>
            {
                _ = DialogHelper.ShowErrorAsync(e, $"Error when opening serial port", "RootDialog");
                await RefreshPorts().ConfigureAwait(true);
            });

            return;
        }

        try
        {
            EventAggregator.Publish(new SyncRequestMessage());

            var stopwatch      = Stopwatch.StartNew();
            var lastSentValues = DeviceAxis.All.ToDictionary(a => a, _ => float.NaN);
            while (!token.IsCancellationRequested && serialPort.IsOpen)
            {
                stopwatch.Restart();
                Sleep(stopwatch);

                UpdateValues();

                if (serialPort.IsOpen && serialPort.BytesToRead > 0)
                {
                    Logger.Debug("Received \"{0}\" from \"{1}\"", serialPort.ReadExisting(), SelectedSerialPortDeviceId);
                }

                var dirtyValues = Values.Where(x => DeviceAxis.IsDirty(x.Value, lastSentValues[x.Key]));
                var commands    = DeviceAxis.ToString(dirtyValues, 1000 * stopwatch.ElapsedTicks / (float)Stopwatch.Frequency);
                if (serialPort.IsOpen == true && !string.IsNullOrWhiteSpace(commands))
                {
                    Logger.Trace("Sending \"{0}\" to \"{1}\"", commands.Trim(), SelectedSerialPortDeviceId);
                    serialPort.Write(commands);
                }

                foreach (var(axis, value) in dirtyValues)
                {
                    lastSentValues[axis] = value;
                }
            }
        }
        catch (Exception e) when(e is TimeoutException || e is IOException)
        {
            Logger.Error(e, $"{Identifier} failed with exception");
            _ = Execute.OnUIThreadAsync(async() =>
            {
                _ = DialogHelper.ShowErrorAsync(e, $"{Identifier} failed with exception", "RootDialog");
                await RefreshPorts().ConfigureAwait(true);
            });
        }
        catch (Exception e) { Logger.Debug(e, $"{Identifier} failed with exception"); }

        try { serialPort?.Close(); }
        catch { }
    }