diff options
Diffstat (limited to 'Software/Visual_Studio/PPC/Tango.PPC.Common')
6 files changed, 643 insertions, 0 deletions
diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/FileSystem/DefaultFileSystemService.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/FileSystem/DefaultFileSystemService.cs new file mode 100644 index 000000000..cf7a21e13 --- /dev/null +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/FileSystem/DefaultFileSystemService.cs @@ -0,0 +1,243 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.Core; +using Tango.Core.DI; +using Tango.Core.IO; +using Tango.FileSystem; +using Tango.FileSystem.Network; +using Tango.Integration.ExternalBridge; +using Tango.PPC.Common.ExternalBridge; +using Tango.Transport; + +namespace Tango.PPC.Common.FileSystem +{ + [TangoCreateWhenRegistered] + public class DefaultFileSystemService : ExtendedObject, IFileSystemService, IExternalBridgeRequestHandler + { + private enum FileSystemOperationMode + { + Upload, + Download + } + + private class FileSystemOperation + { + public FileSystemOperationMode Mode { get; set; } + public String Id { get; set; } + public String Path { get; set; } + public bool IsPathTempZip { get; set; } + + public FileSystemOperation(FileSystemOperationMode mode, String path) + { + Mode = mode; + Id = Guid.NewGuid().ToString(); + Path = path; + } + } + + private FileSystemManager _manager; + private Dictionary<String, FileSystemOperation> _operations; + + public bool Enabled { get; set; } = true; + + public DefaultFileSystemService(IPPCExternalBridgeService externalBridge) + { + _manager = new FileSystemManager(); + _operations = new Dictionary<string, FileSystemOperation>(); + externalBridge.RegisterRequestHandler(this); + } + + [ExternalBridgeRequestHandlerMethod(typeof(GetFileSystemItemRequest))] + public async void OnGetFileSystemItemRequest(GetFileSystemItemRequest request, String token, ExternalBridgeReceiver receiver) + { + try + { + FileSystemItemDTO dto = _manager.GetFolder(request); + await receiver.SendGenericResponse(new GetFileSystemItemResponse() { FileSystemItem = dto }, token); + } + catch (Exception ex) + { + await receiver.SendErrorResponse(ex, token); + } + } + + [ExternalBridgeRequestHandlerMethod(typeof(FileUploadRequest))] + public async void OnFileUploadRequest(FileUploadRequest request, String token, ExternalBridgeReceiver receiver) + { + try + { + using (var stream = new FileStream(request.Path, FileMode.Create)) { } + + FileSystemOperation operation = new FileSystemOperation(FileSystemOperationMode.Upload, request.Path); + _operations.Add(operation.Id, operation); + + await receiver.SendGenericResponse(new FileUploadResponse() { OperationId = operation.Id }, token); + } + catch (Exception ex) + { + await receiver.SendErrorResponse(ex, token); + } + } + + [ExternalBridgeRequestHandlerMethod(typeof(FileDownloadRequest))] + public async void OnFileDownloadRequest(FileDownloadRequest request, String token, ExternalBridgeReceiver receiver) + { + try + { + if (!File.Exists(request.Path)) + { + await receiver.SendErrorResponse(new FileNotFoundException("Could not find the specified file."), token); + return; + } + + FileSystemOperation operation = new FileSystemOperation(FileSystemOperationMode.Download, request.Path); + + _operations.Add(operation.Id, operation); + + await receiver.SendGenericResponse(new FileDownloadResponse() + { + OperationId = operation.Id, + Length = new FileInfo(request.Path).Length + }, token); + } + catch (Exception ex) + { + await receiver.SendErrorResponse(ex, token); + } + } + + [ExternalBridgeRequestHandlerMethod(typeof(FolderDownloadRequest))] + public async void OnFolderDownloadRequest(FolderDownloadRequest request, String token, ExternalBridgeReceiver receiver) + { + try + { + if (!Directory.Exists(request.Path)) + { + await receiver.SendErrorResponse(new FileNotFoundException("Could not find the specified directory."), token); + return; + } + + var tempFile = TemporaryManager.CreateImaginaryFile(); + + ZipFile.CreateFromDirectory(request.Path, tempFile); + + FileSystemOperation operation = new FileSystemOperation(FileSystemOperationMode.Download, tempFile); + operation.IsPathTempZip = true; + + _operations.Add(operation.Id, operation); + + await receiver.SendGenericResponse(new FolderDownloadResponse() + { + OperationId = operation.Id, + Length = new FileInfo(tempFile).Length + }, token); + } + catch (Exception ex) + { + await receiver.SendErrorResponse(ex, token); + } + } + + [ExternalBridgeRequestHandlerMethod(typeof(ChunkUploadRequest))] + public async void OnChunkUploadRequest(ChunkUploadRequest request, String token, ExternalBridgeReceiver receiver) + { + try + { + FileSystemOperation operation; + _operations.TryGetValue(request.OperationId, out operation); + + if (operation == null) + { + await receiver.SendErrorResponse(new ArgumentException("Invalid operation id."), token); + return; + } + + using (var stream = new FileStream(operation.Path, FileMode.Append)) + { + stream.Write(request.Data, 0, request.Data.Length); + } + + await receiver.SendGenericResponse(new ChunkUploadResponse(), token, new TransportResponseConfig() { Priority = QueuePriority.Low }); + } + catch (Exception ex) + { + await receiver.SendErrorResponse(ex, token); + } + } + + [ExternalBridgeRequestHandlerMethod(typeof(ChunkDownloadRequest))] + public async void OnChunkDownloadRequest(ChunkDownloadRequest request, String token, ExternalBridgeReceiver receiver) + { + FileSystemOperation operation; + _operations.TryGetValue(request.OperationId, out operation); + + if (operation == null) + { + await receiver.SendErrorResponse(new ArgumentException("Invalid operation id."), token); + return; + } + + using (FileStream stream = new FileStream(operation.Path, FileMode.Open)) + { + stream.Position = request.Position; + byte[] data = new byte[Math.Min(request.MaxChunkSize, stream.Length - stream.Position)]; + await stream.ReadAsync(data, 0, data.Length); + await receiver.SendGenericResponse(new ChunkDownloadResponse() + { + Data = data + }, token, new TransportResponseConfig() { Priority = QueuePriority.Low }); + } + } + + [ExternalBridgeRequestHandlerMethod(typeof(AbortOperationRequest))] + public async void OnAbortOperationRequest(AbortOperationRequest request, String token, ExternalBridgeReceiver receiver) + { + FileSystemOperation operation; + _operations.TryGetValue(request.OperationId, out operation); + + if (operation == null) + { + await receiver.SendErrorResponse(new ArgumentException("Invalid operation id."), token); + return; + } + + try + { + if (operation.Mode == FileSystemOperationMode.Upload) + { + if (File.Exists(operation.Path)) + { + File.Delete(operation.Path); + } + else if (Directory.Exists(operation.Path)) + { + Directory.Delete(operation.Path, true); + } + } + else if (operation.IsPathTempZip) + { + if (File.Exists(operation.Path)) + { + File.Delete(operation.Path); + } + } + + await receiver.SendGenericResponse(new AbortOperationResponse(), token); + } + catch (Exception ex) + { + await receiver.SendErrorResponse(ex, token); + } + } + + public void OnReceiverDisconnected(ExternalBridgeReceiver receiver) + { + + } + } +} diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/FileSystem/IFileSystemService.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/FileSystem/IFileSystemService.cs new file mode 100644 index 000000000..050bb1cd6 --- /dev/null +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/FileSystem/IFileSystemService.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tango.PPC.Common.FileSystem +{ + public interface IFileSystemService + { + bool Enabled { get; set; } + } +} diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/Performance/DefaultPerformanceService.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/Performance/DefaultPerformanceService.cs new file mode 100644 index 000000000..2279d204c --- /dev/null +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/Performance/DefaultPerformanceService.cs @@ -0,0 +1,227 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Tango.Core; +using Tango.Core.DI; +using Tango.Integration.ExternalBridge; +using Tango.Integration.ExternalBridge.Network.Performance; +using Tango.PPC.Common.ExternalBridge; + +namespace Tango.PPC.Common.Performance +{ + [TangoCreateWhenRegistered] + public class DefaultPerformanceService : ExtendedObject, IPerformanceService + { + #region Nested Classes + + public static class PerformanceInfo + { + [DllImport("psapi.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool GetPerformanceInfo([Out] out PerformanceInformation PerformanceInformation, [In] int Size); + + [StructLayout(LayoutKind.Sequential)] + public struct PerformanceInformation + { + public int Size; + public IntPtr CommitTotal; + public IntPtr CommitLimit; + public IntPtr CommitPeak; + public IntPtr PhysicalTotal; + public IntPtr PhysicalAvailable; + public IntPtr SystemCache; + public IntPtr KernelTotal; + public IntPtr KernelPaged; + public IntPtr KernelNonPaged; + public IntPtr PageSize; + public int HandlesCount; + public int ProcessCount; + public int ThreadCount; + } + + public static Int64 GetPhysicalAvailableMemoryInMiB() + { + PerformanceInformation pi = new PerformanceInformation(); + if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi))) + { + return Convert.ToInt64((pi.PhysicalAvailable.ToInt64() * pi.PageSize.ToInt64() / 1048576)); + } + else + { + return -1; + } + + } + + public static Int64 GetTotalMemoryInMiB() + { + PerformanceInformation pi = new PerformanceInformation(); + if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi))) + { + return Convert.ToInt64((pi.PhysicalTotal.ToInt64() * pi.PageSize.ToInt64() / 1048576)); + } + else + { + return -1; + } + + } + } + + #endregion + + private class PerformanceClient + { + public ExternalBridgeReceiver Receiver { get; set; } + public String Token { get; set; } + } + + private List<PerformanceClient> _clients; + private PerformancePackage _package; + private bool _isStarted; + private Thread _performanceThread; + + public bool Enabled { get; set; } = true; + + public DefaultPerformanceService(IPPCExternalBridgeService externalBridge) + { + _package = new PerformancePackage(); + _clients = new List<PerformanceClient>(); + externalBridge.RegisterRequestHandler(this); + } + + [ExternalBridgeRequestHandlerMethod(typeof(StartPerformanceUpdatesRequest))] + public async void OnStartPerformanceUpdatesRequest(StartPerformanceUpdatesRequest request, String token, ExternalBridgeReceiver receiver) + { + if (Enabled) + { + try + { + if (!_clients.Exists(x => x.Receiver == receiver)) + { + _clients.Add(new PerformanceClient() { Receiver = receiver, Token = token }); + OnReceiversChanged(); + } + + await receiver.SendGenericResponse(new StartPerformanceUpdatesResponse() { Package = _package }, token); + } + catch (Exception ex) + { + LogManager.Log(ex, "Error sending performance package."); + } + } + } + + public void OnReceiverDisconnected(ExternalBridgeReceiver receiver) + { + _clients.RemoveAll(x => x.Receiver == receiver); + OnReceiversChanged(); + } + + private void OnReceiversChanged() + { + if (_clients.Count > 0 && !_isStarted) + { + _isStarted = true; + _performanceThread = new Thread(PerformanceThreadMethod); + _performanceThread.IsBackground = true; + _performanceThread.Start(); + } + else if (_clients.Count == 0 && _isStarted) + { + _isStarted = false; + } + } + + private async void PerformanceThreadMethod() + { + while (_isStarted) + { + try + { + _package.ApplicationCPU = (int)GetAppCPU(); + _package.CPU = (int)GetTotalCPU(); + _package.ApplicationRAM = (int)BytesToMegaBytes(GetAppRam()); + _package.MaxRAM = (int)BytesToMegaBytes((long)new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory); + _package.RAM = _package.MaxRAM - (int)PerformanceInfo.GetPhysicalAvailableMemoryInMiB(); + + DriveInfo info = new DriveInfo("C"); + _package.DiskCapacity = (int)BytesToMegaBytes(info.TotalSize); + _package.AvailableDiskSpace = (int)BytesToMegaBytes(info.AvailableFreeSpace); + _package.DateTime = DateTime.Now; + + foreach (var client in _clients.ToList()) + { + try + { + await client.Receiver.SendGenericResponse(new StartPerformanceUpdatesResponse() { Package = _package }, client.Token); + } + catch (Exception ex) + { + LogManager.Log(ex, "Error sending performance package."); + } + } + } + catch (Exception ex) + { + LogManager.Log(ex, "Error creating performance package."); + } + + Thread.Sleep(200); + } + } + + #region Helpers + + private float BytesToMegaBytes(long bytes) + { + return bytes / 1024f / 1024f; + } + + public float GetAppCPU() + { + PerformanceCounter cpuCounter = new PerformanceCounter(); + cpuCounter.CategoryName = "Process"; + cpuCounter.CounterName = "% Processor Time"; + cpuCounter.InstanceName = Process.GetCurrentProcess().ProcessName; + + // will always start at 0 + float firstValue = cpuCounter.NextValue(); + System.Threading.Thread.Sleep(1000); + // now matches task manager reading + float secondValue = cpuCounter.NextValue(); + + return secondValue / Environment.ProcessorCount; + } + + public float GetTotalCPU() + { + PerformanceCounter cpuCounter = new PerformanceCounter(); + cpuCounter.CategoryName = "Processor"; + cpuCounter.CounterName = "% Processor Time"; + cpuCounter.InstanceName = "_Total"; + + // will always start at 0 + float firstValue = cpuCounter.NextValue(); + System.Threading.Thread.Sleep(1000); + // now matches task manager reading + float secondValue = cpuCounter.NextValue(); + + return secondValue; + } + + public long GetAppRam() + { + Process proc = Process.GetCurrentProcess(); + return proc.PrivateMemorySize64; + } + + #endregion + } +} diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/Performance/IPerformanceService.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/Performance/IPerformanceService.cs new file mode 100644 index 000000000..c3bfd1543 --- /dev/null +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/Performance/IPerformanceService.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.Integration.ExternalBridge; + +namespace Tango.PPC.Common.Performance +{ + public interface IPerformanceService : IExternalBridgeRequestHandler + { + bool Enabled { get; set; } + } +} diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/SystemInfo/DefaultSystemInfoService.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/SystemInfo/DefaultSystemInfoService.cs new file mode 100644 index 000000000..205013e0c --- /dev/null +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/SystemInfo/DefaultSystemInfoService.cs @@ -0,0 +1,133 @@ +using Microsoft.WindowsAPICodePack.Net; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.Core; +using Tango.Core.DI; +using Tango.Integration.ExternalBridge; +using Tango.Integration.ExternalBridge.Network.Information; +using Tango.PPC.Common.Application; +using Tango.PPC.Common.Connectivity; +using Tango.PPC.Common.ExternalBridge; +using Tango.Settings; +using Tango.SystemInfo; + +namespace Tango.PPC.Common.SystemInfo +{ + [TangoCreateWhenRegistered] + public class DefaultSystemInfoService : ExtendedObject, ISystemInfoService, IExternalBridgeRequestHandler + { + public bool Enabled { get; set; } = true; + + private GetMachineInformationResponse response; + private IPPCApplicationManager _applicationManager; + private IConnectivityProvider _connectivityProvider; + + public DefaultSystemInfoService(IPPCExternalBridgeService externalBridge, IPPCApplicationManager applicationManager, IConnectivityProvider connectivityProvider) + { + _applicationManager = applicationManager; + _connectivityProvider = connectivityProvider; + externalBridge.RegisterRequestHandler(this); + } + + [ExternalBridgeRequestHandlerMethod(typeof(GetMachineInformationRequest))] + public async void OnGetMachineInformationRequest(GetMachineInformationRequest request, String token, ExternalBridgeReceiver receiver) + { + try + { + if (response == null) + { + //Get the networks that are currently connected to + var connectedNetwork = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected).FirstOrDefault(); + + var settings = SettingsManager.Default.GetOrCreate<PPCSettings>(); + + var system = SystemObjectsCollection.Create(); + + //Add custom information.. + system.Insert(0, new SystemObjectsCollection() + { + Name = "Application", + Objects = new List<SystemObject>() + { + new SystemObject() + { + Name = "Tango PPC", + Properties = new List<SystemObjectProperty>() + { + new SystemObjectProperty() { Name = "Version", Value = _applicationManager.Version.ToString(3) }, + new SystemObjectProperty() { Name = "Build Date", Value = _applicationManager.BuildDate.ToString() }, + new SystemObjectProperty() { Name = "Previous Version", Value = settings.PreviousApplicationVersion.ToString() }, + new SystemObjectProperty() { Name = "Firmware Version", Value = _applicationManager.FirmwareVersion.ToString() }, + new SystemObjectProperty() { Name = "Technician Mode", Value = _applicationManager.IsInTechnicianMode.ToStringYesNo() }, + new SystemObjectProperty() { Name = "After Update", Value = _applicationManager.IsAfterUpdate.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Startup Date", Value = _applicationManager.StartUpDate.ToString() }, + }, + }, + new SystemObject() + { + Name = "Network", + Properties = new List<SystemObjectProperty>() + { + new SystemObjectProperty() { Name = "Network Name", Value = connectedNetwork.Name }, + new SystemObjectProperty() { Name = "Category", Value = connectedNetwork.Category.ToString() }, + new SystemObjectProperty() { Name = "Type", Value = connectedNetwork.Connectivity.ToString() }, + new SystemObjectProperty() { Name = "Domain", Value = connectedNetwork.DomainType.ToString() }, + new SystemObjectProperty() { Name = "Connected Time", Value = connectedNetwork.ConnectedTime.ToString() }, + new SystemObjectProperty() { Name = "Internet Connection", Value = connectedNetwork.IsConnectedToInternet.ToStringYesNo() }, + }, + }, + new SystemObject() + { + Name = "Settings", + Properties = new List<SystemObjectProperty>() + { + new SystemObjectProperty() { Name = "Application State", Value = settings.ApplicationState.ToString() }, + new SystemObjectProperty() { Name = "Auto Update Check", Value = settings.AutoCheckForUpdates.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Auto Update Interval", Value = settings.AutoUpdateCheckInterval.ToString() }, + new SystemObjectProperty() { Name = "Automatic Thread Loading", Value = settings.EnableAutomaticThreadLoading.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Firmware Logs Enabled", Value = settings.EnableEmbeddedDebugLogs.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Emergency Switch Enabled", Value = settings.EnableEmergencyNotifications.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Liquid Quantity Validation Enabled", Value = settings.EnableJobLiquidQuantityValidation.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Remote Assistance Enabled", Value = settings.EnableRemoteAssistance.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Remote Desktop Enabled", Value = settings.EnableRemoteDesktop.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Start in Technician Mode", Value = settings.EnableTechnicianModeByDefault.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Watchdog Enabled", Value = settings.EnableWatchDog.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Job Units Method", Value = settings.JobUnitsMethod.ToString() }, + new SystemObjectProperty() { Name = "PowerUp Screen Enabled", Value = settings.DisplayPowerUpScreen.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Firmware COM Port", Value = settings.EmbeddedComPort.ToString() }, + new SystemObjectProperty() { Name = "Emergency COM Port", Value = settings.EmergencyComPort.ToString() }, + new SystemObjectProperty() { Name = "Job Upload Method", Value = settings.JobUploadStrategy.ToString() }, + new SystemObjectProperty() { Name = "Diagnostics Synchronization", Value = settings.SynchronizeDiagnostics.ToStringYesNo() }, + new SystemObjectProperty() { Name = "Jobs Synchronization", Value = settings.SynchronizeJobs.ToStringYesNo() }, + new SystemObjectProperty() { Name = "TCP Write Mode", Value = settings.TcpTransportAdapterWriteMode.ToString() }, + }.OrderBy(x => x.Name).ToList(), + }, + }, + }); + + response = new GetMachineInformationResponse() + { + Package = new InformationPackage() + { + System = system, + } + }; + } + + await receiver.SendGenericResponse(response, token); + } + catch (Exception ex) + { + LogManager.Log(ex, "Error sending system information."); + } + } + + public void OnReceiverDisconnected(ExternalBridgeReceiver receiver) + { + + } + } +} diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/SystemInfo/ISystemInfoService.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/SystemInfo/ISystemInfoService.cs new file mode 100644 index 000000000..0cc493891 --- /dev/null +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/SystemInfo/ISystemInfoService.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tango.PPC.Common.SystemInfo +{ + public interface ISystemInfoService + { + bool Enabled { get; set; } + } +} |
