-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathConnectionManager.cs
More file actions
421 lines (338 loc) · 10.9 KB
/
ConnectionManager.cs
File metadata and controls
421 lines (338 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using StreamDeckLib.Messages;
using StreamDeckLib.Models;
using System;
using System.Diagnostics;
using System.IO;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace StreamDeckLib
{
/// <summary>
/// This class manages the connection to the StreamDeck hardware
/// </summary>
public partial class ConnectionManager : IDisposable
{
private readonly int _port;
private readonly string _uuid;
private readonly string _registerEvent;
private IStreamDeckProxy _proxy;
private IGlobalSettings _globalSettings;
public Info Info { get; private set; }
private ConnectionManager()
{
this._ActionManager = new ActionManager(_LoggerFactory?.CreateLogger<ActionManager>());
}
public ConnectionManager(IOptions<StreamDeckToolkitOptions> options, ActionManager actionManager, ILogger<ConnectionManager> logger, IStreamDeckProxy streamDeckProxy = null)
{
if (options == null) throw new ArgumentNullException("options", "Options cannot be null, these should be retrieved from commandline args.");
if (actionManager == null) throw new ArgumentNullException("actionManager", "ActionManager cannot be null, these should be retrieved from commandline args.");
_ActionManager = actionManager;
_logger = logger;
if (options.Value != null)
{
if (!string.IsNullOrEmpty(options.Value.Info))
{
var myInfo = JsonConvert.DeserializeObject<Info>(options.Value.Info);
Info = myInfo;
}
_port = options.Value.Port;
_uuid = options.Value.PluginUUID;
_registerEvent = options.Value.RegisterEvent;
}
_proxy = streamDeckProxy ?? new StreamDeckProxy();
}
private ConnectionManager(StreamDeckToolkitOptions options, ILoggerFactory loggerFactory = null, IStreamDeckProxy streamDeckProxy = null) : this()
{
var myInfo = JsonConvert.DeserializeObject<Info>(options.Info);
Info = myInfo;
_port = options.Port;
_uuid = options.PluginUUID;
_registerEvent = options.RegisterEvent;
_proxy = streamDeckProxy ?? new StreamDeckProxy();
_LoggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
_logger = loggerFactory?.CreateLogger<ConnectionManager>();
}
public static ConnectionManager Initialize(string[] commandLineArgs, ILoggerFactory loggerFactory = null, IStreamDeckProxy streamDeckProxy = null)
{
try
{
var options = ParseCommandlineArgs(commandLineArgs);
return new ConnectionManager(options, loggerFactory, streamDeckProxy);
}
catch
{
throw new ArgumentException($"{nameof(commandLineArgs)} must be the commandline args that the StreamDeck application calls this program with.");
}
}
public ConnectionManager RegisterGlobalSettings(IGlobalSettings settings)
{
_globalSettings = settings;
return this;
}
public async Task<ConnectionManager> StartAsync(CancellationToken token)
{
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
await Run(token);
return this;
}
public async Task<ConnectionManager> StartAsync()
{
var source = new CancellationTokenSource();
return await this.StartAsync(source.Token);
}
private static StreamDeckToolkitOptions ParseCommandlineArgs(string[] args)
{
using (var app = new CommandLineApplication())
{
app.HelpOption();
var optionPort = app.Option<int>("-port|--port <PORT>",
"The port the Elgato StreamDeck software is listening on",
CommandOptionType.SingleValue);
var optionPluginUUID = app.Option<string>("-pluginUUID <UUID>",
"The UUID that the Elgato StreamDeck software knows this plugin as.",
CommandOptionType.SingleValue);
var optionRegisterEvent = app.Option<string>("-registerEvent <REGEVENT>", "The registration event",
CommandOptionType.SingleValue);
var optionInfo = app.Option<string>("-info <INFO>", "Some information", CommandOptionType.SingleValue);
// var optionBreak = app.Option("-break", "Attach the debugger", CommandOptionType.NoValue);
app.Parse(args);
return new StreamDeckToolkitOptions
{
// Break = optionBreak.,
Info = optionInfo.ParsedValue,
PluginUUID = optionPluginUUID.ParsedValue,
Port = optionPort.ParsedValue,
RegisterEvent = optionRegisterEvent.ParsedValue
};
}
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
_logger?.LogError(e.Exception, "Error handling StreamDeck information");
}
private async Task Run(CancellationToken token)
{
_logger?.LogTrace($"{nameof(ConnectionManager)}.{nameof(Run)} port:{_port}, event: {_registerEvent}, uuid: {_uuid}");
await _proxy.ConnectAsync(new Uri($"ws://localhost:{_port}"), token);
_logger?.LogTrace($"{nameof(ConnectionManager)}.{nameof(Run)} Connected");
await _proxy.Register(_registerEvent, _uuid);
_logger?.LogTrace($"{nameof(ConnectionManager)}.{nameof(Run)} Registered");
var keepRunning = true;
while (!token.IsCancellationRequested && keepRunning)
{
// Exit loop if the socket is closed or aborted
switch (_proxy.State)
{
case WebSocketState.CloseReceived:
case WebSocketState.Closed:
case WebSocketState.Aborted:
keepRunning = false;
break;
}
if (!keepRunning) break;
var jsonString = await _proxy.GetMessageAsString(token);
if (!string.IsNullOrEmpty(jsonString) && !jsonString.StartsWith("\u0000", StringComparison.OrdinalIgnoreCase))
{
try
{
var msg = JsonConvert.DeserializeObject<StreamDeckEventPayload>(jsonString);
if (msg == null)
{
_logger?.LogError($"Unknown message received: {jsonString}");
continue;
}
if (string.IsNullOrWhiteSpace(msg.context) && string.IsNullOrWhiteSpace(msg.action))
{
this.BroadcastMessage(msg);
}
else
{
var action = GetInstanceOfAction(msg.context, msg.action);
if (action == null)
{
_logger?.LogWarning($"The action requested (\"{msg.action}\") was not found as being registered with the plugin");
continue;
}
if (!_EventDictionary.ContainsKey(msg.Event))
{
_logger?.LogWarning($"Plugin does not handle the event '{msg.Event}'");
continue;
}
_EventDictionary[msg.Event]?.Invoke(action, msg);
}
}
catch (Exception ex)
{
_logger?.LogError(ex, "Error while processing payload from StreamDeck");
}
}
await Task.Delay(100);
}
Dispose();
}
#region StreamDeck Methods
public async Task SetTitleAsync(string context, string newTitle)
{
var args = new SetTitleArgs()
{
context = context,
payload = new SetTitleArgs.Payload
{
title = newTitle,
TargetType = SetTitleArgs.TargetType.HardwareAndSoftware
}
};
await _proxy.SendStreamDeckEvent(args);
}
public async Task SetImageAsync(string context, string imageLocation, int? state = null)
{
Debug.WriteLine($"Getting Image from {new FileInfo(imageLocation).FullName} on disk");
_logger?.LogDebug($"Getting Image from {new FileInfo(imageLocation).FullName} on disk");
var imgString = Convert.ToBase64String(File.ReadAllBytes(imageLocation), Base64FormattingOptions.None);
var args = new SetImageArgs
{
context = context,
payload = new SetImageArgs.Payload
{
TargetType = SetTitleArgs.TargetType.HardwareAndSoftware,
image = $"data:image/{new FileInfo(imageLocation).Extension.ToLowerInvariant().Substring(1)};base64, {imgString}",
state = state
}
};
await _proxy.SendStreamDeckEvent(args);
}
public async Task ShowAlertAsync(string context)
{
var args = new ShowAlertArgs()
{
context = context
};
await _proxy.SendStreamDeckEvent(args);
}
public async Task ShowOkAsync(string context)
{
var args = new ShowOkArgs()
{
context = context
};
await _proxy.SendStreamDeckEvent(args);
}
public async Task SetSettingsAsync(string context, dynamic value)
{
var args = new SetSettingsArgs()
{
context = context,
payload = new { settingsModel = value }
};
await _proxy.SendStreamDeckEvent(args);
}
public async Task SetGlobalSettingsAsync(string context, dynamic value)
{
var args = new SetGlobalSettingsArgs()
{
context = context,
payload = new { settingsModel = value }
};
await _proxy.SendStreamDeckEvent(args);
}
public async Task SetStateAsync(string context, int state)
{
var args = new SetStateArgs
{
context = context,
payload = new SetStateArgs.Payload
{
state = state
}
};
await _proxy.SendStreamDeckEvent(args);
}
public async Task SwitchToProfileAsync(string context, string device, string profileName)
{
var args = new SwitchToProfileArgs
{
context = context,
device = device,
payload = new SwitchToProfileArgs.Payload
{
profile = profileName
}
};
await _proxy.SendStreamDeckEvent(args);
}
public async Task OpenUrlAsync(string context, string url)
{
var args = new OpenUrlArgs()
{
context = context,
payload = new OpenUrlArgs.Payload()
{
url = url
}
};
await _proxy.SendStreamDeckEvent(args);
}
public async Task GetSettingsAsync(string context)
{
var args = new GetSettingsArgs() { context = context };
await _proxy.SendStreamDeckEvent(args);
}
public async Task GetGlobalSettingsAsync(string context)
{
var args = new GetGlobalSettingsArgs() { context = context };
await _proxy.SendStreamDeckEvent(args);
}
public async Task LogMessageAsync(string context, string logMessage)
{
var args = new LogMessageArgs()
{
context = context,
payload = new LogMessageArgs.Payload()
{
message = logMessage
}
};
await _proxy.SendStreamDeckEvent(args);
}
public async Task SendToPropertyInspectorAsync(string context, dynamic settings)
{
var args = new SendToPropertyInspectorArgs()
{
context = context,
payload = settings
};
await _proxy.SendStreamDeckEvent(args);
}
#endregion
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
private static ILoggerFactory _LoggerFactory;
private readonly ILogger<ConnectionManager> _logger;
void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_proxy.Dispose();
}
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
//GC.SuppressFinalize(this);
}
#endregion
}
}