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
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Tango.BL;
using Tango.BL.Entities;
using Tango.Core;
using Tango.Core.DI;
using Tango.Emulations.ExternalBridge;
using Tango.FSE.BL;
using Tango.FSE.Common.Authentication;
using Tango.FSE.Common.Connection;
using Tango.FSE.Common.Notifications;
using Tango.FSE.UI.Dialogs;
using Tango.Integration.ExternalBridge;
using Tango.Integration.Operation;
using Tango.SharedUI;
using Tango.Transport;
namespace Tango.FSE.UI.Connection
{
public class DefaultMachineProvider : ExtendedObject, IMachineProvider
{
private List<EventRegistration> _eventRegistrations;
private class EventRegistration
{
public Delegate Handler { get; set; }
public EventInfo EventInfo { get; set; }
public void RemoveHandler(Object instance)
{
try
{
EventInfo.RemoveEventHandler(instance, Handler);
}
catch
{
Debug.WriteLine($"Cannot remove handler '{Handler.Method.Name}' for event '{instance.GetType().Name}.{EventInfo.Name}'.");
}
}
public void AddHandler(Object instance)
{
try
{
EventInfo.AddEventHandler(instance, Handler);
}
catch
{
Debug.WriteLine($"Cannot add handler '{Handler.Method.Name}' for event '{instance.GetType().Name}.{EventInfo.Name}'.");
}
}
}
[TangoInject]
private INotificationProvider NotificationProvider { get; set; }
[TangoInject]
private IAuthenticationProvider AuthenticationProvider { get; set; }
[TangoInject]
private FSEServicesContainer Services { get; set; }
private Machine _machine;
/// <summary>
/// Gets the database machine entity associated with the current machine.
/// </summary>
public Machine Machine
{
get { return _machine; }
private set { _machine = value; RaisePropertyChangedAuto(); }
}
private bool _isConnected;
/// <summary>
/// Gets or sets a value indicating whether a machine is currently connected.
/// </summary>
public bool IsConnected
{
get { return _isConnected; }
private set { _isConnected = value; RaisePropertyChangedAuto(); }
}
private bool _isBusy;
/// <summary>
/// Gets a value indicating whether this instance is busy connecting/disconnecting.
/// </summary>
public bool IsBusy
{
get { return _isBusy; }
private set { _isBusy = value; RaisePropertyChangedAuto(); }
}
private IExternalBridgeClient _machineOperator;
/// <summary>
/// Gets the machine operator.
/// </summary>
public IExternalBridgeClient MachineOperator
{
get { return _machineOperator; }
private set { _machineOperator = value; RaisePropertyChangedAuto(); }
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultMachineProvider"/> class.
/// </summary>
public DefaultMachineProvider()
{
MachineOperator = new ExternalBridgeTcpClient("N/A", "N/A");
MachineOperator.StateChanged += MachineOperator_StateChanged;
MachineOperator.As<ExternalBridgeTcpClient>().SessionClosed += DefaultMachineProvider_SessionClosed;
}
/// <summary>
/// Connects to the specified machine.
/// </summary>
/// <param name="machine">The machine.</param>
/// <returns></returns>
public async Task<bool> ConnectToMachine(IExternalBridgeClient machine)
{
try
{
IsBusy = true;
MachineConnectionBaseViewVM vm = null;
if (machine.GetType() == typeof(ExternalBridgeUsbClient))
{
vm = await NotificationProvider.ShowDialog<MachineConnectionUsbViewVM>();
}
else if (machine.GetType() == typeof(EmulatorExternalBridge))
{
vm = await NotificationProvider.ShowDialog<MachineConnectionEmulatorViewVM>();
}
else if (machine is ExternalBridgeTcpClient)
{
var secureClient = machine.As<ExternalBridgeTcpClient>();
if (machine.GetType() == typeof(ExternalBridgeTcpClient))
{
vm = await NotificationProvider.ShowDialog(new MachineConnectionWifiViewVM(secureClient));
}
else
{
vm = await NotificationProvider.ShowDialog(new MachineConnectionSignalRViewVM(secureClient));
}
secureClient.LoginRequest = new PMR.Integration.ExternalBridgeLoginRequest()
{
AppID = "Tango FSE",
HostName = Environment.MachineName,
Password = (vm as MachineConnectionWifiViewVM).Password,
Intent = (vm as MachineConnectionWifiViewVM).SelectedIntent,
UserGuid = AuthenticationProvider.CurrentUser.Guid,
};
}
else
{
throw new NotSupportedException($"The specified type {machine.GetType().Name} is not supported.");
}
if (vm.DialogResult)
{
if (IsConnected)
{
await DisconnectMachine();
}
IsBusy = true;
String serial = vm.GetMachineSerialNumber();
using (var task = NotificationProvider.PushTaskItem($"Connecting to machine '{serial}'..."))
{
Machine = await Services.MachinesService.GetMachine(serial);
if (Machine == null)
{
throw new KeyNotFoundException("The specified machine was not found on the database.");
}
ReassignEventHandlers(MachineOperator, machine);
MachineOperator = machine;
ApplyOperatorSettings();
await MachineOperator.Connect();
IsConnected = true;
return true;
}
}
else
{
return false;
}
}
catch
{
throw;
}
finally
{
IsBusy = false;
}
}
/// <summary>
/// Disconnects the current connected machine.
/// </summary>
/// <returns></returns>
public async Task DisconnectMachine()
{
if (IsConnected)
{
using (var task = NotificationProvider.PushTaskItem("Disconnecting from current machine..."))
{
try
{
IsBusy = true;
Machine = null;
await MachineOperator.Disconnect();
}
catch (Exception ex)
{
LogManager.Log(ex, "Error disconnecting from machine.");
}
finally
{
IsConnected = false;
IsBusy = false;
}
}
}
}
#region Machine Operator Event Handlers
private void MachineOperator_StateChanged(object sender, TransportComponentState state)
{
if (IsConnected && state == TransportComponentState.Failed)
{
IsConnected = false;
InvokeUI(async () =>
{
var vm = await NotificationProvider.ShowDialog<MachineConnectionLostViewVM>(new MachineConnectionLostViewVM(MachineOperator, MachineOperator.FailedStateException.FlattenMessage(), 10));
if (vm.DialogResult)
{
try
{
IsBusy = true;
using (var task = NotificationProvider.PushTaskItem($"Reconnecting to machine '{Machine.SerialNumber}'..."))
{
await Task.Delay(2000);
await MachineOperator.Connect();
IsConnected = true;
}
}
catch (Exception ex)
{
await NotificationProvider.ShowError($"Failed to reconnect to the last connected machine.\n{ex.FlattenMessage()}");
}
finally
{
IsBusy = false;
}
}
});
}
}
private void DefaultMachineProvider_SessionClosed(object sender, EventArgs e)
{
IsConnected = false;
InvokeUI(() =>
{
NotificationProvider.ShowError("The connection has been terminated by the remote machine.");
});
}
#endregion
private void ApplyOperatorSettings()
{
MachineOperator.EnableDiagnostics = true;
MachineOperator.EnableMachineStatusUpdates = true;
MachineOperator.EnableEmbeddedDebugging = true;
MachineOperator.EnableEventsNotification = true;
MachineOperator.UseKeepAlive = true;
MachineOperator.JobUnitsMethod = JobUnitsMethods.Device;
MachineOperator.JobRunsLogger.JobSource = Tango.BL.Enumerations.JobSource.Remote;
MachineOperator.RequestTimeout = TimeSpan.FromSeconds(5);
MachineOperator.ContinuousRequestTimeout = TimeSpan.FromSeconds(5);
}
/// <summary>
/// Reassigns the event handlers from the previous connected machine to a new one.
/// </summary>
/// <param name="oldInstance">The old instance.</param>
/// <param name="newInstance">The new instance.</param>
/// <exception cref="NullReferenceException"></exception>
private void ReassignEventHandlers(IMachineOperator oldInstance, IMachineOperator newInstance)
{
if (_eventRegistrations == null)
{
_eventRegistrations = GetEventsRegistrations(oldInstance);
}
foreach (var registration in _eventRegistrations)
{
registration.RemoveHandler(oldInstance);
registration.AddHandler(newInstance);
}
}
private List<EventRegistration> GetEventsRegistrations(IMachineOperator instance)
{
List<EventRegistration> registrations = new List<EventRegistration>();
var instanceEvents = instance.GetType().GetEvents(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).ToList();
foreach (var ev in instanceEvents)
{
if (ev.IsMulticast)
{
FieldInfo eventField = null;
Type type = instance.GetType();
while (eventField == null)
{
eventField = type.GetField(ev.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);
if (eventField == null)
{
type = type.BaseType;
}
if (type == typeof(Object))
{
break;
}
}
if (eventField == null)
{
throw new NullReferenceException($"Could not locate event field for '{ev.Name}'.");
}
var eventDelegate = (MulticastDelegate)type.GetField(ev.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static).GetValue(instance);
if (eventDelegate != null)
{
foreach (var handler in eventDelegate.GetInvocationList())
{
registrations.Add(new EventRegistration()
{
EventInfo = ev,
Handler = handler,
});
}
}
}
}
return registrations;
}
}
}
|