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/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See src/Resources/Files/License.txt for full licensing and attribution //
// details. //
// . //
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Drawing;
namespace Tango.RemoteDesktop.Quantization
{
internal sealed class PaletteTable
{
private Color[] palette;
public Color this[int index]
{
get
{
return this.palette[index];
}
set
{
this.palette[index] = value;
}
}
private int GetDistanceSquared(Color a, Color b)
{
int dsq = 0; // delta squared
int v;
v = a.B - b.B;
dsq += v * v;
v = a.G - b.G;
dsq += v * v;
v = a.R - b.R;
dsq += v * v;
return dsq;
}
public int FindClosestPaletteIndex(Color pixel)
{
int dsqBest = int.MaxValue;
int ret = 0;
for (int i = 0; i < this.palette.Length; ++i)
{
int dsq = GetDistanceSquared(this.palette[i], pixel);
if (dsq < dsqBest)
{
dsqBest = dsq;
ret = i;
}
}
return ret;
}
public PaletteTable(Color[] palette)
{
this.palette = (Color[])palette.Clone();
}
}
}
' href='#n533'>533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
|
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;
namespace Tango.Integration.ExternalBridge
{
public class ExternalBridgeService : BasicTransporter, IExternalBridgeService
{
private UdpDiscoveryService<ExternalBridgeUdpDiscoveryPacket> _discoveryService;
private TcpServer _tcpServer;
private bool _send_app_logs;
private String _app_logs_token;
private Dictionary<MessageType, Action<MessageContainer>> _messageHandlers;
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 String _eventsNotificationsToken;
private String _diagnosticsNotificationToken;
private String _debugLogsNotificationToken;
#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 ClientDisconnected;
/// <summary>
/// Occurs when the service has received a new color profile request.
/// </summary>
public event EventHandler<ColorProfileRequestEventArgs> ColorProfileRequest;
#endregion
#region Properties
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 _isInSession;
/// <summary>
/// Gets a value indicating whether a remote client is authenticated and in session.
/// </summary>
public bool IsInSession
{
get { return _isInSession; }
private set { _isInSession = value; RaisePropertyChangedAuto(); }
}
/// <summary>
/// Gets the current session login intent.
/// </summary>
public ExternalBridgeLoginIntent SessionIntent { get; private set; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ExternalBridgeService"/> class.
/// </summary>
public ExternalBridgeService()
{
var settings = SettingsManager.Default.GetOrCreate<IntegrationSettings>();
_discovery_port = settings.ExternalBridgeServiceDiscoveryPort;
_external_bridge_port = settings.ExternalBridgeServicePort;
_messageHandlers = new Dictionary<MessageType, Action<MessageContainer>>();
RegisterMessageHandlers();
_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.StateChanged -= MachineOperator_StateChanged;
MachineOperator.StateChanged += MachineOperator_StateChanged;
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)
{
if (!IsInSession)
{
UseKeepAlive = false;
LogManager.Log("External bridge client connected from: " + e.Socket.GetIPAddress());
Adapter = new TcpTransportAdapter(e.Socket);
await Connect();
}
else
{
e.Socket.Dispose();
}
}
/// <summary>
/// Machines the operator state changed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void MachineOperator_StateChanged(object sender, TransportComponentState e)
{
//Do nothing right now.
}
private void MachineOperator_StatusChanged(object sender, MachineStatuses e)
{
if (e == MachineStatuses.ReadyToDye)
{
if (IsInSession)
{
if (_diagnosticsNotificationToken != null)
{
var msg = MessageFactory.CreateTangoMessage<StartDiagnosticsRequest>(_diagnosticsNotificationToken);
_machineOperator.SendContinuousRequest<StartDiagnosticsRequest, StartDiagnosticsResponse>(msg);
}
if (_debugLogsNotificationToken != null)
{
var msg = MessageFactory.CreateTangoMessage<StartDebugLogRequest>(_debugLogsNotificationToken);
_machineOperator.SendContinuousRequest<StartDebugLogRequest, StartDebugLogResponse>(msg);
}
}
}
}
private void LogManager_NewLog(object sender, Tango.Logging.LogItemBase e)
{
if (State == TransportComponentState.Connected && _send_app_logs)
{
try
{
SendResponse<StartApplicationLogsResponse>(new StartApplicationLogsResponse()
{
LogItem = ByteString.CopyFrom(e.Serialize())
}, _app_logs_token);
}
catch { }
}
}
private void MachineOperator_PendingResponseReceived(object sender, MessageContainer container)
{
OnOperatorResponseReceived(container);
}
#endregion
#region Public Methods
/// <summary>
/// Starts this instance.
/// </summary>
public void Start()
{
if (!IsStarted)
{
_tcpServer.Start();
_discoveryService.Start();
IsStarted = true;
_enabled = true;
RaisePropertyChanged(nameof(Enabled));
}
}
/// <summary>
/// Stops this instance.
/// </summary>
public async void Stop()
{
if (IsStarted)
{
_tcpServer.Stop();
_discoveryService.Stop();
IsStarted = false;
IsInSession = false;
_enabled = false;
RaisePropertyChanged(nameof(Enabled));
try
{
await Disconnect();
}
catch { }
}
}
/// <summary>
/// Disconnects the current remote client session.
/// </summary>
public async void DisconnectSession()
{
await Disconnect();
}
#endregion
#region Override Methods
protected override void OnRequestReceived(MessageContainer container)
{
base.OnRequestReceived(container);
try
{
if (Enabled)
{
if (container.Type == MessageType.ConnectRequest || container.Type == MessageType.DisconnectRequest)
{
//Do nothing !
}
else
{
if (IsInSession)
{
if (container.Type == MessageType.ExternalBridgeLoginRequest)
{
SendErrorResponse(new AuthenticationException("Machine is already in session."), container.Token);
return;
}
if (_messageHandlers.ContainsKey(container.Type))
{
try
{
try
{
_messageHandlers[container.Type](container);
}
catch (Exception ex)
{
SendErrorResponse(ex, container.Token);
}
}
catch (Exception ex)
{
if (ex is ResponseErrorException)
{
SendResponse((ex as ResponseErrorException).Container);
}
else
{
SendErrorResponse(ex, container.Token);
}
}
}
else
{
OnAnyRequest(container);
}
}
else
{
if (container.Type == MessageType.ExternalBridgeLoginRequest)
{
OnExternalBridgeLoginRequest(container);
}
else if (container.Type == MessageType.ColorProfileRequest)
{
OnColorProfileRequest(container);
}
}
}
}
}
catch (Exception ex)
{
LogManager.Log(ex, String.Format("An error occurred while processing a request message '{0}' from the remote host.", container.Type));
}
}
public async override Task Disconnect()
{
_send_app_logs = false;
try
{
if (IsInSession)
{
await SendRequest<ExternalBridgeLogoutRequest, ExternalBridgeLogoutResponse>(new ExternalBridgeLogoutRequest(), TimeSpan.FromSeconds(0.5));
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending an external bridge log out request.");
}
finally
{
ClearQueues();
}
OnClientDisconnected();
}
protected override void OnFailed(Exception ex)
{
if (ex is KeepAliveException)
{
LogManager.Log("External bridge client has failed to provide a keep alive response. Disconnecting session...");
}
base.OnFailed(ex);
}
#endregion
#region Virtual Methods
protected async virtual void OnClientDisconnected()
{
_eventsNotificationsToken = null;
_diagnosticsNotificationToken = null;
_debugLogsNotificationToken = null;
IsInSession = false;
_send_app_logs = false;
if (MachineOperator.State == TransportComponentState.Connected)
{
try
{
await MachineOperator.SendRequest(new StopDiagnosticsRequest());
}
catch (Exception ex)
{
LogManager.Log(ex);
}
try
{
await MachineOperator.SendRequest(new StopDebugLogRequest());
}
catch (Exception ex)
{
LogManager.Log(ex);
}
}
ClientDisconnected?.Invoke(this, new EventArgs());
try
{
await base.Disconnect();
}
catch (Exception ex)
{
LogManager.Log(ex);
}
LogManager.Log("External bridge client disconnected.");
}
protected virtual void OnOperatorResponseReceived(MessageContainer container)
{
try
{
if (IsInSession)
{
if (container.Type == MessageType.StartEventsNotificationResponse)
{
if (_eventsNotificationsToken != null)
{
container.Token = _eventsNotificationsToken;
SendResponse(container);
}
}
else if (container.Type == MessageType.StartDiagnosticsResponse)
{
if (_diagnosticsNotificationToken != null)
{
container.Token = _diagnosticsNotificationToken;
SendResponse(container);
}
}
else if (container.Type == MessageType.StartDebugLogResponse)
{
if (_debugLogsNotificationToken != null)
{
container.Token = _debugLogsNotificationToken;
SendResponse(container);
}
}
}
}
catch { }
}
#endregion
#region Message Handlers
private void RegisterMessageHandlers()
{
_messageHandlers.Add(MessageType.ExternalBridgeLogoutRequest, OnExternalBridgeLogoutRequest);
_messageHandlers.Add(MessageType.StartApplicationLogsRequest, OnStartApplicationLogsRequest);
_messageHandlers.Add(MessageType.StopApplicationLogsRequest, OnStopApplicationLogsRequest);
_messageHandlers.Add(MessageType.JobRequest, OnJobRequest);
//Events
_messageHandlers.Add(MessageType.StartEventsNotificationRequest, OnStartEventsNotificationRequest);
_messageHandlers.Add(MessageType.StopEventsNotificationRequest, OnStopEventsNotificationRequest);
//Diagnostics
_messageHandlers.Add(MessageType.StartDiagnosticsRequest, OnStartDiagnosticsRequest);
//Debug Logs
_messageHandlers.Add(MessageType.StartDebugLogRequest, OnStartDebugLogRequest);
}
protected virtual async void OnAnyRequest(MessageContainer container)
{
if (SessionIntent == ExternalBridgeLoginIntent.ColorProfile)
{
await SendErrorResponse(new AuthenticationException("The specified intent does not grant the specified action."), container.Token);
return;
}
if (!container.Continuous)
{
try
{
var response = await MachineOperator.SendRequest(container);
await SendResponse(response);
}
//catch (TimeoutException)
//{
//}
catch (Exception ex)
{
await SendErrorResponse(ex, container.Token);
}
}
else
{
try
{
MachineOperator.SendContinuousRequest(container).Subscribe((response) =>
{
if (Enabled && IsInSession)
{
SendResponse(response);
}
}, (ex) =>
{
if (Enabled)
{
if (ex is ResponseErrorException)
{
SendResponse((ex as ResponseErrorException).Container);
}
}
});
}
catch (Exception ex)
{
await SendErrorResponse(ex, container.Token);
}
}
}
protected async virtual void OnExternalBridgeLoginRequest(MessageContainer container)
{
var request = MessageFactory.ParseTangoMessageFromContainer<ExternalBridgeLoginRequest>(container);
LogManager.Log($"External bridge login attempt:\nIntent: {request.Message.Intent}\nMessage:\n{request.Message.ToJsonString()}");
if (MachineOperator.Status != MachineStatuses.Printing || request.Message.Intent != ExternalBridgeLoginIntent.FullControl)
{
ExternalBridgeClientConnectedEventArgs args = new ExternalBridgeClientConnectedEventArgs();
args.Request = request;
args.IpAddress = Adapter.Address;
ConnectionRequest?.Invoke(this, args);
var response = new ExternalBridgeLoginResponse();
response.Authenticated = args.Confirmed;
response.SerialNumber = Machine.SerialNumber;
response.DeviceInformation = MachineOperator.DeviceInformation;
IsInSession = args.Confirmed;
if (IsInSession)
{
LogManager.Log("External bridge client has logged-in successfully.");
UseKeepAlive = true;
MachineOperator.EnableDiagnostics = false;
MachineOperator.EnableEmbeddedDebugging = false;
SessionIntent = request.Message.Intent;
}
else
{
LogManager.Log("External bridge client login failed, invalid password.");
}
await SendResponse<ExternalBridgeLoginResponse>(response, container.Token, null, null, IsInSession ? null : "Invalid password or intent.");
}
else
{
LogManager.Log($"External bridge client login failed because the machine is currently printing and '{ExternalBridgeLoginIntent.FullControl}' intent was requested.");
await SendResponse<ExternalBridgeLoginResponse>(new ExternalBridgeLoginResponse(), container.Token, false, ErrorCode.GeneralError, $"Machine connection with '{ExternalBridgeLoginIntent.FullControl}' intent is not permitted while printing.");
}
}
protected async virtual void OnExternalBridgeLogoutRequest(MessageContainer container)
{
try
{
await SendResponse<ExternalBridgeLogoutResponse>(new ExternalBridgeLogoutResponse(), container.Token);
}
catch (Exception ex)
{
LogManager.Log(ex);
}
finally
{
ClearQueues();
}
OnClientDisconnected();
}
protected virtual void OnStartApplicationLogsRequest(MessageContainer container)
{
if (SessionIntent == ExternalBridgeLoginIntent.Diagnostics || SessionIntent == ExternalBridgeLoginIntent.FullControl)
{
_app_logs_token = container.Token;
_send_app_logs = true;
SendResponse<StartApplicationLogsResponse>(new StartApplicationLogsResponse(), container.Token);
}
else
{
throw new AuthenticationException("The specified intent does not grant the specified action.");
}
}
protected virtual void OnStopApplicationLogsRequest(MessageContainer container)
{
if (SessionIntent == ExternalBridgeLoginIntent.Diagnostics || SessionIntent == ExternalBridgeLoginIntent.FullControl)
{
_send_app_logs = false;
SendResponse<StopApplicationLogsResponse>(new StopApplicationLogsResponse() { }, container.Token);
SendResponse<StartApplicationLogsResponse>(new StartApplicationLogsResponse() { }, _app_logs_token, true);
}
else
{
throw new AuthenticationException("The specified intent does not grant the specified action.");
}
}
protected virtual void OnJobRequest(MessageContainer container)
{
if (SessionIntent != ExternalBridgeLoginIntent.FullControl)
{
throw new InvalidOperationException($"Job execution is disabled while session intent is '{SessionIntent}'.");
}
if (MachineOperator.Status != MachineStatuses.ReadyToDye)
{
throw new InvalidOperationException($"Could not execute job while machine operator status is '{MachineOperator.Status}'.");
}
else
{
OnAnyRequest(container);
}
}
protected virtual void OnStartEventsNotificationRequest(MessageContainer container)
{
_eventsNotificationsToken = container.Token;
SendResponse<StartEventsNotificationResponse>(new StartEventsNotificationResponse(), container.Token);
}
protected virtual void OnStopEventsNotificationRequest(MessageContainer container)
{
if (_eventsNotificationsToken != null)
{
SendResponse<StartEventsNotificationResponse>(new StartEventsNotificationResponse(), _eventsNotificationsToken, true);
_eventsNotificationsToken = null;
SendResponse<StopEventsNotificationResponse>(new StopEventsNotificationResponse(), container.Token);
}
}
protected virtual void OnStartDiagnosticsRequest(MessageContainer container)
{
_diagnosticsNotificationToken = container.Token;
_machineOperator.SendContinuousRequest(container);
}
protected virtual void OnStartDebugLogRequest(MessageContainer container)
{
_debugLogsNotificationToken = container.Token;
_machineOperator.SendContinuousRequest(container);
}
private void OnColorProfileRequest(MessageContainer container)
{
var request = MessageFactory.ParseTangoMessageFromContainer<ColorProfileRequest>(container);
ColorProfileRequestEventArgs e = new ColorProfileRequestEventArgs(request, () =>
{
//Approved.
SendResponse<ColorProfileResponse>(new ColorProfileResponse()
{
Approved = true
}, container.Token);
},
() =>
{
//Declined.
SendResponse<ColorProfileResponse>(new ColorProfileResponse(), container.Token);
});
ColorProfileRequest?.Invoke(this, e);
}
#endregion
}
}
|