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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
using Tango.BL;
using Tango.BL.Entities;
using Tango.Integration.Operation;
using Tango.Logging;
using Tango.PMR;
using Tango.PMR.Common;
using Tango.PMR.Connection;
using Tango.PMR.Integration;
using Tango.PMR.MachineStatus;
using Tango.Settings;
using Tango.Transport;
using Tango.Transport.Adapters;
using Tango.Transport.Transporters;
namespace Tango.Integration.ExternalBridge
{
/// <summary>
/// Represents a secure external bridge TCP client.
/// </summary>
/// <seealso cref="Tango.Transport.Transporters.BasicTransporter" />
/// <seealso cref="Tango.Integration.ExternalBridge.IExternalBridgeSecureClient" />
public class ExternalBridgeTcpClient : MachineOperator, IExternalBridgeSecureClient
{
private bool _logs_sent;
public event EventHandler<LogItemBase> ApplicationLogAvailable;
#region Properties
private String _serialNumber;
/// <summary>
/// Gets the machine serial number.
/// </summary>
public String SerialNumber
{
get { return _serialNumber; }
set
{
_serialNumber = value;
RaisePropertyChangedAuto();
}
}
private String _ipAddress;
/// <summary>
/// Gets or sets the machine IP address.
/// </summary>
public String IPAddress
{
get { return _ipAddress; }
set { _ipAddress = value; RaisePropertyChangedAuto(); }
}
private bool _enableApplicationLogs;
/// <summary>
/// Gets or sets a value indicating whether to enable receiving application logs.
/// </summary>
public bool EnableApplicationLogs
{
get { return _enableApplicationLogs; }
set
{
_enableApplicationLogs = value;
RaisePropertyChangedAuto();
OnEnableApplicationLogsChanged(value);
}
}
public bool InjectApplicationLogsToDefaultLogManager { get; set; } = true;
/// <summary>
/// Gets a value indicating whether this client requires authentication.
/// </summary>
public bool RequiresAuthentication => true;
/// <summary>
/// Gets or sets the login request message when using <see cref="Connect"/>.
/// </summary>
public ExternalBridgeLoginRequest LoginRequest { get; set; }
/// <summary>
/// Gets or sets the configure protocol request message when using <see cref="Connect"/>.
/// </summary>
public ConfigureProtocolRequest ConfigureProtocolRequest { get; set; }
/// <summary>
/// Gets or sets a value indicating to apply the <see cref="ConfigureProtocolRequest"/> even if there is an error with the request.
/// </summary>
public bool ForceProtocolConfiguration { get; set; }
private ApplicationInformation _applicationInformation;
/// <summary>
/// Gets or sets the remote application information (PPC).
/// </summary>
public ApplicationInformation ApplicationInformation
{
get { return _applicationInformation; }
protected set { _applicationInformation = value; RaisePropertyChangedAuto(); }
}
#endregion
/// <summary>
/// Connects to a remote external bridge service using the specified <see cref="LoginRequest"/>.
/// </summary>
/// <param name="login">The login.</param>
/// <returns></returns>
/// <exception cref="AuthenticationException">The machine password is invalid.</exception>
public override Task Connect()
{
if (LoginRequest == null)
{
throw new InvalidOperationException("No LoginRequest was not specified.");
}
return Connect(LoginRequest, ConfigureProtocolRequest);
}
/// <summary>
/// Connects to a remote external bridge service using the specified login.
/// </summary>
/// <param name="login">The login request.</param>
/// <param name="protocol">Optional protocol configuration.</param>
/// <returns></returns>
/// <exception cref="AuthenticationException"></exception>
public virtual async Task Connect(ExternalBridgeLoginRequest login, ConfigureProtocolRequest protocol = null)
{
if (State != TransportComponentState.Connected)
{
try
{
Adapter.EnableCompression = false;
GenericProtocol = GenericMessageProtocol.Json;
await Adapter.Connect();
State = TransportComponentState.Connected;
StartThreads();
LogManager.Log($"{ComponentName}: External Bridge TCP Client Connected...");
TimeSpan? timeout = null;
if (login.RequireSafetyLevelOperations)
{
timeout = TimeSpan.FromSeconds(35);
}
var response = await SendRequest<ExternalBridgeLoginRequest, ExternalBridgeLoginResponse>(login, new TransportRequestConfig() { ShouldLog = true, Timeout = timeout });
if (protocol != null)
{
try
{
var configureResponse = await SendRequest<ConfigureProtocolRequest, ConfigureProtocolResponse>(protocol, new TransportRequestConfig() { ShouldLog = true });
if (configureResponse.Message.Confirmed)
{
await Task.Delay(500);
Adapter.EnableCompression = protocol.EnableCompression;
GenericProtocol = protocol.GenericProtocol;
}
}
catch (Exception ex)
{
if (ForceProtocolConfiguration)
{
LogManager.Log(ex, $"{ComponentName}: Could not configure remote machine protocol. Could be an old PPC version. (forcing protocol configuration)");
Adapter.EnableCompression = protocol.EnableCompression;
GenericProtocol = protocol.GenericProtocol;
}
else
{
LogManager.Log(ex, $"{ComponentName}: Could not configure remote machine protocol. Could be an old PPC version.");
}
}
}
ApplicationInformation = response.Message.ApplicationInformation;
SessionLogger.CreateSession();
DeviceInformation = response.Message.DeviceInformation;
if (!response.Message.Authenticated)
{
await Adapter.Disconnect();
throw new AuthenticationException(response.Container.ErrorMessage);
}
}
catch (Exception ex)
{
try
{
await Adapter.Disconnect();
}
catch { }
throw ex;
}
ApplyContinuousChannelsConfiguration();
}
}
protected virtual void ApplyContinuousChannelsConfiguration()
{
OnEnableDiagnosticsChanged(EnableDiagnostics);
OnEnableEmbeddedDebuggingChanged(EnableEmbeddedDebugging);
OnEnableEventsNotification(EnableEventsNotification);
OnEnableApplicationLogsChanged(EnableApplicationLogs);
OnEnableMachineStatusUpdatesChanged(EnableMachineStatusUpdates);
OnEnableInkFillingStatus(EnableInkFillingStatus);
//TODO: Uncomment this only when Machine Studio enables automatic thread loading (ExternalBridgeTCPClient).
//OnEnableAutomaticThreadLoadingChanged(EnableAutomaticThreadLoading);
}
protected async void OnEnableApplicationLogsChanged(bool value)
{
if (value && State == TransportComponentState.Connected && !_logs_sent)
{
var request = new StartApplicationLogsRequest();
bool responseLogged = false;
_logs_sent = true;
SendContinuousRequest<StartApplicationLogsRequest, StartApplicationLogsResponse>(request, new TransportContinuousRequestConfig() { ShouldLog = true }).ObserveOn(new NewThreadScheduler())
.Subscribe
(
(response) =>
{
if (!responseLogged)
{
responseLogged = true;
}
OnApplicationLogAvailable(response);
},
(ex) =>
{
_logs_sent = false;
},
() =>
{
_logs_sent = false;
});
}
else if (_logs_sent)
{
_logs_sent = false;
if (State == TransportComponentState.Connected)
{
var req = new StopApplicationLogsRequest();
try
{
var res = await SendRequest<StopApplicationLogsRequest, StopApplicationLogsResponse>(req, new TransportRequestConfig() { ShouldLog = true });
}
catch { }
}
}
}
private void OnApplicationLogAvailable(TangoMessage<StartApplicationLogsResponse> response)
{
try
{
if (response.Message.LogItem.Count() > 0)
{
LogItemBase log = LogItemBase.Deserialize(response.Message.LogItem.ToArray());
log.LogObject = "External Bridge";
if (InjectApplicationLogsToDefaultLogManager)
{
LogManager.Log(log);
}
ApplicationLogAvailable?.Invoke(this, log);
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error deserializing incoming application log item!");
}
}
public async override Task Disconnect()
{
if (State == TransportComponentState.Connected)
{
ExternalBridgeLogoutRequest request = new ExternalBridgeLogoutRequest();
try
{
var response = await SendRequest<ExternalBridgeLogoutRequest, ExternalBridgeLogoutResponse>(request, new TransportRequestConfig() { ShouldLog = true });
}
catch { }
Status = MachineStatuses.Standby;
}
State = TransportComponentState.Disconnected;
NotifyContinuousRequestMessagesDisconnection();
SessionLogger.EndSession();
if (Adapter != null)
{
await Adapter.Disconnect();
}
LogManager.Log($"{ComponentName} disconnected.");
}
internal ExternalBridgeTcpClient()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExternalBridgeTcpClient"/> class.
/// </summary>
/// <param name="serialNumber">The machine serial number.</param>
/// <param name="ipAddress">The machine IP address.</param>
public ExternalBridgeTcpClient(String serialNumber, String ipAddress)
{
ComponentName = $"External Bridge TCP Client {_component_counter++}";
SerialNumber = serialNumber;
if (ObservablesStaticCollections.Instance.IsInitialized)
{
Machine = ObservablesStaticCollections.Instance.Machines.SingleOrDefault(x => x.SerialNumber == serialNumber);
}
IPAddress = ipAddress;
KeepAliveTimeout = TimeSpan.FromSeconds(5);
KeepAliveRetries = 2;
UseKeepAlive = false;
EnableDiagnostics = true;
Adapter = new TcpTransportAdapter(IPAddress, SettingsManager.Default.GetOrCreate<IntegrationSettings>().ExternalBridgeServicePort);
}
public ExternalBridgeTcpClient(Machine machine, String ipAddress)
{
ComponentName = $"External Bridge TCP Client {_component_counter++}";
Machine = machine;
SerialNumber = Machine.SerialNumber;
IPAddress = ipAddress;
KeepAliveTimeout = TimeSpan.FromSeconds(5);
KeepAliveRetries = 2;
UseKeepAlive = false;
EnableDiagnostics = true;
Adapter = new TcpTransportAdapter(IPAddress, SettingsManager.Default.GetOrCreate<IntegrationSettings>().ExternalBridgeServicePort);
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return SerialNumber;
}
/// <summary>
/// Called when a new request has been received.
/// </summary>
/// <param name="request">The request.</param>
protected async override void OnRequestReceived(RequestReceivedEventArgs e)
{
base.OnRequestReceived(e);
var container = e.Container;
if (container.Type == MessageType.ExternalBridgeLogoutRequest)
{
try
{
await SendResponse<ExternalBridgeLogoutResponse>(new ExternalBridgeLogoutResponse(), container.Token);
}
catch { }
await Task.Delay(2000);
try
{
State = TransportComponentState.Disconnected;
if (Adapter != null)
{
await Adapter.Disconnect();
}
LogManager.Log("External Bridge TCP client disconnected by the remote host.");
}
catch { }
SessionLogger.EndSession();
SessionClosed?.Invoke(this, new EventArgs());
NotifyContinuousRequestMessagesDisconnection();
}
}
protected override void OnMachineStateChanged(MachineState state)
{
//Do Nothing...
}
/// <summary>
/// Occurs when the remote host has closed the session.
/// </summary>
public event EventHandler SessionClosed;
/// <summary>
/// Gets the database machine associated with this client.
/// </summary>
public Machine Machine { get; protected set; }
/// <summary>
/// Sets the database machine.
/// </summary>
/// <param name="machine">The machine.</param>
public void SetMachine(Machine machine)
{
Machine = machine;
}
}
}
|