public MainForm(string[] arguments) { m_loading = true; Visible = false; m_prefences = new Preferences(getPreferencesPath); Localization.SetCulture(m_prefences.General.Culture); InitializeComponent(); m_Port_ECU_Status = new MainForm.UltraStatusBarEx(m_statusPortECU); this.Icon = OCTech.OBD2.Applications.Properties.Resources.Application; this.Text = MainForm.ApplicationName; string titleBarCompany = Localization.GetTitleBarCompany(m_prefences.General.Culture); if (!string.IsNullOrEmpty(titleBarCompany)) Text = string.Format("{0} - {1}", Text, titleBarCompany); m_statusErrorECU = Localization.GetStatusBarBanner(m_prefences.General.Culture); m_mainForm = (Form)this; processCommandOptions(arguments); this.Disposed += new EventHandler(mainForm_Disposed); Version version = m_scanTool.GetType().Assembly.GetName().Version; int unlock = version.Major ^ version.Minor ^ version.Build ^ version.Revision; m_scanTool.Unlock(unlock); FileUtility.PathResolverReplacements.Add("[ApplicationName]", MainForm.ApplicationName); LoggableItem.RegisterLoggableItem( typeof(PIDLoggableItem), new LoggableItemXmlReader(PIDLoggableItem.FromXml) ); LoggableItem.RegisterLoggableItem( typeof(FuelLoggableItem), new LoggableItemXmlReader(FuelLoggableItem.FromXml) ); LoggableItem.RegisterLoggableItem( typeof(UserPIDLoggableItem), new LoggableItemXmlReader(UserPIDLoggableItem.FromXml) ); LoggableItem.RegisterLoggableItem( typeof(PIDPluginLoggableItem), new LoggableItemXmlReader(PIDPluginLoggableItem.FromXml) ); if (m_prefences.Layout.TouchScreenSize) { customListView.ItemSpacing = ListViewItemSpacing.Small; toolStripContainer.TopToolStripPanelVisible = false; } customListView.Add( OCTech.OBD2.Applications.Properties.Resources.SetupPageName, "Setup", OCTech.OBD2.Applications.Properties.Resources.p000075 ); customListView.Add( OCTech.OBD2.Applications.Properties.Resources.DiagPageName, "Diagnostics", OCTech.OBD2.Applications.Properties.Resources.p000026 ); customListView.Add( OCTech.OBD2.Applications.Properties.Resources.MonitorsPageName, "Monitors", OCTech.OBD2.Applications.Properties.Resources.p000045 ); customListView.Add( OCTech.OBD2.Applications.Properties.Resources.DashboardPageName, "Dashboard", OCTech.OBD2.Applications.Properties.Resources.p000015 ); customListView.Add( OCTech.OBD2.Applications.Properties.Resources.LogsPageName, "Logs", OCTech.OBD2.Applications.Properties.Resources.p000043 ); customListView.Add( OCTech.OBD2.Applications.Properties.Resources.ExitText, "Exit", OCTech.OBD2.Applications.Properties.Resources.p000032, true ); customListView.ItemSelected += new EventHandler<CustomListViewItemSelectedEventArgs>(customListView_ItemSelected); customListView.Font = this.Font; CurrentOperationStatus = OCTech.OBD2.Applications.Properties.Resources.SystemReadyText; ConnectedStatus = ConnectionStatus.NotConnected; if (m_prefences.Layout.SelectedPageKey == "Exit" || !m_prefences.Layout.RememberLastPageOnStartup || string.IsNullOrEmpty(m_prefences.Layout.SelectedPageKey) ) m_prefences.Layout.SelectedPageKey = "Setup"; m_scanTool.CommunicationErrorOccurred += new EventHandler<MessageEventArgs>(m_scanTool_CommunicationErrorOccurred); m_scanTool.SelectECU += new EventHandler<SelectedECUEventArgs>(m_scanTool_SelectECU); m_scanTool.ConnectionChanged += new EventHandler(m_scanTool_ConnectionChanged); m_scanTool.ConnectionStatusChanged += new EventHandler<ConnectionStatusChangedEventArgs>(m_scanTool_ConnectionStatusChanged); m_pidMonitor = new PIDMonitor(m_scanTool); m_pidMonitor.SetCulture(m_prefences.General.Culture); m_pidMonitor.ErrorOccurred += new EventHandler<OCTech.Utilities.ExceptionEventArgs>(utilities_ErrorOccurred); m_pidMonitor.NewPIDResponseArrived += new EventHandler<PIDResponseEventArgs>(m_pidMonitor_NewPIDResponseArrived); m_pidMonitor.NewPIDTimingAvailable += new EventHandler<PIDMonitorTimingEventArgs>(m_pidMonitor_NewPIDTimingAvailable); m_pidMonitor.Playback.RecordedPlaybackChanged += new EventHandler<RecordedDataPlayBackEventArgs>(m_pidMonitor_RecordedPlaybackChanged); FuelCalculator fuelCalculator = new FuelCalculator(m_pidMonitor, m_scanTool); fuelCalculator.ErrorOccurred += new EventHandler<OCTech.Utilities.ExceptionEventArgs>(utilities_ErrorOccurred); vehicleManagement = new VehicleManagement(this, m_scanTool, m_pidMonitor, fuelCalculator, this, MainForm.MyDocumentsPath); m_context = new AppContext(m_prefences, this, m_scanTool, m_pidMonitor, fuelCalculator, MainForm.MyDocumentsPath, MainForm.ApplicationDataDirectory, m_messageDispatcher, this, this, vehicleManagement); MainForm.m_StaticContext = m_context; TripManager.Initialize(m_context.ScanTool, m_context.PidMonitor, m_context.FuelCalculator, MainForm.ApplicationDataDirectory); TripManager.ErrorOccurred += new EventHandler<OCTech.Utilities.ExceptionEventArgs>(utilities_ErrorOccurred); pluginInitialize(); sensorCalibration = new SensorCalibration(); sensorCalibration.Initialize(m_context); DispatchPID.Initialize(m_context); m_setupPage = new SetupPage(m_context); m_setupPage.ColorModeChanged += new EventHandler<ColorModeChangedEventArgs>(m_setupPage_ColorModeChanged); m_diagnostic = new DiagnosticsPage(m_context); m_monitors = new MonitorsPage(m_context); m_dashboard = new CustomDashboard(m_context); m_logs = new LogsPage(m_context); m_TabPages.Add("Setup", m_setupPage); m_TabPages.Add("Diagnostics", m_diagnostic); m_TabPages.Add("Monitors", m_monitors); m_TabPages.Add("Dashboard", m_dashboard); m_TabPages.Add("Logs", m_logs); pagePanel.SuspendLayout(); addPageToPanel(m_setupPage); addPageToPanel(m_diagnostic); addPageToPanel(m_monitors); addPageToPanel(m_dashboard); addPageToPanel(m_logs); pagePanel.ResumeLayout(); m_StripMenus.Add("Setup", setupToolStripMenuItem); m_StripMenus.Add("Diagnostics", diagnosticsToolStripMenuItem); m_StripMenus.Add("Monitors", monitorsToolStripMenuItem); m_StripMenus.Add("Dashboard", dashboardToolStripMenuItem); m_StripMenus.Add("Logs", logsToolStripMenuItem); setControlsText(); setConnectButtonState(); loadOCTechPlugins(); if (m_PluginsInfo.Plugins.Count == 0 && !PIDPluginController.AreAnyPIDPluginAssembliesLoaded) pluginManagerToolStripMenuItem.Visible = false; if (!m_TabPages.ContainsKey(m_prefences.Layout.SelectedPageKey)) m_prefences.Layout.SelectedPageKey = "Setup"; switchPageByName(m_prefences.Layout.SelectedPageKey); customListView.SelectItem(m_prefences.Layout.SelectedPageKey); loadDataDashboard(getDataPath); try { m_pidMonitor.LoadSettings(MainForm.ApplicationDataDirectory); } catch { } m_setupPage.m001d9a(m_PluginsInfo); setColorTheme(ActiveTheme); m_scanTool.DebugEnabled = true; Gauge.ErrorOccurred += new EventHandler<Controls.ExceptionEventArgs>(controls_ErrorOccurred); PowerBar.ErrorOccurred += new EventHandler<Controls.ExceptionEventArgs>(controls_ErrorOccurred); RoundedLabel.ErrorOccurred += new EventHandler<Controls.ExceptionEventArgs>(controls_ErrorOccurred); LinearGauge.ErrorOccurred += new EventHandler<Controls.ExceptionEventArgs>(controls_ErrorOccurred); }
public SettingsViewModel(TabiConfiguration config, INavigation navigation, IRepoManager repoManager, SyncService syncService, DataResolver dataResolver) { _navigation = navigation ?? throw new ArgumentNullException(nameof(navigation)); _config = config ?? throw new ArgumentNullException(nameof(config)); _repoManager = repoManager ?? throw new ArgumentNullException(nameof(repoManager)); _dataResolver = dataResolver ?? throw new ArgumentNullException(nameof(dataResolver)); _syncService = syncService ?? throw new ArgumentNullException(nameof(syncService)); ExportDatabaseCommand = new Command(async key => { Log.Info("Command: Exporting database"); IFolder rootFolder = PCLStorage.FileSystem.Current.LocalStorage; var t = await rootFolder.GetFileAsync("tabi.db"); DependencyService.Get <IShareFile>().ShareFile(t.Path); }); DropDatabaseCommand = new Command(async() => { Log.Info("Command: Dropping database"); var answer = await Application.Current.MainPage.DisplayAlert("Confirm", "Drop database?", "Yes", "Cancel"); if (answer) { //SQLiteHelper.Instance.ClearPositions(); } }); InfoCommand = new Command((obj) => { InfoCount++; if (InfoCount == 10 && App.Developer) { Settings.Developer = true; InfoCount = 0; } }); ExportKMLCommand = new Command(async key => { Log.Info("Command: Export KML"); //IFolder rootFolder = FileSystem.Current.LocalStorage; //string fileName = "Tabi-Export.kml"; //IFile file = await rootFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); ////Repository<Position> posRepo = new Repository<Position>(SQLiteHelper.Instance.Connection); //var result = await posRepo.Get(p => p.Accuracy < 100, x => x.Timestamp); //string kml = GeoUtil.GeoSerialize(result); //await file.WriteAllTextAsync(kml); //DependencyService.Get<IShareFile>().ShareFile(file.Path); }); ExportCSVCommand = new Command(async key => { Log.Info("Command: Export CSV"); IFolder rootFolder = PCLStorage.FileSystem.Current.LocalStorage; string fileName = "Tabi-Export.txt"; string path = PortablePath.Combine(rootFolder.Path, fileName); IFile file = await rootFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting); IPositionEntryRepository positionEntryRepository = _repoManager.PositionEntryRepository; var result = positionEntryRepository.FilterAccuracy(100).ToList(); Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite); GeoUtil.PositionsToCsv(result, stream); DependencyService.Get <IShareFile>().ShareFile(path, "text/csv"); }); ExportBatteryCSVCommand = new Command(async key => { Log.Info("Command: Export Battery CSV"); IFolder rootFolder = PCLStorage.FileSystem.Current.LocalStorage; string fileName = "Tabi-Export-Battery.txt"; string path = PortablePath.Combine(rootFolder.Path, fileName); IFile file = await rootFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting); var batteryEntryRepo = _repoManager.BatteryEntryRepository; var result = batteryEntryRepo.GetAll().ToList(); Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite); using (TextWriter tw = new StreamWriter(stream)) { var csv = new CsvWriter(tw); csv.Configuration.RegisterClassMap <BatteryEntryMap>(); csv.WriteRecords(result); } DependencyService.Get <IShareFile>().ShareFile(path, "text/csv"); }); ClearStopsCommand = new Command((obj) => { _repoManager.StopVisitRepository.ClearAll(); _repoManager.TrackEntryRepository.ClearAll(); }); OpenLogsCommand = new Command((obj) => { LogsPage page = new LogsPage(); _navigation.PushAsync(page); }); LoadSampleCommand = new Command(async() => { DummyDbLoader dummy = new DummyDbLoader(); await dummy.LoadAsync(); }); ShowMockupCommand = new Command(() => { var assembly = typeof(SettingsViewModel).GetTypeInfo().Assembly; using (Stream stream = assembly.GetManifestResourceStream("Tabi.DemoCsv")) { List <PositionEntry> entries = GeoUtil.CsvToPositions(stream).ToList(); _dataResolver.ResolveData(DateTimeOffset.MinValue, DateTimeOffset.Now); //var x = sv.GroupPositions(entries, 100); //var z = sv.DetermineStopVisits(x, null); //Log.Debug(z.ToString()); } // ActivityOverviewMockupPage sPage = new ActivityOverviewMockupPage(); // navigationPage.PushAsync(sPage); }); ShowPageCommand = new Command(() => { TourVideoPage sPage = new TourVideoPage(); _navigation.PushModalAsync(sPage); }); ShowTourCommand = new Command(async() => { Page tPage = new TourVideoPage(); Analytics.TrackEvent("ShowTour clicked"); await _navigation.PushModalAsync(tPage); }); PrivacyDataCommand = new Command(async() => { Analytics.TrackEvent("Privacy & data settings clicked"); await _navigation.PushAsync(new SettingsPrivacyPage(this)); }); AppAboutCommand = new Command(async() => { Analytics.TrackEvent("Privacy & data settings clicked"); await _navigation.PushAsync(new AboutSettings(this)); }); SendSupportCallCommand = new Command(async() => { try { PhoneDialer.Open(_config.Support.PhoneNumber); } catch (ArgumentNullException ex) { await UserDialogs.Instance.AlertAsync(AppResources.ErrorOccurredTitle, okText: AppResources.OkText); Log.Error(ex); } catch (FeatureNotSupportedException ex) { await UserDialogs.Instance.AlertAsync(AppResources.DeviceUnsupportedText, AppResources.DeviceUnsupportedTitle, AppResources.OkText); Log.Error(ex); } catch (Exception ex) { await UserDialogs.Instance.AlertAsync(AppResources.ErrorOccurredTitle, AppResources.OkText); Log.Error(ex); } }); SendSupportEmailCommand = new Command(async() => { string subject = _config.Support.EmailSubject ?? "Tabi app"; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(" "); stringBuilder.AppendLine("=========================="); stringBuilder.AppendLine($"{_config.App.AppName} app"); stringBuilder.AppendLine($"Version: {VersionTracking.CurrentVersion} ({VersionTracking.CurrentBuild})"); stringBuilder.AppendLine($"Platform: {DeviceInfo.Platform} ({DeviceInfo.VersionString})"); stringBuilder.AppendLine($"Model: {DeviceInfo.Manufacturer} ({DeviceInfo.Model})"); stringBuilder.AppendLine($"API URL: {_config.Api.Url}"); stringBuilder.AppendLine($"Client Id: {_config.Api.ClientIdentifier}"); stringBuilder.AppendLine($"Device ID: {Settings.Device}"); stringBuilder.AppendLine($"Username: {Settings.Username}"); List <string> to = new List <string>() { _config.Support.Email }; try { var message = new EmailMessage { Subject = subject, Body = stringBuilder.ToString(), To = to, }; await Email.ComposeAsync(message); } catch (FeatureNotSupportedException ex) { await UserDialogs.Instance.AlertAsync(AppResources.DeviceUnsupportedText, AppResources.DeviceUnsupportedTitle, AppResources.OkText); Log.Error(ex); } catch (Exception ex) { Log.Error(ex); } }); OpenSupportWebsiteCommand = new Command(async() => { await Browser.OpenAsync(_config.Support.Url); }); LicensesCommand = new Command(async() => { await Browser.OpenAsync(_config.App.LicensesUrl); }); AgreementCommand = new Command(async() => { await Browser.OpenAsync(_config.App.AgreementUrl); }); UploadCommand = new Command(async() => { Analytics.TrackEvent("Upload clicked"); // Check if there is an active internet connection if (CrossConnectivity.Current.IsConnected) { bool wifiAvailable = CrossConnectivity.Current.ConnectionTypes.Contains(Plugin.Connectivity.Abstractions.ConnectionType.WiFi); bool upload = !Settings.WifiOnly || wifiAvailable; // Check if connected to WiFI if (!upload) { upload = await UserDialogs.Instance.ConfirmAsync(AppResources.MobileDataUsageText, AppResources.MobileDataUsageTitle, AppResources.ContinueButton, AppResources.CancelText); } if (upload) { UserDialogs.Instance.ShowLoading(AppResources.UploadDataInProgress, MaskType.Black); // Check if the API is available (within 5 seconds). // Display message to user if api is unavailable. bool available = await _syncService.Ping(5); if (!available) { UserDialogs.Instance.HideLoading(); await UserDialogs.Instance.AlertAsync(AppResources.APIUnavailableText, AppResources.APIUnavailableTitle, AppResources.OkText); return; } try { await _syncService.UploadAll(false); UserDialogs.Instance.HideLoading(); Settings.LastUpload = DateTime.Now.Ticks; UserDialogs.Instance.Toast(AppResources.DataUploadSuccesful); } catch (Exception e) { UserDialogs.Instance.HideLoading(); await UserDialogs.Instance.AlertAsync(AppResources.UploadDataErrorText, AppResources.ErrorOccurredTitle, AppResources.OkText); Log.Error($"UploadAll exception {e.Message}: {e.StackTrace}"); } } } else { UserDialogs.Instance.HideLoading(); // Show user a message that there is no internet connection await UserDialogs.Instance.AlertAsync(AppResources.NoInternetConnectionText, AppResources.NoInternetConnectionTitle, AppResources.OkText); } }); Settings.PropertyChanged += Settings_PropertyChanged; }