Beispiel #1
0
        public void SendEvent(StreamDeckEvent streamDeckEvent)
        {
            string json = JsonConvert.SerializeObject(streamDeckEvent);

            byte[] data = CreateFrameFromString(json);
            _clientSocket.Send(data);
        }
        private void OnMessageReceived(object?sender, string json)
        {
            StreamDeckEvent?streamDeckEvent = StreamDeckEvent.FromJson(json);

            if (streamDeckEvent == null)
            {
                return;
            }

            switch (streamDeckEvent.Event)
            {
            case EventType.KeyDown:
            case EventType.KeyUp:
            case EventType.WillAppear:
            case EventType.WillDisappear:
            case EventType.TitleParametersDidChange:
            case EventType.DidReceiveSettings:
            case EventType.PropertyInspectorDidAppear:
            case EventType.PropertyInspectorDidDisappear:
                ActionEventReceived?.Invoke(this, (StreamDeckActionEvent)streamDeckEvent);
                break;

            case EventType.DeviceDidConnect:
            case EventType.DeviceDidDisconnect:
            case EventType.ApplicationDidLaunch:
            case EventType.ApplicationDidTerminate:
            case EventType.SendToPlugin:
            case EventType.DidReceiveGlobalSettings:
            case EventType.SystemDidWakeUp:
                PluginEventReceived?.Invoke(this, (StreamDeckPluginEvent)streamDeckEvent);
                break;
            }
        }
Beispiel #3
0
 private void ProcessEvent(JObject document)
 {
     if (StreamDeckEvent.TryParse(document, out var evnt, out var eventType))
     {
         Task.Run(() =>
         {
             return(eventManager.TriggerEvent(evnt));
         });
     }
        /// <summary>
        /// Temporarily show an OK checkmark icon on the image displayed by an instance of an action.
        /// </summary>
        /// <param name="context">Action context.</param>
        public async Task ShowOk(string context)
        {
            var @event = new StreamDeckEvent
            {
                Event   = SentEvents.ShowOk,
                Context = context
            };

            await SendEvent(@event);
        }
        /// <summary>
        /// Save persistent data for the action's instance
        /// </summary>
        /// <param name="context">Action context.</param>
        /// <param name="settings">An object which is persistently saved for the action's instance.</param>
        public async Task SetSettings(string context, Dictionary <string, object> settings)
        {
            var @event = new StreamDeckEvent
            {
                Event   = SentEvents.SetSettings,
                Context = context,
                Payload = settings
            };

            await SendEvent(@event);
        }
        /// <summary>
        /// Send a payload to the Property Inspector
        /// </summary>
        /// <param name="context">Action context.</param>
        /// <param name="payload">An object that will be received by the Property Inspector.</param>
        public async Task SendToPropertyInspector(string context, Dictionary <string, object> payload)
        {
            var @event = new StreamDeckEvent
            {
                Event   = SentEvents.SendToProperyInspector,
                Context = context,
                Payload = payload
            };

            await SendEvent(@event);
        }
        private static StreamDeckPluginEvent CreateEvent(EventType eventType, object payload = null)
        {
            var json = JObject.FromObject(new
            {
                @event = eventType.ToString("G"),
                device = "device",
                payload
            }).ToString();

            return((StreamDeckPluginEvent)StreamDeckEvent.FromJson(json));
        }
Beispiel #8
0
        internal void Initialise(string address)
        {
            this.WebSocketPort = new Uri(address).Port;
            var pluginPath = LaunchSettings.Plugin ?? "%APPDATA%\\Elgato\\StreamDeck\\Plugins";

            var paths = pluginPath.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

            var pluginFolders = paths.SelectMany(p => Expand(p)).ToList();

            if (int.TryParse(LaunchSettings.Pid, out var pid))
            {
                var process = Process.GetProcessById(pid);

                if (process == null)
                {
                    applicationLifetime.StopApplication();
                    return;
                }

                var pluginFolder = Path.GetDirectoryName(process.MainModule.FileName);

                var p = new Plugin(this, pluginFolder, process);
                this.plugins.Add(p);

                Task.Run(async() =>
                {
                    while (true)
                    {
                        if (process.HasExited)
                        {
                            applicationLifetime.StopApplication();
                            break;
                        }
                        await Task.Delay(250);
                    }
                });

                var data = new
                {
                    port          = this.WebSocketPort,
                    pluginUUID    = p.UUID,
                    registerEvent = new RegisterPluginEvent().Event,
                    info          = "{}"
                };

                console.Write($"\n\n--STREAMDECK_REG_START--\n{StreamDeckEvent.Serialize(data)}\n--STREAMDECK_REG_END--\n");
            }
            else
            {
                this.plugins.AddRange(pluginFolders.Select(p => new Plugin(this, p)));
            }
        }
        /// <summary>
        /// The name of the profile to switch to.
        /// </summary>
        /// <param name="url">A URL to open in the default browser.</param>
        public async Task OpenUrl(string url)
        {
            var @event = new StreamDeckEvent
            {
                Event   = SentEvents.OpenUrl,
                Payload = new Dictionary <string, object>
                {
                    { "url", url }
                }
            };

            await SendEvent(@event);
        }
Beispiel #10
0
        private async void FromJson_WithInput_ParsesCorrectly(EventType eventType)
        {
            // Arrange
            string json = await GetEmbeddedJsonAsync(eventType);

            // Act
            StreamDeckEvent streamDeckEvent = StreamDeckEvent.FromJson(json);

            // Assert
            Assert.NotNull(streamDeckEvent);
            Assert.Equal(eventType, streamDeckEvent.Event);
            StreamDeckApprovals.VerifyObject(streamDeckEvent);
        }
        /// <summary>
        /// The name of the profile to switch to.
        /// </summary>
        /// <param name="context">Action context.</param>
        /// <param name="deviceId">The device ID.</param>
        /// <param name="profileName">The name of the profile to switch to.</param>
        public async Task SwitchToProfile(string context, string deviceId, string profileName)
        {
            var @event = new StreamDeckEvent
            {
                Event   = SentEvents.SwitchToProfle,
                Context = context,
                Payload = new Dictionary <string, object>
                {
                    { "profile", profileName }
                }
            };

            await SendEvent(@event);
        }
        /// <summary>
        /// Dynamically change the state of an action supporting multiple states
        /// </summary>
        /// <param name="context">Action context</param>
        /// <param name="state">A zero indexed integer representing the desired state</param>
        public async Task SetState(string context, int state)
        {
            var @event = new StreamDeckEvent
            {
                Event   = SentEvents.SetState,
                Context = context,
                Payload = new Dictionary <string, object>
                {
                    { "state", state }
                }
            };

            await SendEvent(@event);
        }
        /// <summary>
        /// Sets the image displayed by an instance of an action.
        /// If <see cref="image"/> is null or empty the action is rest to its original image.
        /// </summary>
        /// <param name="context">Action context.</param>
        /// <param name="image">Image as a Base64 string.</param>
        /// <param name="destination">Event Destination.</param>
        public async Task SetImage(string context, string image, Destination destination = Destination.HardwareAndSoftware)
        {
            var @event = new StreamDeckEvent
            {
                Event   = SentEvents.SetImage,
                Context = context,
                Payload = new Dictionary <string, object>
                {
                    { "image", image ?? "" },
                    { "target", (int)destination }
                }
            };

            await SendEvent(@event);
        }
        private static StreamDeckActionEvent CreateEvent(EventType eventType)
        {
            var json = JObject.FromObject(new
            {
                action  = "testAction",
                @event  = eventType.ToString("G"),
                context = "context",
                device  = "device",
                payload = new
                {
                    coordinates = new
                    {
                        column = 0,
                        row    = 0
                    },
                    state            = 0,
                    userDesiredState = 0,
                    isInMultiAction  = false
                }
            }).ToString();

            return((StreamDeckActionEvent)StreamDeckEvent.FromJson(json));
        }
 private async Task SendEvent(StreamDeckEvent @event)
 {
     var json  = JsonConvert.SerializeObject(@event, _serialiserSettings);
     var bytes = Encoding.UTF8.GetBytes(json);
     await SocketHandler.Socket.SendAsync(bytes, WebSocketMessageType.Binary, true, CancellationToken.None);
 }
Beispiel #16
0
        public async Task Connect()
        {
#if DEBUG
            Debugger.Launch();
#endif
            var cmd       = "dotnet";
            var arguments = new string[] {
                "tool",
                "run",
                "StreamDeckEmulator",
                "--"
            };

            // default commands, lets fallback to the emulators directly
            var envCmd = Environment.GetEnvironmentVariable("StreamDeckEmulatorCommand");
            if (!string.IsNullOrEmpty(envCmd))
            {
                var parts = envCmd.TrimEnd().Split(new[] { ' ' });
                cmd       = parts[0];
                arguments = parts.Skip(1).ToArray();
            }
            // start emulator process if availible else lets logout that global tool is unavailible
            // emulator starting with a specific argument will get it to write out
            var executionDirectory = Path.GetDirectoryName(typeof(StreamDeckEmulator).Assembly.Location);

            var depsPath = Directory.GetFiles(executionDirectory, "*.deps.json", SearchOption.TopDirectoryOnly).SingleOrDefault();

            if (!string.IsNullOrEmpty(depsPath))
            {
                var file = Newtonsoft.Json.JsonConvert.DeserializeObject <SimpleDepsFile>(File.ReadAllText(depsPath));
                var lib  = file.libraries?.Where(x => x.Key.StartsWith("Tocsoft.StreamDeck/")).Select(X => X.Value).SingleOrDefault();
                if (lib != null)
                {
                    if (lib.type == "project")
                    {
                        var parent = executionDirectory;
                        while (parent != null && !Directory.Exists(Path.Combine(parent, ".git")))
                        {
                            parent = Path.GetDirectoryName(parent);
                        }
                        if (!string.IsNullOrEmpty(parent))
                        {
                            var emulatorProject = Path.GetFullPath(Path.Combine(parent, "src/Tocsoft.StreamDeckEmulator/Tocsoft.StreamDeckEmulator.csproj"));

                            if (File.Exists(emulatorProject))
                            {
                                cmd       = "dotnet";
                                arguments = new[] {
                                    "run",
                                    "-p",
                                    emulatorProject,
                                    "--"
                                };
                            }
                        }
                        // sln root
                        // this is running from reference to a project rather than the package
                        // lets walkt the tree looking for the csproj and look for the
                    }
                    else
                    {
                        var probPaths = Directory.GetFiles(executionDirectory, "*.runtimeconfig.dev.json", SearchOption.TopDirectoryOnly).SingleOrDefault();
                        if (!string.IsNullOrEmpty(probPaths))
                        {
                            var obj   = JObject.Parse(File.ReadAllText(probPaths));
                            var paths = obj["runtimeOptions"]?["additionalProbingPaths"]?.Values <string>();
                            if (paths != null)
                            {
                                foreach (var p in paths)
                                {
                                    var emulatorPath = Path.Combine(p, lib.path, "tools\\emulator\\Tocsoft.StreamDeckEmulator.dll");
                                    if (File.Exists(emulatorPath))
                                    {
                                        cmd       = $"dotnet";
                                        arguments = new[] {
                                            emulatorPath
                                        };
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // find the 'deps.json' files
            // find the 'runtime.dev.config'
            // if the type == project then use 'dotnet run' to the project.
            // if the type == 'package' then find the tools folder in the package folder and run the tool from there!

            // find the package store location
            var info = new ProcessStartInfo(cmd);
            foreach (var a in arguments)
            {
                info.ArgumentList.Add(a);
            }
            info.ArgumentList.Add("--Pid");
            info.ArgumentList.Add(Process.GetCurrentProcess().Id.ToString());
            info.RedirectStandardOutput = true;
            info.UseShellExecute        = false;
            info.CreateNoWindow         = false;

            this.process = Process.Start(info);
            this.process.EnableRaisingEvents = true;
            this.process.Exited += (s, e) =>
            {
                applicationLifetime.StopApplication();
            };

            StringBuilder dataReceived = new StringBuilder();
            Regex         matcher      = new Regex(@"(.*?)--STREAMDECK_REG_END--", RegexOptions.Singleline);
            bool          capturelines = false;
            while (!this.process.HasExited)
            {
                var line = await process.StandardOutput.ReadLineAsync();

                if (capturelines)
                {
                    var settings = StreamDeckEvent.Deserialize <StartupArguments>(line);
                    this.connection = new StreamDeckConnection(settings, logger, eventManager, applicationLifetime);
                    await this.connection.Connect();

                    break;
                }
                else if (line == "--STREAMDECK_REG_START--")
                {
                    capturelines = true;
                }
            }
        }