using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Tango.Core; using Tango.Core.Commands; using Tango.Core.Helpers; using Tango.Integration.Operation; using Tango.Logging; using Tango.PMR.Connection; using Tango.PPC.Common; using Tango.PPC.Common.Application; using Tango.PPC.Common.MachineSetup; using Tango.PPC.Common.Navigation; using Tango.PPC.UI.ViewsContracts; using Tango.Settings; using Tango.SharedUI.Helpers; using Tango.SQLExaminer; using Tango.Transport.Adapters; namespace Tango.PPC.UI.ViewModels { /// /// Represents the machine setup view ViewModel. /// /// public class MachineSetupViewVM : PPCViewModel { /// /// Represents the various machine setup view states. /// public enum MachineSetupStates { None, Working, Completed, Failed, } public enum MachineSetupView { WelcomeView, WiFiSelectionView, WiFiTestView, EmbeddedWelcomeView, EmbeddedTestView, SetupWelcomeView, SetupProgressView, SetupCompletedView, SetupFailedView, } private MachineSetupResult _setup_result; #region Properties /// /// Gets or sets the machine setup manager. /// public IMachineSetupManager MachineSetupManager { get; set; } private String _serialNumber; /// /// Gets or sets the serial number. /// public String SerialNumber { get { return _serialNumber; } set { _serialNumber = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); } } private String _hostAddress; /// /// Gets or sets the host address. /// public String HostAddress { get { return _hostAddress; } set { _hostAddress = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); } } private String _log; /// /// Gets or sets the log. /// public String Log { get { return _log; } set { _log = value; RaisePropertyChangedAuto(); } } private MachineSetupStates _state; /// /// Gets or sets the state. /// public MachineSetupStates State { get { return _state; } set { _state = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); } } private String _machineConnectionStatus; public String MachineConnectionStatus { get { return _machineConnectionStatus; } set { _machineConnectionStatus = value; RaisePropertyChangedAuto(); } } #endregion #region Commands /// /// Gets or sets the complete command. /// public RelayCommand CompleteCommand { get; set; } /// /// Gets or sets the navigate to WiFi command. /// public RelayCommand NavigateToWiFiCommand { get; set; } /// /// Gets or sets the skip embedded test command. /// public RelayCommand SkipEmbeddedTestCommand { get; set; } /// /// Gets or sets the perform embedded test command. /// public RelayCommand PerformEmbeddedTestCommand { get; set; } /// /// Gets or sets the install command. /// public RelayCommand InstallCommand { get; set; } /// /// Gets or sets the restart command. /// public RelayCommand RestartCommand { get; set; } #endregion #region Constructors /// /// Initializes a new instance of the class. /// /// The application manager. /// The machine setup manager. public MachineSetupViewVM(IPPCApplicationManager applicationManager, IMachineSetupManager machineSetupManager) { MachineSetupManager = machineSetupManager; //MachineSetupManager.ProgressLog += (x, msg) => AppendLog(msg); MachineSetupManager.ProgressStep += (x, step) => AppendLog(Environment.NewLine + "-----------" + step.ToDescription().ToUpper() + "-----------" + Environment.NewLine); HostAddress = "localhost\\SQLEXPRESS"; SerialNumber = "1111"; CompleteCommand = new RelayCommand(CompleteSetup, () => State == MachineSetupStates.Completed); applicationManager.SetupRequired += ApplicationManager_SetupRequired; NavigateToWiFiCommand = new RelayCommand(EnsureWiFi); PerformEmbeddedTestCommand = new RelayCommand(PerformEmbeddedTest); SkipEmbeddedTestCommand = new RelayCommand(SkipEmbeddedTest); InstallCommand = new RelayCommand(Install); RestartCommand = new RelayCommand(() => { NavigateTo(MachineSetupView.WelcomeView); }); if (!LogManager.Categories.Contains(LogCategory.Debug)) { LogManager.Categories.Add(LogCategory.Debug); } var logger = new SimpleStringLogger(); LogManager.RegisterLogger(logger); logger.LogReceived += Logger_LogReceived; } #endregion #region Event Handlers /// /// Handles the SetupRequired event of the ApplicationManager. /// /// The source of the event. /// The instance containing the event data. private void ApplicationManager_SetupRequired(object sender, EventArgs e) { LogManager.Log("SetupRequired event received. Navigating to MachineSetupView..."); NavigationManager.NavigateTo(NavigationView.MachineSetupView); } private void Logger_LogReceived(object sender, LogItemBase e) { AppendLog(e.Message); } #endregion #region Private Methods /// /// Appends the log. /// /// The MSG. private void AppendLog(String msg) { if (msg != null && !msg.Contains("SQL Examiner")) { InvokeUI(() => { View.AppendLog(msg + Environment.NewLine); }); } } /// /// Completes the setup. /// private void CompleteSetup() { String updater_exe = AssemblyHelper.GetCurrentAssemblyFolder() + "\\Tango.PPC.Updater.exe"; LogManager.Log("Completing machine setup..."); LogManager.Log($"Executing '{updater_exe}' with arguments '{_setup_result.UpdatePackagePath}'..."); Process.Start(updater_exe, _setup_result.UpdatePackagePath); LogManager.Log("Terminating application process!"); Environment.Exit(0); } /// /// Navigates to the specified view. /// /// The view. private Task NavigateTo(MachineSetupView view) { return View.NavigateTo(view); } #endregion #region WiFi private async void EnsureWiFi() { await NavigateTo(MachineSetupView.WiFiTestView); await Task.Delay(2000); bool connected = await ConnectivityProvider.CheckInternetConnection(); if (connected) { await NavigateTo(MachineSetupView.EmbeddedWelcomeView); } else { await NavigateTo(MachineSetupView.WiFiSelectionView); await ConnectivityProvider.RefreshAvailableWiFiNetworks(); ConnectivityProvider.ConnectionStateChanged += ConnectivityProvider_ConnectionStateChanged; } } private void ConnectivityProvider_ConnectionStateChanged(object sender, Common.Connectivity.ConnectionStateEventArgs e) { if (e.IsConnected) { ConnectivityProvider.ConnectionStateChanged -= ConnectivityProvider_ConnectionStateChanged; EnsureWiFi(); } } #endregion #region Embedded private async void PerformEmbeddedTest() { await NavigateTo(MachineSetupView.EmbeddedTestView); try { MachineConnectionStatus = "Scanning for the machine..."; LogManager.Log("Starting machine connection procedure..."); TimeSpan timeout = TimeSpan.FromSeconds(SettingsManager.Default.GetOrCreate().MachineScanningTimeoutSeconds); LogManager.Log("Scanning for machine on available serial ports..."); Transport.Discovery.UsbCommunicationScanner scanner = new Transport.Discovery.UsbCommunicationScanner(UsbSerialBaudRates.BR_9600); scanner.ScanningPort += (port) => { MachineConnectionStatus = $"Scanning for the machine on {port}..."; }; var response = await scanner.Scan(new ConnectRequest() { Password = "1234" }, timeout); MachineConnectionStatus = "Machine discovered on port: " + response.Adapter.Address + ", trying to connect..."; LogManager.Log("Machine discovered on port: " + response.Adapter.Address); LogManager.Log("Device Information:"); LogManager.Log(response.Response.DeviceInformation.ToJsonString()); LogManager.Log("Disconnecting machine operator..."); IMachineOperator op = new MachineOperator(response.Adapter); op.EnableDiagnostics = false; op.EnableEmbeddedDebugging = false; op.EnableEventsNotification = false; LogManager.Log("Connecting machine operator..."); await op.Connect(); MachineConnectionStatus = "Test completed successfully!"; await Task.Delay(1000); try { await op.Disconnect(); } catch { } await NavigateTo(MachineSetupView.SetupWelcomeView); } catch (Exception ex) { LogManager.Log(ex, "Error while trying to scan and connect to the machine."); MachineConnectionStatus = "Test Failed!"; await Task.Delay(2000); await NavigateTo(MachineSetupView.EmbeddedWelcomeView); } } private async void SkipEmbeddedTest() { if (await NotificationProvider.ShowQuestion("Are you sure you want to skip the machine communication test?")) { } } #endregion #region Setup private async void Install() { await NavigateTo(MachineSetupView.SetupProgressView); LogManager.Log("Starting machine setup..."); State = MachineSetupStates.Working; try { _setup_result = await MachineSetupManager.Setup(SerialNumber, HostAddress); Settings.ApplicationState = ApplicationStates.SemiSetup; Settings.Save(); State = MachineSetupStates.Completed; LogManager.Log("Machine setup completed."); await NavigateTo(MachineSetupView.SetupCompletedView); } catch (Exception ex) { LogManager.Log(ex, "Machine setup failed."); State = MachineSetupStates.Failed; await NavigateTo(MachineSetupView.SetupFailedView); } } #endregion } }