aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Integration/ExternalBridge/ExternalBridgeService.cs
blob: 335150491ee6b496eae446dc0b4e0a722070152f (plain)
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Protobuf;
using Tango.BL.Entities;
using Tango.Integration.Operation;
using Tango.PMR;
using Tango.PMR.Common;
using Tango.Transport;
using Tango.Transport.Transporters;
using Tango.PMR.Integration;
using Tango.Transport.Discovery;
using Tango.Transport.Servers;
using Tango.Transport.Adapters;
using Tango.PMR.Connection;
using Tango.PMR.Diagnostics;
using Tango.PMR.Debugging;
using System.Security.Authentication;
using Tango.Settings;
using Tango.Core.ExtensionMethods;
using Tango.PMR.MachineStatus;
using Tango.PMR.Power;
using Tango.Core;
using Microsoft.AspNet.SignalR.Client;
using Tango.Integration.ExternalBridge.Web;

namespace Tango.Integration.ExternalBridge
{
    public class ExternalBridgeService : ExtendedObject, IExternalBridgeService
    {
        private List<ExternalBridgeReceiver> _receivers;
        private UdpDiscoveryService<ExternalBridgeUdpDiscoveryPacket> _discoveryService;
        private TcpServer _tcpServer;
        private int _discovery_port = 8888; //Will be overridden by settings in constructor..
        private int _external_bridge_port = 1984; //Will be overridden by settings in constructor..
        private HubConnection _connection;
        private IHubProxy _proxy;

        #region Events

        /// <summary>
        /// Occurs when a new client is waiting for authentication.
        /// </summary>
        public event EventHandler<ExternalBridgeClientConnectedEventArgs> ConnectionRequest;

        /// <summary>
        /// Occurs when the last client has been disconnected.
        /// </summary>
        public event EventHandler FullControlSessionDisconnected;

        /// <summary>
        /// Occurs when the service has received a new color profile request.
        /// </summary>
        public event EventHandler<ColorProfileRequestEventArgs> ColorProfileRequest;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the SignalR configuration.
        /// </summary>
        public ExternalBridgeSignalRConfiguration SignalRConfiguration { get; set; }

        private IMachineOperator _machineOperator;
        /// <summary>
        /// Gets or sets the machine operator.
        /// </summary>
        public IMachineOperator MachineOperator
        {
            get { return _machineOperator; }
            set { _machineOperator = value; OnMachineOperatorChanged(); }
        }

        private Machine _machine;
        /// <summary>
        /// Gets or sets the machine.
        /// </summary>
        public Machine Machine
        {
            get { return _machine; }
            set { _machine = value; OnMachineChanged(); }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is started.
        /// </summary>
        public bool IsStarted { get; private set; }

        private bool _enabled;
        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="IExternalBridgeService" /> is enabled.
        /// </summary>
        public bool Enabled
        {
            get { return _enabled; }
            set
            {
                _enabled = value;

                if (_enabled)
                {
                    Start();
                }
                else
                {
                    Stop();
                }

                RaisePropertyChangedAuto();
            }
        }

        private bool _hasSessions;
        /// <summary>
        /// Gets a value indicating whether there are any connected sessions.
        /// </summary>
        public bool HasSessions
        {
            get { return _hasSessions; }
            private set { _hasSessions = value; RaisePropertyChangedAuto(); }
        }

        private ExternalBridgeReceiver _fullControlSessionReceiver;
        /// <summary>
        /// Gets the current full control session receiver.
        /// </summary>
        public ExternalBridgeReceiver FullControlSessionReceiver
        {
            get { return _fullControlSessionReceiver; }
            private set { _fullControlSessionReceiver = value; RaisePropertyChangedAuto(); }
        }


        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ExternalBridgeService"/> class.
        /// </summary>
        public ExternalBridgeService()
        {
            SignalRConfiguration = new ExternalBridgeSignalRConfiguration();

            _receivers = new List<ExternalBridgeReceiver>();

            var settings = SettingsManager.Default.GetOrCreate<IntegrationSettings>();

            _discovery_port = settings.ExternalBridgeServiceDiscoveryPort;
            _external_bridge_port = settings.ExternalBridgeServicePort;

            _tcpServer = new TcpServer(_external_bridge_port);
            _tcpServer.ClientConnected += _tcpServer_ClientConnected;

            LogManager.NewLog += LogManager_NewLog;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ExternalBridgeService"/> class.
        /// </summary>
        /// <param name="machineOperator">The machine operator.</param>
        /// <param name="machine">The machine.</param>
        public ExternalBridgeService(IMachineOperator machineOperator, Machine machine) : this()
        {
            Machine = machine;
            MachineOperator = machineOperator;
        }

        #endregion

        #region Properties Changes

        /// <summary>
        /// Called when the machine has been changed
        /// </summary>
        protected virtual void OnMachineChanged()
        {
            if (_discoveryService != null && _discoveryService.IsStarted)
            {
                _discoveryService.Stop();
            }

            _discoveryService = new UdpDiscoveryService<ExternalBridgeUdpDiscoveryPacket>(_discovery_port, new ExternalBridgeUdpDiscoveryPacket()
            {
                SerialNumber = Machine.SerialNumber,
            });

            _discoveryService.BeforeBroadcasting -= _discoverySevice_BeforeBroadcasting;
            _discoveryService.BeforeBroadcasting += _discoverySevice_BeforeBroadcasting;
        }

        private void _discoverySevice_BeforeBroadcasting(object sender, ExternalBridgeUdpDiscoveryPacket e)
        {
            e.Time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
        }

        /// <summary>
        /// Called when the machine operator has been changed
        /// </summary>
        protected virtual void OnMachineOperatorChanged()
        {
            if (MachineOperator != null)
            {
                MachineOperator.StatusChanged -= MachineOperator_StatusChanged;
                MachineOperator.StatusChanged += MachineOperator_StatusChanged;
                MachineOperator.PendingResponseReceived -= MachineOperator_PendingResponseReceived;
                MachineOperator.PendingResponseReceived += MachineOperator_PendingResponseReceived;
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handles the ClientConnected event of the _tcpServer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="ClientConnectedEventArgs"/> instance containing the event data.</param>
        private async void _tcpServer_ClientConnected(object sender, ClientConnectedEventArgs e)
        {
            LogManager.Log("External bridge TCP client connected from: " + e.Socket.GetIPAddress());
            ExternalBridgeReceiver receiver = new ExternalBridgeReceiver(e.Socket, MachineOperator);
            receiver.LoginRequest += Receiver_LoginRequest;
            receiver.ColorProfileRequest += Receiver_ColorProfileRequest;
            receiver.Disconnected += Receiver_Disconnected;
            _receivers.Add(receiver);
            await receiver.Connect();
        }

        private async void OnSignalRSessionCreated(String sessionID)
        {
            LogManager.Log("External bridge SignalR client connected.");

            var adapter = new SignalRTransportAdapter(SignalRConfiguration.Address, SignalRConfiguration.Hub, SignalRTransportAdapterMode.JoinSession, Machine.SerialNumber, sessionID); ;

            ExternalBridgeReceiver receiver = new ExternalBridgeReceiver(adapter, MachineOperator);
            receiver.LoginRequest += Receiver_LoginRequest;
            receiver.ColorProfileRequest += Receiver_ColorProfileRequest;
            receiver.Disconnected += Receiver_Disconnected;
            _receivers.Add(receiver);
            await receiver.Connect();
            //await _proxy.Invoke("NotifySessionCreated");
        }

        private void MachineOperator_StatusChanged(object sender, MachineStatuses status)
        {
            try
            {
                _receivers.ToList().Where(x => x.IsLoggedInAndRequiresDiagnostics).ToList().ForEach(x => x.UpdateMachineOperatorStatus((UpdateStatus)status));
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error updating status of external bridge service client.");
            }
        }

        private void LogManager_NewLog(object sender, Tango.Logging.LogItemBase e)
        {
            var toSend = _receivers.ToList().Where(x => x.IsLoggedInAndRequiresDiagnostics && x.RequiresApplicationLogs).ToList();

            if (_receivers.Count > 0)
            {
                var msg = MessageFactory.CreateTangoMessage<StartApplicationLogsResponse>(new StartApplicationLogsResponse()
                {
                    LogItem = ByteString.CopyFrom(e.Serialize())
                });

                msg.ToBytes();

                toSend.ToList().ForEach(x => x.UpdateApplicationLogs(msg.Container));
            }
        }

        private void MachineOperator_PendingResponseReceived(object sender, MessageContainer container)
        {
            OnOperatorResponseReceived(container);
        }

        #endregion

        #region Receiver Events Handlers

        private void Receiver_Disconnected(object sender, EventArgs e)
        {
            var receiver = sender as ExternalBridgeReceiver;

            receiver.LoginRequest -= Receiver_LoginRequest;
            receiver.ColorProfileRequest -= Receiver_ColorProfileRequest;
            receiver.Disconnected -= Receiver_Disconnected;

            _receivers.Remove(receiver);

            if (receiver.LoginIntent == ExternalBridgeLoginIntent.FullControl)
            {
                FullControlSessionDisconnected?.Invoke(this, new EventArgs());
            }

            HasSessions = _receivers.Count(x => x.IsLoggedIn) > 0;

            FullControlSessionReceiver = _receivers.SingleOrDefault(x => x.IsLoggedIn && x.LoginIntent == ExternalBridgeLoginIntent.FullControl);
        }

        private void Receiver_ColorProfileRequest(object sender, ColorProfileRequestEventArgs e)
        {
            ColorProfileRequest?.Invoke(this, e);
        }

        private void Receiver_LoginRequest(object sender, ExternalBridgeReceiverLoginRequestEventArgs e)
        {
            var request = e.Request;

            if (request.Intent == ExternalBridgeLoginIntent.FullControl && _receivers.Any(x => x.IsLoggedIn && x.LoginIntent == ExternalBridgeLoginIntent.FullControl))
            {
                e.Decline("Only one full control client is allowed.");
                return;
            }

            if (request.Intent == ExternalBridgeLoginIntent.FullControl && MachineOperator.IsPrinting)
            {
                e.Decline($"External bridge client login failed because the machine is currently printing and '{ExternalBridgeLoginIntent.FullControl}' intent was requested.");
                return;
            }

            ExternalBridgeClientConnectedEventArgs args = new ExternalBridgeClientConnectedEventArgs();
            args.Request = request;
            args.Address = e.Address;
            ConnectionRequest?.Invoke(this, args);

            var response = new ExternalBridgeLoginResponse();
            response.Authenticated = args.Confirmed;
            response.SerialNumber = Machine.SerialNumber;
            response.DeviceInformation = MachineOperator.DeviceInformation;

            if (args.Confirmed)
            {
                e.Confirm(Machine, MachineOperator.DeviceInformation);
                HasSessions = true;

                if (request.Intent == ExternalBridgeLoginIntent.FullControl)
                {
                    FullControlSessionReceiver = sender as ExternalBridgeReceiver;
                }
            }
            else
            {
                e.Decline("Invalid password or intent.");
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Starts this instance.
        /// </summary>
        public void Start()
        {
            if (!IsStarted)
            {
                _tcpServer.Start();
                _discoveryService.Start();

                if (SignalRConfiguration.Enabled)
                {
                    _connection = new HubConnection(SignalRConfiguration.Address);
                    _proxy = _connection.CreateHubProxy(SignalRConfiguration.Hub);
                    _proxy.On<String>("OnSessionCreated", OnSignalRSessionCreated);
                    _connection.Start();
                    _connection.StateChanged += (x) =>
                    {
                        if (x.NewState == ConnectionState.Connected)
                        {
                            _proxy.Invoke("RegisterMachine", new MachineInfo()
                            {
                                SerialNumber = Machine.SerialNumber,
                                Organization = Machine.Organization.Name,
                            });
                        }
                    };
                }

                IsStarted = true;
                _enabled = true;
                RaisePropertyChanged(nameof(Enabled));
            }
        }

        /// <summary>
        /// Stops this instance.
        /// </summary>
        public async void Stop()
        {
            if (IsStarted)
            {
                _tcpServer.Stop();
                _discoveryService.Stop();

                foreach (var receiver in _receivers.ToList())
                {
                    await receiver.Disconnect();
                }

                if (SignalRConfiguration.Enabled)
                {
                    await _proxy.Invoke("UnregisterMachine");
                    _connection.Stop();
                    _connection.Dispose();
                }

                IsStarted = false;
                HasSessions = false;
                _enabled = false;
                RaisePropertyChanged(nameof(Enabled));
            }
        }

        /// <summary>
        /// Disconnects the current remote client session.
        /// </summary>
        public async void DisconnectFullControlSession()
        {
            var sessionReceiver = _receivers.SingleOrDefault(x => x.IsLoggedIn && x.LoginIntent == ExternalBridgeLoginIntent.FullControl);
            if (sessionReceiver != null)
            {
                await sessionReceiver.Disconnect();
            }
        }

        #endregion

        #region Virtual Methods

        protected virtual void OnOperatorResponseReceived(MessageContainer container)
        {
            try
            {
                switch (container.Type)
                {
                    case MessageType.StartDiagnosticsResponse:
                        _receivers.ToList().Where(x => x.IsLoggedInAndRequiresDiagnostics && x.RequiresDiagnostics).ToList().ForEach(x => x.UpdateDiagnostics(container));
                        break;
                    case MessageType.StartDebugLogResponse:
                        _receivers.ToList().Where(x => x.IsLoggedInAndRequiresDiagnostics && x.RequiresDebugLogs).ToList().ForEach(x => x.UpdateDebugLogs(container));
                        break;
                    case MessageType.StartEventsNotificationResponse:
                        _receivers.ToList().Where(x => x.IsLoggedInAndRequiresDiagnostics && x.RequiresEventsNotification).ToList().ForEach(x => x.UpdateEvents(container));
                        break;
                    case MessageType.StartMachineStatusUpdateResponse:
                        _receivers.ToList().Where(x => x.IsLoggedInAndRequiresDiagnostics && x.RequiresMachineStatusUpdate).ToList().ForEach(x => x.UpdateMachineStatus(container));
                        break;
                }

            }
            catch { }
        }

        #endregion
    }
}