コード例 #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
    protected virtual float CoerceProviderValue(DeviceAxis axis, float value)
    {
        if (!float.IsFinite(value))
        {
            return(axis.DefaultValue);
        }

        return(value);
    }
コード例 #3
0
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (value is string name && DeviceAxis.TryParse(name, out var axis))
        {
            return(axis);
        }

        return(base.ConvertFrom(context, culture, value));
    }
コード例 #4
0
    public void Update(DeviceAxis axis, string motionProviderName, float deltaTime)
    {
        var motionProvider = GetMotionProvider(axis, motionProviderName);

        if (motionProvider == null)
        {
            return;
        }

        motionProvider.Update(deltaTime);
        _values[axis] = motionProvider.Value;
    }
コード例 #5
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");
        }
    }
コード例 #6
0
    public IMotionProvider GetMotionProvider(DeviceAxis axis, string motionProviderName)
    {
        if (axis == null || motionProviderName == null)
        {
            return(null);
        }

        var motionProviders = _motionProviders[axis];

        if (!motionProviders.TryGetValue(motionProviderName, out var motionProvider))
        {
            return(null);
        }

        return(motionProvider);
    }
コード例 #7
0
ファイル: Bootstrapper.cs プロジェクト: Yoooi0/MultiFunPlayer
    private bool SetupDevice(JObject settings)
    {
        var devices    = SettingsHelper.Read(SettingsType.Devices);
        var serializer = JsonSerializer.Create(new JsonSerializerSettings()
        {
            ContractResolver = new DefaultContractResolver()
        });

        var dirty = false;

        if (!settings.TryGetValue <string>("SelectedDevice", serializer, out var selectedDevice) || selectedDevice == null)
        {
            selectedDevice             = devices.Properties().First().Name;
            settings["SelectedDevice"] = selectedDevice;
            dirty = true;
        }

        DeviceAxis.LoadSettings(devices[selectedDevice] as JObject, serializer);
        return(dirty);
    }
コード例 #8
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) { }
    }
コード例 #9
0
ファイル: TCodeParser.cs プロジェクト: Yoooi0/BusDriver
        public bool Parse(string data, IDictionary <int, float> values)
        {
            var matches = _regex.Matches(data).OfType <Match>();

            if (!matches.Any())
            {
                return(false);
            }

            foreach (var match in matches)
            {
                var axisName  = match.Groups[1].Value;
                var axisValue = match.Groups[2].Value;

                var value = int.Parse(axisValue) / ((float)Math.Pow(10, axisValue.Length) - 1);
                var axis  = -1;
                if (DeviceAxis.TryParse(axisName, out axis))
                {
                    values[axis] = value;
                }
            }

            return(true);
        }
コード例 #10
0
 public RandomMotionProviderViewModel(DeviceAxis target, IEventAggregator eventAggregator)
     : base(target, eventAggregator)
 {
     _noise = new OpenSimplex(Random.Shared.NextInt64());
 }
コード例 #11
0
 public IMotionProvider CreateMotionProvider(Type type, DeviceAxis target)
 => (IMotionProvider)Activator.CreateInstance(type, new object[] { target, _eventAggregator });
コード例 #12
0
ファイル: Plugin.cs プロジェクト: Yoooi0/BusDriver
        protected void FixedUpdate()
        {
            if (!_initialized || SuperController.singleton.isLoading)
            {
                return;
            }

            if (_physicsIteration == 0)
            {
                DebugDraw.Clear();
            }

            try
            {
                _valuesSource?.Update();

                if (!SuperController.singleton.freezeAnimation && _valuesSource != null && _motionTarget != null)
                {
                    var upValue      = UpRangeSlider.val * (_valuesSource.GetValue(DeviceAxis.L0) - DeviceAxis.DefaultValue(DeviceAxis.L0)) * 2;
                    var rightValue   = RightRangeSlider.val * (_valuesSource.GetValue(DeviceAxis.L1) - DeviceAxis.DefaultValue(DeviceAxis.L1)) * 2;
                    var forwardValue = ForwardRangeSlider.val * (_valuesSource.GetValue(DeviceAxis.L2) - DeviceAxis.DefaultValue(DeviceAxis.L2)) * 2;
                    var yawValue     = YawRangeSlider.val * (_valuesSource.GetValue(DeviceAxis.R0) - DeviceAxis.DefaultValue(DeviceAxis.R0)) * 2;
                    var rollValue    = RollRangeSlider.val * (_valuesSource.GetValue(DeviceAxis.R1) - DeviceAxis.DefaultValue(DeviceAxis.R1)) * 2;
                    var pitchValue   = PitchRangeSlider.val * (_valuesSource.GetValue(DeviceAxis.R2) - DeviceAxis.DefaultValue(DeviceAxis.R2)) * 2;

                    var newUp = Vector3.zero;
                    if (UpDirectionChooser.val == "+Up")
                    {
                        newUp = Vector3.up;
                    }
                    else if (UpDirectionChooser.val == "+Right")
                    {
                        newUp = Vector3.right;
                    }
                    else if (UpDirectionChooser.val == "+Forward")
                    {
                        newUp = Vector3.forward;
                    }
                    else if (UpDirectionChooser.val == "-Up")
                    {
                        newUp = -Vector3.up;
                    }
                    else if (UpDirectionChooser.val == "-Right")
                    {
                        newUp = -Vector3.right;
                    }
                    else if (UpDirectionChooser.val == "-Forward")
                    {
                        newUp = -Vector3.forward;
                    }

                    var coordinatesRotation = Quaternion.FromToRotation(Vector3.up, newUp);
                    var rotation            = Quaternion.Euler(coordinatesRotation * new Vector3(pitchValue, yawValue, rollValue));
                    var offset = coordinatesRotation * new Vector3(rightValue, upValue, forwardValue);

                    _motionTarget?.Apply(offset, rotation);
                }
            }
            catch (Exception e)
            {
                SuperController.LogError("Exception caught: " + e);
            }

            if (_physicsIteration == 0)
            {
                DebugDraw.Enabled = false;
            }

            _physicsIteration++;
        }
コード例 #13
0
 protected AbstractMotionProvider(DeviceAxis target, IEventAggregator eventAggregator)
 {
     _target          = target;
     _eventAggregator = eventAggregator;
 }
コード例 #14
0
    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 { }
    }
コード例 #15
0
 public PatternMotionProviderViewModel(DeviceAxis target, IEventAggregator eventAggregator)
     : base(target, eventAggregator)
 {
 }
コード例 #16
0
 protected AbstractValuesSource()
 {
     Values = DeviceAxis.Values.ToDictionary(a => a, a => DeviceAxis.DefaultValue(a));
 }
コード例 #17
0
    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 { }
    }
コード例 #18
0
 public LoopingScriptMotionProviderViewModel(DeviceAxis target, IEventAggregator eventAggregator)
     : base(target, eventAggregator)
 {
 }
コード例 #19
0
 public float GetValue(DeviceAxis axis) => _values[axis];
コード例 #20
0
 public IEnumerable <IMotionProvider> CreateMotionProviderCollection(DeviceAxis target)
 => ReflectionUtils.FindImplementations <IMotionProvider>().Select(t => CreateMotionProvider(t, target));