private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                Messenger.Default.Unregister <FirstSetupWizardComplete>(this);

                CottonDBMS.TruckApp.Tasks.TruckPullFromCloudTask.Cancel();
                AggregateDataProvider.Cleanup();
                TagDataProvider.Disconnect();
                GPSDataProvider.Disconnect();
                QuadratureEncoderDataProvider.Dispose();
                Logging.Logger.CleanUp();
                base.OnClosed(e);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Trace.Write(exc.Message);
            }

            //if (ConfigurationManager.AppSettings["AllowStartupAndShutdown"].ToLower() == "true")
            //System.Diagnostics.Process.Start("Shutdown", "-s -t 10");
        }
        public override void Cleanup()
        {
            Messenger.Default.Unregister <SettingsSavedMessage>(this);
            Messenger.Default.Unregister <BusyMessage>(this);
            Messenger.Default.Unregister <ScaleWeightReportMessage>(this);
            Messenger.Default.Unregister <KeyDownMessage>(this);
            Messenger.Default.Unregister <List <TagItem> >(this);
            Messenger.Default.Unregister <BarcodeScannedMessage>(this);
            timer.Enabled = false;
            TagDataProvider.Disconnect();

            if (_scaleReader != null)
            {
                _scaleReader.Dispose();
            }

            if (_barCodeReader != null)
            {
                _barCodeReader.Dispose();
            }
            base.Cleanup();
        }
        private void connectToReader()
        {
            try
            {
                if (!TagDataProvider.IsConnected)
                {
                    Logging.Logger.Log("INFO", "READER NOT CONNECTED");

                    if (ReaderStatus == "CONNECTED")
                    {
                        Logging.Logger.Log("INFO", "READER CHANGE FROM CONNECTED TO DISCONNECTED");
                    }

                    using (var dp = SimpleIoc.Default.GetInstance <IUnitOfWorkFactory>().CreateUnitOfWork())
                    {
                        var setting = dp.SettingsRepository.GetSettingWithDefault(BridgeSettingKeys.READER_HOST_NAME, "169.254.1.1");
                        TagDataProvider.SetHostName(setting);
                        TagDataProvider.Connect();
                        //System.Threading.Thread.Sleep(1000);
                    }
                }

                if (!TagDataProvider.IsConnected)
                {
                    ReaderStatus = "DISCONNECTED";
                }
                else
                {
                    if (ReaderStatus == "DISCONNECTED")
                    {
                        Logging.Logger.Log("INFO", "READER RE-CONNECTED");
                    }


                    ReaderStatus = "CONNECTED";
                    if (!readerTimeSet)
                    {
                        readerTimeSet = true;
                        TagDataProvider.Stop();
                        TagDataProvider.SyncReaderTime();
                        //TagDataProvider.Disconnect();
                    }
                }

                if (TagDataProvider.IsConnected && !TagDataProvider.IsSingulating())
                {
                    System.Threading.Thread.Sleep(500);

                    TagDataProvider.Start(0);

                    if (!TagDataProvider.IsSingulating())
                    {
                        TagDataProvider.Stop();
                        TagDataProvider.Disconnect();
                    }
                }
            }
            catch (Exception readerExc)
            {
                ReaderStatus = "ERROR";
                Logging.Logger.Log(readerExc);
            }
        }
        private async void ExecuteSave()
        {
            Messenger.Default.Send <BusyMessage>(new BusyMessage {
                IsBusy = true, Message = "Validating settings..."
            });
            if (!await ValidateForm())
            {
                Messenger.Default.Send <BusyMessage>(new BusyMessage {
                    IsBusy = false, Message = ""
                });
                return;
            }

            Messenger.Default.Send <BusyMessage>(new BusyMessage {
                IsBusy = true, Message = "Saving..."
            });

            await Task.Run(() =>
            {
                try
                {
                    Settings settings = TagDataProvider.GetDefaultSettings();

                    if (settings != null)
                    {
                        settings.Antennas.TxPowerMax       = false;
                        settings.Antennas.RxSensitivityMax = false;
                        settings.HoldReportsOnDisconnect   = false;
                        settings.Report.Mode = ReportMode.Individual;
                        settings.SearchMode  = SearchMode.DualTarget;
                        settings.ReaderMode  = ReaderMode.AutoSetStaticDRM;
                        settings.Report.IncludeFirstSeenTime      = true;
                        settings.Report.IncludeLastSeenTime       = true;
                        settings.Report.IncludeSeenCount          = true;
                        settings.Keepalives.Enabled               = true;
                        settings.Report.IncludePeakRssi           = true;
                        settings.Report.IncludePhaseAngle         = true;
                        settings.Report.IncludeAntennaPortNumber  = true;
                        settings.Keepalives.EnableLinkMonitorMode = true;
                        settings.Keepalives.LinkDownThreshold     = 5;
                        settings.Keepalives.PeriodInMs            = 3000;

                        settings.Antennas.GetAntenna(1).RxSensitivityInDbm = (double)_antenna1ReceivePower;
                        settings.Antennas.GetAntenna(1).TxPowerInDbm       = (double)_antenna1TransmitPower;

                        settings.Antennas.GetAntenna(2).RxSensitivityInDbm = (double)_antenna2ReceivePower;
                        settings.Antennas.GetAntenna(2).TxPowerInDbm       = (double)_antenna2TransmitPower;

                        settings.Antennas.GetAntenna(3).RxSensitivityInDbm = (double)_antenna3ReceivePower;
                        settings.Antennas.GetAntenna(3).TxPowerInDbm       = (double)_antenna3TransmitPower;

                        settings.Antennas.GetAntenna(4).RxSensitivityInDbm = (double)_antenna4ReceivePower;
                        settings.Antennas.GetAntenna(4).TxPowerInDbm       = (double)_antenna4TransmitPower;

                        TagDataProvider.ApplySettings(settings);

                        Messenger.Default.Send <BusyMessage>(new BusyMessage {
                            IsBusy = true, Message = "Settings saved."
                        });
                        System.Threading.Thread.Sleep(3000);
                    }
                    else
                    {
                        Messenger.Default.Send <BusyMessage>(new BusyMessage {
                            IsBusy = true, Message = "Unable to save reader settings. Reader disconnected?"
                        });
                        System.Threading.Thread.Sleep(3000);
                    }


                    using (var dp = SimpleIoc.Default.GetInstance <IUnitOfWorkFactory>().CreateUnitOfWork())
                    {
                        if (PortName == "NONE")
                        {
                            PortName = "";
                        }
                        if (BarcodePortName == "NONE")
                        {
                            BarcodePortName = "";
                        }

                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.SCALE_COM_PORT, PortName);
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.BARCODE_COM_PORT, BarcodePortName);

                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.BRIDGE_ID, BridgeID);
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.GIN_NAME, ScreenTitle);
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.DOCUMENTDB_ENDPOINT, DocumentDbEndpoint);
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.DOCUMENT_DB_KEY, DocumentDbConnection);
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.LATITUDE, Latitude);
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.LONGITUDE, Longitude);
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.TARGET_STATUS, TargetStatus);
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.DATA_SYNC_INTERVAL, DataSyncInterval.ToString());
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.WEIGH_IN_TIMEOUT, WeighInTimeout.ToString());
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.STABLE_WEIGHT_SECONDS, StableWeightSeconds.ToString());

                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.WEIGHT_AUTO_SAVE_TIMEOUT, WeightAutoSaveTimeout.ToString());
                        dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.UNATTENDED_MODE, UnattendedMode.ToString());

                        bool needsReaderDisconnect = false;
                        if (_originalHost != ReaderHostname)
                        {
                            needsReaderDisconnect = true;
                            dp.SettingsRepository.UpsertSetting(BridgeSettingKeys.READER_HOST_NAME, ReaderHostname);
                        }

                        dp.SaveChanges();

                        if (needsReaderDisconnect)
                        {
                            Messenger.Default.Send <BusyMessage>(new BusyMessage {
                                IsBusy = true, Message = "Reconnecting to " + ReaderHostname
                            });
                            System.Threading.Thread.Sleep(1000);
                            TagDataProvider.Disconnect();
                            TagDataProvider.SetHostName(ReaderHostname);
                            TagDataProvider.Connect();
                            Messenger.Default.Send <BusyMessage>(new BusyMessage {
                                IsBusy = false, Message = "Reader connected to " + ReaderHostname
                            });
                            //shell should start the reader back up in 15-30 seconds
                        }
                    }

                    /*if (portChanged)
                     * {
                     *  System.Windows.Application.Current.Dispatcher.Invoke((Action)(() =>
                     *  {
                     *      System.Windows.MessageBox.Show("Please close and restart the application for new scale setting to take effect");
                     *  }));
                     * }*/
                }
                catch (Exception exc)
                {
                    System.Windows.Application.Current.Dispatcher.Invoke((Action)(() =>
                    {
                        System.Windows.MessageBox.Show("An error occurred saving settings. " + exc.Message);
                    }));
                    Logging.Logger.Log(exc);
                }
                finally
                {
                    Messenger.Default.Send <BusyMessage>(new BusyMessage {
                        IsBusy = false, Message = ""
                    });
                    Messenger.Default.Send <SettingsSavedMessage>(new SettingsSavedMessage {
                        GinName = ScreenTitle, IsFirstLaunch = IsFirstLaunch
                    });
                }
            });
        }